<?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>Shaun Abram &#187; Java</title>
	<atom:link href="http://www.shaunabram.com/category/java/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.shaunabram.com</link>
	<description>Java and Technology weblog</description>
	<lastBuildDate>Thu, 09 Feb 2012 18:06:07 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>JavaOne: Tuesday&#8217;s Keynote</title>
		<link>http://www.shaunabram.com/javaone2011-tuesday-keynote/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=javaone2011-tuesday-keynote</link>
		<comments>http://www.shaunabram.com/javaone2011-tuesday-keynote/#comments</comments>
		<pubDate>Tue, 04 Oct 2011 18:28:53 +0000</pubDate>
		<dc:creator>sabram</dc:creator>
				<category><![CDATA[Events]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[javaone]]></category>
		<category><![CDATA[javaone2011]]></category>

		<guid isPermaLink="false">http://www.shaunabram.com/?p=1416</guid>
		<description><![CDATA[This morning&#8217;s Keynote at JavaOne contained a few interesting announcements, including JDK7 for MacOS X Developer Preview announced by Hasan Rizvi (SVP @ Oracle). Available here. Java FX to be open sourced, and it will be proposed to the JCP (Confirmed, see press release) JDK8 will be released in the summer of 2013 (not 2012 [...]]]></description>
			<content:encoded><![CDATA[<p>This morning&#8217;s Keynote at JavaOne contained a few interesting announcements, including</p>
<ul>
<li>JDK7 for MacOS X Developer Preview announced by Hasan Rizvi (SVP @ Oracle). Available <a href="http://jdk7.java.net/macportpreview/">here</a>.</li>
<li>Java FX to be open sourced, and it will be proposed to the JCP (Confirmed, see <a href="http://www.oracle.com/us/corporate/press/512728">press release</a>)</li>
<li>JDK8 will be released in the summer of 2013 (not 2012 as previously discussed), as announced by Adam Messinger from Oracle</li>
</ul>
<p>There was also mention of an <a href="http://www.oracle.com/technetwork/java/javamagazine/index.html">Oracle Java Magazine</a>, which I confess I had never heard of before.</p>
<p>For a summary of this morning&#8217;s announcements, see <a href="http://blogs.oracle.com/otn/entry/the_most_exciting_oracle_openworld">here</a>.</p>
<p>Overall, not the most exciting keynote I have seen. It opened with a presentation from Juniper Networks. I didn&#8217;t find the topic of &#8220;Programming the network&#8221; to bring networks and apps closer together particular relevant for me personally. They then rolled out a bunch of other corporate folks from the likes of Intel, Redhat, IBM and ARM. The Twitter guy did announce that Twitter are joining OpenJDK as well as the JCP though.</p>
<p>On to the sessions&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.shaunabram.com/javaone2011-tuesday-keynote/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JavaOne: Comparing Java Web Frameworks</title>
		<link>http://www.shaunabram.com/javaone-web-frameworks/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=javaone-web-frameworks</link>
		<comments>http://www.shaunabram.com/javaone-web-frameworks/#comments</comments>
		<pubDate>Tue, 04 Oct 2011 05:07:06 +0000</pubDate>
		<dc:creator>sabram</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Products]]></category>
		<category><![CDATA[grails]]></category>
		<category><![CDATA[gwt]]></category>
		<category><![CDATA[javaone]]></category>
		<category><![CDATA[javaone2011]]></category>
		<category><![CDATA[jsf]]></category>
		<category><![CDATA[tapestry]]></category>
		<category><![CDATA[webframework]]></category>
		<category><![CDATA[wicket]]></category>

		<guid isPermaLink="false">http://www.shaunabram.com/?p=1398</guid>
		<description><![CDATA[The first talk I attended at this year&#8217;s JavaOne was &#8220;Choosing Your Java Web Framework&#8221; by Richard Pack from salesforce.com Overall, I found this a really interesting talk. It was lacking in any sales pitch, nor did it have the unquestioning devotion to one particular framework that I felt some of the Java FX talks [...]]]></description>
			<content:encoded><![CDATA[<p>The first talk I attended at this year&#8217;s <a href="http://www.oracle.com/javaone/index.html">JavaOne</a> was &#8220;Choosing Your Java Web Framework&#8221; by Richard Pack from salesforce.com</p>
<p>Overall, I found this a really interesting talk. It was lacking in any sales pitch, nor did it have the unquestioning devotion to one particular framework that I felt some of the Java FX talks had. Instead it seemed like an unbiased look at web frameworks in general and a handful of frameworks in more detail, based on Richard&#8217;s extensive and hands on experience and SalesForce and Hyperic.<br />
<span id="more-1398"></span></p>
<p>Richard started by listing some of the web frameworks that are out there today. He managed to list over 100 and there were still many missing (e.g. I couldn&#8217;t see <a href="http://liftweb.net/">Lift</a> or <a href="http://www.playframework.org/">Play</a> listed).</p>
<p>Given the abundance of choices, I think it was wise to start with a broad definition of what a web framework is. His definition included something that uses <a href="http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93presenter">MVP</a> or <a href="http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller">MVC</a> and provides an event model, resource management, data binding and that is ideally stateless.</p>
<p>He then talked about the evolution that has taken place from server side rendering to client side rendering (where you have a stateless server, with the component model living on the client side), and had a few interesting &#8216;Architecture Evolution&#8217; diagrams in <a href="http://bit.ly/jwf-2011">his slides</a>.</p>
<p>Next, Richard talked about the consequences of &#8216;choosing poorly&#8217;, i.e. picking a framework not best suited to your project&#8217;s needs (steep learning curves, excessive boilerplate code, unable to debug templates etc). I got the feeling Richard had learned many of these the hard way. He followed with a set of criteria to help better define your web framework requirements and selection criteria to avoid such issues, including usage scenarios, environment (intranet, mobile) and team competencies. On a side note, he pointed out that using forms for posting had become old hat (and those &#8216;Are you sure you wish to resend&#8217; popups are certainly annoying).</p>
<p>Then, on to the main event. Richard ran through 4 of the most popular web frameworks: <a href="http://grails.org/">Grails</a>, <a href="http://tapestry.apache.org/">Tapestry</a>, <a href="http://wicket.apache.org/">Wicket</a> and <a href="http://code.google.com/webtoolkit/">GWT</a>. In each case he compared them using criteria such as AJAX support, friendly URLs, open source license etc. I won&#8217;t try to recreate his findings (again, see <a href="http://bit.ly/jwf-2011">his slides</a>), but I did come away with a higher opinion of both Tapestry (its Form builder using POJOs sounds particularly cool) and Wicket and I am definitely keen to learn more on GWT (which Salesforce.com use extensively).</p>
<p>In some of the follow up questions, Richard was asked about <a href="http://www.oracle.com/technetwork/java/javaee/javaserverfaces-139869.html">JSF</a>, which he didn&#8217;t have very high opinion of (and he <a href="http://ptrthomas.wordpress.com/2009/05/15/jsf-sucks/">is</a> <a href="http://www.dzone.com/links/jsf_sucks_compendium_of_jsf_rantsreviews.html">not</a> <a href="http://blog.brunoborges.com.br/2010/12/top-10-reasons-why-i-dont-like-jsf.html">alone</a>). I was however disappointed to not hear some info (merits or otherwise) on <a href="http://javafx.com/">JavaFX</a>, especially considering its high visibility at this year&#8217;s conference, but I also understand no one can know all frameworks.</p>
<p>Finally, he finished with an interesting thought &#8211; that one of the main scalability issues with any web framework is people i.e. the competencies and preferences of the developers on the team.</p>
<p>Find Richard&#8217;s slides <a href="http://bit.ly/jwf-2011">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.shaunabram.com/javaone-web-frameworks/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>@JavaOne</title>
		<link>http://www.shaunabram.com/javaone2011/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=javaone2011</link>
		<comments>http://www.shaunabram.com/javaone2011/#comments</comments>
		<pubDate>Tue, 04 Oct 2011 00:26:57 +0000</pubDate>
		<dc:creator>sabram</dc:creator>
				<category><![CDATA[Events]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[javaone]]></category>
		<category><![CDATA[javaone2011]]></category>

		<guid isPermaLink="false">http://www.shaunabram.com/?p=1403</guid>
		<description><![CDATA[I am at JavaOne 2011 right now. Always fun and it seems to be bigger than last year, with a huge selection of talks and presentations (although frustratingly flaky wifi!). Some of the themes of this morning&#8217;s keynote talk were JavaFX 2.0, what will be coming in Java 8 and a new Oracle NoSQL Database. [...]]]></description>
			<content:encoded><![CDATA[<p>I am at JavaOne 2011 right now. Always fun and it seems to be bigger than last year, with a huge selection of talks and presentations (although frustratingly flaky wifi!).</p>
<p>Some of the themes of this morning&#8217;s keynote talk were JavaFX 2.0, what will be coming in Java 8 and a new Oracle NoSQL Database. There are some links <a href="http://blogs.oracle.com/otn/entry/the_most_exciting_oracle_openworld">here</a>, <a href="http://www.theserverside.com/feature/JavaOne-Keynote-Duke-Cloud-JavaFX-and-Glassfish">here</a> and <a href="http://www.infoq.com/news/2011/10/javaone-tech-keynote">here</a> (and I believe the videos will be posted soon <a href="http://www.oracle.com/javaone/live/on-demand/index.html">here</a>).</p>
<p>I just attended a very useful Java Web Framework comparison talk that I will try to post about shortly. I also met up with some of the <a href="http://java.dzone.com/">DZone</a> team. For now, I am going to some JavaFX talks.</p>
<p>If any of you are attending, let me know!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.shaunabram.com/javaone2011/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Spring MVC Hello World</title>
		<link>http://www.shaunabram.com/springmvchelloworld/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=springmvchelloworld</link>
		<comments>http://www.shaunabram.com/springmvchelloworld/#comments</comments>
		<pubDate>Tue, 20 Sep 2011 05:07:03 +0000</pubDate>
		<dc:creator>sabram</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[OpenSource]]></category>
		<category><![CDATA[Products]]></category>
		<category><![CDATA[helloworld]]></category>
		<category><![CDATA[jsp]]></category>
		<category><![CDATA[servlet]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[springmvc]]></category>
		<category><![CDATA[webapp]]></category>
		<category><![CDATA[webframework]]></category>

		<guid isPermaLink="false">http://www.shaunabram.com/?p=1376</guid>
		<description><![CDATA[There is a good Getting Started with Spring MVC blog post over on the Spring team blog. I have created several Spring MVC projects for both work and play, and am attaching my own simple version of the HelloWorld example here, based on the Spring blog example. Find my maven ready source here. Like my [...]]]></description>
			<content:encoded><![CDATA[<p>There is a good <a href="http://blog.springsource.com/2011/01/04/green-beans-getting-started-with-spring-mvc/">Getting Started with Spring MVC</a> blog post over on the Spring team <a href="http://blog.springsource.com/">blog</a>.</p>
<p>I have created several <a href="http://static.springsource.org/spring/docs/current/spring-framework-reference/html/mvc.html">Spring MVC</a> projects for both work and play, and am attaching my own simple version of the HelloWorld example here, based on the Spring blog example.<br />
Find <a href="http://www.shaunabram.com/attachments/SpringMVCHelloWorld.zip">my maven ready source here</a>.<br />
Like my previous <a href="http://www.shaunabram.com/helloworld-jsp-servlet/">JSP/Servlet example</a>, I find these templates useful for getting prototypes up and running.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.shaunabram.com/springmvchelloworld/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>SLF4J &amp; Logback is the new commons-logging &amp; log4j</title>
		<link>http://www.shaunabram.com/slf4j_logback/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=slf4j_logback</link>
		<comments>http://www.shaunabram.com/slf4j_logback/#comments</comments>
		<pubDate>Wed, 14 Sep 2011 05:04:51 +0000</pubDate>
		<dc:creator>sabram</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[OpenSource]]></category>
		<category><![CDATA[log4j]]></category>
		<category><![CDATA[logback]]></category>
		<category><![CDATA[logging]]></category>
		<category><![CDATA[slf4j]]></category>

		<guid isPermaLink="false">http://www.shaunabram.com/?p=1370</guid>
		<description><![CDATA[Interesting post on which logging framework to choose from the logging mess. I still default to log4j, but it sounds like logback (as the new alternative to log4j), wrapped by SLF4J (as the new alternative to commons logging) is the way forward. Both are written by Ceki Gülcü (blog), the original log4j author.]]></description>
			<content:encoded><![CDATA[<p>Interesting post on which logging framework to choose from <a href="http://www.dzone.com/links/r/the_logging_mess.html">the logging mess</a>.</p>
<p>I still default to <a href="http://logging.apache.org/log4j/">log4j</a>, but it sounds like <a href="http://logback.qos.ch/">logback</a> (as the new alternative to log4j), wrapped by <a href="http://www.slf4j.org/">SLF4J</a> (as the new alternative to <a href="commons.apache.org/logging/">commons logging</a>) is the way forward. Both are written by Ceki Gülcü (<a href="http://ceki.blogspot.com/">blog</a>), the original log4j author.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.shaunabram.com/slf4j_logback/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JSP EL statements not being evaluated</title>
		<link>http://www.shaunabram.com/jsp-el-not-evaluated/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=jsp-el-not-evaluated</link>
		<comments>http://www.shaunabram.com/jsp-el-not-evaluated/#comments</comments>
		<pubDate>Sun, 11 Sep 2011 21:38:38 +0000</pubDate>
		<dc:creator>sabram</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[el]]></category>
		<category><![CDATA[j2ee]]></category>
		<category><![CDATA[jsp]]></category>
		<category><![CDATA[jstl]]></category>

		<guid isPermaLink="false">http://www.shaunabram.com/?p=1347</guid>
		<description><![CDATA[On several occasions I have had problems with EL (Expression Language) statements not being evaluated. As an example, you add a statement to a JSP like $(2+2), expecting the JSP to simply display 4, when it in fact displays the raw statement, i.e. $(2+2). After digging around the web, I found a number of points [...]]]></description>
			<content:encoded><![CDATA[<p>On several occasions I have had problems with EL (Expression Language) statements not being evaluated.<br />
As an example, you add a statement to a JSP like<br />
$(2+2), expecting the JSP to simply display 4, when it in fact displays the raw statement, i.e. $(2+2).</p>
<p>After digging around the web, I found a number of points to check&#8230;</p>
<p><span id="more-1347"></span> </p>
<ul>
<li>Check you application server supports JSP 2.0 or above (Tomcat 5.0 and higher does)</li>
<li>Check your web.xml descriptor file is using at least version 2.4 of the Servlet deployment descriptor (I have been using 2.5). If it is using Servlet 2.3 spec or earlier, EL will be disabled by default.</li>
<li>Even if you are using version 2.5 of the Servlet deployment descriptor, make sure that the schemaLocation is correct. For example, I copied this from somewhere on the web and it failed to work:
<pre><code>&lt;?xml version="1.0" encoding="ISO-8859-1"?&gt;
&lt;web-app xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/<strong>j2ee</strong>
            http://java.sun.com/xml/ns/<strong>j2ee</strong>/web-app_2_5.xsd"
         Version="2.5"&gt;</code></pre>
<p>I then found this version, which does work correctly. Note the subtle difference in the schema location of j2ee vs javaee.</p>
<pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
         &lt;web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/<strong>javaee</strong>
             http://java.sun.com/xml/ns/<strong>javaee</strong>/web-app_2_5.xsd"
         version="2.5"&gt;  </code></pre>
<p>I found the above <a href="http://download.oracle.com/docs/cd/E12840_01/wls/docs103/webapp/web_xml.html">here</a> at Oracle.</p>
<li>As a last resort, you can use <code>&lt;%@ page isELIgnored="false" %&gt;</code> in your JSP, but having to do this is usually a sign that something else may be wrong (as described above).</li>
</ul>
<p>Related posts:</p>
<ul>
<li><a href="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">XML Schema for the Servlet 2.5 deployment descriptor</a>[java.sun.com]</li>
<li><a href="http://download.oracle.com/javaee/5/tutorial/doc/bnahq.html">Java EE 5 &#8211; Unified Expression Language</a>[oracle.com]</li>
<li><a href="http://www.coderanch.com/how-to/java/ElOrJstlNotWorkingAsExpected">JSP, JSTL, Servlet and Tomcat version matching</a>[coderanch.com]</li>
<li>Stack Overflow related problem postings:</li>
<ul>
<li><a href="http://stackoverflow.com/questions/504071/el-in-a-jsp-stopped-evaluating">EL in a JSP stopped evaluating</a>[stackoverflow.com]</li>
<li><a href="http://stackoverflow.com/questions/793983/jsp-el-expression-is-not-evaluated">JSP: EL expression is not evaluated</a>[stackoverflow.com]</li>
<li><a href="http://stackoverflow.com/questions/472500/javascript-string-replace-str-works-weirdly-in-jsp-file/472573#472573">Javascript String.replace works weirdly in jsp file</a>[stackoverflow.com]</li>
</ul>
</ul>
<ul>
]]></content:encoded>
			<wfw:commentRss>http://www.shaunabram.com/jsp-el-not-evaluated/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Setting up multiple instances of Tomcat</title>
		<link>http://www.shaunabram.com/multiple-tomcat-instances/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=multiple-tomcat-instances</link>
		<comments>http://www.shaunabram.com/multiple-tomcat-instances/#comments</comments>
		<pubDate>Thu, 08 Sep 2011 23:48:06 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[OpenSource]]></category>
		<category><![CDATA[apache]]></category>
		<category><![CDATA[appserver]]></category>
		<category><![CDATA[tomcat]]></category>

		<guid isPermaLink="false">http://www.shaunabram.com/?p=1305</guid>
		<description><![CDATA[With multiple tomcat instances, each can run in its own JVM, have its own configuration and can be started/stopped independently. For example, you can have a dev, QA and Prod version of tomcat all running on the same box. One approach to doing this would be to have multiple, full tomcat installations. This article instead [...]]]></description>
			<content:encoded><![CDATA[<p>With multiple <a href="http://tomcat.apache.org/index.html">tomcat</a> instances, each can run in its own JVM, have its own configuration and can be started/stopped independently. For example, you can have a dev, QA and Prod version of tomcat all running on the same box.</p>
<p>One approach to doing this would be to have multiple, full tomcat installations. This article instead details how to install tomcat once (in CATALINA_HOME) but have multiple independent instances (by utilizing CATALINA_BASE). This is a more streamlined approach that makes creating multiple instances easier and also simplifies upgrades/rollbacks of tomcat.</p>
<p><span id="more-1305"></span></p>
<h3>Version info</h3>
<p>I have tested with <a href="http://tomcat.apache.org/download-60.cgi">tomcat 6</a> and <a href="http://tomcat.apache.org/download-70.cgi">tomcat 7</a> and it seems to work well with both.<br />
These notes relate to a windows install, but should be easily modified for *nix.</p>
<h3>Steps</h3>
<p>First, <a href="http://tomcat.apache.org/whichversion.html">download </a>and install tomcat to whatever directory you choose. We will refer to this directory as CATALINA_HOME.<br />
Now, repeat the following steps for each instance of tomcat you want to setup.</p>
<ol>
<li>Create a new folder which will be your tomcat instance. Note that this should preferably not be in CATALINA_HOME. We will refer to this tomcat instance folder as CATALINA_BASE.</li>
<li>Copy the conf directory from CATALINA_HOME to CATALINA_BASE. (I think, strictly speaking, just copying the server.xml would suffice, but no harm in copying the whole directory for now).</li>
<li>Isolate your tomcat instance<br />
Edit CATALINA_BASE\conf\server.xml file so that the following ports do not interfere with other Tomcat instances:</p>
<ul>
<li>HTTP connector port (e.g. use 8080, 8081 &#8230;)</li>
<li>Shutdown port (e.g. use 8005, 8006&#8230;)</li>
<li>AJP port (e.g. use 8009, 8010&#8230;)</li>
</ul>
<p>Obviously if you have more than 4 instances, the shutdown and AJP ports will start to clash, so adapt accordingly (e.g. Shutdown = 9000, 9001; AJP = 9500, 9501 and HTTP continues with =8084, 8085&#8230;).</li>
<li>Create the following empty directories under CATALINA_BASE
<ul>
<li>logs</li>
<li>temp</li>
<li>work</li>
<li>webapps</li>
</ul>
<p>Tomcat will use the first 3 as part of its normal running. The webapps directory is where you will place your projects.</li>
<li>Optional: Set up the default page and tomcat manager<br />
Copy CATALINA_HOME\webapps\ROOT and CATALINA_HOME\webapps\manager to CATALINA_BASE\webapps.<br />
This step is optional but will allow you access the default page (useful for ensuring tomcat is running properly) as well as the Tomcat Manager page (useful for managing tomcat and your deployed applications).</li>
<li>Create startup and shutdown scripts<br />
Create a bin directory in CATALINA_BASE.<br />
In that bin directory, create a file called startup.bat like this:</p>
<pre><code>    set CATALINA_BASE=C:\tomcats\tomcat-x
    set CATALINA_HOME=C:\tomcats\apache-tomcat-7.0.21
    C:\tomcats\apache-tomcat-7.0.21\bin\startup.bat</code></pre>
<p>And create a file called shutdown.bat like this:</p>
<pre><code>    set CATALINA_BASE=C:\tomcats\tomcat-x
    set CATALINA_HOME=C:\tomcats\apache-tomcat-7.0.21
    C:\tomcats\apache-tomcat-7.0.21\bin\shutdown.bat</code></pre>
<p>Note that these are just basic scripts; you can obviously customize as you see fit. You can also optionally create a setenv.bat in the same bin directory to set any environment variables.</li>
</ol>
<p>That&#8217;s it! From each instance directory, run CATALINA_BASE\bin\startup.bat and you will have multiple instances of tomcat up and running simultaneously.</p>
<h3>Related links</h3>
<ul>
<li><a href="http://stackoverflow.com/questions/1794444/use-multiple-catalina-base-to-setup-tomcat-6-instances-on-windows">Use multiple CATALINA_BASE to setup tomcat 6 instances on windows</a></li>
<li><a href="http://kief.com/node/23">Running multiple Tomcat instances on one server</a></li>
<li><a href="http://www.servletworld.com/tomcat/howto-create-multiple-tomcat-instances.html">How to create multiple tomcat instances</a></li>
<li><a href="http://willcode4beer.com/ware.jsp?set=tomcat_config">Tomcat Configuration Using CATALINA_BASE</a></li>
</ul>
<h3>Troubleshooting</h3>
<p>If you are having problems, it can be useful to have tomcat run in the same window you start it in (rather than popping up a window with an error that immediately disappears!). To do this, modify the last line in CATALINA_HOME\bin\startup.bat by replacing the word <em>start</em> with the word <em>run</em></p>
]]></content:encoded>
			<wfw:commentRss>http://www.shaunabram.com/multiple-tomcat-instances/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>EasyMock</title>
		<link>http://www.shaunabram.com/easymock-2/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=easymock-2</link>
		<comments>http://www.shaunabram.com/easymock-2/#comments</comments>
		<pubDate>Wed, 17 Aug 2011 02:20:17 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[OpenSource]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[easymock]]></category>
		<category><![CDATA[mocks]]></category>
		<category><![CDATA[unittesting]]></category>

		<guid isPermaLink="false">http://www.shaunabram.com/?p=1195</guid>
		<description><![CDATA[EasyMock is an open source library for creating, and defining the behavior of, mock objects as part of your unit tests. This article describes how to use EasyMock (v3.0), including its record/playback approach, after setting the context with an brief introduction to unit testing in general and the associated need for mock objects. Unit Testing [...]]]></description>
			<content:encoded><![CDATA[<p>EasyMock is an open source library for creating, and defining the behavior of, mock objects as part of your unit tests. This article describes how to use EasyMock (v3.0), including its record/playback approach, after setting the context with an brief introduction to unit testing in general and the associated need for mock objects.<br />
<span id="more-1195"></span> </p>
<h3>Unit Testing</h3>
<p>The benefits of unit testing code are many and include allowing us to find problems early, enable refactoring with confidence, and even provide a form of documentation for our code. Writing code with testing in mind (or, in the <a href="http://www.amazon.com/Test-Driven-Development-Kent-Beck/dp/0321146530/ref=sr_1_1?ie=UTF8&#038;qid=1313544869&#038;sr=8-1">TDD</a> world, to make already written tests pass) helps us to write code that is modular, with low coupling and high cohesion.</p>
<p>Unit testing is a way to verify that a unit of code works as we expect and want. In Java, that unit is often centered around a method. Sometimes a small part of one method (such as a particularly if block); sometimes several methods (for example, in the case of the public method under test calling one or more private methods). However, what a unit test should not do is test outside its own class boundary since this gets in to the realm of integration testing.  </p>
<h3>Using Mock Objects</h3>
<p>Inevitably however, your class will rely on the behavior of other classes. So, the issue then becomes how to deal with those other classes. We somehow need to isolate, or control, their behavior in order to be able to focus on the unit under test. (We will either test that other code separately or, in the case of 3rd party libraries, assume that it works well already.) </p>
<p>The solution to isolating your unit under test from the other collaborating classes is to use mock objects in place of those collaborators. Mock objects allow us to focus on just the code under test by mocking the collaborator&#8217;s behavior. We specify expectations for how our code will interact (methods calls and return values), control those interactions and confirm that everything in our unit test code works as expected. Mock objects are, in essence, a way to test our code in isolation from the rest of our software world.</p>
<p>Fortunately, in the Java world, we have several mock object frameworks available, including <a href="http://www.jmock.org/">JMock</a>, <a href="http://mockito.org/">Mockito</a> and <a href="http://easymock.org/">EasyMock</a>. There are some interesting discussions on the relative merits of each <a href="http://stackoverflow.com/questions/22697/whats-the-best-mock-framework-for-java">here</a> and <a href="http://softwareinabottle.wordpress.com/2010/09/12/finding-the-mock-framework-that-best-suits-me-part-1-the-contenders/">here</a>. This article focuses on the functionality of EasyMock.</p>
<h1>EasyMock</h1>
<p>EasyMock uses a record/playback paradigm for unit testing with mock objects. In record mode, you record what methods you expect to be called on your mock objects (and specify how you want your mock to respond). In playback mode, your mocks wait for those expected calls, playing back the canned responses you have specified. EasyMock will alert you to any unexpected behavior, such as missing calls and incorrect argument or return values and can also alert you to other behavior such as unexpected method calls.</p>
<p>These are the basic steps for using an EasyMock mock object:</p>
<ol>
<a href="#1">
<li>Create a Mock Object</li>
<p></a><br />
<a href="#2">
<li>Record the expected behavior</li>
<p></a><br />
<a href="#3">
<li>Switch to replay state</li>
<p></a><br />
<a href="#4">
<li>Call the methods under test</li>
<p></a><br />
<a href="#5">
<li>Verify the mock was used as expected</li>
<p></a>
</ol>
<p><a name="1"><br />
<h2>1. Creating Mocks</h2>
<p></a><br />
Creating a mock is simple. Simply call createMock and pass in the class of the interface to be mocked, For example:</p>
<pre><code>    MyInterface mock = org.easymock.EasyMock.createMock(MyInterface.class);</code></pre>
<p>Or better yet, statically import the EasyMock static methods in you class import statements. For example:</p>
<pre><code>    import static org.easymock.EasyMock.*;
    …
    MyInterface mock = createMock(MyInterface.class);</code></pre>
<p>(Note that this static import approach applies to pretty much all of the EasyMock methods discussed in this article).</p>
<p>That&#8217;s it! Mock created. I have included some details on more customized mocks below, but in most cases, you can simply skip to the next step: <a href="#2">specifying the expected behavior</a>.</p>
<h3>Mock creation specifics</h3>
<p>Using <code>createMock</code> creates a mock object that has 2 notable characteristics:</p>
<ol>
<li>
Order checking is disabled by default. That is, you can specify the method call expectations (more later) in any order you wish &#8211; they do not need to match the actual order of the method invocations at test run time.</li>
<li>Calls to unexpected methods cause the test to fail</li>
</ol>
<p>However, EasyMock provides two other approaches for creating mocks&#8230;</p>
<h3>Strict/Nice mocks</h3>
<h4>Strict Mocks</h4>
<p>A strict Mock Object has order checking enabled by default (and calls to unexpected methods still cause the test to fail).</p>
<pre><code>    MyInterface mock = org.easymock.EasyMock.createStrictMock(MyInterface.class);</code></pre>
<p>Since method order invocation is important under normal use, I often create my mocks as &#8216;strict&#8217; by default.</p>
<h4>Nice Mocks</h4>
<p>Like a regular mock, order checking is disabled by default but &#8216;nice&#8217; mocks will also allow calls to unexpected methods to pass unnoticed. Nice mocks also have another useful behavior: They will do their best to create a return value for unexpected method invocations. Specifically, they will return 0 (for methods with a numeric return type), false (for methods with a boolean return type) or null (for all other methods). </p>
<p>I find nice mocks particular use for testing legacy classes (or classes that were perhaps not created with unit testing in mind) that may interact with a large number of other classes which my current tests have no concern with.</p>
<h3>Partial Mocks</h3>
<p>EasyMock also provides the capability to mock specific methods of a class while not mocking (i.e. keeping the real behavior) of others. I have not personally used this functionality yet, but it is available via the <code>createMockBuilder</code> method, which returns a <a href="http://easymock.org/api/easymock/3.0/org/easymock/IMockBuilder.html">IMockBuilder</a>interface.</p>
<h3>Mocking concrete classes</h3>
<p>The final point on mock creation is that although EasyMock (and indeed the use of mock objects in general) is most often associated with mocks of interfaces, you can in fact also create mocks of concrete class also. You simply use </p>
<pre><code>    org.easymock.classextension.EasyMock.createMock(...)</code></pre>
<p>instead of the more conventional</p>
<pre><code>    org.easymock.EasyMock.createMock(...);</code></pre>
<p>e.g.</p>
<pre><code>    ConcreteClass mock = org.easymock.classextension.EasyMock.createMock(ConcreteClass.class);</code></pre>
<p><a name="2"><br />
<h2>2. Record the expected behavior for your mock</h2>
<p></a><br />
After creating our mock object, we next need to tell EasyMock how we expect that mock to be used, that is, what methods we expect to be called on it.</p>
<h3>2.1 Simplest case</h3>
<p>In the simplest case where the expected method call has no return values (i.e. void) and accepts no arguments, you simply just call the method directly. For example:</p>
<pre><code>    mock.expectedOperation() </code></pre>
<p>EasyMock still picks up &#038; records the expectation.</p>
<p>Note that if you need to apply other expectations (such as expected Exceptions, or number of invocations as discussed later) to these simple cases, you can do so by invoking <code>expectLastCall()</code> followed by your expectations.</p>
<p>In addition to these simple calls however, EasyMock also provides the capabilities to specify return types and argument values, where required&#8230;</p>
<h3>2.2 Specifying return values</h3>
<p>If the call to expectedOperation returns a value, you must specify what EasyMock will return to your calling code. This can be done using the <code>andReturn()</code> method (a method provided by the return object of <code>EasyMock.expect()</code>, <a href="http://easymock.org/api/easymock/3.0/org/easymock/IExpectationSetters.html">IExpectationSetters</a>). </p>
<p>For example:</p>
<pre><code>    EasyMock.expect(mock.expectedOperation()).andReturn(expectedReturnValue);</code></pre>
<p>Where “expectedReturnValue” can be any object or primitive that matches expectedOperation’s return type.</p>
<h4>Gotcha:</h4>
<p>If the expected operation does indeed return a value, and you do not specify<br />
e.g. EasyMock.expect(mock.expectedOperation());<br />
You will get an error like:</p>
<pre><code>    java.lang.IllegalStateException: missing behavior definition for the preceding method call expectedOperation()</code></pre>
<p>Note that you can also get this error if you forget to call replay() before using a mock – more below.</p>
<h4>Advanced return values</h4>
<p>If you need more advanced return type creation, e.g. creating a value (or an Exception) at runtime, you can use <code>andAnswer(IAnswer answer)</code>. See <a href="http://easymock.org/api/easymock/2.4/org/easymock/IAnswer.html">IAnswer</a> for more details.</p>
<h3>2.3 Specifying arg values</h3>
<p>In the simplest approach, to specify an argument value, you just pass it with the expected method call, as in:</p>
<pre><code>    mock.expectedOperation(argValue)</code></pre>
<p>or</p>
<pre><code>    EasyMock.expect(mock.expectedOperation(argValue)).andReturn(expectedReturnValue);</code></pre>
<p>EasyMock simply compares the actual method arguments and the expected arguments by using <code>equals()</code>. </p>
<h4>Flexible Argument Matchers</h4>
<p>It is also possible to have EasyMock adopt a more flexible approach to matching actual and expected arguments. For example, you may be happy to just have </p>
<ul>
<li>any Object passed</li>
<li>A String starting with a certain value</li>
<li>A number in a certain range</li>
</ul>
<p>Easyock support these, and more, using argument matchers such as</p>
<ul>
<li>anyObject()</li>
<li>startsWith(String prefix)</li>
<li>eq(X value, X delta)</li>
</ul>
<p>For example:</p>
<pre><code>    expect(mock.expectedOpreation(EasyMock.anyInt()));</code></pre>
<p>See the <a href="http://easymock.org/api/easymock/3.0/org/easymock/EasyMock.html">EasyMock class API</a> for more details (or the EasyMock <a href="http://easymock.org/Documentation.html">readme</a>).</p>
<h3>2.4 Specifying how many calls are expected</h3>
<p>EasyMock also provides the capability to either relax or tighten the rules regarding the number of calls expected for a method.</p>
<h4>Specifying an exact number of calls</h4>
<p>To specify that a method must be called a certain number of times, we can just repeat the expected call the required number of time, e.g.</p>
<pre><code>    EasyMock.expect(mock.expectedOperation()).andReturn(expectedReturnValue);
    EasyMock.expect(mock.expectedOperation()).andReturn(expectedReturnValue);</code></pre>
<p>But this can get tedious for large numbers of calls, so we can also do:</p>
<pre><code>EasyMock.expect(mock.expectedOperation()).<strong>times(2)</strong>.andReturn(expectedReturnValue);</code></pre>
<h4>Specifying an inexact number of calls</h4>
<p>There are a number of other methods (again, all provided by the return object of EasyMock.expect()) allowing us to specify looser rules on the number of expected method calls. These are:</p>
<ul>
<li>anyTimes() </li>
<li>atLeastOnce() </li>
</ul>
<p><a name="3"><br />
<h2>3. Switch to replay state</h2>
<p></a><br />
Switching a mock object to replay state is simply done by calling EasyMock.replay(), passing in the mock object.<br />
e.g. </p>
<pre><code>    EasyMock.replay(mock).</code></pre>
<p>This should be done for all mocks you have created (or, alternatively, call <code>EasyMock.replayAll()</code>)<br />
If you forget to call replay() before using a mock you will get this error:</p>
<pre><code>    java.lang.IllegalStateException: missing behavior definition for the preceding method call expectedOperation()</code></pre>
<p>Calling replay tells EasyMock that you are no longer specifying expected method calls and moving into replay mode.</p>
<p><a name="4"><br />
<h2>4. Call the methods under test</h2>
<p></a><br />
This part is not really EasyMock specific since this is the crux of your test and needs to be done even if you are not using mock objects.<br />
e.g. if you are unit testing a method of a <a href="http://www.corej2eepatterns.com/Patterns2ndEd/ApplicationService.htm">Service</a> object, at some point you are going to have to call that method in order to test its effect.</p>
<p><a name="5"><br />
<h2>5. Verify the mock was used as expected</h2>
<p></a><br />
The final step is where we ask EasyMock to confirm that all our expectations were met. That is, we ask EasyMock to confirm that a method call corresponding to each expectation we set is actually made. This can be done as either</p>
<pre><code>EasyMock.verify(mock)</code></pre>
<p>or</p>
<pre><code>EasyMock.verifyAll()</code></pre>
<p>Note that this step is not mandatory, but if it is omitted, there will be no verification performed that the expected behavior we specified actually took place. So for example, if you specify</p>
<pre><code>    mock.expectedOperation() </code></pre>
<p>and <code>expectedOperation</code> is never called, the tests will still pass.</p>
<p>If verify() <em>is</em> called, exactly what checks are performed depends on the type of mock object we created in step 1.</p>
<blockquote><p>Note that I personally find the exact behavior of verify to be one more confusing parts of EasyMock. The following is my understanding of it and you should consult the EasyMock documentation (and run some tests yourself) before relying on it!</p></blockquote>
<ul>
<li>EasyMock.createNiceMock() &#8211; As discussed earlier, unexpected method calls are not flagged. Calling verify() on a nice mock simply checks that all your expected methods were called, in any order.</li>
<li>EasyMock.createMock() – On a &#8216;normal&#8217; mock, <em>unexpected</em> method calls will be be flagged (they would result in <code>AssertionError: Unexpected method call</code>) even without the call to verify. I think that the call to verify acts the same way as for a &#8216;nice&#8217; mock&#8217;. That is, EasyMock simply checks that all your <em>expected</em> methods were called, in any order.
<p>[If anyone out there knows of a difference in the effect of calling verify() between a nick mock and a normal mock, I would like to know!]</li>
<li>EasyMock.createStrictMock() – Again, unexpected method calls will be flagged, and the order of the expected method calls is also checked but this time, the order of the expected methods is also checked.</li>
</ul>
<p>Again, with the same disclaimer as before of this being my understanding only, I have tried to summarize the above behavior in the following table:</p>
<table border="1">
<tr>
<td>&nbsp;</td>
<td bgcolor="#FFF380">NiceMock
<p>without verify()</td>
<td bgcolor="#FFF380">NiceMock
<p>with verify()</td>
<td bgcolor="#FBB117">Mock
<p>without verify()</td>
<td bgcolor="#FBB117">Mock
<p>with verify()</td>
<td bgcolor="#F9966B">StrickMock
<p>without verify()</td>
<td bgcolor="#F9966B">StrickMock
<p>with verify()</td>
</tr>
<tr>
<td>Checks for Expectations being met</td>
<td bgcolor="#FFF380">N</td>
<td bgcolor="#FFF380">Y</td>
<td bgcolor="#FBB117">N</td>
<td bgcolor="#FBB117">Y</td>
<td bgcolor="#F9966B">N</td>
<td bgcolor="#F9966B">Y</td>
</tr>
<tr>
<td>Checks for Expectations being met in exact order</td>
<td bgcolor="#FFF380">N</td>
<td bgcolor="#FFF380">N</td>
<td bgcolor="#FBB117">N</td>
<td bgcolor="#FBB117">N</td>
<td bgcolor="#F9966B">N</td>
<td bgcolor="#F9966B">Y</td>
</tr>
<tr>
<td>Unexpected methods flagged</td>
<td bgcolor="#FFF380">N</td>
<td bgcolor="#FFF380">N</td>
<td bgcolor="#FBB117">Y</td>
<td bgcolor="#FBB117">Y</td>
<td bgcolor="#F9966B">Y</td>
<td bgcolor="#F9966B">Y</td>
</tr>
</table>
</p>
<h2>References</h2>
<p><a href="http://easymock.org/Documentation.html">EasyMock Documentation</a><br />
<a href="http://www.ibm.com/developerworks/java/library/j-easymock/index.html">Easier testing with EasyMock</a></p>
<h2>Links</h2>
<p><a href="http://www.dzone.com/links/r/easymock_facts_and_fallacies.html">EasyMock Facts and Fallacies</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.shaunabram.com/easymock-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Hamcrest Matcher</title>
		<link>http://www.shaunabram.com/hamcrest-matcher/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=hamcrest-matcher</link>
		<comments>http://www.shaunabram.com/hamcrest-matcher/#comments</comments>
		<pubDate>Wed, 20 Apr 2011 05:50:08 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[OpenSource]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Hamcrest]]></category>
		<category><![CDATA[JUnit]]></category>
		<category><![CDATA[unittesting]]></category>

		<guid isPermaLink="false">http://www.shaunabram.com/?p=1157</guid>
		<description><![CDATA[As a follow up to the Hamcrest post I made yesterday, I wanted to post an example of my own Hamcrest matcher implementation. This matcher tests if a string contains a specified number of substrings. An example usage could be: String sql = "select a,b,c from tableA"; assertThat(sql, hasNumberOfSubstrings(",", 2)); See the source code below. [...]]]></description>
			<content:encoded><![CDATA[<p>As a follow up to the <a href="http://www.shaunabram.com/hamcrest/">Hamcrest post</a> I made yesterday, I wanted to post an example of my own Hamcrest matcher implementation. This matcher tests if a string contains a specified number of substrings.<br />
An example usage could be:</p>
<pre><code>    String sql = "select a,b,c from tableA";
    assertThat(sql, hasNumberOfSubstrings(",", 2));</code></pre>
<p>See the source code below. I have been reading up on OSS licenses recently and decided to release this using the same license as <a href="http://code.google.com/p/hamcrest/">Hamcrest</a> &#8211; the <a href="http://www.opensource.org/licenses/bsd-license.php">new BSD license</a>.</p>
<p>I have also attached a <a href="http://www.shaunabram.com/HasNumberOfSubStrings_Hamcrest_Matcher.jar">jar</a> which includes the associated unit tests, although you will need the hamcrest-unit-test project to compile, which can be <a href="http://code.google.com/p/hamcrest/downloads/list">downloaded</a> as part of the hamcrest all-in-one jar.<br />
<span id="more-1157"></span> </p>
<pre><code>
package com.shaunabram.hamcrest;

import java.util.regex.Pattern;
import org.hamcrest.*;

/**
 * Matcher which tests if a string contains a specified number of substrings.
 *
 * @author sabram
 */
public class HasNumberOfSubstrings extends TypeSafeMatcher&lt;String&gt; {

    private final String substring;
    private final int count;

    public HasNumberOfSubstrings(String substring, int count) {
        this.substring = substring;
        this.count = count;
    }

    @Override
    protected boolean matchesSafely(String item) {
        Pattern p = Pattern.compile(substring);
        java.util.regex.Matcher m = p.matcher(item);
        int actualCount = 0;
        while (m.find()) {
            actualCount++;
        }
        if (actualCount == count) return true;
        else return false;
    }

    public void describeTo(Description description) {
        description.appendText("String containing ")
            .appendText(count + " occurences of ")
            .appendText(substring);

    }

    @Override
    public void describeMismatchSafely(String item, Description mismatchDescription) {
      mismatchDescription.appendValue(count)
                         .appendText(" occurence(s) of ")
                         .appendValue(substring)
                         .appendText(" in ")
                         .appendText(item);
    }

    @Factory
    public static Matcher&lt;String&gt; hasNumberOfSubstrings(String substring, int count) {
        return new HasNumberOfSubstrings(substring, count);
    }

}

</code></pre>
]]></content:encoded>
			<wfw:commentRss>http://www.shaunabram.com/hamcrest-matcher/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Hamcrest</title>
		<link>http://www.shaunabram.com/hamcrest/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=hamcrest</link>
		<comments>http://www.shaunabram.com/hamcrest/#comments</comments>
		<pubDate>Mon, 18 Apr 2011 03:33:31 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[OpenSource]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Hamcrest]]></category>
		<category><![CDATA[JUnit]]></category>

		<guid isPermaLink="false">http://www.shaunabram.com/?p=1014</guid>
		<description><![CDATA[Hamcrest is a framework for writing matcher objects. Matchers have a variety of uses, but are particularly useful when writing unit tests. Instead of using JUnit&#8217;s assertEquals methods, we use Hamcrest&#8217;s assertThat construct with one (or more) of the many Matchers available. For example assertTrue(a.equalTo(b)); becomes assertThat(a, equalTo(b)); A small change in this example, but [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://code.google.com/p/hamcrest/wiki/Tutorial">Hamcrest</a> is a framework for writing matcher objects. <a href="http://www.jmock.org/matchers.html">Matchers</a> have a variety of uses, but are particularly useful when writing unit tests. Instead of using JUnit&#8217;s assertEquals methods, we use Hamcrest&#8217;s assertThat construct with one (or more) of the many Matchers available. For example</p>
<pre><code>    assertTrue(a.equalTo(b));</code></pre>
<p>becomes</p>
<pre><code>    assertThat(a, equalTo(b));</code></pre>
<p>A small change in this example, but Hamcrest&#8217;s benefits are many, enabling you to write much more flexible tests that are easier to read and have more meaningful failure messages.<br />
<span id="more-1014"></span><br />
<br/></p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;<a href="#benefits">Benefits of using Hamcrest</a><br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#improvedReadability">Improved readability of tests</a><br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#easierFailure">Better failure messages</a><br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#combineMatcher">Combine Matchers</a><br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#customMatcher">Custom Matchers</a><br />
&nbsp;&nbsp;&nbsp;&nbsp;<a href="#limitations">Limitations</a><br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#whenNotToUse">Don&#8217;t use if JUnit will do</a><br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#findingMatchers">Finding the right Matcher</a><br />
&nbsp;&nbsp;&nbsp;&nbsp;<a href="#setup">Setup</a><br />
&nbsp;&nbsp;&nbsp;&nbsp;<a href="#troubleShooting">Trouble Shooting</a><br />
&nbsp;&nbsp;&nbsp;&nbsp;<a href="#links">Links</a></p>
<p><a name="benefits"></a><br />
<br/></p>
<h3>Benefits of using Hamcrest</h3>
<p><br/><br />
<a name="improvedReadability"></a></p>
<h4>Improved readability of tests</h4>
<p>The following code, which utilizes the Hamcrest API, is easy to understand, even if you have no understanding of Hamcrest, or Java for that matter:</p>
<pre><code>    assertThat(car, is(equalTo(ferrari));
    assertThat(cars, hasItems(ferarri, porsche));</code></pre>
<p>Basically, Hamcrest provides a <a href="http://en.wikipedia.org/wiki/Fluent_interface">fluent API</a>.</p>
<p><a name="easierFailure"></a><br />
<br/></p>
<h4>Better failure messages</h4>
<p>This is one of the biggest advantages of using Hamcrest.<br />
For example, if you run the following test, which makes use of JUnit&#8217;s assertTrue method:</p>
<pre><code>
    @Test
    public void testGreatThan_JUnit() {
        int minimumPrice = 0;
        int actualPrice = -1;
        //using org.junit.Assert.assertTrue
        assertTrue(actualPrice &gt; minimumPrice);
    }</code></pre>
<p>You get the following terse and uninformative error:</p>
<blockquote><p>java.lang.AssertionError</p></blockquote>
<p>However if you rewrite the test to use Hamcrest&#8217;s assertThat method with the greaterThan matcher, as follows:</p>
<pre><code>
    @Test
    public void testGreaterThan_Hamcrest() {
        int minimumPrice = 0;
        int actualPrice = -1;
        //using org.hamcrest.MatcherAssert.assertThat
        //and  org.hamcrest.Matchers.greaterThan
        assertThat(actualPrice, greaterThan(minimumPrice));
    }</code></pre>
<p>You would get the following much more informative error message:</p>
<blockquote><p>
java.lang.AssertionError:<br />
Expected: a value greater than <0><br />
     but: <-1> was less than <0>
</p></blockquote>
<p>Basically, assertThat will tell you what was expected and what the value actually was where as assertTrue will only tell you that you got false where you expected true.<br />
(You can of course put an explicit error message in the JUnit assertion yourself of course, as in:<br />
assertTrue(&#8220;Expected a value greater than &#8221; + minimumPrice, actualPrice > minimumPrice);<br />
But Hamcrest is more descriptive and avoids the extra effort.)</p>
<p><a name="combineMatchers"></a></p>
<h4>Combinations of Matchers</h4>
<p>Hamcrest allows you to use weird and wonderful combinations of Matchers. The obvious example is using not(), but other combinations can be achieved using Matchers such as both(), either(), or(), anyOf(), and many more.</p>
<p><a name="customMatcher"></a></p>
<h4>Create your own Matchers</h4>
<p>You can also create your own custom Matchers too, by implementing the Matcher interface. I wrote a blog post with an <a href="http://www.shaunabram.com/hamcrest-matcher/">example of a custom matcher</a>, but you can also find good examples <a href="http://code.google.com/p/hamcrest/wiki/Tutorial#Writing_custom_matchers">here</a> and <a href="http://blogs.atlassian.com/developer/2009/06/how_hamcrest_can_save_your_sou.html">here</a>.<br />
<br/><br />
Finally, as a wrap up to the benefits of using Hamcrest, see the <a href="http://junit.sourceforge.net/doc/ReleaseNotes4.4.html">JUnit release notes</a> which includes a description of using the Matcher mechanism.<br />
<a name="limitations"></a><br />
<br/></p>
<h3>Limitations</h3>
<p><a name="whenNotToUse"></a><br />
<br/></p>
<h4>Don&#8217;t use if JUnit will do</h4>
<p>If there is already a suitable JUnit method to use, there may not be any benefit to using a Hamcrest Matcher. Specifically, if you are just comparing primitive or String values, JUnit&#8217;s overloaded assertEquals methods should be adequate. For example, the follow two test approaches are both fairly easy to read and give the same message on test failure:</p>
<pre>
<code>	@Test
    	public void testEquals_JUnit() {
	    int expectedPrice = 0;
	    int actualPrice = -1;
	    //using org.junit.Assert.assertEquals
	    assertEquals(expectedPrice, actualPrice);
	    //java.lang.AssertionError: expected:&lt;0&gt; but was:&lt;-1&gt;
	}

	@Test
	public void testEquals_Hamcrest() {
	    int expectedPrice = 0;
	    int actualPrice = -1;
	    //using org.hamcrest.MatcherAssert.assertThat
            //and org.hamcrest.Matchers.equalTo
	    assertThat(actualPrice, equalTo(expectedPrice));
	    //java.lang.AssertionError: Expected: &lt;0&gt; but: was &lt;-1&gt;
	}</code>
</pre>
<p>However, for anything more complicated than primitive or String comparison, Hamcrest&#8217;s Matchers are likely to be much more useful.</p>
<p><a name="findingMatchers"></a><br />
<br/></p>
<h4>Finding the right Matcher</h4>
<p>One of the issues I have with Hamcrest is that the matchers are not all available in one place. It makes finding the correct matcher difficult and also means your IDE&#8217;s code assist, or import organizer, is not likely to be much help either. Most matchers are accessible via the <a href="http://www.shaunabram.com/hamcrest1.2-javadoc/org/hamcrest/Matchers.html">Matchers</a> class (although confusingly there is also the <a href="http://www.shaunabram.com/hamcrest1.2-javadoc/org/hamcrest/CoreMatchers.html">CoreMatchers</a> class, which seems to be a subset &#8211; I never quite figured that one out&#8230;). But other matchers are located in other classes and packages.</p>
<p>Example 1<br />
The very useful <a href="http://www.shaunabram.com/hamcrest1.2-javadoc/org/hamcrest/Matchers.html#hasItem(T)">hasItem</a> matcher is available in the aforementioned Matchers class:</p>
<pre><code>    import static org.hamcrest.MatcherAssert.assertThat;
    import static org.hamcrest.Matchers.hasItem;

    public class HamcrestExamples {

        List&lt;String&gt; list = new ArrayList&lt;String&gt;();

	@Before
	public void setup() {
		list.add("itemA");
		list.add("itemB");
	}

	@Test
	public void test() {
		assertThat(list, hasItem("itemA"));
	}
}</code></pre>
<p>But if you want to use the very similar <a href="http://www.shaunabram.com/hamcrest1.2-javadoc/org/hamcrest/core/IsCollectionContaining.html#hasItems%28T...%29">hasItems</a> matcher, you need to know (or trawl the javadocs to find out) it is in the <a href="http://www.shaunabram.com/hamcrest1.2-javadoc/org/hamcrest/core/IsCollectionContaining.html">IsCollectionContaining</a> class.</p>
<pre><code>    import static org.hamcrest.core.IsCollectionContaining.hasItems;
    ...
        @Test
	public void testHasItems() {
		assertThat(list, hasItems("itemA", "itemB"));
	}</code></pre>
<p>Example 2<br />
There is a useful containsString() method in the Matchers class that returns a Matcher to check is a String contains a sub-String, but if you want to check if a String contains several sub-Strings, in order, you need to know to look at the <a href="http://www.shaunabram.com/hamcrest1.3RC2-javadoc/org/hamcrest/text/StringContainsInOrder.html">StringContainsInOrder</a> class.</p>
<p>Notes: </p>
<ul>
<li>It looks like the above hasItems example will be remedied in 1.3 where hasItems will be made available via the Matchers class.</li>
<li>There is a very similar testing library that seems to overcome this problem called <a href="http://docs.codehaus.org/display/FEST/Fluent+Assertions+Module">Fluent Assertions module</a> from <a href="http://fest.easytesting.org/">FEST</a>. FEST has all the matchers available via a single static import. (Also, see this interesting <a href="http://docs.codehaus.org/display/FEST/Comparing+to+Hamcrest">comparison</a> with Hamcrest  &#8211; I see no reason not to use both)</li>
</ul>
<p><a name="setup"></a><br />
<br/></p>
<h3>Setup</h3>
<ol>
<li>Download the Hamcrest jar(s) from <a href="http://code.google.com/p/hamcrest/downloads">http://code.google.com/p/hamcrest/downloads</a> (using the all-in-one Jar is easiest)<br />
<blockquote><p>Note that JUnit does ship with some Hamcrest classes included. However, I prefer to use the Hamcrest jars directly because</p>
<ul>
<li>JUnit only includes the core Hamcrest (hamcrest-core) API classes. A much larger library of Matcher implementations is available by also using the hamcrest-library jars. Personally, I simply use the hamcrest-all.jar, which includes all the available Hamcrest classes.
</li>
<li>The package names in JUnit are different than those in Hamcrest e.g.  <em>org.hamcrest.MatcherAssert.assertThat</em> versus <em>org.junit.Assert.assertThat</em><br />
I prefer to keep things simply by always referring to the native org.hamcrest packages directly.
</li>
</ul>
<p>If you do choose to use the Hamcrest jars directly, it is also advisable to use the junit-dep jars. These come without the Hamcrest classes included, avoiding any uncertainty about which Hamcrest classes you are actually using.
</p></blockquote>
<li>Add the Hamcrest jar(s) to your classpath or maven dependencies.</li>
<li>Statically import Hamcrest&#8217;s assertThat construct and the Hamcrest matchers:<br />
<blockquote><p>import static org.hamcrest.MatcherAssert.assertThat;<br />
import static org.hamcrest.Matchers.*;</p></blockquote>
</li>
<li>Start using Hamrests&#8217;s assertThat in your unit tests, instead of JUnit&#8217;s assertTrue and assertEquals etc<br />
e.g. instead of</p>
<pre><code>    assertEquals(expectedValue, actualValue);</code></pre>
<p>use</p>
<pre><code>    assertThat(actualValue, equalTo(expectedValue));</code></pre>
</li>
</ol>
<p>Perhaps in future postings I will talk about how to use Hamcrest&#8217;s Matchers with Mock object frameworks such as <a href="http://easymock.org/">EasyMock</a> and <a href="http://www.jmock.org/">JMock</a>.</p>
<p><a name="troubleShooting"></a><br />
<br/></p>
<h3>Trouble Shooting</h3>
<p>Error:</p>
<blockquote><p>java.lang.SecurityException: class &#8220;org.hamcrest.Matchers&#8221;&#8216;s signer information does not match signer information of other classes in the same package</p></blockquote>
<p>You simply need to make sure the Hamcrest jar comes before JUnit in your classpath. Alternatively, use junit-dep.</p>
<p>Error:</p>
<blockquote><pre><code>cannot find symbol method
assertThat(java.util.List&lt;ExampleClass&gt;,org.hamcrest.Matcher&lt;java.lang.Iterable&lt;java.lang.Object&gt;&gt;)</code></pre>
</blockquote>
<p>or</p>
<blockquote><pre><code>cannot find symbol method
assertThat(java.util.List&lt;ExampleClass&gt;,org.hamcrest.Matcher&lt;java.lang.Iterable&lt;? super
java.lang.Object&gt;&gt;)</code></pre>
</blockquote>
<p>This error can happen with any iterable (not just Lists, as in the above example) using hasItem or hasItems (and possibly other matchers too). It is a known issue with Hamcrest at the moment and is documented <a href="http://code.google.com/p/hamcrest/issues/detail?id=84">here</a>, along with some fixes. I took the not-pretty-but-works option of declaring the Matcher in a local variable first<br />
e.g.</p>
<pre><code>    assertThat(list, hasItems(item1, item2));</code></pre>
<p>becomes</p>
<pre><code>    Matcher&lt;java.lang.Iterable&lt;ExampleClass&gt;&gt; matcher = hasItems(item1, item2);
    assertThat(list, matcher);</code></pre>
<p>Like I said, not-pretty-but-works.</p>
<p><a name="links"></a><br />
<br/></p>
<h3>Links</h3>
<ul>
<li><a href="http://code.google.com/p/hamcrest/">Hamcrest home page</a></li>
<li><a href="http://code.google.com/p/hamcrest/wiki/Tutorial">Hamcrest Tutorial</a></li>
<li><a href="http://www.shaunabram.com/hamcrest1.2-javadoc/index.html">Hamcrest API docs</a> &#8211; At the time of writing, the Hamcrest API docs seem surprisingly hard to come by online and there is an <a href="http://code.google.com/p/hamcrest/issues/detail?id=81">ticket</a> for this on the Hamcrest site. There also seems to be <a href="http://code.google.com/p/hamcrest/issues/detail?id=98">some issues</a> when building the javadocs for yourself:<br />
In the mean time, I have taken the liberty of posting them on my site here:</p>
<ul>
<li><a href="http://www.shaunabram.com/hamcrest1.2-javadoc/index.html">Hamcrest 1.2 javadocs</a></li>
<li><a href="http://www.shaunabram.com/hamcrest1.3RC2-javadoc/index.html">Hamcrest 1.3 RC2 javadocs</a></li>
</ul>
<p></a></p>
<li><a href="http://kentbeck.github.com/junit/javadoc/latest/">JUnit API docs</a></li>
<li><a href="http://docs.codehaus.org/display/FEST/Fluent+Assertions+Module">Fluent Assertions module</a> from <a href="http://fest.easytesting.org/">FEST</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.shaunabram.com/hamcrest/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

