Showing posts with label Spring. Show all posts
Showing posts with label Spring. Show all posts

Spring Security + Hibernate : Enabling database login via Annotations

Hibernate Entities:

Employee.java
===========
package com.mycompany.myapp.entity;

import javax.persistence.*;
import java.util.*;

@Entity
@Table(name = "employee")
public class Employee {

    private long id;
    private String username;
    private String password;

    @Column(name = "enabled", columnDefinition = "boolean default true",
     nullable = false)
    private Boolean enabled = true;

    @Id
    @GeneratedValue
    @Column(name = "id")
    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

//...

//other getters, setters

}

EmployeeRoles.java:
============
package com.mycompany.myapp.entity;

import javax.persistence.*;


@Entity
@Table(name = "employee_roles")
public class EmployeeRoles{

 private int id;
 private String employeeCode;
 private String role;

 @Id
 @GeneratedValue
 @Column(name = "id")
 public int getId()
 {

     return id;

 }

 
 public void setId(int id)
 {

     this.id = id;

 }

//other getters, setters
}

Initial Roles:

src/main/resources/import.sql:
====================================
insert into employee_roles(employee_code,role) 
values('SOME_EMPLOYEE_CODE','ROLE_USER');

Spring Security config:

WebSecurityConfig.java:
===================
package com.mycompany.myapp;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication
.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders
.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration
.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configuration
.EnableWebSecurity;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation
.ResourceHandlerRegistry;
import javax.sql.*;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/webjars/**","/webjars/","/img/**",
                 "/styles/**","/js/**","/api/1.0/get**", "/about.html")
                 .permitAll().anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
            .logout()
                .permitAll();
                
    }


    @Autowired
    DataSource dataSource;
    
    @Autowired
    public void configAuthentication(AuthenticationManagerBuilder auth) 
throws Exception {
         
            auth.jdbcAuthentication().dataSource(dataSource)
       .usersByUsernameQuery(
          "select username,password, enabled 
                           from employee where username=?")
         .authoritiesByUsernameQuery(
            "select employee_code, role 
                        from employee_roles where employee_code=?");
    }
}

Spring Boot : java.lang.NoClassDefFoundError: javax/mail/MessagingException


Exception in thread "main" java.lang.NoClassDefFoundError: javax/mail/MessagingException
Caused by: java.lang.ClassNotFoundException: javax.mail.MessagingException
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
Could not find the main class: MasterProcess.  Program will exit.
This may happen if you accedentaly add other javax.mail maven dependency into your pom.xml:

  1. <dependency>
  2. <groupId>javax.mail</groupId>
  3. <artifactId>mail</artifactId>
  4. <version>1.4</version>
  5. </dependency>

but in Spring-Boot the actual dependency is:
  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-mail</artifactId>
  4. </dependency>
Goto: http://start.spring.io/

try creating maven project with javax mail dependency and examine the pom.xml. You will find some dependecies like this:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3.     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4.     <modelVersion>4.0.0</modelVersion>
  5.     <groupId>com.example</groupId>
  6.     <artifactId>skeleton</artifactId>
  7.     <version>0.0.1-SNAPSHOT</version>
  8.     <packaging>jar</packaging>
  9.     <name>demo</name>
  10.     <description>Demo project for Spring Boot</description>
  11.     <parent>
  12.         <groupId>org.springframework.boot</groupId>
  13.         <artifactId>spring-boot-starter-parent</artifactId>
  14.         <version>1.4.0.RELEASE</version>
  15.         <relativePath/> <!-- lookup parent from repository -->
  16.     </parent>
  17.     <properties>
  18.         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  19.         <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  20.         <java.version>1.8</java.version>
  21.     </properties>
  22.     <dependencies>
  23.         <dependency>
  24.             <groupId>org.springframework.boot</groupId>
  25.             <artifactId>spring-boot-starter-mail</artifactId>
  26.         </dependency>
  27.         <dependency>
  28.             <groupId>org.springframework.boot</groupId>
  29.             <artifactId>spring-boot-starter-test</artifactId>
  30.             <scope>test</scope>
  31.         </dependency>
  32.     </dependencies>
  33.     <build>
  34.         <plugins>
  35.             <plugin>
  36.                 <groupId>org.springframework.boot</groupId>
  37.                 <artifactId>spring-boot-maven-plugin</artifactId>
  38.             </plugin>
  39.         </plugins>
  40.     </build>
  41. </project>

Spring Boot : Generate new maven project via Spring Boot

Spring Boot awsome CLI tool lets get start with new template project real quick :)

Go to http://start.spring.io/

Set group and package names,packaging(standalone(jar) or web(war)),project type(maven orgradle).
You can also select java version,language(java or groovy) and pre-add lots of dependencies(jpa,template engin,AOP and lote more :) ).

Click Generate project button and  project will be downloaded as zip :)

Doing it in shell/command prompt:
so that we can get it done via script:
  1. #generate & download
  2. spring init --build=maven --java-version=1.8 --dependencies=mail --packaging=jar skeleton.zip
  3. #unzip
  4. unzip skeleton.zip
  5. #remove zip
  6. rm -f skeleton.zip
  7. #we have our project in current directory :)
  8. cat pom.xml
look at the generated pom.xml:-
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3.     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4.     <modelVersion>4.0.0</modelVersion>
  5.     <groupId>com.example</groupId>
  6.     <artifactId>skeleton</artifactId>
  7.     <version>0.0.1-SNAPSHOT</version>
  8.     <packaging>jar</packaging>
  9.     <name>demo</name>
  10.     <description>Demo project for Spring Boot</description>
  11.     <parent>
  12.         <groupId>org.springframework.boot</groupId>
  13.         <artifactId>spring-boot-starter-parent</artifactId>
  14.         <version>1.4.0.RELEASE</version>
  15.         <relativePath/> <!-- lookup parent from repository -->
  16.     </parent>
  17.     <properties>
  18.         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  19.         <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  20.         <java.version>1.8</java.version>
  21.     </properties>
  22.     <dependencies>
  23.         <dependency>
  24.             <groupId>org.springframework.boot</groupId>
  25.             <artifactId>spring-boot-starter-mail</artifactId>
  26.         </dependency>
  27.         <dependency>
  28.             <groupId>org.springframework.boot</groupId>
  29.             <artifactId>spring-boot-starter-test</artifactId>
  30.             <scope>test</scope>
  31.         </dependency>
  32.     </dependencies>
  33.     <build>
  34.         <plugins>
  35.             <plugin>
  36.                 <groupId>org.springframework.boot</groupId>
  37.                 <artifactId>spring-boot-maven-plugin</artifactId>
  38.             </plugin>
  39.         </plugins>
  40.     </build>
  41. </project>
more examples here:-
http://docs.spring.io/spring-boot/docs/current/reference/html/cli-using-the-cli.html#cli-init

Batch(*.bat) Script : Install Spring-Boot CLI on Windows 7

  1. mkdir C:\spring
  2. cd C:\spring
  3. C:
  4. wget --no-check-certificate http://repo.spring.io/release/org/springframework/boot/spring-boot-cli/1.1.4.RELEASE/spring-boot-cli-1.1.4.RELEASE-bin.zip

    REM "Latest version = 2.7.3.RELEASE . So, url http://repo.spring.io/release/org/springframework/boot/spring-boot-cli/2.7.3/spring-boot-cli-2.7.3-bin.zip should work."
  5. unzip spring-boot-cli-1.1.4.RELEASE-bin
  6. rm -f spring-boot-cli-1.1.4.RELEASE-bin.zip
  7. cd spring-1.1.4.RELEASE
  8. setx SPRING_HOME "%cd%"
  9. refreshenv
  10. cd bin
  11. setx PATH "%PATH%;%cd%"
  12. refreshenv
  13. spring --version

Please make sure you have installed choletey and GNU unix-utils for Windows and go theough this article if you dont have any of above commands preinstalled :

JPA : Can not run ddl-auto=update with Spring Boot

Caused by: org.postgresql.util.PSQLException: ERROR: column i.indproc does not exist


This may happen while trying to update development db schema without loosing data and adding schema updates into development db:


  1. spring.jpa.hibernate.ddl-auto=update

Problem is with Postgresql JDBC driver 9.1-901-1.jdbc4:

  1. compile group: 'postgresql', name: 'postgresql', version: '9.1-901-1.jdbc4'
Upgrade it to latest version 42.2.5 in build.gradle:

  1. compile group: 'org.postgresql', name: 'postgresql', version: '42.2.5'
Maven repository:
https://mvnrepository.com/artifact/org.postgresql/postgresql/42.2.5

maven:
<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <version>42.2.5</version>
</dependency>

Running maven web project with maven tomcat7 plugin

With maven tomcat7 plugin you won't have download,install and configure Tomcat server seperately.Maven can do it for you.Just run:
mvn tomcat7:run
with a tomcat7 maven plugin enabled project and browse to localhost:port/path
In your pom.xml simply put this plugin:
  1. <plugin>
  2. <groupId>org.apache.tomcat.maven</groupId>
  3. <artifactId>tomcat7-maven-plugin</artifactId>
  4. <version>2.0</version>
  5. <configuration>
  6. <server>tomcat-development-server</server>
  7. <port>9966</port> <!--make sure port doesnt conflict with others -->
  8. <path>/SpringMVC</path><!--http://localhost:9966/SpringMVC/ -->
  9. </configuration>
  10. </plugin>

Example spring maven hello world web project pom.xml:
  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2.      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  3.     <modelVersion>4.0.0</modelVersion>
  4.     <groupId>com.mohi</groupId>
  5.     <artifactId>SpringMVC</artifactId>
  6.     <packaging>war</packaging>
  7.     <version>1.0-SNAPSHOT</version>
  8.     <name>SpringMVC Maven Webapp</name>
  9.     <url>http://maven.apache.org</url>
  10.     <dependencies>
  11.         <dependency>
  12.             <groupId>org.springframework</groupId>
  13.             <artifactId>spring-webmvc</artifactId>
  14.             <version>4.0.3.RELEASE</version>
  15.         </dependency>
  16.     </dependencies>
  17.     <build>
  18.         <plugins>
  19.             <plugin>
  20.                 <groupId>org.apache.maven.plugins</groupId>
  21.                 <artifactId>maven-compiler-plugin</artifactId>
  22.                 <version>2.3.2</version>
  23.             </plugin>
  24.             <plugin>
  25.                 <groupId>org.apache.tomcat.maven</groupId>
  26.                 <artifactId>tomcat7-maven-plugin</artifactId>
  27.                 <version>2.0</version>
  28.                 <configuration>
  29.                     <server>tomcat-development-server</server>
  30.                     <port>9966</port>
  31.                     <path>/SpringMVC</path>
  32.                 </configuration>
  33.             </plugin>
  34.         </plugins>
  35.     </build>
  36. </project>

Sample code:
Here is a Spring Helloworld maven with tomcat7 plugin example project SpringHelloworldMavenTomcat7PluginExample.zip
Download ,unzip and run:
mvn clean install tomcat7:run
Browse to localhost:9966/SpringMVC/welcome