Tuesday, October 29, 2013

How to substitute dynamic placeholder in properties file

This blog will explain you how can you use replace placeholder with original value in properties file. To achieve this task we will you Java API MessageFormat.

Suppose you have properties file named "welcome.properties" having message :
welcome=Hi {0} , Welcome to {1}
Sample : 

import java.io.File;
import java.io.FileInputStream;
import java.text.MessageFormat;
import java.util.Properties;

 * @author abdul
public class DynamicPlaceholder {

* @param args
* @throws Exception 
public static void main(String[] args) throws Exception {
File propFile = new File("D:\\juno\\Practise\\src\\com\\waheed\\dynamic\\placeholder\\substitution\\welcome.properties");
Properties props = new Properties();
FileInputStream stream=new FileInputStream(propFile);
String message = props.getProperty("welcome");
               // Here the {0} and {1} will be substitute with "Waheed" and "India".
String welcome = MessageFormat.format(message, "Waheed","India");
System.out.println("Your message : " + welcome);

Output : 

Your message : Hi Waheed , Welcome to India

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.


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
public class EmployeeServiceImpl implements EmployeeService {

    private EmployeeDao employeeDao;

    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;

public class EmployeeTest {
    @Mock EmployeeDao mockDao;

    @InjectMocks EmployeeServiceImpl employeeServiceImpl;
    private Employee employee;
    public void setup() {
        employee = new Employee();
    private void setEmployee() {
    public void employeeTest() throws Exception {
        Employee emp =employeeServiceImpl.getEmployee(1);
        //Verify if getEmployee method was invoked on employeeServiceImpl call
    public void employeeTestFailure() throws Exception {
        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


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
<!-- This is not in Maven Central yet must include Spring snapshot repository -->

<!-- For testing against latest Spring snapshots -->
<name>Spring Maven Snapshot Repository</name>
</repository >

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

public class RestController {
private static final Logger LOG = LoggerFactory
RestTemplate template;
IRestService iRestService;
@RequestMapping(value = "/google", method = RequestMethod.GET)
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;

public class RestServiceImpl implements IRestService {

private static final Logger LOG = LoggerFactory

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",
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;

public class TestMockRestServiceServer {

private RestTemplate restTemplate;

private MockRestServiceServer mockServer;
RestController restController;

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

public void testGoogleSuccess() {
String response = restController.hitGoogle();
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))

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:

    If using Spring 3.1.x, the static import classes are named differently:

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 :

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:                         


Thursday, July 25, 2013

How to do JVM Remote debugging via SSH

Last week I was getting one issue which was difficult to debug as the product was on EC2 instance. We were wasting lot of time as It was difficult to test and check the actual cause of issue.  Later I decided to attach the Eclipse debugger to my target JVM which is running on some different(EC2 instance) machine with the help of PuTTy ( PuTTY is an SSH and telnet client).

Lets start with the steps :

1. Make sure your target JVM is started with these args:
2. Create an SSH session into your PuTTy.
      Open Putty, Add :
        -- IP Address : "YOUR_TARGET_JVM_ADDRESS"
        -- PORT : 22
        -- Saved Sessions : your session name
        -- Choose 'SSH' radio button and Save it.

3. After saving your server detail, in the same putty :
     -- Goto Category -> SSH ->tunnels
     -- source port :7000
     -- Destination : ip:port <eg :> 
     -- Click on 'Add' button
     -- Again click on 'session' under category and save it.
     -- Start the session once you are done with above settings by clicking on 'open'  button.

4 . In Eclipse, Goto Run -> Debug Configuration -> Remote Java Application and Add :
      -- Project : point to your project directory
      -- Choose 'connection type'  as 'Standard (Socket Attach)'
      -- Host : localhost
      -- Port : 7000 (Must be same as source port in PuTTy)


Now You  are good to go to start with your remote debugging :)

Note : Sometime during Remote Debugging, You might get some error message like "Connection timeout". To fix the issue, Goto : Eclipse - > Windows -> Preferences -> Java ->Debug and set debugger timeout as some higher value.

 Please let me know your comments/feedback, if any.

Friday, May 24, 2013

How to enable convert extension into Mercurial ?

Advanced users of Mercurial can be aided with the use of Mercurial extensions. Extensions allow the integration of powerful new features directly into the Mercurial core. 
Built-in help on extensions is available with 'hg help extensions'. To get help about an enabled extension, run 'hg help <extension-name>'.

Convert Extension

The Convert extension converts repositories from other SCMs (or even Mercurial itself) into Mercurial repositories, with options for filtering and renaming. It can also be used to filter Mercurial repositories to get subsets of an existing one.
The current release supports the following repository types as sources:
  • CVS
  • Subversion
  • Git
  • Darcs
  • Monotone
  • Bazaar
  • GNU Arch
  • Mercurial
  • Perforce
Convert extension comes up together with Mercurial. To enable convert extension, add following lines in your configuration file, Edit your $HOME/.hgrcwhich look like:

Lets begin by downloading the latest revision of the repository. Mercurial will download it from the remote repository with the full history.

[root@localhost Desktop]# hg convert svn://svn.repo.com/frontend/mxlLayer mxl_test
initializing destination mxl_test repository
scanning source...
9 creating new repository for mxl Service layer.
8 * Fixed 500 error while creating tenant
7 * Javadocs added
6 * Renamed MXLLayerLog.xml back to logback.xml
5 1. Change return type of createTenant from long to MXLServiceResponse in TenantController.java
4 Added 3 new Api's:
3 Added target to ignore list
2 Added start/stop functionality.
1 Changed code according to review comments.
0 1.Added test cases for TenanatController Api's:1.CreateTenant 2.GetProtalInfo 3. GetApplications.

We are done! If you cd to the newly created mxl_test directory, you will be entering a fully fledged, history-preserved Mercurial repository, consisting of the exact same files as the Subversion repository.

[root@localhost mxl_test]# hg update # update to pull all repositories.
26 files updated, 0 files merged, 0 files removed, 0 files unresolved

[root@localhost mxl_test]# hg log # All log entry are preserved.
changeset: 9:08614ddd43c7
branch: mxlLayer
tag: tip
user: ankush
date: Fri Dec 28 16:19:17 2012 +0000
summary: 1.Added test cases for TenanatController Api's:1.CreateTenant 2.GetProtalInfo 3. GetApplications.
changeset: 8:c59c6dedf445
branch: mxlLayer
user: pravin
date: Fri Dec 28 13:54:15 2012 +0000
summary: Changed code according to review comments.
changeset: 7:7b863092bf77
branch: mxlLayer
user: abdul
date: Fri Dec 28 09:55:34 2012 +0000
summary: Added start/stop functionality.
changeset: 6:14064cef906d
branch: mxlLayer
user: deepak

date: Thu Dec 27 16:12:38 2012 +0000
summary: Added target to ignore list
changeset: 5:2a450c99b687
branch: mxlLayer
user: pravin
date: Thu Dec 27 15:10:07 2012 +0000
summary: Added 3 new Api's:
changeset: 4:681d8882361e
branch: mxlLayer
user: abdul
date: Thu Dec 27 13:09:46 2012 +0000
summary: 1. Change return type of createTenant from long to MXLServiceResponse in TenantController.java
changeset: 3:dc92af2b2e48
branch: mxlLayer
user: deepak
date: Thu Dec 27 08:54:07 2012 +0000
summary: * Renamed MXLLayerLog.xml back to logback.xml
changeset: 2:628fd78ee782
branch: mxlLayer
user: deepak
date: Thu Dec 27 05:52:43 2012 +0000
summary: * Javadocs added
changeset: 1:7513eadc9761
branch: mxlLayer
user: deepak
date: Wed Dec 26 15:39:08 2012 +0000
summary: * Fixed 500 error while creating tenant
changeset: 0:bc1f1d1f6a30
branch: mxlLayer
user: abdul
date: Wed Dec 26 14:11:55 2012 +0000
summary: creating new repository for mxl Service layer.

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