Thursday, October 5, 2017

Getting started with spring boot , eclipse and maven


This post will explain about How to work with spring boot , eclipse and maven

Step 1: Start eclipse
Step 2: Create new java project
Step 3 : Add below code into pom.xml file
       

    4.0.0

    org.springframework
    spring_boot_first
    0.1.0

    
        org.springframework.boot
        spring-boot-starter-parent
        1.5.7.RELEASE
    

    
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.springframework.boot
            spring-boot-starter-actuator
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    

    
        1.8
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
            
                maven-failsafe-plugin
                
                    
                        
                            integration-test
                            verify
                        
                    
                
            
        
    



     
Step 4: Right click on Project-> Configure->Convert To Maven Project
Step 5: If maven plugin not installed in your eclipse then got to market place of eclipse and search for maven , install from there.
Step 6: Now we need to create source folder -
create a folder with name main under src folder
create a folder with name java under main folder
create a folder with name test under main folder

Step 7: Link created folder to src.
Right click on src -> new -> Source folder -> browse on Folder Name-> Give upto main/java
Check the first check box

Right click on src -> new -> Source folder -> browse on Folder Name-> Give upto main/test
Check the first check box

Step 8: Create package wiht name springboot and create a class called HelloController.java


     package springboot;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;

@RestController
public class HelloController {
    
    @RequestMapping("/")
    public String index() {
        return "Greetings from Spring Boot you have done the greate job!";
    }
    
}

    
  

Step 9: Create a class called Application . This is the main class to run the spring boot application.

    package springboot;

import java.util.Arrays;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Bean
    public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
        return args -> {

            System.out.println("Spring boot beans:");

            String[] beanNames = ctx.getBeanDefinitionNames();
            Arrays.sort(beanNames);
            for (String beanName : beanNames) {
                System.out.println(beanName);
            }

        };
    }

}

  

Step 10:Now we need to run this project. Right click on the pom.xml file and Run As -> maven install
Step 11: After Build success . Now we Need to run the Spring Boot Applcation.
Step 12 : Right click on the Application.java Run As - Java Application.
Step 13 : Once executed successfully, then open any Browser and type - http://localhost:8080/
Step 14: Out put will be -Greetings from Spring Boot you have done the greate job! - This details will be available in HelloController.java
Step 15: If you notice that , spring boot will have in built tomcat. Once we started Spring boot, then it will start the tomcat. No external server configuration required.
Step 16 : if you want to know more about spring boot please check the Spring Boot
Step 17 : if you want to change the out put in HelloController. change the return value and again try to run the Application.java.
In this case you may get the below error
      2017-10-05 11:23:38.382  INFO 9172 --- [           main] o.s.c.support.DefaultLifecycleProcessor  : Starting beans in phase 0
2017-10-05 11:23:41.318 ERROR 9172 --- [           main] o.a.coyote.http11.Http11NioProtocol      : Failed to start end point associated with ProtocolHandler ["http-nio-8080"]

java.net.BindException: Address already in use: bind
 at sun.nio.ch.Net.bind0(Native Method) ~[na:1.8.0_131]
 at sun.nio.ch.Net.bind(Unknown Source) ~[na:1.8.0_131]
 at sun.nio.ch.Net.bind(Unknown Source) ~[na:1.8.0_131]
        service.getName(): "Tomcat";  Protocol handler start failed
 at org.apache.catalina.connector.Connector.startInternal(Connector.java:1029) ~[tomcat-embed-core-8.5.20.jar:8.5.20]
 at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) ~[tomcat-embed-core-8.5.20.jar:8.5.20]
 ... 13 common frames omitted
Caused by: java.net.BindException: Address already in use: bind
The Tomcat connector configured to listen on port 8080 failed to start. The port may already be in use or the connector may be misconfigured.

  

To Kill the existing port 8080, which is already in use.
Step 18: Go to command prompt- type netstat -a -o -n
Step 19 find the PID for tomcat port 0.0.0.0:8080 then kill that PID using below command
Step 20 - taskkill /F /PID 28345

Thanks for viewing this post.


Wednesday, September 13, 2017

java 8 Simple example, Stream , BiFunction, Sorting Using comparator and streams


This post will explain how to sort the list by name using Comparator and java 8 Stream.

usage of BiFunction

package com.siva;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.function.BiFunction;
import java.util.stream.Stream;

public class TestJava8Example {
 
 public static void main(String[] args) {
  
  //Usage of BiFunction
  
  BiFunction add = (a, b) -> a + b;
  System.out.println("Addition of two values["+add.apply(20, 30) +"]");
  
  //usage of stream 
  
  List arrayList = new ArrayList();
  Person p = new Person();
  p.setName("siva");
  p.setAge(32);
  arrayList.add(p);
  Person p1 = new Person();
  p1.setName("kumar");
  p1.setAge(33);
  arrayList.add(p1);
  
  Person p2 = new Person();
  p2.setName("raju");
  p2.setAge(33);
  arrayList.add(p2);
  
  Person p3 = new Person();
  p3.setName("jatin");
  p3.setAge(2);
  arrayList.add(p3);
 
  Stream stream = arrayList.stream();
  stream.forEach(x -> System.out.println("Name: [" + x.getName()+"] Age ["+x.getAge()+"]"));
  
  
  //Sort By name Using comparator
  Comparator byPersonName = (Person p4, Person p5) -> p4.getName().compareTo(
              p5.getName());
  Stream sorted = arrayList.stream().sorted(byPersonName);
  sorted.forEach(e -> System.out.println("sorted Name: [" + e.getName()+"] Age ["+e.getAge()+"]"));
  
  
 }
 

}




output

Addition of two values[50]
Name: [siva] Age [32]
Name: [kumar] Age [33]
Name: [raju] Age [33]
Name: [jatin] Age [2]
sorted Name: [jatin] Age [2]
sorted Name: [kumar] Age [33]
sorted Name: [raju] Age [33]
sorted Name: [siva] Age [32]


Getting Started With Jboss Drools, Simple Drools program with eclipse maven and java


This post will explain , how to work with Jboss Drools.

Step 1: Open eclipse and install Drools plugin through Market place.
Help - Eclipse Marketplace- search for drools and install the same.
Step 2: Create a new Maven Project and add below code snippet in pom.xml

//created on: 7 Sep, 2017
package src.main.resources.rules
import com.sample.*;

//list any import classes here.



rule "We have an Best Cricketer"
    salience 10
    when
    then
        System.out.println("We have an Best Cricketer");
end

rule "Cricket Lives"
    salience 10
        when
        then
            System.out.println("Hurrah!!! Cricket Lives");
end

rule "Hello World"
    when
        Cricketer( name == "sachin" )
    then
        System.out.println( "Hello sachin" );
        end


rule "Cricket Score above 50"
    when
      $cricketerDetails : Cricketer( score >= 50 )   
    then
        System.out.println( "I'm best bat's man , my name is[ " + $cricketerDetails.getName() + "]and my score is["+$cricketerDetails.getScore()+"]");
        
  
end


rule "Cricket Score below 50"
      when
      $cricketerDetails : Cricketer( score < 50 )   
    then
        System.out.println( "I'm not best bat's man , my name is[ " + $cricketerDetails.getName() + "]and my score is["+$cricketerDetails.getScore()+"]");
end



Step 3: Write a Simple Pojo Java class.
package com.sample;

public class Cricketer {
    private String name;
     private boolean honest;
     private int score;

     public Cricketer(){
      
     }
     public Cricketer(String name, boolean honest,int score){
      this.name = name;
      this.honest = honest;
      this.score = score;
     }
  public String getName() {
   return name;
  }

  public void setName(String name) {
   this.name = name;
  }

  public boolean isHonest() {
   return honest;
  }

  public void setHonest(boolean honest) {
   this.honest = honest;
  }
  public int getScore() {
   return score;
  }
  public void setScore(int score) {
   this.score = score;
  }

}

Step 4: Now Write a Test java class to execute the drool file.
package com.sample;

import org.kie.api.KieServices;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;

public class BestCricketer {
 public static void main(String[] args) {
   KieServices ks = KieServices.Factory.get();
      KieContainer kContainer = ks.getKieClasspathContainer();
      KieSession ksession = kContainer.newKieSession("ksession-rules");
      Cricketer sachin = new Cricketer("sachin", true,70);

      Cricketer dravid = new Cricketer("dravid", true,55);

      Cricketer rohan = new Cricketer("rohan", true,100);

      Cricketer ajay = new Cricketer("ajay", true,40);

          

      ksession.insert( sachin );

      ksession.insert( dravid );

      ksession.insert( rohan );

      ksession.insert( ajay );


      ksession.fireAllRules();
 }

}

Step 5: Output could be like below
We have an Best Cricketer
Hurrah!!! Cricket Lives
Hello sachin
I'm best bat's man , my name is[ rohan]and my score is[100]
I'm best bat's man , my name is[ dravid]and my score is[55]
I'm best bat's man , my name is[ sachin]and my score is[70]
I'm not best bat's man , my name is[ ajay]and my score is[40]
More information about droolsMore Information on drools Thanks for viewing this post

Monday, August 14, 2017

Spring MVC annotations rest controller , JUnit With Service layer , Mockmvc for Controller test with JSON Object



This post will explain about, how to work with spring mvc ,Junit test case for Services,Mock test for controller with Json Object.


Step 1: Create a dynamic webproject in eclipse->i have created with name spring_junit
Step 2: Modify the web.xml


  spring_junit
  
     redirect.jsp
  
  
  contextConfigLocation/WEB-INF/applicationContext.xml
 
 
 
  org.springframework.web.context.ContextLoaderListener
 
  
        dispatcher
        org.springframework.web.servlet.DispatcherServlet
        1
    
    
        dispatcher
        *.htm
    

Step 3: we need to create applicationContext.xml inside WEB-INF folder. This will have details related to database and other values. Here mentioned only DB details.



    
 
    
          
    
 
    
    
        
        
        
        
    


Step 4: Create dispatcher-servlet.xml(in web.xml we have mentioned servlet name as dispatcher, so in sping mvc xml configuration with name [servletname-servlet.xml].
So here we have to give name as dispatcher-servlet.xml





 


 

 

 

 




Step 5: Create a database schema name as employee and create a table called user with the columns - id,name,password,gender,country
Step 6: Configuration files has been created for spring-mvc . Now we need to write source code. First we will create controller class with name UserController under package - com.siva.controller
package com.siva.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.siva.domain.User;
import com.siva.service.UserService;

@Controller
@RequestMapping("/userRegistration.htm")
@SessionAttributes("user")
public class UserController {

 
 private UserService userService;

 @Autowired
 public void setUserService(UserService userService) {
  this.userService = userService;
 }
 
 @RequestMapping(method = RequestMethod.GET)
 public String showUserForm(ModelMap model)
 {
  User user = new User();
  model.addAttribute(user);
  return "userForm";
 }

 @RequestMapping(method = RequestMethod.POST)
 public String onSubmit(@ModelAttribute("user") User user) {
  userService.add(user);
  return "redirect:userSuccess.htm";
 }

 public UserService getUserService() {
  return userService;
 }
 
}


Step 7: Create domain class with name User under com.siva.domain package
package com.siva.domain;

public class User {
   
 private int id;
 private String name;
 private String password;
 private String gender;
 private String country;
 
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public String getPassword() {
  return password;
 }
 public void setPassword(String password) {
  this.password = password;
 }
 public String getGender() {
  return gender;
 }
 public void setGender(String gender) {
  this.gender = gender;
 }
 public String getCountry() {
  return country;
 }
 public void setCountry(String country) {
  this.country = country;
 }
}

Step 8: Create service and serviceImpl classes inside com.siva.service package.
package com.siva.service;

import com.siva.domain.User;

public interface UserService {

 public void add(User user);
}

package com.siva.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.siva.dao.UserDAO;
import com.siva.domain.User;

@Repository("userService")
public class UserServiceImpl implements UserService {

 @Autowired
 private UserDAO userDAO;
 
 public void setUserDAO(UserDAO userDAO) {
 this.userDAO = userDAO;
}
 @Override
 public void add(User user) {
  //Persist the user object here. 
  userDAO.add(user);
  System.out.println("User added successfully");
  System.out.println("UserName["+user.getName()+"]");
  System.out.println("Gender["+user.getGender()+"]");
  System.out.println("Pasword["+user.getPassword()+"]");
  System.out.println("Country["+user.getCountry()+"]");

 }
 public UserDAO getUserDAO() {
  return userDAO;
 }

}



Step 9: Create dao and daoImpl classes inside com.siva.dao package.
package com.siva.dao;

import com.siva.domain.User;

public interface UserDAO {

 public void add(User user);
}

package com.siva.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import com.siva.domain.User;
@Repository("userDAO")
public class UserDAOImpl implements UserDAO {

 @Autowired
    public JdbcTemplate jdbcTemplate;
 
    public JdbcTemplate getJdbcTemplate() {
     return jdbcTemplate;
    }
     
 @Override
 public void add(User user) {
  //Persist the user object here. 
   String sql = "INSERT INTO USER(id,name,gender,password,country) VALUES(?, ?, ?,?,?)";
        int returnValue = getJdbcTemplate().update(
                sql,
                new Object[] {user.getId(), user.getName(), user.getGender(),user.getPassword(),user.getCountry()});
        if(1 == returnValue)
            System.out.println("Record inserted successfully");
        else{
         System.out.println("Record inserted Failure");
        }
  

 }

}


Step 10: Java code has been completed. Now we need to write jsp files under /WEB-INF/jsp/userForm.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>




Registration Page



User Id :
User Name :
Password :
Gender :
Country :

Step 11: create one more jsp /WEB-INF/jsp/userSuccess.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>




Success Page


User Details

User ID : ${user.id} User Name : ${user.name} Password : ${user.password} Gender : ${user.gender} Country : ${user.country}
Step 12 : We need to add the jar file under /WEB-INF/lib
antlr-runtime-3.0.jar
com.mysql.jdbc_5.1.5.jar
commons-logging-1.0.4.jar
hamcrest-core-1.2.jar
javax.json-1.0.jar
junit-4.11.jar
spring-aop-4.1.6.RELEASE.jar
spring-beans-4.1.6.RELEASE.jar
spring-context-4.1.6.RELEASE.jar
spring-core-4.1.6.RELEASE.jar
spring-expression-4.1.6.RELEASE.jar
spring-jdbc-4.1.6.RELEASE.jar
spring-orm-4.1.6.RELEASE.jar
spring-test-4.1.6.RELEASE.jar
spring-tx-4.1.6.RELEASE.jar
spring-web-4.1.6.RELEASE.jar
spring-webmvc-4.1.6.RELEASE.jar

Step 13: We can run this project by using any one of the server. I have used tomcat and input and output will be display like below.
use URL - http://localhost:8080/spring_junit/userRegistration.htm and provide input details like id, name etc..








Step 14: Now it's time to write junit test case for service. Here i have written simple test case , u can write more test cases depening upon your requirement.
Step 15: First Create a UserServiceAndControllerTest under package - com.siva.test
package com.siva.test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import javax.sql.DataSource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import com.siva.domain.User;
import com.siva.service.UserService;
import com.siva.web.UserController;


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=AppConfig.class)
public class UserServiceAndControllerTest {
 
 private MockMvc mockMvc;
 @Autowired
 private UserService userService;
 
 @Autowired
 DataSource dataSource;
 
 @Autowired
 private UserController userController;
 
 @Autowired 
 MockHttpSession mockHttpSession;
 @Test
 public void testUserService(){
  
  assertEquals("class com.siva.service.UserServiceImpl", this.userService.getClass().toString());
  
 }
 @Test
 public void testUserController(){
  
  assertEquals("class com.siva.web.UserController", this.userController.getClass().toString());
  
 }
 @Test
 public void testAdd() {
  User user = new User();
  user.setId(13);
  user.setName("Varma");
  user.setGender("Male");
  user.setPassword("Varma 123");
  user.setCountry("India");
  userService.add(user);
  assertTrue(true);
 }
 
 @Test
 public void testOnSubmit(){
   mockMvc= MockMvcBuilders.standaloneSetup(this.userController).build();
  try {
   /*User user = new User();
   user.setName("siva1");
   user.setGender("Male");
   user.setPassword("Raju1");*/
   mockHttpSession.setAttribute("user", new UserJSONReader().getUserJSOnObject());
   mockMvc.perform(post("/userRegistration.htm").session(mockHttpSession).accept(MediaType.APPLICATION_JSON))
   .andExpect(status().is3xxRedirection()).andExpect(redirectedUrl("userSuccess.htm"));
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

}


Step 16: In the above class we have 4 test methods first two are to check whether service and controller classes loaded successfully or not.
Other two are actual functionality for service and controller method test through spring mockmvc.
Step 17 : In the above class to test the controller method either passing user object values as hard coded or we can pass through json object.
I have passed here json object for this we need to create one json class to read the json file and conver it into user json object.
Step 18: create UserJSONReader.java under package com.siva.test
package com.siva.test;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonReader;

import com.siva.domain.User;

public class UserJSONReader {
 
 public User getUserJSOnObject(){
   User user = new User();
  try {
 InputStream fis = new FileInputStream("user_json.txt");
 
 //create JsonReader object
 JsonReader jsonReader = Json.createReader(fis);
 //get JsonObject from JsonReader
 JsonObject jsonObject = jsonReader.readObject();
   
 user.setId(jsonObject.getInt("id"));
 user.setName(jsonObject.getString("name"));
 user.setPassword(jsonObject.getString("password"));
 user.setCountry(jsonObject.getString("country"));
 user.setGender(jsonObject.getString("gender"));
 
  jsonReader.close();
  fis.close();
 } catch (IOException e) {
  e.printStackTrace();
 }
 
 return user;
 }
 }




Step 19: create user_json.txt file under project.
{
    "id":14,
 "name":"Jatin",
 "password":"jatin 123",
 "gender":"Male",
 "country":"India is a Great Country"
}

Step 20: Now we need to create one xml file with name-UserServiceAndControllerTest-context.xml



    

Step 21: This is very important step for spring junit. need to configure bean details inside java class. Create class called AppConfig under package com.siva.test
package com.siva.test;

import javax.sql.DataSource;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.siva.dao.UserDAO;
import com.siva.dao.UserDAOImpl;
import com.siva.service.UserService;
import com.siva.service.UserServiceImpl;
import com.siva.web.UserController;
import com.siva.web.UserSuccessController;

@Configuration
public class AppConfig {
 
 @Bean
 public UserService getUserService(){
  return new UserServiceImpl();
 }
 @Bean
 public UserDAO getUserDAO(){
  return new UserDAOImpl();
 }
 @Bean
 public JdbcTemplate getJdbcTemplate() {
   JdbcTemplate jdbcTemplate = new JdbcTemplate();
         jdbcTemplate.setDataSource(getDataSource());
         return jdbcTemplate;
  }
 @Bean
 public DataSource getDataSource() {
         DriverManagerDataSource dataSource = new DriverManagerDataSource();
         //MySQL database we are using
         dataSource.setDriverClassName("com.mysql.jdbc.Driver");
         dataSource.setUrl("jdbc:mysql://localhost:3306/employee");//change url
         dataSource.setUsername("root");//change userid
         dataSource.setPassword("root");//change pwd
         return dataSource;
     }
  
     
  
 @Bean
 public UserController getUserController(){
  return new UserController();
 }
 @Bean
 public UserSuccessController getUserSuccessController(){
  return new UserSuccessController();
 }
 
 @Bean
 public MockHttpSession getMockHttpSession(){
  return new MockHttpSession(); 
 }
}


Step 21: Once everything is done , then we will run this Test program as Run AS Junit, it has to insert data successfully and test case execution should be passed.

Thank you very much for viewing this post.


AddToAny

Contact Form

Name

Email *

Message *