<?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; Java</title>
	<atom:link href="http://ralf.schaeftlein.de/category/java/feed/" rel="self" type="application/rss+xml" />
	<link>http://ralf.schaeftlein.de</link>
	<description>tech stuff, talk,...</description>
	<lastBuildDate>Tue, 03 Jan 2012 18:30:06 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Using Cargo for Maven War Deployments to Tomcat 6.x</title>
		<link>http://ralf.schaeftlein.de/2012/01/03/using-cargo-for-maven-war-deployments-to-tomcat-6-x/</link>
		<comments>http://ralf.schaeftlein.de/2012/01/03/using-cargo-for-maven-war-deployments-to-tomcat-6-x/#comments</comments>
		<pubDate>Tue, 03 Jan 2012 18:20:51 +0000</pubDate>
		<dc:creator>Ralf</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[jee]]></category>
		<category><![CDATA[maven]]></category>
		<category><![CDATA[tomcat]]></category>

		<guid isPermaLink="false">http://ralf.schaeftlein.de/?p=286</guid>
		<description><![CDATA[JEE based projects with maven build artifacts like war or ear files is the cargo plugin the right choice for automatic deployments during the build process. First step is to define in the build section of your pom.xml the cargo plugin: org.codehaus.cargo cargo-maven2-plugin 1.1.4 tomcat6x remote runtime ${cargo.manager.url} ${cargo.username} ${cargo.password} remote ${project.groupId} ${project.artifactId} war ${project.artifactId} Notice [...]]]></description>
			<content:encoded><![CDATA[<p>JEE based projects with maven build artifacts like war or ear files is the <a title="cargo" href="http://cargo.codehaus.org/Maven2+plugin" target="_blank">cargo</a> plugin the right choice for automatic deployments during the build process.</p>
<p>First step is to define in the build section of your pom.xml the cargo plugin:</p>
<pre name="code" class="xml">
<plugin>
	<groupId>org.codehaus.cargo</groupId>
	<artifactId>cargo-maven2-plugin</artifactId>
	<version>1.1.4</version>
	<configuration>
		<container>
			<containerId>tomcat6x</containerId>
			<type>remote</type>
		</container>
		<configuration>
			<type>runtime</type>
<properties>
				<!-- see tomcat6x profile -->
				<cargo.tomcat.manager.url>${cargo.manager.url}</cargo.tomcat.manager.url>
				<cargo.remote.username>${cargo.username}</cargo.remote.username>
				<cargo.remote.password>${cargo.password}</cargo.remote.password>
			</properties>
		</configuration>
		<deployer>
			<type>remote</type>
			<deployables>
				<deployable>
					<groupId>${project.groupId}</groupId>
					<artifactId>${project.artifactId}</artifactId>
					<type>war</type>
<properties>
						<context>${project.artifactId}</context>
					</properties>
				</deployable>
			</deployables>
		</deployer>
	</configuration>
</plugin>
</pre>
<p>Notice the variables with the url and the credentials. The will filled with the used profile section for the build:</p>
<pre name="code" class="xml">
<profiles>
<profile>
		<id>tomcat6x_remote</id>
		<activation>
			<activeByDefault>true</activeByDefault>
		</activation>
<properties>
			<cargo.manager.url>http://ubuntu-vm.localdomain:8080/manager</cargo.manager.url>
			<cargo.username>tomcat</cargo.username>
			<cargo.password>tomcat</cargo.password>
		</properties>
	</profile>
<profile>
		<id>tomcat6x_ide</id>
<properties>
			<cargo.manager.url>http://localhost:9999/manager</cargo.manager.url>
			<cargo.username>tomcat</cargo.username>
			<cargo.password>tomcat</cargo.password>
		</properties>
	</profile>
</profiles>
</pre>
<p>The activeByDefault settings marks the remote section as default profile if nothing is set by command line parameters. </p>
<p>With</p>
<p>mvn org.codehaus.cargo:cargo-maven2-plugin:redeploy</p>
<p>you first undeploy the current application and then deploy the new build application to the remote tomcat instance. The command line parameter-Ptomcat6x_ide force maven to use the local tomcat instance for deployments.</p>
<p>mvn -Ptomcat6x_ide org.codehaus.cargo:cargo-maven2-plugin:redeploy</p>
<p>Hudson or Jenkins as continuous integration server can then be setup to use a primary project with the goal &#8220;clean deploy&#8221; to have a full test and maven repo deployment on success. The seconday project have the goal &#8220;clean package org.codehaus.cargo:cargo-maven2-plugin:redeploy -Dmaven.test.skip=true&#8221;. Inside the configuration of the primary job is the section with post build actions. Define here the secondary project to be build only on success of the primary build. Deployments can go wrong and should not have any effect on the primary build. Build trigger for the primary project is source code changes checked every minute (&#8220;* * * * *&#8221; as time plan). Changes by each developer force a complete junit and integration test of the module and new deployed artifacts inside  the maven repo like nexus for the rest of the team. A little bit later is then the new application ready to use. With different profiles is it possible to define DEV,QA and PROD target server inside one maven project pom.</p>
<p>Tomcat needs credentials of a user with explicit rights granted for successful remote deployments. See the following excerpt of the tomcat-user.xml inside the conf folder of your tomcat instance:</p>
<pre name="code" class="xml">
  <role rolename="tomcat"></role>
  <role rolename="manager-gui"></role>
  <role rolename="manager-script"></role>
  <role rolename="manager-status"></role>
  <role rolename="manager-jmx"></role>
  <user username="tomcat" password="tomcat" roles="tomcat,manager-gui,manager-script,manager-jmx,manager-status"></user>
</pre>
]]></content:encoded>
			<wfw:commentRss>http://ralf.schaeftlein.de/2012/01/03/using-cargo-for-maven-war-deployments-to-tomcat-6-x/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Control Hudson or Jenkins from Eclipse Indigo 3.7</title>
		<link>http://ralf.schaeftlein.de/2011/07/15/control-hudson-or-jenkins-from-eclipse-indigo-3-7/</link>
		<comments>http://ralf.schaeftlein.de/2011/07/15/control-hudson-or-jenkins-from-eclipse-indigo-3-7/#comments</comments>
		<pubDate>Fri, 15 Jul 2011 12:34:54 +0000</pubDate>
		<dc:creator>Ralf</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[ci]]></category>
		<category><![CDATA[eclipse]]></category>
		<category><![CDATA[hudson]]></category>
		<category><![CDATA[jenkins]]></category>

		<guid isPermaLink="false">http://ralf.schaeftlein.de/?p=253</guid>
		<description><![CDATA[For the latest eclipse release 3.7 called indigo is a plugin available to watch and control your build server based on hudson or jenkins. It is part of mylyn 3.5 as a view called &#8220;Builds&#8221;. See here for more information about the new features of mylyn 3.5. Their is as well a commercial plugin suite called [...]]]></description>
			<content:encoded><![CDATA[<p>For the latest eclipse release 3.7 called <a title="indigo" href="http://eclipse.org/indigo/">indigo </a>is a plugin available to watch and control your build server based on <a title="hudson" href="http://hudson-ci.org/">hudson </a>or <a title="jenkins" href="http://jenkins-ci.org/">jenkins</a>. It is part of <a title="mylyn" href="http://www.eclipse.org/mylyn/">mylyn </a>3.5 as a view called &#8220;Builds&#8221;. See <a title="here" href="http://www.eclipse.org/mylyn/new/">here </a>for more information about the new features of mylyn 3.5. Their is as well a commercial plugin suite called <a title="tasktop" href="http://tasktop.com/blog/mylyn/mylyn-hudson-connector-update">tasktop </a>available.</p>
<p>Howto install:</p>
<ol>
<li>Go to help -&gt; install new software</li>
<li>Click on &#8220;Available software sites&#8221;</li>
<li>Click on add with name &#8220;mylyn&#8221; and url &#8220;http://download.eclipse.org/mylyn/releases/latest&#8221;</li>
<li>Click ok to go back to site list</li>
<li>Click ok to go back to available software</li>
<li>Choose under &#8220;Work with&#8221; mylyn</li>
<li>Choose under &#8220;Mylyn integrations&#8221; the point &#8220;Mylyn Builds Connector: Hudson/Jenkins (Incubation)&#8221;</li>
<li>Choose under &#8220;Mylyn SDKs and Frameworks&#8221; the point  &#8221;Mylyn Builds (Incubation)&#8221;</li>
<li>Click on next</li>
<li>Go through install process and restart eclipse</li>
<li>Choose from menu &#8220;Window&#8221; -&gt; &#8220;show view&#8221;</li>
<li>Choose &#8220;Mylyn&#8221; -&gt; &#8220;Builds&#8221;</li>
</ol>
<div><a href="http://ralf.schaeftlein.de/wp-content/uploads/2011/07/Java-Eclipse-SDK_2011-07-15_14-24-17.png"><img class="aligncenter size-full wp-image-256" title="Java - Eclipse SDK_2011-07-15_14-24-17" src="http://ralf.schaeftlein.de/wp-content/uploads/2011/07/Java-Eclipse-SDK_2011-07-15_14-24-17.png" alt="" width="572" height="166" /></a></div>
<div>With the blue server icon on the left side of the title bar you can add a new build server. Choose &#8220;Hudson&#8221; inside the wizard and click next. Enter the url of your jenkins server and enter a label. Click on refresh at the right side under build plans. Choose your favorite builds and click on finish. After that you should have a view similar to the one above. You can start a new build and get updates as notification during the build process.</div>
]]></content:encoded>
			<wfw:commentRss>http://ralf.schaeftlein.de/2011/07/15/control-hudson-or-jenkins-from-eclipse-indigo-3-7/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Migrating a Hibernate Application from JPA 1.0 to 2.0</title>
		<link>http://ralf.schaeftlein.de/2010/03/10/migrating-a-hibernate-application-from-jpa-1-0-to-2-0/</link>
		<comments>http://ralf.schaeftlein.de/2010/03/10/migrating-a-hibernate-application-from-jpa-1-0-to-2-0/#comments</comments>
		<pubDate>Wed, 10 Mar 2010 16:44:00 +0000</pubDate>
		<dc:creator>ralf</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[hibernate]]></category>
		<category><![CDATA[JPA]]></category>
		<category><![CDATA[maven]]></category>

		<guid isPermaLink="false">http://ralf.schaeftlein.de/?p=209</guid>
		<description><![CDATA[Spring 3.0.1 explicit supports the second release candidate of hibernate 3.5 aka 3.5-CR-2. Migration is very easy with maven: old pom.xml (part) for hibernate 2.3 and jpa 1.0 cglib cglib-nodep 2.1_3 org.hibernate hibernate-annotations 3.2.0.ga org.hibernate hibernate 3.2.6.ga javax.persistence persistence-api 1.0 new pom.xml (part) for hibernate 3.5 and jpa 2.0 org.hibernate hibernate-entitymanager 3.5.0-CR-2 org.hibernate.java-persistence jpa-api 2.0-cr-1]]></description>
			<content:encoded><![CDATA[<p><a href="http://blog.springsource.com/2010/02/18/spring-framework-3-0-1-released/">Spring 3.0.1</a> explicit supports the second release candidate of hibernate 3.5 aka 3.5-CR-2. Migration is very easy with maven:</p>
<p>old pom.xml (part) for hibernate 2.3 and jpa 1.0</p>
<pre name='code' class='xml'>
		<!-- 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>
</pre>
<p>new pom.xml (part) for hibernate 3.5 and jpa 2.0</p>
<pre name='code' class='xml'>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-entitymanager</artifactId>
			<version>3.5.0-CR-2</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate.java-persistence</groupId>
			<artifactId>jpa-api</artifactId>
			<version>2.0-cr-1</version>
		</dependency>
</pre>
]]></content:encoded>
			<wfw:commentRss>http://ralf.schaeftlein.de/2010/03/10/migrating-a-hibernate-application-from-jpa-1-0-to-2-0/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Tomcat 6 Problems on Ubuntu 9.10</title>
		<link>http://ralf.schaeftlein.de/2010/03/10/tomcat-6-problems-on-ubuntu-9-10/</link>
		<comments>http://ralf.schaeftlein.de/2010/03/10/tomcat-6-problems-on-ubuntu-9-10/#comments</comments>
		<pubDate>Wed, 10 Mar 2010 15:13:03 +0000</pubDate>
		<dc:creator>ralf</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[aspectj]]></category>
		<category><![CDATA[ubuntu]]></category>

		<guid isPermaLink="false">http://ralf.schaeftlein.de/?p=199</guid>
		<description><![CDATA[The default behavior of the tomcat6 server installed from the ubuntu repository is to forbid any read operation of System.getProperty(). I used tomcat6 as deployment target for the hudson builds on the same machine. AspectJ is used in a sample Spring 3 REST application. Tomcat6 logs (catalina-&#8230;log) shows the following exception Caused by: java.security.AccessControlException: access [...]]]></description>
			<content:encoded><![CDATA[<p>The default behavior of the tomcat6 server installed from the ubuntu repository is to forbid any read operation of System.getProperty(). I used tomcat6 as deployment target for the hudson builds on the same machine. AspectJ is used in a sample <a href="http://ralf.schaeftlein.de/2010/03/05/junit-tests-for-spring-3-rest-services/">Spring 3 REST application</a>. Tomcat6 logs (catalina-&#8230;log) shows the following exception</p>
<pre name="code" code='java'>
Caused by: java.security.AccessControlException: access denied (java.util.PropertyPermission org.aspectj.tracing.debug read)
        at java.security.AccessControlContext.checkPermission(AccessControlContext.java:323)
        at java.security.AccessController.checkPermission(AccessController.java:546)
        at java.lang.SecurityManager.checkPermission(SecurityManager.java:532)
        at java.lang.SecurityManager.checkPropertyAccess(SecurityManager.java:1285)
        at java.lang.System.getProperty(System.java:686)
        at org.aspectj.weaver.tools.TraceFactory.getBoolean(TraceFactory.java:34)
        at org.aspectj.weaver.tools.TraceFactory.<clinit>(TraceFactory.java:21)
        ... 68 more
</pre>
<p>Updating aspectj in the maven pom to the latest version <a href="http://www.eclipse.org/aspectj/downloads.php">1.6.8</a> doesn&#8217;t solve<br />
the problem. The same war file works under windows with tomcat <a href="http://tomcat.apache.org/download-60.cgi">6.0.24</a> without any problems. An Forum entry shows the right <a href="http://www.activeobjects.no/subsonic/forum/viewtopic.php?t=2340">hint</a>. Inside the init script<br />
/etc/init.d/tomcat6 is default TOMCAT_SECURITY set to true, which forces the /etc/tomcat6/policy.d/* policies to be used in every web<br />
application inside tomcat. </p>
<pre name="code" code='py'>
# Use the Java security manager? (yes/no)
TOMCAT6_SECURITY=yes
</pre>
<p>So the solution can be quick (set the TOMCAT_SECURITY property inside the init script to no) or a bit more complicated (set a new policy for your web application as new file inside the policy.d folder). The problem with the more complicated one is that you need to know every  security relevant operation to write the policy file). </p>
]]></content:encoded>
			<wfw:commentRss>http://ralf.schaeftlein.de/2010/03/10/tomcat-6-problems-on-ubuntu-9-10/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<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[internet]]></category>
		<category><![CDATA[Java]]></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>
		<item>
		<title>ide for testing JDK 7 features (Milestone 5: Build b76)</title>
		<link>http://ralf.schaeftlein.de/2009/11/23/ide-for-testing-jdk-1-7-features/</link>
		<comments>http://ralf.schaeftlein.de/2009/11/23/ide-for-testing-jdk-1-7-features/#comments</comments>
		<pubDate>Mon, 23 Nov 2009 15:55:16 +0000</pubDate>
		<dc:creator>ralf</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[eclipse]]></category>
		<category><![CDATA[jdk 1.7]]></category>
		<category><![CDATA[netbeans]]></category>

		<guid isPermaLink="false">http://ralf.schaeftlein.de/?p=169</guid>
		<description><![CDATA[Sun has published milestone 5 (b76) of the upcoming Java JDK 7. JDK 7 release is currently scheduled for September 2010. My standard IDE is eclipse but the current production version 3.5 SR 1 support only Java up to JDK 6. I tried the new eclipse e4 1.0 milestone 2 (status: technical preview) which has [...]]]></description>
			<content:encoded><![CDATA[<p>Sun has published <a href="http://download.java.net/jdk7/m5/">milestone 5</a> (b76) of the upcoming Java JDK 7. JDK 7 release is currently <a href="http://mail.openjdk.java.net/pipermail/jdk7-dev/2009-November/001054.html">scheduled</a> for September 2010. My standard IDE is eclipse but the current production version <a href="http://www.eclipse.org/downloads/">3.5 SR 1</a> support only Java up to JDK 6. I tried the new <a href="http://download.eclipse.org/e4/downloads/drops/S-1.0M2-200911201200/index.html">eclipse e4 1.0 milestone 2</a> (status: technical preview) which has JDK support up to JDK 7. You can define a JDK 7 as new JRE and create a new Java project with that JRE and compiler compliance level JDK 1.7. According to <a href="http://blogs.sun.com/darcy/entry/project_coin_milestone_5_netbeans">Joseph Darcy</a> from SUN is a <a href="http://bertram.netbeans.org/hudson/job/jdk7/">developer build</a> of Netbeans available with support for JDK 7. I tested with code from <a href="http://www.certpal.com/blogs/2009/11/coding-with-jdk7/">CertPal</a> which includes several features of JDK 7. Eclipse e4 still complain about compiler errors but the developer build of netbeans can compile and run the sample code. Check in netbeans under tools -> Java platform the availability of JDK 7 and create a new java project. Set in the java project under properties the source/binary format to jdk 1.7 (sources tab) and choose as java platform JDK 1.7 (libraries tab). On OpenJDK is a <a href="http://openjdk.java.net//projects/jdk7/milestones/">overview</a> of the current implemented features of JDK 7 in the M5 version. Mark Reinhold from sun <a href="http://blogs.sun.com/mr/entry/jdk7_m5">blogs</a> as well about the new features. A more complete list of features which was formerly planned shows <a href="http://tech.puredanger.com/java7">Alex Miller</a> in his blog.</p>
]]></content:encoded>
			<wfw:commentRss>http://ralf.schaeftlein.de/2009/11/23/ide-for-testing-jdk-1-7-features/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Spring 3.0 RC 2 and JSR-330 (Dependency Injection for Java)</title>
		<link>http://ralf.schaeftlein.de/2009/11/19/spring-3-0-rc-2-and-jsr-330-dependency-injection-for-java/</link>
		<comments>http://ralf.schaeftlein.de/2009/11/19/spring-3-0-rc-2-and-jsr-330-dependency-injection-for-java/#comments</comments>
		<pubDate>Thu, 19 Nov 2009 18:03:59 +0000</pubDate>
		<dc:creator>ralf</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[google]]></category>
		<category><![CDATA[guice]]></category>
		<category><![CDATA[spring]]></category>

		<guid isPermaLink="false">http://ralf.schaeftlein.de/?p=159</guid>
		<description><![CDATA[SpringSource has published release candidate 2 of the upcoming 3.0 release of their Spring Framework. New Feature is the compliance with JSR-330 (&#8220;Dependency Injection for Java&#8221;). The JSR was developed together by Google (for their Guice Framework and SpringSource (for their Spring Framework) and is finally approved since 14.10.2009. A little example shows how to [...]]]></description>
			<content:encoded><![CDATA[<p>SpringSource has <a href="http://blog.springsource.com/2009/11/13/spring-framework-3-0-rc2-released/">published</a> release candidate 2 of the upcoming 3.0 release of their Spring Framework. New Feature is the compliance with <a href="http://jcp.org/en/jsr/detail?id=330">JSR-330</a> (&#8220;Dependency Injection for Java&#8221;). The JSR was developed together by Google (for their <a href="http://code.google.com/p/google-guice/">Guice</a> Framework and SpringSource (for their <a href="http://www.springsource.org/documentation">Spring Framework</a>) and is finally approved since 14.10.2009.</p>
<p>A little example shows how to develop services with interfaces and implementations without dependencies to Spring Framework or Google Guice: </p>
<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</groupId>
	<artifactId>jsr330-sample</artifactId>
<packaging>jar</packaging>
	<name>jsr330-sample</name>
	<version>0.0.1-SNAPSHOT</version>
	<description>Sample App with Spring 3.0 RC 2 and JSR330</description>
<properties>
		<springVersion>3.0.0.RC2</springVersion>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${springVersion}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>${springVersion}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${springVersion}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-asm</artifactId>
			<version>${springVersion}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-expression</artifactId>
			<version>${springVersion}</version>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.7</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>javax.inject</groupId>
			<artifactId>javax.inject</artifactId>
			<version>1</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>jsr330-sample</finalName>
		<sourceDirectory>src/main/java</sourceDirectory>
		<testSourceDirectory>${basedir}/src/test/java</testSourceDirectory>

		<!-- 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>
<plugins>
<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>1.6</source>
					<target>1.6</target>
				</configuration>
			</plugin>
<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-eclipse-plugin</artifactId>
				<configuration>
					<downloadJavadocs>true</downloadJavadocs>
					<downloadSources>true</downloadSources>
					<excludes>
						<exclude>_svn</exclude>
						<exclude>.svn</exclude>
					</excludes>
				</configuration>
			</plugin>
<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-jar-plugin</artifactId>
				<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>
				<executions>
					<execution>
						<id>attach-sources</id>
<phase>verify</phase>
						<goals>
							<goal>jar</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>
</project>
</pre>
<p>
a simple encode/decode interface<br />
<P></p>
<pre name="code" class='java'>
package de.schaeftlein.dev.spring;

public interface Encryption
{
  String encode(String value);
  String decode(String value);
}
</pre>
<p>
a simple implementation for Encryption</p>
<p><pre name="code" class='java'>
package de.schaeftlein.dev.spring;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.inject.Named;

@Named // service name is the name of the class
public class URLEncoderEncyrption implements Encryption
{

  @Override
  public String decode(String value)
  {
    try
    {
      return URLDecoder.decode(value, "UTF-8");
    }
    catch (UnsupportedEncodingException e)
    {
      return null; // never happen
    }
  }

  @Override
  public String encode(String value)
  {
    try
    {
      return URLEncoder.encode(value, "UTF-8");
    }
    catch (UnsupportedEncodingException e)
    {
      return null; // never happen
    }
  }

}
</pre>
<p>
a more secure implementation for Encryption</p>
<p><pre name="code" class='java'>
package de.schaeftlein.dev.spring;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.inject.Named;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import com.sun.org.apache.xml.internal.security.utils.Base64;

@Named("secure") // named service bean
public class Base64Encyption implements Encryption
{
  private sun.misc.BASE64Encoder base64encoder;
  private SecretKey key;

  public Base64Encyption()
  {
    try
    {
      DESKeySpec keySpec = new DESKeySpec("Your secret Key phrase".getBytes("UTF8"));
      SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
      key = keyFactory.generateSecret(keySpec);
      base64encoder = new BASE64Encoder();
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
  }

  @Override
  public String decode(String input)
  {
    try
    {
      Cipher cipher = Cipher.getInstance("DES"); // cipher is not thread safe
      cipher.init(Cipher.DECRYPT_MODE, key);
      byte[] bOut = cipher.doFinal(Base64.decode(input.getBytes("UTF-8")));
      return new String(bOut, "UTF-8");
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
    return null;
  }

  @Override
  public String encode(String plainTextPassword)
  {
    try
    {
      byte[] cleartext = plainTextPassword.getBytes("UTF8");

      Cipher cipher = Cipher.getInstance("DES"); // cipher is not thread safe
      cipher.init(Cipher.ENCRYPT_MODE, key);
      return base64encoder.encode(cipher.doFinal(cleartext));
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
    return null;
  }

}
</pre>
<p>
a small interface for a service</p>
<p><pre name="code" class='java'>
package de.schaeftlein.dev.spring;

public interface SecureUtil
{
  void compareEncryption(String input);
}
</pre>
<p>
a implementation for our service</p>
<p><pre name="code" class='java'>
package de.schaeftlein.dev.spring;

import javax.inject.Inject;
import javax.inject.Named;

@Named("SecureUtil")
public class SecureUtilImpl implements SecureUtil
{
  @Inject // automatically set by DI framework
  @Named("secure") // get the namend bean
  private Encryption secureEncryption;

  @Inject // automatically set by DI framework
  @Named("URLEncoderEncyrption") // get the bean by its classname
  private Encryption unsecureEncryption;

  public void compareEncryption(String input){

    String encodedSecure = secureEncryption.encode(input);
    System.out.println("Secure encoded: "+encodedSecure);
    String encodeUnsecure = unsecureEncryption.encode(input);
    System.out.println("Unsecure encoded: "+encodeUnsecure);
    System.out.println("Secure decoded: "+secureEncryption.decode(encodedSecure));
    System.out.println("Unsecure decoded: "+unsecureEncryption.decode(encodeUnsecure));
  }
}
</pre>
<p>
finally a main class for testing</p>
<p><pre name="code" class='java'>
package de.schaeftlein.dev.spring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main
{

  /**
   * main method
   */
  public static void main(String[] args)
  {
    ApplicationContext ctx = new AnnotationConfigApplicationContext(Main.class.getPackage().getName()); // new way to get Application context without applicationContext.xml available
    SecureUtil util = ctx.getBean("SecureUtil", SecureUtil.class); // get bean with new generics method
    util.compareEncryption("an sample input string 1234567890");
  }

}
</pre>
<p>
output of our Main class</p>
<p><pre name="code" class='java'>
19.11.2009 18:56:03 org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@c1b531: startup date [Thu Nov 19 18:56:03 CET 2009]; root of context hierarchy
19.11.2009 18:56:03 org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor <init>
INFO: JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
19.11.2009 18:56:03 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@a83b8a: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,secure,SecureUtil,URLEncoderEncyrption]; root of factory hierarchy
Secure encoded: QDQvd4uK14YNUQ4uoqhqsZEMDDxUqJAMyisvZr2wsA2GyMC5tSEIiw==
Unsecure encoded: an+sample+input+string+1234567890
Secure decoded: an sample input string 1234567890
Unsecure decoded: an sample input string 1234567890
</pre>
]]></content:encoded>
			<wfw:commentRss>http://ralf.schaeftlein.de/2009/11/19/spring-3-0-rc-2-and-jsr-330-dependency-injection-for-java/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>ANT -version still shows 1.6.5 with installed version 1.7.x&#8230;</title>
		<link>http://ralf.schaeftlein.de/2009/10/15/ant-version-still-shows-1-6-5-with-installed-version-1-7-x/</link>
		<comments>http://ralf.schaeftlein.de/2009/10/15/ant-version-still-shows-1-6-5-with-installed-version-1-7-x/#comments</comments>
		<pubDate>Thu, 15 Oct 2009 12:31:45 +0000</pubDate>
		<dc:creator>ralf</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://ralf.schaeftlein.de/?p=116</guid>
		<description><![CDATA[Upgrading ant was in the past no big deal. Just download the binary archive, extract it and adopt the ANT_HOME environment variable. ANT_HOME is set to the extracted folder and PATH contains a entry %ANT_HOME%\bin. So PATH does not need to change during an ant update. I&#8217;m recently updated from ANT 1.6.5 to 1.7.1. and [...]]]></description>
			<content:encoded><![CDATA[<p>Upgrading ant was in the past no big deal. Just download the binary archive, extract it and adopt the ANT_HOME environment variable. ANT_HOME is set to the extracted folder and PATH contains a entry %ANT_HOME%\bin. So PATH  does not need to change during an ant update. I&#8217;m recently updated from ANT 1.6.5 to 1.7.1. and was a bit suprised by the output of ant -version. It still shows 1.6.5 as version. I checked the environment variables but everything was fine. The problem is that ANT batch files look in different folders according to the <a href="http://ant.apache.org/manual/running.html#libs">manual</a>. Prior to the ANT_HOME\lib folder will be the files in USER_HOME\.ant\lib be added to the classpath. This user home folder was on my machine still filled up with the jars from the 1.6.5 release. After deleting the contents show ant now the correct version. I understand the purpose of having additional libs available for own used tasks but the result behavior was annoying.   </p>
]]></content:encoded>
			<wfw:commentRss>http://ralf.schaeftlein.de/2009/10/15/ant-version-still-shows-1-6-5-with-installed-version-1-7-x/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Howto setup a OpenLDAP Server for Ubuntu 8.10</title>
		<link>http://ralf.schaeftlein.de/2009/02/04/howto-setup-a-openldap-server-for-ubuntu-810/</link>
		<comments>http://ralf.schaeftlein.de/2009/02/04/howto-setup-a-openldap-server-for-ubuntu-810/#comments</comments>
		<pubDate>Wed, 04 Feb 2009 10:34:34 +0000</pubDate>
		<dc:creator>ralf</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[ldap]]></category>
		<category><![CDATA[openldap]]></category>
		<category><![CDATA[ubuntu]]></category>

		<guid isPermaLink="false">http://ralf.schaeftlein.de/?p=75</guid>
		<description><![CDATA[Most enterprises use LDAP as interface to their company structure database. In the Microsoft world is Active Directory the implementation for LDAP. Under Linux is OpenLDAP the common choice for admins. Such LDAP directories are tree based. OpenLDAP is the reference implementation for LDAP v3. The JNDI API inside the Java SDK is usable as [...]]]></description>
			<content:encoded><![CDATA[<p>Most enterprises use LDAP as interface to their company structure database. In the Microsoft world is Active Directory the implementation for LDAP. Under Linux is <a href="http://www.openldap.org/">OpenLDAP</a> the common choice for admins. Such LDAP directories are tree based. OpenLDAP is the reference implementation for LDAP v3.</p>
<p>The <a href="http://java.sun.com/j2se/1.4.2/docs/guide/jndi/">JNDI API</a> inside the Java SDK is usable as implementation to access such LDAP directories. With <a href="http://www.springsource.org/ldap">Spring LDAP</a> is more sophisticated API available. </p>
<p>My first code sample works in the company against their OpenLDAP server. For security reasons is the access not possible from outside. So my JUNIT Tests was code red after running in my homeoffice. Maven standard is to run all test prior to build a package like a J2EE war or ear file. So i decided to setup a OpenLDAP server inside my ubuntu 8.10 server <a href="http://www.vmware.com/de/products/server/">vmware server</a> vm.</p>
<p>First step is to retrieve and install the openldap package as root:</p>
<p/>
<ul>
<li>sudo su -</li>
<li>apt-get install slapd ldap-utils nmap php5-ldap db4.2-util</li>
</ul>
<p/>
You have to set a password during installation for the OpenLDAP server. <strong>Keep that in mind!</strong><br />
Now run the configuration assistant:</p>
<p/>
<ul>
<li>dpkg-reconfigure slapd</li>
</ul>
<p>
Wizard steps:</p>
<ol>
<li>omit openldap server configuration? &#8211; no</li>
<li>dns domain name? vm.example.org</li>
<li>organization name? myCompany</li>
<li>database backend to use? hdb</li>
<li>do you want the database to be removed when slapd is purged? yes</li>
<li>may be the question: move old database? yes</li>
<li>administrator password? the same one as entered during installation</li>
<li>confirm password? see last step</li>
<li>allow LDAPv2 protocol? no</li>
</ol>
<p/>
Now edit the /etc/ldap/ldap.conf file for the client side configuration:</p>
<p/>
<pre>
ldap_version 3
URI ldap://localhost:389
SIZELIMIT 0
TIMELIMIT 0
DEREF never
BASE dc=vm,dc=example, dc=org
</pre>
<p/>
With the command &#8220;ldapsearch -x&#8221; you should see the following output:</p>
<p/>
<pre>
# extended LDIF
#
# LDAPv3
# base <dc=vm,dc=example, dc=org> (default) with scope subtree
# filter: (objectclass=*)
# requesting: ALL
#

# vm.example.org
dn: dc=vm,dc=example,dc=org
objectClass: top
objectClass: dcObject
objectClass: organization
o: myCompany
dc: vm

# admin, vm.example.org
dn: cn=admin,dc=vm,dc=example,dc=org
objectClass: simpleSecurityObject
objectClass: organizationalRole
cn: admin
description: LDAP administrator

# search result
search: 2
result: 0 Success

# numResponses: 3
# numEntries: 2
</pre>
<p/>
For easier admininstration exist a php admin ui called <a href="http://phpldapadmin.sourceforge.net/wiki/index.php/Main_Page">phpldapadmin</a> and can be installed with:</p>
<p/>
<ul>
<li>apt-get install phpldapadmin</li>
<li>ln -s /usr/share/phpldapadmin/ /var/www/phpldapadmin</li>
</ul>
<p/>
Open now the config file /etc/phpldapadmin/config.php with joe (a editor) and change the line with the ldap node info to:</p>
<p/>
<pre name="code" class="php">

/* Array of base DNs of your LDAP server. Leave this blank to have phpLDAPadmin
   auto-detect it for you. */
$ldapservers->SetValue($i,'server','base',array('dc=vm,dc=example,dc=org'));
...
$ldapservers->SetValue($i,'login','dn','cn=admin,dc=vm,dc=example,dc=org');
</pre>
<p/>
Check your PHP5 memory settings in /etc/php5/apache2/php.ini:</p>
<p/>
<pre>
memory_limit = 64M      ; Maximum amount of memory a script may consume (16MB)
</pre>
<p/>
Restart the apache to use this changed configuration</p>
<p/>
<ul>
<li>/etc/init.d/apache2 restart</li>
</ul>
<p/>
and go to:</p>
<p/>
<p>http://your.vm.ip/phpldapadmin</p>
<p/>
Click on the login link on the left side and enter as &#8220;login dn&#8221;:</p>
<p/>
<ul>
<li>cn=admin,dc=vm,dc=example,dc=org</li>
</ul>
<p/>
and your password in mind. First step is now to enter a &#8220;organisational unit&#8221;:</p>
<ul>
<li>click on the left side on the link beside the world icon &#8220;dc=vm&#8230;&#8221;</li>
<li>click on &#8220;create a child entry here&#8221;</li>
<li>choose &#8220;organisational unit&#8221; as template</li>
<li>enter &#8220;people&#8221; and click on &#8220;create object&#8221;</li>
<li>click on this new orginsational unit people in the tree</li>
<li>click on &#8220;create a child entry here&#8221;</li>
<li>choose &#8220;Address Book Entry (mozillaOrgPerson)&#8221; as template</li>
<li>enter &#8220;John&#8221; as &#8220;first name&#8221;</li>
<li>enter &#8220;Doe&#8221; as &#8220;last name&#8221;</li>
<li>go to common name (cn) and enter &#8220;John Doe&#8221;</li>
<li>click on &#8220;create object&#8221;</li>
</ul>
<p/>
Now check with &#8220;ldapsearch -x&#8221; if everything is ok:</p>
<p/>
<pre>
# extended LDIF
#
# LDAPv3
# base <dc=vm,dc=example, dc=org> (default) with scope subtree
# filter: (objectclass=*)
# requesting: ALL
#

# vm.example.org
dn: dc=vm,dc=example,dc=org
objectClass: top
objectClass: dcObject
objectClass: organization
o: myCompany
dc: vm

# admin, vm.example.org
dn: cn=admin,dc=vm,dc=example,dc=org
objectClass: simpleSecurityObject
objectClass: organizationalRole
cn: admin
description: LDAP administrator

# people, vm.example.org
dn: ou=people,dc=vm,dc=example,dc=org
objectClass: organizationalUnit
objectClass: top
ou: people

# John Doe, people, vm.example.org
dn: cn=John Doe,ou=people,dc=vm,dc=example,dc=org
objectClass: inetOrgPerson
objectClass: top
givenName: John
sn: Doe
cn: John Doe

# search result
search: 2
result: 0 Success

# numResponses: 5
# numEntries: 4
</pre>
<p>Your LDAP server is now running and you can easily configure it inside your favorite browser</p>
<p>
<img src="http://ralf.schaeftlein.com/images/ldap_tree.png" alt="LDAP Tree" /></p>
]]></content:encoded>
			<wfw:commentRss>http://ralf.schaeftlein.de/2009/02/04/howto-setup-a-openldap-server-for-ubuntu-810/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Dbunit with JUnit 4.x and Spring for testing Oracle DB Application</title>
		<link>http://ralf.schaeftlein.de/2009/01/05/dbunit-with-junit-4x-and-spring-for-testing-oracle-db-application/</link>
		<comments>http://ralf.schaeftlein.de/2009/01/05/dbunit-with-junit-4x-and-spring-for-testing-oracle-db-application/#comments</comments>
		<pubDate>Mon, 05 Jan 2009 17:59:23 +0000</pubDate>
		<dc:creator>ralf</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[dbunit]]></category>
		<category><![CDATA[oracle]]></category>
		<category><![CDATA[spring]]></category>

		<guid isPermaLink="false">http://ralf.schaeftlein.de/?p=62</guid>
		<description><![CDATA[DBUnit is very nice for testing database content changes made by an application. You define in XML the data including the structure of your tables (dataset.xml). Simple_Data is the name of the table and each column is a attribute in the xml doc with the content value e.g. id with value 1. The Getting Started [...]]]></description>
			<content:encoded><![CDATA[<p>DBUnit is very nice for testing database content changes made by an application. You define in XML the data including the structure of your tables (dataset.xml).</p>
<p><pre name="code" class='xml'>
<?xml version='1.0' encoding='UTF-8'?>
<dataset>
	<simple_data id="1" content="value_before"/>
</dataset>
</pre>
<p>
Simple_Data is the name of the table and each column is a attribute in the xml doc with the content value e.g. id with value 1.</p>
<p>
The <a href="http://dbunit.sourceforge.net/howto.html">Getting Started</a> of DBUnit work with JUnit 3.8 and self handling of the JDBC Connection.</p>
<p>
JUnit 4.x are more comfortable with annotations based test methods and Spring comes with dependency injection for separating<br />
configuration from implementation code.</p>
<p>
The following approach combines DBUnit with JUnit 4.4 and Spring 2.5.6 to test comfortable a Oracle 10g database.</p>
<p>
I use Maven 2.x to define the depending libraries used by the example (pom.xml):</p>
<p><pre name="code" class='xml'>
<?xml version="1.0" encoding="UTF-8"?>
<project
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<modelVersion>4.0.0</modelVersion>
	<groupId>de.schaeftlein.dev.dbunit</groupId>
	<artifactId>test-dbunit</artifactId>
	<name>test-dbunit</name>
	<version>0.0.1-SNAPSHOT</version>
	<description />
	<dependencies>
		<dependency>
			<groupId>org.dbunit</groupId>
			<artifactId>dbunit</artifactId>
			<version>2.4.2</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring</artifactId>
			<version>2.5.6</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.4</version>
		</dependency>
		<dependency>
			<groupId>commons-dbcp</groupId>
			<artifactId>commons-dbcp</artifactId>
			<version>1.2.2</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>2.5.6</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>1.5.6</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>log4j-over-slf4j</artifactId>
			<version>1.5.6</version>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.14</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>1.5.6</version>
		</dependency>
		<dependency>
			<groupId>com.oracle</groupId>
			<artifactId>ojdbc14</artifactId>
			<version>10.2.0.2.0</version>
		</dependency>
	</dependencies>
</project>
</pre>
<p>
Keep in mind that the Oracle JDBC Driver has to be downloaded <a href="http://www.oracle.com/technology/software/tech/java/sqlj_jdbc/htdocs/jdbc_10201.html">manually</a>.<br />
The public maven repos include only the Pom definition for the oracle driver. Generate with maven command line tool the eclipse project files:
<p>
<code>mvn clean eclipse:clean eclipse:eclipse</code></p>
<p>
The JDBC datasource is defined via Spring (applicationContext.xml):
<p><pre name="code" class='xml'>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
  <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
	destroy-method="close">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:@10.0.0.2:1521:orcl" />
<property name="username" value="your_user_name" />
<property name="password" value="your_password" />
  </bean>
</beans>
</pre>
<p>
Additionally we define the expected data as well in XML for DBUnit (expectedDataSet.xml):
<p>
<P></p>
<pre name="code" class='xml'>
<?xml version='1.0' encoding='UTF-8'?>
<dataset>
	<simple_data id="1" content="value_after"/>
</dataset>
</pre>
<p>
Now we can code our JUnit 4.x Test to
<ol>
<li>load data before the test method
<li>change the data via JDBC to emulate a application
<li>compare the changed data with expected data
<li>clean up the database
</ol>
<p><pre name="code" class='java'>
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:applicationContext.xml"})
public class TestDBUnitWithSpring {

	@Autowired
	private DataSource dataSource;

	@Before
	public void init() throws Exception{
		// insert data into db
		DatabaseOperation.CLEAN_INSERT.execute(getConnection(), getDataSet());
	}

	@After
	public void after() throws Exception{
		// insert data into db
		DatabaseOperation.DELETE_ALL.execute(getConnection(), getDataSet());
	}

	private IDatabaseConnection getConnection() throws Exception{
	// get connection
		Connection con = dataSource.getConnection();
		DatabaseMetaData  databaseMetaData = con.getMetaData();
		// oracle schema name is the user name
		IDatabaseConnection connection = new DatabaseConnection(con,databaseMetaData.getUserName().toUpperCase());
		DatabaseConfig config = connection.getConfig();
		// oracle 10g
		config.setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, new Oracle10DataTypeFactory());
		// receycle bin
		config.setFeature(DatabaseConfig.FEATURE_SKIP_ORACLE_RECYCLEBIN_TABLES, Boolean.TRUE);
		return connection;
	}

	private IDataSet getDataSet() throws Exception{
		// get insert data
		File file = new File("src/test/resources/dataset.xml");
		return new FlatXmlDataSet(file);
	}

	@Test
	public void testSQLUpdate() throws Exception{
		Connection con = dataSource.getConnection();
		Statement stmt = con.createStatement();
		// get current data
		ResultSet rst = stmt.executeQuery("select * from simple_data where id = 1");
		if(rst.next()){
			// from dataset.xml
			assertEquals("value_before", rst.getString("content"));
			rst.close();

			// update via sql
			int count = stmt.executeUpdate("update simple_data set content='value_after' where id=1");

			stmt.close();
			con.close();

			// expect only one row to be updated
			assertEquals("one row should be updated", 1, count);

			// Fetch database data after executing the code
			QueryDataSet databaseSet = new QueryDataSet(getConnection());
			// filter data
			databaseSet.addTable("simple_data", "select * from simple_data where id = 1");
			ITable actualTable = databaseSet.getTables()[0];

			// Load expected data from an XML dataset
			IDataSet expectedDataSet = new FlatXmlDataSet(new File("src/test/resources/expectedDataSet.xml"));
			ITable expectedTable = expectedDataSet.getTable("simple_data");

			// filter unnecessary columns of current data by xml definition
			actualTable = DefaultColumnFilter.includedColumnsTable(actualTable, expectedTable.getTableMetaData().getColumns());

			// Assert actual database table match expected table
			assertEquals(1,expectedTable.getRowCount());
			assertEquals(expectedTable.getRowCount(), actualTable.getRowCount());
			assertEquals(expectedTable.getValue(0, "content"), actualTable.getValue(0, "content"));

		} else {
			fail("no rows");
			rst.close();
			stmt.close();
			con.close();
		}

	}
}
</pre>
<p>
]]></content:encoded>
			<wfw:commentRss>http://ralf.schaeftlein.de/2009/01/05/dbunit-with-junit-4x-and-spring-for-testing-oracle-db-application/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

