<?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</title>
	<atom:link href="http://blog.smartkey.co.uk/tag/java/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>Working around a javax.net.ssl.SSLHandshakeException</title>
		<link>http://blog.smartkey.co.uk/2010/09/working-around-a-sslhandshakeexception/</link>
		<comments>http://blog.smartkey.co.uk/2010/09/working-around-a-sslhandshakeexception/#comments</comments>
		<pubDate>Mon, 27 Sep 2010 14:00:29 +0000</pubDate>
		<dc:creator>Steve Neal</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Networking]]></category>

		<guid isPermaLink="false">http://blog.smartkey.co.uk/?p=776</guid>
		<description><![CDATA[When trying to download data from an HTTPS connection, you might see the following exception reported:
javax.net.ssl.SSLHandshakeException: renegotiation is not allowed
This rather unhelpful error message can be raised on either the server or the client and indicates that the SSL libraries in Java cannot determine whether the CA that signed the server&#8217;s certificate is to be [...]]]></description>
			<content:encoded><![CDATA[<p>When trying to download data from an HTTPS connection, you might see the following exception reported:</p>
<pre>javax.net.ssl.SSLHandshakeException: renegotiation is not allowed</pre>
<p>This rather unhelpful error message can be raised on either the server or the client and indicates that the SSL libraries in Java cannot determine whether the CA that signed the server&#8217;s certificate is to be trusted or not. The solution is pretty straight-forward but will differ between client and server.</p>
<h3>Error appears in a Java client application</h3>
<p>A quick fix to this problem is to add the server&#8217;s certificate to the local trust store.  Here&#8217;s how to do this:</p>
<ol>
<li>Visit the server using a web browser and click on the navigation bar to see the server&#8217;s certificate details.</li>
<li>Export/save the X509 certificate to a local .cer file</li>
<li>Import the certificate into the local CA trust store using the JDK keytool.</li>
</ol>
<p>For step 3, given a certificate file called tomcat.cer and assuming that you are using JDK 1.5.0, you could use the following command line instruction:</p>
<pre>keytool -import -keystore C:\jdk1.5.0_22\jre\lib\security\cacerts -alias tomcat -file tomcat.cer</pre>
<p>For other JDK versions you&#8217;ll just need to adjust the above command a little.</p>
<h3>Error appears in a Java server application</h3>
<p>This is less common but something that I encountered recently when trying to access a Tomcat server that relied on client certificate (client-cert) based authentication. The fix to this is much the same as above except that the certificate for the client should be trusted by the server.</p>
<p>In this scenario the client is sending the certificate to prove their identity and the server needs reassuring that the certificate was issued by a trusted authority. To fix this scenario, repeat the command shown above substituting the CA certificate that is used t0 sign the client-certs.</p>
<p>Note that this change should only be made if you are certain that the CA that signed the clients certificate is trusted!</p>
<h3>Different results discovered when using different versions of Java</h3>
<p>Note that this exception is only raised by versions of Java 1.6.0_19 or later (SSL renegotiation was disabled in this version). Version 1.6.0_07, for example, just fails quietly and drops the socket connection. Version 1.5.0_20 (on Windows) seemed to work just fine for me.</p>
<p>This took me a while to find a work-around for so I hope this post helps someone.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smartkey.co.uk/2010/09/working-around-a-sslhandshakeexception/feed/</wfw:commentRss>
		<slash:comments>1</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>Getting Maven to work from behind a firewall</title>
		<link>http://blog.smartkey.co.uk/2010/05/maven-behind-firewall/</link>
		<comments>http://blog.smartkey.co.uk/2010/05/maven-behind-firewall/#comments</comments>
		<pubDate>Fri, 28 May 2010 14:51:51 +0000</pubDate>
		<dc:creator>Steve Neal</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Configuration]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Maven]]></category>

		<guid isPermaLink="false">http://blog.smartkey.co.uk/?p=748</guid>
		<description><![CDATA[Maven needs to access the Internet to download a number of things including POM files and dependent JAR files that are not held in your local repository. If you are trying to do this from behind a corportate firewall then you&#8217;ll need to configure Maven to work around it or you&#8217;ll get a load of [...]]]></description>
			<content:encoded><![CDATA[<p>Maven needs to access the Internet to download a number of things including POM files and dependent JAR files that are not held in your local repository. If you are trying to do this from behind a corportate firewall then you&#8217;ll need to configure Maven to work around it or you&#8217;ll get a load of error messages when it runs.</p>
<p>First you&#8217;ll need to find out your network&#8217;s HTTP proxy settings. You could ask a network administrator, or just look in your Internet browser settings and figure it out for yourself.</p>
<p>Once you&#8217;ve got the details of the proxy, edit Maven&#8217;s conf/settings.xml file and enter the proxy details in the proxy element:</p>
<pre class="brush: xml">
&lt;proxy&gt;
    &lt;id&gt;optional&lt;/id&gt;
    &lt;active&gt;true&lt;/active&gt;
    &lt;protocol&gt;http&lt;/protocol&gt;
    &lt;username&gt;proxyuser&lt;/username&gt;
    &lt;password&gt;proxypassword&lt;/password&gt;
    &lt;host&gt;webproxy.smartkey.co.uk&lt;/host&gt;
    &lt;port&gt;8080&lt;/port&gt;
    &lt;nonProxyHosts&gt;&lt;/nonProxyHosts&gt;
&lt;/proxy&gt;
</pre>
<p>Save the changes in this file and try launching Maven again. If it still doesn&#8217;t play ball, check the settings with your network admin, make sure that the above XML is uncommented (it&#8217;ll be commented in the file that ships with Maven) and try again.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smartkey.co.uk/2010/05/maven-behind-firewall/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Java 1.4 Debugger Not Working?</title>
		<link>http://blog.smartkey.co.uk/2010/05/java-1-4-debugger-not-working/</link>
		<comments>http://blog.smartkey.co.uk/2010/05/java-1-4-debugger-not-working/#comments</comments>
		<pubDate>Thu, 13 May 2010 14:55:44 +0000</pubDate>
		<dc:creator>Steve Neal</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Debug]]></category>
		<category><![CDATA[Error]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Socket]]></category>

		<guid isPermaLink="false">http://blog.smartkey.co.uk/?p=732</guid>
		<description><![CDATA[There&#8217;s a bug that I&#8217;d encountered running the debugger in JDK 1.4.2  ages ago that reared it&#8217;s head again today. I&#8217;ve been working on a system that uses this old JDK and thought I&#8217;d note the solution here in case I ever came across it again.
The problem is encountered when the JVM is launched [...]]]></description>
			<content:encoded><![CDATA[<p>There&#8217;s a bug that I&#8217;d encountered running the debugger in JDK 1.4.2  ages ago that reared it&#8217;s head again today. I&#8217;ve been working on a system that uses this old JDK and thought I&#8217;d note the solution here in case I ever came across it again.</p>
<p>The problem is encountered when the JVM is launched in debug mode and is reported as:</p>
<p><code>FATAL ERROR in native method: No transports initialized<br />
Transport dt_socket failed to initialize, rc = 509.<br />
</code><br />
Apparently, from looking at reports of this on the Web, this can happen on any operating system. I encountered it on a Windows XP machine and found that the simplest fix was to copy the following two files from the JAVA_HOME/jre/bin folder, to my c:/windows/system32 folder:</p>
<p><code>dt_socket.dll<br />
dt_shmem.dll<br />
</code><br />
You can also fix this by putting the JRE bin folder at the start of your PATH environment variable.  For a more detailed discussion of the problem take a look at <a href="http://forums.sun.com/thread.jspa?threadID=160025&#038;start=15">this thread</a> on the Sun forums web site.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smartkey.co.uk/2010/05/java-1-4-debugger-not-working/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>
	</channel>
</rss>

