<?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>Bogdan Mocanu</title>
	<atom:link href="http://bmocanu.ro/coding/feed/" rel="self" type="application/rss+xml" />
	<link>http://bmocanu.ro/coding</link>
	<description>discussing about Java, coding and anything tech-related</description>
	<lastBuildDate>Sun, 20 Nov 2011 13:10:16 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>Client for OAuth with Spring Security</title>
		<link>http://bmocanu.ro/coding/409/client-for-oauth-with-spring-security/</link>
		<comments>http://bmocanu.ro/coding/409/client-for-oauth-with-spring-security/#comments</comments>
		<pubDate>Sun, 20 Nov 2011 12:53:11 +0000</pubDate>
		<dc:creator>Bogdan</dc:creator>
				<category><![CDATA[Spring]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[oauth]]></category>
		<category><![CDATA[security]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[spring security]]></category>

		<guid isPermaLink="false">http://bmocanu.ro/coding/?p=409</guid>
		<description><![CDATA[About one year ago I wrote an article in which I described how can one implement a client and a server that uses the OAuth security protocol. The implementation was using Spring Security and a plugin for OAuth. The article was intended to focus on the 2Legged flavor of the OAuth 1.0 protocol. However, because [...]]]></description>
			<content:encoded><![CDATA[<p>About one year ago I wrote <a title="OAuth 2-legged model with Spring Security" href="http://bmocanu.ro/coding/303/oauth-2legged-model-with-spring-security/">an article </a>in which I described how can one implement a client and a server that uses the OAuth security protocol. The implementation was using Spring Security and a plugin for OAuth. The article was intended to focus on the 2Legged flavor of the OAuth 1.0 protocol. However, because of a misunderstanding from my part, that article is just a normal OAuth 1.0 implementation of Client and Server, with a small hack for the second step. Thanks to all the people that commented on that article, I was able to understand how the 2Legged mode should work.</p>
<p>Therefore, this article presents a small client application that uses both the normal OAuth 1.0 mode and the 2Legged mode (also know as &#8220;signed fetch&#8221;) for accessing a protected resource.<span id="more-409"></span></p>
<p>Before we begin with the client application, some references are in order. I will present here only the details of the protocol that are interesting for the target of this article. If one needs further information,  one should check the reference links below in order to get a good understanding of the protocol.</p>
<p>The following links are useful when dealing with the OAuth protocol:</p>
<ul>
<li><a href="http://oauth.net/">OAuth protocol homepage</a></li>
<li><a href="http://tools.ietf.org/html/rfc5849">OAuth 1.0 RFC</a></li>
<li><a href="http://oauth.net/code/">OAuth implementations</a> (a list that is little bit outdated, unfortunately)</li>
<li><a href="http://static.springsource.org/spring-security/oauth/">OAuth plugin for Spring Security</a> (since the previous OAuth article, the plugin has moved from Codehaus to SpringSource)</li>
<li><a href="https://github.com/SpringSource/spring-security-oauth/wiki/">Spring Security OAuth plugin wiki</a></li>
<li><a href="https://github.com/SpringSource/spring-security-oauth/wiki/twolegged">Spring Security OAuth plugin for 2Legged setup</a></li>
<li><a href="https://github.com/SpringSource/spring-security-oauth/tree/master/samples/oauth">Sparklr and Tonr examples</a></li>
<li><a href="http://forum.springsource.org/showthread.php?103067-How-to-configure-2-Legged-OAuth">Very good thread</a> discussing the changes to perform in Sparklr for having the 2Legged mode working</li>
</ul>
<p></p>
<p>This article presents only the client code for the two modes: the normal mode and the 2Legged mode. The server that will be used is the <a href="https://github.com/SpringSource/spring-security-oauth/tree/master/samples/oauth/sparklr">Sparklr</a> sample application (I decided that it makes no sense to build my own server application, since it will most likely be an almost identical copy of the Sparklr; therefore the client is custom, but the server is the one provided as sample for the Spring Security OAuth plugin).</p>
<h3>OAuth normal mode</h3>
<p>In the normal mode the OAuth protocol involves 3 parties: the provider of the protected resources (the server that stores the resources), the consumer of resources (the application that needs access to the resources) and the user (the human or non-human party that owns the resources).</p>
<p>The prerequisites are the following:</p>
<ul>
<li>the provider stores one or more protected resources, on behalf of the user</li>
<li>the user has an account on the provider application, through which he/she/it can access the resources</li>
<li>the user needs to securely allow the consumer to access the protected resources stored by the provider</li>
</ul>
<p></p>
<p>The flow happens like the following:</p>
<ol>
<li>the consumer issues a request for a temporary token (called the request token). For this request it needs the consumer key and the consumer secret. The request is signed using these security details.</li>
<li>the provider verifies the request and issues the request token, which is returned to the consumer.</li>
<li>the consumer sends the user to the provider&#8217;s site, in order to authorize the request token. Optionally, on the provider&#8217;s site the user will have to log in (if he/she/it is not already authenticated there). After the log in, the provider asks the user to authorize the access of the consumer on the protected resources.</li>
<li>after authorization on the provider&#8217;s site, the provider generates a request verifier, which the user must give to the consumer (this happens, in most cases, automatically by using a callback URL that the provider builds using the URL given by the consumer and the newly generated verifier; the user is then redirected to this callback URL).</li>
<li>the consumer uses the request token and the verifier to make a second request for the access token</li>
<li>the provider verifies the request and generates the access token</li>
<li>the consumer uses the access token to make a third request, this time for the actual protected resource</li>
</ol>
<p></p>
<h3>2Legged mode (aka <em>signed fetch</em>)</h3>
<p>The 2Legged mode of the OAuth protocol is called this way becase instead of having 3 parties involved (the provider, the consumer and the user) one has only 2 parties (the provider and the consumer). The user is left outside of the game, since the cases when this mode applies simply don&#8217;t need the user. For example some mobile applications might need to access server resources that are owned bya particular user. Therefore, the OAuth protocol can be employed and the consumer will only need to know the consumer key and the consumer secret in order to be able to access the resources.</p>
<p>The prerequisites are the following:</p>
<ul>
<li>the provider stores one or more protected resources</li>
<li>the consumer needs to securely access the resources, using a consumer key and a consumer secret</li>
</ul>
<p></p>
<p>The flow happens like the following:</p>
<ol>
<li>the consumer makes a signed request to the provider, using the consumer key and the consumer secret in order to build the signature of the request</li>
<li>the provider verifies the request and returns the protected resource</li>
</ol>
<p></p>
<h3>The code</h3>
<p>The following Java class tests both modes (after this class and the Maven pom XML, there are also some small changes that one needs to perform in the Sparklr application, in order to have the 2Legged mode running, so make sure to read to the bottom of the article):</p>
<p>[java]<br />
public class TestOAuthClient {</p>
<p>    private static final Logger log = LoggerFactory.getLogger(TestOAuthClient.class);</p>
<p>    private static final String SERVER_URL = &#8220;http://localhost:8080&#8243;;<br />
    private static final String SERVER_URL_OAUTH_REQUEST = SERVER_URL + &#8220;/oauth/request_token&#8221;;<br />
    private static final String SERVER_URL_OAUTH_CONFIRM = SERVER_URL + &#8220;/oauth/confirm_access&#8221;;<br />
    private static final String SERVER_URL_OAUTH_ACCESS = SERVER_URL + &#8220;/oauth/access_token&#8221;;</p>
<p>    private static final String RESOURCE_URL = SERVER_URL + &#8220;/photos?format=xml&#8221;;<br />
    private static final String RESOURCE_ID = &#8220;photos&#8221;;</p>
<p>    private static final String CONSUMER_KEY = &#8220;tonr-consumer-key&#8221;;<br />
    private static final String CONSUMER_SECRET = &#8220;SHHHHH!!!!!!!!!!&#8221;;<br />
    private static final String SIGNATURE_METHOD = &#8220;HMAC-SHA1&#8243;;<br />
    private static final String DEFAULT_ENCODING = &#8220;ISO-8859-1&#8243;;</p>
<p>    // &#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-</p>
<p>    public static void main(String[] args) throws IOException {<br />
        testClassicMode();<br />
        test2LeggedMode();<br />
    }</p>
<p>    // &#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-</p>
<p>    private static void testClassicMode() throws IOException {<br />
        OAuthConsumerSupport consumerSupport = createConsumerSupport();<br />
        // step 1 &#8211; get the request token<br />
        OAuthConsumerToken requestToken = getRequestToken(consumerSupport);<br />
        // step 2 &#8211; wait for the user to grant access on the protected resource<br />
        String verifier = authorizeRequestToken(requestToken);<br />
        // step 3 &#8211; get the access token<br />
        OAuthConsumerToken accessToken = getAccessToken(consumerSupport, requestToken, verifier);<br />
        // step 4 &#8211; get the protected resource<br />
        getProtectedResource(consumerSupport, accessToken);<br />
    }</p>
<p>    private static void test2LeggedMode() throws IOException {<br />
        OAuthConsumerSupport consumerSupport = createConsumerSupport();<br />
        getProtectedResource(consumerSupport, new OAuthConsumerToken());<br />
    }</p>
<p>    // &#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-</p>
<p>    private static OAuthConsumerSupport createConsumerSupport() {<br />
        CoreOAuthConsumerSupport consumerSupport = new CoreOAuthConsumerSupport();<br />
        consumerSupport.setStreamHandlerFactory(new DefaultOAuthURLStreamHandlerFactory());<br />
        consumerSupport.setProtectedResourceDetailsService(new ProtectedResourceDetailsService() {<br />
            public ProtectedResourceDetails loadProtectedResourceDetailsById(String id) throws IllegalArgumentException {<br />
                SignatureSecret secret = new SharedConsumerSecret(CONSUMER_SECRET);</p>
<p>                BaseProtectedResourceDetails result = new BaseProtectedResourceDetails();<br />
                result.setConsumerKey(CONSUMER_KEY);<br />
                result.setSharedSecret(secret);<br />
                result.setSignatureMethod(SIGNATURE_METHOD);<br />
                result.setUse10a(true); // set this to false to not require the verifier on the second step<br />
                result.setRequestTokenURL(SERVER_URL_OAUTH_REQUEST);<br />
                result.setAccessTokenURL(SERVER_URL_OAUTH_ACCESS);<br />
                return result;<br />
            }<br />
        });<br />
        return consumerSupport;<br />
    }</p>
<p>    private static OAuthConsumerToken getRequestToken(OAuthConsumerSupport consumerSupport) {<br />
        log.info(&#8220;OAUTH: Request token: getting&#8230;&#8221;);<br />
        OAuthConsumerToken requestToken = consumerSupport.getUnauthorizedRequestToken(RESOURCE_ID, null);<br />
        log.info(&#8220;OAUTH: Request token: &#8221; + requestToken.getValue());<br />
        log.info(&#8220;OAUTH: Request token secret: &#8221; + requestToken.getSecret());<br />
        return requestToken;<br />
    }</p>
<p>    private static String authorizeRequestToken(OAuthConsumerToken requestToken) {<br />
        log.info(&#8220;OAUTH: Waiting for token authorization&#8230; &#8220;);<br />
        System.out.println(&#8220;\t1. Go to: &#8221; + SERVER_URL_OAUTH_CONFIRM + &#8220;?oauth_token=&#8221; + requestToken.getValue());<br />
        System.out.println(&#8220;\t2. Authorize the request for the protected resource (with an eventual login first)&#8221;);<br />
        System.out.println(&#8220;\t3. After authorization, copy the verifier value from the URL&#8221;);<br />
        System.out.print(&#8220;\t4. Enter the verifier here: &#8220;);<br />
        return new Scanner(System.in, DEFAULT_ENCODING).next();<br />
    }</p>
<p>    private static OAuthConsumerToken getAccessToken(OAuthConsumerSupport consumerSupport, OAuthConsumerToken requestToken, String verifier) {<br />
        log.info(&#8220;OAUTH: Access token: getting&#8230;&#8221;);<br />
        OAuthConsumerToken accessToken = consumerSupport.getAccessToken(requestToken, verifier);<br />
        log.info(&#8220;OAUTH: Access token: &#8221; + accessToken.getValue());<br />
        log.info(&#8220;OAUTH: Access token secret: &#8221; + accessToken.getSecret());<br />
        return accessToken;<br />
    }</p>
<p>    private static void getProtectedResource(OAuthConsumerSupport consumerSupport, OAuthConsumerToken accessToken) throws IOException {<br />
        log.info(&#8220;OAUTH: Getting protected resource&#8221;);<br />
        InputStream is = null;<br />
        ByteArrayOutputStream baos = new ByteArrayOutputStream();<br />
        try {<br />
            is = consumerSupport.readProtectedResource(new URL(RESOURCE_URL), accessToken, &#8220;GET&#8221;);<br />
            IOUtils.copy(is, baos);<br />
            log.info(&#8220;OAUTH: Resource : &#8221; + new String(baos.toByteArray(), DEFAULT_ENCODING));<br />
        } finally {<br />
            IOUtils.closeQuietly(is);<br />
            IOUtils.closeQuietly(baos);<br />
        }<br />
    }<br />
}<br />
[/java]</p>
<p>The test project is a maven project, with the following pom:<br />
[xml]</p>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"<br />
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<p>    <modelVersion>4.0.0</modelVersion><br />
    <artifactId>test-oauth-client</artifactId></p>
<packaging>jar</packaging>
    <name>test-oauth-client</name></p>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
<p>    <build></p>
<pluginManagement>
<plugins>
<plugin>
                    <artifactId>maven-compiler-plugin</artifactId><br />
                    <configuration><br />
                        <source>1.6</source><br />
                        <target>1.6</target><br />
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
    </build></p>
<p>    <repositories><br />
        <repository><br />
            <id>com.springsource.repository.bundles.release</id><br />
            <name>SpringSource Enterprise Bundle Repository &#8211; SpringSource Bundle Releases</name><br />
            <url>http://repository.springsource.com/maven/bundles/release</url><br />
        </repository><br />
        <repository><br />
            <id>com.springsource.repository.bundles.external</id><br />
            <name>SpringSource Enterprise Bundle Repository &#8211; External Bundle Releases</name><br />
            <url>http://repository.springsource.com/maven/bundles/external</url><br />
        </repository><br />
        <repository><br />
            <id>com.springsource.repository.bundles.milestone</id><br />
            <url>http://repository.springsource.com/maven/bundles/milestone</url><br />
        </repository><br />
        <repository><br />
            <id>spring-snapshot</id><br />
            <name>Spring Framework Snapshot Repository</name><br />
            <url>http://maven.springframework.org.s3.amazonaws.com/milestone</url><br />
        </repository><br />
    </repositories></p>
<p>    <dependencies><br />
        <dependency><br />
            <groupId>ch.qos.logback</groupId><br />
            <artifactId>logback-core</artifactId><br />
            <version>1.0.0</version><br />
        </dependency><br />
        <dependency><br />
            <groupId>ch.qos.logback</groupId><br />
            <artifactId>logback-classic</artifactId><br />
            <version>1.0.0</version><br />
        </dependency><br />
        <dependency><br />
            <groupId>org.slf4j</groupId><br />
            <artifactId>slf4j-api</artifactId><br />
            <version>1.6.4</version><br />
        </dependency><br />
        <dependency><br />
            <groupId>org.slf4j</groupId><br />
            <artifactId>jcl-over-slf4j</artifactId><br />
            <version>1.6.4</version><br />
        </dependency><br />
        <dependency><br />
            <groupId>org.springframework.security.oauth</groupId><br />
            <artifactId>spring-security-oauth</artifactId><br />
            <version>1.0.0.M5</version><br />
        </dependency><br />
        <dependency><br />
            <groupId>commons-io</groupId><br />
            <artifactId>commons-io</artifactId><br />
            <version>2.1</version><br />
        </dependency><br />
    </dependencies></p>
</project>
[/xml]</p>
<p>As one can see, for the 2Legged mode the client needs to simply give the consumer key and the consumer secret, and request the protected resources. No other token accessing is required.</p>
<p>The client for the normal mode works with the version of the Sparklr application that one can find in the git sources. However, for the 2Legged mode, some small changes are required in the Sparklr application.</p>
<p>First of all, we need to allow the consumer to access the protected resources without an authorized token. For this, one should open the <em>sparklr / src / main / webapp / WEB-INF / applicationContext.xml</em> and perform the following changes:</p>
<p>[xml]<br />
  <oauth:consumer-details-service id="consumerDetails"><br />
    <oauth:consumer name="Tonr.com"<br />
                                  key="tonr-consumer-key"<br />
                                  secret="SHHHHH!!!!!!!!!!"<br />
                                  resourceName="Your Photos"<br />
                                  resourceDescription="Your photos that you have uploaded to sparklr.com."<br />
                                  requiredToObtainAuthenticatedToken="false"<br />
                                  authorities="ROLE_USER"/><br />
    <oauth:consumer name="iGoogle" key="www.google.com" secret="classpath:/org/springframework/security/oauth/examples/sparklr/certs/igoogle.cert" typeOfSecret="rsa-cert" resourceName="Your Photos" resourceDescription="Your photos that you have uploaded to sparklr.com."/><br />
  </oauth:consumer-details-service><br />
[/xml]</p>
<p>Second, the <strong>PhotoServiceImpl</strong> class needs to be a little changed, in order to have it take into account the fact that a consumer might access the application without going through the normal login process. Therefore, change the <strong>PhotoServiceImpl.getPhotosForCurrentUser()</strong> like the following:</p>
<p>[java]<br />
    public Collection<PhotoInfo> getPhotosForCurrentUser() {<br />
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();<br />
        if (authentication.getPrincipal() instanceof UserDetails) {<br />
            UserDetails details = (UserDetails) authentication.getPrincipal();<br />
            String username = details.getUsername();<br />
            ArrayList<PhotoInfo> infos = new ArrayList<PhotoInfo>();<br />
            for (PhotoInfo info : getPhotos()) {<br />
                if (username.equals(info.getUserId())) {<br />
                    infos.add(info);<br />
                }<br />
            }<br />
            return infos;<br />
        } else if (authentication.getPrincipal() instanceof ConsumerDetails) {<br />
            return getPhotos();<br />
        } else {<br />
            throw new BadCredentialsException(&#8220;Bad credentials: not a username/password authentication.&#8221;);<br />
        }<br />
    }<br />
[/java]</p>
<h3>Epilogue</h3>
<p>That is about it. Thanks again to all the people that commented on the previous OAuth article and that provided valuable insights on how the protocol works and what the 2Legged mode looks like. If you have any questions, please feel free to leave a comment below.</p>
]]></content:encoded>
			<wfw:commentRss>http://bmocanu.ro/coding/409/client-for-oauth-with-spring-security/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Unit testing with Spring &#8211; a bad mix</title>
		<link>http://bmocanu.ro/coding/399/unit-testing-with-spring-a-bad-mix/</link>
		<comments>http://bmocanu.ro/coding/399/unit-testing-with-spring-a-bad-mix/#comments</comments>
		<pubDate>Sun, 20 Mar 2011 14:23:03 +0000</pubDate>
		<dc:creator>Bogdan</dc:creator>
				<category><![CDATA[Spring]]></category>
		<category><![CDATA[Unit testing]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[testing]]></category>
		<category><![CDATA[unit test]]></category>
		<category><![CDATA[unit testing]]></category>

		<guid isPermaLink="false">http://bmocanu.ro/coding/?p=399</guid>
		<description><![CDATA[There has been a discussion recently, on the JUnit group, about doing unit testing with Spring. The arguments provided in the answers to that question reminded me of a problem that we faced in the project that I am currently working on: the usage of Spring for unit tests was a bad idea. Let me [...]]]></description>
			<content:encoded><![CDATA[<p>There has been a discussion recently, on the <a href="http://tech.groups.yahoo.com/group/junit/">JUnit group</a>, about doing <a href="http://tech.groups.yahoo.com/group/junit/message/23340">unit testing with Spring</a>. The arguments provided in the answers to that question reminded me of a problem that we faced in the project that I am currently working on: the usage of Spring for unit tests was a bad idea. Let me tell you how we started, and why we got to realise that it is not good to mix the well-known framework in the unit tests.<span id="more-399"></span>When we started the project we thought that Spring is nice to add to the unit tests. After all, with just a few annotations, you have an instance of the class under test ready for testing. Spring takes care of creating and configuring all the dependencies required for our target instance, injects those dependencies, and we get an object that is ready for testing. However, were we writing unit tests or integration tests? I think the latter is the correct answer.</p>
<p><strong>1. Testing half of the system at once</strong></p>
<p>Therefore, the first problem with using Spring is that you don&#8217;t test just one class (that is, one <strong>unit</strong>). No sir, you are integrating and testing a part of your system, composed of your class under test but also the other services that this class is making use of. Even if you strive to only test your class (which is what you should do, since that is the unit test for a particular class, not for the entire system or for a particular functionality of the system) you will be forced to rely on other services, and hope that the other services will work correctly, and if your test fails, then the problem is in your class. Which brings us to the second problem.</p>
<p><strong>2. When something breaks, you better be mr. Holmes</strong></p>
<p>The problem nr 2 arises from the fact that your class is mixed with other services. Since it DOES use other services, this is the normal way for the class under test to work, but it is not ok for unit testing. For unit testing you need <strong>isolation</strong>. Why? Because only then you know that if a test fails, then you have a problem in either the class under test or the actual test that fails. You don&#8217;t have to search on 5 other services to make sure that the data retrieved from those services was correct and that the tests of the other services are correct (if they are correct, then at least you know that your class is the best candidate for the flaw owner). By making a change in a class and getting several tests to fail is a clear sign that your unit tests are not done in complete isolation and are depending one to another.</p>
<p><strong>3. Working with test data</strong></p>
<p>Preparing the test data for an unit test that is using Spring can be a pain in the ass. Since your services are processing and returning the data to the class under test, you need to know very well that kind of processing those services are doing, how should the input data look like, and you must tailor the input data so that after it gets through the processing of 5 services, it reaches your class under test in the shape that you want it. This, in most cases, involves custom test files and custom database records. A good approach to solve this problem is creating a fixed testing database content, which is used by all the tests. While this works for most cases, you will quickly find the need to throw some wild data to your class under test, just to make sure that you are also testing the limits and the special cases for the class methods (not only the happy paths). Since the setup for this wild data breaks the initial contract with static test data inserted in the database, you will have to resort to workarounds in order to reach your goal.</p>
<p><strong>4. It&#8217;s only time&#8230;</strong></p>
<p>With a good architecture and sound testing practices, you can make your live easier, even if you have to deal with the first 3 problems. However, what bothered us enough to decide that testing with Spring is bad was the time. Running a test was taking, in some cases, even 2 minutes to start. That is because Spring has a lot of dependencies to create, a lot of things to load and to start up, and it might take 2 minutes to setup the application context and create the instance of the class under test, until you get to see the first method executing. All in all, we found that half of the time the build system required to build our project was spent on creating and destroying Spring contexts.</p>
<p><strong>Removing Spring from tests</strong></p>
<p>Therefore, we decided to remove Spring from tests. We are using <a href="http://mockito.org/">Mockito</a> (we started with EasyMock but decided that Mockito&#8217;s methods and approach look better in code) to create mocks for the services that the class under test needs. Since Mockito allows you to make all the mocking and wiring through annotations, in some cases we don&#8217;t even need the <em>@Before</em> setup method<strong>. </strong>Moreover, with such mocks much more easier to prepare the test data. Since you only need to specify what data should be delivered to the class under test, you can focus on the class your are testing, and remove from your mind all the other services. You are effectively and efficiently testing your class in isolation.</p>
<p>Another nice thing with this approach is that you are forced to create your classes easy to test. Your classes will not be too coupled with other classes, because if they are then you will have a bad time writing the unit tests and you will like more and more to work with interfaces instead of concrete classes (even though Mockito and also EasyMock can create mocks for concrete classes).</p>
<p>Your tests will be blazingly fast, because all you have to wait for is the JVM to start. When something will break, it will surely be a problem in the class under test or the actual unit tests. You know this for sure, because everything that the class is using are mocks, and mocks do what they are told to do. They don&#8217;t have bugs outside the unit test.</p>
<p><strong>Epilogue</strong></p>
<p>To finish my story, we are currently in the process of removing Spring from the unit tests. Whenever we have to work on a test that has Spring, we first remove Spring from it, then we do the update that we had to do in the first place. In time, this showed that the tests are becoming simpler to read and understand (for someone looking at that test for the first time), the build time gets smaller and you also get the nice feeling of working with small unit test boxes that are completely under your control.</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://bmocanu.ro/coding/399/unit-testing-with-spring-a-bad-mix/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Ehcache event listeners as Spring beans</title>
		<link>http://bmocanu.ro/coding/394/ehcache-event-listeners-as-spring-beans/</link>
		<comments>http://bmocanu.ro/coding/394/ehcache-event-listeners-as-spring-beans/#comments</comments>
		<pubDate>Wed, 02 Feb 2011 19:35:12 +0000</pubDate>
		<dc:creator>Bogdan</dc:creator>
				<category><![CDATA[Spring]]></category>
		<category><![CDATA[cache]]></category>
		<category><![CDATA[dependency injection]]></category>
		<category><![CDATA[ehcache]]></category>
		<category><![CDATA[listeners]]></category>
		<category><![CDATA[spring]]></category>

		<guid isPermaLink="false">http://bmocanu.ro/coding/?p=394</guid>
		<description><![CDATA[When working with Ehcache and Spring, one might get to the point where he/she needs to implement cache event listeners: objects that are observing the cache and want to be notified by the cache when an element is put, removed or expires in/from the cache. However, Ehcache has a requirement that for each such listener [...]]]></description>
			<content:encoded><![CDATA[<p>When working with <a href="http://ehcache.org/" target="_blank">Ehcache</a> and <a href="http://en.wikipedia.org/wiki/Spring_Framework" target="_blank">Spring</a>, one might get to the point where he/she needs to implement cache event listeners: objects that are observing the cache and want to be notified by the cache when an element is put, removed or expires in/from the cache. However, Ehcache has a requirement that for each such listener you need to write 2 classes: a cache listener factory and the actual cache listener. Moreover, Ehcache takes care by itself of the instantiations of the factory and the listeners, so if one wants to have the listeners as Spring beans and have some other beans autowired in one&#8217;s listeners, then there is certainly a problem. Here is a solution to this problem. <span id="more-394"></span>In the next posts I will show a solution that contains a generic cache event listener factory, that can be configured to return custom beans when Ehcache asks for the listeners. This way, one gets the following benefits:</p>
<ul>
<li>no need to implement one factory for each listener. Reuse this generic factory for all the listeners</li>
<li>implement the listeners as full Spring beans, with all the DI support that comes with the framework</li>
<li>for each listener one needs one single line of configuration code (and the implementation of the listeners, of course)</li>
</ul>
<p>Here is the generic listener factory:<br />
[java]<br />
public class GenericCacheEventListenerFactory extends CacheEventListenerFactory {</p>
<p>    @Override<br />
    public CacheEventListener createCacheEventListener( Properties properties ) {<br />
        String beanName = properties.getProperty( &#8220;bean&#8221; );<br />
        if ( beanName == null ) {<br />
            throw new IllegalArgumentException( &#8220;The cache event listener factory must be configured with &#8216;bean&#8217; &#8221; +<br />
                                                        &#8220;property pointing to the Spring bean to return as cache event listener&#8221; );<br />
        }</p>
<p>        return (CacheEventListener) ApplicationContextProvider.getContext().getBean( beanName );<br />
    }<br />
}<br />
[/java]<br />
As the code presents it, I am accessing the Spring context statically, using the simple pattern with the <em>ApplicationContextProvider </em>that I presented in a <a href="http://bmocanu.ro/coding/387/access-spring-context-from-static-methods/" target="_self">previous post</a>. Ehcache creates an instance of the factory, and when it asks for the listener, the factory fetches the bean from the Spring application context and returns it to the cache manager.</p>
<p>Next step is to configure this factory in the Ehcache configuration file:<br />
[xml]<br />
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"<br />
         xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"<br />
         updateCheck="false"<br />
         monitoring="off"></p>
<p>    <defaultCache maxElementsInMemory="100000" eternal="false" timeToIdleSeconds="300" timeToLiveSeconds="500" memoryStoreEvictionPolicy="LRU" overflowToDisk="false"/></p>
<p>    <cache name="testCache" maxElementsInMemory="5000000" eternal="false" timeToIdleSeconds="3600" overflowToDisk="false" memoryStoreEvictionPolicy="LRU"><br />
        <cacheEventListenerFactory class="zendo.playground.spring.cache.GenericCacheEventListenerFactory"<br />
                                   properties="bean=myCacheEventListener"/><br />
    </cache><br />
</ehcache><br />
[/xml]<br />
When configuring, one must supply the name of the bean that should be returned as cache listener. If the property is not supplied, the factory will crash with an <em>IllegalArgumentException</em> to make the use aware of the slip.</p>
<p>Finally, here is the Spring application context, that defines the static application context provider, the cache manager and the actual cache listener (which is a very simple implementation of <a href="http://ehcache.org/apidocs/net/sf/ehcache/event/CacheEventListener.html" target="_blank"><em>CacheEventListener</em></a>) :<br />
[xml]<br />
<?xml version="1.0" encoding="UTF-8"?><br />
<beans xmlns="http://www.springframework.org/schema/beans"<br />
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"<br />
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"></p>
<p>    <bean id="applicationContextProvider" class="zendo.playground.spring.ApplicationContextProvider"/></p>
<p>    <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"></p>
<property name="configLocation" value="/zendo/playground/spring/cache/TestEhcacheConfig.xml"/>
    </bean></p>
<p>    <bean id="testCache" class="org.springframework.cache.ehcache.EhCacheFactoryBean"></p>
<property name="cacheManager" ref="cacheManager"/>
    </bean></p>
<p>    <bean id="myCacheEventListener" class="zendo.playground.spring.cache.MyCacheEventListener"/><br />
</beans><br />
[/xml]<br />
The drawback of this solution is the following:</p>
<ul>
<li>one needs to use the <em>ApplicationContextProvider</em> for static access to the application context. This means that if one&#8217;s application has more than one application context loaded (which, however, should not be the case, in most situations) then this solution will not work as easy as it is presented. One must craft a more complex <em>ApplicationContextProvider</em>, that keeps track of multiple contexts (each one with a distinct name).</li>
</ul>
<p>What do you think about this solution? Do you know if the problem can be solved in a better way? Please take the time to leave a comment and give me your opinion.</p>
]]></content:encoded>
			<wfw:commentRss>http://bmocanu.ro/coding/394/ehcache-event-listeners-as-spring-beans/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Access Spring context from static methods</title>
		<link>http://bmocanu.ro/coding/387/access-spring-context-from-static-methods/</link>
		<comments>http://bmocanu.ro/coding/387/access-spring-context-from-static-methods/#comments</comments>
		<pubDate>Sat, 22 Jan 2011 12:15:31 +0000</pubDate>
		<dc:creator>Bogdan</dc:creator>
				<category><![CDATA[Spring]]></category>
		<category><![CDATA[application context]]></category>
		<category><![CDATA[pattern]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[static access]]></category>

		<guid isPermaLink="false">http://bmocanu.ro/coding/?p=387</guid>
		<description><![CDATA[In this post I will present a very simple example that attempts to access an existing Spring application context from a class that has nothing to do with the Spring context. For example from a static method of a class. This is, of course, quite trivial, but I might make use of this little technique [...]]]></description>
			<content:encoded><![CDATA[<p>In this post I will present a very simple example that attempts to access an existing Spring application context from a class that has nothing to do with the Spring context. For example from a static method of a class. This is, of course, quite trivial, but I might make use of this little technique in some next posts about Spring, so I think it is due to first start with this small example.</p>
<p>Therefore, what I want to do is to have an up-and-running application context, and access the beans in that context from a static method. The best approach is to never have to do this. In an ideal case, all your classes are Spring beans, and therefore subjects to autowiring and dependency injection. However, from time to time you need to write a completely independent class, that needs to access some Spring beans.<span id="more-387"></span></p>
<p>The approach that I found it works quite ok is to have an <strong>ApplicationContextProvider.</strong> This class is picked by Spring as a bean, and since it implements <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/context/ApplicationContextAware.html" target="_blank">ApplicationContextAware</a> it will receive the application context. Once it does that, it stores the context in a static field, and then all the other non-Spring classes can get their hands on the context by calling some static <em>getContext()</em> method. Here is the class:</p>
<p>[java]<br />
public class ApplicationContextProvider implements ApplicationContextAware {<br />
    private static ApplicationContext context;</p>
<p>    public static ApplicationContext getContext() {<br />
        if ( context != null ) {<br />
            return context;<br />
        } else {<br />
            throw new IllegalStateException( &#8220;The Spring application context is not yet available. &#8221; +<br />
                                                     &#8220;The call to this method has been performed before the application context &#8221; +<br />
                                                     &#8220;provider was initialized&#8221; );<br />
        }<br />
    }</p>
<p>    @Override<br />
    public void setApplicationContext( ApplicationContext applicationContext ) throws BeansException {<br />
        if ( context == null ) {<br />
            ApplicationContextProvider.context = applicationContext;<br />
        } else {<br />
            throw new IllegalStateException( &#8220;The application context provider was already initialized. &#8221; +<br />
                                                     &#8220;It is illegal to place try to initialize the context provider twice or create &#8221; +<br />
                                                     &#8220;two different beans of this type (even if the contexts are different)&#8221; );<br />
        }<br />
    }<br />
}<br />
[/java]</p>
<p>My context XML file looks like the following:<br />
[xml]<br />
<?xml version="1.0" encoding="UTF-8"?><br />
<beans xmlns="http://www.springframework.org/schema/beans"<br />
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"<br />
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"></p>
<p>    <bean id="messagePrinter" class="zendo.playground.spring.MessagePrinter"/><br />
    <bean class="zendo.playground.spring.ApplicationContextProvider"/></p>
<p></beans><br />
[/xml]</p>
<p>And finally, the test classes that show how to use the ACP:<br />
[java]<br />
@RunWith( SpringJUnit4ClassRunner.class )<br />
@ContextConfiguration( locations = &#8220;TestStaticAccess.xml&#8221; )<br />
public class TestStaticAccess {<br />
    @Test<br />
    public void test() {<br />
        StaticAccess.doSmt();<br />
    }<br />
}</p>
<p>class StaticAccess {<br />
    public static void doSmt() {<br />
        MessagePrinter printer = (MessagePrinter) ApplicationContextProvider.getContext().getBean( &#8220;messagePrinter&#8221; );<br />
        printer.print();<br />
    }<br />
}<br />
[/java]</p>
<p>As one can see from above, the ACP guards against trying to access the context before it was initialized (like, for example, calling the ACP from the static constructor of a class, long before the Spring context was started) and against the usage of the ACP in two different Spring contexts.</p>
<p>Please mind that I am not referring here to the case when you are in a  servlet, for example, and want to access the Spring context. For this,  you can safely use the alternative provided by Spring: <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/context/support/WebApplicationContextUtils.html" target="_blank">WebApplicationContextUtils</a></p>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 130px; width: 1px; height: 1px; overflow: hidden;">http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/context/support/WebApplicationContextUtils.htmlWeb</div>
]]></content:encoded>
			<wfw:commentRss>http://bmocanu.ro/coding/387/access-spring-context-from-static-methods/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Transactional code blocks in Java</title>
		<link>http://bmocanu.ro/coding/351/transactional-code-blocks-in-java/</link>
		<comments>http://bmocanu.ro/coding/351/transactional-code-blocks-in-java/#comments</comments>
		<pubDate>Mon, 11 Oct 2010 09:29:04 +0000</pubDate>
		<dc:creator>Bogdan</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[coding]]></category>
		<category><![CDATA[transactions]]></category>
		<category><![CDATA[transparency]]></category>

		<guid isPermaLink="false">http://bmocanu.ro/blog/?p=351</guid>
		<description><![CDATA[Recently I read about a feature available in the .NET frametwork 2.0 or later that allows you to write transactional code blocks: that is, code blocks in which you can execute some actions or change the state of some objects and then, if something goes wrong, have the entire changes reverted to the initial state. [...]]]></description>
			<content:encoded><![CDATA[<p>Recently I read about a feature available in the .NET frametwork 2.0 or later that allows you to write transactional code blocks: that is, code blocks in which you can execute some actions or change the state of some objects and then, if something goes wrong, have the entire changes reverted to the initial state. The objects are taken to the state before the start of the transactional blocks and any other changes you performed are rolled back. The article <a href="http://msdn.microsoft.com/en-us/magazine/cc163688.aspx" target="_blank">is here</a>.</p>
<p>Reading this got me thinking about how can I implement this in Java. I formulate the problem as it follows:  <em>&#8220;How transparent for the user can one implement transactional code blocks?&#8221;</em>. Please note that I don&#8217;t say <em>&#8220;Can you&#8230;&#8221; </em>but <em>&#8220;How transparent&#8230;&#8221;</em>. I believe that allowing any amount of stress for the user, you can implement anything. The question is, how transparent and easy to use can one do it.<span id="more-351"></span></p>
<p>First, let me present some sample (pseudo) code. Let&#8217;s assume that I have two accounts, implemented with 2 atomic integers. What I want to do is transfer one amount of money from one accout to the other. The code is something like this:</p>
<p>[java]<br />
    public static void main( String[] args ) {<br />
        boolean someCondition = false;<br />
        AtomicInteger account1 = new AtomicInteger( 25000 );<br />
        AtomicInteger account2 = new AtomicInteger( 0 );</p>
<p>        { // transactional block<br />
            try {<br />
                System.out.println( &quot;Before op: &quot; + account1 + &quot; | &quot; + account2 );<br />
                account1.set( account1.get() &#8211; 5000 );<br />
                account2.set( account2.get() + 5000 );<br />
                System.out.println( &quot;After op: &quot; + account1 + &quot; | &quot; + account2 );</p>
<p>                if ( someCondition ) {<br />
                    throw new NullPointerException();<br />
                }<br />
            } catch ( Exception exception ) {<br />
                // rollback<br />
            }<br />
        } // END of transactional block<br />
        System.out.println( &quot;Finish: &quot; + account1 + &quot; | &quot; + account2 );<br />
    }<br />
[/java]</p>
<p>What I want is to have some helper classes so that I can mark the code block as transactional: if everything goes well, the changes performed in the block are permanent. If, however, something goes wrong (like throwing that NPE) then all the objects should be reverted to the initial state.</p>
<p>Therefore, I identify the following requirements to the problem:</p>
<ol>
<li> the state of all the objects should be reverted to the initial state, before entering the transactional block</li>
<li>the commit/rollback should be as transparent as possible for the user</li>
<li>the solution should work equally for objects as for primitive types</li>
</ol>
<p>Reverting the state of an object can be accomplished in two ways. First, the class of that object can be made aware of the whole transactional process, so that it implements methods like COMMIT and ROLLBACK. This way, it is the job of the object to save it&#8217;s state and restore it later, if something went wrong. This, however, invalidates the rule no. 2, because if the user has to implement COMMIT/ROLLBACK in each of the classes involved in the operations, then this is not transparent at all.</p>
<p>The second way is to let the classes be implemented without the knowledge of code transactions, and provide the transactional support using some external helper classes. This is what we will see in this post. We will implement some classes that the user can involve in the process, and all the classes will be completely unaware of the transactions that are started, committed or rolled back.</p>
<p>Implement this second method presents one big problem. Java does not allow passing the parameters by reference. In Java you pass parameters by value. Each value that you pass is copied, and in each method you work on a copy of the value. This means that you CANNOT change, in a method, the value of a variable from outside that method. This makes the rollback of variables a hard-to-accomplish task (I think you can do it by JNI + a specially crafted DLL that allows the swapping of memory contents (perhaps using <a href="http://jnative.sourceforge.net/" target="_blank">JNative</a> or some similar library; for the time being, I will exclude the JNI approach).</p>
<p>With these requirements in mind, here is how I solved the problem. First, the client code using my helper classes:</p>
<p>[java]<br />
    public static void main( String[] args ) {<br />
        AtomicInteger account1 = new AtomicInteger( 25000 );<br />
        AtomicInteger account2 = new AtomicInteger( 0 );</p>
<p>        Transactional trans = new Transactional();<br />
        trans.put( &quot;account1&quot;, account1 );<br />
        trans.put( &quot;account2&quot;, account2 );</p>
<p>        trans.execute( new Transactional.Execution() {<br />
            protected void execute() throws Exception {<br />
                AtomicInteger account1 = get( &quot;account1&quot; );<br />
                AtomicInteger account2 = get( &quot;account2&quot; );</p>
<p>                System.out.println( &quot;Before op: &quot; + account1 + &quot; | &quot; + account2 );<br />
                account1.set( account1.get() &#8211; 5000 );<br />
                account2.set( account2.get() + 5000 );</p>
<p>                System.out.println( &quot;After op: &quot; + account1 + &quot; | &quot; + account2 );</p>
<p>                throw new NullPointerException();<br />
                // rollback();<br />
            }<br />
        } );</p>
<p>        account1 = trans.get( &quot;account1&quot; );<br />
        account2 = trans.get( &quot;account2&quot; );<br />
        System.out.println( &quot;Finish: &quot; + account1 + &quot; | &quot; + account2 );<br />
    }<br />
[/java]</p>
<p>The user must, first, create an instance of Transactional, place the objects that will participate in the transaction in the context, then start the transactional block. Inside, he/she must get the transactional objects and make any operations on them. Upon exiting the block, he/she must get the objects back from the context. If something goes wrong, the objects that the user gets in the end will be the original ones, with unchanged state. On the other hand, if all works well the user gets back the changed objects. The rollback is performed if some exception escapes from the block or the rollback() method is called explicitly.</p>
<p>If all works well, the code prints:</p>
<pre>Before op: 25000 | 0
After op: 20000 | 5000
Finish: 20000 | 5000</pre>
<p>If something wrong happens:</p>
<pre>Before op: 25000 | 0
After op: 20000 | 5000
	java.lang.NullPointerException .......
Finish: 25000 | 0</pre>
<p>The helper classes are as follows:</p>
<p>[java]<br />
public class Transactional {</p>
<p>    private Map&lt;String, Object&gt; mappedObjects = new HashMap&lt;String, Object&gt;();<br />
    private Map&lt;String, byte[]&gt; serializedObjects = new HashMap&lt;String, byte[]&gt;();<br />
    private boolean rollback = false;</p>
<p>    public void put( String name, Object object ) {<br />
        mappedObjects.put( name, object );<br />
        serializedObjects.put( name, serializeObject( object ) );<br />
    }</p>
<p>    @SuppressWarnings( &quot;unchecked&quot; )<br />
    public &lt;T&gt; T get( String name ) {<br />
        return (T) mappedObjects.get( name );<br />
    }</p>
<p>    public void rollback() {<br />
        rollback = true;<br />
    }</p>
<p>    // &#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8211;</p>
<p>    public void execute( Execution exec ) {<br />
        try {<br />
            exec.transactionalParent = this;<br />
            exec.execute();<br />
        } catch ( Exception exception ) {<br />
            exception.printStackTrace();<br />
            rollback = true;<br />
        }<br />
        if ( rollback ) {<br />
            rollbackData();<br />
        }<br />
    }</p>
<p>    private byte[] serializeObject( Object object ) {<br />
        ObjectOutputStream oos = null;<br />
        try {<br />
            ByteArrayOutputStream baos = new ByteArrayOutputStream();<br />
            oos = new ObjectOutputStream( baos );<br />
            oos.writeObject( object );<br />
            return baos.toByteArray();<br />
        } catch ( Exception exception ) {<br />
            exception.printStackTrace();<br />
            return null;<br />
        } finally {<br />
            IOUtils.closeQuietly( oos );<br />
        }<br />
    }</p>
<p>    private Object unserializeObject( byte[] content ) {<br />
        ObjectInputStream ois = null;<br />
        try {<br />
            ByteArrayInputStream bais = new ByteArrayInputStream( content );<br />
            ois = new ObjectInputStream( bais );<br />
            Object result = ois.readObject();<br />
            return result;<br />
        } catch ( Exception exception ) {<br />
            exception.printStackTrace();<br />
            return null;<br />
        } finally {<br />
            IOUtils.closeQuietly( ois );<br />
        }<br />
    }</p>
<p>    private void rollbackData() {<br />
        Map&lt;String, Object&gt; originalMappedObjects = new HashMap&lt;String, Object&gt;();<br />
        for ( Entry&lt;String, Object&gt; mappedEntry : mappedObjects.entrySet() ) {<br />
            String key = mappedEntry.getKey();<br />
            Object originalObject = unserializeObject( serializedObjects.get( key ) );<br />
            originalMappedObjects.put( key, originalObject );<br />
        }<br />
        mappedObjects = originalMappedObjects;<br />
    }</p>
<p>    // &#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8211;</p>
<p>    protected static abstract class Execution {<br />
        private Transactional transactionalParent;</p>
<p>        protected abstract void execute() throws Exception;</p>
<p>        protected &lt;T&gt; T get( String name ) {<br />
            return transactionalParent.get( name );<br />
        }</p>
<p>        protected void rollback() {<br />
            transactionalParent.rollback();<br />
        }<br />
    }<br />
}<br />
[/java]</p>
<p>As you can see, I am serializing all the objects upon entering the transactional blocks, store the initial state of them in a separate map, and let the block move on. If some exception is thrown or the user calls explicitly the rollback() method, then I restore the state of all the objects, and replace the map of objects with the restored one.</p>
<p>This solution is not so great, since the user must constantly get and push objects from/to the transactional context. However, the rollback is transparent to the code and also the objects are free from any transaction-oriented code.</p>
<p>Can you design something better? Perhaps using annotations and APT? Or somehow enhance the transactional objects and add the commit/rollback methods at runtime, on fly? Feel free to drop a comment on these issues.</p>
]]></content:encoded>
			<wfw:commentRss>http://bmocanu.ro/coding/351/transactional-code-blocks-in-java/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
		<item>
		<title>King, Stephen &#8211; Under the Dome</title>
		<link>http://bmocanu.ro/coding/349/king-stephen-under-the-dome/</link>
		<comments>http://bmocanu.ro/coding/349/king-stephen-under-the-dome/#comments</comments>
		<pubDate>Sun, 26 Sep 2010 11:52:56 +0000</pubDate>
		<dc:creator>Bogdan</dc:creator>
				<category><![CDATA[Books I read]]></category>
		<category><![CDATA[book]]></category>

		<guid isPermaLink="false">http://bmocanu.ro/blog/?p=349</guid>
		<description><![CDATA[Reading Stephen King&#8217;s &#8220;Under the Dome&#8220; has been a nice experience. At first you get to know a lot of characters that are living in the unfortunate local town, and this might be a little confusing, at first. However, the author comes back to each character on a somehow regular basis, so that you don&#8217;t [...]]]></description>
			<content:encoded><![CDATA[<p><img class="alignleft" style="margin: 0px 5px;" title="Under the Dome" src="http://ecx.images-amazon.com/images/I/51Fe43%2BAe6L._BO2,204,203.jpg" alt="" width="200" height="300" />Reading <a href="http://www.amazon.com/Under-Dome-Novel-Stephen-King/dp/1439149038/ref=sr_1_1?s=gateway&amp;ie=UTF8&amp;qid=1285500736&amp;sr=8-1" target="_blank">Stephen King&#8217;s &#8220;<em>Under the Dome</em>&#8220;</a> has been a nice experience. At first you get to know a lot of characters that are living in the unfortunate local town, and this might be a little confusing, at first. However, the author comes back to each character on a somehow regular basis, so that you don&#8217;t forget what was that character doing and how he or she relates to the other people involved in the action. Also, all these character get to bring their share of participation and changing in the course of events in a manner that I really got to enjoy.</p>
<p>What got me by surprise in the book is the end of the story. The book has a considerable size, and the action goes in a fast pace. However, the actual explanation for the dome (the reason why the dome is there, who or what is powering it up, why that city and not a different one, perhaps why not a more important one) as well as the end of the entire story happens very fast, in less than 50 pages. You wait the entire book for getting the explanation for it, and when you actually get it you realise it is not quite the one you expected, or the one that you considered as a possible option. Sure, the alien element of the dome is presented to the user at about 1/3 of the book, but I think everyone reading the book expects the dome to have a more <em>earthly</em> nature. However I consider this as a good element of the book, as I was not disappointed by the outcome of the story.</p>
<p>The end of the book also tends to be philosophical and get a 2nd sub-level of interpreting the events, which is something that you don&#8217;t encounter in the rest of the book. All in all, though, an excellent reading and some great times that I had with it.</p>
]]></content:encoded>
			<wfw:commentRss>http://bmocanu.ro/coding/349/king-stephen-under-the-dome/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Developing Swing applications with Eclipse and Netbeans</title>
		<link>http://bmocanu.ro/coding/344/developing-swing-applications-with-eclipse-and-netbeans/</link>
		<comments>http://bmocanu.ro/coding/344/developing-swing-applications-with-eclipse-and-netbeans/#comments</comments>
		<pubDate>Thu, 19 Aug 2010 21:23:09 +0000</pubDate>
		<dc:creator>Bogdan</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[applets]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[mvc]]></category>
		<category><![CDATA[netbeans]]></category>
		<category><![CDATA[swing]]></category>
		<category><![CDATA[wysiwyg]]></category>

		<guid isPermaLink="false">http://bmocanu.ro/blog/?p=344</guid>
		<description><![CDATA[Developing Swing projects is not so easy with Eclipse all alone. Adding Netbeans to the mix really makes the things flowing.]]></description>
			<content:encoded><![CDATA[<p>I recently worked on some personal projects that required Swing development. They were some desktop applications and some Java applets. For the development, I used primarily Eclipse, because I like the IDE and I am very accustomed with it. However, for the Swing development, I didn&#8217;t wanted to write the code by myself. Therefore, I had to either search for a Swing plugin for Eclipse or revert to some other solution (read IDE) for developing the Swing parts. Here is the combination that works for me very well.<span id="more-344"></span>The first solution was to find a proper plugin for Eclipse to do the Swing layout of elements, editing of properties and the general binding of the interface to the controller. Although I haven&#8217;t tested the latest version of the existing Swing editors, a few months ago I remember that pretty much all of the plugins available for Eclipse were unstable and not really to be trusted for a project. Also, the generated code was not something to be proud of (although, as you will see in the next lines, my aim was to never touch or look at the code generated by the Swing editor.</p>
<p>Therefore, I chose to not do the Swing editing in Eclipse. I selected a different IDE, namely Netbeans, for the Swing part. Netbeans comes with a fantastic plugin for Swing programming, <a href="http://netbeans.org/features/java/swing.html" target="_blank">formerly called Matisse</a>. Working with the plugin is really easy, you can just drag the components, arrange them how you want, and that&#8217;s it.</p>
<p>To connect the interface to my code, I implemented <em>Controller</em> classes. The only customization that I added to the Swing forms was a reference to the corresponding controller and the wiring to the controller methods in the listeners for the buttons, menus, etc.</p>
<p>Here is how such a Swing dialog would look like:</p>
<p>[java]<br />
public class FolderDialog extends javax.swing.JDialog {<br />
private static final long serialVersionUID = 1L;</p>
<p>private FolderDialogController controller;</p>
<p>/**<br />
* Sets the controller to the given value. See {@link #controller} for more details.<br />
*<br />
* @param controller<br />
*            the new value for controller<br />
*/<br />
public void setController( FolderDialogController controller ) {<br />
this.controller = controller;<br />
}</p>
<p>// &#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-</p>
<p>/** Creates new form FolderDialog */<br />
public FolderDialog(java.awt.Frame parent, boolean modal) {<br />
super(parent, modal);<br />
initComponents();<br />
}</p>
<p>&#8230;&#8230;..</p>
<p>private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed<br />
controller.handleOkClick();<br />
}//GEN-LAST:event_jButton2ActionPerformed</p>
<p>&#8230;&#8230;..</p>
<p>}<br />
[/java]</p>
<p>The reference to the controller, the setter for it and the invocation of controller&#8217;s methods were the only changes that I performed in the generated code. Otherwise, all the changes were operated using Netbeans.</p>
<p>I found that it was quite easy to change between IDEs, not to mention that Netbeans is REALLY fast and smart at detecting changes in the project and reloading them (for example it detects the changes in the Eclipse projects, and reloads the classpath, the libraries, and various other settings).</p>
<p>Usually I am against the generators of code. I don&#8217;t trust them and I think that they are not able to generate the code as easy to read and as perfect as I am able to write it. Therefore, I try to avoid them as much as possible. That is why I never use JSP/JSF editors that provide drag &amp; drop features, like those available in VS for ASP.NET. However, for Swing development I found that Netbeans was a time saver and if it hadn&#8217;t been for me to favor Eclipse, I would have developed both of the Java desktop projects in Oracle&#8217;s IDE.</p>
]]></content:encoded>
			<wfw:commentRss>http://bmocanu.ro/coding/344/developing-swing-applications-with-eclipse-and-netbeans/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Q1: Get the star! … if you can &#8211; solution</title>
		<link>http://bmocanu.ro/coding/338/q1-get-the-star-%e2%80%a6-if-you-can-solution/</link>
		<comments>http://bmocanu.ro/coding/338/q1-get-the-star-%e2%80%a6-if-you-can-solution/#comments</comments>
		<pubDate>Wed, 04 Aug 2010 20:49:43 +0000</pubDate>
		<dc:creator>Bogdan</dc:creator>
				<category><![CDATA[Quiz of the week]]></category>
		<category><![CDATA[checked exceptions]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[language]]></category>
		<category><![CDATA[quiz]]></category>
		<category><![CDATA[star]]></category>

		<guid isPermaLink="false">http://bmocanu.ro/blog/?p=338</guid>
		<description><![CDATA[The first issue of the Quiz of the week category involved the writing of a method that could throw a checked exception without declaring it in the throws clause. Here are the 3 solutions to this problem.]]></description>
			<content:encoded><![CDATA[<p><a href="http://bmocanu.ro/coding/wp-content/uploads/2010/07/java-thinking-64.png"><img class="alignright" title="Quizz of the week" src="http://bmocanu.ro/coding/wp-content/uploads/2010/07/java-thinking-64.png" alt="Quizz of the week" width="64" height="66" /></a>The <a href="http://bmocanu.ro/blog/2010/07/q1-get-the-star-if-you-can/" target="_self">first issue</a> of the <em>Quiz of the week category</em> involved the writing of a method that could throw a checked exception without declaring it in the <em>throws</em> clause. Here are the 3 solutions to this problem.<span id="more-338"></span></p>
<p><strong>Solution no. 1 </strong>(Alin, Bedretin)</p>
<p>[java]<br />
    public static void doSomething() {<br />
        class CheckedExceptionThrower {<br />
            CheckedExceptionThrower() throws Exception {<br />
                throw new IOException();<br />
            }<br />
        }</p>
<p>        try {<br />
            CheckedExceptionThrower.class.newInstance();<br />
        } catch (InstantiationException e) {<br />
        } catch (IllegalAccessException e) {<br />
        }<br />
    }<br />
[/java]</p>
<p>The thing to keep in mind here is that the <em>Class.newInstance()</em> method invokes the specified constructor (depending on the parameters spcified to the method), and if that constructor throws a checked exception, then also <em>Class.newInstance()</em> throws that exception, although it doesn&#8217;t declare it.</p>
<p><strong>Solution no. 2</strong> (Cristian)</p>
<p>[java]<br />
    public static void doSomething() {<br />
        Thread.currentThread().stop(new IOException());<br />
    }<br />
[/java]</p>
<p>With this line, the current thread is forcibly stopped (don&#8217;t use this in real life; the method is deprecated anyway) and the specified exception is thrown at the point of call to <em>stop()</em>.</p>
<p><strong>Solution no. 3</strong> (Alexandru)</p>
<p>[java]<br />
    public static void doSomething() {<br />
        class MyClass&lt;T extends Throwable&gt; {<br />
            public void throwT(Throwable t) {<br />
                new MyClass&lt;Error&gt;().innerThrow(t);<br />
            }</p>
<p>            @SuppressWarnings(&quot;unchecked&quot;)<br />
            private void innerThrow(Throwable t) throws T {<br />
                throw (T) t;<br />
            }<br />
        }<br />
        MyClass&lt;IOException&gt; thrower = new MyClass&lt;IOException&gt;();<br />
        thrower.throwT(new IOException(&quot;test&quot;));<br />
    }<br />
[/java]</p>
<p>With this third solution, the generics mechanism is used to cover the fact that the actual exception object that is thrown is not an <em>Error</em> (which is an unchecked exception) but a checked one. An important note regarding the exception-checking mechanism is that it functions in a similar way to the generics mechanism: the check is performed at compile time, while at runtime no enforcement is performed.</p>
<p>Huge thanks to all who answered the first issue of the <em>Quiz of the week.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://bmocanu.ro/coding/338/q1-get-the-star-%e2%80%a6-if-you-can-solution/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Q1: Get the star! &#8230; if you can</title>
		<link>http://bmocanu.ro/coding/334/q1-get-the-star-if-you-can/</link>
		<comments>http://bmocanu.ro/coding/334/q1-get-the-star-if-you-can/#comments</comments>
		<pubDate>Thu, 22 Jul 2010 10:32:19 +0000</pubDate>
		<dc:creator>Bogdan</dc:creator>
				<category><![CDATA[Quiz of the week]]></category>
		<category><![CDATA[checked exceptions]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[language]]></category>
		<category><![CDATA[quiz]]></category>
		<category><![CDATA[star]]></category>

		<guid isPermaLink="false">http://bmocanu.ro/blog/?p=331</guid>
		<description><![CDATA[Problems and questions about various less known aspects of languages and tools. One question per week, the answer can be found at the beginning of the next question. This is item Q1]]></description>
			<content:encoded><![CDATA[<p><a href="http://bmocanu.ro/coding/wp-content/uploads/2010/07/java-thinking-64.png"><img class="alignright size-full wp-image-333" style="margin-right: 3px; margin-left: 3px; border: 0pt none;" title="Quizz of the week" src="http://bmocanu.ro/coding/wp-content/uploads/2010/07/java-thinking-64.png" alt="Quizz of the week" width="64" height="66" /></a>I started this category because I like to solve problems, of any type, especially if they are related to the languages and the tools that I am using on a daily basis. This type of posts is not something new, of course. You can find probably hundreds of sites and blogs that are doing pretty much the same thing. A simple search on google reveals <a href="http://www.iut-info.univ-lille1.fr/docs/examplets/developer.java.sun.com/developer/qow/archive/default.htm" target="_blank">this</a>, but you could find some other sites for sure.</p>
<p>The problems that I will post here are not completely invented by me. Most of them are actually found in other books, on the internet, in the language specs (such as <a href="http://java.sun.com/docs/books/jls/third_edition/html/j3TOC.html" target="_blank">JLS</a>), in the APIs, in the code that I am working on every day. Some of them (albeit only a few) are actually invented by me, but I don&#8217;t exclude the possibility that they are already posted somewhere else. Anyway, the source of the problem is irrelevant.</p>
<p>The answer(s) to each problem will be posted in the next question, next week.</p>
<p>Since I am posting these problems, I would also love to get comments with possible solutions, ideas for improving the problem or just general remarks about the discussed problem. So feel free to join the club, and solve the issues <img src='http://bmocanu.ro/coding/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Here is the first issue of this series. <span id="more-334"></span></p>
<p>We have one little gold star for you:</p>
<p>[java]public class TestQ1 {</p>
<p>    public static void main( String[] args ) {<br />
        try {<br />
            if ( 2 &gt; 3 ) {<br />
                throw new IOException();<br />
            }<br />
            doSomething();<br />
        } catch ( IOException exception ) {<br />
            System.out.println( &quot;*&quot; );<br />
        }<br />
    }</p>
<p>    public static void doSomething() {<br />
        //<br />
        // edit here<br />
        //<br />
    }<br />
}<br />
[/java]</p>
<p>What you need to do is write some code in the commented lines above so that the <strong>star</strong> in line 10 is printed. You are NOT allowed to change any other part of the code except the commented lines (however, you can insert as many lines as you want in that section, not just three).</p>
]]></content:encoded>
			<wfw:commentRss>http://bmocanu.ro/coding/334/q1-get-the-star-if-you-can/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Combining JUnit Theories/Parameterized tests with Spring</title>
		<link>http://bmocanu.ro/coding/320/combining-junit-theoriesparameterized-tests-with-spring/</link>
		<comments>http://bmocanu.ro/coding/320/combining-junit-theoriesparameterized-tests-with-spring/#comments</comments>
		<pubDate>Wed, 07 Jul 2010 14:13:51 +0000</pubDate>
		<dc:creator>Bogdan</dc:creator>
				<category><![CDATA[Spring]]></category>
		<category><![CDATA[dependency injection]]></category>
		<category><![CDATA[ioc]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[junit]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[theories]]></category>
		<category><![CDATA[unit testing]]></category>

		<guid isPermaLink="false">http://bmocanu.ro/blog/?p=320</guid>
		<description><![CDATA[JUnit tests that are using Theories or Parameterized approaches can use Spring at the same, provided that you take care of invoking Spring in order to have the test object's references autowired.]]></description>
			<content:encoded><![CDATA[<p>In almost any project that is using Spring, you get to the point where the Spring&#8217;s dependency injection mechanism is required also for unit tests. Combining this with JUnit leads one to the usage of the <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/test/context/junit4/SpringJUnit4ClassRunner.html" target="_blank">SpringJUnit4Runner</a> to enable the initialization of the Spring context, as well as the autowiring of various beans in the test object that is just being executed.</p>
<p>However, for more specialized unit testing purposes, such as implementing <a href="http://www.junit.org/apidocs/org/junit/runners/Parameterized.html" target="_blank">parameterized</a> tests or <a href="http://blogs.sun.com/jacobc/entry/junit_theories" target="_blank">theories</a>, one must use a specialized runner (<em>Parameterized</em> and <em>Theories</em>, respectively). This, of course, gets in conflict with Spring, which needs to use it&#8217;s own runner. JUnit does not support multiple runners for the same unit test (and except for the Spring runner, all the other runners are pretty excluding one another so it kind of makes sense to allow only one runner at a time).<span id="more-320"></span></p>
<p>Here is a way for implementing a unit test class that is using Theories and Spring, combined:</p>
<p>[java]import org.junit.Before;<br />
import org.junit.experimental.theories.DataPoints;<br />
import org.junit.experimental.theories.Theories;<br />
import org.junit.experimental.theories.Theory;<br />
import org.junit.runner.RunWith;<br />
import org.springframework.beans.factory.annotation.Autowired;<br />
import org.springframework.test.context.ContextConfiguration;<br />
import org.springframework.test.context.TestContextManager;</p>
<p>@RunWith( Theories.class )<br />
@ContextConfiguration( locations = &quot;classpath:/spring-context.xml&quot; )<br />
public class IndirectSpringTest {</p>
<p>    private TestContextManager testContextManager;</p>
<p>    @Autowired<br />
    private PointProvider provider;</p>
<p>    @DataPoints<br />
    public static int[] inputIndexes = { 0, 1, 2 };</p>
<p>    // &#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;</p>
<p>    @Before<br />
    public void setUp() throws Exception {<br />
        this.testContextManager = new TestContextManager( getClass() );<br />
        this.testContextManager.prepareTestInstance( this );<br />
    }</p>
<p>    @Theory<br />
    public void testThatEverythingIsWell( int index ) {<br />
        String point = provider.getPoint( index );<br />
        System.out.println( &quot;Point: &quot; + point );<br />
    }</p>
<p>}<br />
[/java]</p>
<p>The central point of the sample code is the usage of the <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/test/context/junit4/SpringJUnit4ClassRunner.html" target="_blank">TestContextManager</a> class for loading the Spring context (this is performed only once per unit test class, not for each method) and for initializing the test object before starting the actual test. The <em>prepareTestInstance()</em> method makes the autowiring of the test object&#8217;s dependencies, therefore simulating the behaviour of the <em>SpringJUnit4ClassRunner</em>.</p>
<p>On a general note, keep in mind that JUnit creates a new instance of the unit test class for each test method. The order of the methods is:</p>
<ol>
<li>@BeforeClass static method</li>
<li>constructor</li>
<li>@Before method</li>
<li>test method</li>
<li>@After method</li>
<li><em>goto 2 </em> <img src='http://bmocanu.ro/coding/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </li>
<li>@AfterClass static method</li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://bmocanu.ro/coding/320/combining-junit-theoriesparameterized-tests-with-spring/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
	</channel>
</rss>

