Monday, December 31, 2012

Json deserialization with Jackson and Super type tokens

Datatables is a jquery plugin to present tabular information - it can enhance a simple table or can use a AJAX based data and present the information in a tabular form.

Datatables requires the data from the server to follow a specific JSON format for it to be displayed on screen. Consider the case where a list of Member entities is to be displayed, the expected json structure for Members then has to be along these lines:


{
   "aaData":[
      {
         "id":1,
         "first":"one",
         "last":"one",
         "addresses":[

         ],
         "version":0
      },
      {
         "id":2,
         "first":"two",
         "last":"two",
         "addresses":[

         ],
         "version":0
      }
   ],
   "iTotalRecords":100,
   "iTotalDisplayRecords":10,
   "success":true
}

A generic java type can be defined which Jackson can use to generate json of the type shown above, consider the following Java generic type:

package mvcsample.types;
import java.util.List;

public class ListWrapper<T> {
    private List<T> aaData;
    private int iTotalRecords;
    private int iTotalDisplayRecords;
    private  Boolean success;

    public List<T> getAaData() {
  return aaData;
 }
 public void setAaData(List<T> aaData) {
  this.aaData = aaData;
 }
 public int getiTotalRecords() {
  return iTotalRecords;
 }
 public void setiTotalRecords(int iTotalRecords) {
  this.iTotalRecords = iTotalRecords;
 }
 public int getiTotalDisplayRecords() {
  return iTotalDisplayRecords;
 }
 public void setiTotalDisplayRecords(int iTotalDisplayRecords) {
  this.iTotalDisplayRecords = iTotalDisplayRecords;
 }
 public Boolean getSuccess() {
  return success;
 }
 public void setSuccess(Boolean success) {
  this.success = success;
 }   
}

So, with this generic type, to generate a list of Members I would have a parameterized type defined as in this test:

List<Member> members = new ArrayList<>();
members.add(new Member("one", "one"));
members.add(new Member("two", "two"));
ListWrapper<Member> membersWrapper = new ListWrapper<>();
membersWrapper.setAaData(members);
membersWrapper.setiTotalDisplayRecords(10);
membersWrapper.setiTotalRecords(100);
ObjectMapper objectMapper = new ObjectMapper();

StringWriter w = new StringWriter();
objectMapper.writeValue(w, membersWrapper);
String json = w.toString();
System.out.println(json);

And similarly a json for any other type can be generated.

However, what about the other way around, generating the Java type given the json.

Again, consider a case where the json given in the beginning is to be converted to ListWrapper<Member> , I can try a deserialization this way:

ObjectMapper objectMapper = new ObjectMapper();  
ListWrapper<Member> membersUpdated = objectMapper.readValue(json, ListWrapper.class);

Note that above I cannot refer to the class type as ListWrapper<Member>.class, I can only refer to it as ListWrapper.class.

This however will not work and the resulting type will not be a wrapper around Member class, as at runtime Jackson has no idea that it has to generate a ListWrapper<Member>.

The fix is to somehow pass the information about the ListWrapper's type to Jackson and this is where Super type tokens fits in. The article explains how this works in great detail, the essence is that
while type erasure does remove the type information from parameterized instances of generic type, however the type is retained in subclasses of generic classes.

For eg. Consider the following StringList class which derives from ArrayList<String> , it is possible to find that the type parameter of the base class is a String as shown in the test below:

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;

public class StringList extends ArrayList<String>{

 public static void main(String[] args) {
  StringList list = new StringList();
  Type superClassType = list.getClass().getGenericSuperclass();
  ParameterizedType parameterizedType = (ParameterizedType)superClassType;
  System.out.println(parameterizedType.getActualTypeArguments()[0]);
 }
}

This is applicable for a case where a subclass is defined as an anonymous class also this way:

ArrayList<String> list = new ArrayList<String>(){};
Type superClassType = list.getClass().getGenericSuperclass();
ParameterizedType parameterizedType = (ParameterizedType)superClassType;
System.out.println(parameterizedType.getActualTypeArguments()[0]);

This is what is used internally with the Super Type tokens pattern to find the type of the parameterized type. Jackson's com.fasterxml.jackson.core.type.TypeReference abstract class implements this and using this the Jackson deserialization would work this way:

import com.fasterxml.jackson.core.type.TypeReference;

....
ListWrapper<Member> membersWrapper = objectMapper.readValue(json, new TypeReference<ListWrapper<Member>>() {});

ListWrapper<Address> addressWrapper = objectMapper.readValue(json, new TypeReference<ListWrapper<Address>>() {});

This way two different parameterized types can be deserialized given a generic type and a json representation.


References:

Reflecting Generics: http://www.artima.com/weblogs/viewpost.jsp?thread=208860

Neal Gafter's Super type tokens: http://gafter.blogspot.com/2006/12/super-type-tokens.html

Thursday, December 27, 2012

Spring Data JPA and pagination

Let us start with the classic JPA way to support pagination.

Consider a simple domain class - A "Member" with attributes first name, last name. To support pagination on a list of members, the JPA way is to support a finder which takes in the offset of the first result(firstResult) and the size of the result(maxResults) to retrieve, this way:

import java.util.List;

import javax.persistence.TypedQuery;

import org.springframework.stereotype.Repository;

import mvcsample.domain.Member;

@Repository
public class JpaMemberDao extends JpaDao<Long, Member> implements MemberDao{

 public JpaMemberDao(){
  super(Member.class);
 }
 @Override
 public List<Member> findAll(int firstResult, int maxResults) {
  TypedQuery<Member> query = this.entityManager.createQuery("select m from Member m", Member.class);
  return query.setFirstResult(firstResult).setMaxResults(maxResults).getResultList();
 }

 @Override
 public Long countMembers() {
  TypedQuery<Long> query = this.entityManager.createQuery("select count(m) from Member m", Long.class);
  return query.getSingleResult();
 }
}

An additional API which returns the count of the records is needed to determine the number of pages for the list of entity, as shown above.

Given this API, two parameters are typically required from the UI:


  • the current page being displayed (say "page.page")
  • the size of list per page (say "page.size")
The controller will be responsible for transforming these inputs to the one required by the JPA - firstResult and maxResults this way:

@RequestMapping(produces="text/html")
public String list(@RequestParam(defaultValue="1", value="page.page", required=false) Integer page, 
   @RequestParam(defaultValue="10", value="page.size", required=false) Integer size, Model model){
 int firstResult = (page==null)?0:(page-1) * size;
 model.addAttribute("members",this.memberDao.findAll(firstResult, size));
 float nrOfPages = (float)this.memberDao.countMembers()/size;
 int maxPages = (int)( ((nrOfPages>(int)nrOfPages) || nrOfPages==0.0)?nrOfPages+1:nrOfPages);
 model.addAttribute("maxPages", maxPages);
 return "members/list";
}

Given a list as a model attribute and the count of all pages(maxPages above), the list can be transformed to a simple table in a jsp, there is a nice tag library that is packaged with Spring Roo which can be used to present the pagination element in a jsp page, I have included it with the reference.



So this is the approach to pagination using JPA and Spring MVC.

Spring-Data-JPA makes this even simpler, first is the repository interface to support retrieving a paginated list - in its simplest form the repository simply requires extending Spring-Data-JPA interfaces and at runtime generates the proxies which implements the real JPA calls:

import mvcsample.domain.Member;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

public interface MemberRepository extends JpaRepository<Member, Long>{
 //
}

Given this, the controller method which accesses the repository interface is also very simple:

@RequestMapping(produces="text/html")
public String list(Pageable pageable, Model model){
 Page<Member> members = this.memberRepository.findAll(pageable);
    model.addAttribute("members", members.getContent());
    float nrOfPages = members.getTotalPages();
    model.addAttribute("maxPages", nrOfPages);
 return "members/list";
}

The controller method accepts a parameter called Pageable, this parameter is populated using a Spring MVC HandlerMethodArgumentResolver that looks for request parameters by name "page.page" and "page.size" and converts them into the Pageable argument. This custom HandlerMethodArgumentResolver is registered with Spring MVC this way:

<mvc:annotation-driven>
 <mvc:argument-resolvers>
  <bean class="org.springframework.data.web.PageableArgumentResolver"></bean>
 </mvc:argument-resolvers>
</mvc:annotation-driven> 

the JpaRepository API takes in the pageable argument and returns a page, internally automatically populating the count of pages also which can retrieved from the Page methods.

If the queries need to be explicitly specified then this can be done in a number of ways, one of which is the following:

@Query(value="select m from Member m", countQuery="select count(m) from Member m")
Page<Member> findMembers(Pageable pageable);


One catch which I could see is that that pageable's page number is 0 indexed, whereas the one passed from the UI is 1 indexed, however the PageableArgumentResolver internally handles and converts the 1 indexed UI page parameter to the required 0 indexed value.

Spring Data JPA thus makes it really simple to implement a paginated list page.

I am including a sample project which ties all this together, along with the pagination tag library which makes it simple to show the paginated list.

Reference:
A sample projects which implements a paginated list is available here : https://github.com/bijukunjummen/spring-mvc-test-sample.git

Spring-Data-JPA reference: http://static.springsource.org/spring-data/data-jpa/docs/current/reference/html/




Sunday, December 23, 2012

context:component-scan, context:annotation-config and list of beans registered

A <context:component-scan/> custom tag registers the same set of bean definitions as is done by <context:annotation-config/>, apart from its primary responsibility of scanning the java packages and registering bean definitions from the classpath.

The following bean types are registered by either of these custom tags:


Bean Purpose
ConfigurationClassPostProcessor
A bean factory post processor used for bootstrapping classes annotated with @Configuration
AutowiredAnnotationBeanPostProcessor
A bean post processor which processes fields, setter methods, arbitrary methods annotated with @AutoWired, @Value and supports JSR-330 @Inject annotation
RequiredAnnotationBeanPostProcessor
A bean post processor which enforces that the required bean properties have been set - by looking for fields annotated with @Required annotation
CommonAnnotationBeanPostProcessor
A bean post processor which supports JSR-250 annotations - eg. @Resource
PersistenceAnnotationBeanPostProcessor
A bean post processor that processes @PersistenceUnit and @PersistenceContext annotations for injecting in a EntityManagerFactory and EntityManager respectively.

This is the reason why if component-scan is present, annotation-config can be kept out.

If for some reason this registration of default bean definitions are to be avoided, the way to do that is to specify an additional "annotation-config" attribute in component-scan, this way:



<context:component-scan basePackages=".." annotation-config="false"/>

Reference:
Spring Reference site

Sunday, December 9, 2012

Composing Java annotations

The allowed attribute types of a Java annotations are deliberately very restrictive, however some clean composite annotation types are possible with the allowed types.

Consider a sample annotation from the tutorial site:

package annotation;
@interface ClassPreamble {
   String author();
   String[] reviewers();
}

Here the author and reviewers are of String and array types which is in keeping with the allowed types of annotation attributes. The following is a comprehensive list of allowed types(as of Java 7):


  • String
  • Class
  • any parameterized invocation of Class
  • an enum type
  • an annotation type, do note that cycles are not allowed, the annotated type cannot refer to itself
  • an array type whose element type is one of the preceding types.

Now, to make a richer ClassPreable consider two more annotation types defined this way:

package annotation;

public @interface Author {
 String first() default "";
 String last() default "";
}


package annotation;

public @interface Reviewer {
 String first() default "";
 String last() default "";
}


With these, the ClassPreamble can be composed from the richer Author and Reviewer annotation types, this way:

package annotation;
@interface ClassPreamble {
   Author author();
   Reviewer[] reviewers();
}

Now an annotation applied on a class looks like this:

package annotation;

@ClassPreamble(author = @Author(first = "John", last = "Doe")
    , reviewers = {@Reviewer(first = "first1", last = "last1"), @Reviewer(last = "last2") }
)
public class MyClass {
....
}

This is a contrived example just to demonstrate composition of annotations, however this approach is used extensively for real world annotations, for eg, to define a many to many relationship between two JPA entities:

    @ManyToMany
    @JoinTable(name="Employee_Project",
          joinColumns=@JoinColumn(name="Employee_ID"),
          inverseJoinColumns=@JoinColumn(name="Project_ID"))
    private Collection<Project> projects;

Tuesday, November 27, 2012

Spring test mvc with Spring 3.2RC1

I had an opportunity earlier to try out Spring-test-mvc and was very impressed with how easy it now makes integration testing of the Spring MVC controllers.

Spring-test-mvc is now packaged with Spring-test module as of Spring 3.2RC1 and has made a few changes which is what I wanted to record for myself here:

First is to include the Spring-test-mvc module, the following is the dependency now that it is packaged with spring-test module:

<dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-test</artifactId>
 <version>3.2.0.RC1</version>
 <scope>test</scope>
</dependency>

Now on the test side the first change is to include a @WebAppConfiguration annotation:

@WebAppConfiguration
@ContextConfiguration(locations={"file:src/main/webapp/WEB-INF/spring/mvc-config.xml", "classpath:/META-INF/spring/applicationContext.xml", "classpath:/META-INF/spring/applicationContext-jpa.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
public class MemberJsonControllerTest {
 
 @Autowired
 private WebApplicationContext wac;




This new annotation instructs Spring test support to load up a WebApplicationContext - a mock ServletContext is automatically assigned to this WebApplicationContext.

Another change from previous version of Spring-test-mvc is the updated package names, the following are the new static imports:

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.*;

Now that a WebApplicationContext is available in the scope of the test, the next step is to get hold of MockMvc which will drive all the controller related tests:

private MockMvc mockMvc;

@Before
public void setup() {
 this.mockMvc = webAppContextSetup(this.wac).build();
}

Once a MockMvc instance is available all the controller tests can be driven using this, consider the following test where I have a series of CRUD actions and tests on the results being performed on a controller:

@Test
public void testAControllerFlow() throws Exception {
 this.mockMvc.perform(post("/membersjson").contentType(MediaType.APPLICATION_JSON).content(String.format(createJson, 1,"One","One", 0).getBytes()))
   .andExpect(status().isOk());
 this.mockMvc.perform(post("/membersjson").contentType(MediaType.APPLICATION_JSON).content(String.format(createJson, 2,"Two","Two", 0).getBytes()))
  .andExpect(status().isOk());
 this.mockMvc.perform(post("/membersjson").contentType(MediaType.APPLICATION_JSON).content(String.format(createJson, 3,"Three","Three", 0).getBytes()))
  .andExpect(status().isOk());  
 
 this.mockMvc.perform(get("/membersjson").contentType(MediaType.APPLICATION_JSON))
   .andExpect(status().isOk())
   .andExpect(content().string(containsString(membersJson)));
 
 this.mockMvc.perform(put("/membersjson").contentType(MediaType.APPLICATION_JSON).content(String.format(createJson, 1,"One","OneUpdated", 0).getBytes()))
  .andExpect(status().isOk());
 
 mockMvc.perform(get("/membersjson").contentType(MediaType.APPLICATION_JSON))
  .andExpect(status().isOk())
  .andExpect(jsonPath("$[0].first").value("One"));
 
 mockMvc.perform(get("/membersjson/1").contentType(MediaType.APPLICATION_JSON))
  .andExpect(status().isOk())
  .andExpect(content().string(containsString("OneUpdated")));

}


The tests are very readable thanks to the fluent interfaces and supports matchers on response data based on Hamcrest which I have used above(containsString) and also supports jsonpath for validating json responses.


I have a github project which provides the complete working sample: https://github.com/bijukunjummen/spring-mvc-test-sample.git



Friday, November 16, 2012

Spring Integration Standalone application

Creating a standalone Spring application and by extension a Spring Integration application is very easy. As long as a non-daemon thread is active, the main thread does not terminate, so if the Spring Integration application has some task related or polling related threads active the main task will be alive.

Consider the Spring Integration application that I had outlined in my previous Blog entry:

<?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:int="http://www.springframework.org/schema/integration"
 xmlns:int-http="http://www.springframework.org/schema/integration/http"
 xsi:schemaLocation="http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd
  http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/integration/http http://www.springframework.org/schema/integration/http/spring-integration-http.xsd">

 <int:inbound-channel-adapter channel="quakeinfotrigger.channel" expression="''">
  <int:poller fixed-delay="60000"></int:poller>
 </int:inbound-channel-adapter>
 
 <int:channel id="quakeinfo.channel">
  <int:queue capacity="10"/>
 </int:channel>

 <int:channel id="quakeinfotrigger.channel"></int:channel> 

 <int-http:outbound-gateway id="quakerHttpGateway"
     request-channel="quakeinfotrigger.channel"
     url="http://earthquake.usgs.gov/earthquakes/feed/geojson/all/hour"
     http-method="GET"
     expected-response-type="java.lang.String"
     charset="UTF-8"
     reply-timeout="5000"
     reply-channel="quakeinfo.channel">     
 </int-http:outbound-gateway>
 
 <int:logging-channel-adapter id="messageLogger" log-full-message="true" channel="quakeinfo.channel" level="ERROR">
  <int:poller fixed-delay="5000" ></int:poller>
 </int:logging-channel-adapter>

</beans>

The above Spring Integration flow polls a http endpoint every minute and prints the contents to System out. Now to write a standalone application out of this, is as simple as the following:
package standalone;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {

 public static void main(String[] args) {
  ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:/httpgateway.xml");
  applicationContext.registerShutdownHook();
 }
}

Initialize the ApplicationContext, and register a shutdown hook for orderly shutdown of the context, that's it! Since the sample flow above spawns threads to poll an http endpoint the application stays active with just the above code.

This sample is available at the following github repo:
https://github.com/bijukunjummen/si-standalone-sample

Thursday, November 15, 2012

Polling an http end point using Spring Integration

It is a little non-intuitive if you want to write a flow with Spring Integration which polls an http end point and gathers some content from the http end point for further processing.

Spring Integration provides a couple of ways for integrating with a HTTP endpoint -

1. Http Outbound adapter - to send the messages to an http endpoint
2. Http Outbound gateway - to send messages to an http endpoint and to collect the response as a message

My first instinct to poll the http endpoint was to use a Http Inbound channel adapter, the wrong assumption that I made was that the adapter will be responsible for getting the information from an endpoint - what Http Inbound Gateway actually does is to expose an Http endpoint and wait for requests to come in! , this is why I started by saying that it was a little non-intuitive to me that to poll a URL and collect content from it I will actually have to use a Http Outbound gateway

With this clarified, consider an example where I want to poll the USGS Earth Quake information feed available at this url - http://earthquake.usgs.gov/earthquakes/feed/geojson/all/hour

This is how my sample http Outbound component looks like:

<int:channel id="quakeinfo.channel">
  <int:queue capacity="10"/>
 </int:channel>

 <int:channel id="quakeinfotrigger.channel"></int:channel> 

 <int-http:outbound-gateway id="quakerHttpGateway"
     request-channel="quakeinfotrigger.channel"
     url="http://earthquake.usgs.gov/earthquakes/feed/geojson/all/hour"
     http-method="GET"
     expected-response-type="java.lang.String"
     charset="UTF-8"
     reply-timeout="5000"
     reply-channel="quakeinfo.channel">     
 </int-http:outbound-gateway>

Here the http outbound gateway waits for messages to come into the quakeinfotrigger channel, sends out a GET request to the "http://earthquake.usgs.gov/earthquakes/feed/geojson/all/hour" url, and places the response json string into the "quakeinfo.channel" channel

Testing this is easy:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("httpgateway.xml")
public class TestHttpOutboundGateway {
 
 @Autowired @Qualifier("quakeinfo.channel") PollableChannel quakeinfoChannel;
 @Autowired @Qualifier("quakeinfotrigger.channel") MessageChannel quakeinfoTriggerChannel;

 @Test
 public void testHttpOutbound() {
  quakeinfoTriggerChannel.send(MessageBuilder.withPayload("").build());
  Message<?> message = quakeinfoChannel.receive();
  assertThat(message.getPayload(), is(notNullValue()));
 }

}

What I am doing here is getting a reference to the channel which triggers the outbound gateway to send a message to the http endpoint and reference to another channel where the response from the http endpoint is placed. I am triggering the test flow by placing a dummy empty message in the trigger channel and then waiting on message to be available on the response channel and asserting on the contents.

This works cleanly, however my original intent was to write a poller which would trigger polling of this endpoint once every minute or so, to do this what I have to do is essentially place a dummy message into the "quakeinfotrigger.channel" channel every minute and this is easily accomplished using a Spring Integration "poller" and a bit of Spring Expression language:

<int:inbound-channel-adapter channel="quakeinfotrigger.channel" expression="''">
 <int:poller fixed-delay="60000"></int:poller>
</int:inbound-channel-adapter>

Here I have a Spring inbound-channel-adapter triggered attached to a poller , with the poller triggering an empty message every minute.

All this looks a little convoluted but works nicely - here is a gist with a working code

References:

1. Based on a question I had posed at the Spring forum http://forum.springsource.org/showthread.php?130711-Need-help-with-polling-to-a-json-based-HTTP-service


Friday, November 2, 2012

JSP Expression Language and .class

This is something which I faced when using JSP-EL this week, consider the following JSP-EL statement which displays content based on the type of an object:

<c:choose>
 <c:when test="${container.class.simpleName=='TableContainer'}">
  <table>...</table>
 </c:when>
 <c:when test="${container.class.simpleName=='ListContainer'}">
  <ul>...</ul>
 </c:when>
 <c:otherwise>
  <c:out value="Wrong container Type"/>
 </c:otherwise>
</c:choose>



However if this is run on Tomcat 7.0+, you are likely to see a very unhelpful exception, along these lines:

org.apache.jasper.JasperException: /WEB-INF/tags/formlayout/display/displaycontainer.tag (line: 11, column: 1) "${container.class.simpleName=='TableContainer'}" contains invalid expression(s): javax.el.ELException: Failed to parse the expression [${container.class.simpleName=='TableContainer'}]


The actual cause of the issue is the use of the .class above - The expression language parser in Tomcat 7+ by default performs a check to ensure that all identifiers conform to Java Language specifications, since class(which is actually a shortcut for getClass()) is a java Keyword it fails the check for the name of an identifier and hence the error -

There are multiple fixes possible for this issue, the first fix is simply to use .getClass() instead of just .class -


....
 <c:when test="${container.getClass().simpleName=='TableContainer'}">
...
</c:choose>


The second fix is a more sensible one, don't depend on the type of the class, instead introduce a method in the class to describe its type and avoiding Java identifier issue altogether:


....
<c:when test="${container.type=='table'}">
...


Another fix is to soften the identifier check in Tomcat 7+, this can be done using a system property set at Tomcat startup -

org.apache.el.parser. SKIP_IDENTIFIER_CHECK

and is described in more detail here - http://tomcat.apache.org/tomcat-7.0-doc/config/systemprops.html

Friday, October 26, 2012

Method Parameter Names and Spring

Continuing on the previous blog entry about Constructor and method parameters and Java not retaining the parameter names at runtime - the previous entry was about constructor not retaining the parameter names and the implication of this for Contructor injections in Spring, here I will cover a few more scenarios where parameter names not being retained has implications with Spring:

1. Consider Spring MVC Controller method with a parameter to bind to a request parameter which is passed in:

@RequestMapping(value="/members/find")
 public String getMembersByName(@RequestParam String name){
  ...
  return "list";
 }

Here the parameter "name" has a @RequestParam annotation associated with it, which is in an indication to Spring MVC to bind a request parameter "name" to this method parameter.

Since the parameter name is not retained at runtime, it is likely that an exception will be thrown by Spring:

Request processing failed; nested exception is java.lang.IllegalArgumentException: Name for argument type [java.lang.String] not available, and parameter name i
nformation not found in class file either.

The fix here is simple, to either compile with debug options on which will retain the parameter names at runtime OR a better one is to simply indicate what the expected request parameter name is, as an argument to the @RequestParam annotation:

@RequestMapping(value="/members/find")
public String getMembersByName(@RequestParam("name") String name){
 return "list";
}


2. Along the same lines consider another Spring MVC controller method, this time supporting URI template patterns:

@RequestMapping(value="/members/{id}", method=RequestMethod.GET)
public @ResponseBody Member get(@PathVariable Integer id){
 return this.memberDB.get(id);
}

Here the expectation is that if a request comes in with a uri of /members/20, then the id parameter will get bound with a value of 20, however since at runtime the parameter name of "id" is not retained, the fix like in the previous case is either to compile with debug on, or to explicitly mention in the @PathVariable annotation what the expected pattern name is:

@RequestMapping(value="/members/{id}", method=RequestMethod.GET)
public @ResponseBody Member get(@PathVariable("id") Integer id){

3. A third example is with caching support in Spring with @Cacheable annotation. Consider a sample method annotated with @Cacheable:

@Cacheable(value="default", key="#param1.concat('-').concat(#param2)")
public String cachedMethod(String param1, String param2){
    return "" + new Random().nextInt();
}

Here the key is a Spring-EL expression, which instructs the keygenerator to generate the key by combining the argument of the first parameter of name param1 with argument to the second parameter with name param2. However the problem like before is that these names are not available at runtime.

One of the fixes, as before is to compile with debug symbols turned on. A second fix is to use placeholders to stand in for parameter index - a0 OR p0 for first parameter, a1 OR p1 for second parameter and so on, this way the @Cacheable key will look like this:
@Cacheable(value="default", key="#p0.concat('-').concat(#p1)")
public String cachedMethod(String param1, String param2){
    return "" + new Random().nextInt();
}



So in conclusion, a safe way to use Spring features that depend on method parameter names is to compile with debug on(-g or -g:var option of javac) or by explicitly passing in meta information that indicates what the parameter names are at runtime.

Sunday, October 21, 2012

Spring Constructor Injection and parameter names

At runtime, java classes do not retain the name of the constructor or method parameters, unless classes are compiled with debug options on. This has some interesting implications for Spring Constructor Injection:

Consider the following simple class:

package dbg;
public class Person {

 private final String first;
 private final String last;
 private final Address address;

 public Person(String first, String last, Address address){
  this.first = first;
  this.last = last;
  this.address = address;
 }

 public String getFirst() {
  return first;
 }

 public String getLast() {
  return last;
 }

 public Address getAddress() {
  return address;
 }
}

and a sample Spring bean configuration xml file:

<bean name="address1" class="dbg.Address" p:street1="street1" p:street2="street1" p:state="state1"/>
 <bean name="person1" class="dbg.Person" c:address-ref="address1" c:last="Last1" c:first="First1"  ></bean>
 <bean name="person2" class="dbg.Person" c:first="First2" c:address-ref="address1" c:last="Last2"   ></bean>

Here I am using the c namespace for constructor injection. This fails with the exception that the argument types are ambiguous - this is because the first argument is a String and since its runtime representation does not have the argument name present, Spring cannot determine if it should be substituted for the first name or last.

There are a couple of fixes possible for this scenario:

1. To use index based constructor injection, the drawback though is that it is very verbose:
<bean name="person1" class="dbg.Person" >
  <constructor-arg value="First1"></constructor-arg>
  <constructor-arg value="Last1"></constructor-arg>
  <constructor-arg ref="address1"></constructor-arg>
 </bean>
 <bean name="person2" class="dbg.Person" >
  <constructor-arg value="First2"></constructor-arg>
  <constructor-arg value="Last2"></constructor-arg>
  <constructor-arg ref="address1"></constructor-arg>
 </bean>


2. To compile with debug symbols on, this can be done by passing a -g or -g:var flag to the java compiler - this will ensure that the parameter names are preserved in the class file and the original concise bean configuration with c namespace will work.


3. A neat fix is to annotate the constructor with @ConstructorProperties which basically provides the argument names to Spring:

public class Person {

 private final String first;
 private final String last;
 private final Address address;

 @ConstructorProperties({"first","last","address"})
 public Person(String first, String last, Address address){
  this.first = first;
  this.last = last;
  this.address = address;
 }

This works with or without debug options turned on.

4. Probably the best fix of all is to simply use @Configuration to define the beans:
@Configuration
public static class TestConfiguration{
 
 @Bean
 public Address address1(){
  return new Address();
 }
 @Bean
 public Person person1(){
  return new Person("First1", "Last1", address1());
 }
 @Bean
 public Person person2(){
  return new Person("First2", "Last2", address1());
 }
 
}


Saturday, October 13, 2012

Spring Collection Merging

Spring collection merging is a feature that I first came across as an answer to a StackOverflow question

It is a way of creating a base collection (list, set, map or properties) and modifying this base collection in other beans, best explained using an example -

Consider a Person class with a field holding a list of addresses:

public class Person {
 private List<Address> addresses;
..
}

Assume that all Person instances have a common set of addresses, which can be specified using an abstract person bean this way:

<bean name="basePerson" class="Person" abstract="true">
 <property name="addresses">
  <list>
   <bean class="Address" p:street="Street1" p:state="State1" p:zip="001"></bean>
   <bean class="Address" p:street="Street2" p:state="State2" p:zip="002"></bean>
   <bean class="Address" p:street="Street3" p:state="State3" p:zip="003"></bean>
  </list>
 </property>
</bean>

Now, Person bean instances with addresses in addition to the addresses from the basePerson can be specified using Collection Merging feature this way - note the "merge=true" attribute of list:

<bean name="person1" class="Person" parent="basePerson">
 <property name="addresses">
  <list merge="true">
   <bean class="Address" p:street="Street4" p:state="State4" p:zip="004"></bean>
  </list>
 </property>
</bean>

Collection merging also works with <set/>, <map/> and <props/>

With Spring 3.1 and higher, a simpler option though could be simply to use @Configuraion and @Bean options, as then the merging can be directly handled with Java code, for eg, an equivalent @Configuration for the above xml bean configuration:

@Configuration
public class CollectionConfig{
 
 private List<Address> baseAddresses(){
  return Lists.newArrayList(new Address("Street1", "State1", "001"), new Address("Street2", "State2", "002"), new Address("Street3", "State3", "003"));
 }
 
 
 @Bean
 public Person person1(){
  Person person1 = new Person();
  person1.setAddresses(baseAddresses());
  person1.getAddresses().add(new Address("Street4", "State4", "004"));
  return person1;
 }
}


Saturday, October 6, 2012

Spring Autowire - Subtle behavior difference in xml and @Configuration

There is a subtle difference in the behavior of how autowire behaves with new @Configuration style of Spring bean configuration and using an xml file:

Consider a service into which a Dao is wired in:

public class SampleService {
 @Autowired private SampleDao sampleDao;
 
 public Sample getSample(int id){
  return this.sampleDao.findOne(id);
 }
}

Using an xml, the bean configuration would have been defined this way:

<bean name="sampleDao" class="SampleDaoImpl"/>
 <bean name="sampleService" class="SampleService"/>

and using the new @Configuration style it is defined this way:

@Configuration
public class AnnotationConfig {
 @Bean
 public SampleDao sampleDao(){
  return new SampleDaoImpl();
 }
 
 @Bean
 public SampleService sampleService(){
  return new SampleService();
 }
}

Now consider a program which uses the @Configuration defined bean configuration:

public static void main(String[] args) {
  ApplicationContext ctx = new AnnotationConfigApplicationContext(AnnotationConfig.class);
  SampleService sampleService = ctx.getBean(SampleService.class);
  System.out.println(sampleService.getSample(10));
 }

and a similar one using xml bean configuration:
public static void main(String[] args) {
  ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("springconfig.xml");
  SampleService sampleService = ctx.getBean(SampleService.class);
  System.out.println(sampleService.getSample(10));
 }

The behavior is that the SampleDao will not get correctly autowired into the SampleService in the case of xml based bean configuration but works correctly for @Configuration based bean configuration.

The reason for the behavior difference is that in the @Configuration case the AutowiredAnnotationBeanPostProcessor responsible for autowiring the fields is registered automatically whereas with XML bean configuration it has to be done explicitly. So the fix is to include AutowiredAnnotationBeanPostProcessor, which can be done in a few different ways, one of which is using:

<context:annotation-config/>

Note: I have deliberately demonstrated this in a main method instead of a unit test - In a unit test with Spring test support, the AutowiredAnnotationBeanPostProcessor is automatically registered by the test context and this behavior difference will not be seen there.

Thursday, October 4, 2012

Spring MVC - static resource handling with / servlet-mapping

A servlet mapping of "/" registers a "default" servlet - if a request comes in which matches a mapping in the web.xml file then the request will be handled by that servlet, however if no servlet is found matching a specific request pattern then the request is handled by the "default" servelt.

The "default" servlet is also responsible for handling the requests to the static content in a web application.

A convention for Spring MVC based applications is to register the Spring MVC Front Controller called the DispatcherServlet with a servlet mapping of '/'

    <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:/META-INF/spring/web/webmvc-config.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>


    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

This enables Spring MVC to handle all the requests coming to the web application, except for cases where other specific mappings are available. A good example of a case where a specific mapping may be required is to configure the front controller for Apache CXF to accept webservice requests to /webservices servlet path:

 <servlet>
  <servlet-name>CXFServlet</servlet-name>
  <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
 </servlet>
 
 
 <servlet-mapping>
  <servlet-name>CXFServlet</servlet-name>
  <url-pattern>/webservices/*</url-pattern>
 </servlet-mapping>

Given that it is the "default" servlet which handles the request for the static resources like images, and the default servlet with Spring MVC is the DispatcherServlet, there are a few recommendations to serve out static content from Spring MVC based web applications:

1. Using mvc:resources -
For eg.
<mvc:resources mapping="/resources/**" location="/public-resources/"/>

This enables serving any static content whose location can be specified as a Spring Resource

2. Using mvc:default-servlet-handler:
 <mvc:default-servlet-handler />
This provides a way to serve out the static content from the root of the web application even though the Dispatcher Servlet is registered at /, the details of how Spring does this is available at the Spring documentation site here - in brief the responsibility is delegated to the containers default servlet.


Friday, September 28, 2012

Scala Iteration - step by 2*previous loop index

I had a basic Scala related question about how to replicate the following Java loop in Scala:

for (int i=1;i<100000;i=2*i){
    System.out.println(i);
}

I knew one way to go about doing this using a recursive loop this way:

def loopByTwiceBefore(from:Int, to:Int)(f:Int=>Unit):Unit = {
    if (from<to){
        f(from)
        loopByTwiceBefore(from*2, to)(f);
    }
}
loopByTwiceBefore(1, 100000)(println)

I asked this question in StackOverflow and immediately got back two better ways of doing this:

for (n <- Iterator.iterate(1)(2*).takeWhile(100000>)) println(n)

OR

Iterator.iterate(1)(_*2).takeWhile(_ < 100000) foreach {println(_)}

and the link to the Iterator companion object at the Scala API site for more information

Sunday, September 23, 2012

Spring Testing Support and Context caching

Spring provides a comprehensive support for unit and integration testing - through annotations to load up a Spring application context, integrate with unit testing frameworks like JUnit and TestNG. Since loading up a large application context for every test takes time, Spring intelligently caches the application context for a test suite - typically when we execute tests for a project, say through ant or maven, a suite is created encompassing all the tests in the project.

There are a few points to note with caching which is what I intend to cover here, this is not likely to be comprehensive but is based on some situations which I have encountered:

1. Caching is based on the locations of Spring application context files

Consider a sample Spring configuration file:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:p="http://www.springframework.org/schema/p"
 xsi:schemaLocation="
  http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
 
 <bean id="user1"  class="org.bk.lmt.domain.TaskUser" p:username="user1" p:fullname="testUser1" />
 <bean name="user2" class="org.bk.lmt.domain.TaskUser" p:username="user2" p:fullname="testUser" />
 
 <bean class="org.bk.contextcaching.DelayBean"/>
 
</beans>


And a sample test to load up this context file and verify something.:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "contexttest.xml" })
public class Test1 {
 @Autowired Map<String, TaskUser> usersMap;

 @Test
 public void testGetAUser() {
  TaskUser user = usersMap.get("user1");
  assertThat(user.getFullname(), is("testUser1"));
 }
}

I have deliberately added in an additional bean(DelayBean) which takes about 2 seconds to instantiate, to simulate Spring Application Contexts which are slow to load up.

If I now run a small test suite with two tests, both using the same application context, the behavior is that the first test takes about 2 seconds to run through, but the second test runs through quickly because of context caching.

If there were a third test using a different application context, this test would again take time to run through as the new application context has to be loaded up:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "contexttest2.xml" })
public class Test3 {
...
}



2. Caching of application contexts respects the active profile under which the test is run - essentially the profile is also part of the internal key that Spring uses to cache the context, so if two tests use the exact same application context, but different profiles are active for each of the tests, then the cached application context will not be used for the second test:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "contexttest.xml" })
@ActiveProfiles("dev1")
public class Test1 {
....


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "contexttest.xml" })
@ActiveProfiles("dev2")
public class Test2 {
....




3. Caching of application context applies even with the new @Configuration style of defining a application context and using it in tests:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={TestConfiguration.class})
public class Test1 {
...


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={TestConfiguration.class})
public class Test2 {
....



One implication of caching is that if a test class modifies the state of a bean, then another class in the test suite which uses the cached application context will end up seeing the modified bean instead of the bean the way it was defined in the application context:

For eg. consider two tests, both of which modify a bean in the context, but are asserting on a state the way it is defined in the application context - Here one of the tests would end up failing(based on the order in which Junit executes the tests):

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={TestConfiguration.class})
public class Test1 {
 @Autowired Map<String, TaskUser> usersMap;


 @Test
 public void testGetAUser1() {
  TaskUser user = usersMap.get("user1");
  assertThat(user.getFullname(), is("testUser1"));
  user.setFullname("New Name");
 }
 
 @Test
 public void testGetAUser2() {
  TaskUser user = usersMap.get("user1");
  assertThat(user.getFullname(), is("testUser1"));
  user.setFullname("New Name");
 }
}


The fix is to instruct Spring test support that the application context is now dirty and needs to be reloaded for other tests, and this is done with @DirtiesContext annotation which can specified at the test class level or test method level.

@Test
@DirtiesContext
public void testGetAUser2() {
...



Tuesday, September 11, 2012

Java Annotations - Retention

Consider a Java annotation:


public @interface AnAnnotaton {

}

A class with this annotation applied on it:

@AnAnnotaton
class AnAnnotatedClass{
 
}

And a test which checks if this annotation is present on a class:

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;

import java.lang.annotation.Annotation;
import org.junit.Test;

public class AnAnnotationTest {
 
 
 @Test
 public void testAnAnnotation() throws Exception {
  AnAnnotatedClass anAnnotatedClass = new AnAnnotatedClass();
  Annotation[] annotationsOnClass = anAnnotatedClass.getClass().getAnnotations();
  assertThat(annotationsOnClass.length, is(1));
 }

}

Sounds reasonable right, one would expect the above test to pass since the class does have an annotation of AnAnnotation on it.

But, this test fails, and the reason is...


a missing meta annotation(@Retention) on the annotation which indicates how long the annotation is to be retained, if the annotation above is changed as follows, the test would work as expected.

@Retention(RetentionPolicy.RUNTIME)
public @interface AnAnnotaton {

}


So what does @Retention do - to quote from the Javadoc:


Indicates how long annotations with the annotated type are to be retained. If no Retention annotation is present on an annotation type declaration, the retention policy defaults to RetentionPolicy.CLASS

there are three different retention policies:
1. SOURCE - where the annotations are removed by the compiler
2. CLASS - Annotations are present in the bytecode, but are not present at runtime and hence not available when trying to reflectively determine if a class has the annotation.
3. RUNTIME - Annotations are retained in the byte code and is available at runtime and hence can be reflectively found on a class.

This is the reason why when the annotation definition was changed to include @Retention(RetentionPolicy.RUNTIME), the test now runs through.

Something basic, but easy to miss out.

Monday, September 3, 2012

Ways to wire dependencies for an object outside of a Spring Container

There are a few interesting ways of setting the properties and dependencies of an object instantiated outside of a Spring container.

Use Cases

To start with, why would we need to do inject in dependencies outside of a Spring container - I am aware of three use cases where I have instantiated objects outside of the Spring container and needed to inject in dependencies.

Consider first the case of a series of tasks executed using a Spring TaskExecutor, the tasks highlighted below are instantiated outside of a Spring container:

List<Callable<ReportPart>> tasks = new ArrayList<Callable<ReportPart>>();
        List<ReportRequestPart> reportRequestParts = reportRequest.getRequestParts();
        for (ReportRequestPart reportRequestPart : reportRequestParts) {
            tasks.add(new ReportPartRequestCallable(reportRequestPart, reportPartGenerator));
        }

        List<Future<ReportPart>> responseForReportPartList;
        List<ReportPart> reportParts = new ArrayList<ReportPart>();
        try {
            responseForReportPartList = executors.invokeAll(tasks);
            for (Future<ReportPart> reportPartFuture : responseForReportPartList) {
                reportParts.add(reportPartFuture.get());
            }

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new RuntimeException(e);
        }

public class ReportPartRequestCallable implements Callable<ReportPart> {
 private final ReportRequestPart reportRequestPart;
 private final ReportPartGenerator reportPartGenerator;

 public ReportPartRequestCallable(ReportRequestPart reportRequestPart, ReportPartGenerator reportPartGenerator) {
     this.reportRequestPart = reportRequestPart;
     this.reportPartGenerator = reportPartGenerator;
    }

 @Override
    public ReportPart call() {
    return this.reportPartGenerator.generateReportPart(reportRequestPart);
    } 
}

The second use case is with ActiveRecord pattern say with the samples that come with Spring Roo, consider the following method where a Pet class needs to persist itself and needs an entity manager to do this:
@Transactional
    public void Pet.persist() {
        if (this.entityManager == null) this.entityManager = entityManager();
        this.entityManager.persist(this);
    }

The third use case is for a tag library which is instantiated by a web container, but needs some dependencies from Spring.


Solutions

1. The first approach is actually simple, to provide the dependencies at the point of object instantiation, through constructors or setters. This is what I have used with the first use case where the task has two dependencies which are being provided by the service instantiating the task:

tasks.add(new ReportPartRequestCallable(reportRequestPart, reportPartGenerator));


2. The second approach is a to create a factory that is aware of the Spring container, declaring the beans that are required with a prototype scope within the container and getting the beans by a getBeans method of the application context,

Declaring the bean as a prototype scoped bean:
    <bean name="reportPartRequestCallable" class="org.bk.sisample.taskexecutor.ReportPartRequestCallable" scope="prototype">
     <property name="reportPartGenerator" ref="reportPartGenerator"></property>
    </bean>
    
    <bean name="reportPartRequestCallableFactory" class="org.bk.sisample.taskexecutor.ReportPartRequestCallableFactory"/>

and the factory serving out the bean:
public class ReportPartRequestCallableFactory implements ApplicationContextAware{
 private ApplicationContext applicationContext;

 @Override
 public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
  this.applicationContext = applicationContext;
 }
 
 public ReportPartRequestCallable getReportPartRequestCallable(){
  return this.applicationContext.getBean("reportPartRequestCallable", ReportPartRequestCallable.class);
 }
}


3.  The third approach is a variation of the above approach is to instantiate the bean and then inject dependencies using AutoWireCapableBeanFactory.autowireBean(instance), this way:
public class ReportPartRequestCallableFactory implements ApplicationContextAware{
 private GenericApplicationContext applicationContext;

 @Override
 public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
  this.applicationContext = (GenericApplicationContext)applicationContext;
 }
 
 public ReportPartRequestCallable getReportPartRequestCallable(){
  ReportPartRequestCallable reportPartRequestCallable = new ReportPartRequestCallable();
  applicationContext.getBeanFactory().autowireBean(reportPartRequestCallable);
  return reportPartRequestCallable;
 }
}



4.  The fourth approach is using @Configurable, the catch though is that it requires AspectJ to work. Spring essentially enhances the constructor of the class to inject in the dependencies along the lines of what is being explicitly done in the third approach above:

import org.springframework.beans.factory.annotation.Configurable;

@Configurable("reportPartRequestCallable")
public class ReportPartRequestCallable implements Callable<ReportPart> {
    private ReportRequestPart reportRequestPart;
    @Autowired private ReportPartGenerator reportPartGenerator;

    public ReportPartRequestCallable() {
    }

    @Override
    public ReportPart call() {
       return this.reportPartGenerator.generateReportPart(reportRequestPart);
    }

    public void setReportRequestPart(ReportRequestPart reportRequestPart) {
        this.reportRequestPart = reportRequestPart;
    }

    public void setReportPartGenerator(ReportPartGenerator reportPartGenerator) {
        this.reportPartGenerator = reportPartGenerator;
    }
}

The following is also required to configure the Aspect responsible for @Configurable weaving:
<context:spring-configured/>

With these changes in place, any dependency for a class annotated with @Configurable is handled by Spring even if the construction is done completely outside of the container:

    @Override
    public Report generateReport(ReportRequest reportRequest) {
        List<Callable<ReportPart>> tasks = new ArrayList<Callable<ReportPart>>();
        List<ReportRequestPart> reportRequestParts = reportRequest.getRequestParts();
        for (ReportRequestPart reportRequestPart : reportRequestParts) {
            ReportPartRequestCallable reportPartRequestCallable = new ReportPartRequestCallable(); 
            reportPartRequestCallable.setReportRequestPart(reportRequestPart);
            tasks.add(reportPartRequestCallable);
        }
    .......


Conclusion
All of the above approaches are effective with injecting in dependencies in objects which are instantiated outside of a container. I personally prefer to use Approach 4 (using @Configurable) in cases where AspectJ support is available, else I would go with Approach 2(hiding behind a factory and using a prototype bean).

Saturday, August 25, 2012

Spring Scoped Proxy

Consider two Spring beans defined this way:

@Component
class SingletonScopedBean{
 @Autowired private PrototypeScopedBean prototypeScopedBean;
 
 public String getState(){
  return this.prototypeScopedBean.getState();
 }
}

@Component
@Scope(value="prototype")
class PrototypeScopedBean{
 private final String state;
 
 public PrototypeScopedBean(){
  this.state = UUID.randomUUID().toString();
 }

 public String getState() {
  return state;
 }
}

Here a prototype scoped bean is injected into a Singleton scoped bean.

Now, consider this test using these beans:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class ScopedProxyTest {
 
 @Autowired private SingletonScopedBean singletonScopedBean;
 
 @Test
 public void testScopedProxy() {
  assertThat(singletonScopedBean.getState(), not(equalTo(singletonScopedBean.getState())));
 }
 
 @Configuration
 @ComponentScan("org.bk.samples.scopedproxy")
 public static class SpringContext{}

}

The point to note is that there is only 1 instance of PrototypeScopedBean that is created here - and that 1 instance is injected into the SingletonScopedBean, so the above test which actually expects a new instance of PrototypeScopedBean with each invocation of getState() method will fail.

If a new instance is desired with every request to PrototypeScopedBean (and in general if a bean with longer scope has a bean with shorter scope as a dependency, and the shorter scope needs to be respected), then there are a few solutions:

1. Lookup method injection - which can be read about here
2. A better solution is using Scoped proxies -

A scoped proxy can be specified this way using @Configuration:
@Component
@Scope(value="prototype", proxyMode=ScopedProxyMode.TARGET_CLASS)
class PrototypeScopedBean{
 private final String state;
 
 public PrototypeScopedBean(){
  this.state = UUID.randomUUID().toString();
 }

 public String getState() {
  return state;
 }

}

With this change, the bean injected into the SingletonScopedBean is not the PrototypeScopedBean itself, but a proxy to the bean (created using CGLIB or Dynamic proxies) and this proxy understands the scope and returns instances based on the requirements of the scope, the test should now work as expected.

Saturday, August 18, 2012

@ContextConfiguration defaults

Spring @ContextConfiguration is a way to specify the Application Context for a test.

The location of a xml based test application context can be specified using the locations attribute:
@ContextConfiguration(locations={"test-context.xml"})

and if @Configuration is used as the context, then a classes attibute can be specified:

@ContextConfiguration(classes={TestConfiguration.class})

There are intelligent defaults for these attributes though and that is what I wanted to highlight in this post.

If the locations or the classes attribute is not specified, the default behavior is to first look for a xml configuration with a name as the test class name - "context.xml" file

For eg. if I have a Test class this way:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class TestSpringCache {


The location of the configuration that will be tried first is "TestSpringCache-context.xml"

If a context is not found at this location, then a @Configuration default is looked for by scanning all static inner classes annotated with @Configuration of the test class. So if I had the following:


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class TestSpringCache {
   ...
 
 @Configuration
 @EnableCaching
 @ComponentScan("org.bk.samples.cache")
 public static class TestConfiguration{
 .. 


the inner class TestConfiguration would be used as the source of the Application context.

The default behaviour can be changed by supplying a loader attribute to the @ContextConfiguration, say for eg, if I want to default to @Configuration with its defaults, it can done this way:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader=AnnotationConfigContextLoader.class)
public class TestSpringCache {
..

So to conclude, the defaults provided by @Configuration are a great way to make the tests a little more concise!

Friday, August 10, 2012

Spring @Configuration and FactoryBean

Consider a FactoryBean  for defining a cache using a Spring configuration file:

 <cache:annotation-driven />
 <context:component-scan base-package="org.bk.samples.cachexml"></context:component-scan>
 
 <bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">
  <property name="caches">
   <set>
    <ref bean="defaultCache"/>
   </set>
  </property>
 </bean>
 
 <bean name="defaultCache" class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean">
  <property name="name" value="default"/>
 </bean>

The factory bean ConcurrentMapCacheFactoryBean is a bean which is in turn responsible for creating a Cache bean.

My first attempt at translating this setup to a @Configuration style was the following:


@Bean
public SimpleCacheManager cacheManager(){
 SimpleCacheManager cacheManager = new SimpleCacheManager();
 List<Cache> caches = new ArrayList<Cache>();
 ConcurrentMapCacheFactoryBean cacheFactoryBean = new ConcurrentMapCacheFactoryBean();
 cacheFactoryBean.setName("default");
 caches.add(cacheFactoryBean.getObject());
 cacheManager.setCaches(caches );
 return cacheManager;
}

This did not work however, the reason is that here I have bypassed some Spring bean lifecycle mechanisms altogether. It turns out that ConcurrentMapCacheFactoryBean also implements the InitializingBean interface and does a eager initialization of the cache in the "afterPropertiesSet" method of InitializingBean. Now by directly calling factoryBean.getObject() , I was completely bypassing the afterPropertiesSet method.

There are two possible solutions:
1. Define the FactoryBean the same way it is defined in the XML:
@Bean
public SimpleCacheManager cacheManager(){
 SimpleCacheManager cacheManager = new SimpleCacheManager();
 List<Cache> caches = new ArrayList<Cache>();
 caches.add(cacheBean().getObject());
 cacheManager.setCaches(caches );
 return cacheManager;
}

@Bean
public ConcurrentMapCacheFactoryBean cacheBean(){
 ConcurrentMapCacheFactoryBean cacheFactoryBean = new ConcurrentMapCacheFactoryBean();
 cacheFactoryBean.setName("default");
 return cacheFactoryBean;
}
In this case, there is an explicit FactoryBean being returned from a @Bean method, and Spring will take care of calling the lifecycle methods on this bean.

2. Replicate the behavior in the relevant lifecycle methods, in this specific instance I know that the FactoryBean instantiates the ConcurrentMapCache in the afterPropertiesSet method, I can replicate this behavior directly this way:

@Bean
public SimpleCacheManager cacheManager(){
 SimpleCacheManager cacheManager = new SimpleCacheManager();
 List<Cache> caches = new ArrayList<Cache>();
 caches.add(cacheBean());
 cacheManager.setCaches(caches );
 return cacheManager;
}

@Bean
public Cache  cacheBean(){
 Cache  cache = new ConcurrentMapCache("default");
 return cache;
}

Something to keep in mind when translating a FactoryBean from xml to @Configuration.

Note:
A working one page test as a gist is available here:

Tuesday, August 7, 2012

Mergesort using Fork/Join Framework

The objective of this entry is to show a simple example of a Fork/Join RecursiveAction, not to delve too much into the possible optimizations to merge sort or the relative advantages of using Fork/Join Pool over the existing Java 6 based implementations like ExecutorService.

The following is a typical implementation of a Top Down Merge sort algorithm using Java:

import java.lang.reflect.Array;

public class MergeSort {
 public static <T extends Comparable<? super T>> void sort(T[] a) {
  @SuppressWarnings("unchecked")
  T[] helper = (T[])Array.newInstance(a[0].getClass() , a.length);
  mergesort(a, helper, 0, a.length-1);
 }
 
 private static <T extends Comparable<? super T>> void mergesort(T[] a, T[] helper, int lo, int hi){
  if (lo>=hi) return;
  int mid = lo + (hi-lo)/2;
  mergesort(a, helper, lo, mid);
  mergesort(a, helper, mid+1, hi);
  merge(a, helper, lo, mid, hi);  
 }

 private static <T extends Comparable<? super T>> void merge(T[] a, T[] helper, int lo, int mid, int hi){
  for (int i=lo;i<=hi;i++){
   helper[i]=a[i];
  }
  int i=lo,j=mid+1;
  for(int k=lo;k<=hi;k++){
   if (i>mid){
    a[k]=helper[j++];
   }else if (j>hi){
    a[k]=helper[i++];
   }else if(isLess(helper[i], helper[j])){
    a[k]=helper[i++];
   }else{
    a[k]=helper[j++];
   }
  }
 }

 private static <T extends Comparable<? super T>> boolean isLess(T a, T b) {
  return a.compareTo(b) < 0;
 }
}

To quickly describe the algorithm -
The following steps are performed recursively:

  1.  The input data is divided into 2 halves
  2.  Each half is sorted
  3. The sorted data is then merged

Merge sort is a canonical example for an implementation using Java Fork/Join pool, and the following is a blind implementation of Merge sort using the Fork/Join framework:

The  recursive task in Merge sort can be succinctly expressed as an implementation of RecursiveAction -


 private static class MergeSortTask<T extends Comparable<? super T>> extends RecursiveAction{
  private static final long serialVersionUID = -749935388568367268L;
  private final T[] a;
  private final T[] helper;
  private final int lo;
  private final int hi;
  
  public MergeSortTask(T[] a, T[] helper, int lo, int hi){
   this.a = a;
   this.helper = helper;
   this.lo = lo;
   this.hi = hi;
  }
  @Override
  protected void compute() {
   if (lo>=hi) return;
   int mid = lo + (hi-lo)/2;
   MergeSortTask<T> left = new MergeSortTask<>(a, helper, lo, mid);
   MergeSortTask<T> right = new MergeSortTask<>(a, helper, mid+1, hi);
   invokeAll(left, right);
   merge(this.a, this.helper, this.lo, mid, this.hi);
   
   
  }
  private void merge(T[] a, T[] helper, int lo, int mid, int hi){
   for (int i=lo;i<=hi;i++){
    helper[i]=a[i];
   }
   int i=lo,j=mid+1;
   for(int k=lo;k<=hi;k++){
    if (i>mid){
     a[k]=helper[j++];
    }else if (j>hi){
     a[k]=helper[i++];
    }else if(isLess(helper[i], helper[j])){
     a[k]=helper[i++];
    }else{
     a[k]=helper[j++];
    }
   }
  }
  private boolean isLess(T a, T b) {
   return a.compareTo(b) < 0;
  }
 }

MergeSortTask above implements a compute method, which takes in a array of values, split it up into two parts, creates a MergeSortTask out of each of the parts and forks off two more tasks(hence it is called RecursiveAction!). The specific API used here to spawn of the task is invokeAll which returns only when the submitted subtasks are marked as completed. So once the left and right subtasks return the result is merged in a merge routine.

Given this the only work left is to use a ForkJoinPool to submit this task. ForkJoinPool is analogous to the ExecutorService used for distributing tasks in a threadpool, the difference to quote the ForkJoinPool's API docs:

A ForkJoinPool differs from other kinds of ExecutorService mainly by virtue of employing work-stealing: all threads in the pool attempt to find and execute subtasks created by other active tasks (eventually blocking waiting for work if none exist)

This is how the task of submitting the task to the Fork/Join Pool looks like:

 public static <T extends Comparable<? super T>> void sort(T[] a) {
  @SuppressWarnings("unchecked")
  T[] helper = (T[])Array.newInstance(a[0].getClass() , a.length);
  ForkJoinPool forkJoinPool = new ForkJoinPool(10);
  forkJoinPool.invoke(new MergeSortTask<T>(a, helper, 0, a.length-1));
 }

A complete sample is also available here: https://github.com/bijukunjummen/algos/blob/master/src/main/java/org/bk/algo/sort/algo04/merge/MergeSortForkJoin.java

Sunday, August 5, 2012

Accept header vs Content-Type Header

I occasionally get confused between the Accept and the Content-Type Headers and this post is a way of clarifying the difference for myself. Let me summarize the difference to start with and then go onto a little bit of detail -
Accept and Content-type are both headers sent from a client(browser say) to a service.
Accept header is a way for a client to specify the media type of the response content it is expecting and Content-type is a way to specify the media type of request being sent from the client to the server.

To expand on this:

Accept header to quote the HTTP/1.1 RFC:

The Accept request-header field can be used to specify certain media types which are acceptable for the response. 
An example of an Accept header for a json request to a REST based service will be the following:
Accept: application/json

This is saying the response expected is a json content.

Content-Type to quote from the HTTP/1.1 RFC:

The Content-Type entity-header field indicates the media type of the entity-body sent to the recipient or, in the case of the HEAD method, the media type that would have been sent had the request been a GET.
As a sample if a json is being sent from a browser to a server, then the content type header would look like this:
Content-Type: application/json

Friday, July 27, 2012

Spring Integration - Session 2 - More Hello Worlds

This is a follow up to Spring Integration Session 1

The first session was a simple Hello World application using Spring Integration. I want to take it a little further by considering a few more scenarios around it

So the first change to the Hello World application is to add in a Gateway component. To quickly revisit the earlier test program:

package org.bk.si.helloworld.hw1;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.integration.Message;
import org.springframework.integration.MessageChannel;
import org.springframework.integration.message.GenericMessage;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("helloworld.xml")
public class HelloWorldTest {
 
 @Autowired
 @Qualifier("messageChannel")
 MessageChannel messageChannel;

 @Test
 public void testHelloWorld() {
  Message<String> helloWorld = new GenericMessage<String>("Hello World");
  messageChannel.send(helloWorld);
 }
}



In the lines highlighted above, the test is dependent on a Spring Integration specific component - a Message Channel, and in the test an explicit Spring Integration Message is constructed and sent to the Message Channel. There is a little too much coupling with Spring Integration which is the Messaging System here.

A Gateway component provides a facade to the messaging system, shielding the user application(in this case the Unit test) from the details of Messaging System - the messaging channel, Message and explicit sending of a message.

An example first to illustrate how the test will look with a Gateway component in place:

package org.bk.si.helloworld.hw2;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("helloworld.xml")
public class HelloWorldTest {

 @Autowired Greeter greeter;

 @Test
 public void testHelloWorld(){
   this.greeter.sendGreeting("Hello World");
 }
}


The Greeter interface above is the Gateway component. Now that this component has been introduced there is no dependency to Spring Integration in this test - there is no mention of Message, Message Channel in the code at all.

The Gateway component is also a very simple Java Interface defined this way:

package org.bk.si.helloworld.hw2;

public interface Greeter {
 public void sendGreeting(String message);
}

So now the question is who takes care of creating the messaging and sending the message to a message channel - it is through Spring Integration configuration:

<?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:int="http://www.springframework.org/schema/integration"
 xmlns:int-stream="http://www.springframework.org/schema/integration/stream"
 xsi:schemaLocation="http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration-2.1.xsd
  http://www.springframework.org/schema/integration/stream http://www.springframework.org/schema/integration/stream/spring-integration-stream-2.1.xsd
  http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">


 <int:channel id="messagesChannel"></int:channel>
 
 <int:gateway service-interface="org.bk.si.helloworld.hw2.Greeter" default-request-channel="messagesChannel"></int:gateway>
 
 <int-stream:stdout-channel-adapter channel="messagesChannel" append-newline="true"/>
 

</beans>


The highlighted line above creates the Gateway component out of the Greeter interface, a proxy is created in the background which handles everything that was being done explicitly earlier - creating the messaging and sending the message to the message channel.


Now to add a little more complexity to the Hello World sample:

Consider the following test:
package org.bk.si.helloworld.hw3;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("helloworld.xml")
public class HelloWorldTest {

 @Autowired Greeter greeter;

 @Test
 public void testHelloWorld(){
  System.out.println("Started..");
  long start = System.nanoTime();
  for (int i=0;i<10;i++){
   this.greeter.sendMessage(String.format("Hello World %d",i));
  }
  System.out.println("Completed..");
  System.out.println(String.format("Took %f ms", (System.nanoTime()-start)/10e6));
 }
}

This is same as the previous unit test, except that in this case the "Hello World" message is being dispatched 10 times. The supporting Spring Integration configuration file is the following:

<?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:int="http://www.springframework.org/schema/integration"
 xmlns:int-stream="http://www.springframework.org/schema/integration/stream"
 xsi:schemaLocation="http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration-2.1.xsd
  http://www.springframework.org/schema/integration/stream http://www.springframework.org/schema/integration/stream/spring-integration-stream-2.1.xsd
  http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">


 <int:publish-subscribe-channel id="messagesChannel"/>
 <int:gateway service-interface="org.bk.si.helloworld.hw3.Greeter" default-request-channel="messagesChannel"></int:gateway>
 
 
 <int-stream:stderr-channel-adapter channel="messagesChannel" append-newline="true"/>
 <int-stream:stdout-channel-adapter channel="messagesChannel" append-newline="true"/>
 
</beans>


If I run this test now, the output is along these lines:


The lines in red are being printed to syserr and in black are being printed to sysout.

So the question is why are some of them going to sysout and some of them going to syserr and why not to both?

The answer is because of the type of channel - "messagesChannel" above is a "Direct Channel" in the Spring Integration terminology and has "Point to point" semantics. The point-to-point semantics basically means that when a message comes into the Messaging Channel, only 1 receiver gets the message - so in this case either the standard out adapter OR the standard err adapter ends up printing the message that is coming into the message channel.

So to print to both adapters, the fix is to simply change the semantics of the channel - instead of a Point to Point channel, make it a Publish-Subscribe channel, which is a channel broadcasting out a message to multiple receivers. The change is very simple using Spring Integration:

<?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:int="http://www.springframework.org/schema/integration"
 xmlns:int-stream="http://www.springframework.org/schema/integration/stream"
 xsi:schemaLocation="http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration-2.1.xsd
  http://www.springframework.org/schema/integration/stream http://www.springframework.org/schema/integration/stream/spring-integration-stream-2.1.xsd
  http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">


 <int:publish-subscribe-channel id="messagesChannel"/>
 <int:gateway service-interface="org.bk.si.helloworld.hw3.Greeter" default-request-channel="messagesChannel"></int:gateway>
 
 
 <int-stream:stderr-channel-adapter channel="messagesChannel" append-newline="true"/>
 <int-stream:stdout-channel-adapter channel="messagesChannel" append-newline="true"/>
 
</beans>


The output now will be the messages being printed to BOTH sysout and syserr

So this completes the introduction to a Gateway component, Direct Channel and Publish Subscribe channel.








Thursday, July 26, 2012

EclipseLink MOXy as a JAXB provider

EclipseLink MOXy is a JAXB provider and is a compelling alternative to the default JAXB provider built into JDK.

First a simple test to marshal a Java object to XML:

This is the model:

@XmlRootElement(name="MemberDetailsRequest", namespace="http://bk.org/memberservice/")
@XmlAccessorType(XmlAccessType.FIELD)
public class MemberDetailsRequest {

 public MemberDetailsRequest() {
 }

 public MemberDetailsRequest(Long id) {
  this.id = id;
 }

 private Long id;

 public Long getId() {
  return id;
 }

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

and the test for marshalling:
package org.bk.memberservice.binding;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.is;

import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;

import org.bk.memberservice.message.MemberDetailsRequest;
import org.junit.Test;

public class TestJaxbRequestBinding {

 @Test
 public void testJaxbBinding() throws Exception{
  JAXBContext jaxbContext = JAXBContext.newInstance(MemberDetailsRequest.class);
  assertThat((jaxbContext instanceof org.eclipse.persistence.jaxb.JAXBContext), is(true));
  Marshaller marshaller = jaxbContext.createMarshaller();
  
  MemberDetailsRequest memberDetailsRequest = new MemberDetailsRequest();
  memberDetailsRequest.setId(1L);
  StringWriter writer = new StringWriter();
  
  marshaller.marshal(memberDetailsRequest, writer);
  String marshalledXml = writer.toString();
  assertThat(marshalledXml, containsString("MemberDetailsRequest"));
 }
}


The highlighted line checks to make sure that MOXy's JAXBContext is the one created.

So to use MOXy as the JAXB provider, first step is to get the jar files,

I had a little difficulty finding the MOXy jars to be used in a Maven pom file, this is what worked for me:

<repository>
            <id>EclipseLink Repo</id>
            <url>http://download.eclipse.org/rt/eclipselink/maven.repo</url>
            <name>EclipseLink Repo</name>
        </repository>

  <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>org.eclipse.persistence.moxy</artifactId>
            <version>2.4.0</version>
        </dependency>

The next step is to instruct to set MOXy as the JAXB provider. This is done by placing a jaxb.properties along with any of the JAXB model classes. So in this case, I have placed a jaxb.properties into my package holding MemberDetailsRequest class, and the contents are the following:
javax.xml.bind.context.factory = org.eclipse.persistence.jaxb.JAXBContextFactory

and that's it!

Reference:
Blaise Dougan's Blog: http://blog.bdoughan.com/ and his very enthusiastic participation in Stack Overflow

Wednesday, July 18, 2012

Spring-test-mvc, @Configuration and 1 page test

I like how a very concise 1 page end to end controller test for a sample REST service is possible through a combination of @Configuration, Spring Testing Support and Spring-test-mvc.

Here is the test:

package org.bk.webtest;

import static org.hamcrest.Matchers.containsString;
import static org.springframework.test.web.server.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.server.result.MockMvcResultMatchers.*;
import static org.springframework.test.web.server.setup.MockMvcBuilders.*;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import org.junit.Test;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.test.web.server.MockMvc;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

public class WebContextConfigurationTest {
 private final String createJson = "{\"id\":%d,\"first\":\"%s\",\"last\":\"%s\"}";
 private final String membersJson = "[{\"id\":1,\"first\":\"One\",\"last\":\"One\"},{\"id\":2,\"first\":\"Two\",\"last\":\"Two\"},{\"id\":3,\"first\":\"Three\",\"last\":\"Three\"}]";
 private final String updatedMembersJson = "[{\"id\":1,\"first\":\"One\",\"last\":\"OneUpdated\"},{\"id\":2,\"first\":\"Two\",\"last\":\"Two\"},{\"id\":3,\"first\":\"Three\",\"last\":\"Three\"}]";
 
 @Test
 public void testAWebFlow() throws Exception {
  MockMvc mockMvc = annotationConfigSetup(WebContextConfigurationTest.TestConfiguration.class)
   .build();
  mockMvc.perform(post("/members").contentType(MediaType.APPLICATION_JSON).body(String.format(createJson, 1,"One","One").getBytes()))
    .andExpect(status().isOk());
  mockMvc.perform(post("/members").contentType(MediaType.APPLICATION_JSON).body(String.format(createJson, 2,"Two","Two").getBytes()))
   .andExpect(status().isOk());
  mockMvc.perform(post("/members").contentType(MediaType.APPLICATION_JSON).body(String.format(createJson, 3,"Three","Three").getBytes()))
   .andExpect(status().isOk());
  
  
  mockMvc.perform(get("/members").contentType(MediaType.APPLICATION_JSON))
    .andExpect(status().isOk())
    .andExpect(content().string(containsString(membersJson)));
  
  mockMvc.perform(put("/members").contentType(MediaType.APPLICATION_JSON).body(String.format(createJson, 1,"One","OneUpdated").getBytes()))
   .andExpect(status().isOk());
  
  mockMvc.perform(get("/members").contentType(MediaType.APPLICATION_JSON))
   .andExpect(status().isOk())
   .andExpect(content().string(containsString(updatedMembersJson)));
  
  mockMvc.perform(get("/members/1").contentType(MediaType.APPLICATION_JSON))
   .andExpect(status().isOk())
   .andExpect(content().string(String.format(createJson, 1,"One","OneUpdated")));
  
  mockMvc.perform(delete("/members/1").contentType(MediaType.APPLICATION_JSON))
   .andExpect(status().isOk());
  
  
 }

 @Configuration
 @EnableWebMvc
 @ComponentScan(basePackages="org.bk.webtest")
 public static class TestConfiguration{
  
 }
}

@Controller
class MembersController{
 private Map<Integer, Member> memberDB = new HashMap<>();
 @RequestMapping(value = "/members", method = RequestMethod.GET)
    @ResponseBody
    public Collection<Member> list() {
        return this.memberDB.values();
    }
 
 @RequestMapping(value="/members", method=RequestMethod.POST)
 public @ResponseBody Member create(@RequestBody Member member){
  this.memberDB.put(member.getId(), member);
  return member;
 }
 
 @RequestMapping(value="/members", method=RequestMethod.PUT)
 public @ResponseBody Member update(@RequestBody Member member){
  this.memberDB.put(member.getId(), member);
  return member;
 }
 
 @RequestMapping(value="/members/{id}", method=RequestMethod.GET)
 public @ResponseBody Member get(@PathVariable("id") Integer id){
  return this.memberDB.get(id);
 }
 
 @RequestMapping(value="/members/{id}", method=RequestMethod.DELETE)
 public void delete(@PathVariable("id") Integer id){
  this.memberDB.remove(id);
 }
}

class Member{
 private Integer id;
 private String first;
 private String last;
 
 public Integer getId() {
  return id;
 }
 public void setId(Integer id) {
  this.id = id;
 }

 public String getFirst() {
  return first;
 }
 
 public void setFirst(String first) {
  this.first = first;
 }
 public String getLast() {
  return last;
 }
 public void setLast(String last) {
  this.last = last;
 }
}



This is a complete test which performs a test for a REST based controller supporting creating a new entity through Http POST, Updating it through a Http PUT, getting a list or an entity through Http GET, and deleting it through DELETE.

Just the following configures the complete Spring MVC!
@Configuration
 @EnableWebMvc
 @ComponentScan(basePackages="org.bk.webtest")
 public static class TestConfiguration{
  
 }