Thursday 27 June 2013

Example Thread Runner Using the ExecutorService

Here is a simple example of how to create a thread runner using thread pools. This can be useful during testing or when trying to establish the time it takes for a number of threads to complete.

The Thread

package com.blah.thread.runner;



/**
 * This is a sample class to launch a rule.
 */
public class SomeThread implements Runnable {

String name;
public SomeThread(String name) {
this.name = name;
}

@Override
public void run() {
System.out.println(getName() + " is running");
}
public String getName() {
return name;
}

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


}

The Runner


package com.blah.thread.runner;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


public class SomeThreadRunner {
private static final int THREAD_POOL_SIZE = 5;
private static final int NO_OF_THREADS = 10;

 public static void main(String[] args) {
long start = System.nanoTime(); 
   ExecutorService executor = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
   for (int i = 0; i < NO_OF_THREADS ; i++) {
     Runnable worker = new SomeThread("Thread " + i);
     executor.execute(worker);
   }
   //Accept no more threads
   executor.shutdown();
   
   // Wait until all threads are finished
   while (!executor.isTerminated()) {}
   
   long elapsedTime = System.nanoTime() - start;
   System.out.println("Threads took " + elapsedTime / 1000000000.0 + " seconds to complete");
 }

}

Friday 21 June 2013

JDBC DAO Unit Test using Mockito

For some, it's hard to think of unit testing a DAO without actually interacting with a database. This example illustrates a basic unit test for a dao class, that uses a Spring NamedParameterJdbcTemplate, without the need to actully query the underlying database:

package com.blah.test.dao;

import static org.junit.Assert.assertEquals;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.eq;
import static org.mockito.Matchers.refEq;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.test.util.ReflectionTestUtils;

public class MockJdbcLookUpDAOTest {

private JdbcLookUpDAODAO dao;

@Mock
private NamedParameterJdbcTemplate namedTemplate;

private static final String SAMPLE_SQL = "SELECT * " +
"FROM SOME_TABLE " +
"WHERE ID = :id";

@Before
public void setUp(){
MockitoAnnotations.initMocks(this);
dao = new JdbcFssCodeLookUpDAO();

//Spring utility class for use in unit and integration testing scenarios.
//Allows mocks to be used where no setters are accessible
ReflectionTestUtils.setField(dao, "namedTemplate", namedTemplate);
}

@Test
public void testGetFssCodeUpByPostcode(){

MapSqlParameterSource param = new MapSqlParameterSource();
param.addValue("id", "1");

//Mock the named template call to return a known String, 
//without the need for any db look up, as this would be an integration test
given(namedTemplate.queryForObject(eq(SAMPLE_SQL), refEq(param), eq(String.class))).willReturn("K");

//call the dao method, but trigger the above mock method call
String fssCode = dao.doLookUp(((String) param.getValue("id"));

//check the named template method was called once, with the expected query string and parameter values
verify(namedTemplate, times(1)).queryForObject(eq(FSS_CODE_BY_POSTCODE_SQL), refEq(param), eq(String.class));

//Check the dao method returns the expected value
assertEquals(fssCode, "K");

}


}

Wednesday 5 June 2013

Extract parameter from URL String

The code below is shows how to extract a parameter from a URL string. This is useful when you need to extract a parameter value from the HTTP referrer string, which itself is a parameter of the HttpServletRequest object.

String searchTerm = null;
String urlString = "http://www.somewebaddress.co.uk/?test=blah+blah+blah&Test2=stuff";
URL url;
try {
url = new URL(urlString);
String queryString = url.getQuery();
//Check for single or multiple params
String[] params = (queryString.split("&").length > 0) ? queryString.split("&"): new String[]{queryString};
for(String param : params){
String[] paramNameValuePair = param.split("=");
if(paramNameValuePair[0].equals("test")){
searchTerm = paramNameValuePair[1];
System.out.println(searchTerm);
}
}
} catch (MalformedURLException e) {
System.out.println("Invalid URL!!");
}