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.

Saturday, 17 March 2018

Caused by: org.postgresql.util.PSQLException: Large Objects may not be used in auto-commit mode.

A large object refers to the entity property that is modified by @Lob. It may be persisted in several records.

However, in database management system, auto-commit means that each query or persistence is considered as one transaction, and implemented immediately. So, it seems that this setup conflicts a lob property, which may need several statements to persist it.

It may need a transaction to wrap several statements together, between BEGIN and COMMIT.  Turning off the auto-commit mode could be a solution, however, using @Transactional to wrap statements should be a fundamental solution.

I solved the error by this way.



Friday, 16 March 2018

Difference between @Bean and @Component


@Component(Spring stereotype Annotation):

It modifies classes. All components can be auto-wired in Spring context as the Component scan is turned on.

@Bean: 

It modifies methods in a @Configuration class. The instance returned by this method will be registered in the Spring application context. By default, the bean has the same name as the method name. It is an explicit way to declare a bean in the IoC container. They are injected by the framework just like constructor dependencies are resolved

When source code is not available, it is not able to modify a class with a @Component.  So it cannot be auto-wired. In this case, using @Bean is the option.

@Bean methods and inter-dependencies



1. Injecting by type
The dependent type has only one instance. It can be injected by the type directly.
2. Injecting by name
If there are more that one instance of the same type for a target injection point. 
3.Injecting by name to matching qualifier
4. Injecting by qualifiers on both sides.




References:

SPRING STEREOTYPE ANNOTATIONS

Spring Method @Bean Dependency Injection

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...