Sunday, 20 May 2018

Handle Exception in SpringBoot

In SpringBoot, how to handle exceptions?

Before 3.2,


1. The controller level @ExceptionHandler

drawback: it is defined within a controller, and it works only for that controller.

2. The HandlerExceptionResolver:

It offers a uniform exception handler, which is enabled by default Dispatch servlet.

@ExceptionHandler: since Spring 3.1
@ResponseStatus: since Spring 3.0, it is a ResponseStatusExceptionResolver, mapping an Exception to a HttpStatus code.

drawback: 1) it maps an exception to an HTTP status code in the response but without a body massage. 2) one ResponseStatus is able to handle only one Exception.

3. The new one:  @ControllerAdvice
Since Spring 3.2 above, it allows scattered handlers resided in one handler, and it allows to customize response body.


Reference:
Error Handling for REST with Spring


Saturday, 19 May 2018

Spring Data Rest

Spring-Data-Rest builds on top of Spring-Data-Repository. it may automatically analyze underlying data model, and bring out a REST API layer in a hypermedia format.  It, implicitly, merged Rest-API within the repository layer. By this way, it removes controller and service layer.

In Spring boot, it is quite simple to initiate a Spring-Data-Rest layer by adding a starter, i.e.
 org.springframework.boot
 spring-boot-starter-data-rest

Certainly, it also needs to include following for repository objects, i.e.
 org.springframework.boot
 spring-boot-starter-data-jpa
 


 
 

Wednesday, 9 May 2018

Checked and Unchecked Exception

Java exceptions are categorized into 3 groups.

(1) checked exception: those are verified during compile time.
(2) unchecked exception: those are not verified during compile time.
(3) error (unchecked)

(1): A Checked exception can be predicted by the programmer.
(2): A Unchecked exception is a runtime exception. it may not be predicted as coding it, fx: index out of bound etc.
(3): Errors made by JVM, for instance, run out of memory etc.

An exception extends a Throwable interface.  All exceptions are throwables.
(1): extends from Exception extends Throwable;  fx:  IOException
(2): extends from RuntimeException extends Throwable; for instance: ArithmeticException
(3): extends from Error extends Throwable

(1) must be handled by a developer by try catch finally, or throws to a caller.
(2) not an error; a developer may handle it or not; whatever it will be handled by the system.
(3) Errors come from the system; they cannot be handled.


Rule in inheritance

class A{
doIt(){ };  //overriden method
}

class B extends A{
@override
doIt() throws RuntimeException{ //overriding method
}
}

In general,  an overriding method cannot throw an exception more generic than the overridden method.  The case above is valid,  only because a RuntimeException is an unchecked exception, so the overriding is valid.

Sunday, 6 May 2018

How to print 1 to 100 without using loop

recursion call works the same as a loop.

/**
 *
 * @author YNZ
 */
public class PrintOneToNWithoutLoop {

    public static void main(String[] args) {
        printN(1);
        System.out.println("");
    }

    public static void printN(int n) {
        if (n <= 100) {
            System.out.print(" " + n);
            n++;
            printN(n);
        }

    }

}



Thursday, 3 May 2018

Using Lombok to create Builder Pattern

Applying the builder pattern to a data model is a trivial task.  Now it is able to use Lombok annotation to auto-generate it.




import lombok.Getter;
import lombok.Setter;
import lombok.NoArgsConstructor;
import java.io.Serializable;
import java.time.ZonedDateTime;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.springframework.format.annotation.DateTimeFormat;

/**
 *
 * @author YNZ
 */
@Entity
@Table(name = "SHARE_ORDER")
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@ToString
@EqualsAndHashCode
public class Order implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ORDER_PK")
    protected long id;

    @OneToOne
    @JoinColumn(name = "LISTER_PK_FK", referencedColumnName = "USER_PK")
    @NotNull
    protected Lister lister;

    @OneToOne
    @JoinColumn(name = "SEARCHER_PK_FK", referencedColumnName = "USER_PK")
    protected Searcher searcher;

    @Column(name = "CREATION_TIME")
    @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
    @Builder.Default
    protected ZonedDateTime createdDateTime = ZonedDateTime.now();

    @Column(name = "ACTIVATED")
    protected Boolean activated;

    @Column(name = "ORDER_START_TIME")
    @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
    protected ZonedDateTime startTime;

    @Column(name = "ORDER_END_TIME")
    @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
    protected ZonedDateTime endTime;

}



Thursday, 12 April 2018

How to reduce a stream in to a specific map in Java 8

Using Collectors.toMap to collect stream elements into a map. You have to fill up four arguments.

the first argument: key mapper;
the second argument: value mapper;
the 3rd argument: binary operator -- merge function.
the 4th argument: supplier -- a specific map construction here



package StreamCollectingResult;

import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 *
 * @author YNZ
 */
public class CollectingToSpecificMap {

    public static void main(String[] args) {

        Map wordLengthMap = Pattern.compile("[\\s]")
                .splitAsStream("then you need to provide 4th argument")
                .collect(Collectors.toMap(w -> w, String::length, (o, n) -> {
                    throw new IllegalStateException();
                }, TreeMap::new));

        System.out.println("" + wordLengthMap);

    }

}


Tuesday, 20 March 2018

Spring Current Security Context



Spring Security framework has two key context objects which an application must interact with:
  • SecurityContextHolder – SecurityContextHolder contains information about the current security context of the application, which includes detailed information about the user currently working with the application.
  • UserDetailsService – UserDetailsService is used to create a UserDetails object by implementing the single method of this interface: UserDetails loadUserByUsername (String username) throws UsernameNotFoundException
There are four steps needed to secure a web application with a login page via the Spring Security framework:
  1. The user logs in with a name and a password. These two credentials are combined into an instance of the class UsernamePasswordAuthenticationToken. Then, they are passed to the AuthenticationManager for verification.
  2. If the username does not match the password, the BadCredentialsException is returned along with the message “Bad Credentials.”
  3. If the username and password match, it will return a populated authentication instance.
  4. The user sets a security context by calling the SecurityContextHolder.getContext().setAuthentication() method, where the object that returned from authenticationProvider.authenticate() is passed.

Can Jackson Deserialize Java Time ZonedDateTime

Yes, but must include JSR310. Thus ZonedDateTime can be deserialized directly from JSON response to POJO field. <dependency> <g...