<?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>REVERT TO CONSOLE &#187; Spring</title>
	<atom:link href="http://www.reverttoconsole.com/blog/category/spring/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.reverttoconsole.com</link>
	<description>for f in *;do echo &#124; sed &#039;i\rtc&#039; &#62;&#62; $f;done; java programming et al</description>
	<lastBuildDate>Thu, 25 Aug 2011 15:02:46 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3</generator>
		<item>
		<title>Mock Unit Testing Services and Daos with Mockito and Spring 3</title>
		<link>http://www.reverttoconsole.com/blog/spring/mock-unit-testing-services-and-daos-with-mockito-and-spring-3/</link>
		<comments>http://www.reverttoconsole.com/blog/spring/mock-unit-testing-services-and-daos-with-mockito-and-spring-3/#comments</comments>
		<pubDate>Mon, 09 May 2011 14:46:02 +0000</pubDate>
		<dc:creator>Priyatam</dc:creator>
				<category><![CDATA[Spring]]></category>
		<category><![CDATA[UnitTest]]></category>

		<guid isPermaLink="false">http://www.reverttoconsole.com/?p=984</guid>
		<description><![CDATA[If you haven&#8217;t been mocking yet, check this out. There are other tools in Groovy using DSLs but if you want to stick to Java, Mockito is by far the best BDD-style mock unit testing tool. Traditional examples provide a List mocking example or foo/bar example which I find it mostly annoying since it doesn&#8217;t [...]]]></description>
			<content:encoded><![CDATA[<p>If you haven&#8217;t been <em>mocking </em>yet, check <a href="http://www.mockito.org/">this </a>out. There are other tools in Groovy using DSLs but if you want to stick to Java, Mockito is by far the best BDD-style mock unit testing tool.  </p>
<p>Traditional examples provide a List mocking example or foo/bar example which I find it mostly annoying since it doesn&#8217;t teach you how to solve real problems. And the documentation is verbose and crams with unnecessary features confusing us further. In this tutorial, I&#8217;ll dive straight into a relevant example of mock testing Daos in Service layer. I&#8217;m not a big fan of Daos anymore (after the advent of JPA), however for the purposes of this tutorial, it&#8217;ll be easier to explain.</p>
<p>Consider a Profile entity (like facebook user profile) with daos/services: ProfileDao/JPAProfileDao, ProfileService/ProfileServiceImpl. To complicate things further, say you are using DTOs since it&#8217;s a client server app with a GWT front end. You might need a simple mapper class. Let&#8217;s call it ProfileMapper/ProfileMapperImpl. </p>
<pre>
@Service("profileService")
public class ProfileServiceImpl implements ProfileService {
	private final ProfileDao profileDao;
	private final ProfileMapper profileMapper;

	@Inject
	public ProfileServiceImpl(final ProfileDao profileDao, final ProfileMapper profileMapper) {
		this.profileDao = profileDao;
		this.profileMapper = profileMapper;
	}

	@Transactional
	public void create(ProfileDto profile) throws DuplicateProfileException {
		if (profile == null) {
			throw new IllegalArgumentException("profile cannot be null.");
		}

		Profile profile = profileMapper.toEntity(profile);
		// set default state as active
		profile .setIsActive(true);

		try {
			profileDao.save(profile);
		}
		catch (DuplicateKeyException e) {
			logger.warn("Unable to save profile with userId: " + profile.getUserId() + " already exists.");
			throw new DuplicateProfileException();
		}
		logger.debug("Profile saved successfully.");
	}

	@Transactional(readOnly = true)
	public ProfileDto read(String userId) throws InvalidProfileException {
		validateProfileInfo(userId);

		ProfileDto profileDto = null;
		Profile profile = profileDao.read(userId);
		if (profile != null) {
			profileDto = profileMapper.fromEntity(profile);
			logger.debug("Profile retrieved successfully.");
		}
		else {
			logger.debug("...");
		}
		return profileDto;
	}

	...
}
</pre>
<p>Now, in order to test ProfileService, you need to mock out ProfileMapper and ProfileDao, right? Let&#8217;s see how we do this in a simple JUnit 4.4+ test.</p>
<pre>
import static org.mockito.Mockito.*;

@RunWith(MockitoJUnitRunner.class)
public class ProfileServiceTest {

	@Mock
	ProfileDao profileDao;

	@Mock
	ProfileMapper profileMapper;

	// Can't use @InjectMocks because Mockito doesn't support constructor injection
	// As a workaround use @Before below to initialize service with stubs
	ProfileService profileService;

	@Before
	public void init() {
		profileService = new ProfileServiceImpl(profileDao, profileMapper);
	}

	@Test
	public void testRead() throws InvalidProfileException {
		// Simulate InvalidProfileException
		try {
			profileService.read("");
			fail(); // should never execute
		}
		catch (InvalidProfileException e) {
			e.getMessage(); // expected
		}

		// Given
		Profile profile = TestData.createTestProfile("userid"); // test utility to create a test Profile
		when(profileDao.read("userid")).thenReturn(profile);
		when(profileMapper.fromEntity(profile )).thenReturn(TestData.createTestProfileDto("userid"));

		// When
		ProfileDto dto = profileService.read("userid");

		// Then
		assertEquals(dto.getUserId(), "userid");
	}
}
</pre>
<p>Explanation:<br />
1) Wrapping your test with @RunWith(MockitoJUnitRunner.class) helps create the mock initialization through annotation scanning (@Mock, @InjectMocks)<br />
2) Add @Mock annotations for the components to mock. In this case profileDao, profileMapper<br />
3) As of 1.8.5, Mockito doesn&#8217;t provide @InjectMock with construction injection. @Before test initializer is a workaround to inject ProfileService with mocks. Note that this will not be required if ProfileService has setter/getter injection of dependencies. However, I prefer JSR330 construction injection which is a <a href="http://martinfowler.com/articles/injection.html#ConstructorVersusSetterInjection">best practice </a>.<br />
4) The actual @Test class with mockito stubs. Let&#8217;s dig deep into this.</p>
<p>As a template, it&#8217;s a good practice to view tests like a BDD style test. </p>
<pre>
// Given 

// When

// Then
</pre>
<p>The above template forces you to think on the explicit conditions during which we run our unit test.</p>
<p>Next, we need to figure out a way to stub our mock component&#8217;s methods,</p>
<pre>
when(operation).thenReturn(object)
</pre>
<p>In our example we want to mock profileDao.read(userId). So that translates to</p>
<pre>
when(profileDao.read("userid")).thenReturn(profile);
</pre>
<p>Note that we&#8217;re letting the mocked dao return a profile object that we just created in the previous step. This will be 50% of most of your mocking use cases.</p>
<p>The next common used use case is to simulate exceptions from the mocked classes. Consider a test for create(&#8230;) that simulates the DuplicateProfileException.          </p>
<pre>
@Test
	public void testCreateDuplicate() {
		// Given
		ProfileDto dto = TestData.createTestProfileDto("userid");
		Profile profile = TestData.createTestProfile("userid");
		when(profileMapper.toEntity(dto)).thenReturn(profile);
		doThrow(new DuplicateKeyException("duplicate profile")).when(profileDao).save(profile);

		// When
		try {
			profileService.create(dto);
			assertEquals(1, 2); // should never execute
		}
		// Then
		catch (DuplicateProfileException e) {
			e.getMessage();
		}
	}
</pre>
<p>Notice the line</p>
<pre>
doThrow(new DuplicateKeyException("duplicate profile")).when(profileDao).save(profile);
</pre>
<p>Quite simple, isn&#8217;t it? </p>
<p>If you&#8217;ve read so far, you can succuessfully write mock unit tests for 80% of your use cases. There are other advanced features like finding <a href="http://www.mockito.org/">redundant invocations</a>, spying on objects to simulate partial mocking, most of which I don&#8217;t see implementing for majority of my use cases. </p>

<span class="slashdigglicious">
<a href="http://slashdot.org/bookmark.pl?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fmock-unit-testing-services-and-daos-with-mockito-and-spring-3%2F&amp;title=Mock+Unit+Testing+Services+and+Daos+with+Mockito+and+Spring+3" title="Slashdot It!"><img src="http://slashdot.org/favicon.ico" height="16" width="16" alt="[Slashdot]" /></a>
<a href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fmock-unit-testing-services-and-daos-with-mockito-and-spring-3%2F&amp;title=Mock+Unit+Testing+Services+and+Daos+with+Mockito+and+Spring+3" title="Digg This Story"><img src="http://digg.com/favicon.ico" width="16" height="16" alt="[Digg]" /></a>
<a href="http://reddit.com/submit?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fmock-unit-testing-services-and-daos-with-mockito-and-spring-3%2F&amp;title=Mock+Unit+Testing+Services+and+Daos+with+Mockito+and+Spring+3" title="Reddit"><img src="http://reddit.com/favicon.ico" width="16" height="16" alt="[Reddit]" /></a>
<a href="http://del.icio.us/post?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fmock-unit-testing-services-and-daos-with-mockito-and-spring-3%2F&amp;title=Mock+Unit+Testing+Services+and+Daos+with+Mockito+and+Spring+3" title="Save to del.icio.us" onclick="window.open('http://del.icio.us/post?v=4&amp;noui&amp;jump=close&amp;url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fmock-unit-testing-services-and-daos-with-mockito-and-spring-3%2F&amp;title=Mock+Unit+Testing+Services+and+Daos+with+Mockito+and+Spring+3', 'delicious', 'toolbar=no,width=700,height=400'); return false;"><img src="http://images.del.icio.us/static/img/delicious.small.gif" width="16" height="16" alt="[del.icio.us]" /></a>
<a href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fmock-unit-testing-services-and-daos-with-mockito-and-spring-3%2F" title="Share on Facebook"><img src="http://www.facebook.com/favicon.ico" width="16" height="16" alt="[Facebook]" /></a>
<a href="http://technorati.com/faves?add=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fmock-unit-testing-services-and-daos-with-mockito-and-spring-3%2F" title="Add to my Technorati Favorites"><img src="http://technorati.com/favicon.ico" width="16" height="16" alt="[Technorati]" /></a>
<a href="http://www.google.com/bookmarks/mark?op=edit&amp;output=popup&amp;bkmk=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fmock-unit-testing-services-and-daos-with-mockito-and-spring-3%2F&amp;title=Mock+Unit+Testing+Services+and+Daos+with+Mockito+and+Spring+3" title="Save to Google Bookmarks"><img src="http://www.google.com/favicon.ico" width="16" height="16" alt="[Google]" /></a>
<a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fmock-unit-testing-services-and-daos-with-mockito-and-spring-3%2F&amp;title=Mock+Unit+Testing+Services+and+Daos+with+Mockito+and+Spring+3" title="Stumble it!"><img src="http://www.stumbleupon.com/favicon.ico" width="16" height="16" alt="[StumbleUpon]" /></a>
</span>]]></content:encoded>
			<wfw:commentRss>http://www.reverttoconsole.com/blog/spring/mock-unit-testing-services-and-daos-with-mockito-and-spring-3/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Understanding Spring Transaction Management</title>
		<link>http://www.reverttoconsole.com/blog/spring/understanding-spring-transaction-management/</link>
		<comments>http://www.reverttoconsole.com/blog/spring/understanding-spring-transaction-management/#comments</comments>
		<pubDate>Sun, 06 Mar 2011 16:17:24 +0000</pubDate>
		<dc:creator>Priyatam</dc:creator>
				<category><![CDATA[Spring]]></category>

		<guid isPermaLink="false">http://www.reverttoconsole.com/?p=990</guid>
		<description><![CDATA[This is a little wiki file I had for a long time while understanding how spring transactions worked. Time to put it in a blog. (Note: data is unprocessed) - Two types of transactions: Global and Local Transactions - PlatformTransactionManager is main interface in Spring - PROPAGATION_REQUIRED, PROPAGATION_SUPPORTS, PROPAGATION_MANDATORY, PROPAGATION_REQUIRES_NEW, PROPAGATION_NOT_SUPPORTED, PROPAGATION_NEVER, PROPAGATION_NESTED - ISOLATION_DEFAULT, [...]]]></description>
			<content:encoded><![CDATA[<p>This is a little wiki file I had for a long time while understanding how spring transactions worked. Time to put it in a blog. (Note: data is unprocessed)</p>
<p>- Two types of transactions: Global and Local Transactions<br />
- PlatformTransactionManager is main interface in Spring<br />
- <em>PROPAGATION_REQUIRED, PROPAGATION_SUPPORTS, PROPAGATION_MANDATORY, PROPAGATION_REQUIRES_NEW, PROPAGATION_NOT_SUPPORTED, PROPAGATION_NEVER, PROPAGATION_NESTED</em><br />
- ISOLATION_DEFAULT, ISOLATION_READ_UNCOMMITTED, ISOLATION_READ_COMMITTED, ISOLATION_REPEATABLE_READ, ISOLATION_SERIALIZABLE<br />
- Spring&#8217;s Declarative Transaction management. Can customize transactional behavior using AOP. Like custom behavior in case<br />
  of transaction rollback declaritvely.<br />
- How @Transactional works. The combination of AOP with transactional metadata yields an AOP proxy that uses a TransactionInterceptor in conjunction with an appropriate PlatformTransactionManager implementation to drive transactions around method invocations</p>
<p>- <strong>Steps when a method is invoked with @Transactional</strong><br />
 &#8212; Spring AOP kicks in, create proxy of the target. If nothing is configured JDDK dynamic proxy is created, but if aspectj is configured,<br />
    aspectJ proxy is created<br />
 &#8212; TransactionInterceptor kicks in the configured TransactionAdvice<br />
 &#8212; TransactionAdvice calls the underlying PlatformTransactionManager to acquire a new db connection<br />
 &#8212; Datasource is kicked in. If a connection pool is present, a conection is returned from the pool<br />
 &#8212; Method is invoked<br />
 &#8212; If no exceptions, great<br />
 &#8212; If exceptions are returned, apply rules to determine whether transaction should be rolled back. If yes, TransactionInterceptor will roll back<br />
    transaction<br />
 &#8212; Based on exceptions, PlatformTransactionManager either commits or rollsback transaction<br />
 &#8212; Release connection JDBC after transaction<br />
 &#8212; Return conenction to pool<br />
 &#8212; Return the method call</p>
<p>- Annotate @Transactional on classes and not interfaces because Java annotations are not inherited from interfaces means that if you are using class-based proxies or the weaving-based aspect then the transaction settings are not recognized by the proxying and weaving infrastructure, and the object will not be wrapped in a transactional proxy.</p>
<p>- When using proxies, you should apply the @Transactional annotation only to methods with public visibility.</p>
<p>- Spring AOP uses either JDK dynamic proxies or CGLIB to create the proxy for a given target object. If the target object to be proxied implements at least one interface then a JDK dynamic proxy will be used. If the target object does not implement any interfaces then a CGLIB proxy will be created.</p>
<p>- Using &#8216;proxy-target-class=&#8221;true&#8221;&#8216; on <tx:annotation-driven/>, <aop:aspectj-autoproxy/> or <aop:config/> elements will force the use of CGLIB proxies for all three of them.</p>
<p>- multiple transaction managers can be used and referred as @Transactional (&#8220;account&#8221;)</p>
<pre>
&lt;bean id=&quot;transactionManager1&quot; class=&quot;org.springframework.jdbc.DataSourceTransactionManager&quot;&gt;
    ...
   &lt;qualifier value=&quot;account&quot;/&gt;
&lt;/bean&gt;
</pre>
<p>- Programmatic transaction can be done by TransactionTemplate (callBack approach) or PlatformTransactionManager directly</p>
<p>JPA<br />
&#8212;</p>
<pre>
&lt;!-- Activates @PersistentContext --&gt;
&lt;bean class=&quot;org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor&quot; /&gt;
</pre>
<p>References:<br />
<a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/transaction.html">Spring Transaction Propogation</a><br />
<a href="http://stackoverflow.com/questions/tagged/transactions">Stack Overflow &#8220;transactions&#8221;</a><br />
<a href="http://www.ibm.com/developerworks/java/library/j-ts1/index.html">Transactional Pitfalls	</a>	</p>

<span class="slashdigglicious">
<a href="http://slashdot.org/bookmark.pl?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Funderstanding-spring-transaction-management%2F&amp;title=Understanding+Spring+Transaction+Management" title="Slashdot It!"><img src="http://slashdot.org/favicon.ico" height="16" width="16" alt="[Slashdot]" /></a>
<a href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Funderstanding-spring-transaction-management%2F&amp;title=Understanding+Spring+Transaction+Management" title="Digg This Story"><img src="http://digg.com/favicon.ico" width="16" height="16" alt="[Digg]" /></a>
<a href="http://reddit.com/submit?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Funderstanding-spring-transaction-management%2F&amp;title=Understanding+Spring+Transaction+Management" title="Reddit"><img src="http://reddit.com/favicon.ico" width="16" height="16" alt="[Reddit]" /></a>
<a href="http://del.icio.us/post?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Funderstanding-spring-transaction-management%2F&amp;title=Understanding+Spring+Transaction+Management" title="Save to del.icio.us" onclick="window.open('http://del.icio.us/post?v=4&amp;noui&amp;jump=close&amp;url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Funderstanding-spring-transaction-management%2F&amp;title=Understanding+Spring+Transaction+Management', 'delicious', 'toolbar=no,width=700,height=400'); return false;"><img src="http://images.del.icio.us/static/img/delicious.small.gif" width="16" height="16" alt="[del.icio.us]" /></a>
<a href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Funderstanding-spring-transaction-management%2F" title="Share on Facebook"><img src="http://www.facebook.com/favicon.ico" width="16" height="16" alt="[Facebook]" /></a>
<a href="http://technorati.com/faves?add=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Funderstanding-spring-transaction-management%2F" title="Add to my Technorati Favorites"><img src="http://technorati.com/favicon.ico" width="16" height="16" alt="[Technorati]" /></a>
<a href="http://www.google.com/bookmarks/mark?op=edit&amp;output=popup&amp;bkmk=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Funderstanding-spring-transaction-management%2F&amp;title=Understanding+Spring+Transaction+Management" title="Save to Google Bookmarks"><img src="http://www.google.com/favicon.ico" width="16" height="16" alt="[Google]" /></a>
<a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Funderstanding-spring-transaction-management%2F&amp;title=Understanding+Spring+Transaction+Management" title="Stumble it!"><img src="http://www.stumbleupon.com/favicon.ico" width="16" height="16" alt="[StumbleUpon]" /></a>
</span>]]></content:encoded>
			<wfw:commentRss>http://www.reverttoconsole.com/blog/spring/understanding-spring-transaction-management/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Spring Security 3 Unit Testing Example with DbUnit</title>
		<link>http://www.reverttoconsole.com/blog/spring/spring-security-3-unit-testing-example-with-dbunit/</link>
		<comments>http://www.reverttoconsole.com/blog/spring/spring-security-3-unit-testing-example-with-dbunit/#comments</comments>
		<pubDate>Wed, 18 Aug 2010 15:03:09 +0000</pubDate>
		<dc:creator>Priyatam</dc:creator>
				<category><![CDATA[Spring]]></category>
		<category><![CDATA[UnitTest]]></category>

		<guid isPermaLink="false">http://www.reverttoconsole.com/?p=701</guid>
		<description><![CDATA[This tutorial extends on the baseline laid by Spring Security Tutorial maven archetype. I&#8217;ve modified the spring security config file and will be unit testing a simple ProfileService (CRUD) on a Profile entity (User object). The tests include login/logout and spring services security unit testing. application-security.xml &#60;?xml version=&#34;1.0&#34; encoding=&#34;UTF-8&#34;?&#62; &#60;beans:beans xmlns=&#34;http://www.springframework.org/schema/security&#34; xmlns:beans=&#34;http://www.springframework.org/schema/beans&#34; xmlns:xsi=&#34;http://www.w3.org/2001/XMLSchema-instance&#34; xsi:schemaLocation=&#34;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd [...]]]></description>
			<content:encoded><![CDATA[<p>This tutorial extends on the baseline laid by Spring Security Tutorial maven <a href="http://mvnrepository.com/artifact/org.springframework.security/spring-security-samples-tutorial/3.0.5.RELEASE">archetype</a>.</p>
<p>I&#8217;ve modified the spring security config file and will be unit testing a simple ProfileService (CRUD) on a Profile entity (User object). The tests include login/logout and spring services security unit testing.</p>
<p>application-security.xml</p>
<pre>
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;

&lt;beans:beans
    xmlns=&quot;http://www.springframework.org/schema/security&quot;
    xmlns:beans=&quot;http://www.springframework.org/schema/beans&quot;
	xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
	xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans

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

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

http://www.springframework.org/schema/security/spring-security-3.0.xsd&quot;&gt;

	&lt;global-method-security pre-post-annotations=&quot;enabled&quot;/&gt;

	&lt;http use-expressions=&quot;true&quot;&gt;
		&lt;intercept-url pattern=&quot;/secure/extreme/**&quot; access=&quot;hasRole(&#039;ROLE_SUPERVISOR&#039;)&quot;/&gt;
		&lt;intercept-url pattern=&quot;/secure/**&quot; access=&quot;isAuthenticated()&quot; /&gt;
		&lt;intercept-url pattern=&quot;/**&quot; access=&quot;permitAll&quot; /&gt;
		&lt;form-login /&gt;
		&lt;logout /&gt;
		&lt;remember-me /&gt;

		&lt;!-- Uncomment to limit the number of sessions a user can have --&gt;
		&lt;session-management invalid-session-url=&quot;/timeout.jsp&quot;&gt;
			&lt;concurrency-control max-sessions=&quot;1&quot; error-if-maximum-exceeded=&quot;true&quot; /&gt;
		&lt;/session-management&gt;
	&lt;/http&gt;

	&lt;authentication-manager&gt;
		&lt;authentication-provider&gt;
			&lt;!--  &lt;password-encoder hash=&quot;md5&quot;/&gt; --&gt;
			&lt;user-service&gt;
				&lt;user name=&quot;admin&quot; password=&quot;admin&quot; authorities=&quot;ROLE_ADMIN, ROLE_USER&quot; /&gt;
				&lt;user name=&quot;user&quot; password=&quot;user&quot; authorities=&quot;ROLE_USER&quot; /&gt;
				&lt;user name=&quot;reports&quot; password=&quot;reports&quot; authorities=&quot;ROLE_REPORTS&quot; /&gt;
			&lt;/user-service&gt;
		&lt;/authentication-provider&gt;
	&lt;/authentication-manager&gt;	

&lt;/beans:beans&gt;
</pre>
<p>Base DB Unit Test with utils for Spring Security</p>
<pre>
import java.io.FileInputStream;
import java.sql.Connection;
import javax.inject.Inject;
import javax.sql.DataSource;
import org.apache.log4j.Logger;
import org.dbunit.database.*;
import org.dbunit.operation.DatabaseOperation;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.test.context.transaction.*;

/**
 * Base Test that wraps a DbUnit style Test case by inserting a sample testdata
 * on startup. Provides necessary functions to login/logout, add roles, etc
 */
public abstract class BaseSecurityTest {

	private static final Logger logger = Logger
			.getLogger(BaseSecurityTest.class);

	Connection con;
	IDatabaseConnection dbUnitCon;
	IDataSet dataSet;

	@Inject
	private DataSource dataSource;

	protected abstract String getTestClassname();

	@BeforeTransaction
	public void beforeTx() throws Exception {
		logger.debug("Opening Db Connection ... ");
		con = DataSourceUtils.getConnection(dataSource);
		dbUnitCon = new DatabaseConnection(con);
		dataSet = getDataSet(getTestClassname());

		DatabaseOperation.CLEAN_INSERT.execute(dbUnitCon, dataSet);
	}

	@AfterTransaction
	public void afterTx() throws Exception {
		logger.debug("Releasing Db Connection ...");
		DataSourceUtils.releaseConnection(con, dataSource);
	}

	protected IDataSet getDataSet(String name) throws Exception {
		return new FlatXmlDataSetBuilder().build(new FileInputStream(
				"src/test/resources/" + name + ".xml"));
	}

	protected void clearContext() {
		SecurityContextHolder.clearContext();
	}

	protected void login(String username, String password) {
		SecurityContextHolder.getContext().setAuthentication(
				new UsernamePasswordAuthenticationToken(username, password));

		logger.debug("User:" + username + " logged in");
	}

	protected String getLoginDetails() {
		Object principal = SecurityContextHolder.getContext()
				.getAuthentication().getPrincipal();

		if (principal instanceof UserDetails) {
			return ((UserDetails)principal).getUsername();
		}
		else {
			return principal.toString();
		}

	}
}
</pre>
<p>ProfileServiceTest</p>
<pre>
import static org.junit.Assert.assertEquals;
import java.util.List;
import javax.inject.Inject;
import org.apache.log4j.Logger;
import xxx.Profile;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
		&quot;classpath*:spring/applicationContext-core.xml&quot;,
		&quot;classpath*:spring/applicationContext-mail.xml&quot;,
		&quot;classpath*:spring/applicationContext-security.xml&quot; })
@TransactionConfiguration
@Transactional
public class ProfileServiceTest extends BaseSecurityTest {

	private static final Logger logger = Logger
			.getLogger(ProfileServiceTest.class);

	@Inject
	private ProfileService profileService;

	@Override
	protected String getTestClassname() {
		return &quot;ProfileServiceTest&quot;;
	}

	@Test
	public void testUserLogin() {
		login(&quot;admin&quot;, &quot;admin&quot;);
		String username = getLoginDetails();
		assertEquals(username, &quot;admin&quot;);

		login(&quot;user&quot;, &quot;user&quot;);
		String username2 = getLoginDetails();
		assertEquals(username2, &quot;user&quot;);

		login(&quot;reports&quot;, &quot;reports&quot;);
		String username3 = getLoginDetails();
		assertEquals(username3, &quot;reports&quot;);
	}

	@Test
	public void testRead() {

		// Test with role that has access to the service
		login(&quot;user&quot;, &quot;user&quot;);
		profileService.read(&quot;1&quot;);

		login(&quot;reports&quot;, &quot;reports&quot;);
		profileService.read(&quot;1&quot;);

		// Test with role that doesn&#039;t have access to the service
		login(&quot;admin&quot;, &quot;admin&quot;);
		try {
			profileService.read(&quot;1&quot;);
		}
		catch (AccessDeniedException e) {
			// Expected
			assert(true);
			return;
		}

		// it should not reach here
		assert(false);
	}

	@Test
	public void testFindProfiles() {
		List&lt;Profile&gt; list = profileService.FindProfiles();
		assertEquals(4, list.size());
	}

	@Test
	public void testFindProfileById() {
		List&lt;Profile&gt; list = profileService.findProfileById(&quot;123&quot;);
		assertEquals(1, list.size());
	}

	@Test
	public void testSave() {

		// Test with role that has access to the service
		login(&quot;admin&quot;, &quot;admin&quot;);
		Profile dummy = new Profile();
		profileService.save(dummy);		

		// Test with role that doesn&#039;t have access to the service
		login(&quot;reports&quot;, &quot;reports&quot;);
		try {
			profileService.save(dummy);
		}
		catch (AccessDeniedException e) {
			// Expected
			assert(true);
			return;
		}

		// it should not reach here
		assert(false);
	}
}
</pre>
<p>The Profile Service</p>
<pre>
public interface ProfileService {

	@PreAuthorize(&quot;hasRole(&#039;ROLE_USER&#039;) or hasRole(&#039;ROLE_REPORTS&#039;)&quot;)
	Profile read(String id);

	List&lt;Profile&gt; findProfiles();

	List&lt;Profile&gt; findProfileById(String Id);

	@PreAuthorize(&quot;hasRole(&#039;ROLE_ADMIN&#039;) or hasRole(&#039;ROLE_USER&#039;)&quot;)
	Profile save(Profile account);

	@PreAuthorize(&quot;hasRole(&#039;ROLE_ADMIN&#039;)&quot;)
	void delete();

}
</pre>

<span class="slashdigglicious">
<a href="http://slashdot.org/bookmark.pl?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fspring-security-3-unit-testing-example-with-dbunit%2F&amp;title=Spring+Security+3+Unit+Testing+Example+with+DbUnit" title="Slashdot It!"><img src="http://slashdot.org/favicon.ico" height="16" width="16" alt="[Slashdot]" /></a>
<a href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fspring-security-3-unit-testing-example-with-dbunit%2F&amp;title=Spring+Security+3+Unit+Testing+Example+with+DbUnit" title="Digg This Story"><img src="http://digg.com/favicon.ico" width="16" height="16" alt="[Digg]" /></a>
<a href="http://reddit.com/submit?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fspring-security-3-unit-testing-example-with-dbunit%2F&amp;title=Spring+Security+3+Unit+Testing+Example+with+DbUnit" title="Reddit"><img src="http://reddit.com/favicon.ico" width="16" height="16" alt="[Reddit]" /></a>
<a href="http://del.icio.us/post?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fspring-security-3-unit-testing-example-with-dbunit%2F&amp;title=Spring+Security+3+Unit+Testing+Example+with+DbUnit" title="Save to del.icio.us" onclick="window.open('http://del.icio.us/post?v=4&amp;noui&amp;jump=close&amp;url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fspring-security-3-unit-testing-example-with-dbunit%2F&amp;title=Spring+Security+3+Unit+Testing+Example+with+DbUnit', 'delicious', 'toolbar=no,width=700,height=400'); return false;"><img src="http://images.del.icio.us/static/img/delicious.small.gif" width="16" height="16" alt="[del.icio.us]" /></a>
<a href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fspring-security-3-unit-testing-example-with-dbunit%2F" title="Share on Facebook"><img src="http://www.facebook.com/favicon.ico" width="16" height="16" alt="[Facebook]" /></a>
<a href="http://technorati.com/faves?add=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fspring-security-3-unit-testing-example-with-dbunit%2F" title="Add to my Technorati Favorites"><img src="http://technorati.com/favicon.ico" width="16" height="16" alt="[Technorati]" /></a>
<a href="http://www.google.com/bookmarks/mark?op=edit&amp;output=popup&amp;bkmk=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fspring-security-3-unit-testing-example-with-dbunit%2F&amp;title=Spring+Security+3+Unit+Testing+Example+with+DbUnit" title="Save to Google Bookmarks"><img src="http://www.google.com/favicon.ico" width="16" height="16" alt="[Google]" /></a>
<a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fspring-security-3-unit-testing-example-with-dbunit%2F&amp;title=Spring+Security+3+Unit+Testing+Example+with+DbUnit" title="Stumble it!"><img src="http://www.stumbleupon.com/favicon.ico" width="16" height="16" alt="[StumbleUpon]" /></a>
</span>]]></content:encoded>
			<wfw:commentRss>http://www.reverttoconsole.com/blog/spring/spring-security-3-unit-testing-example-with-dbunit/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Custom Logout Filter handler in Spring 3</title>
		<link>http://www.reverttoconsole.com/blog/spring/custom-logout-filter-handler-in-spring-3/</link>
		<comments>http://www.reverttoconsole.com/blog/spring/custom-logout-filter-handler-in-spring-3/#comments</comments>
		<pubDate>Thu, 04 Mar 2010 22:06:37 +0000</pubDate>
		<dc:creator>Priyatam</dc:creator>
				<category><![CDATA[Spring]]></category>

		<guid isPermaLink="false">http://www.reverttoconsole.com/?p=668</guid>
		<description><![CDATA[Spring Security provides comprehensive support for adding custom handlers for logout/login. The default logout simply logs the user out and goes to the login page. What if the application needs to determine the user&#8217;s role and redirect to a separate screen? For example, for an admin, a custom logout screen. What if the user is [...]]]></description>
			<content:encoded><![CDATA[<p>Spring Security provides comprehensive support for adding custom handlers for logout/login. The default logout simply logs the user out and goes to the login page. What if the application needs to determine the user&#8217;s role and redirect to a separate screen? For example, for an admin, a custom logout screen. What if the user is automatically logged out after 10 mins of user inactivity? You don&#8217;t want the user to see a login screen without any message on it. That&#8217;s bad. </p>
<p>Here&#8217;s an example demonstrating a custom logout handler using Spring 3 security module. The code has some incompatibility issues with Spring 2 as Spring 3 Security is not 100% backward compatibility.</p>
<p>Sample User</p>
<pre>
public class User extends org.springframework.security.core.userdetails.User {
 // Stuff
}
</pre>
<p>Custom Filter Handler</p>
<pre>
import java.io.IOException;

import javax.annotation.PostConstruct;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.logout.LogoutFilter;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;

import xxx.model.User;

public class LogoutFilterWrapper
	implements Filter {

	private String logoutSuccessfulUrl;

	private String logoutSuccessfulUrlAdmin;

	private String logoutSuccessfulInactivityUrl;

	private LogoutFilter filter;

	@PostConstruct
	protected void initialize() {

		final SecurityContextLogoutHandler context = new SecurityContextLogoutHandler();
		context.setInvalidateHttpSession( true );
		this.filter =
			new LogoutFilter( new CustomLogoutSuccessHandler(), new LogoutHandler[] { context } );
	}

	public void setLogoutSuccessfulUrl(
		String inUrl ) {

		this.logoutSuccessfulUrl = inUrl;
	}

	public void setLogoutSuccessfulUrlAdmin(
		String inUrl ) {

		this.logoutSuccessfulUrlAdmin = inUrl;
	}

	public void setLogoutSuccessfulUrlInactivity(
		String inUrl ) {

		this.logoutSuccessfulInactivityUrl = inUrl;
	}

	public final void init(
		FilterConfig inFilterConfig )
		throws ServletException {

		this.filter.init( inFilterConfig );
	}

	public final void destroy() {

		this.filter.destroy();
	}

	public final void doFilter(
		ServletRequest inRequest,
		ServletResponse inResponse,
		FilterChain inChain )
		throws IOException, ServletException {

		this.filter.doFilter( inRequest, inResponse, inChain );
	}

	/**
	 * Success Handler
	 */
	private class CustomLogoutSuccessHandler
		implements LogoutSuccessHandler {

		private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

		@Override
		public void onLogoutSuccess(
			HttpServletRequest request,
			HttpServletResponse response,
			Authentication authentication )
			throws IOException, ServletException {

			String targetUrl = "";
			User principal = null;

			if ( authentication != null ) {
				if ( !(authentication.getPrincipal() instanceof User) ) {
					throw new IllegalArgumentException( "Invalid security principal type!" );
				}
				principal = (User) authentication.getPrincipal();
			}

			if ( principal == null ) {
				throw new IllegalStateException( "Security principal is not initialized!" );
			}

			final String loginUrl =
				principal.isAdministrator() ? LogoutFilterWrapper.this.logoutSuccessfulUrlAdmin
					: LogoutFilterWrapper.this.logoutSuccessfulUrl;

			final String timeoutUrl =
				LogoutFilterWrapper.this.logoutSuccessfulInactivityUrl
					+ "?login="
					+ request.getContextPath()
					+ loginUrl;

			targetUrl = request.getQueryString().contains( "timeout=true" ) ? timeoutUrl : loginUrl;

			redirectStrategy.sendRedirect( request, response, targetUrl );
		}
	}
}
</pre>
<p>Spring-config</p>
<pre>
&lt;!-- Register a custom logout filter --&gt;
&lt;beans:bean id=&quot;customLogoutFilter&quot; class=&quot;com.cramer.srf.security.LogoutFilterWrapper&quot;&gt;
    &lt;beans:property name=&quot;logoutSuccessfulUrl&quot; value=&quot;/public/auth/login.htmlx&quot; /&gt;
    &lt;beans:property name=&quot;logoutSuccessfulUrlAdmin&quot; value=&quot;/public/auth/admlogin.htmlx&quot; /&gt;
    &lt;beans:property name=&quot;logoutSuccessfulUrlInactivity&quot; value=&quot;/public/auth/timedout.htmlx&quot; /&gt;
&lt;/beans:bean&gt;
</pre>

<span class="slashdigglicious">
<a href="http://slashdot.org/bookmark.pl?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fcustom-logout-filter-handler-in-spring-3%2F&amp;title=Custom+Logout+Filter+handler+in+Spring+3" title="Slashdot It!"><img src="http://slashdot.org/favicon.ico" height="16" width="16" alt="[Slashdot]" /></a>
<a href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fcustom-logout-filter-handler-in-spring-3%2F&amp;title=Custom+Logout+Filter+handler+in+Spring+3" title="Digg This Story"><img src="http://digg.com/favicon.ico" width="16" height="16" alt="[Digg]" /></a>
<a href="http://reddit.com/submit?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fcustom-logout-filter-handler-in-spring-3%2F&amp;title=Custom+Logout+Filter+handler+in+Spring+3" title="Reddit"><img src="http://reddit.com/favicon.ico" width="16" height="16" alt="[Reddit]" /></a>
<a href="http://del.icio.us/post?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fcustom-logout-filter-handler-in-spring-3%2F&amp;title=Custom+Logout+Filter+handler+in+Spring+3" title="Save to del.icio.us" onclick="window.open('http://del.icio.us/post?v=4&amp;noui&amp;jump=close&amp;url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fcustom-logout-filter-handler-in-spring-3%2F&amp;title=Custom+Logout+Filter+handler+in+Spring+3', 'delicious', 'toolbar=no,width=700,height=400'); return false;"><img src="http://images.del.icio.us/static/img/delicious.small.gif" width="16" height="16" alt="[del.icio.us]" /></a>
<a href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fcustom-logout-filter-handler-in-spring-3%2F" title="Share on Facebook"><img src="http://www.facebook.com/favicon.ico" width="16" height="16" alt="[Facebook]" /></a>
<a href="http://technorati.com/faves?add=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fcustom-logout-filter-handler-in-spring-3%2F" title="Add to my Technorati Favorites"><img src="http://technorati.com/favicon.ico" width="16" height="16" alt="[Technorati]" /></a>
<a href="http://www.google.com/bookmarks/mark?op=edit&amp;output=popup&amp;bkmk=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fcustom-logout-filter-handler-in-spring-3%2F&amp;title=Custom+Logout+Filter+handler+in+Spring+3" title="Save to Google Bookmarks"><img src="http://www.google.com/favicon.ico" width="16" height="16" alt="[Google]" /></a>
<a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fcustom-logout-filter-handler-in-spring-3%2F&amp;title=Custom+Logout+Filter+handler+in+Spring+3" title="Stumble it!"><img src="http://www.stumbleupon.com/favicon.ico" width="16" height="16" alt="[StumbleUpon]" /></a>
</span>]]></content:encoded>
			<wfw:commentRss>http://www.reverttoconsole.com/blog/spring/custom-logout-filter-handler-in-spring-3/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Generic Entity Converter for JSF / Spring / JPA</title>
		<link>http://www.reverttoconsole.com/blog/jsf/generic-entity-converter-for-jsf-spring-jpa/</link>
		<comments>http://www.reverttoconsole.com/blog/jsf/generic-entity-converter-for-jsf-spring-jpa/#comments</comments>
		<pubDate>Tue, 28 Apr 2009 13:27:01 +0000</pubDate>
		<dc:creator>Priyatam</dc:creator>
				<category><![CDATA[JSF]]></category>
		<category><![CDATA[Spring]]></category>

		<guid isPermaLink="false">http://www.reverttoconsole.com/?p=330</guid>
		<description><![CDATA[If you&#8217;ve come across Seam&#8217;s &#60;s:convertEntity&#62; and wondered why isn&#8217;t one there for JSF, here you go: Before using this, you should&#8217;ve designed your domain model to extend a Base Class (do it, it&#8217;s a good practice). In my case, I have BaseIdentityEntity which has an @Id, @Version properties import java.io.Serializable; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; [...]]]></description>
			<content:encoded><![CDATA[<p>If you&#8217;ve come across Seam&#8217;s &lt;s:convertEntity&gt; and wondered why isn&#8217;t one there for JSF, here you go:</p>
<p>Before using this, you should&#8217;ve designed your domain model to extend a Base Class (do it, it&#8217;s a good practice). In my case, I have BaseIdentityEntity which has an @Id, @Version properties</p>
<pre>
<pre>
import java.io.Serializable;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import xxx.model.BaseIdentityEntity;

/**
* Generic Entity Converter for any Entity that extends BaseIdentityEntity
*
*/
@Service("entityConverter")
public class EntityConverter implements Converter, Serializable {
	static Logger log = Logger.getLogger(EntityConverter.class);
	private static final long serialVersionUID = -5137676309479323480L;

	@PersistenceContext
	protected EntityManager entityManager;

	@SuppressWarnings("unchecked")
	public Object getAsObject(FacesContext facesContext, UIComponent component,
			String value) throws ConverterException {
		BaseIdentityEntity entity;
		if (value == null) {
			entity = null;
		} else {
			Integer id = new Integer(value);
			entity = (BaseIdentityEntity) entityManager.find(getClazz(
					facesContext, component), id);
			if (entity == null) {
				log.debug("There is no entity with id:  " + id);
				//throw new IllegalArgumentException("There is no entity with id:  " + id);
			}
		}
		return entity;
	}

	public String getAsString(FacesContext facesContext, UIComponent component,
			Object value) throws ConverterException {
		if (value != null &#038;&#038; !(value instanceof BaseIdentityEntity)) {
			throw new IllegalArgumentException(
					"This converter only handles instances of BaseIdentityEntity");
		}
		if (value == null) {
			return "";
		}
		if (value instanceof String) {
			return (String) value;
		}
		BaseIdentityEntity entity = (BaseIdentityEntity) value;
		return entity.getId() == null ? "" : entity.getId().toString();
	}

	// Gets the class corresponding to the context in jsf page
	@SuppressWarnings("unchecked")
	private Class getClazz(FacesContext facesContext, UIComponent component) {
		return component.getValueExpression("value").getType(facesContext.getELContext());
	}

}
</pre>
</pre>
<p>You don&#8217;t have to add any configuration in the taglibs since Spring&#8217;s @Service tag makes the converter a managed bean and you can reference it directly in jsf.</p>
<p>Usage: (Using JSF tomahawk here, but works for any jsf component library)</p>
<pre>
<pre>
&lt;h:selectOneMenu value=&quot;#{mycontroller.foo}&quot; converter=&quot;#{enumConverter}&quot;&gt;
	&lt;h:selectItems value=&quot;#{mycontroller.foos}&quot; var=&quot;element&quot;
	itemLabel=&quot;#{element}&quot; itemValue=&quot;#{element}&quot; /&gt;
&lt;/h:selectOneMenu&gt;
</pre>
</pre>

<span class="slashdigglicious">
<a href="http://slashdot.org/bookmark.pl?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fjsf%2Fgeneric-entity-converter-for-jsf-spring-jpa%2F&amp;title=Generic+Entity+Converter+for+JSF+%2F+Spring+%2F+JPA" title="Slashdot It!"><img src="http://slashdot.org/favicon.ico" height="16" width="16" alt="[Slashdot]" /></a>
<a href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fjsf%2Fgeneric-entity-converter-for-jsf-spring-jpa%2F&amp;title=Generic+Entity+Converter+for+JSF+%2F+Spring+%2F+JPA" title="Digg This Story"><img src="http://digg.com/favicon.ico" width="16" height="16" alt="[Digg]" /></a>
<a href="http://reddit.com/submit?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fjsf%2Fgeneric-entity-converter-for-jsf-spring-jpa%2F&amp;title=Generic+Entity+Converter+for+JSF+%2F+Spring+%2F+JPA" title="Reddit"><img src="http://reddit.com/favicon.ico" width="16" height="16" alt="[Reddit]" /></a>
<a href="http://del.icio.us/post?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fjsf%2Fgeneric-entity-converter-for-jsf-spring-jpa%2F&amp;title=Generic+Entity+Converter+for+JSF+%2F+Spring+%2F+JPA" title="Save to del.icio.us" onclick="window.open('http://del.icio.us/post?v=4&amp;noui&amp;jump=close&amp;url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fjsf%2Fgeneric-entity-converter-for-jsf-spring-jpa%2F&amp;title=Generic+Entity+Converter+for+JSF+%2F+Spring+%2F+JPA', 'delicious', 'toolbar=no,width=700,height=400'); return false;"><img src="http://images.del.icio.us/static/img/delicious.small.gif" width="16" height="16" alt="[del.icio.us]" /></a>
<a href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fjsf%2Fgeneric-entity-converter-for-jsf-spring-jpa%2F" title="Share on Facebook"><img src="http://www.facebook.com/favicon.ico" width="16" height="16" alt="[Facebook]" /></a>
<a href="http://technorati.com/faves?add=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fjsf%2Fgeneric-entity-converter-for-jsf-spring-jpa%2F" title="Add to my Technorati Favorites"><img src="http://technorati.com/favicon.ico" width="16" height="16" alt="[Technorati]" /></a>
<a href="http://www.google.com/bookmarks/mark?op=edit&amp;output=popup&amp;bkmk=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fjsf%2Fgeneric-entity-converter-for-jsf-spring-jpa%2F&amp;title=Generic+Entity+Converter+for+JSF+%2F+Spring+%2F+JPA" title="Save to Google Bookmarks"><img src="http://www.google.com/favicon.ico" width="16" height="16" alt="[Google]" /></a>
<a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fjsf%2Fgeneric-entity-converter-for-jsf-spring-jpa%2F&amp;title=Generic+Entity+Converter+for+JSF+%2F+Spring+%2F+JPA" title="Stumble it!"><img src="http://www.stumbleupon.com/favicon.ico" width="16" height="16" alt="[StumbleUpon]" /></a>
</span>]]></content:encoded>
			<wfw:commentRss>http://www.reverttoconsole.com/blog/jsf/generic-entity-converter-for-jsf-spring-jpa/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Spring Integration Presentation with Mark Fisher</title>
		<link>http://www.reverttoconsole.com/blog/spring/spring-integration-presentation-with-mark-fischer/</link>
		<comments>http://www.reverttoconsole.com/blog/spring/spring-integration-presentation-with-mark-fischer/#comments</comments>
		<pubDate>Mon, 21 Jul 2008 20:39:30 +0000</pubDate>
		<dc:creator>Priyatam</dc:creator>
				<category><![CDATA[Spring]]></category>

		<guid isPermaLink="false">http://reverttoconsole.com/?p=204</guid>
		<description><![CDATA[I had a chance to attend Mark Fisher&#8216;s presentations a couple of times before at NEJUG. This time around, it was a local Java Meetup group in Cambridge. He&#8217;s a very humble and knowledgeable guy about a lot of things, from Spring to Hibernate to Seam, to Scala &#38; MDA! With a brief introduction on [...]]]></description>
			<content:encoded><![CDATA[<p>I had a chance to attend<a href="http://www.springsource.com/people/mfisher"> Mark Fisher</a>&#8216;s presentations a couple of times before at NEJUG. This time around, it <img class="alignright" style="margin: 10px; float: right;" src="http://farm4.static.flickr.com/3161/2691540718_591a73dcbf_m.jpg" alt="" width="180" height="240" />was a local Java Meetup group in Cambridge. He&#8217;s a very humble and knowledgeable guy about a lot of things, from Spring to Hibernate to Seam, to <a href="http://www.scala-lang.org/">Scala</a> &amp; MDA!</p>
<p>With a brief introduction on Spring, an <a href="http://www.springframework.org/spring-integration" target="_blank">overview of Spring Integration</a> was covered, the 1.0 version of which is due in a couple of months from now (latest is 1.0 Milestone 5). I haven&#8217;t coded on JMS Messaging or worked on any of the open source EAI/ESB infrastructure for a long time, so I&#8217;ll keep this post relatively small.</p>
<p>If you&#8217;re familiar with EAI Patterns, and have been using Spring for a while, Spring Integration should feel like a breeze, a clean API working around already known concepts &#8212; Message, Message Channel, Endpoint, Pipes &amp; Filters, you get the drift. A much simpler model compared to existing proprietary approaches. Read the <a href="http://static.springframework.org/spring-integration/reference/htmlsingle/spring-integration-reference.html#overview-goalsandprinciples">goals and principles</a>. Spring&#8217;s annotation approach to wire end points, a router or even a splitter is pretty cool when combined with Spring&#8217;s <a href="http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/stereotype/Component.html">Component</a> Scanner annotation. The recent release also includes several default adapters included (Source and target implementations for JMS, Files, Streams, and Spring ApplicationEvents.)</p>
<p>For a deeper understanding and hand&#8217;s on code, I&#8217;d recommend, go through the <a href="http://static.springframework.org/spring-integration/reference/htmlsingle/spring-integration-reference.html#samples-cafe">Cafe Sample</a>. It&#8217;s quite self explainatory and is easy to implement one.</p>
<p>On a last note, I think &#8220;Spring Integration&#8221; is a such a confusing name. A google search results in all other integration results, not necessarily Spring&#8217;s EAI. &#8220;integration&#8221;. Perhaps it should have been named <em>Spring EAI </em>for simplicity sake.</p>
<p>Resources:-</p>
<p><a href="http://www.enterpriseintegrationpatterns.com/">EAI Patterns </a>home<a href="http://www.eaipatterns.com/ramblings.html"><br />
Greg&#8217;s Ramblings</a><br />
<a href="http://en.wikipedia.org/wiki/Enterprise_application_integration">EAI Wiki</a><br />
<a href="http://www.manageability.org/blog/stuff/open-source-messaging-integration-transformation-routing-java">Open source EAI </a>Tools</p>

<span class="slashdigglicious">
<a href="http://slashdot.org/bookmark.pl?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fspring-integration-presentation-with-mark-fischer%2F&amp;title=Spring+Integration+Presentation+with+Mark+Fisher" title="Slashdot It!"><img src="http://slashdot.org/favicon.ico" height="16" width="16" alt="[Slashdot]" /></a>
<a href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fspring-integration-presentation-with-mark-fischer%2F&amp;title=Spring+Integration+Presentation+with+Mark+Fisher" title="Digg This Story"><img src="http://digg.com/favicon.ico" width="16" height="16" alt="[Digg]" /></a>
<a href="http://reddit.com/submit?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fspring-integration-presentation-with-mark-fischer%2F&amp;title=Spring+Integration+Presentation+with+Mark+Fisher" title="Reddit"><img src="http://reddit.com/favicon.ico" width="16" height="16" alt="[Reddit]" /></a>
<a href="http://del.icio.us/post?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fspring-integration-presentation-with-mark-fischer%2F&amp;title=Spring+Integration+Presentation+with+Mark+Fisher" title="Save to del.icio.us" onclick="window.open('http://del.icio.us/post?v=4&amp;noui&amp;jump=close&amp;url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fspring-integration-presentation-with-mark-fischer%2F&amp;title=Spring+Integration+Presentation+with+Mark+Fisher', 'delicious', 'toolbar=no,width=700,height=400'); return false;"><img src="http://images.del.icio.us/static/img/delicious.small.gif" width="16" height="16" alt="[del.icio.us]" /></a>
<a href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fspring-integration-presentation-with-mark-fischer%2F" title="Share on Facebook"><img src="http://www.facebook.com/favicon.ico" width="16" height="16" alt="[Facebook]" /></a>
<a href="http://technorati.com/faves?add=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fspring-integration-presentation-with-mark-fischer%2F" title="Add to my Technorati Favorites"><img src="http://technorati.com/favicon.ico" width="16" height="16" alt="[Technorati]" /></a>
<a href="http://www.google.com/bookmarks/mark?op=edit&amp;output=popup&amp;bkmk=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fspring-integration-presentation-with-mark-fischer%2F&amp;title=Spring+Integration+Presentation+with+Mark+Fisher" title="Save to Google Bookmarks"><img src="http://www.google.com/favicon.ico" width="16" height="16" alt="[Google]" /></a>
<a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fspring-integration-presentation-with-mark-fischer%2F&amp;title=Spring+Integration+Presentation+with+Mark+Fisher" title="Stumble it!"><img src="http://www.stumbleupon.com/favicon.ico" width="16" height="16" alt="[StumbleUpon]" /></a>
</span>]]></content:encoded>
			<wfw:commentRss>http://www.reverttoconsole.com/blog/spring/spring-integration-presentation-with-mark-fischer/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Automated Unit Testing with DBUnit, Hsqldb in Spring &amp; Hibernate projects</title>
		<link>http://www.reverttoconsole.com/blog/hibernate-jpa/automated-unit-testing-with-dbunit-hsqldb-in-spring-hibernate-projects/</link>
		<comments>http://www.reverttoconsole.com/blog/hibernate-jpa/automated-unit-testing-with-dbunit-hsqldb-in-spring-hibernate-projects/#comments</comments>
		<pubDate>Sat, 07 Jun 2008 23:16:11 +0000</pubDate>
		<dc:creator>Priyatam</dc:creator>
				<category><![CDATA[Hibernate/JPA]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[UnitTest]]></category>
		<category><![CDATA[hsqldb]]></category>

		<guid isPermaLink="false">http://reverttoconsole.com/archives/157</guid>
		<description><![CDATA[If your project has a lot of unit testing in Java and you use continuous builds (CruiseControl) to automate, it is often difficult to automate tests which connect to Database (Dao and integration tests). For most companies, having a dedicated Oracle schema for testing is expensive. Also, sometimes, developers need their own instances of schemas [...]]]></description>
			<content:encoded><![CDATA[<p>If your project has a lot of unit testing in Java and you use continuous builds (CruiseControl) to automate, it is often difficult to automate tests which connect to Database (Dao and integration tests). For most companies,  having a dedicated Oracle schema for testing is expensive. Also, sometimes, developers need their own instances of schemas to test on, which again is not possible with a corporate DBA on Oracle.  Obviously writing unit tests connecting to the same instance where dev environment is setup is extremely unpleasant.</p>
<p>What do you do then?</p>
<p>Welcome to <a href="http://schemamule.sourceforge.net/index.html">Schemamule</a>. It&#8217;s a tiny jar file and has a single ant task which copies the entire Oracle Schema and generates a Hsqldb database. <strong>YES. </strong>It replicates an entire Oracle Schema into a hsqldb in seconds! You can either use it as an in memory database for your automated unit testing or as dev only local database for unit testing. For more details, read the original blog <a href="http://www.moseshohman.com/blog/2006/05/23/schemamule-10-released/">here</a>.</p>
<p>Let me iterate the advantages:-</p>
<p>&#8211; Can write database dependent test cases<br />
&#8211; Need not connect to a network for running tests<br />
&#8211; Database tests run at blazing speed, as now they&#8217;re on hsqldb</p>
<p>I worked with one of the developers &#8212; Rhett Sutphin, in my earlier project. He&#8217;s a brilliant programmer. I&#8217;ve also reused it in one of my projects at a financial firm, it works great and is amazingly productive once you have setup a framework based on <a href="http://dbunit.sourceforge.net/">dbunit</a>. Wait, what is dbunit? I&#8217;m not going into the details but it&#8217;s a no-brainer that if you use hibernate and junit, you better get started on using dbunit for unit testing backed by xml datasets instead of the cumbersome setup/teardown methods to populate data for each junit test case</p>
<p>We have a sample project checked into RTC&#8217;s sourceforge (We call it <a href="http://sourceforge.net/projects/helloworld2/" target="_blank">helloworld2</a>), with custom classes on top of DBUnit (most of it has been written by the author of Schemamule).</p>
<p>My example considers of an entity, Foo with FooDao, mapped to a table Foo<em>.</em> For simplicity, I assume one field called name. As a step by step tutorial on extending DBUnit Unit Testing ,  I&#8217;ll show how simple it is to write a Dao based unit test case using Dbunit, Spring and Hibernate (of course on our generated hsqldb)</p>
<p>Step 1:Create an Hsqldb database from Oracle</p>
<p>Download <a href="https://sourceforge.net/project/showfiles.php?group_id=166480">Schemamule</a> and run the following ant task</p>
<pre>
&lt;schemacopy xmlns=&quot;http://bioinformatics.northwestern.edu/schemamule&quot;&gt;
    &lt;to uri=&quot;jdbc:hsqldb:file:${basedir}/hsqldb/mydb&quot; username=&quot;sa&quot;&gt;
    &lt;from uri=&quot;jdbc:oracle:thin:mydb&quot; username=&quot;scott&quot; password=&quot;tiger&quot;&gt;
&lt;/from&gt;
&lt;/to&gt;&lt;/schemacopy&gt;
</pre>
<p>Step 2: Setup DBUnit<br />
Download the latest version of <a href="http://dbunit.sourceforge.net/">dbunit </a>(jdk1.4 or jdk5)</p>
<p>Step 3: Download the svn repository (0r copy by browsing svn) Revert To Console&#8217;s sample test utility classes and example DBUnit tutorial from sourceforge <a href="http://sourceforge.net/svn/?group_id=200388">here</a>.</p>
<p>- Checkout under projects/unit-test.<br />
- I&#8217;m not providing a complete working example with spring/hibernate configuration, as I presume you are running under an environment where you already have a this configured with an Oracle database.</p>
<p>- the utility classes include the following classes<br />
- CoreTestCase &#8212; An extension on JUnit with much more useful assert statements<br />
- ApplicationTestCase &#8212; All the unit tests in your Spring/Hibernate project should extend this class<br />
- DaoTestCase &#8212; All your Dao Tests should extend this class<br />
- ContextTools &#8211; The class which reads your applicationContext-xyz.xml file, where hibernate session is configured<br />
- Sample Dao and entity</p>
<p>Configure these files in your project, which can read the applicationContext from the classpath (for the tests to work!)</p>
<p>Step 4:With all this configured, let&#8217;s write a simple Dao Test</p>
<pre>
public class FooDAOTest extends DaoTestCase {
    FooDao dao = (FooDao)getApplicationContext().getBean(&quot;fooDao&quot;);
         // assuming that your spring config has a bean-id 'fooDao'
	 public void testGetById() throws Exception {
            Foo foo = (Foo)dao.getById(1);
            assertEquals(&quot;revert to console&quot;, foo.getName());
	 }
}</pre>
<p>By Default, DBUnit assumes a test data xml file in the same testdata/FooDaoTest.xml (you can override this). Now, lets see the dataset</p>
<pre>
&lt;dataset&gt;
&lt;table name=&quot;FOO&quot;&gt;&lt;column&gt;name&lt;/column&gt;
        &lt;row&gt;
            &lt;value&gt;revert to console&lt;/value&gt;
         &lt;/row&gt;&lt;/table&gt;
&lt;/dataset&gt;
</pre>
<p>That&#8217;s it! For all the configuration that I&#8217;ve showed you (which will take some time to setup), all you need to do to write another test is, to write another method with testdata! This setup will create,drop the testdata on the generated HsqlDb schema before/after each test. What more, because, it is in memory, you can even run, Dao Tests and complete round trip unit tests automated in your nightly builds, without coupling to an existing Oracle Schema.</p>
<p>There are some limitations to Schemamule though. I had to customize it for my project as we were using DB Views. I finally got it working after modifying the sourcecode. Unfortunately I could never put that back into Schemamule as a patch but I recommend downloading the source and try it for yourself. It&#8217;s a great example on understanding how Spring&#8217;s Jdbc template works and can be extended.</p>

<span class="slashdigglicious">
<a href="http://slashdot.org/bookmark.pl?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fhibernate-jpa%2Fautomated-unit-testing-with-dbunit-hsqldb-in-spring-hibernate-projects%2F&amp;title=Automated+Unit+Testing+with+DBUnit%2C+Hsqldb+in+Spring+%26%23038%3B+Hibernate+projects" title="Slashdot It!"><img src="http://slashdot.org/favicon.ico" height="16" width="16" alt="[Slashdot]" /></a>
<a href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fhibernate-jpa%2Fautomated-unit-testing-with-dbunit-hsqldb-in-spring-hibernate-projects%2F&amp;title=Automated+Unit+Testing+with+DBUnit%2C+Hsqldb+in+Spring+%26%23038%3B+Hibernate+projects" title="Digg This Story"><img src="http://digg.com/favicon.ico" width="16" height="16" alt="[Digg]" /></a>
<a href="http://reddit.com/submit?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fhibernate-jpa%2Fautomated-unit-testing-with-dbunit-hsqldb-in-spring-hibernate-projects%2F&amp;title=Automated+Unit+Testing+with+DBUnit%2C+Hsqldb+in+Spring+%26%23038%3B+Hibernate+projects" title="Reddit"><img src="http://reddit.com/favicon.ico" width="16" height="16" alt="[Reddit]" /></a>
<a href="http://del.icio.us/post?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fhibernate-jpa%2Fautomated-unit-testing-with-dbunit-hsqldb-in-spring-hibernate-projects%2F&amp;title=Automated+Unit+Testing+with+DBUnit%2C+Hsqldb+in+Spring+%26%23038%3B+Hibernate+projects" title="Save to del.icio.us" onclick="window.open('http://del.icio.us/post?v=4&amp;noui&amp;jump=close&amp;url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fhibernate-jpa%2Fautomated-unit-testing-with-dbunit-hsqldb-in-spring-hibernate-projects%2F&amp;title=Automated+Unit+Testing+with+DBUnit%2C+Hsqldb+in+Spring+%26%23038%3B+Hibernate+projects', 'delicious', 'toolbar=no,width=700,height=400'); return false;"><img src="http://images.del.icio.us/static/img/delicious.small.gif" width="16" height="16" alt="[del.icio.us]" /></a>
<a href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fhibernate-jpa%2Fautomated-unit-testing-with-dbunit-hsqldb-in-spring-hibernate-projects%2F" title="Share on Facebook"><img src="http://www.facebook.com/favicon.ico" width="16" height="16" alt="[Facebook]" /></a>
<a href="http://technorati.com/faves?add=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fhibernate-jpa%2Fautomated-unit-testing-with-dbunit-hsqldb-in-spring-hibernate-projects%2F" title="Add to my Technorati Favorites"><img src="http://technorati.com/favicon.ico" width="16" height="16" alt="[Technorati]" /></a>
<a href="http://www.google.com/bookmarks/mark?op=edit&amp;output=popup&amp;bkmk=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fhibernate-jpa%2Fautomated-unit-testing-with-dbunit-hsqldb-in-spring-hibernate-projects%2F&amp;title=Automated+Unit+Testing+with+DBUnit%2C+Hsqldb+in+Spring+%26%23038%3B+Hibernate+projects" title="Save to Google Bookmarks"><img src="http://www.google.com/favicon.ico" width="16" height="16" alt="[Google]" /></a>
<a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fhibernate-jpa%2Fautomated-unit-testing-with-dbunit-hsqldb-in-spring-hibernate-projects%2F&amp;title=Automated+Unit+Testing+with+DBUnit%2C+Hsqldb+in+Spring+%26%23038%3B+Hibernate+projects" title="Stumble it!"><img src="http://www.stumbleupon.com/favicon.ico" width="16" height="16" alt="[StumbleUpon]" /></a>
</span>]]></content:encoded>
			<wfw:commentRss>http://www.reverttoconsole.com/blog/hibernate-jpa/automated-unit-testing-with-dbunit-hsqldb-in-spring-hibernate-projects/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Generating Excel Formulas with Spring MVC and POI</title>
		<link>http://www.reverttoconsole.com/blog/spring/generating-excel-formulas-with-spring-mvc-and-poi/</link>
		<comments>http://www.reverttoconsole.com/blog/spring/generating-excel-formulas-with-spring-mvc-and-poi/#comments</comments>
		<pubDate>Thu, 15 May 2008 10:47:23 +0000</pubDate>
		<dc:creator>Jeff</dc:creator>
				<category><![CDATA[Spring]]></category>

		<guid isPermaLink="false">http://reverttoconsole.com/archives/182</guid>
		<description><![CDATA[I figured I&#8217;d lay this out there. It&#8217;s not awesome code, just quick and dirty. But it works. @Override protected void buildExcelDocument(Map model, HSSFWorkbook workbook, HttpServletRequest req, HttpServletResponse resp) throws Exception { //CREATE THE SHEET String periodDate = (String)model.get(PAYROLL_PERIOD_KEY); HSSFSheet sheet = workbook.createSheet(periodDate); sheet.setDefaultColumnWidth((short) 12); //GETCELL: getCell(SHEET, ROW, COLUMN); short currentRow = 0; //WRITE ROW [...]]]></description>
			<content:encoded><![CDATA[<p>I figured I&#8217;d lay this out there. It&#8217;s not awesome code, just quick and dirty. But it works.</p>
<pre>
	@Override
	protected void buildExcelDocument(Map model, HSSFWorkbook workbook,
			HttpServletRequest req, HttpServletResponse resp) throws Exception {

	    //CREATE THE SHEET
		String periodDate = (String)model.get(PAYROLL_PERIOD_KEY);
	    HSSFSheet sheet = workbook.createSheet(periodDate);
	    sheet.setDefaultColumnWidth((short) 12);

	    //GETCELL: getCell(SHEET, ROW, COLUMN);
	    short currentRow = 0;

	    //WRITE ROW FOR HEADER
	    HSSFCell header0 = getCell(sheet, currentRow, NAME_COLUMN);
	    setText(header0, &quot;NAME&quot;);

	    HSSFCell header1 = getCell(sheet, currentRow, TOTAL_BILLABLE_COLUMN);
	    setText(header1, &quot;TOTAL BILLABLE&quot;);

	    HSSFCell header2 = getCell(sheet, currentRow, OVERTIME_COLUMN);
	    setText(header2, &quot;OVERTIME&quot;);

	    HSSFCell header3 = getCell(sheet, currentRow, SUPPORT_COLUMN);
	    setText(header3, &quot;SUPPORT&quot;);

	    HSSFCell header4 = getCell(sheet, currentRow, VACATION_COLUMN);
	    setText(header4, &quot;VACATION&quot;);

	    HSSFCell header5 = getCell(sheet, currentRow, SICK_COLUMN);
	    setText(header5, &quot;SICK&quot;);

	    Collection&lt;payrollReportConsultantDisplay&gt; timesheetList =
	    	(Collection&lt;payrollReportConsultantDisplay&gt;) model.get(PAYROLL_LIST_KEY);

	    Iterator&lt;payrollReportConsultantDisplay&gt; timesheetIterator = timesheetList.iterator();
	    while (timesheetIterator.hasNext())  {
	      currentRow++;
	      PayrollReportConsultantDisplay timesheet = timesheetIterator.next();
	      HSSFRow row = sheet.createRow(currentRow);
	      row.createCell(NAME_COLUMN).setCellValue(
	    		  new HSSFRichTextString(timesheet.getDisplayName()));
	      if(StringUtils.isNotEmpty(timesheet.getTotalBillableHours())) {
		      row.createCell(TOTAL_BILLABLE_COLUMN).setCellValue(
		    		  new Double(timesheet.getTotalBillableHours()).doubleValue());
	      }
	      if(StringUtils.isNotEmpty(timesheet.getOvertimeHours())) {
		      row.createCell(OVERTIME_COLUMN).setCellValue(
		    		  new Double(timesheet.getOvertimeHours()).doubleValue());
	      }
	      if(StringUtils.isNotEmpty(timesheet.getInternalSupportHours())) {
		      row.createCell(SUPPORT_COLUMN).setCellValue(
		    		  new Double(timesheet.getInternalSupportHours()).doubleValue());
	      }
	      if(StringUtils.isNotEmpty(timesheet.getVacationHours())) {
		      row.createCell(VACATION_COLUMN).setCellValue(
		    		  new Double(timesheet.getVacationHours()).doubleValue());
	      }
	      if(StringUtils.isNotEmpty(timesheet.getSickHours())) {
		      row.createCell(SICK_COLUMN).setCellValue(
		    		  new Double(timesheet.getSickHours()).doubleValue());
	      }
	    }
            //Provide a formula for totals
	    HSSFRow row = sheet.createRow(++currentRow);
	    row.createCell(NAME_COLUMN).setCellValue(new HSSFRichTextString(&quot;Totals:&quot;));
	    row.createCell(TOTAL_BILLABLE_COLUMN).setCellFormula(&quot;SUM(B1:B&quot; + (currentRow -1) + &quot;)&quot;);
	    row.createCell(OVERTIME_COLUMN).setCellFormula(&quot;SUM(C1:C&quot; + (currentRow -1) + &quot;)&quot;);
	    row.createCell(SUPPORT_COLUMN).setCellFormula(&quot;SUM(D1:D&quot; + (currentRow -1) + &quot;)&quot;);
	    row.createCell(VACATION_COLUMN).setCellFormula(&quot;SUM(E1:E&quot; + (currentRow -1) + &quot;)&quot;);
	    row.createCell(SICK_COLUMN).setCellFormula(&quot;SUM(F1:F&quot; + (currentRow -1) + &quot;)&quot;);
	}
</pre>
<p>Hat tip to <a href="http://www.zabada.com/technology/Wiki.jsp?page=ExcelGenerationWithSpringAndPOI">Zabada Technologies</a>.<br />
Hat tip to <a href="http://officewriter.softartisans.com/OfficeWriter-306.aspx">softartisans</a>.</p>

<span class="slashdigglicious">
<a href="http://slashdot.org/bookmark.pl?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fgenerating-excel-formulas-with-spring-mvc-and-poi%2F&amp;title=Generating+Excel+Formulas+with+Spring+MVC+and+POI" title="Slashdot It!"><img src="http://slashdot.org/favicon.ico" height="16" width="16" alt="[Slashdot]" /></a>
<a href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fgenerating-excel-formulas-with-spring-mvc-and-poi%2F&amp;title=Generating+Excel+Formulas+with+Spring+MVC+and+POI" title="Digg This Story"><img src="http://digg.com/favicon.ico" width="16" height="16" alt="[Digg]" /></a>
<a href="http://reddit.com/submit?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fgenerating-excel-formulas-with-spring-mvc-and-poi%2F&amp;title=Generating+Excel+Formulas+with+Spring+MVC+and+POI" title="Reddit"><img src="http://reddit.com/favicon.ico" width="16" height="16" alt="[Reddit]" /></a>
<a href="http://del.icio.us/post?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fgenerating-excel-formulas-with-spring-mvc-and-poi%2F&amp;title=Generating+Excel+Formulas+with+Spring+MVC+and+POI" title="Save to del.icio.us" onclick="window.open('http://del.icio.us/post?v=4&amp;noui&amp;jump=close&amp;url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fgenerating-excel-formulas-with-spring-mvc-and-poi%2F&amp;title=Generating+Excel+Formulas+with+Spring+MVC+and+POI', 'delicious', 'toolbar=no,width=700,height=400'); return false;"><img src="http://images.del.icio.us/static/img/delicious.small.gif" width="16" height="16" alt="[del.icio.us]" /></a>
<a href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fgenerating-excel-formulas-with-spring-mvc-and-poi%2F" title="Share on Facebook"><img src="http://www.facebook.com/favicon.ico" width="16" height="16" alt="[Facebook]" /></a>
<a href="http://technorati.com/faves?add=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fgenerating-excel-formulas-with-spring-mvc-and-poi%2F" title="Add to my Technorati Favorites"><img src="http://technorati.com/favicon.ico" width="16" height="16" alt="[Technorati]" /></a>
<a href="http://www.google.com/bookmarks/mark?op=edit&amp;output=popup&amp;bkmk=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fgenerating-excel-formulas-with-spring-mvc-and-poi%2F&amp;title=Generating+Excel+Formulas+with+Spring+MVC+and+POI" title="Save to Google Bookmarks"><img src="http://www.google.com/favicon.ico" width="16" height="16" alt="[Google]" /></a>
<a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fgenerating-excel-formulas-with-spring-mvc-and-poi%2F&amp;title=Generating+Excel+Formulas+with+Spring+MVC+and+POI" title="Stumble it!"><img src="http://www.stumbleupon.com/favicon.ico" width="16" height="16" alt="[StumbleUpon]" /></a>
</span>]]></content:encoded>
			<wfw:commentRss>http://www.reverttoconsole.com/blog/spring/generating-excel-formulas-with-spring-mvc-and-poi/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Limitations of AbstractTransactionalDataSourceSpringContextTests</title>
		<link>http://www.reverttoconsole.com/blog/spring/limitations-of-abstracttransactionaldatasourcespringcontexttests/</link>
		<comments>http://www.reverttoconsole.com/blog/spring/limitations-of-abstracttransactionaldatasourcespringcontexttests/#comments</comments>
		<pubDate>Tue, 13 May 2008 21:35:13 +0000</pubDate>
		<dc:creator>Jeff</dc:creator>
				<category><![CDATA[Spring]]></category>
		<category><![CDATA[UnitTest]]></category>

		<guid isPermaLink="false">http://reverttoconsole.com/archives/180</guid>
		<description><![CDATA[This has apparently gotten a fair amount of attention over the last year or so, but I never encountered it until today- call me lucky. Here&#8217;s the situation, you&#8217;re using Spring MVC and you have a controller that extends another controller (A->B). Your unit test extends AbstractTransactionalDataSourceSpringContextTests, and makes use of autowiring. You write your [...]]]></description>
			<content:encoded><![CDATA[<p>This has apparently gotten a fair amount of attention over the last year or so, but I never encountered it until today- call me lucky. Here&#8217;s the situation, you&#8217;re using <a href="http://www.springframework.org/about">Spring MVC</a> and you have a controller that extends another controller (A->B).</p>
<p>Your unit test extends <a href="http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/test/AbstractTransactionalDataSourceSpringContextTests.html">AbstractTransactionalDataSourceSpringContextTests</a>, and makes use of <a href="http://groups.google.com/group/EtoE/browse_thread/thread/9306c581470b47cb/31a62772d677bd12">autowiring</a>.</p>
<p>You write your test, run it, and receive something like this:</p>
<pre>
 Unsatisfied dependency expressed through bean property 'aController':
 No unique bean of type [org.reverttoconsole.majorapplication.controller.aController] is defined:
  expected single matching bean but found 2: [aController.htm, bController.htm]
</pre>
<p>I tried using <a href="http://static.springframework.org/spring/docs/2.5.x/reference/testing.html">annotations</a>, using @Autowire and @Resource, but in the end had to refactor my code to fit the tests&#8230; by creating an Abstract class that both controllers could extend.</p>

<span class="slashdigglicious">
<a href="http://slashdot.org/bookmark.pl?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Flimitations-of-abstracttransactionaldatasourcespringcontexttests%2F&amp;title=Limitations+of+AbstractTransactionalDataSourceSpringContextTests" title="Slashdot It!"><img src="http://slashdot.org/favicon.ico" height="16" width="16" alt="[Slashdot]" /></a>
<a href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Flimitations-of-abstracttransactionaldatasourcespringcontexttests%2F&amp;title=Limitations+of+AbstractTransactionalDataSourceSpringContextTests" title="Digg This Story"><img src="http://digg.com/favicon.ico" width="16" height="16" alt="[Digg]" /></a>
<a href="http://reddit.com/submit?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Flimitations-of-abstracttransactionaldatasourcespringcontexttests%2F&amp;title=Limitations+of+AbstractTransactionalDataSourceSpringContextTests" title="Reddit"><img src="http://reddit.com/favicon.ico" width="16" height="16" alt="[Reddit]" /></a>
<a href="http://del.icio.us/post?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Flimitations-of-abstracttransactionaldatasourcespringcontexttests%2F&amp;title=Limitations+of+AbstractTransactionalDataSourceSpringContextTests" title="Save to del.icio.us" onclick="window.open('http://del.icio.us/post?v=4&amp;noui&amp;jump=close&amp;url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Flimitations-of-abstracttransactionaldatasourcespringcontexttests%2F&amp;title=Limitations+of+AbstractTransactionalDataSourceSpringContextTests', 'delicious', 'toolbar=no,width=700,height=400'); return false;"><img src="http://images.del.icio.us/static/img/delicious.small.gif" width="16" height="16" alt="[del.icio.us]" /></a>
<a href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Flimitations-of-abstracttransactionaldatasourcespringcontexttests%2F" title="Share on Facebook"><img src="http://www.facebook.com/favicon.ico" width="16" height="16" alt="[Facebook]" /></a>
<a href="http://technorati.com/faves?add=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Flimitations-of-abstracttransactionaldatasourcespringcontexttests%2F" title="Add to my Technorati Favorites"><img src="http://technorati.com/favicon.ico" width="16" height="16" alt="[Technorati]" /></a>
<a href="http://www.google.com/bookmarks/mark?op=edit&amp;output=popup&amp;bkmk=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Flimitations-of-abstracttransactionaldatasourcespringcontexttests%2F&amp;title=Limitations+of+AbstractTransactionalDataSourceSpringContextTests" title="Save to Google Bookmarks"><img src="http://www.google.com/favicon.ico" width="16" height="16" alt="[Google]" /></a>
<a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Flimitations-of-abstracttransactionaldatasourcespringcontexttests%2F&amp;title=Limitations+of+AbstractTransactionalDataSourceSpringContextTests" title="Stumble it!"><img src="http://www.stumbleupon.com/favicon.ico" width="16" height="16" alt="[StumbleUpon]" /></a>
</span>]]></content:encoded>
			<wfw:commentRss>http://www.reverttoconsole.com/blog/spring/limitations-of-abstracttransactionaldatasourcespringcontexttests/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>HSQLDB Integration Into Spring Security</title>
		<link>http://www.reverttoconsole.com/blog/security/hsqldb-integration-into-spring-security/</link>
		<comments>http://www.reverttoconsole.com/blog/security/hsqldb-integration-into-spring-security/#comments</comments>
		<pubDate>Fri, 02 May 2008 15:40:18 +0000</pubDate>
		<dc:creator>Jeff</dc:creator>
				<category><![CDATA[Database]]></category>
		<category><![CDATA[Security]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[hsqldb]]></category>

		<guid isPermaLink="false">http://reverttoconsole.com/archives/176</guid>
		<description><![CDATA[Adding a database back end to Spring Security seems deceptively simple. And to be fair, there are several ways to do it. The way I had in mind looked like a shortcut. In my application there is basically one table for all users. It contains the values I need for username, password, role, and the [...]]]></description>
			<content:encoded><![CDATA[<p>Adding a database back end to Spring Security seems deceptively simple. And to be fair, <a href="http://static.springframework.org/spring-security/site/reference/html/authentication-common-auth-services.html#jdbc-service">there are several ways to do it</a>. The way I had in mind looked like a shortcut.</p>
<p>In my application there is basically one table for all users. It contains the values I need for username, password, role, and the active flag that Spring Security supports. No, it wouldn&#8217;t be my first choice of table setup, but that&#8217;s what I have to work with.</p>
<p>I read through Chris Baker&#8217;s <a href="http://java.dzone.com/tips/pathway-acegi-spring-security-">fine article in the Java DZONE</a> and the way he did it was to override two values in the jdbc-user-service, which replaces the user-service authentication provider. He used:</p>
<pre>
&lt;authentication-provider&gt;
	&lt;jdbc-user-service data-source-ref=&quot;dataSource&quot;
	users-by-username-query=&quot;SELECT U.username, U.password, U.accountEnabled AS &#039;enabled&#039; FROM User U where U.username=?&quot;
	authorities-by-username-query=&quot;SELECT U.username, R.name as &#039;authority&#039; FROM User U JOIN Authority A ON u.id = A.userId JOIN Role R ON R.id = A.roleId WHERE U.username=?&quot;/&gt;
&lt;/authentication-provider&gt;
</pre>
<p>I wanted to do something similar, and initially banged out:</p>
<pre>
	&lt;authentication-provider&gt;
	&lt;jdbc-user-service data-source-ref=&quot;baseDataSource&quot;
	users-by-username-query=&quot;SELECT LOGONID, PASSWORD, ACTIVE FROM EMPLOYEE WHERE LOGONID=?&quot;
	authorities-by-username-query=&quot;SELECT LOGONID, ROLE FROM EMPLOYEE WHERE LOGONID=?&quot;/&gt;
	&lt;/authentication-provider&gt;
</pre>
<p>The result was that all employees were inactive for Spring Security. Why? Because the EMPLOYEE table&#8217;s ACTIVE column is a CHAR, and Spring Security expects a BIT or BOOLEAN. After tinkering around for a bit, I decided to modify the EMPLOYEE table to use a BOOLEAN instead. The actually posed a <a href="http://www.carbonfive.com/community/archives/2005/07/dbunit_hsql_and.html">problem for DbUnit</a>, surprise surprise. The workaround in Ant didn&#8217;t work for me, I had a weird classnotfound error that I couldn&#8217;t track back to ant, and just gave up after a while. I didn&#8217;t really want to change the column type anyway.</p>
<p>In the end, I played around with HSQL for a while and came up with</p>
<pre>
	&lt;authentication-provider&gt;
	&lt;jdbc-user-service data-source-ref=&quot;baseDataSource&quot;
	users-by-username-query=&quot;SELECT LOGONID, PASSWORD, CASE WHEN UCASE(ACTIVE)=&#039;T&#039; THEN 1 ELSE 0 END FROM EMPLOYEE WHERE LOGONID=?&quot;
	authorities-by-username-query=&quot;SELECT LOGONID, ROLE FROM EMPLOYEE WHERE LOGONID=?&quot;/&gt;
	&lt;/authentication-provider&gt;
</pre>
<p>Disclaimer: There are other ways to do this that are identified in the Spring Security reference documentation. The documentation is very good, my only wish would be that they provide the default schema, and provide a description of the default roles.</p>

<span class="slashdigglicious">
<a href="http://slashdot.org/bookmark.pl?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fsecurity%2Fhsqldb-integration-into-spring-security%2F&amp;title=HSQLDB+Integration+Into+Spring+Security" title="Slashdot It!"><img src="http://slashdot.org/favicon.ico" height="16" width="16" alt="[Slashdot]" /></a>
<a href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fsecurity%2Fhsqldb-integration-into-spring-security%2F&amp;title=HSQLDB+Integration+Into+Spring+Security" title="Digg This Story"><img src="http://digg.com/favicon.ico" width="16" height="16" alt="[Digg]" /></a>
<a href="http://reddit.com/submit?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fsecurity%2Fhsqldb-integration-into-spring-security%2F&amp;title=HSQLDB+Integration+Into+Spring+Security" title="Reddit"><img src="http://reddit.com/favicon.ico" width="16" height="16" alt="[Reddit]" /></a>
<a href="http://del.icio.us/post?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fsecurity%2Fhsqldb-integration-into-spring-security%2F&amp;title=HSQLDB+Integration+Into+Spring+Security" title="Save to del.icio.us" onclick="window.open('http://del.icio.us/post?v=4&amp;noui&amp;jump=close&amp;url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fsecurity%2Fhsqldb-integration-into-spring-security%2F&amp;title=HSQLDB+Integration+Into+Spring+Security', 'delicious', 'toolbar=no,width=700,height=400'); return false;"><img src="http://images.del.icio.us/static/img/delicious.small.gif" width="16" height="16" alt="[del.icio.us]" /></a>
<a href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fsecurity%2Fhsqldb-integration-into-spring-security%2F" title="Share on Facebook"><img src="http://www.facebook.com/favicon.ico" width="16" height="16" alt="[Facebook]" /></a>
<a href="http://technorati.com/faves?add=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fsecurity%2Fhsqldb-integration-into-spring-security%2F" title="Add to my Technorati Favorites"><img src="http://technorati.com/favicon.ico" width="16" height="16" alt="[Technorati]" /></a>
<a href="http://www.google.com/bookmarks/mark?op=edit&amp;output=popup&amp;bkmk=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fsecurity%2Fhsqldb-integration-into-spring-security%2F&amp;title=HSQLDB+Integration+Into+Spring+Security" title="Save to Google Bookmarks"><img src="http://www.google.com/favicon.ico" width="16" height="16" alt="[Google]" /></a>
<a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fsecurity%2Fhsqldb-integration-into-spring-security%2F&amp;title=HSQLDB+Integration+Into+Spring+Security" title="Stumble it!"><img src="http://www.stumbleupon.com/favicon.ico" width="16" height="16" alt="[StumbleUpon]" /></a>
</span>]]></content:encoded>
			<wfw:commentRss>http://www.reverttoconsole.com/blog/security/hsqldb-integration-into-spring-security/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

