<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Ralf Schäftlein&#039;s Blog &#187; REST</title>
	<atom:link href="http://ralf.schaeftlein.de/tag/rest/feed/" rel="self" type="application/rss+xml" />
	<link>http://ralf.schaeftlein.de</link>
	<description>tech stuff, talk,...</description>
	<lastBuildDate>Sat, 07 Aug 2010 11:45:35 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>JUnit Tests for Spring 3 Rest Services</title>
		<link>http://ralf.schaeftlein.de/2010/03/05/junit-tests-for-spring-3-rest-services/</link>
		<comments>http://ralf.schaeftlein.de/2010/03/05/junit-tests-for-spring-3-rest-services/#comments</comments>
		<pubDate>Fri, 05 Mar 2010 15:39:31 +0000</pubDate>
		<dc:creator>ralf</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[internet]]></category>
		<category><![CDATA[JAXB]]></category>
		<category><![CDATA[JPA]]></category>
		<category><![CDATA[junit]]></category>
		<category><![CDATA[maven]]></category>
		<category><![CDATA[REST]]></category>
		<category><![CDATA[SOA]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[webservices]]></category>

		<guid isPermaLink="false">http://ralf.schaeftlein.de/?p=187</guid>
		<description><![CDATA[SpringSource has recently released 3.0.1 of their Spring Framework. Spring 3 extended the REST functionalities inside the Web MVC part of the Framework. Rest Service are defined as Controller and can be tested with the new Resttemplate. In this little sample project is Spring 3 combined with JUnit 4, Maven, Hibernate 3.2, Jetty, MySQL, JPA, [...]]]></description>
			<content:encoded><![CDATA[<p>SpringSource has recently released <a href="http://blog.springsource.com/2010/02/18/spring-framework-3-0-1-released/">3.0.1</a> of their Spring Framework. Spring 3 extended the REST functionalities inside the Web MVC part of the Framework. Rest Service are defined as <a href="http://blog.springsource.com/2009/03/08/rest-in-spring-3-mvc/">Controller</a> and can be tested with the new <a href="http://blog.springsource.com/2009/03/27/rest-in-spring-3-resttemplate/">Resttemplate</a>. In this little sample project is Spring 3 combined with JUnit 4, Maven, Hibernate 3.2, Jetty, MySQL, JPA, JAXB and AspectJ. Additional tests was made with <a href="https://addons.mozilla.org/de/firefox/addon/2691">Poster</a> as a Firefox Plugin to test REST bases Webservices. Jetty 6.1 is used as embedded container for the web application as backend for the seperated maven integration tests. Jetty can be started with mvn jetty:run for tests with Poster or will be started before the integration tests runs with mvn integration-test. The Project is configured via Maven pom.xml as seen later in this post. Via mvn eclipse:eclipse will the eclipse settings generated to use the project as WTP project. I used <a href="http://maven.apache.org/download.html">Maven 2.2.1</a> in combination with <a href="http://www.eclipse.org/downloads/">eclipse 3.5.2.</a>. As backend infrastructure runs inside Ubuntu 9.1 Server a <a href="http://www.bugzilla.org/">Bugzilla 3</a>, <a href="http://www.jfrog.org/products.php">Artifactory 2.2.1</a>, Subversion 1.6 and a <a href="http://hudson-ci.org/">Hudson 1.348</a>.</p>
<p>REST as <a href="http://en.wikipedia.org/wiki/Representational_State_Transfer">representational state transferr</a> has less protocol overhead as SOAP. It heavily depends on HTTP mechanism like PUT, GET, DELETE or POST method calls or HTTP accept header definition of the mime type like &#8216;text/xml&#8217;, &#8216;text/plain&#8217; or &#8216;image/jpeg&#8217; to define delivered and expected content. So you make a HTTP GET request with an accept header &#8216;image/jpeg&#8217; with a url like http://myserver/restservice/1 in firefox to see their a picture of catalog item with id 1. A HTTP Post send data to the server as new data and a PUT override existing data. HTTP 1.1 defines a <a href="http://http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html">list of methods</a> to use in your REST based Service. </p>
<p>The whole project is Java annotation driven and use JDK 1.6 but can easily switched to run with JDK 1.5 as well. Configuration is Spring based as <a href="http://de.wikipedia.org/wiki/Inversion_of_Control">IOC pattern</a> and as annotations inside the Java classes. XML content is converted by JAXB Marshaller to use only domain objects inside your business logic. Persistence is defined as JPA annotations with Hibernate as implementation against a MySQL 5 database. The code was inspired by a blog from <a href="http://java.dzone.com/articles/spring-30-rest-example">Solomon Duskis</a>.</p>
<p><strong>The Java Source files</strong></p>
<p>The controller RestServiceController</p>
<pre name="code" class='java'>
package de.schaeftlein.dev.spring.rest.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
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 de.schaeftlein.dev.spring.rest.dao.PersonDao;
import de.schaeftlein.dev.spring.rest.domain.People;
import de.schaeftlein.dev.spring.rest.domain.Person;

@Controller
@RequestMapping("/people")
public class RestServiceController
{
  @Autowired
  private PersonDao personDao;

  @RequestMapping(method = RequestMethod.GET)
  @Transactional(readOnly = true)
  @ResponseBody
  public People getAll() {
    List<Person> persons = personDao.getPeople();
    People people = new People(persons);
    return people;
  }

  @RequestMapping(value = "/person/{id}", method = RequestMethod.GET)
  @ResponseBody
  @Transactional(readOnly = true)
  public Person getPerson(@PathVariable("id") Long personId) {
    return personDao.getPerson(personId);
  }

  @RequestMapping(method = RequestMethod.POST)
  @Transactional(readOnly = false)
  @ResponseBody
  public Person savePerson(@RequestBody Person person) {
    personDao.savePerson(person);
    return person;
  }
}
</pre>
<p>The Interface for the DAO PersonDAO</p>
<pre name="code" class='java'>
package de.schaeftlein.dev.spring.rest.dao;

import java.util.List;

import de.schaeftlein.dev.spring.rest.domain.Person;

public interface PersonDao {

  public Person getPerson(Long personId);

  public void savePerson(Person person);

  public List<Person> getPeople();

  public Person getPersonByUsername(String username);

}
</pre>
<p>The DAO implementation PersonDAOHibernate</p>
<pre name="code" class='java'>
package de.schaeftlein.dev.spring.rest.dao.hibernate;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import de.schaeftlein.dev.spring.rest.dao.PersonDao;
import de.schaeftlein.dev.spring.rest.domain.Person;

@Repository
@Transactional
@SuppressWarnings("unchecked")
public class PersonDaoHibernate extends HibernateDaoSupport implements
    PersonDao {

  @Autowired
  public void setupSessionFactory(SessionFactory sessionFactory) {
    this.setSessionFactory(sessionFactory);
  }

  public Person getPerson(Long personId) throws DataAccessException {
    return this.getHibernateTemplate().get(Person.class, personId);
  }

  @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
  public void savePerson(Person person) throws DataAccessException {
    this.getHibernateTemplate().saveOrUpdate(person);
  }

  public List<Person> getPeople() throws DataAccessException {
    return this.getHibernateTemplate().find("select people from Person people");
  }

  public Person getPersonByUsername(String username) {
    List<Person> people = this.getHibernateTemplate().findByNamedParam(
        "select people from Person people "
            + "where people.username = :username", "username", username);
    Person person = getFirst(people);
    if (person != null)
      getHibernateTemplate().evict(person);
    return person;
  }

  private static <T> T getFirst(List<T> list) {
    return CollectionUtils.isEmpty(list) ? null : list.get(0);
  }
}
</pre>
<p>The JAXB domain object People</p>
<pre name="code" class='java'>
package de.schaeftlein.dev.spring.rest.domain;

import java.io.Serializable;
import java.util.List;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class People implements Serializable {
  private static final long serialVersionUID = 1L;

  private List<Person> person;

  public People() {
    // empty constructor required for JAXB
  }

  public People(List<Person> person) {
    this.person = person;
  }

  public List<Person> getPerson() {
    return person;
  }

  public void setPerson(List<Person> person) {
    this.person = person;
  }

}
</pre>
<p>The JAXB and JPA entity domain object Person</p>
<pre name="code" class='java'>
package de.schaeftlein.dev.spring.rest.domain;

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Version;
import javax.xml.bind.annotation.XmlRootElement;

@Entity
@XmlRootElement
public class Person implements Serializable
{
  private static final long serialVersionUID = 1L;

  @Id
  @GeneratedValue
  private Long id;
  private String firstName;
  private String lastName;
  private String username;
  private String password;
  private int roleLevel;

  @Version
  private Integer version;

  public Person()
  {

  }

  public Person(String firstName, String lastName, String username, String password, int roleLevel)
  {
    this.firstName = firstName;
    this.lastName = lastName;
    this.username = username;
    this.password = password;
    this.roleLevel = roleLevel;
  }

  public Long getId()
  {
    return id;
  }

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

  public String getFirstName()
  {
    return firstName;
  }

  public void setFirstName(String firstName)
  {
    this.firstName = firstName;
  }

  public String getLastName()
  {
    return lastName;
  }

  public void setLastName(String lastName)
  {
    this.lastName = lastName;
  }

  public String getUsername()
  {
    return username;
  }

  public void setUsername(String username)
  {
    this.username = username;
  }

  public String getPassword()
  {
    return password;
  }

  public void setPassword(String password)
  {
    this.password = password;
  }

  public int getRoleLevel()
  {
    return roleLevel;
  }

  public void setRoleLevel(int roleLevel)
  {
    this.roleLevel = roleLevel;
  }

  public Integer getVersion()
  {
    return version == null ? 1 : version;
  }

  public void setVersion(Integer version)
  {
    this.version = version;
  }

  public enum RoleLevel {
    ADMIN(1), GUEST(2), PUBLIC(3);
    private final int level;

    RoleLevel(int value)
    {
      this.level = value;
    }

    public static RoleLevel getLevel(String roleName)
    {
      return RoleLevel.valueOf(roleName);
    }

    public int getLevel()
    {
      return this.level;
    }
  }

  @Override
  public boolean equals(Object obj)
  {
    if (obj == null)
    {
      return false;
    }
    else if (!(obj instanceof Person))
    {
      return false;
    }
    else
    {
      Person p = (Person) obj;
      if (p.getId().equals(getId()) &#038;&#038; p.getUsername().equals(getUsername()) &#038;&#038;
          p.getVersion().equals(getVersion()) &#038;&#038;
          p.getLastName().equals(getLastName()) &#038;&#038; p.getPassword().equals(getPassword())
          &#038;&#038; p.getFirstName().equals(getFirstName()) &#038;&#038; p.getRoleLevel() == getRoleLevel())
      {
        return true;
      }
    }
    return false;
  }

}
</pre>
<p>The DAO test PersonDAOTest</p>
<pre name="code" class='java'>
package de.schaeftlein.dev.spring.rest.dao;

import java.util.List;

import static junit.framework.Assert.*;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;

import de.schaeftlein.dev.spring.rest.domain.Person;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:spring-context.xml" })
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = false)
public class PersonDaoTest {

  @Autowired
  PersonDao personDao;

  private Logger log = LoggerFactory.getLogger(PersonDaoTest.class);

  @Test
  public void testPerson() {
    String username = "jane.doe";
    Person person = new Person("Jane", "Doe", username, "password",
        Person.RoleLevel.ADMIN.getLevel());
    person.setVersion(1);
    personDao.savePerson(person);

    final List<Person> people = personDao.getPeople();
    assertEquals(1, people.size());
    assertEquals(person,people.get(0));

    Long personId = person.getId();
    Person savedPerson = personDao.getPerson(personId);
    assertEquals(username,savedPerson.getUsername());
  }

  @Test
  public void testVersion() {
    Person solomon = new Person("John", "Doe", "john.doe", "mypass",
        Person.RoleLevel.ADMIN.getLevel());
    // version 0
    personDao.savePerson(solomon);

    Integer version = solomon.getVersion();
    log.info("old version:"+solomon.getVersion());

    solomon = personDao.getPersonByUsername("john.doe");
    solomon.setPassword("password1");
    // version 1
    personDao.savePerson(solomon);

    log.info("new version:"+solomon.getVersion());

    assertTrue(!(version.equals(solomon.getVersion())));
  }
}
</pre>
<p>The Rest test RestClientTest</p>
<pre name="code" class='java'>
package de.schaeftlein.dev.spring.rest.itest.controller;

import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertNull;
import static junit.framework.Assert.assertTrue;

import java.util.Collections;
import java.util.Map;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.web.client.RestTemplate;

import de.schaeftlein.dev.spring.rest.domain.People;
import de.schaeftlein.dev.spring.rest.domain.Person;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:spring-context.xml"})
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = false)
public class RestClientTest
{

  private static final String BASE_URL = "http://localhost:9090/spring3-rest-sample/people";

  private Logger log = LoggerFactory.getLogger(RestClientTest.class);

  @Autowired
  private RestTemplate restTemplate;

  @Test
  public void saveAndGet() throws Exception{
    // save
    Person input = new Person("jane","doe","jane.doe","pw",Person.RoleLevel.ADMIN.getLevel());
    assertNull(input.getId());
    Person output = restTemplate.postForObject(BASE_URL, input, Person.class, new Object[]{});
    assertNotNull("no person",output);
    assertNotNull(output.getId());
    assertEquals(input.getUsername(), output.getUsername());
    log.info("Saved jane.doe with id "+output.getId());
    // get all
    People people = restTemplate.getForObject(BASE_URL, People.class,new Object[]{});
    assertNotNull("no people",people);
    assertNotNull("no persons in people",people.getPerson());
    assertTrue("empty persons in people",!people.getPerson().isEmpty());
    assertEquals("no one person in people",input.getUsername(),people.getPerson().get(0).getUsername());
    log.info("Peple size "+people.getPerson().size());
    // get id
    Map<String, String> vars = Collections.singletonMap("id", output.getId()+"");
    Person idPerson = restTemplate.getForObject(BASE_URL+"/person/{id}", Person.class,vars);
    assertNotNull("no person",idPerson);
    assertNotNull(idPerson.getId());
    assertEquals(input.getUsername(), idPerson.getUsername());
    log.info("Get person by id <"+output.getId()+"> : "+idPerson.getUsername());
  }

}
</pre>
<p><strong>The configuration files</strong></p>
<p>The Spring annotation.xml</p>
<pre name="code" class='xml'>
<?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:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
       http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
	<!--
		Instruct Spring to perform declarative transaction management
		automatically on annotated classes.
	-->
	<tx:annotation-driven />
	<!--
		Activates various annotations to be detected in bean classes: Spring's
		@Required and @Autowired, as well as JSR 250's @PostConstruct,
		@PreDestroy and @Resource (if available) and JPA's @PersistenceContext
		and @PersistenceUnit (if available).
	-->
	<context:annotation-config />

	<!--
		Instruct Spring to retrieve and apply @AspectJ aspects which are
		defined as beans in this context (such as the UsageLogAspect below).
	-->
	<aop:aspectj-autoproxy />
</beans>
</pre>
<p>The JDBC settings jdbc.properties</p>
<pre name="code" class='xml'>
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=test
jdbc.password=test
jdbc.initialPoolSize=5
jdbc.maxPoolSize=100
jdbc.minPoolSize=5
jdbc.maxStatementsPerConnection=25
jdbc.maxStatements=50
jpa.databasePlatform=org.hibernate.dialect.MySQL5InnoDBDialect
jpa.showSql=true
jdbc.schema=test
jdbc.dataTypeFactory=org.dbunit.ext.mysql.MySqlDataTypeFactory
jdbc.autoCommitOnClose=true
jdbc.autoCommit=true
hibernate.release_mode=after_transaction
hibernate.hbm2ddl=create
hibernate.auto_close_session=true
hibernate.current_session_context_class=thread
hibernate.flush_before_completion=true
</pre>
<p>The JAXB marshalling.xml</p>
<pre name="code" class='xml'>
<?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:context="http://www.springframework.org/schema/context"
  xmlns:p="http://www.springframework.org/schema/p"
  xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
  xmlns:aop="http://www.springframework.org/schema/aop"
  xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context-3.0.xsd

http://www.springframework.org/schema/tx

http://www.springframework.org/schema/tx/spring-tx-3.0.xsd

http://www.springframework.org/schema/aop

http://www.springframework.org/schema/aop/spring-aop-3.0.xsd

http://www.springframework.org/schema/jdbc

		   http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd">

  <bean id="marshallingHttpMessageConverter"
    class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter"
    p:marshaller-ref="jaxb2Marshaller" p:unmarshaller-ref="jaxb2Marshaller" />

  <bean id="jaxb2Marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="classesToBeBound">
<list>
        <value>de.schaeftlein.dev.spring.rest.domain.Person</value>
        <value>de.schaeftlein.dev.spring.rest.domain.People</value>
      </list>
    </property>
  </bean>

</beans>
</pre>
<p>The AOP based transactionAdvices.xml</p>
<pre name="code" class='xml'>
<?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:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

http://www.springframework.org/schema/aop

http://www.springframework.org/schema/aop/spring-aop-3.0.xsd

http://www.springframework.org/schema/tx

http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

  <aop:config>
    <aop:pointcut id="serviceMethods"
            expression="execution(* dao.*Dao*.*(..))"/>
    <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethods"/>
  </aop:config>

  <tx:advice id="txAdvice" transaction-manager="transactionManager">
    <tx:attributes>
      <tx:method name="save*" propagation="REQUIRED"/>
      <tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
    </tx:attributes>
  </tx:advice>

</beans>
</pre>
<p>The spring-dispatcher.xml</p>
<pre name="code" class='xml'>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
  xmlns:p="http://www.springframework.org/schema/p"
  xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
  xmlns:aop="http://www.springframework.org/schema/aop"
  xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context-3.0.xsd

http://www.springframework.org/schema/tx

http://www.springframework.org/schema/tx/spring-tx-3.0.xsd

http://www.springframework.org/schema/aop

http://www.springframework.org/schema/aop/spring-aop-3.0.xsd

http://www.springframework.org/schema/jdbc

		   http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd">

  <import resource="transactionAdvices.xml" />
  <import resource="annotation.xml" />
  <import resource="marshalling.xml" />

  <bean
    class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />

  <bean
    class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
        <ref bean="marshallingHttpMessageConverter"/>
      </list>
    </property>
 </bean>

  <context:component-scan base-package="de.schaeftlein.dev.spring.rest.controller" />
</beans>
</pre>
<p>The spring-context.xml</p>
<pre name="code" class='xml'>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
	xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context-3.0.xsd

http://www.springframework.org/schema/tx

http://www.springframework.org/schema/tx/spring-tx-3.0.xsd

http://www.springframework.org/schema/aop

http://www.springframework.org/schema/aop/spring-aop-3.0.xsd

http://www.springframework.org/schema/jdbc

	http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd">

	<import resource="transactionAdvices.xml" />
	<import resource="annotation.xml" />
	<import resource="marshalling.xml" />

   <context:component-scan base-package="de.schaeftlein.dev.spring.rest" />

    <bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
<property name="messageConverters" ref="marshallingHttpMessageConverter"/>
    </bean>

	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass">
			<value>${jdbc.driverClassName}</value>
		</property>
<property name="jdbcUrl">
			<value>${jdbc.url}</value>
		</property>
<property name="user">
			<value>${jdbc.username}</value>
		</property>
<property name="password">
			<value>${jdbc.password}</value>
		</property>
<property name="autoCommitOnClose">
			<value>${jdbc.autoCommitOnClose}</value>
		</property>
<property name="initialPoolSize">
			<value>${jdbc.initialPoolSize}</value>
		</property>
<property name="maxPoolSize">
			<value>${jdbc.maxPoolSize}</value>
		</property>
<property name="minPoolSize">
			<value>${jdbc.minPoolSize}</value>
		</property>
<property name="maxStatementsPerConnection">
			<value>${jdbc.maxStatementsPerConnection}</value>
		</property>
<property name="maxStatements">
			<value>${jdbc.maxStatements}</value>
		</property>
	</bean>

	<bean id="propertyConfigurer"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
		p:location="classpath:jdbc.properties" />

	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"
		p:dataSource-ref="dataSource" p:lobHandler-ref="defaultLobHandler"
		p:packagesToScan="de.schaeftlein.dev.spring.rest.domain">
<property name="hibernateProperties">
<props>
<prop key="hibernate.connection.url">${jdbc.url}</prop>
<prop key="hibernate.connection.driver_class">${jdbc.driverClassName}</prop>
<prop key="hibernate.connection.password">${jdbc.username} </prop>
<prop key="hibernate.connection.username">${jdbc.password}</prop>
<prop key="hibernate.connection.autocommit">${jdbc.autoCommit}</prop>
<prop key="hibernate.connection.release_mode">${hibernate.release_mode}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl}</prop>
<prop key="hibernate.transaction.auto_close_session">${hibernate.auto_close_session}</prop>
<prop key="hibernate.current_session_context_class">${hibernate.current_session_context_class}</prop>
<prop key="hibernate.cglib.use_reflection_optimizer">false</prop>
<prop key="hibernate.bytecode.use_reflection_optimizer">false</prop>
<prop key="hibernate.bytecode.provider">javassist</prop>
<prop key="hibernate.transaction.flush_before_completion">${hibernate.flush_before_completion}</prop>
			</props>
		</property>
	</bean>

	<bean id="defaultLobHandler" class="org.springframework.jdbc.support.lob.DefaultLobHandler" />

	<bean id="transactionManager"
		class="org.springframework.orm.hibernate3.HibernateTransactionManager"
		p:sessionFactory-ref="sessionFactory" />   

</beans>
</pre>
<p>The web.xml</p>
<pre name="code" class='xml'>
<?xml version="1.0" encoding="ISO-8859-1"?>

<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
  version="2.4">

  <display-name>spring3-rest-sample</display-name>
  <description>Spring 3 Rest sample</description>
  <distributable />

  <context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-context.xml</param-value>
  </context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener
    </listener-class>
  </listener>

  <servlet>
    <servlet-name>springDispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-dispatcher.xml</param-value>
    </init-param>
    <load-on-startup>2</load-on-startup>
  </servlet>

  <!--
    - Dispatcher servlet mapping for the web user interface
  -->
  <servlet-mapping>
    <servlet-name>springDispatcher</servlet-name>
    <url-pattern>/*</url-pattern>
  </servlet-mapping>

</web-app>
</pre>
<p>The Maven pom.xml</p>
<pre name="code" class='xml'>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>de.schaeftlein.dev.spring.rest</groupId>
	<artifactId>spring3-rest-sample</artifactId>
<packaging>war</packaging>
	<version>1.0-SNAPSHOT</version>
	<name>spring3-rest-sample Maven Webapp</name>
	<description>A sample project for showing how to write JUnit Test against Spring 3 Rest Services</description>
    <developers>
     <developer>
       <name>Ralf Schäftlein</name>
       <url>http://ralf.schaeftlein.com</url>
     </developer>
    </developers>
    <inceptionYear>2010</inceptionYear>
    <issueManagement>
      <system>bugzilla</system>
      <url>http://ubuntu-vm.localdomain/cgi-bin/bugzilla3/index.cgi</url>
    </issueManagement>
    <url>http://ralf.schaeftlein.de/2010/03/05/junit-tests-for-spring-3-rest-spring-3-rest-services</url>

	<reporting>
<plugins>
<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-report-plugin</artifactId>
				<version>2.5</version>
			</plugin>
<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-checkstyle-plugin</artifactId>
				<version>2.5</version>
			</plugin>
<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-javadoc-plugin</artifactId>
				<version>2.6.1</version>
			</plugin>
<plugin>
				<groupId>org.codehaus.mojo</groupId>
				<artifactId>cobertura-maven-plugin</artifactId>
				<version>2.3</version>
			</plugin>
<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-pmd-plugin</artifactId>
				<version>2.4</version>
				<configuration>
					<sourceEncoding>utf-8</sourceEncoding>
					<targetJdk>1.6</targetJdk>
				</configuration>
			</plugin>
<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-jxr-plugin</artifactId>
				<version>2.1</version>
				<configuration>
<inputEncoding>UTF-8</inputEncoding>
					<outputEncoding>UTF-8</outputEncoding>
				</configuration>
			</plugin>
<plugin>
				<groupId>org.codehaus.mojo</groupId>
				<artifactId>taglist-maven-plugin</artifactId>
				<version>2.4</version>
			</plugin>
<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-changes-plugin</artifactId>
				<version>2.3</version>
				<reportSets>
					<reportSet>
						<reports>
							<report>changes-report</report>
						</reports>
					</reportSet>
				</reportSets>
			</plugin>
		</plugins>
	</reporting>
	<distributionManagement>
		<repository>
			<id>internal</id>
			<url>
				dav:http://ubuntu-vm.localdomain:8081/artifactory/internal
			</url>
		</repository>
		<snapshotRepository>
			<id>snapshots</id>
			<url>
				dav:http://ubuntu-vm.localdomain:8081/artifactory/snapshots
			</url>
		</snapshotRepository>
	</distributionManagement>
	<scm>
		<connection>
           scm:svn:http://ubuntu-vm.localdomain/svn/
       </connection>
		<developerConnection>
           scm:svn:http://ubuntu-vm.localdomain/svn/
       </developerConnection>
		<url>http://ubuntu-vm.localdomain/svn/</url>
	</scm>
	<ciManagement>
		<system>Hudson</system>
		<url>http://ubuntu-vm.localdomain/hudson/job/spring3-rest-sample</url>
	</ciManagement>
	<build>
		<finalName>spring3-rest-sample</finalName>
<plugins>
<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-report-plugin</artifactId>
				<version>2.5</version>
			</plugin>
<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-deploy-plugin</artifactId>
				<version>2.5</version>
			</plugin>
<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-plugin</artifactId>
				<version>2.5</version>
				<configuration>
					<skip>true</skip>
				</configuration>
				<executions>
					<execution>
						<id>surefire-test</id>
<phase>test</phase>
						<goals>
							<goal>test</goal>
						</goals>
						<configuration>
							<skip>false</skip>
							<excludes>
								<exclude>**/itest/**</exclude>
							</excludes>
						</configuration>
					</execution>

					<execution>
						<id>surefire-itest</id>
<phase>integration-test</phase>
						<goals>
							<goal>test</goal>
						</goals>
						<configuration>
							<skip>false</skip>
							<includes>
								<include>**/itest/**</include>
							</includes>
						</configuration>
					</execution>
				</executions>
			</plugin>
<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-pmd-plugin</artifactId>
				<version>2.4</version>
				<configuration>
					<sourceEncoding>utf-8</sourceEncoding>
					<targetJdk>1.6</targetJdk>
				</configuration>
				<executions>
					<execution>
						<goals>
							<goal>check</goal>
							<goal>cpd-check</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
<plugin>
				<groupId>org.codehaus.mojo</groupId>
				<artifactId>cobertura-maven-plugin</artifactId>
				<version>2.3</version>
				<configuration>
<formats>
<format>html</format>
<format>xml</format>
					</formats>
				</configuration>
			</plugin>
<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-jxr-plugin</artifactId>
				<version>2.1</version>
			</plugin>
<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-checkstyle-plugin</artifactId>
				<version>2.5</version>
			</plugin>
<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.1</version>
				<configuration>
					<source>1.6</source>
					<target>1.6</target>
				</configuration>
			</plugin>
<plugin>
				<groupId>org.mortbay.jetty</groupId>
				<artifactId>maven-jetty-plugin</artifactId>
				<version>6.1.22</version>
				<configuration>
					<scanIntervalSeconds>10</scanIntervalSeconds>
					<stopKey>foo</stopKey>
					<stopPort>9999</stopPort>
					<contextPath>/${artifactId}</contextPath>
					<connectors>
						<connector implementation="org.mortbay.jetty.nio.SelectChannelConnector">
<port>9090</port>
							<maxIdleTime>60000</maxIdleTime>
						</connector>
					</connectors>
				</configuration>
				<executions>
					<execution>
						<id>start-jetty</id>
<phase>pre-integration-test</phase>
						<goals>
							<goal>run</goal>
						</goals>
						<configuration>
							<scanIntervalSeconds>0</scanIntervalSeconds>
							<daemon>true</daemon>
						</configuration>
					</execution>
					<execution>
						<id>stop-jetty</id>
<phase>post-integration-test</phase>
						<goals>
							<goal>stop</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-eclipse-plugin</artifactId>
				<version>2.8</version>
				<configuration>
					<downloadSources>true</downloadSources>
					<downloadJavadocs>true</downloadJavadocs>
					<wtpversion>2.0</wtpversion>
				</configuration>
			</plugin>
			<!--
				If you build jars the classpath of the referenced libraries will be
				added in the manifest.
			-->
<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-jar-plugin</artifactId>
				<version>2.3</version>
				<configuration>
					<archive>
						<manifest>
							<addClasspath>true</addClasspath>
						</manifest>
					</archive>
				</configuration>
			</plugin>
			<!-- if you build jars a source file will be built as well -->
<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-source-plugin</artifactId>
				<version>2.1.1</version>
				<executions>
					<execution>
						<id>attach-sources</id>
<phase>verify</phase>
						<goals>
							<goal>jar</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-scm-plugin</artifactId>
				<version>1.3</version>
				<configuration>
					<username>${svn_username}</username>
<password>${svn_password}</password>
				</configuration>
			</plugin>
<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-war-plugin</artifactId>
				<version>2.1-beta-1</version>
				<configuration>
					<warSourceDirectory>src/main/webapp</warSourceDirectory>
					<webXml>src/main/webapp/WEB-INF/web.xml</webXml>
					<!-- we must exclude the svn folders -->
<packagingExcludes>
						<![CDATA[**/.svn,**/.svn/**,**/_svn,**/_svn/**]]&gt;
					</packagingExcludes>
					<archive>
						<manifest>
							<addClasspath>true</addClasspath>
							<classpathPrefix>lib/</classpathPrefix>
						</manifest>
					</archive>
				</configuration>
			</plugin>
		</plugins>
		<!-- we must exclude the svn folders -->
		<resources>
			<resource>
				<directory>src/main/resources</directory>
				<excludes>
					<exclude>**/.svn</exclude>
					<exclude>**/.svn/**</exclude>
					<exclude>**/_svn</exclude>
					<exclude>_svn</exclude>
					<exclude>**/_svn/**</exclude>
				</excludes>
			</resource>
		</resources>
		<testResources>
			<testResource>
				<directory>src/test/resources</directory>
				<excludes>
					<exclude>**/.svn</exclude>
					<exclude>**/.svn/**</exclude>
					<exclude>**/_svn</exclude>
					<exclude>_svn</exclude>
					<exclude>**/_svn/**</exclude>
				</excludes>
			</testResource>
		</testResources>
	</build>
<properties>
		<spring.framework.version>3.0.1.RELEASE</spring.framework.version>
		<org.slf4j.version>1.5.2</org.slf4j.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<!--  AOP -->
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
			<version>1.6.2</version>
		</dependency>
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjrt</artifactId>
			<version>1.6.2</version>
		</dependency>
		<!-- Spring  -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>${spring.framework.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
			<version>${spring.framework.version}</version>
			<exclusions>
				<exclusion>
					<groupId>quartz</groupId>
					<artifactId>quartz</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.framework.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aspects</artifactId>
			<version>${spring.framework.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>${spring.framework.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${spring.framework.version}</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>${spring.framework.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-oxm</artifactId>
			<version>${spring.framework.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>${spring.framework.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring.framework.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.framework.version}</version>
		</dependency>

		<!-- Hibernate -->
		<dependency>
			<groupId>cglib</groupId>
			<artifactId>cglib-nodep</artifactId>
			<version>2.1_3</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-annotations</artifactId>
			<version>3.2.0.ga</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate</artifactId>
			<version>3.2.6.ga</version>
		</dependency>
		<dependency>
			<groupId>javax.persistence</groupId>
			<artifactId>persistence-api</artifactId>
			<version>1.0</version>
		</dependency>
		<dependency>
			<groupId>javassist</groupId>
			<artifactId>javassist</artifactId>
			<version>3.11.0.GA</version>
		</dependency>

		<!-- Database -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.12</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>c3p0</groupId>
			<artifactId>c3p0</artifactId>
			<version>0.9.1.2</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>commons-dbcp</groupId>
			<artifactId>commons-dbcp</artifactId>
			<version>1.4</version>
		</dependency>
		<dependency>
			<groupId>commons-collections</groupId>
			<artifactId>commons-collections</artifactId>
			<version>3.2.1</version>
		</dependency>
		<dependency>
			<groupId>javax.transaction</groupId>
			<artifactId>jta</artifactId>
			<version>1.1</version>
		</dependency>

		<!-- JAXB -->
		<dependency>
			<groupId>javax.xml.bind</groupId>
			<artifactId>jaxb-api</artifactId>
			<version>2.0</version>
		</dependency>

		<!-- JUnit -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.8.1</version>
			<scope>test</scope>
		</dependency>
		<!--  logging -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${org.slf4j.version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-simple</artifactId>
			<version>${org.slf4j.version}</version>
		</dependency>
		<!-- integration test -->
		<dependency>
			<groupId>org.mortbay.jetty</groupId>
			<artifactId>maven-jetty-plugin</artifactId>
			<version>6.1.15</version>
			<scope>test</scope>
		</dependency>

	</dependencies>
</project>
</pre>
<p><strong>Sample Content for Poster</strong></p>
<p>The person.xml</p>
<pre name="code" class='xml'>
<?xml version="1.0" encoding="UTF-8"?>
<person>
    <firstName>Jane</firstName>
    <lastName>Doe</lastName>
    <username>jane.doe</username>
<password>bar</password>
    <roleLevel>2</roleLevel>
</person>
</pre>
]]></content:encoded>
			<wfw:commentRss>http://ralf.schaeftlein.de/2010/03/05/junit-tests-for-spring-3-rest-services/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
