Subscribe To Our Newsletter
You will receive our latest post and tutorial.
Thank you for subscribing!

required
required


Spring boot – bean

Spring beans are Java POJO classes created, wired, configured, and managed by the Spring container from start to finish. The Spring container uses DI to manage the components that make up an application. 

The Spring container gets its instructions on what objects to instantiate, configure, and assemble by reading the configuration metadata(Configuration classes) provided. The configuration metadata can be represented either by XML, Java annotations, or Java code. The Spring IoC container makes use of Java POJO classes and configuration metadata to produce a fully configured and executable system or application.

Add Java configuration class

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.lovemesomecoding.service.UserService;
import com.lovemesomecoding.service.UserServiceImpl;

@Configuration
public class BeanConfig {

    @Bean
    public UserService userService() {
        UserService userService = new UserServiceImpl();
        return userService;
    }

}

Source code on Github

May 23, 2019

Spring Boot Rest

May 22, 2019

MySQL Functions

LAST_INSERT_ID Function

The LAST_INSERT_ID functions returns the last id of the column that uses AUTO_INCREMENT for its id. It’s also important to know that this function has be called after an insert or else if you just call it without an insert statement it will give you 0.

SELECT LAST_INSERT_ID();

REPLACE Function

REPLACE function replaces a substring within a string with another string. This is very helpful when updating rows.

REPLACE(str,lookingFor,replacement);

Now we are updating rd to Road in street address

CONCAT Function

The CONCAT function concatenates two or more strings together to a single string. It can be used in SELECT statements to concatenate column values.

SELECT CONCAT(column1,column2, ... ) as alias FROM table_name;

Here is an example of the CONCAT function.

CONCAT_WS Function

The CONCAT_WS concatenates strings or columns together with a separator.

Here is an example of the CONCAT_WS function with a ” ” separator.

CURDATE Function (CURRENT_DATE or CURRENT_DATE() are same to CURDATE)

The CURDATE function returns the current date in the format of ‘YYYY-MM-DD’ for string format.

For numeric format, add +0 like the example below.

The CURDATE function is different from the NOW function. The NOW function returns both date and time of the current time.

DATEDIFF Function

The DATEDIFF function calculates the number of days between two DATE, DATETIME, or TIMESTAMP values. If you pass in a DATETIME or TIMESTAMP, the DATEDIFF function only takes the date part and ignores the time part.

SELECT DATEDIFF(date_expression_1,date_expression_2) FROM table_name;

TIMEDIFF Funciton

The TIMEDIFF calculates the time difference between two TIME or DATETIME values. Note here that these two values must be of the same data type. They must be either both TIME or both DATETIME. It one is TIME and the other is DATETIME, MySQL will return a NULL.

SELECT TIMEDIFF(time_expression_1,time_expression_2) FROM table_name;

The result of TIMEDIFF is of this range -838:59:59 to 838:59:59which is about 35 days worth of time.

Here is an example of TIMEDIFF with TIMEs

Here is an example of TIMEDIFF with DATETIMEs

TIMESTAMPDIFF Function

The TIMESTAMPDIFF function calculates the difference between two DATE or DATETIME values. The calculation is begin_timestamp – end_timestamp. These two values can be of mix data type DATE or DATETIME.

SELECT TIMESTAMPDIFF(unit,begin_timestamp,end_timestamp) FROM table_name;

Unit can be: MICROSECOND, SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER, YEAR

Here is an example of mix formats

A practical example is finding user’s age.

SELECT id, TIMESTAMPDIFF(YEAR, date_of_birth, NOW()) age
FROM users;

DATETIME vs TIMESTAMP

TIMESTAMP has a timezone but DATETIME does not.

May 8, 2019

Spring Boot Api Authentication

Spring boot security

Image result for spring security authentication
May 8, 2019

Spring Boot Security @Secured on method level

First, authorities need to be loaded into the Authentication.

private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request, JwtPayload jwtPayload) {

		List<GrantedAuthority> authorities = new ArrayList<>();
		if (jwtPayload.getAuthorities() != null || jwtPayload.getAuthorities().isEmpty() == false) {
			for (String role : jwtPayload.getAuthorities()) {
				authorities.add(new SimpleGrantedAuthority("ROLE_" + role.toUpperCase()));
			}
		}
		return new UsernamePasswordAuthenticationToken(jwtPayload, jwtPayload.getUid(), authorities);
	}

On the method level use @Secured

	@Secured(value={"ROLE_"+Role.ADMIN})
	@ApiOperation(value = "Get Member By Uuid")
	@GetMapping("/users/{uid}")
	public ResponseEntity<UserDto> getUserByUid(@RequestHeader(name="token", required=true) String token, @ApiParam(name="uid", required=true, value="uid") @PathVariable("uid") String uid){
		log.debug("getUserByUid(..)");
		
		User user = userService.getByUid(uid);
		
		UserDto userDto = userMapper.userToUserDto(user);
		
		log.debug("userDto: {}",ObjectUtils.toJson(userDto));
		
		return new ResponseEntity<>(userDto, HttpStatus.OK);
	}
May 5, 2019