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

Friday, June 26, 2015

org.hibernate.HibernateException: No Session found for current thread

I am working one Spring MVC project in which I have integrated Spring with hibernate and most of the time, I use to get this error message while performing database operation ..

org.hibernate.HibernateException: No Session found for current thread

Reason : This is happening because I have missed declaring the transaction in my Spring Application. sessionFacory needs transaction to work.

Solution :

Define transaction manager in your Spring configuration file. Here is my spring-config.xml file :


<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${db.driverClassName}" />
<property name="jdbcUrl"
value="jdbc:mysql://${db.host}:${db.port}/${db.name}" />
<property name="user" value="${db.username}" />
<property name="password" value="${db.password}" />
</bean>

<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
depends-on="provDB">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="PACKAGE_NAME" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${db.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>

<bean id="dao" class="DAO_IMPL_CLASS.DaoImpl">
<property name="sessionFactory" ref="sessionFactory" />
</bean>

<tx:annotation-driven transaction-manager="transactionManager" />

<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>

and Add @Transactional annotation on your service function

@Override
@Transactional
public String saveConfiguration(...) {
daoImpl.saveConfiguration(configuration);
return "issue_resolved";
}

I guess, It can be useful to many prople.. Happy Coding..!!!

Monday, October 21, 2013

Junit Test with Mockito

Mockito is a testing framework for Java which allows the creation of Test Double objects called "Mock Objects" for use in automated unit testing in conjunction with framework like Junit. 
For more details, Check here.

This blog will show you step by step working of Mockito.

Step 1 : You need mockito-all and Junit jars into you project classpath which you can download it from here.
If you are using maven, add following dependency into your pom.xml file.

<dependency>
            <groupid>org.mockito</groupid>
            <artifactid>mockito-all</artifactid>
            <version>1.9.5</version>
</dependency>
<dependency>
            <groupid>junit</groupid>
            <artifactid>junit</artifactid>
            <version>4.11</version>
</dependency>

Step 2 : Below is the main service method which we are going to test using Mockito.

import java.util.Iterator;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Provide methods to work with Employees.
 *
 * @author abdul
 *
 */
@Service
public class EmployeeServiceImpl implements EmployeeService {

    private EmployeeDao employeeDao;

  
    @Override
    @Transactional
    public Employee getEmployee(long employeeId) throws Exception {
        Employee employee = employeeDao.getEmployee(employeeId);
        if(employee == null) throw new Exception("Employee not found");
        return employee;
    }
}

Step 3: Now create the test with Mockito


package com.waheed.spring.hibernate.test;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import com.waheed.spring.hibernate.Employee;
import com.waheed.spring.hibernate.EmployeeDao;
import com.waheed.spring.hibernate.EmployeeServiceImpl;

@RunWith(MockitoJUnitRunner.class)
public class EmployeeTest {
   
    @Mock EmployeeDao mockDao;

    @InjectMocks EmployeeServiceImpl employeeServiceImpl;
   
    private Employee employee;
   
    @Before
    public void setup() {
        employee = new Employee();
        setEmployee();
    }
   
    private void setEmployee() {
        employee.setId(1);
        employee.setGender("M");
        employee.setCountry("INDIA");
        employee.setAboutYou("CRICKEETER");
        employee.setName("Sachin");
    }
   
    @Test
    public void employeeTest() throws Exception {
        when(mockDao.getEmployee(1)).thenReturn(employee);
        Employee emp =employeeServiceImpl.getEmployee(1);
        System.out.println(emp.toString());
       
        //Verify if getEmployee method was invoked on employeeServiceImpl call
        verify(mockDao).getEmployee(1);
        assertEquals("Tesing",emp.getName(),"Sachin");
    }
   
    @Test(expected=Exception.class)
    public void employeeTestFailure() throws Exception {
        when(mockDao.getEmployee(10)).thenReturn(null);
        Employee emp = employeeServiceImpl.getEmployee(10);
       
    }
}
Step 4 : Let me explain in few words, what's going on in my test class. 
  • As I am testing the EmployeeDao so I have created the mocks for EmployeeDao using @Mock Annotation. 
  • @InjectMocks : Use this annotation on the class you are testing. The mock classes are injected into the @InjectMocks class.
  • To create mocks, we need to add @RunWith(MockitoJUnitRunner.class) annotation to the test class or you can use MockitoAnnotations.initMocks(this) in your class in @Before method. 
  • When(...)thenReturn(...) : It specify what should be returned after the particular method was called. 
  • verify() : It ensure that specified conditions are met.
You can download the above source code from here

References:


Friday, October 18, 2013

Testing REST Client using MockRestServiceServer

Problem : I have a Web Application which is deployed on tomcat server and I needed to write unit test cases which can test all the controllers. Secondly It internally also hits another Web server using RestTemplate that means for the success of all unit test cases both the applications should be up and running. 
 
Solution : After spending some time on Google, I found that Spring provide a new feature “MockRestServiceServer” by which testing a REST Client is simple. This new feature is in Spring 3.2.x but also available in Spring 3.1.x via the extra jar named “spring-test-mvc”. So, You can test your Spring MVC controllers very easy without starting any Web Application.

MockRestServiceServer takes the approach of mocking the server and allowing you to specify expected behavior and responses in your junit test class. It also handles server exception classes.
MockRestRequestMatchers offers many hamcrest matchers to check your request URL, headers, HTTP method, and even json and xpath matchers to check body content. MockRestResponseCreators allows you to easily build both success and error responses.

This blog will show you how the mock server works.

My Configuration :
  1. Spring 3.1.x
  2. Junit 4

Step 1 : Add following dependency in your pom.xml
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
<scope>test</scope>
</dependency>
<!-- This is not in Maven Central yet must include Spring snapshot repository -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test-mvc</artifactId>
<version>1.0.0.BUILD-SNAPSHOT</version>
<scope>test</scope>
</dependency>

<!-- For testing against latest Spring snapshots -->
<repositories>
<repository>
<id>org.springframework.maven.snapshot</id>
<name>Spring Maven Snapshot Repository</name>
<url>http://maven.springframework.org/snapshot</url>
<releases>
<enabled>false</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository >
</repositories>

Step 2: The next step is to define a Spring MVC controller that we will be writing unit test for :

@Controller
@RequestMapping("/test")
public class RestController {
private static final Logger LOG = LoggerFactory
.getLogger(RestController.class);
@Autowired
RestTemplate template;
@Autowired
IRestService iRestService;
@RequestMapping(value = "/google", method = RequestMethod.GET)
@ResponseBody
public String hitGoogle() {
LOG.info("Notification : hit google command received from REST");
return iRestService.hitGoogle();
}
}

Step 3: Write Impl class which actually perform REST Client operation to get information from some another end Web application.

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.client.RestTemplate;

import com.waheed.mockserver.service.IRestService;

@Service
public class RestServiceImpl implements IRestService {

private static final Logger LOG = LoggerFactory
.getLogger(RestServiceImpl.class);

@Autowired
RestTemplate restTemplate;

/**
* REST client that makes a call to a URL and handle success and error by
* returning them in error String.
*/
public String hitGoogle() {
LOG.info("Testing google :");
String response;
try {
response = restTemplate.getForObject("http://google.com",
String.class);
LOG.info("Response : {}", response);
} catch (HttpStatusCodeException e) {
LOG.error("Error while testing google", e);
return "FAILED : " + e.getStatusCode();
} catch (Exception e) {
LOG.error("Error while testing google", e);
return "FAILED : " + e.getStackTrace();
}
return response;
}
}
Step 4 : Finally the unit test class that uses Spring-test-mvc to mock the controller that returns the response as String.

import static org.junit.Assert.assertEquals;
import static org.springframework.test.web.client.match.RequestMatchers.method;
import static org.springframework.test.web.client.match.RequestMatchers.requestTo;
import static org.springframework.test.web.client.response.ResponseCreators.withSuccess;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.web.client.RestTemplate;

import com.waheed.mockserver.controller.RestController;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="file:WebContent/WEB-INF/spring-servlet.xml")
public class TestMockRestServiceServer {

@Autowired
private RestTemplate restTemplate;

private MockRestServiceServer mockServer;
@Autowired
RestController restController;

// Execute the Setup method before the test.
@Before
public void setUp() {
//create a mock Server instance for RestTemplate
mockServer = MockRestServiceServer.createServer(restTemplate);
}

@Test
public void testGoogleSuccess() {
mockServer
.expect(requestTo("http://google.com"))
.andExpect(method(HttpMethod.GET))
.andRespond(
withSuccess("SUCCESS",
MediaType.TEXT_PLAIN));
String response = restController.hitGoogle();
mockServer.verify();
assertEquals("SUCCESS",response);
}
}
Here :
@RunWithSpring(SpringJunit4ClassRunner.class) runs the test with Spring custom runner that will load Spring application context from @ContextConfiguration(locations="file:WebContent/WEB-INF/spring-servlet.xml")

@Before annotation executes the setup method before the test. It will create the mockServer for the restTemplate Instance. 
@Test executes the actual test
    mockServer.expect(requestTo("URL")).andExpect(method(Method Type))
.andRespond(withSuccess("RESPONSE MESSAGE”,”MESSAGE FROMAT LIKE JSON OR XML”));

If the controller hit some URL which has exactly the same URL and method type as we have set above then the spring-test-mvc will mock the response as set above.

Note : You must have observed that in unit test case there are few imports which are static. To find the Static imports in your Eclipse IDE you have to configure a bit. Goto Java>Editor>Content Assist>Favorites and Add

    If using Spring 3.2.x:
    org.springframework.test.web.client.match.MockRestRequestMatchers
    org.springframework.test.web.client.response.MockRestResponseCreators

    If using Spring 3.1.x, the static import classes are named differently:
    org.springframework.test.web.client.match.RequestMatchers
    org.springframework.test.web.client.response.ResponseCreators

Common issue:

java.lang.SecurityException: class "org.hamcrest.TypeSafeMatcher"'s signer information does not match signer information of other classes in the same package
at java.lang.ClassLoader.checkCerts(Unknown Source)

There are few ways to resolve the above issue :
Mockito use Hamcrest 1.1 API in the classpath and Eclipse JUnit 4 distribution also has the Hamcrest Core 1.1 API.
  1. You may get this error when Hamcrest API is invoked from Eclipse JUnit’s and Not Mockito. The solution is change the ordering of the jar files in “Order & Export” tab of Eclipse build path.
  2. Or simply removing the JUnit 4 library also fixes the problem apparently
     (junit and hamcrest will be in the maven deficiencies anyway).
You can download the above tutorial form here. 
 
References :
http://docs.spring.io/spring/docs/3.2.x/javadoc-api/index.html?org/springframework/test/web/client/MockRestServiceServer.html
https://github.com/spring-projects/spring-framework/tree/master/spring-test-mvc/src/test/java/org/springframework/test/web/client/match

Thursday, October 17, 2013

How to create Spring MVC project using Maven and Eclipse


This blog will show you how quickly you can  create a Spring MVC project and get it up and running, using the Maven archetype called spring-mvc-archetype.

Note: First You should verify that the Maven Integration for FTP is already installed in your eclipse, If not first installed and then create a new project.

Steps :
  • In Eclipse IDE, Goto  File > New > Project
  • Select Maven > Maven Project and click Next.
  • Make sure you don’t check the option Create a simple project (skip archetype selection), and click Next. In the next screen,
  • Select Catalog as All Catalogs, Archetype as spring-mvc into the Filter  and select maven-archetype-webapp in the artifact list as shown below :

 

In case, If you don't see the above artifact in your Archtype then Click on "Add Archetype" and Add :
    • Archetype Group Id: co.ntier
    • Archetype Artifact Id: spring-mvc-archetype
    • Archetype Version: 1.0.2
    • Repository URL: http://maven-repository.com/artifact/co.ntier/spring-mvc-archetype/1.0.2\
     
Click Next and Enter Group Id (e.g. Test), Artifact Id (e.g. Test), Version (e.g. 1.0) and Package (com.waheed.test), as shown below :

Click Finish.Finally you have a project structure looks like below:                         

 

Wednesday, January 2, 2013

How ExceptionHandler return JSON in spring MVC

I am working on one project where client/server response is in JSON format. It is easy to send object in JSON format but what if some exception occured and you want to send the Exception also in JSON format ?
After n number of trial. I finally able to do the above task

Step 1 : Add following annotation "AnnotationMethodHandlerExceptionResolver" in your <CONTROLLER>-servlet.xml file.


<!-- JSON format support for Exception -->
    <bean id="methodHandlerExceptionResolver"
        class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver">
        <property name="messageConverters">
            <list>
                <ref bean="jacksonMessageConverter" />
            </list>
        </property>
    </bean>

    <bean id="jacksonMessageConverter"
        class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>


Step 2: Make sure you have added jackson jars into your classpath.


Step 3: In controller class :



    @RequestMapping(value="/test", method = RequestMethod.GET)
    @ResponseBody
    public String toTest() throws MxlServiceException {

   try {
      int i = 10/0; // it will throw exception which will be caught by handleException(...)
  }catch (Exception e) {
    throw e;
   }
             return "hello";
 }


then catch them both by writing an exception handler that looks like this:

@ExceptionHandler({ Exception.class })
  @ResponseBody
    public ErrorResponse handleException(Exception ex,
            HttpServletRequest request, HttpServletResponse response) {
             response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        ErrorResponse errorResponse = new ErrorResponse();
        errorResponse.setMessage(ex.getMessage());
        return errorResponse;
    }


Output:

{"message": "your_message"}


Feel free to comment :)



Wednesday, August 29, 2012

How to integrate Liquibase with Spring and Hibernate ?

A sample tutorial on how to integrate Liquibase with Spring and Hibernate.

While writing this tutorial, I have added javadoc in the code for better understanding and I believe You already have good knowledge on Spring and Hibernate. The main motto of this tutorial is to give an idea on how you can integrate Liquibase with Spring and Hibernate.

If you are new to Liquibase : Click Here

To integrate liquibase into your project, you need liquibase jars, So download it before starting the project.

I have created an application named "SHLIntegration". The Structure of the project is as follows :

The dependencies are also listed here:

Lets start with Employee class :

1. Create Employee class having getter/setter and add proper JPA annotation to each variable as below.

  public class Employee {

    @Id
    @GeneratedValue
    @Column(name="EMPLOYEE_ID")
    private long id;

    @Column(name="NAME")
    private String name;
   
    @Column(name="GENDER")
    private String gender;
   
    @Column(name="COUNTRY")
    private String country;
   
    @Column(name="ABOUT_YOU")
    private String aboutYou;

.....
....
.... // getter setter of each object

}

2. Create liquibase file i,e db-changelog.xml file

<?xml version="1.0" encoding="UTF-8"?>
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-2.0.xsd">
       
    <changeSet author="waheed" id="123456789-1">
        <createTable tableName="EMPLOYEE">
            <column autoIncrement="true" name="EMPLOYEE_ID" type="BIGINT">
                <constraints nullable="false" primaryKey="true" />
            </column>
            <column name="NAME" type="VARCHAR(255)" />
            <column name="GENDER" type="VARCHAR(2)" />
            <column name="COUNTRY" type="VARCHAR(255)" />
            <column name="ABOUT_YOU" type="VARCHAR(255)" />
        </createTable>
    </changeSet>
</databaseChangeLog>




3. Add liquibase bean in your bean :

    <bean id="LiquibaseUpdater" class="liquibase.integration.spring.SpringLiquibase">
        <property name="dataSource" ref="dataSource" />
        <property name="changeLog" value="classpath:db-changelog.xml" />
    </bean>


 and others beans which are required for Spring/Hibernate.  Check bean file


The complete tutorial : 
https://github.com/abdulwaheed18/SHLIntegration


Please feel free to do comment or drop me a mail regarding any suggestion/Feedback.
Email : waheedtechblog@gmail.com















 


Spring MVC tutorial

Before Starting, I believe you must have basic idea about JAVA, SPRING and Spring MVC.

For Spring MVC : http://waheedtechblog.blogspot.in/2012/08/spring-mvc.html

In this tutorial , I will just tell you what are the basic thing that you need to start MVC.

Step 1 : Create a class 


@Controller
public class HelloWorld {
 
    @RequestMapping("/hello")
    public String helloWorld() {
         return = "Hello World, Spring 3.0!";
    }
}


1 . The class HelloWorld  has the annotation @Controller and @RequestMapping("/hello"). When Spring scans this class, it will recognize this bean as being a Controller bean for processing requests. 2 .The @RequestMapping annotation tells Spring that this Controller should process all requests beginning with /hello in the URL path.

Step 2. Mapping Spring MVC in WEB.xml

The entry point of Spring 3.0 MVC is the DispatcherServlet. DispatcherServlet is a normal servlet class which implements HttpServlet base class. Thus we need to configure it in web.xml.

<!-- ========================== -->
    <!-- Spring MVC: Core -->
    <!-- ========================== -->

    <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>

<!-- This loads the root webapp Spring context -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:beans.xml</param-value>
    </context-param>
   
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

Note that I have mapped /rest/* url pattern with example DispatcherServlet. Thus any url with /rest/* pattern will call Spring MVC Front controller.

                  The REST call would be http://ip:port/rest/hello

If your controller class has some dependency which you have defined in your spring context file.Then you have to load it in <context-param>.(red line).
Once the DispatcherServlet is initialized, it will looks for a file name [servlet-name]-servlet.xml in WEB-INF folder of web application. I have created the file named spring-servlet.xml


3 . Spring Configuration file

Create a file spring-servlet.xml in WEB-INF folder and copy following content into it.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:task="http://www.springframework.org/schema/task"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:util="http://www.springframework.org/schema/util"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/task
    http://www.springframework.org/schema/task/spring-task-3.0.xsd
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/util
        http://www.springframework.org/schema/util/spring-util-2.0.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
        ">

    <!-- ========================== -->
    <!-- Spring MVC: Core -->
    <!-- ========================== -->

    <context:annotation-config />
    <mvc:annotation-driven />
    <mvc:default-servlet-handler />

    <!-- class name of the controller or If you have package use component-scan -->
    <bean class="com.waheed.spring.hibernate.HelloWorld" />

 </beans>

The highlighted red line allow Spring to load the components from class. This will load our HelloWorld class.

Congratulation..!!! You are done here...

Download source code : https://github.com/abdulwaheed18/SpringMVC-Hibernate-Integration

How TOPT Works: Generating OTPs Without Internet Connection

Introduction Have you ever wondered how authentication apps like RSA Authenticator generate One-Time Passwords (OTPs) without requiring an i...