Sunday, November 19, 2017

Spring Boot Gradle Multi Module Project

How to use Spring Boot Gradle Multi Module Project in your application or add one spring boot gradle project/application in to another spring boot gradle project/application.

1) Create parent Spring Boot Gradle Project.





















2) Create child Spring Boot Gradle Project.






















3) in child project create settings.gradle file and configure your parent project

include   ':SpringBootCore'
project(':SpringBootCore').projectDir = new File(settingsDir, '../SpringBootCore')


 4) build.gradle of child project add parent project as dependencies

dependencies {
    compile project(':SpringBootCore')
}


5) now run gradle clean build from your child project.

Note: Download source code from below link.
Parent Project
Child Project

Wednesday, July 19, 2017

Hibernate MappedBy Example (like @OneToOne, @OneToMany, @ManyToMany)

Using "mappedBy" attribute of mapping annotations(like @OneToOne, @OneToMany, @ManyToMany) for bi-directional relationship. This attribute allows you to refer the associated entities from both sides. If "X" has association with "Y" then you can get X from Y and Y from X.



You can download source code from Github MappedByExample

1) OneToOne

    Book and Author
 
            Author
        id, email, name, phone
        1, author@gmail.com, name, 543653465

        Book
        id, content, title, author_id
        1, re  td e sdf asdfasdfasd f, java, 1


2) OneToMany

    Person and Phone
 
            Person
        id, firstName, lastName
        1, Saurabh, Chaudhari

        Phone
        id, network, number, person_id
        1, BSNL, 0987654321, 1
        2, Vodafone, 1234567890, 1

   
3) ManyToMany

    Employee and Department
 
            Employee
        id, firstName, lastName
        1, Saurabh, Chaudhari

        Department
        id, name
        1, QA
        2, Software Engineer
   
   
        Employee_Department
        employees_id, departments_id
        1, 1
        1, 2

Spring JSP Enum in Select/Combo box

This post demonstrate that how to use Enum values in JSP page with Spring Framework


Java Class:

public class User{
    private String name;
    private UserType userType;

    setter and getter
}



Enum Class:

public enum UserType {
    ADMIN("Admin"), USER("User"), TEACHER("Teacher"), STUDENT("Student");

    private String code;

    UserType(String code) {
        this.code = code;
    }

    public String getCode() {
        return code;
    }


    public static UserType fromCode(String userType) {
        for (UserType uType : UserType.values()) {
        if (uType.getCode().equals(userType)) {
            return uType;
        }
        }
        throw new UnsupportedOperationException("The code " + userType + " is not supported!");
    }
}



How to copy properties from one Java bean to another?

We can copy properties from one Java bean to another using Java Reflection API.

public static <T> void copy(T target, T source) throws Exception {
    Class<?> clazz = source.getClass();

    for (Field field : clazz.getDeclaredFields()) {
        if (Modifier.isPrivate(field.getModifiers()))
            field.setAccessible(true);
        Object value = field.get(source);
        field.set(target, value);
    }
}

Spring Security Java Configuration Annotation Example

This application demonstrate how to use spring security in spring mvc application. This is java config annotation based configuration. I tried to implement following customization on spring security framework.

  1. Custom Authentication Provider.
  2. Custom UserDetailsService.
  3. Custom LoginSuccessHandler
  4. Custom AuthenticationFailureHandler
  5. Custom AccessDecisionVoter
  6. Update Current LoggedIn UserDetails
  7. Display All LoggedIn User In Application.
  8. Custom taglib to show/hide action based on user's role and permission.
  9. Prevent multiple login for same user (spring security concurrent user login prevention).
  10. Override spring security message as custom message.
  11. Expiring all Sessions of a LoggedIn Users.
  12. How to implement apache tiles template engine for multiple layout on JSP page.
 You can download source code from SpringSecurityMVC

@Configuration
@EnableWebSecurity
@ComponentScan("com.application")
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    CustomAuthenticationProvider customAuthenticationProvider;

    @Autowired
    @Qualifier("secureUserDetailsService")
    UserDetailsService userDetailsService;

    @Autowired
    LoginSuccessHandler loginSuccessHandler;

    @Autowired
    LoginFailHandler loginFailHandler;

    public SecurityConfig() {
        super();
    }

    @Autowired
    public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(encoder());
        auth.authenticationProvider(customAuthenticationProvider);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers(UrlMapping.getLoginUrl(), UrlMapping.getSignInUrl())
                .permitAll()
                .anyRequest()
                .authenticated()
                .accessDecisionManager(accessDecisionManager())
                .and()
                    .formLogin()
                        .loginPage(UrlMapping.getLoginUrl())
                        .loginProcessingUrl(UrlMapping.getSignInUrl())
                        .failureUrl(UrlMapping.getSignInUrl())
                        .failureHandler(loginFailHandler)
                        .successHandler(loginSuccessHandler)
                        .usernameParameter("email").passwordParameter("password").and()
                        .exceptionHandling().accessDeniedPage(UrlMapping.getUnauthorizedUrl())
                .and()
                    .logout()
                        .logoutSuccessUrl("/")
                        .deleteCookies("JSESSIONID", "SESSION")
                        .invalidateHttpSession(true)
                .and()
                    .sessionManagement()
                        .sessionAuthenticationStrategy(concurrentSessionControlAuthenticationStrategy())
                        .maximumSessions(1)
                        .maxSessionsPreventsLogin(true)
                        .expiredUrl("/")
                        .sessionRegistry(sessionRegistry());

    }
   
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring()
        .antMatchers("/resources/**");
//        super.configure(web);
    }

    @Bean
    PasswordEncoder encoder() {
        return new BCryptPasswordEncoder(15);
    }

    @Bean
    public AccessDecisionManager accessDecisionManager() {
        List<AccessDecisionVoter<? extends Object>> decisionVoters = Arrays.asList(new WebExpressionVoter(),
                new RoleVoter(), new AuthenticatedVoter(), new MinuteBasedVoter());
        return new UnanimousBased(decisionVoters);
    }

    @Bean
    public SessionRegistry sessionRegistry() {
        return new SessionRegistryImpl();
    }

    @Bean
    public HttpSessionEventPublisher httpSessionEventPublisher() {
        return new HttpSessionEventPublisher();
    }

    @Bean
    ConcurrentSessionControlAuthenticationStrategy concurrentSessionControlAuthenticationStrategy() {
        ConcurrentSessionControlAuthenticationStrategy csca = new ConcurrentSessionControlAuthenticationStrategy(
                sessionRegistry());
        csca.setExceptionIfMaximumExceeded(true);
        csca.setMaximumSessions(1);
        return csca;
    }



Spring 4 Jdbc Template CRUD

How to use Jdbc Template in Spring MVC application using Java Config

You can download source code from Spring4JdbcTemplate

@Bean
public JdbcTemplate jdbcTemplate(DataSource dataSource) {
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
jdbcTemplate.setResultsMapCaseInsensitive(true);
return jdbcTemplate;
}

@Bean
public PlatformTransactionManager txManager() {
return new DataSourceTransactionManager(dataSource());
}


public interface EmployeeDao {
public void save(Employee employee);
public void update(Employee employee, Integer id);
public void delete(Integer id);
public Employee get(Integer id);
public List<Employee> list();
}