<?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; OpenSource</title>
	<atom:link href="http://www.shaunabram.com/category/opensource/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.shaunabram.com</link>
	<description>Java and Technology weblog</description>
	<lastBuildDate>Wed, 18 Jan 2012 00:39:03 +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>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>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_BASE.<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>0</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>
		<item>
		<title>OSCON Day4: WebSockets</title>
		<link>http://www.shaunabram.com/oscon-day4-websockets/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=oscon-day4-websockets</link>
		<comments>http://www.shaunabram.com/oscon-day4-websockets/#comments</comments>
		<pubDate>Sun, 25 Jul 2010 01:03:14 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Events]]></category>
		<category><![CDATA[OpenSource]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[comet]]></category>
		<category><![CDATA[html]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[oscon]]></category>
		<category><![CDATA[websockets]]></category>

		<guid isPermaLink="false">http://www.shaunabram.com/?p=882</guid>
		<description><![CDATA[The first talk of the day I attended at Day 4 of OSCON was from Sean Sullivan (Aravo), who gave a talk on &#8220;Programming WebSockets&#8220;. Intro WebSockets is a technology that enables bidirectional communication between web browsers and server side processes. It provides a persistent connection between client &#038; Server, hence enabling &#8216;push&#8217; abilities where [...]]]></description>
			<content:encoded><![CDATA[<p>The first talk of the day I attended at Day 4 of <a href="http://www.oscon.com/oscon2010">OSCON</a> was from Sean Sullivan (<a href="http://www.aravo.com/">Aravo</a>), who  gave a talk on &#8220;<a href="http://www.oscon.com/oscon2010/public/schedule/detail/13805">Programming WebSockets</a>&#8220;.</p>
<h3>Intro</h3>
<p><a href="http://en.wikipedia.org/wiki/WebSockets">WebSockets</a> is a technology that enables bidirectional communication between web browsers and server side processes. It provides a persistent connection between client &#038; Server, hence enabling &#8216;push&#8217; abilities where you can push data/notification to browsers from the client. Other client communication options to compare it with would be <a href="http://en.wikipedia.org/wiki/Ajax_%28programming%29">Ajax</a><br />
and <a href="http://en.wikipedia.org/wiki/Comet_%28programming%29">Comet</a> (basically Ajax with long polling).</p>
<p><span id="more-882"></span> </p>
<h3>Specifications</h3>
<ul>
<li><a href="http://dev.w3.org/html5/websockets/">WebSockets API</a> &#8211; This focuses on the client side programming model.</li>
<li><a href="http://www.whatwg.org/specs/web-socket-protocol/">WebSockets protocol</a> &#8211; Describes the client/server communication in more detail. More complicated and 51 pages long. The WebSockets protocol is still actively being changed.</li>
</ul>
<h3>Browser Support</h3>
<ul>
<li>Google Chrome 4.0.249.0 and higher (v5 has WebSockets enabled by default)</li>
<li>Safari 5.0</li>
<li>FireFox 4.0 beta 1</li>
<li>
IE 9: TBD</li>
</ul>
<p>There was a suggestion that Apple have decided to disable WebSockets in iOS4 but this is unconfirmed and the speaker suspects Apple will support WebSockets in the future.</p>
<h3>Server side support</h3>
<ul>
<li>Apache Server &#8211; not supported yet</li>
<li><a href="http://code.google.com/p/pywebsocket/">Py WebSocket</a> &#8211; designed for use with Apache Server (actually implemented by Google Chromium team.)</li>
<li>There is also a DJango solution: <a href="http://pypi.python.org/pypi/django-websocket/">django-websocket</a></li>
<li><a href="http://blogs.webtide.com/gregw/entry/jetty_websocket_server">Jetty WebSocket Server</a> &#8211; Jetty has supported WebSockets since last September. This seems to be a good option.</li>
</ul>
<p>However, note that there is no standard service side Java API. Each Java container has it&#8217;s own API. Therefore it will likely be difficult to write WebSockets for one app server and do a straight port to another app server.</p>
<h3>Projects</h3>
<p>Other Java Projects supporting WebSockets:</p>
<ul>
<li>GlassFish/Grizzly (see a DZone posting on it <a href="http://www.dzone.com/links/glassfish_web_sockets_sample.html?ref=rs">here</a>)</li>
<li><a href="http://jwebsocket.org/">jWebSocket</a></li>
<li><a href="http://jboss.org/netty">JBoss Netty</a> (see patch <a href="https://jira.jboss.org/browse/NETTY-264">here</a>)</li>
<li><a href="http://www.caucho.com/resin/examples/websocket-java/index.xtp">Caucho Resin</a></li>
</ul>
<p>Sean finished by showing the <a href="http://code.google.com/p/quake2-gwt-port/">Google Quake demo</a> (also reported <a href="http://www.bit-tech.net/news/2010/04/05/google-ports-quake-2-to-html5/1">here</a>).</p>
<p>The conclusion of the talk was on how to gracefully handle browsers that don&#8217;t support WebSockets (e.g. IE8). The main option here seems to be &#8220;<a href="http://code.google.com/p/jquery-graceful-websocket/">The Graceful WebSocket</a>&#8220;. This resorts back to using AJAX long pulling if WebSockets isn&#8217;t supported in the browser.</p>
<h3>My Thoughts</h3>
<p>WebSockets looks like one of the most interesting technologies that fall under the HTML5 umbrella. If it gets wide browser support (e.g. IE9), and perhaps some standardization on the server side, it could really take off and even potentially over take Ajax. Definitely one to watch&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.shaunabram.com/oscon-day4-websockets/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Open Source Convention in Portland, Oregon</title>
		<link>http://www.shaunabram.com/attending-oscon/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=attending-oscon</link>
		<comments>http://www.shaunabram.com/attending-oscon/#comments</comments>
		<pubDate>Sat, 17 Jul 2010 18:18:01 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Events]]></category>
		<category><![CDATA[OpenSource]]></category>

		<guid isPermaLink="false">http://www.shaunabram.com/?p=863</guid>
		<description><![CDATA[I will be attending the week long Open Source Convention (OSCON) next week in Portland, Oregon. Looking forward to it as there is a huge variety of talks, including databases, Android, Scala, Spring, HTML5 and a bunch of Google technologies. Get in touch with me at Shaun at Abram dot com if you happen to [...]]]></description>
			<content:encoded><![CDATA[<p>I will be attending the week long Open Source Convention (<a href="http://www.oscon.com">OSCON</a>) next week in Portland, Oregon. Looking forward to it as there is a huge <a href="http://www.oscon.com/oscon2010/public/schedule/grid">variety of talks</a>, including databases, Android, Scala, Spring, HTML5 and a bunch of Google technologies. Get in touch with me at Shaun at Abram dot com if you happen to be going along&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.shaunabram.com/attending-oscon/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Selenium talk at SF JUG</title>
		<link>http://www.shaunabram.com/sfjug-selenium/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=sfjug-selenium</link>
		<comments>http://www.shaunabram.com/sfjug-selenium/#comments</comments>
		<pubDate>Wed, 13 Jan 2010 07:26:17 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Events]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[OpenSource]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[JUG]]></category>
		<category><![CDATA[q]]></category>
		<category><![CDATA[selenium]]></category>
		<category><![CDATA[sfjug]]></category>
		<category><![CDATA[unittesting]]></category>

		<guid isPermaLink="false">http://www.shaunabram.com/?p=749</guid>
		<description><![CDATA[I attended another great San Francisco JUG meeting tonight, this time on How to use Selenium with Maven/Ant to automate testing of web apps. The talk was given by Chris Bedford, from Build Lackey Labs &#8211; &#8220;Automating the Monkey Work Out and the Quality In!&#8221;. Overall, I thought this was a great talk by Chris. [...]]]></description>
			<content:encoded><![CDATA[<p>I attended another great <a href="http://www.sfjava.org/calendar/10674274/">San Francisco JUG</a> meeting tonight, this time on <a href="http://www.sfjava.org/calendar/11982857/">How to use Selenium with Maven/Ant to automate testing of web apps</a>.</p>
<p>The talk was given by Chris Bedford, from <a href="http://buildlackey.com/">Build Lackey Labs</a> &#8211; &#8220;Automating the Monkey Work Out and the Quality In!&#8221;. Overall, I thought this was a great talk by Chris. He clearly has a huge amount of experience creating automated tests and integrating them with build tools and he gave a well structured, interesting, well delivered presentation. I have posted a copy of <a href="http://www.shaunabram.com/attachments/testing-java-web-apps-with-selenium5.ppt">Chris&#8217;s slides</a> and I think the video will be posted on the SF JUG site at some point, but I have also posted my notes from the presentation below&#8230;<br />
<span id="more-749"></span></p>
<h3>Selenium Overview</h3>
<p>Chris started off with an overview of <a href="http://seleniumhq.org/">Selenium</a> &#8211; a tool for automating tests for web based applications. He then introduced us to the Selenium IDE &#8211; a Firefox add-on that allows you to set up tests by recording clicks on a web page, or by manually entering commands. The tests can then be played back as part of your automated test suite.</p>
<h3>Creating Selenium Tests</h3>
<p>Chris showed us the process by both executing an existing test he had already setup, and by walking us through the creation of a new test, which loaded a page, waited for text to be present, clicked on a link, and confirmed that text was present. The test was a html file, but he showed how to export it as <a href="http://testng.org/doc/index.html">TestNG</a> and <a href="http://www.junit.org/">JUnit</a> tests  (although both exports resulted in kind of ugly java code!)</p>
<h3>Possible hiccups with Selenium</h3>
<p>One of the things I thought Chris did well was, in addition to pointing out all the many great things about Selenium, he also pointed out some of the slight issues with Selenium that he has encountered during his time using it, such as</p>
<ul>
<li>Difficulties getting the initial Open page to work</li>
<li>Issues with where the test files get saved</li>
<li>Making sure you have the tests run slow to start with (to avoid timing/loading issues)</li>
<li>The Selenium IDE may be difficult to get working with IE (Firefox is fine)</li>
</ul>
<h3>Selenium Components</h3>
<p>The main Selenium section then finished up with a quick over of the various Selenium Components:</p>
<ul>
<li>Selenium IDE</li>
<li>Selenese Commands</li>
<li>Selenium RC (Remote Control)</li>
</ul>
<p>Chris also had a section on the &#8216;<a href="http://en.wikipedia.org/wiki/Same_origin_policy">same origin</a>&#8216; JavaScript  policy that Selenium manages to circumvent by using the Selenium RC Server. He managed to explain the issue in simple terms.</p>
<h3>Other functional test alternatives</h3>
<p>Chris discussed other functional test alternatives by comparing <a href="http://webtest.canoo.com/webtest/manual/WebTestHome.html">Canoo</a> to Selenium (Canoo is also an automated web app testing framework).</p>
<p>Chris also mentionted <a href="http://code.google.com/p/umangite/">Umangite</a>, Chris Richardson&#8217;s open source testing framework that makes Selenium tests easier to write. I have used this before, and agree it is worth checking out&#8230;</p>
<h3>Using Selenium with Build Tools</h3>
<p>He then discussed using Maven with Selenium, including using <a href="http://cargo.codehaus.org/">Cargo</a> (e.g. using the <a href="http://cargo.codehaus.org/Maven2+plugin">cargo maven2 plugin</a>). Cargo is a set of APIs that assists in</p>
<ul>
<li>installing web containers, such as Tomcat, JBoss</li>
<li>booting and shutting them down</li>
<li>deploying web apps (.wars, .ears)</li>
</ul>
<p>Chris finished the Selenium &#038; build tools section with a quick run through of using Selenium with <a href="http://ant.apache.org/">Ant</a>.</p>
<h4>Continuous Integration</h4>
<p>The final section of the presentation was a talk on Continuous Integration (CI). Chris described CI as: </p>
<ul>
<li>A dedicated box (see my follow up question below!) that runs regular full builds (including tests) of your software</li>
<li>Build triggers when any developer checks into SCM</li>
<li>Team is notified of any issues</li>
</ul>
<p>And talked about how Selenium can be used with <a href="http://hudson-ci.org/">Hudson</a> &#8211; a very cool CI tool from Sun. This leads well into <a href="http://www.sfjava.org/calendar/12296161/">next month&#8217;s SF JUG talk</a>!</p>
<h3>Q&#038;A</h3>
<p>Q: Do you have any info on WebDriver merging with Selenium?<br />
A: No, but sounds interesting!</p>
<p>Q: How closely do test writers work with marketing people?<br />
A: Chris suggested checking out the <a href="http://www.easyb.org/">easyb</a> framework, a behavior driven development framework that allows you to write conditions in a very abstract level, using a DSL that marketers can use and understand. He also suggested looking at the <a href="http://www.fitnesse.org/">fitnesse</a> framework.</p>
<p>Q: I asked Chris via email after the talk what he meant by needing &#8216;dedicated&#8217; box/server for Continuous Integration.<br />
A: He clarified that by &#8216;dedicated&#8217;, he just meant that the build box  should not be a box that you are doing development on, and that there isn&#8217;t anything wrong with having a mix of services on one machine. e.g. having a qa box that has the CI server and maybe hosts the bug tracking system as well&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.shaunabram.com/sfjug-selenium/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Data binding in Spring MVC</title>
		<link>http://www.shaunabram.com/data-binding-in-spring-mvc/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=data-binding-in-spring-mvc</link>
		<comments>http://www.shaunabram.com/data-binding-in-spring-mvc/#comments</comments>
		<pubDate>Thu, 05 Nov 2009 08:35:08 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[OpenSource]]></category>
		<category><![CDATA[Products]]></category>
		<category><![CDATA[mvc]]></category>
		<category><![CDATA[spring]]></category>

		<guid isPermaLink="false">http://www.shaunabram.com/?p=667</guid>
		<description><![CDATA[Two of the most important tasks carried out by Spring MVC when you submit a form are Data binding and validation. The following article discusses data binding, including the use of custom PropertyEditors, and some of the options available for registering such editors. Most of the information discussed applies to Spring in general, but its [...]]]></description>
			<content:encoded><![CDATA[<p>Two of the most important tasks carried out by Spring MVC when you submit a form are Data binding and validation.<br />
The following article discusses data binding, including the use of custom PropertyEditors, and some of the options available for registering such editors. Most of the information discussed applies to Spring in general, but its application in Spring MVC is my primary interest.</p>
<p>In a future article I would like to discuss validation including the use of custom error messages.</p>
<p>Note that these notes relate to version 2.5.6 of Spring, the latest production code at time of writing, and depend heavily on the corresponding <a href="http://static.springsource.org/spring/docs/2.5.x/reference/">Spring reference docs</a>.</p>
<p><span id="more-667"></span><br />
<script type="text/javascript"><!--
google_ad_client = "ca-pub-6044065224180784";
/* Midpage banner */
google_ad_slot = "3447137835";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>
<h2>Data Binding</h2>
<p>Spring MVC allows the use of command objects (aka form backing objects, model attributes, domain model objects &#8211; basically the objects used to transport data between your view and your controller) using just about any type. However, the Servlet API deals with form parameters as Strings. Spring uses a technique called data binding to covert between the String representation and the real underlying type. This enables user input to be bound to the objects you use to process user input. In other words, the values entered by a user in a form can be used to set the property values on a chosen object.<br />
As well as binding the values, Spring includes support for validation and binding result analysis. </p>
<p>The binding functionality is provided by Spring&#8217;s <a href="http://static.springsource.org/spring/docs/2.5.6/api/org/springframework/validation/DataBinder.html">org.springframework.validation.DataBinder</a> class.<br />
And when converting a String to some arbitrary type, DataBinders make use of ProperEditors. PropertyEditors are not Spring specific, but rather part of the <a href="http://java.sun.com/javase/7/docs/api/java/beans/PropertyEditor.html">JavaBeans API</a>.</p>
<h3>Using PropertyEditors</h3>
<p>Spring heavily uses the concept of PropertyEditors to effect the conversion between an Object and a String.<br />
Spring has a number of built-in PropertyEditors to make life easy (for a complete list, see <a href="http://static.springsource.org/spring/docs/2.5.x/reference/validation.html#beans-beans-conversion">here</a>).<br />
If you are using a custom type that Spring is unable to convert to and from a String, you will likely receive a lovely error such as this:</p>
<blockquote><p>org.springframework.web.bind.ServletRequestBindingException: Errors binding onto object &#8216;dependsOnExoticType&#8217;; nested exception is org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors<br />
Field error in object &#8216;dependsOnExoticType&#8217; on field &#8216;type&#8217;: rejected value [test]; codes [typeMismatch.dependsOnExoticType.type,typeMismatch.type,typeMismatch.example.ExoticType,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [dependsOnExoticType.type,type]; arguments []; default message [type]]; default message [Failed to convert property value of type [java.lang.String] to required type [example.ExoticType] for property &#8216;type&#8217;; nested exception is java.lang.IllegalArgumentException: Cannot convert value of type [java.lang.String] to required type [example.ExoticType] for property &#8216;type&#8217;: no matching editors or conversion strategy found]</p></blockquote>
<p>The solution is to create your own custom editor.</p>
<h4>Creating a custom property editor</h4>
<p>A custom property editor should be of type java.beans.PropertyEditor. It tells Spring how to convert to a String and back again. As an example, see the ExoticTypeEditor in the Spring reference docs <a href="http://static.springsource.org/spring/docs/2.5.x/reference/validation.html#beans-beans-conversion-customeditor-registration">here</a>. </p>
<p>The question is then how to register the custom editor. </p>
<h4>Registering your custom editor</h4>
<p>There are several ways to ensure you custom editor gets registered.</p>
<h5>1) Put Editor in same package</h5>
<p>The simplest way (by far!) is to put the Editor in the same package as the class it handles. This is because the standard JavaBeans infrastructure will automatically discover PropertyEditor classes (without you having to register them explicitly) if they are in the same package as the class they handle, and have the same name as that class, with&#8217;Editor&#8217; appended;</p>
<p>However, if putting the Editor in the same package as the class it handlers is not possible (If for example, you are using a custom type from a 3rd party library and hence you don&#8217;t have access to the source code), try one of the other options below&#8230;</p>
<h5>2) CustomEditorConfigurer </h5>
<p>Another approach to registering a custom PropertyEditor is to use a special bean factory post-processor called CustomEditorConfigurer.<br />
This is the approach used in the spring reference manual for the &#8216;ExoticType&#8217; example. Again, see<br />
section 5.4.2.1. Registering additional custom PropertyEditors, <a href="http://static.springsource.org/spring/docs/2.5.x/reference/validation.html#beans-beans-conversion-customeditor-registration">here</a>.</p>
<p>The CustomEditorConfigurer is used to register the new PropertyEditor with the ApplicationContext, which will then be able to use it as needed.</p>
<h6>Gotchas</h6>
<p><h7>i) Won&#8217;t work with BeanFactory &#8211; only ApplicationContext</h7><br />
The PropertyEditors defined in the &#8216;customEditorConfigurer&#8217; bean will only be automatically used if you are using an ApplicationContext implementation (i.e. will not work for BeanFactory). This is discussed <a href="http://forum.springsource.org/showthread.php?t=15951">here</a>.<br />
<h7>ii) Only works for ApplicationContext created beans &#8211; not data binding beans such as form objects</h7><br />
This approach only works for beans created by the ApplicationContext. The PropertyEditors that are registered via CustomEditorConfigurer are NOT available for use in the data binding infrastructure (this is discussed <a href="http://forum.springsource.org/showthread.php?t=30759">here</a> and <a href="http://jira.springframework.org/browse/SPR-1210">here</a>).<br />
I think this should be made more clear in the spring framework ref docs (although, in fairness, it is covered in the <a href="http://static.springsource.org/spring/docs/3.0.0.M1/javadoc-api/org/springframework/beans/factory/config/CustomEditorConfigurer.html">CustomEditorConfigure javadocs</a>).</p>
<p>
So, if you are using Spring MVC and dealing with form submission, the next option may be better&#8230;</p>
<h5>3) Explicitly register your editor in initBinder</h5>
<p>So, a better approach, as far as form data binding is concerned, is to explicitly register your editor within initBinder() in the relevant Controller. e.g.</p>
<pre>
<code>@Controller
@RequestMapping("/exoticView.htm")
public class TestController {

	//post and get handling methods etc...

	@InitBinder
	protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) {
		binder.registerCustomEditor(ExoticType.class, new ExoticTypeEditor());
	}

}</code>
</pre>
<h5>4) Use a WebBindingInitializer</h5>
<p>If you find yourself using the above approach (registering your customer editor in initBinder) in many controllers, and you use a annotation based controller (Spring 2.5+), then you can use a WebBindingInitializer to register global property editors. </p>
<p>To do this, create a class that implements the WebBindingInitializer interface, for example</p>
<pre>
<code>public class GlobalBindingInitializer implements WebBindingInitializer {

    public void initBinder(WebDataBinder binder, WebRequest request) {
        binder.registerCustomEditor(ExoticType.class, new ExoticTypeEditor());
    }

}</code>
</pre>
<p>Then update your web application context file to contain:</p>
<pre>
<code>&lt;bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"&gt;
    &lt;property name="webBindingInitializer"&gt;
        &lt;bean class="GlobalBindingInitializer"/&gt;
    &lt;/property&gt;
&lt;/bean&gt;</code>
</pre>
<p>I discovered this approach in a posting on <a href="http://stackoverflow.com/about">StackOverflow </a> about <a href="http://stackoverflow.com/questions/1416423/hidden-features-of-spring-framework">hidden features of Spring </a>. It means you can register an editor once and use it anywhere. <strong><em>This is now my preferred way to register custom property editors.</em></strong></p>
<h5>5) Use PropertyEditorRegistrar</h5>
<p>Another mechanism for registering property editors with the Spring container, and the final one in the Spring reference docs, is to create and use a PropertyEditorRegistrar. See section 5.4.2.1.1 <a href="http://static.springsource.org/spring/docs/2.5.x/reference/validation.html#beans-beans-conversion-customeditor-registration">here</a>. The docs say that this is a good approach &#8220;when you need to use the same set of property editors in several different situations&#8221;. I have used this approach successfully in the past, but to be honest, I don&#8217;t quite see the benefits beyond the GlobalBindingInitializer approach above and it seems to require a few more steps. (I also saw some confusing debate on exactly what steps are mandatory <a href="http://jira.springframework.org/browse/SPR-3512?focusedCommentId=28100&#038;page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel#action_28100">here</a>)</p>
<h5>6) BeanInfo</h5>
<p>There is also a BeanInfo mechanism mentioned in the Spring docs which I admit I have never tried &#8211; or fully understood.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.shaunabram.com/data-binding-in-spring-mvc/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>

