<?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>Smartkey - Java Software Consultancy &#187; Java Programming</title>
	<atom:link href="http://blog.smartkey.co.uk/category/development/javaprogramming/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.smartkey.co.uk</link>
	<description></description>
	<lastBuildDate>Tue, 13 Dec 2011 15:03:46 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Adding a thread timeout to methods in Java</title>
		<link>http://blog.smartkey.co.uk/2011/09/adding-a-thread-timeout-to-methods-in-java/</link>
		<comments>http://blog.smartkey.co.uk/2011/09/adding-a-thread-timeout-to-methods-in-java/#comments</comments>
		<pubDate>Thu, 01 Sep 2011 13:19:55 +0000</pubDate>
		<dc:creator>Steve Neal</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Java Programming]]></category>
		<category><![CDATA[Concurrency]]></category>
		<category><![CDATA[Concurrent]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Thread]]></category>

		<guid isPermaLink="false">http://blog.smartkey.co.uk/?p=924</guid>
		<description><![CDATA[When calling a method that could potentially take longer that you&#8217;d like to complete, it is possible to write code that will back out after a given time period. 
This can happen in numerous circumstances where you&#8217;d like an application to maintain a degree of liveness. I&#8217;ve used it recently in an application that needed [...]]]></description>
			<content:encoded><![CDATA[<p>When calling a method that could potentially take longer that you&#8217;d like to complete, it is possible to write code that will back out after a given time period. </p>
<p>This can happen in numerous circumstances where you&#8217;d like an application to maintain a degree of liveness. I&#8217;ve used it recently in an application that needed to run a number of external scripts; if the script does not complete, for whatever reason, the timeout ensures the the calling thread does not get blocked and the remaining scripts can be launched.</p>
<p>Here&#8217;s the basic idea:</p>
<pre class="brush: php">
public class TimeoutDemo {

    //maintains a thread for executing the doWork method
    private ExecutorService executor = Executors.newFixedThreadPool(1);

    public void doWork() {
        //perform some long running task here...
    }

    public void doWorkWithTimeout(int timeoutSecs) {

        //set the executor thread working
        final Future&lt;?&gt; future = executor.submit(new Runnable() {
            public void run() {
                try {
                    doWork();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        });

        //check the outcome of the executor thread and limit the time allowed for it to complete
        try {
            future.get(timeoutSecs, TimeUnit.SECONDS);
        } catch (Exception e) {
            //ExecutionException: deliverer threw exception
            //TimeoutException: didn&#039;t complete within downloadTimeoutSecs
            //InterruptedException: the executor thread was interrupted

            //interrupts the worker thread if necessary
            future.cancel(true);

            log.warn(&quot;encountered problem while doing some work&quot;, e);
        }
    }
}
</pre>
<p>The doWork method is the one that will actually do some potentially long running work. The doWorkWithTimeout illustrates how the java.util.concurrent classes can be used to prevent the method from taking too long to complete. When calling the latter method, just specify the timeout period in minutes.</p>
<p>The trick here is that the actual work will be done by a dedicated worker thread. The calling thread will handle the timeout management and also handle any exceptions thrown by the worker.</p>
<p>Variations of this pattern can be used for methods that accept parameters (just make them final) and for ones that return values too (just return the value from the future.get(&#8230;) call).</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smartkey.co.uk/2011/09/adding-a-thread-timeout-to-methods-in-java/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>What info can you get from an HttpServletRequest?</title>
		<link>http://blog.smartkey.co.uk/2011/02/httpservletrequestmethods/</link>
		<comments>http://blog.smartkey.co.uk/2011/02/httpservletrequestmethods/#comments</comments>
		<pubDate>Tue, 01 Feb 2011 13:17:44 +0000</pubDate>
		<dc:creator>Steve Neal</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Java Programming]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JSP]]></category>
		<category><![CDATA[servlet]]></category>

		<guid isPermaLink="false">http://blog.smartkey.co.uk/?p=883</guid>
		<description><![CDATA[There are many methods on an HttpServletRequest, and if you&#8217;re anything like me, you&#8217;ll forget exactly what each of them returns. Rather than a long winded investigation into them all, here&#8217;s a sample URL:

https://localhost:8443/test/welcome?a=1&#038;b=2

The &#8216;/test&#8217; in the URL will map to a servlet called test. The servlet will dispatch the request to a JSP for [...]]]></description>
			<content:encoded><![CDATA[<p>There are many methods on an HttpServletRequest, and if you&#8217;re anything like me, you&#8217;ll forget exactly what each of them returns. Rather than a long winded investigation into them all, here&#8217;s a sample URL:<br />
<code><br />
https://localhost:8443/test/welcome?a=1&#038;b=2<br />
</code></p>
<p>The &#8216;/test&#8217; in the URL will map to a servlet called test. The servlet will dispatch the request to a JSP for rendering that has the following scriplet code in it:</p>
<pre class="brush: php">
RequestURL: &lt;%= request.getRequestURL() %&gt; &lt;br&gt;
RequestURI: &lt;%= request.getRequestURI() %&gt; &lt;br&gt;
QueryString: &lt;%= request.getQueryString() %&gt; &lt;br&gt;
ServletPath: &lt;%= request.getServletPath() %&gt; &lt;br&gt;
PathInfo: &lt;%= request.getPathInfo() %&gt; &lt;br&gt;
PathTranslated: &lt;%= request.getPathTranslated() %&gt;&lt;br&gt;
AuthType: &lt;%= request.getAuthType() %&gt; &lt;br&gt;
LocalAddress: &lt;%= request.getLocalAddr() %&gt; &lt;br&gt;
Method: &lt;%= request.getMethod() %&gt; &lt;br&gt;
RemoteUser: &lt;%= request.getRemoteUser() %&gt; &lt;br&gt;
</pre>
<p>this is the output generated:</p>
<pre class="brush: php">
RequestURL: https://localhost:8443/test/welcome
RequestURI: /test/welcome
QueryString: a=1&amp;b=2
ServletPath: /test
PathInfo: /welcome
PathTranslated: C:\projects\testproj\out\artifacts\testapp_war_exploded\welcome
AuthType: CLIENT_CERT
LocalAddress: 127.0.0.1
Method: GET
RemoteUser: Steve
</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.smartkey.co.uk/2011/02/httpservletrequestmethods/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Implementing Flash Scope in Java Web Applications</title>
		<link>http://blog.smartkey.co.uk/2011/01/implementing-flash-scope-in-java-web-applications/</link>
		<comments>http://blog.smartkey.co.uk/2011/01/implementing-flash-scope-in-java-web-applications/#comments</comments>
		<pubDate>Mon, 17 Jan 2011 19:20:29 +0000</pubDate>
		<dc:creator>Steve Neal</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Java Programming]]></category>
		<category><![CDATA[Flash scope]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JSP]]></category>
		<category><![CDATA[Request]]></category>
		<category><![CDATA[Session]]></category>
		<category><![CDATA[Spring MVC]]></category>
		<category><![CDATA[Web]]></category>

		<guid isPermaLink="false">http://blog.smartkey.co.uk/?p=828</guid>
		<description><![CDATA[While working recently on a Spring MVC project I found myself wishing it supported flash scope. I hunted around for a simple solution but couldn&#8217;t find anything that didn&#8217;t rely on having to import large framework libraries. After a little thought I came up with the following simple and lightweight solution that has worked really [...]]]></description>
			<content:encoded><![CDATA[<p>While working recently on a Spring MVC project I found myself wishing it supported flash scope. I hunted around for a simple solution but couldn&#8217;t find anything that didn&#8217;t rely on having to import large framework libraries. After a little thought I came up with the following simple and lightweight solution that has worked really well for me. I&#8217;ve included the code for this below so feel free to try it out.</p>
<h3>What is Flash Scope</h3>
<p>Flash scope is a useful part of many web frameworks. It allows the use of the <a href="http://en.wikipedia.org/wiki/Post/Redirect/Get">post/redirect/get</a> design pattern to alleviate many of the problems associated with handling multiple submits or resubmission of data in browser requests to the server.</p>
<p>Flash scope is an additional scope to those provided in a standard Java Web application (page, request, session and application). Any attributes held in flash scope will be available for the duration of the current request, and the subsequent request too.</p>
<h3>My Implementation</h3>
<p>To implement flash scope in my application, I added a servlet filter that checks for request attribute names starting with &#8216;<strong>flash.</strong>&#8216;. When it finds such an attribute, it ensures that it is made available in the subsequent request by temporarily storing it in the user&#8217;s session, and then reinstating it when the next request is received.</p>
<p>For example, to add a message to flash scope, just use the regular syntax for adding a request scoped attribute and let the fiter take care of it:</p>
<pre class="brush: php">
request.setAttribute(&quot;flash.message&quot;, &quot;Here is the news...&quot;);
</pre>
<p>The above attribute can then be accessed in the redirect target JSP using EL or scriptlet syntax (omitting the &#8216;<strong>flash.</strong>&#8216; prefix):</p>
<pre class="brush: php">
${message}
or
&lt;%= request.getAttribute(&quot;message&quot;)  %&gt;
</pre>
<p>Here&#8217;s the code for the filter:</p>
<pre class="brush: php">
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * Ensures that any request parameters whose names start
 * with &#039;flash.&#039; are available for the next request too.
 */
public class FlashScopeFilter implements Filter {

    private static final String FLASH_SESSION_KEY = &quot;FLASH_SESSION_KEY&quot;;

    @SuppressWarnings(&quot;unchecked&quot;)
    public void doFilter(ServletRequest request, ServletResponse response,
					FilterChain chain) throws IOException, ServletException {

        //reinstate any flash scoped params from the users session
		//and clear the session
        if (request instanceof HttpServletRequest) {
            HttpServletRequest httpRequest = (HttpServletRequest) request;
            HttpSession session = httpRequest.getSession(false);
            if (session != null) {
                Map&lt;String, Object&gt; flashParams = (Map&lt;String, Object&gt;)
									session.getAttribute(FLASH_SESSION_KEY);
                if (flashParams != null) {
                    for (Map.Entry&lt;String, Object&gt; flashEntry : flashParams.entrySet()) {
                        request.setAttribute(flashEntry.getKey(), flashEntry.getValue());
                    }
                    session.removeAttribute(FLASH_SESSION_KEY);
                }
            }
        }

        //process the chain
        chain.doFilter(request, response);

        //store any flash scoped params in the user&#039;s session for the
		//next request
        if (request instanceof HttpServletRequest) {
            HttpServletRequest httpRequest = (HttpServletRequest) request;
            Map&lt;String, Object&gt; flashParams = new HashMap();
			Enumeration e = httpRequest.getAttributeNames();
            while (e.hasMoreElements()) {
                String paramName = (String) e.nextElement();
                if (paramName.startsWith(&quot;flash.&quot;)) {
                    Object value = request.getAttribute(paramName);
                    paramName = paramName.substring(6, paramName.length());
                    flashParams.put(paramName, value);
                }
            }
            if (flashParams.size() &gt; 0) {
                HttpSession session = httpRequest.getSession(false);
                session.setAttribute(FLASH_SESSION_KEY, flashParams);
            }
        }
    }

    public void init(FilterConfig filterConfig) throws ServletException {
        //no-op
    }

    public void destroy() {
        //no-op
    }
}
</pre>
<p>You can see from the listing, that the filter stores the flash scoped parameters in a session scoped  map called FLASH_SESSION_KEY. Before the request is processed by the filter chain, the flash attributes are retrieved from the session and added to request scope; after the chain has finished, any new flash scoped parameters are stored in a new session scoped map.</p>
<p>Note that the attributes have the &#8216;<strong>flash.</strong>&#8216; prefix removed when added to the session scoped map &#8211; this not only ensures that they can be accessed using their &#8217;short name&#8217;, but that they are only kept in the session for one extra request.</p>
<p>This approach is not Spring specific and should work with and Java Web framework. I&#8217;ve omitted the configuration for the filter as there are loads of examples of how to do this on the Internet already.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smartkey.co.uk/2011/01/implementing-flash-scope-in-java-web-applications/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Specifying a different config file for Log4J</title>
		<link>http://blog.smartkey.co.uk/2010/09/specifying-config-file-for-log4j/</link>
		<comments>http://blog.smartkey.co.uk/2010/09/specifying-config-file-for-log4j/#comments</comments>
		<pubDate>Thu, 02 Sep 2010 15:24:55 +0000</pubDate>
		<dc:creator>Steve Neal</dc:creator>
				<category><![CDATA[Java Programming]]></category>
		<category><![CDATA[Configuration]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[log4j]]></category>

		<guid isPermaLink="false">http://blog.smartkey.co.uk/?p=772</guid>
		<description><![CDATA[Generally, adding a log4j.properties file to the classpath is all that needed to bootstrap your Log4J runtime. In certain cases though you might want to override this behaviour.
I needed to do this recently and it took me a while to find out how to do it in the Log4J docs, so I though I&#8217;d make [...]]]></description>
			<content:encoded><![CDATA[<p>Generally, adding a log4j.properties file to the classpath is all that needed to bootstrap your Log4J runtime. In certain cases though you might want to override this behaviour.</p>
<p>I needed to do this recently and it took me a while to find out how to do it in the Log4J docs, so I though I&#8217;d make a note of how to do it here.</p>
<p>To specify a file that Log4J will use instead of the default, pass its details as a system property when starting the JVM as follows:</p>
<pre class="brush: php">

java -Dlog4j.configuration=resources/log4j_dev.properties
</pre>
<p>The above example will load the log4j_dev.properties file from within the resources folder in the classpath. A file URL may also be specified:</p>
<pre class="brush: php">

java -Dlog4j.configuration=file:/resources/log4j_dev.properties
</pre>
<p>This will cause the log4j_dev.properties file to be loaded from the resources folder at the root of the file system.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smartkey.co.uk/2010/09/specifying-config-file-for-log4j/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Getting a &#8220;Netscape security model is no longer supported&#8221; error when using IntelliJ</title>
		<link>http://blog.smartkey.co.uk/2010/08/netscape-security-model-error-in-intellij/</link>
		<comments>http://blog.smartkey.co.uk/2010/08/netscape-security-model-error-in-intellij/#comments</comments>
		<pubDate>Fri, 06 Aug 2010 10:48:01 +0000</pubDate>
		<dc:creator>Steve Neal</dc:creator>
				<category><![CDATA[Java Programming]]></category>
		<category><![CDATA[errors]]></category>
		<category><![CDATA[IntelliJ]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[netscape]]></category>

		<guid isPermaLink="false">http://blog.smartkey.co.uk/?p=769</guid>
		<description><![CDATA[I&#8217;ve been working on a JMS application that uses encryption with JNDI authentication and have encountered the following error message when running it:

Netscape security model is no longer supported. Please migrate to the Java 2 security model instead.

It turns out that this is a problem with the JDK&#8217;s plugin.jar file and can be fixed quite [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been working on a JMS application that uses encryption with JNDI authentication and have encountered the following error message when running it:<code></code><br />
<code><br />
Netscape security model is no longer supported. Please migrate to the Java 2 security model instead.<br />
</code></p>
<p>It turns out that this is a problem with the JDK&#8217;s plugin.jar file and can be fixed quite easily by removing it from IntelliJ&#8217;s JDK configuration page as follows:</p>
<ol>
<li>In your project open the Project Structure dialog and click to edit the JDK you are working with</li>
<li>Remove the plugin.jar file from the JDK classpath</li>
</ol>
<p>That should fix it.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smartkey.co.uk/2010/08/netscape-security-model-error-in-intellij/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Open Session in View Pattern for Spring and JPA</title>
		<link>http://blog.smartkey.co.uk/2010/03/open-session-in-view-pattern-spring-jpa/</link>
		<comments>http://blog.smartkey.co.uk/2010/03/open-session-in-view-pattern-spring-jpa/#comments</comments>
		<pubDate>Mon, 08 Mar 2010 18:13:24 +0000</pubDate>
		<dc:creator>Steve Neal</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Java Programming]]></category>
		<category><![CDATA[Hibernate]]></category>
		<category><![CDATA[JPA]]></category>
		<category><![CDATA[JSP]]></category>
		<category><![CDATA[Open]]></category>
		<category><![CDATA[Session]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[Transaction]]></category>
		<category><![CDATA[View]]></category>
		<category><![CDATA[Web]]></category>

		<guid isPermaLink="false">http://blog.smartkey.co.uk/?p=676</guid>
		<description><![CDATA[The Open Session in View Pattern is well publicised in Hibernate circles as the best practice approach to presenting data in the Web tier of an application. In this article I'll demonstrate how simple it is to configure a Spring application to do the same thing with the Java Persistence API (JPA).]]></description>
			<content:encoded><![CDATA[<p>The Open Session in View Pattern is a well publicised <a href="https://www.hibernate.org/43.html" target="_blank">design pattern</a> for Hibernate applications and is considered the best practice approach to presenting data within the Web tier of an application. In this article I&#8217;ll demonstrate how simple it is to configure a Spring application to work the same way when JPA is used for the persistence technology. The exact same principles apply for a plain Spring/Hibernate application that does not use JPA.</p>
<h3>What is Open Session in View?</h3>
<p>The Java Persistence API (JPA) allows an object oriented model to be mapped to a relational database. JPA is a standard specification for Java based Object Relational Mapping frameworks &#8211; in order to use JPA an underlying implementation must be available; the most common choice being Hibernate.</p>
<p>Both JPA an Hibernate support lazy loading of data to restrict the number of queries fired off to the database. In general this means that data will be loaded on demand when methods are called, on a loaded object, that require more data to be loaded. In order for this to work, the object that the method is called on must have been loaded by JPA and be part of the current running transaction.</p>
<p>In a Spring application, calls to demarcate transactions are generally handled by the Spring interceptors.Transactions are normally started when a method call is made on a Spring managed object and committed once that method call ends. This means that if a JSP page requests data by calling a transactional method on a Spring managed bean, then it can only access the data in that bean that has already been loaded within that call. Any calls for data that might be loaded lazily will fail because the object is no longer attached to a JPA transaction after that method call has returned.</p>
<p>Hibernate developers solved this problem using the Open Session in View design, which associates the active session (and hence it&#8217;s transaction) with the thread that makes the call. In this design, the transaction will be committed when the thread completed processing the request, rather than when a method call completes. This allows lazily loaded data to be loaded within the JSP page not just within Spring managed objects.</p>
<h3>Providing Request Scoped Transactions</h3>
<p>A standard way to intercept requests in any Java Web application is to use a web filter. Spring provide an out-of-the-box Web filters that implement the Open Session in View design for both Hibernate and JPA. We will see the JPA version here, but the Hibernate one works in just the same way; just change the class name in the configuration file.</p>
<p>In web.xml:</p>
<pre class="brush: xml">
&lt;filter&gt;
    &lt;filter-name&gt;oemInViewFilter&lt;/filter-name&gt;
    &lt;filter-class&gt;
        org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter
    &lt;/filter-class&gt;
    &lt;init-param&gt;
        &lt;param-name&gt;entityManagerFactoryBeanName&lt;/param-name&gt;
        &lt;param-value&gt;reportsEntityManagerFactory&lt;/param-value&gt;
    &lt;/init-param&gt;
&lt;/filter&gt;

&lt;filter-mapping&gt;
    &lt;filter-name&gt;oemInViewFilter&lt;/filter-name&gt;
    &lt;url-pattern&gt;*.jsp&lt;/url-pattern&gt;
&lt;/filter-mapping&gt;
</pre>
<p>The filter class is from the Spring framework libraries. The filter mapping, in this example, applies this filter to all URLs ending with &#8216;.jsp&#8217;; this means that all JSPs that retrieve a lazily loaded object form the service tier of the application are now free to read any data members from it &#8211; any unloaded data will be loaded from the database when calls are made to access it. </p>
<p>Be aware that the filter turns off the auto-flush behaviour of the standard entity manager. This means that any changes that are made to the data in the JSP will not be persisted. The filter can be configured to flush these if requested.</p>
<p>Finally, the init-param that&#8217;s provided to the filter is optional and can be used to explicitly name the entity manager factory that will be used. The example shows how to use an entity manager named &#8216;reportsEntityManagerFactory&#8217; in the Spring configuration files; the default value for this is &#8216;entityManagerFactory&#8217;.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smartkey.co.uk/2010/03/open-session-in-view-pattern-spring-jpa/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using Mockito to Unit Test Java Applications</title>
		<link>http://blog.smartkey.co.uk/2010/02/mockito-unit-test-java/</link>
		<comments>http://blog.smartkey.co.uk/2010/02/mockito-unit-test-java/#comments</comments>
		<pubDate>Thu, 25 Feb 2010 18:39:26 +0000</pubDate>
		<dc:creator>Steve Neal</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Java Programming]]></category>
		<category><![CDATA[Tool support]]></category>
		<category><![CDATA[Google Code]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Mockito]]></category>
		<category><![CDATA[Test]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://blog.smartkey.co.uk/?p=604</guid>
		<description><![CDATA[If you&#8217;ve spent any time writing unit tests then you&#8217;ll know that it&#8217;s not always straight-forward. Certain things are inherently hard to test. In this post I&#8217;ll show you the basic principles of creating mock objects with a little help from the Mockito mocking tool.
One common problem faced when unit testing is how to test [...]]]></description>
			<content:encoded><![CDATA[<p>If you&#8217;ve spent any time writing unit tests then you&#8217;ll know that it&#8217;s not always straight-forward. Certain things are inherently hard to test. In this post I&#8217;ll show you the basic principles of creating mock objects with a little help from the <a href="http://www.mockito.org">Mockito</a> mocking tool.</p>
<p>One common problem faced when unit testing is how to test one object when it is dependant on another object. You could create instances of both the object under test and the dependent object and test them both together, however testing aggregated objects is not what unit testing is about &#8211; unit tests should test individual objects for their correct behaviour, not aggregations of objects! Moreover, this approach just won&#8217;t work if the dependent object hasn&#8217;t even been implemented yet.</p>
<p>A common technique for handling dependencies in unit tests is to provide a surrogate, or &#8220;mock&#8221; object, for the dependent object instead of a real one. The mock object will implement a simplified version of the real objects methods that return predictable results and can be used for testing purposes. </p>
<p>The drawback of this approach is that in a complex application, you could find yourself creating a lot of mock objects. This is where frameworks like Mockito can save you a lot of time and effort.</p>
<h3>A Test Scenario</h3>
<p>To demonstrate what you can do with Mockito, we&#8217;ll examine how we might test an Account object that is dependant on a data access object (AccountDAO).  The account object can calculate the charges applicable in the current month by using the DAO to count the number of days overdrawn and then performing a simple calculation on the value obtained from that call. The method names on the classes we&#8217;ll use are self-explanatory:</p>
<p><img src="http://blog.smartkey.co.uk/wp-content/uploads/2010/02/AccountAndDAO1.png" alt="AccountAndDAO" title="AccountAndDAO" width="376" height="55" class="aligncenter size-full wp-image-648" /><br />
To test this thoroughly, we should test two things:</p>
<ol>
<li>that the account obtains the number of overdrawn days by calling the correct method on the DAO,</li>
<li>that the account calculates the correct fees based upon the value it gets back from the call.</li>
</ol>
<h3>Testing that the account calls the correct method on the DAO</h3>
<p>Using JUnit to run the test case, we could write something like this:</p>
<pre class="brush: java">
import static org.mockito.Mockito.*;

public class TestAccount {
    @Test
    public void checkAccountCallsDaoMethods() {
        //create the object under test
        Account account = new Account();

        //create a mock DAO
        AccountDAO mockedDao = mock(AccountDAO.class);	

        //associate the mocked DAO with the object under test
        account.setDAO(dao);

        //call the method under test
        long charge = account.calculateCharges();

        //verify that the &#039;countOverdrawnDaysThisMonth&#039; was called
        verify(mockedDao).countOverdrawnDaysThisMonth();
    }
}
</pre>
<p>Taking centre stage in all this is the Mockito class which has a bunch of static methods that are used within the unit test (note the static import on line 1). </p>
<p>The call to the &#8216;mock&#8217; method (line 10) creates a mock object that can be used in place of a real AccountDAO. The call to &#8216;verify&#8217; (line 19), will throw an exception if the &#8216;countOverdrawnDaysThisMonth&#8217; method was not called on the mock object. </p>
<p>It is worth noting here that this is a simple example which just demonstrates the basic principle of verification, it is also possible to use the verify method to check for parameter values and ranges in the method call too.</p>
<h3>Testing that the account performs its calculations correctly</h3>
<p>In the above example, we mocked the DAO but didn&#8217;t specify what any of the mocked methods should do. In this case, all methods will return sensible default values of: null, zero or false. More commonly we need to specify something other than these defaults when writing our tests:</p>
<pre class="brush: java">
import static org.mockito.Mockito.*;
import static junit.framework.Assert.*;
import org.junit.*;

public class TestAccount {
    private Account account;

    @Before
    public void setup() {
        AccountDAO mockedDao = mock(AccountDAO.class);

    	//specify that this method on the mock object should return 8
        when(mockedDao.countOverdrawnDaysThisMonth()).thenReturn(8);

        account = new Account();
        account.setDAO(dao);
    }

    @Test
    public void checkChargesWhenOverdrawn() {
        //call the method under test
        long charge = account.calculateCharges();

        //assert that the charge was £2 per day overdrawn
        assertEquals(charge, 16);
    }
}
</pre>
<p>The statement on line 18 specifies that whenever the &#8216;countOverdrawnDaysThisMonth&#8217; is called it should return a value of 8; overriding the default of zero.</p>
<p>Given that the correct charge is two pounds (or dollars) per day overdrawn, then the assertion on line 25 will pass if the account performed the correct calculation (8 x 2 = 16 right).</p>
<h3>Comments</h3>
<p>There&#8217;s loads more to Mockito than we&#8217;ve looked at here. It&#8217;s a neat testing tool that works great with JUnit or TestNG. I&#8217;ve found that it&#8217;s small enough to learn quickly and capable enough to be really useful. Give it a go and write a comment below to let me know what you think of it.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smartkey.co.uk/2010/02/mockito-unit-test-java/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Using Assertions in Java</title>
		<link>http://blog.smartkey.co.uk/2010/02/java-assertions/</link>
		<comments>http://blog.smartkey.co.uk/2010/02/java-assertions/#comments</comments>
		<pubDate>Thu, 18 Feb 2010 14:47:25 +0000</pubDate>
		<dc:creator>Steve Neal</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Java Programming]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://blog.smartkey.co.uk/?p=607</guid>
		<description><![CDATA[I&#8217;ve been working on a project this week and have been delighted to see that the original team of programmers who developed it have made the effort to use assertions in their code. 
The assert keyword was introduced in Java 1.4 and has since been a sadly under-used language feature. Assertions offer developers a neat [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been working on a project this week and have been delighted to see that the original team of programmers who developed it have made the effort to use assertions in their code. </p>
<p>The assert keyword was introduced in Java 1.4 and has since been a sadly under-used language feature. Assertions offer developers a neat way to implement error detecting statements that are only active during development and can be turned off in production environments. </p>
<p>For example you might want to check that appropriate values are passed to a method during development to ensure that it is being called correctly:</p>
<pre class="brush: java">
private void onlyPositiveNumbersPlease(int i) {
    assert i &gt; 0;

    //rest of method implementation...

}
</pre>
<p>If the assertion fails, then an AssertionError is thrown. If you have a lot of assertions in your code, then its useful to be able to specify a value that will be used in the error message:</p>
<pre class="brush: java">
private void onlyPositiveNumbersPlease(int i) {
    assert i &gt; 0 : &quot;only positive numbers are allowed&quot;;

    //rest of method implementation...

}
</pre>
<p>The value that is specified can also be any primitive type, for example:</p>
<pre class="brush: java">
File f = loadFile();
assert f != null : 404;
</pre>
<p>In all cases, the value is converted to a String and set as the detail message of the AssertionException.</p>
<p>When the Java source is compiled, assertions instructions are included in the bytecode that is generated. However, by default, the assertions are not executed at runtime.</p>
<p>In order to activate all of the assertions, a command line flag must be passed to the JVM:<code></p>
<p>$ java <b>-ea</b> co.uk.smartkey.ui.MainClass<br />
</code></p>
<p>it is also possible to specify that assertions should only be activated for classes within a certain package. For example to run the same application as before, but only activate assertions for classes in the util package of our application, you could use something like:<code></p>
<p>$ java <b>-ea:co.uk.smartkey.util</b> co.uk.smartkey.ui.MainClass<br />
</code></p>
<p>if you just wanted to turn on assertions for a single class, you can specify the class name instead of the package name. Finally, if you really feel the need to, you can turn on assertions in the Java system classes with this:<code></p>
<p>$ java <b>-esa</b> co.uk.smartkey.ui.MainClass<br />
</code></p>
<p>Personally, I like using assertions as they can help to iron out problems during development that are unlikely to need checking for in production. Language level support for them means that the statements are only used if the JVM is launched with them activated; this ensures that there is no performance overhead associated with them when they are not in use.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smartkey.co.uk/2010/02/java-assertions/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Counting the Days Between Two Java Dates using a Gregorian Calendar</title>
		<link>http://blog.smartkey.co.uk/2009/12/counting-the-days-between-two-java-dates-using-a-gregorian-calendar/</link>
		<comments>http://blog.smartkey.co.uk/2009/12/counting-the-days-between-two-java-dates-using-a-gregorian-calendar/#comments</comments>
		<pubDate>Wed, 02 Dec 2009 15:03:37 +0000</pubDate>
		<dc:creator>Steve Neal</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Java Programming]]></category>
		<category><![CDATA[Calendar]]></category>
		<category><![CDATA[Date]]></category>
		<category><![CDATA[Gregorian]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://blog.smartkey.co.uk/?p=588</guid>
		<description><![CDATA[Today I needed to figure out a way to count the number of days between two dates in Java. There are no API methods that will do this for you so a little work is required to achieve this. This post illustrates the solution I came up with.
]]></description>
			<content:encoded><![CDATA[<p>Today I needed to figure out a way to count the number of days passed between two dates and this is the solution I came up with.</p>
<p>Some things in Java seem to be a whole lot trickier than they need be, and working with dates is a good example of this. The Date class&#8217; primary purpose is storing date values. For date oriented calculations the Calendar class should be used. The calendars will handle tricky problems like leap years but the methods for doing this operate at a low level and in many cases you still need to do some of the calculations for yourself. In addition to the standard classes, there&#8217;s some great support for working with dates provided in the Apache commons libraries; these libraries don&#8217;t provide a method for counting days between two dates though.</p>
<p>Anyway, to cut to the chase, here&#8217;s the solution I came up with:</p>
<pre class="brush: java">
public class DateTools {
    private static final int MILLISECONDS_IN_DAY = 1000 * 60 * 60 * 24;

    /**
     * Calculates the number of days between start and end dates, taking
     * into consideration leap years, year boundaries etc.
     *
     * @param start the start date
     * @param end the end date, must be later than the start date
     * @return the number of days between the start and end dates
     */
    public static long countDaysBetween(Date start, Date end) {
        if (end.before(start)) {
            throw new IllegalArgumentException(&quot;The end date must be later than the start date&quot;);
        }

        //reset all hours mins and secs to zero on start date
        Calendar startCal = GregorianCalendar.getInstance();
        startCal.setTime(start);
        startCal.set(Calendar.HOUR_OF_DAY, 0);
        startCal.set(Calendar.MINUTE, 0);
        startCal.set(Calendar.SECOND, 0);
        long startTime = startCal.getTimeInMillis();

        //reset all hours mins and secs to zero on end date
        Calendar endCal = GregorianCalendar.getInstance();
        endCal.setTime(end);
        endCal.set(Calendar.HOUR_OF_DAY, 0);
        endCal.set(Calendar.MINUTE, 0);
        endCal.set(Calendar.SECOND, 0);
        long endTime = endCal.getTimeInMillis();

        return (endTime - startTime) / MILLISECONDS_IN_DAY;
    }
}
</pre>
<p>As you can see each of the dates passed to this method are converted into milliseconds and the number of days between them is calculated based upon the number of days this equates to.</p>
<p>In order to ensure that the times are not relevant in the dates, these are set to zero. This means that if the start date is at 11:00 PM, and the end date is at 1:00 AM the next day, you&#8217;ll still get one day returned from this method call, rather than zero.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smartkey.co.uk/2009/12/counting-the-days-between-two-java-dates-using-a-gregorian-calendar/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>The Details of Member Level Inner Class Syntax</title>
		<link>http://blog.smartkey.co.uk/2009/11/details-of-inner-class-syntax/</link>
		<comments>http://blog.smartkey.co.uk/2009/11/details-of-inner-class-syntax/#comments</comments>
		<pubDate>Tue, 17 Nov 2009 15:52:46 +0000</pubDate>
		<dc:creator>Steve Neal</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Java Programming]]></category>
		<category><![CDATA[Inner classes]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://blog.smartkey.co.uk/?p=511</guid>
		<description><![CDATA[Inner classes offer are a powerful extension to Java's object model. However, the syntax for some of the more advanced features of member inner classes is quite tricky to get to grips with. In this article I'll explain the full details of this syntax.]]></description>
			<content:encoded><![CDATA[<p>Inner classes offer are a powerful extension to Java&#8217;s object model. However, the syntax for some of the more advanced features of member inner classes is quite tricky to get to grips with. In a <a href="/2009/11/programming-with-inner-classes-in-java/">previous article</a>, I discussed the different types of inner classes along with a demonstration of how they are most commonly used. In this article I&#8217;ll explain the full details of the inner class syntax in Java.</p>
<h3>The basics</h3>
<p>To define an inner class, just define one class within another:</p>
<pre class="brush: java">
public class Outer {
    public class Inner {

    }
}
</pre>
<p>Generally, the outer class will be responsible for creating instances of the inner classes and this could be done in the methods of the outer class, for example here where the outerClassesMethod creates an inner class instance and calls its method (lines 7-8) :</p>
<pre class="brush: java">
public class Outer {

    private String message = &quot;foo&quot;;

    public void outerClassesMethod() {
        //create an inner object to do the work
        Inner ii = new Inner();
        ii.innerClassesMethod();
    }

    private class Inner {
        private void innerClassesMethod() {
            System.out.println(message);
        }
    }
}
</pre>
<p>Note above that the inner classes method (line 12), although private, can still be called by the outer class. Also note that the private message field on the outer class (line 3) can be accessed from the inner class. A call to the outerClassesMethod will cause the innerClassesMethod to be called and the message &#8216;<strong>foo</strong>&#8216; to be printed to std out. </p>
<h3>What about &#8216;this&#8217; ?</h3>
<p>Each object in a Java application can refer to itself using the &#8216;this&#8217; reference. When an instance of an inner class is created, it is created within the instance that created it; so what effect does this have on &#8216;this&#8217; reference?</p>
<p>In fact, inner class instances have more than one &#8216;this&#8217; reference: one that refers to the instance of the inner instance, and one that refers to the outer instance. Consider this simple change to the example:</p>
<pre class="brush: java">
public class Outer {

    private String message = &quot;foo&quot;;

    public void outerClassesMethod() {
        //create an inner object to do the work
        Inner ii = new Inner();
        ii.innerClassesMethod();
    }

    private class Inner {
        private String message = &quot;bar&quot;;

        private void innerClassesMethod() {
            System.out.println(message);
        }
    }
}
</pre>
<p>Now that the inner class also has a field named message, the text &#8216;<strong>bar</strong>&#8216; will be printed out instead of &#8216;foo&#8217;.</p>
<p>The reason for this is that the inner classes message field has shadowed the outer classes one. The inner classes println call (line 15) would have the exact same behaviour if it were written as:</p>
<pre class="brush: java">
System.out.println(this.message);
</pre>
<p>if we want to access the message field on the outer class, then we need to use a &#8216;this&#8217; reference for the outer instance; we do this by pre-pending the class name to &#8216;this&#8217; as follows:</p>
<pre class="brush: java">
System.out.println(Outer.this.message);
</pre>
<p>substituting the println statement with the one shown above, will access the message field on the Outer class and cause &#8216;<strong>foo</strong>&#8216; to be printed out once again.</p>
<h3>Creating inner instances from outside the outer class</h3>
<p>As noted above, the inner instances will generally be created within the outer class. However, it is possible for inner instances to be created in other places too; for example, a factory class could be used to create the outer objects and also the inner objects that they will contain. </p>
<p>To demonstrate this scenario, we&#8217;ll use a slightly revised example where the inner class, and its method, have been made publicly visible. Note also that the outer class now has a constructor (lines 4-6) that will allow us to initialise its private message field (line 3) :</p>
<pre class="brush: java">
public class Outer {

    private String message;

    public Outer(String message) {
        this.message = message;
    }

    public class Inner {
        public void innerClassesMethod() {
            System.out.println(message);
        }
    }
}
</pre>
<p>If our factory class is to create the inner class instances, then it must associate them with an outer instance. In order to do this the new keyword must be scoped to a particular outer instance using this somewhat cumbersome syntax:</p>
<pre class="brush: java">
Outer o = new Outer(&quot;foo&quot;);
Outer.Inner i = o.new Inner();
i.innerClassesMethod();
</pre>
<p>Note the use of the new keyword (line 2) is prepended with the outer object reference (i.e. <strong>o.new</strong>). It is this outer reference that will be accessible within the inner object&#8217;s methods using the &#8216;this&#8217; syntax explained above.</p>
<p>So, when the call to the inner classes method is made (on line 3), the private message field of the outer instance will be printed out &#8211; i.e. we&#8217;ll see &#8216;<strong>foo</strong>&#8216; appear in std out.</p>
<h3>Static inner classes</h3>
<p>The static modifier can be applied to member level classes in much the same was as it can with the fields and methods of that class. As with fields and methods, use of the static modifier pretty much turns off OO. </p>
<pre class="brush: java">
public class Outer {

    private String message;

    static class Inner {
        private String message;

        public void innerClassesMethod() {
            //can access the message field defined on this class:
            System.out.println(this.message);

            //can&#039;t access the one from the outer class though:
            System.out.println(Outer.this.message);
        }
    }
}
</pre>
<p>In much the same way as a static method is not associated with an object instance, objects created from static inner class definitions are not associated with an outer object instance either.</p>
<p>Static inner classes therefore do not have a second this reference, and cannot access the non-static fields of the outer class (line 13 in the above example would produce a compiler error). Effectively, inner classes are just regular classes defined within an outer classes name-space. </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smartkey.co.uk/2009/11/details-of-inner-class-syntax/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

