<?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>Jayway Team Blog &#187; Mattias Severson</title>
	<atom:link href="http://blog.jayway.com/author/mattiasseverson/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.jayway.com</link>
	<description>Sharing Experience</description>
	<lastBuildDate>Sat, 11 Feb 2012 10:33:02 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Spring Integration Tests, Part II, Using Mock Objects</title>
		<link>http://blog.jayway.com/2011/12/12/spring-integration-tests-part-ii-using-mock-objects/</link>
		<comments>http://blog.jayway.com/2011/12/12/spring-integration-tests-part-ii-using-mock-objects/#comments</comments>
		<pubDate>Mon, 12 Dec 2011 20:17:27 +0000</pubDate>
		<dc:creator>Mattias Severson</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[easymock]]></category>
		<category><![CDATA[mock]]></category>
		<category><![CDATA[mockito]]></category>
		<category><![CDATA[spring]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=10532</guid>
		<description><![CDATA[In the previous post, I wrote how you can use Spring's FactoryBean to facilitate the creation of mock objects for Spring integration tests. Now, it is time to use the EasyMockFactoryBean (in this post EasyMock has been used for creating mock objects, but a similar approach applies to Mockito as well. Start by looking at [...]]]></description>
			<content:encoded><![CDATA[<p>In the previous post, I wrote how you can use Spring's <code>FactoryBean</code> to facilitate the <a href="http://blog.jayway.com/2011/11/30/spring-integration-tests-part-i-creating-mock-objects/">creation of mock objects</a> for Spring integration tests. Now, it is time to use the <a href="https://gist.github.com/1397610#file_easy_mock_factory_bean.java">EasyMockFactoryBean</a> <small>(in this post <a href="http://www.easymock.org">EasyMock</a> has been used for creating mock objects, but a similar approach applies to <a href="http://www.mockito.org">Mockito</a> as well. Start by looking at the <a href="https://gist.github.com/1397610#file_mockito_factory_bean.java">MockitoFactoryBean</a>)</small>.</p>
<p>Next, imagine that the <code>Facade</code> class and the <code>Delegate</code> interface below are part of a bigger system: </p>
<p><script src="https://gist.github.com/1427987.js?file=Facade.java"></script><br />
<script src="https://gist.github.com/1427987.js?file=Delegate.java"></script></p>
<p>Create a matching <a href="https://gist.github.com/1427987#file_easymock_test_config.xml">easymock-test-config.xml</a> <small>(or <a href="https://gist.github.com/1427987#file_movkito_test_config.xml">mockito-test-config.xml</a>)</small>.</p>
<p>Now, we have all the bits and pieces that are needed to start writing the integration test. We start simple to make sure that we autowiring and Spring context has been configured correctly:<br />
<script src="https://gist.github.com/1427987.js?file=InitialTest.java"></script></p>
<p>The test is executed and it passes without any problem.</p>
<p>A second test is added to the same file with some added mock behavior:<br />
<script src="https://gist.github.com/1427987.js?file=SecondTest.java"></script></p>
<p>Excellent, that test also passes.</p>
<p>Now that we have warmed up, we add a third test to the test class:<br />
<script src="https://gist.github.com/1427987.js?file=ThirdTest.java"></script><br />
As expected, this test also passes without any problem.</p>
<p>Unfortunately, that is not always true. A closer investigation reveals that all tests pass when they are executed <i>individually</i>. When executing all three tests (either from the IDE or from a build tool like Maven), the third test <i>fails</i> unexpectedly:</p>
<pre>
java.lang.AssertionError:
  Unexpected method call Delegate.doSomethingElse():
        at org.easymock.internal.MockInvocationHandler.invoke(MockInvocationHandler.java:44)
	at org.easymock.internal.ObjectMethodsFilter.invoke(ObjectMethodsFilter.java:85)
	at $Proxy8.doSomethingElse(Unknown Source)
        [...]
</pre>
<p>This is EasyMock telling us that the mock object is in the wrong state. An EasyMock mock object goes through a series of steps:</p>
<ol>
<li><i>Initialization</i> - Instantiate the mock object.</li>
<li><i>Record</i> - Record the expectations of the mock object.</li>
<li><i>Replay</i> - Call <code>replay()</code> on the mock object so that it can replay the recorded state.</li>
<li><i>Test</i> - Execute the test assertions.</li>
<li><i>Verify</i> - Call <code>verify()</code> on the mock object to certify that the recorded mock expectations are fulfilled.</li>
</ol>
<p>In an ordinary unit test, the mock object is thrown away after the <i>verify</i> phase, a new mock instance is created before the next test that can be used to <i>record</i> the new behavior. However, since we are creating a Spring integration test, there is one more thing to consider.</p>
<h2>Reused beans</h2>
<p>In the <a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/testing.html#testing-ctx-management">testing chapter</a> of the Spring manual it is stated that:</p>
<blockquote><p>By default, once loaded, the configured ApplicationContext and all of its beans are reused for each test method. Thus the setup cost is incurred only once (per test fixture), and subsequent test execution is much faster.</p></blockquote>
<p>Consequently, all Spring beans, including mocked beans, will preserve their state between different test methods. The mock object will be in the <i>verify</i> state when the last test begins and not in the <i>record</i> state when <code>delegateMock.doSomethingElse()</code> is called. To solve the problem, we need some mechanism to ensure that the mock object is in a known, well-defined state before each test.</p>
<h2>Reset mocks</h2>
<p>Both EasyMock and Mockito provide methods to <code>reset()</code> the state of the mocked objects. Normally, resetting mock objects in the middle of a test method is considered to be a <a href="http://docs.mockito.googlecode.com/hg/latest/org/mockito/Mockito.html#17">potential code smell</a>, because it is likely that you are testing too much and that the test could be refactored into two separate tests accordingly. Nonetheless, resetting the mock instance <a href="http://junit.sourceforge.net/javadoc/org/junit/Before.html">@Before</a> each test allow us to keep the same mock instance through the entire lifetime of the test class and yet put it in the <i>record</i> state when before each test starts:</p>
<p><script src="https://gist.github.com/1427987.js?file=SetUp.java"></script></p>
<p>When executing all tests in the test class, we see that that the problem has been solved and all tests pass.<br />
For reference, click the link for the full source code of the <a href="https://gist.github.com/1427987#file_easy_mock_facade_test.java">EasyMock test class</a> <small>(and the <a href="https://gist.github.com/1427987#file_mockito_facade_test.java">Mockito test class</a>)</small>.</p>
<h2>Comments</h2>
<p>You may choose to reset the mocks <a href="http://junit.sourceforge.net/javadoc/org/junit/After.html">@After</a> each test, the result will be the same.</p>
<p>The <code>reset()</code> method is called <i>between</i> the different test methods (because of the nature of <code>@After</code> and <code>@Before</code>), so the code smell of calling reset <i>within</i> a test is avoided.</p>
<p>Tests written using Mockito mocks are generally more tolerant for this kind of problem. In contrast to EasyMock, Mockito has no <code>replay()</code> method and no notion of steps. Therefore, it is possible to add additional mock expectations and to replace existing expectations, both after the test has been executed as well as after the result has been verified. Hence, you should always reset your mock objects before each test so that you do not get any accidental mocking behavior.</p>
<p>As a side note, another solution would be to annotate the test class (or all of its test methods) with the <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/test/annotation/DirtiesContext.html">@DirtiesContext</a> annotation. This will effectively recreate the entire application context after each test has been executed, causing all Spring beans to be in their initial state and thus the mock beans to be in the <i>record</i> state. Although this will work, there will be a significant performance penalty compared to the suggested <code>reset()</code> and <code>@Before</code> / <code>@After</code> solution, because all beans in the application context will be recreated and re-wired before each test method. </p>
<h2>Dependencies</h2>
<ul>
<li>Spring 3.0.6</li>
<li>Mockito 1.8.5</li>
<li>jUnit 4.10</li>
<li>EasyMock 3.1</li>
</ul>
<h2>References</h2>
<ul>
<li><a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/testing.html#testing-ctx-management">Spring Reference Manual - Test Context Management and Caching</a></li>
<li><a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/testing.html#testcontext-junit4-runner">Spring Reference Manual - SpringJunit4ClassRunner</a></li>
<li><a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/testing.html#integration-testing-annotations">Spring Reference Manual - ContextConfiguration</a></li>
<li><a href="http://easymock.org/EasyMock3_1_Documentation.html">EasyMock</a></li>
<li><a href="http://docs.mockito.googlecode.com/hg/org/mockito/Mockito.html">Mockito</a></li>
</ul>
<p>Previous post: <a href="http://blog.jayway.com/2011/11/30/spring-integration-tests-part-i-creating-mock-objects/">Spring Integration Tests, Part I, Creating Mock Objects</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/12/12/spring-integration-tests-part-ii-using-mock-objects/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Spring Integration Tests, Part I, Creating Mock Objects</title>
		<link>http://blog.jayway.com/2011/11/30/spring-integration-tests-part-i-creating-mock-objects/</link>
		<comments>http://blog.jayway.com/2011/11/30/spring-integration-tests-part-i-creating-mock-objects/#comments</comments>
		<pubDate>Wed, 30 Nov 2011 20:26:05 +0000</pubDate>
		<dc:creator>Mattias Severson</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[easymock]]></category>
		<category><![CDATA[factory-method]]></category>
		<category><![CDATA[factorybean]]></category>
		<category><![CDATA[mock]]></category>
		<category><![CDATA[mockito]]></category>
		<category><![CDATA[spring]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=10514</guid>
		<description><![CDATA[When writing integration tests with Spring, it can sometimes be convenient to mock one or more of Spring bean dependencies. However, during some circumstances strange things may happen... (In this post, Mockito has been used for creating mock objects, but the same problem applies to EasyMock as well. You can find the corresponding files if [...]]]></description>
			<content:encoded><![CDATA[<p>When writing integration tests with Spring, it can sometimes be convenient to mock one or more of Spring bean dependencies. However, during some circumstances strange things may happen...</p>
<p><small>(In this post, <a href="http://www.mockito.org">Mockito</a> has been used for creating mock objects, but the same problem applies to <a href="http://www.easymock.org">EasyMock</a> as well. You can find the corresponding files if you follow the provided links.)</small></p>
<h2>Test setup</h2>
<p>In the following example the <code>SomeClass</code> needs a reference to an instance of the <code>SomeDependency</code> interface:</p>
<p><script src="https://gist.github.com/1397610.js?file=SomeClass.java"></script></p>
<p><script src="https://gist.github.com/1397610.js?file=SomeDependency.java"></script></p>
<p>When writing the integration test, we use the static  <a href="http://docs.mockito.googlecode.com/hg/org/mockito/Mockito.html#mock(java.lang.Class)">Mockito.mock(Class classToMock)</a> method to create a mock instance. The straightforward approach would be to let Spring instantiate the mock object with a <a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-factory-class-static-factory-method">static factory method</a> in the xml configuration, e.g.</p>
<p><script src="https://gist.github.com/1397610.js?file=failing-mockito-config.xml"></script><br />
<small>(Corresponding <a href="https://gist.github.com/1397610#file_failing_easymock_config.xml">EasyMock config</a>.)</small></p>
<p>To verify that the beans are created and wired correctly, we write a simple test:</p>
<p><script src="https://gist.github.com/1397610.js?file=BeanWiringTest.java"></script><br />
<small>(Same test for EasyMock, just update the <code>@ContextConfiguration</code> with the EasyMock config file.)</code></small></p>
<p>To our surprise, the test fails:</p>
<pre>
[...]
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.BeanCreationException:
    Error creating bean with name 'someClass': Injection of autowired dependencies failed;
nested exception is org.springframework.beans.factory.BeanCreationException:
    Could not autowire field: private com.jayway.example.SomeDependency com.jayway.example.SomeClass.someDependency;
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
    No matching bean of type [com.jayway.example.SomeDependency] found for dependency:
    expected at least 1 bean which qualifies as autowire candidate for this dependency.
    Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
[...]
</pre>
<h2>Explanation</h2>
<p>In order to find a solution to the problem, we need to understand Spring's initialization process:</p>
<ol>
<li>
<i>Load bean definitions.</i><br />
This step includes scanning the application context XML files, scanning packages defined by <code>component-scan</code>, and loading the bean definitions found into the bean factory. (BeanFactoryPostProcessors such as the PropertyPlaceHolderConfigurer may be called to update the bean definitions.)
</li>
<li>
<i>Instantiate beans and store them in the application context.</i><br />
The bean factory creates the bean from the bean definitions. Bean dependencies get injected.
</li>
<li>
<i>Bean post processing.</i><br />
All initializing methods (e.g. annotated with <code>@PostConstruct</code>, <code>init-method</code>s declared in the XML and the <code>afterPropertiesSet()</code> method will execute. Annotations such as <code>@Required</code> will be validated. Dynamic proxies in an AOP environment will be created and so on.
</li>
</ol>
<p>The problem that we see occurs due to a corner case in the first two steps. When the bean definition is created Spring scans through the application context XML file. It finds the declaration of the mock bean and a reflective call is made to find out the return type of the method defined by the <code>factory-method</code> declaration in an attempt to determine the bean's type. The return type of this method is declared as the formal type parameter <code>&lt;T&gt;</code> (remember that we use the <a href="http://docs.mockito.googlecode.com/hg/org/mockito/Mockito.html#mock(java.lang.Class)">Mockito.mock(Class&lt;T&gt; classToMock)</a> as factory method). Consequently, the bean definition of <code>someDependencyMock</code> will be of <code>java.lang.Object</code> and not <code>SomeDependency</code> as one would think.</p>
<p>In the second step, the <code>someClass</code> bean is instantiated. Springs discovers the <code>@Autowired</code> annotation and tries to fetch an existing <code>SomeDependency</code> bean from the application context. None has yet been created, so the bean factory proceeds and looks for suitable bean definition in order to create an instance of the requested bean on the fly. This operation fails because the bean definition of <code>someDependency</code> is mapped to <code>java.lang.Object</code>. At this point, Spring bails out and throws the <code>NoSuchBeanDefinitionException</code>.  </p>
<h2>FactoryBean to the rescue</h2>
<p>The problem is solved by implementing a custom <a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-factory-extension-factorybean">FactoryBean</a> that can be used whenever we need to mock an object:</p>
<p><script src="https://gist.github.com/1397610.js?file=MockitoFactoryBean.java"></script><br />
<small>(In the <a href="https://gist.github.com/1397610#file_easy_mock_factory_bean.java">EasyMockFactoryBean</a>, I have added an enum to define the type of mock object.)</small></p>
<p>Next, the Spring test config is updated to use the factory bean:</p>
<p><script src="https://gist.github.com/1397610.js?file=mockito-factory-bean.xml"></script><br />
<small>(Corresponding <a href="https://gist.github.com/1397610#file_easymock_factory_bean.xml">EasyMock config</a>.)</small></p>
<p>Spring will still instantiate the beans in the order that they were declared in the <code>mockito-test-config.xml</code>, i.e. starting by creating an instance of <code>SomeClass</code> and then attempt to inject an instance of a <code>SomeDependency</code> into it before any has been created. The good news is that bean factory will scan through all declared <code>FactoryBean</code>s, calls its <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/beans/factory/FactoryBean.html#getObjectType()">getObjectType()</a> method, and if the returned type is correct, call its <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/beans/factory/FactoryBean.html#getObject()">getObject()</a> which should return an instance of the requested type.</p>
<h2>Alternative solution</h2>
<p>There is another more brittle solution to the problem. By simply changing the order of the tags in the initial application context, e.g. putting the bean declaration that defines the mock above the component scan, will cause the test to pass. The bean definition will still be wrong in the sense that the <code>someDependencyMock</code> will be defined as a <code>java.lang.Object</code>, but there is another important difference. In this case, the bean factory will invoke the <a href="http://docs.mockito.googlecode.com/hg/org/mockito/Mockito.html#mock(java.lang.Class)">Mockito.mock(Class&lt;T&gt; classToMock)</a> method with <code>SomeDependency</code> as parameter causing the <code>someDependencyMock</code> bean to be created and subsequently stored in the application context. Later, the <code>someClass</code> bean is created and the dependency can obtained from the application context when requested by the bean factory and the wiring of the beans will succeed. However, making sure that the order of the bean declarations in the XML is always correct may neither be simple nor obvious, and it will get increasingly more difficult the more beans you add to the configuration.</p>
<h2>Disclaimer</h2>
<p>As stated in the in the first paragraph, I would only consider this solution for <i>integration</i> tests because of performance reasons. The application context itself adds some overhead, but the big performance hit is to create and wire all beans that are associated with it. When writing <i>unit</i> tests there is no need for this, so you could revert to constructor or setter dependency injection, Spring's <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/test/util/ReflectionTestUtils.html#setField%28java.lang.Object,%20java.lang.String,%20java.lang.Object%29">ReflectionTestUtils.setField()</a>, PowerMock's <a href="http://powermock.googlecode.com/svn/docs/powermock-1.4.10/apidocs/org/powermock/reflect/Whitebox.html#setInternalState%28java.lang.Object,%20java.lang.Class,%20java.lang.Object%29">Whitebox.setInternalState()</a>, Mockito's <a href="http://docs.mockito.googlecode.com/hg/org/mockito/InjectMocks.html">@InjectMocks</a> or similar techniques.</p>
<h2>Acknowledgements</h2>
<p>Thanks to <a href="http://stackoverflow.com/users/97641/wilhelm-kleu">Wilhelm Kleu</a> at stack overflow for <a href="http://stackoverflow.com/questions/6340007/autowiring-of-beans-generated-by-easymock-factory-method/6340391#6340391">suggesting</a> the solution and to <a href="http://blog.jayway.com/author/mattiasarthursson/">Mattias Hellborg Arthursson</a> for valuable discussions.</p>
<h2>Dependencies</h2>
<ul>
<li>Spring 3.0.6</li>
<li>Mockito 1.8.5</li>
<li>jUnit 4.10</li>
<li>EasyMock 3.1</li>
</ul>
<h2>References</h2>
<ul>
<li><a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-factory-class-static-factory-method">Spring Reference Manual - Static Factory Method</a></li>
<li><a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-factory-extension-factorybean">Spring Reference Manual - FactoryBean</a></li>
<li><a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/testing.html#integration-testing-annotations">Spring Reference Manual - Integration Testing</a></li>
<li><a href="http://docs.mockito.googlecode.com/hg/org/mockito/Mockito.html">Mockito</a></li>
<li><a href="http://easymock.org/EasyMock3_1_Documentation.html">EasyMock</a></li>
</ul>
<p>Next post: <a href="http://blog.jayway.com/2011/12/12/spring-integration-tests-part-ii-using-mock-objects/">Spring Integration Tests, Part II, Using Mock Objects</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/11/30/spring-integration-tests-part-i-creating-mock-objects/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>IntelliJ IDEA performance improvement</title>
		<link>http://blog.jayway.com/2011/09/26/intellij-idea-performance-improvement/</link>
		<comments>http://blog.jayway.com/2011/09/26/intellij-idea-performance-improvement/#comments</comments>
		<pubDate>Mon, 26 Sep 2011 17:26:58 +0000</pubDate>
		<dc:creator>Mattias Severson</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[home directory]]></category>
		<category><![CDATA[idea]]></category>
		<category><![CDATA[intellij]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[tools]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=9443</guid>
		<description><![CDATA[Working as a consultant, it is not unusual that I am referred to customer specific software environment with regard to computers, operating systems, networks and other configurations. However, since I work with Java, most tools are available online and they can easily be downloaded and installed on different platforms. IntelliJ IDEA is no exception, but [...]]]></description>
			<content:encoded><![CDATA[<p>Working as a consultant, it is not unusual that I am referred to customer specific software environment with regard to computers, operating systems, networks and other configurations. However, since I work with Java, most tools are available online and they can easily be downloaded and installed on different platforms. IntelliJ IDEA is no exception, but before you start coding you should make sure you know how the <a href="http://en.wikipedia.org/wiki/Home_directory">home directory</a> of your computer is setup and configure IntelliJ IDEA accordingly. From the <a href="http://devnet.jetbrains.net/docs/DOC-181">documentation</a>:</p>
<blockquote><p>
In some environments user's home directory is located on the mapped network drive which in unacceptable for IntelliJ IDEA. You'll notice the huge performance degradation.
</p></blockquote>
<h2>What is the problem?</h2>
<p>There are some good motives for keeping the home directory mounted to a network folder rather than on the local hard drive. For example, all user settings and user documents can be backed up centrally, and the user could potentially log in to any computer and have the same user environment. However, there are also some drawbacks. Depending on how the home folder is configured, there will either be a remote network call for each file access, or the file changes will be executed as a batch job at scheduled intervals or specific events such as logging off the computer.</p>
<p>The second part of the problem is that IntelliJ IDEA produces quite a lot of data, typically several hundred megabytes, besides the anticipated artifacts. The data consists of IDE plugins, configuration files, log files, but the vast majority is internal cache files. By default, the data is written to a hidden <i>.IntelliJIdea10/</i> folder in your home directory.</p>
<p>If you combine these two factors, the performance will suffer. How much depends on the bandwidth of your network, something that I became painfully aware of when I logged in remotely to the customer's network via a slow VPN connection.</p>
<h2>Solution</h2>
<p>Avoid network overhead by configuring IntelliJ IDEA to cache data on your local computer instead of in your home folder. A recent customer used Windows XP as their working environment, the instructions below are based on that experience.</p>
<ol>
<li>
Create a new directory on a <i>local</i> harddrive that IntelliJ IDEA can use, e.g. <i>C:/.IntelliJIdea10/</i>. Hint, you cannot create a library starting with a "." from Windows Explorer, you have to use the <code>mkdir</code> command from the terminal.
</li>
<li>
Locate the <i>idea.properties</i> file in the <i>bin</i> directory in IntelliJ IDEA's installation directory. The default location is <i>C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 10.5.1\bin</i>.
</li>
<li>
Change the relevant properties to point to the recently created directory:</p>
<pre class="brush:xml">
# path to IDEA config folder. Make sure you're using forward slashes
idea.config.path=C:/.IntelliJIdea10/config

# path to IDEA system folder. Make sure you're using forward slashes
idea.system.path=C:/.IntelliJIdea10/system

# path to user installed plugins folder. Make sure you're using forward slashes
idea.plugins.path=C:/.IntelliJIdea10/config/plugins
</pre>
</li>
</ol>
<h2>Considerations</h2>
<p>Consider <i>not</i> to change the <i>idea.config.path</i> property if you are using several different computers and you would like to have the same configuration on all machines. Additionally, if you are using IntelliJ IDEA Ultimate, i.e. the commercial version of the tool, you should also make a cautious decision about whether or not to keep this property unchanged, because the license file is stored in the denoted directory. On the other hand, if you always use the same computer you might as well change this property together with the other properties, so that all IntelliJ IDEA files are stored in the same location.</p>
<h2>References</h2>
<ul>
<li>IDEA files location: <a href="http://devnet.jetbrains.net/docs/DOC-181">http://devnet.jetbrains.net/docs/DOC-181</a></li>
<li>IDEA license key: <a href="http://devnet.jetbrains.net/docs/DOC-200">http://devnet.jetbrains.net/docs/DOC-200</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/09/26/intellij-idea-performance-improvement/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Dynamic FTP Client using Apache Camel and Spring</title>
		<link>http://blog.jayway.com/2010/08/12/dynamic-ftp-client-using-apache-camel-and-spring/</link>
		<comments>http://blog.jayway.com/2010/08/12/dynamic-ftp-client-using-apache-camel-and-spring/#comments</comments>
		<pubDate>Thu, 12 Aug 2010 16:48:45 +0000</pubDate>
		<dc:creator>Mattias Severson</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[apache]]></category>
		<category><![CDATA[camel]]></category>
		<category><![CDATA[FTP]]></category>
		<category><![CDATA[spring]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=5743</guid>
		<description><![CDATA[I was recently asked to develop an FTP client that could transmit files to various FTP servers as a part of a delivery system in a Java enterprise application. The requirements dictated a flexible implementation: Three different FTP protocols should be supported, namely FTP, FTPS and SFTP It should be possible to transmit different files [...]]]></description>
			<content:encoded><![CDATA[<p>I was recently asked to develop an FTP client that could transmit files to various FTP servers as a part of a delivery system in a Java enterprise application. The requirements dictated a flexible implementation:</p>
<ul>
<li>Three different FTP protocols should be supported, namely <a href="#FTP">FTP</a>, <a href="#FTPS">FTPS</a> and <a href="#SFTP">SFTP</a></li>
<li>It should be possible to transmit different files to several different servers</li>
<li>The files to be sent were generated in runtime, they had different file names and were stored in different directories</li>
</ul>
<p>Basically, I should implement the following interface:</p>
<h4>FtpSender.java</h4>
<p><a name="FtpSender"></a></p>
<pre class="brush:java">
public interface FtpSender {

    /**
     * Uses the {@code ftpProperties} to transmit the provided {@code file} to a remote server
     *
     * @param ftpProperties The FTP properties of the remote server
     * @param file The file to transmit
     */
    void sendFile(FtpProperties ftpProperties, File file);
}
</pre>
<p>where the FtpProperties was another interface:</p>
<h4>FtpProperties.java</h4>
<pre class="brush:java">
public interface FtpProperties {

    /**
     * Gets the protocol
     * @return One of {@code ftp}, {@code ftps} or {@code sftp}
     */
    String getProtocol();

    /**
     * Gets the user name
     * @return The name of the user
     */
    String getUserName();

    /**
     * Gets the password
     * @return The password
     */
    String getPassword();

    /**
     * Gets the FTP host
     * @return The FTP host
     */
    String getHost();

    /**
     * Gets the name of the directory on the server where the file will be transferred
     * @return The name of the remote directory
     */
    String getRemoteDirectory();

    /**
     * Gets the passive mode, e.g. if the server is behind a firewall
     * @return whether or not passive mode should be used
     */
    boolean getPassiveMode();
}
</pre>
<p>Rather than implementing the entire FTP client from scratch, I investigated the capabilities of existing frameworks. Most solutions recommend using an existing FTP framework such as <a href="http://commons.apache.org/net/">Apache Commons / Jakarta Commons Net</a> for FTP and FTPS and then wrap it in a SSH layer like <a href="http://www.jcraft.com/jsch/">Jsch / Java Secure Channel</a> for SFTP. However, soon I discovered <a href="http://camel.apache.org/">Apache Camel</a>, "a powerful open source integration framework based on known Enterprise Integration Patterns with powerful Bean Integration" (their words). They support a various range of <a href="http://camel.apache.org/components.html">components</a>, anything from XQuery and Atom to XSLT and SQL, just to name a few. To my luck, they also support all three FTP protocols that I needed. </p>
<h2>Fundamentals</h2>
<p>What does the <a href="http://camel.apache.org/ftp2.html">Camel FTP</a> API look like? In its basic form it is a little more than a one-liner:</p>
<h4>FtpRouteBuilder.java</h4>
<p><a name="FtpRouteBuilder"></a></p>
<pre class="brush:java">
public class FtpRouteBuilder extends RouteBuilder {

    @Override
    public void configure() throws Exception {
        from("file://localDirectory").to("ftp://user@host.com/remoteDirectory?password=secret&passiveMode=true");
    }
}
</pre>
<p>So what is going on here? The <a href="http://camel.apache.org/routebuilder.html">RouteBuilder</a> is one of Camel's core classes that defines the Camel specific <a href="http://camel.apache.org/dsl.html">DSL</a>. In this example, a <a href="http://camel.apache.org/routes.html">Route</a> from the <code>localDirectory</code> to a <code>remoteDirectory</code> over FTP with the provided credentials has been created. As can be seen, it is easy to create and configure different endpoints using <code>String</code> URIs. It should also be mentioned that it is possible to fetch files from the remote FTP server by swapping the URIs in the <code>to</code> and <code>from</code> methods.</p>
<p>A few more lines are needed to activate the route:</p>
<pre class="brush:java">
public static void main(String[]args) throws Exception {
    CamelContext camelContext = new DefaultCamelContext();
    try {
        camelContext.addRoutes(new FtpRouteBuilder());
        camelContext.start();
        // do other stuff...
    }
    finally {
        camelContext.stop();
    }
}
</pre>
<p>A <a href="http://camel.apache.org/camelcontext.html">CamelContext</a> is created for managing the route. The previously described <a href="#FtpRouteBuilder">FtpRouteBuilder</a> is instantiated and added to the camelContext which is subsequently started. As a consequence, any file that is placed in the "localDirectory" folder will be automatically transferred to the "remoteDirectory" of the FTP server while the program is running. </p>
<h2>Adding Configurability</h2>
<p>The requirement of supporting different FTP protocols is solved by changing the URI from <code>ftp://</code> to <code>ftps://</code> or <code>sftp://</code> respectively. It is just as easy to fulfill the second requirement of multiple server support by changing the host, user, port and other parameters of the URI. Likewise, additional settings may be configured by adding more options if needed, see the <a href="http://camel.apache.org/ftp2.html">Camel FTP</a> documentation.</p>
<h2>Adding Dynamism</h2>
<p>The last challenge was to add the dynamic support of selecting source files and destination servers during runtime. The easiest solution is to use another of Camel's base classes, the <a href="http://camel.apache.org/producertemplate.html">ProducerTemplate</a>. Again, the solution is a one-liner:</p>
<pre class="brush:java">
producerTemplate.sendBodyAndHeader("ftp://user@host.com/remoteDirectory?password=secret", file, Exchange.FILE_NAME, file.getName());
</pre>
<p>The <code>sendBodyAndHeader()</code> method name reveals a glimpse of Camel's underlying messaging architecture. The parameters used are the destination URI with additional options, the message body, i.e. the <code>File</code> to be sent, a message header parameter that identifies the last parameter as the name of the file it will have on the remote server once it has been transferred.</p>
<h2>Spring Integration</h2>
<p>With some refactoring and a little Spring magic we have all the bits and pieces needed to implement the previously defined <a href="#FtpSender">FtpSender</a> interface:</p>
<h4>FtpSenderImpl.java</h4>
<pre class="brush:java">
@Service
class FtpSenderImpl implements FtpSender {

    /** Camel URI, format is ftp://user@host/fileName?password=secret&passiveMode=true */
    private static final String CAMEL_FTP_PATTERN = "{0}://{1}@{2}/{3}?password={4}&passiveMode={5}";

    private final ProducerTemplate producerTemplate;

    /**
      * Constructor
      * @param producerTemplate The producer template to be be used
      */
    @Autowired
    FtpSenderImpl(ProducerTemplate producerTemplate) {
        this.producerTemplate = producerTemplate;
    }

    @Override
    public void sendFile(FtpProperties ftpProperties, File file) throws RuntimeException {
        producerTemplate.sendBodyAndHeader(createFtpUri(ftpProperties), file, Exchange.FILE_NAME, fileName);
    }

    /**
      * Creates a Camel FTP URI based on the provided FTP properties
      * @param ftpProperties The properties to be used
      */
    private String createFtpUri(FtpProperties ftpProperties) {
        return MessageFormat.format(CAMEL_FTP_PATTERN,
                ftpProperties.getProtocol(),
                ftpProperties.getUserName(),
                ftpProperties.getHost(),
                ftpProperties.getRemoteDirectory(),
                ftpProperties.getPassword(),
                ftpProperties.getPassiveMode());
    }
}
</pre>
<p>Using the <a href="http://camel.apache.org/spring.html">Camel namespace</a>, the required plumbing work is delegated to the Spring application config:</p>
<h4>spring-config.xml</h4>
<pre class="brush:xml">
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:camel="http://camel.apache.org/schema/spring"
       xsi:schemaLocation="
		http://www.springframework.org/schema/beans   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
		http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd"&gt;

    &lt;!-- Let Spring create the Camel context and the Camel template, including lifecycle management such as starting and stopping them --&gt;
    &lt;camel:camelContext id="camelContext"&gt;
        &lt;camel:template id="camelTemplate" /&gt;
    &lt;/camel:camelContext&gt;

    &lt;!-- Use Spring component scan to find the FtpSenderImpl implementation --&gt;
    &lt;context:component-scan base-package="com.jayway.ftp" /&gt;

&lt;/beans&gt;
</pre>
<h2>Conclusions</h2>
<p>Camel and Spring provide a simple, yet configurable, way of implementing a dynamic FTP client.</p>
<h2>Acknowledgments</h2>
<p>Thanks to Claus Ibsen and other members of the <a href="http://camel.apache.org/discussion-forums.html">Apache Camel Forums</a> for providing valuable and rapid support.</p>
<h2>Glossary</h2>
<ul>
<li><a name="FTP"></a><code>FTP</code> File Transfer Protocol</li>
<li><a name="FTPS"></a><code>FTPS</code> FTP Secure is an extension to FTP that adds support for the TLS, Transport Layer Security, and the SSL, Secure Sockets Layer, cryptographic protocols</li>
<li><a name="SFTP"></a><code>SFTP</code> SSH File Transfer Protocol, i.e. FTP over the Secure Shell protocol</li>
</ul>
<h2>References</h2>
<p><a href="http://camel.apache.org/maven/camel-2.2.0/camel-core/apidocs/index.html">Camel API</a><br />
<a href="http://camel.apache.org/components.html">Camel Components</a><br />
<a href="http://camel.apache.org/ftp2.html">Camel FTP</a><br />
<a href="http://camel.apache.org/producertemplate.html">Camel ProducerTemplate</a><br />
<a href="http://camel.apache.org/spring.html">Camel Spring</a><br />
<a href="http://camel.apache.org/why-does-camel-use-too-many-threads-with-producertemplate.html">Camel ProducerTemplate and Spring</a><br />
<a href="http://camel.apache.org/enterprise-integration-patterns.html">Camel Enterprise Integration Patterns</a><br />
<a href="http://camel.apache.org/discussion-forums.html">Camel Forums</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/08/12/dynamic-ftp-client-using-apache-camel-and-spring/feed/</wfw:commentRss>
		<slash:comments>19</slash:comments>
		</item>
		<item>
		<title>Architectural Enforcement with Aid of AspectJ</title>
		<link>http://blog.jayway.com/2010/03/28/architectural-enforcement-with-aid-of-aspectj/</link>
		<comments>http://blog.jayway.com/2010/03/28/architectural-enforcement-with-aid-of-aspectj/#comments</comments>
		<pubDate>Sun, 28 Mar 2010 17:50:57 +0000</pubDate>
		<dc:creator>Mattias Severson</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[aop]]></category>
		<category><![CDATA[aspectj]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=4991</guid>
		<description><![CDATA[After working some time within the software industry, you get a feeling for good software architecture. Or, to be more honest, you get a creeping feeling when the architecture is really bad. That is when the code is tangled like a Gordian knot. After some futile refactoring attempts, you consult the software architect at your [...]]]></description>
			<content:encoded><![CDATA[<p>After working some time within the software industry, you get a feeling for good software architecture. Or, to be more honest, you get a creeping feeling when the architecture is really bad. That is when the code is tangled like a Gordian knot. After some futile refactoring attempts, you consult the software architect at your company and you will be given a design document stating the architectural principles that should be obeyed during software development. It is a nifty piece of paper and you can tell by looking at it that someone has spent a lot of time working out how the software should be structured. The bad news is that it has little resemblance of the current state of the code base. </p>
<h2>Recipe</h2>
<p>So how can you shape up the code? Yet better, how can you prevent that the code turns into spaghetti in the first place? One way of looking at architectural requirements is that they are crosscutting concerns that are scattered throughout the software. As such, they can be implemented and enforced by using AOP, <a href="http://en.wikipedia.org/wiki/Aspect-oriented_programming">aspect-oriented programming</a>. The recipe is pretty straight forward:</p>
<ol>
<li>Implement a pointcut that finds the violations of your architecture.</li>
<li>Implement an advice that notifies you about the violations.</li>
<li>Wrap the pointcut and the advice into an aspect.</li>
<li>Refactor your code and exercise your aspect until all architectural violations have been removed.</li>
</ol>
<h2>Example</h2>
<p>This recipe of using aspects as a way of enforcing architectural rules can be applied in any kind of project, for example to enforce the MVC pattern, to separate one domain from another in a DDD project and so on. In this particular example, the application is based on a three layer architecture. The top layer being the GUI layer, the middle layer is the service layer and then there is the DAO layer in the bottom. Each layer has a separate package, as stated below:</p>
<table width="90%">
<colgroup>
<col width="2*"/>
</colgroup>
<colgroup>
<col width="1*"/>
</colgroup>
<tbody>
<tr>
<td>
<h4>SomeGui.java</h4>
<pre class="brush:java">
package com.jayway.application.gui;

/** Simplistic GUI */
public interface SomeGui {

    /** Renders the GUI */
    void render();
}
</pre>
<h4>SomeService.java</h4>
<pre class="brush:java">
package com.jayway.application.service;

/** Simplistic Service */
public interface SomeService {

    /** Executes some service */
    void service();
}
</pre>
<h4>SomeDao.java</h4>
<pre class="brush:java">
package com.jayway.application.dao;

/** Simplistic DAO */
public interface SomeDao {

    /**
     * Finds something in the DAO
     * @return some data
     */
    public Object find();
}
</pre>
</td>
<td>
<img src="http://blog.jayway.com/wordpress/wp-content/uploads/2010/03/architectural-enforcement.png" alt="Architectural Enforcement" class="alignright size-full wp-image-5041" />
</td>
</tr>
</tbody>
</table>
<h3>Architectural Rules</h3>
<p>Four architectural rules have been defined:</p>
<ol>
<li>The GUI layer must not access the DAO layer</li>
<li>The Service layer must not access the GUI layer</li>
<li>The DAO layer must not access the Service layer</li>
<li>The DAO layer must not access the GUI layer</li>
</ol>
<p>These rules are the candidates for defining the pointcuts that should be implemented. An example of code that would violate the first rule is:</p>
<h4>BadGuiImpl.java</h4>
<pre class="brush:java">
/**
 * Bad GUI implementation that violates the architectural rule
 * because it calls a method in the DAO layer
 */
public class BadGuiImpl implements SomeGui {

    private SomeService someService;
    private SomeDao someDao;

    @Override
    public void render() {
        // it is ok to use the service...
        someService.service();

        // ...but it is not ok to call the DAO directly
        someDao.find();    

        // more rendering
    }
}
</pre>
<p>Using <a href="http://eclipse.org/aspectj/">AspectJ</a>, two pointcuts have been implemented to trap the violation. Additionally, AspectJ also provides the <code>@DeclareError</code> annotation that can be used for the advice implementation. Finally, an aspect that comprises the pointcuts and the advice has been created:</p>
<h4> ArchitecturalEnforcement.java</h4>
<pre class="brush:java">
/**
 * The aspect that is responsible for architecture enforcement:
 * The GUI layer must not access the DAO layer.
 */
@Aspect
public class ArchitecturalEnforcement {

    /** Pointcut for finding join points inside the GUI layer */
    @Pointcut("within(*..*gui..*)")
    public void withinGui() {}

    /** Pointcut for finding method calls to the DAO layer */
    @Pointcut("call(* *..*.dao..*(..))")
    public void callDao(){}

    /** Advice that defines an error when a GUI method calls a method in the DAO layer */
    @DeclareError("withinGui() && callDao()")
    private static final String GUI_MUST_NOT_USE_DAO = "GUI must not access DAO";
}
</pre>
<h3>Exercise the Aspect</h3>
<p>How should you use your aspects to enforce the architecture? Since we now have the tools to automate the architectural review, you should use them frequently. AspectJ has support for compile time weaving which means that the advices can be woven into their corresponding join points during source code compilation. The <a href="http://mojo.codehaus.org/aspectj-maven-plugin/">aspectj-maven-plugin</a> can do it for you:</p>
<h4>pom.xml</h4>
<pre class="brush:xml">
&lt;dependencies&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.aspectj&lt;/groupId&gt;
        &lt;artifactId&gt;aspectjrt&lt;/artifactId&gt;
        &lt;version&gt;1.6.7&lt;/version&gt;
    &lt;/dependency&gt;
&lt;/dependencies&gt;
    ...
&lt;build&gt;
    &lt;plugins&gt;
        &lt;plugin&gt;
            &lt;groupId&gt;org.codehaus.mojo&lt;/groupId&gt;
            &lt;artifactId&gt;aspectj-maven-plugin&lt;/artifactId&gt;
            &lt;version&gt;1.3&lt;/version&gt;
            &lt;configuration&gt;
                &lt;complianceLevel&gt;1.6&lt;/complianceLevel&gt;
            &lt;/configuration&gt;
            &lt;executions&gt;
                &lt;execution&gt;
                    &lt;goals&gt;
                        &lt;goal&gt;compile&lt;/goal&gt;   &lt;!-- Weaves the main classes --&gt;
                        &lt;goal&gt;test-compile&lt;/goal&gt;   &lt;!-- Weaves the test classes --&gt;
                    &lt;/goals&gt;
                &lt;/execution&gt;
            &lt;/executions&gt;
        &lt;/plugin&gt;
    &lt;/plugins&gt;
&lt;/build&gt;
</pre>
<h3>Result</h3>
<p>If you have put everything together correctly, you will find that you will get a compile time error when you attempt to execute <code>mvn compile</code>:</p>
<pre class="brush:shell">
[[INFO] [aspectj:compile {execution: default}]
[ERROR] "GUI must not access DAO"
[INFO] ------------------------------------------------------------------------
[ERROR] BUILD ERROR
[INFO] ------------------------------------------------------------------------
[INFO] Compiler errors:
error at someDao.find();
^^^^^^^^^^^^^^
/home/mattias/architectural-enforcement/src/main/java/com/jayway/application/gui/BadGuiImpl.java:20:0::0 "GUI must not access DAO"
	see also: /home/mattias/architectural-enforcement/src/main/java/com/jayway/application/aspects/ArchitecturalEnforcement.java:1::0
</pre>
<p>You can also see the error in your Eclipse IDE if you are using the <a href="http://www.eclipse.org/ajdt/">AJDT - AspectJ Development Tools</a> plugin:<br />
<img src="http://blog.jayway.com/wordpress/wp-content/uploads/2010/04/eclipse-screenshot.png" alt="Eclipse Screenshot" class="alignright size-full wp-image-5357" /></p>
<p>Notably, the implementation above was just one of the stated rules. The implementation of all four rules together with some examples that break them and the Maven pom file are available for <a href="http://blog.jayway.com/wordpress/wp-content/uploads/2010/04/architectural-enforcement.zip">download</a> for your convenience.</p>
<h2>Considerations</h2>
<p>There are some things that you may want to consider before introducing aspects as a tool for automated architectural enforcement:</p>
<ul>
<li>
<h3>Error or Warning</h3>
<p> A compile time error is a powerful tool that prevents the developer to commit any code that does not conform to the architectural rules (presumed, of course, that the code is actually compiled before being checked in). A less brutal way of introducing aspects as a part of architectural review is to use the <code>@DeclareWarning</code> annotation rather than the <code>@DeclareError</code> that was used in the example. Consequently, any architectural offenders will be punished with a compiler warning rather than a compiler error.</li>
<li>
<h3>Performance</h3>
<p> The compile time will increase when you add more architectural rules that should be obeyed, that is when you add more pointcuts. Likewise, the compile time will also increase when your code base grows, because of the increasing number of join points in the code. By limiting the <code>aspectj-maven-plugin</code> to certain maven profiles, the developers only have to verify that their particular module conforms to the rules. Alternatively, all modules can be verified by the integration server during nightly builds. The drawback is that the advantage of having the architecture enforced <i>before</i> the code is committed to the version control system will be lost.
</li>
<li>
<h3>Limitation</h3>
<p> The aspect above can only trap architectural violations when a method is being <i>called</i>. Regrettably, any <i>unused declaration</i> that would violate the architecture will pass unnoticed:</p>
<h4>AnotherBadGuiImpl.java</h4>
<pre class="brush:java">
package com.jayway.application.gui;

import com.jayway.application.dao.SomeDao;

/**
 * Another bad GUI implementation that violates the architectural rule
 * because it has references to the DAO layer.
 * However, these errors will remain undetected by AspectJ.
 */
public class AnotherBadGuiImpl implements SomeGui {

    /** Unused DAO reference */
    private SomeDao someDao;

    /**
     * Setter method that for some obscure reason adds a DAO to the GUI
     * @param someDao A DAO reference that is not found by the pointcut
     */
    public void setDao(SomeDao someDao) {
        this.someDao = someDao;
    }

    @Override
    public void render() {
        // valid gui rendering that does not use the dao reference
    }
}
</pre>
<p>One solution is to create another pointcut, such as <code>@Pointcut("set(*..*.*dao*..* *)")</code>, that traps the assignment of the <code>someDao</code> member variable.
</li>
</ul>
<h2>Wrap Up</h2>
<p>Education of the developers and repeated manual code reviews have been the traditional ways of improving software architecture. Unfortunately, it is not good enough. It is always a good idea to have skilled employees, but even experts do make mistakes. After all, people that manually review code are only humans, which implies that the reviews are resource demanding, yet error prone. With the powerful tools of today's IDEs it is very easy to do refactoring hastily and soon the code starts to degrade. With a proper implementation, AspectJ offers one way to automate architectural enforcement, hereby preventing architectural drift.</p>
<h2>Edit</h2>
<p>2010-04-16: Added screenshot of AJDT plugin and an example of how the "set" pointcut can be used.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/03/28/architectural-enforcement-with-aid-of-aspectj/feed/</wfw:commentRss>
		<slash:comments>17</slash:comments>
		</item>
		<item>
		<title>Getting started with JavaME jUnit testing</title>
		<link>http://blog.jayway.com/2009/03/22/getting-started-with-javame-junit-testing/</link>
		<comments>http://blog.jayway.com/2009/03/22/getting-started-with-javame-junit-testing/#comments</comments>
		<pubDate>Sun, 22 Mar 2009 14:36:36 +0000</pubDate>
		<dc:creator>Mattias Severson</dc:creator>
				<category><![CDATA[Embedded]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[java me]]></category>
		<category><![CDATA[junit]]></category>
		<category><![CDATA[mock]]></category>
		<category><![CDATA[powermock]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=1191</guid>
		<description><![CDATA[Introduction Unit testing is a very powerful tool that should be included in every developer's toolbox. Unfortunately, this has not always been the case, especially not among MIDlet developers. One reason is that JavaME projects usually are small (compared to Java SE projects), which implies that manual testing could be enough. However, as soon as [...]]]></description>
			<content:encoded><![CDATA[<h3>Introduction</h3>
<p>Unit testing is a very powerful tool that should be included in every developer's toolbox. Unfortunately, this has not always been the case, especially not among MIDlet developers. One reason is that JavaME projects usually are small (compared to Java SE projects), which implies that manual testing could be enough. However, as soon as you start developing production code you really should consider to automate your tests by developing your own test suite. </p>
<p>Some of you may have played around with <a href="http://sourceforge.net/projects/jmunit">JMUnit</a> project. It is a nice framework that allows you to write tests that can be transferred to your phone or emulator and you will see the test result on the display. Alternatively, the tests can be executed by Ant. Still, there are some limitations that you cannot bypass:</p>
<ul>
<li>Because of CLDC's lack of reflection, you cannot benefit from the powers of <a href="http://www.junit.org/">jUnit 4.x</a>.</li>
<li>You cannot create mock objects. This means that if a class has dependencies to other classes you will perform an integration test rather than a <i>unit</i> test.</li>
<li>The turn around time for test, debug and retest, is significantly larger compared to Java SE unit testing, especially if you are executing the test on the phone.</li>
</ul>
<p>No offence to the JMUnit guys, they are restricted by the limitations of the CLDC VM and the fact that you need a target device (a phone or an emulator) to run the tests on. But maybe there is a workaround to solve these problems? With some tricks, it is possible to unit test your JavaME code in the same way as you would unit test your Java SE code. In other words, you can execute the tests <i>on the PC side without deploying the tests to an emulator or a phone</i>. </p>
<h3>PowerMock</h3>
<p>One part of the solution is to mock any platform dependencies. Previously, it was an awkward job to do, but the introduction of  <a href="http://code.google.com/p/powermock/">PowerMock</a> allows us to mock the many static methods in MIDP and CLDC. The easiest way to get started with powermock is to download the <a href="http://code.google.com/p/powermock/downloads/list">powermock-1.2-with-dependencies.zip</a>. In another <a href="http://blog.jayway.com/2009/03/22/how-to-mock-midp-recordstore/">post</a> I have explained how PowerMock can be used to mock the RecordStore in MIDP.</p>
<h3>Project configuration</h3>
<p>If you are using Eclipse, you need two projects, one for your phone application and the other your test code. This is because different projects can have different java compiler settings.</p>
<ul>
<li>Create a <i>MIDlet</i> project. This is your phone application. Make sure that the "Java Compiler" compliance level is "1.3".</li>
<li>Create a <i>Java</i> project. This is the test project where you will write your tests. Make sure that the "Java Compiler" compliance level is set to "1.6" (or to whatever JDK version you have installed).
<ul>
<li>Add the midlet project you just created to "Required projects" in the "Java Build Path" setting.</li>
<li>Add the PowerMock jar files and their dependencies to "Libraries" in the "Java Build Path" setting.</li>
</ul>
</ul>
<p>In the MIDlet project, you write your application code and in the java test project you write your java jUnit tests. Normal package protection rules apply, so you should consider to reuse the package name from the class in the midlet project you would like to test when you are writing the test class in the java project.</p>
<h3>Automation</h3>
<p>Naturally, it is possible to automate the test by using build tools. Here is an example using of an Ant build.xml file:</p>
<pre class="xml">&nbsp;
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;?xml</span> <span style="color: #000066;">version</span>=<span style="color: #ff0000;">&quot;1.0&quot;</span> <span style="color: #000066;">encoding</span>=<span style="color: #ff0000;">&quot;UTF-8&quot;</span><span style="font-weight: bold; color: black;">?&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;project</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;Example&quot;</span> <span style="color: #000066;">default</span>=<span style="color: #ff0000;">&quot;test&quot;</span> <span style="color: #000066;">basedir</span>=<span style="color: #ff0000;">&quot;.&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;midlet.project.home&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;C:/your_workspace/MidletProject&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;test.project.home&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;C:/your_workspace/MidletProjectTest&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;powermock.home&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;C:/your_path/powermock-1.2&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;wtk.home&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;C:/WTK2.5.2&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;src.dir&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;${midlet.project.home}/src&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;test.src.dir&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;${test.project.home}/src&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;bin.dir&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;classes&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;test.bin.dir&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;test-classes&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;test.result.dir&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;test-result&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;path</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;midlet.dependencies&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;fileset</span> <span style="color: #000066;">dir</span>=<span style="color: #ff0000;">&quot;${wtk.home}/lib&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
			<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;include</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;*.jar&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/fileset<span style="font-weight: bold; color: black;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/path<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;path</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;test.dependencies&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;pathelement</span> <span style="color: #000066;">location</span>=<span style="color: #ff0000;">&quot;${bin.dir}&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;path</span> <span style="color: #000066;">refid</span>=<span style="color: #ff0000;">&quot;midlet.dependencies&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;fileset</span> <span style="color: #000066;">dir</span>=<span style="color: #ff0000;">&quot;${powermock.home}&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/path<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;target</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;clean&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;delete</span> <span style="color: #000066;">dir</span>=<span style="color: #ff0000;">&quot;${bin.dir}&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;delete</span> <span style="color: #000066;">dir</span>=<span style="color: #ff0000;">&quot;${test.bin.dir}&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;delete</span> <span style="color: #000066;">dir</span>=<span style="color: #ff0000;">&quot;${test.result.dir}&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/target<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;target</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;compile&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;mkdir</span> <span style="color: #000066;">dir</span>=<span style="color: #ff0000;">&quot;${bin.dir}&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;javac</span> <span style="color: #000066;">srcdir</span>=<span style="color: #ff0000;">&quot;${src.dir}&quot;</span>
			<span style="color: #000066;">destdir</span>=<span style="color: #ff0000;">&quot;${bin.dir}&quot;</span>
			<span style="color: #000066;">source</span>=<span style="color: #ff0000;">&quot;1.3&quot;</span>
			<span style="color: #000066;">target</span>=<span style="color: #ff0000;">&quot;1.1&quot;</span>
			<span style="color: #000066;">classpathref</span>=<span style="color: #ff0000;">&quot;midlet.dependencies&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/target<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;target</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;compile-tests&quot;</span> <span style="color: #000066;">depends</span>=<span style="color: #ff0000;">&quot;compile&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;mkdir</span> <span style="color: #000066;">dir</span>=<span style="color: #ff0000;">&quot;${test.bin.dir}&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;javac</span> <span style="color: #000066;">srcdir</span>=<span style="color: #ff0000;">&quot;${test.src.dir}&quot;</span>
			<span style="color: #000066;">destdir</span>=<span style="color: #ff0000;">&quot;${test.bin.dir}&quot;</span>
			<span style="color: #000066;">classpathref</span>=<span style="color: #ff0000;">&quot;test.dependencies&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/target<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;target</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;test&quot;</span> <span style="color: #000066;">depends</span>=<span style="color: #ff0000;">&quot;clean, compile-tests&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;mkdir</span> <span style="color: #000066;">dir</span>=<span style="color: #ff0000;">&quot;${test.result.dir}&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;junit</span> <span style="color: #000066;">printsummary</span>=<span style="color: #ff0000;">&quot;yes&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
			<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;classpath</span> <span style="color: #000066;">refid</span>=<span style="color: #ff0000;">&quot;test.dependencies&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
			<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;classpath</span> <span style="color: #000066;">path</span>=<span style="color: #ff0000;">&quot;${test.bin.dir}&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;formatter</span> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">&quot;plain&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
			<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;batchtest</span> <span style="color: #000066;">fork</span>=<span style="color: #ff0000;">&quot;yes&quot;</span> <span style="color: #000066;">todir</span>=<span style="color: #ff0000;">&quot;${test.result.dir}&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
				<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;fileset</span> <span style="color: #000066;">dir</span>=<span style="color: #ff0000;">&quot;${test.src.dir}&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
			<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/batchtest<span style="font-weight: bold; color: black;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/junit<span style="font-weight: bold; color: black;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/target<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/project<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;</pre>
<p>Now your project configuration is setup and you can test your MIDlet code in the same way as you would test your Java SE code. </p>
<h3>What's next?</h3>
<p>If you are a dedicated MIDlet developer you would probably like to add more build targets later on to preverify, obfuscate, sign, package and deploy your MIDlet. </p>
<p>You should also consider using a continuous integration server together with your version control system and configure it to run your test suite whenever the code has been changed. Depending on the server you choose, you may also find that it may be used to present result from static code analysis tools, code coverage, code metrics and so on.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/03/22/getting-started-with-javame-junit-testing/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to mock MIDP RecordStore</title>
		<link>http://blog.jayway.com/2009/03/22/how-to-mock-midp-recordstore/</link>
		<comments>http://blog.jayway.com/2009/03/22/how-to-mock-midp-recordstore/#comments</comments>
		<pubDate>Sun, 22 Mar 2009 14:32:32 +0000</pubDate>
		<dc:creator>Mattias Severson</dc:creator>
				<category><![CDATA[Embedded]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[java me]]></category>
		<category><![CDATA[junit]]></category>
		<category><![CDATA[mock]]></category>
		<category><![CDATA[powermock]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=1229</guid>
		<description><![CDATA[The challenge PowerMock is a mocking framework that claims to have almost supernatural powers. According to its documentation it is able to mock both static and private methods, final classes, and other nasty things that would be insurmountable obstacles for other mock frameworks. As a result, it has been stated that it should be able [...]]]></description>
			<content:encoded><![CDATA[<h3>The challenge</h3>
<p>PowerMock is a mocking framework that claims to have almost supernatural powers. According to its documentation it is able to mock both static and private methods, final classes, and other nasty things that would be insurmountable obstacles for other mock frameworks. As a result, it has been stated that it should be able to mock the MIDP RecordStore, but so far I have not seen a working example. I accepted the challenge.</p>
<h3>Getting started</h3>
<p>I decided that writing a unit test was the best way to get started. After all, mocking is usually used together with unit testing.<br />
In order to use RecordStore you must first open it. According to the <a href="http://java.sun.com/javame/reference/apis/jsr118/javax/microedition/rms/RecordStore.html">javadoc of RecordStore</a>, the method to be used is: <code>public static RecordStore openRecordStore(String recordStoreName, boolean createIfNecessary)</code>.<br />
A static method that returns an instance of the RecordStore object. Following the "Mocking static methods" guidelines on the <a href="http://code.google.com/p/powermock/">PowerMock web site</a>, it seemed to be a pretty straight forward task:</p>
<ol>
<li>Use the <code>@RunWith</code> annotation at the class-level of the test case.</li>
<li>Use the <code>@PrepareForTest</code> annotation at the class-level of the test case.</li>
<li>Use <code>PowerMock.mockStatic()</code> to mock all methods of this class.</li>
<li>Use <code>PowerMock.replay()</code> to change the class to replay mode.</li>
<li>Use <code>PowerMock.verify()</code> to change the class to verify mode.</li>
</ol>
<p>Ok, a little more complicated than my ordinary EasyMock setup, but nothing to really worry about. In my case, I also needed to create a mock object of the RecordStore class itself because of the return value of the <code>openRecordStore()</code> method. </p>
<h3>The setback</h3>
<p>To my disappointment, my test failed with an <code>ExceptionInInitializerError</code>. I studied the code thoroughly to make sure that I had followed the instructions, but I concluded that error resided elsewhere. A closer look at the failure trace revealed:<br />
<code><br />
[...]<br />
Caused by: java.lang.UnsupportedOperationException: getSlowingFactor is native<br />
at javax.microedition.rms.RecordStore.getSlowingFactor(RecordStore.java)<br />
at javax.microedition.rms.RecordStore.<clinit>(RecordStore.java:2414)<br />
[...]<br />
</code><br />
Hmm, that is strange... According to the API, there should be no <code>getSlowingFactor()</code> in RecordStore? And it seems like it is called by the class initializer? When searching for an answer it seemed like this problem occurs if you have not configured the preverifier correctly. It sort of makes sense, I am not using a preverifier at all in my project and I did not like the idea of introducing one. </p>
<h3>The solution</h3>
<p>Returning to the PowerMock documentation, I discovered instructions how to "Suppressing Unwanted Behavior", maybe this was the way forward? Soon, I found the annotation <code>@SuppressStaticInitializationFor</code>, I added it to my test case and voilÃ , I had successfully mocked the RecordStore!</p>
<h3>Reference code</h3>
<p>You can find the code needed to mock the RecordStore below. If you find it interesting, you can <a href='http://blog.jayway.com/wordpress/wp-content/uploads/2009/03/example.zip'>download</a> a more complex example where a class that uses RecordStore for persistent storage is unit tested with aid of PowerMock.</p>
<pre class="java">&nbsp;
<span style="color: #a1a100;">import static org.easymock.EasyMock.expect;</span>
<span style="color: #a1a100;">import static org.easymock.classextension.EasyMock.createMock;</span>
<span style="color: #a1a100;">import static org.junit.Assert.assertEquals;</span>
<span style="color: #a1a100;">import javax.microedition.rms.RecordStore;</span>
<span style="color: #a1a100;">import javax.microedition.rms.RecordStoreException;</span>
&nbsp;
<span style="color: #a1a100;">import org.junit.Test;</span>
<span style="color: #a1a100;">import org.junit.runner.RunWith;</span>
<span style="color: #a1a100;">import org.powermock.api.easymock.PowerMock;</span>
<span style="color: #a1a100;">import org.powermock.core.classloader.annotations.PrepareForTest;</span>
<span style="color: #a1a100;">import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor;</span>
<span style="color: #a1a100;">import org.powermock.modules.junit4.PowerMockRunner;</span>
&nbsp;
@RunWith<span style="color: #66cc66;">&#40;</span>PowerMockRunner.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>
@PrepareForTest<span style="color: #66cc66;">&#40;</span>RecordStore.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>
@SuppressStaticInitializationFor<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;javax.microedition.rms.RecordStore&quot;</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> RecordStoreMockTest <span style="color: #66cc66;">&#123;</span>
&nbsp;
	@Test
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> testCreateRecordStoreMock<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> RecordStoreException <span style="color: #66cc66;">&#123;</span>
		<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AString+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">String</span></a> recordStoreName = <span style="color: #ff0000;">&quot;record_store_name&quot;</span>;
&nbsp;
		<span style="color: #808080; font-style: italic;">// Create mocks</span>
		PowerMock.<span style="color: #006600;">mockStatic</span><span style="color: #66cc66;">&#40;</span>RecordStore.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>;
		RecordStore recordStoreMock = createMock<span style="color: #66cc66;">&#40;</span>RecordStore.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
		<span style="color: #808080; font-style: italic;">// Record behavior</span>
		expect<span style="color: #66cc66;">&#40;</span>RecordStore.<span style="color: #006600;">openRecordStore</span><span style="color: #66cc66;">&#40;</span>recordStoreName, <span style="color: #000000; font-weight: bold;">true</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">andReturn</span><span style="color: #66cc66;">&#40;</span>
				recordStoreMock<span style="color: #66cc66;">&#41;</span>;
&nbsp;
		<span style="color: #808080; font-style: italic;">// Replay behavior</span>
		PowerMock.<span style="color: #006600;">replay</span><span style="color: #66cc66;">&#40;</span>RecordStore.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
		<span style="color: #808080; font-style: italic;">// Execute test and verify result</span>
		assertEquals<span style="color: #66cc66;">&#40;</span>recordStoreMock, RecordStore.<span style="color: #006600;">openRecordStore</span><span style="color: #66cc66;">&#40;</span>recordStoreName, <span style="color: #000000; font-weight: bold;">true</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
		PowerMock.<span style="color: #006600;">verify</span><span style="color: #66cc66;">&#40;</span>RecordStore.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/03/22/how-to-mock-midp-recordstore/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Øredev 2007</title>
		<link>http://blog.jayway.com/2008/02/01/%c3%b8redev-2007/</link>
		<comments>http://blog.jayway.com/2008/02/01/%c3%b8redev-2007/#comments</comments>
		<pubDate>Fri, 01 Feb 2008 11:41:58 +0000</pubDate>
		<dc:creator>Mattias Severson</dc:creator>
				<category><![CDATA[Events]]></category>
		<category><![CDATA[conference]]></category>
		<category><![CDATA[jayview]]></category>
		<category><![CDATA[oredev]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=3409</guid>
		<description><![CDATA[As most of you know Jayway is one of the organizers of Øredev. Knowing that, and knowing how much we love our own conference, you might not trust our judgment in this review. We beg to differ, and ensure you that Øredev is just as enjoyable as we describe it in this article. The Conference [...]]]></description>
			<content:encoded><![CDATA[<p><strong>As most of you know Jayway is one of the organizers of Øredev. Knowing that, and knowing how much we love our own conference, you might not trust our judgment in this review. We beg to differ, and ensure you that Øredev is just as enjoyable as we describe it in this article. </strong> </p>
<h2>The Conference</h2>
<p>During the last three years, Øredev has grown from a promising initiative to one of<br />
the biggest IT-conferences in Scandinavia. During this year’s event, over 800 visitors<br />
attended more than 100 events. To handle the increasing crowd, the conference was<br />
held at a new location, MalmöMässan, which offered bigger and better conference<br />
halls and more space for the show floor.<br />
The location also offered a lack of heating in some rooms, which in the Swedish<br />
November weather translates into cold conference halls. People kept chugging cof-<br />
fee to keep warm, and everybody wished Oracle would hand out blankets instead<br />
of bottle chillers.<br />
As many as nine parallel tracks were available this year. Back from last year were:<br />
Java, .NET, Methods & Tools, etc. In addition to these, Øredev 2007 offered several<br />
new tracks such as Architecture, Case Studies and more. Especially refreshing were<br />
the User Experience sessions, an important yet often overlooked topic.<br />
Further indicating the growing status of the conference was the number of no-<br />
table speakers that participated this year. The list included big names such as Andy<br />
Hunt, Joel Spolsky, Kevlin Henney, James Coplien, Dan North, and Dr. Jeff Suth-<br />
erland.<br />
At the exhibition floor 26 companies were fighting for the visitors attention. The<br />
innovation in terms of advertising varied ranging from plain old booths with posters<br />
and free pens to elaborate coding competitions with iPods to win.<br />
In spite of being an IT conference, there was only one robot on the show floor,<br />
the SMErobot from Lund. Completely implemented in Java the robot was solving<br />
sudoku and carving in wood taking it’s instructions from a piece of Anoto paper. As<br />
a request for new functionality we would like to see the robot performing massage.<br />
Should not be too hard to implement, considering that the platform is Java based.</p>
<h2>The keynotes</h2>
<p>Being a keynote speaker is always special. There are high expectations of both vi-<br />
sions and entertainment. Being recognized in the business, you would better have a<br />
good presentation up your sleeve. Although some of this years speeches contained<br />
more wittiness than visions, there were three enjoyable keynotes to listen to. </p>
<h3>Andy Hunt: How hard can it be?</h3>
<p>Andy Hunt is well known as one of the 17 founders of the Agile Alliance and the<br />
co-founder of the Pragmatic bookshelf.<br />
During his opening keynote, Hunt asked the audience the infamous question<br />
“How hard can it be?”. He answered the question himself by stating that there are<br />
two different types of complexity, namely essential complexity and accidental com-<br />
plexity. Essential complexity is the complexity required to do a job. It is something<br />
that we all have to live with, some things are hard to achieve by nature. Accidental<br />
complexity or unnecessary complexity on the other hand is something that is arti-<br />
ficial. It should and can be prevented if it is recognized accordingly. There are many<br />
possible reasons for accidental complexity; prejudices or ignorance, stress or lack of<br />
motivation or even just bad luck. Regardless reason, the recipe to avoid accidental<br />
complexity is always the same: rely on reliable things, make a purposeful plan and<br />
stick to it. </p>
<h3>Dan North: No Best Practices: Methodology for thinkers</h3>
<p>Dan North is a renowned speaker from other conferences like JAOO, Agile and<br />
OOPSLA in topics like learning theory and behaviour-driven design. The keynote<br />
North gave at Øredev showed he has a rightful reputation.<br />
As the title indicates, the main mantra in North’s presentation was that there is<br />
no such thing as best practices. As he presented this theory the feeling was similar to </p>
<p><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2009/12/Picture-77.png" alt="Keynote speaker Dan North" title="Keynote speaker Dan North" width="424" height="242" class="alignnone size-full wp-image-3410" /></p>
<p>the scene in Dead Poet’s Society where the teacher asks his students to rip out the<br />
first chapter of their text books.<br />
As a basis for his claim, North explained the Dreyfus Model of Skill Acquisi-<br />
tion. The Dreyfus Model is in itself an interesting topic and describes five different<br />
stages in learning: Novice, Advanced Beginner, Competent, Proficient and Expert.<br />
The novice is the stage of an absolute beginner who relies on rules and guidance to<br />
be able to function whereas the Expert works based off intuition and knowledge at<br />
the subconscious level that has been gathered through many years of work. The in-<br />
teresting part is that the efficiency of people at the expert level is severely reduced if<br />
they are bounded by the safe environments such as a “best practice” that the novice<br />
needs. Best practices are in other words obstructing the people who are the best, the<br />
experts, from doing their job effectively. </p>
<h3>Joel Spolsky: Developing Great Software</h3>
<p>Joel Spolsky has reached his biggest audience through his website joelonsoftware.<br />
com. He is the founder of Fog Creek Software and has created FogBugz, a popular<br />
project management system.<br />
Ten seconds into his seminar, Spolsky immediately showed that he belongs to the<br />
rare selection of people that knows how to make a powerpoint presentation that is<br />
more than just a bunch of slides. As Spolsky brought up a huge picture of Victoria<br />
Beckham on the first page, you knew that you were in for a treat. The topic of the<br />
speech was the importance of good looking software.<br />
Spolsky argued that no matter how good your software is, you will not reach<br />
mass market unless it looks good. He illustrated this through various comparisons<br />
of popular products. Particularly entertaining was the part where he brought up a<br />
Windows XP simulation created entirely within the powerpoint presentation. One<br />
could argue whether that was a good example to bring up in the context of his<br />
speech. Windows is a product that doesn’t necessarily look good compared to one<br />
of its main competitors (OS X), yet has a vastly larger market share. Nevertheless,<br />
the display was impressive and produced lots of laughs from the audience as Spolsky<br />
struggled with various pop-ups and failures in his powerpoint-driven “Windows”.<br />
Even though his presentation clearly was more about entertainment than anything<br />
else, he managed to state an important point: software needs to look good to suc-<br />
ceed! </p>
<p><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2009/12/Picture-78.png" alt="Keynote speaker Joel Spolsky " title="Keynote speaker Joel Spolsky " width="427" height="289" class="alignnone size-full wp-image-3411" /></p>
<h2>Sharing knowledge</h2>
<p>Besides the keynotes the real knowledge sharing was made in the around 80 semi-<br />
nars and in the exhibition hall.<br />
Following the Java track we witnessed the official launch of the Qi4J framework,<br />
introducing Composite Oriented programming, redefining the way we use OOP<br />
today. The new concepts that Qi4J bring are not obvious, even to somebody with<br />
extensive Java experience. We are hoping that Qi4J for dummies will turn up in our<br />
local book store soon.<br />
We also got a first glimpse of Java FX Script, the new GUI framework from<br />
SUN. It has been developed to provide an alternative to the clunky looking Swing<br />
interfaces. Although not yet mature, it is meant to compete with technologies like<br />
Flash and Silverlight.<br />
Another interesting seminar was delivered by Neo Technology, showing us a new<br />
and faster way to store data. Briefly, they have implemented a database using a net-<br />
base, i.e. networks in Java rather than database tables. During the presentation, they<br />
performed a simulated Facebook relation search outclassing a traditional database<br />
by the magnitude of a million.<br />
Identifying some of the trends using Java as a platform rather than as a language is<br />
becoming big. More lightweight languages and scripts such as JRuby on Rails make<br />
use of the Java platform. Domain Driven Design and Web 2.0 (still) were other buz-<br />
zwords that floated around in the lecture halls. As always at Øredev there was a big<br />
focus on open source. The business is changing more towards using and developing<br />
open source frameworks incorporating community thinking into their development<br />
process. There were several seminars that both presented new functionality within<br />
existing frameworks and showed smart ways of using existing technologies. One<br />
example was the demonstration of the new batch framework in Spring.<br />
Sitting in on some of the test and project management seminars a couple of key-<br />
words emerged over and over again, namely “agile” and “test driven”. Even though<br />
most people know that these methods increase productivity and quality of the code,<br />
a quick audience survey showed that there are still few development teams that<br />
actually have incorporated these into their processes. Apparently, it is still tricky to<br />
convince your boss that agile development actually does bring huge winnings.</p>
<h2>Evening activities </h2>
<p>After a full day of new knowledge, inspiring lectures and networking the stage was<br />
taken by the UK stand-up comedian Shazia Mirza. Mirza is a highly acclaimed co-<br />
median and a columnist for the New Statesman. She was recently profiled on CBS<br />
‘60 minutes and has performed all over Europe and USA. Mirza put on a great show<br />
not being the least shy or politically correct, even though she was, as she put it, “the<br />
only Asian woman amongst 600 computer nerds”.<br />
Some great laughs later it was back to business with late evening “Birds Of Feath-<br />
ers” (BOFs), making full flown eagles out of the feathers of knowledge we had been<br />
given during the conference. Some of us joined Owen Taylor at Gigaspaces, making<br />
a complete Gigaspace storage run on our laptops. We were given a chance to try<br />
out this new technology together with one of it’s creators, enabling us to bring the<br />
installation back home for further experiments and tests. We got (and still have) a<br />
good possibility to look under the hood of the magic this product brings, at least that<br />
is promised by Taylor.<br />
For the people that had enough of birds and feathers there was more entertain-<br />
ment from our own band Rockway. </p>
<p><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2009/12/Picture-79.png" alt="Stand-up comedian Shazia Mirza " title="Stand-up comedian Shazia Mirza " width="418" height="246" class="alignnone size-full wp-image-3412" /></p>
<h2>Workshops </h2>
<p>There were many that sought a hands-on experience with the material that was<br />
presented during Øredev, and all participants were given a chance to follow up the<br />
lectures with a variety of workshops. The most popular one was the full Scrum certi-<br />
fication course held by Dr Jeff Sutherland, one of the main creators and preachers of<br />
the Scrum methodology. Another popular workshop was a full day of Qi4J training<br />
allowing programmers to try out the newly launched framework. Andy Hunt also<br />
followed up his lecture on refactoring wetware, i.e. the human mind, with a three<br />
hour workshops, allowing the participants to try out some of the concepts that will<br />
increase productivity and make more efficient use of our brain cells. Hunt presented<br />
a bunch of mind tricks that would have come very handy earlier in the conference. </p>
<h2>Finally</h2>
<p>The yearly Øredev conference is a source of inspiration to an increasing amount of<br />
people. As an employee in the IT sector it is a great opportunity to get access to all<br />
the knowledge presented at the conference, get hands-on with new technologies<br />
and share the visions of some of the biggest names in the business. We tend to spend<br />
more and more time behind our screens, teaching ourselves new tools, technologies<br />
and reinventing the wheel. With Øredev there is a possibility to meet like-minded<br />
people, share experiences and last but not least, to network. Adding new contacts on<br />
your favorite social website is an important goal as any.<br />
Besides the large amount of participants attending there is an increasing number<br />
of exhibitors from all over the world. Be sure to sign up for next year, because the<br />
conference will keep on growing, not only in the number of participants, but also<br />
in importance. There is no better way to keep up to speed with the ever changing<br />
market. Hopefully, the heat will be switched on in all seminar rooms by then.<br />
Until next Øredev... </p>
<p><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2009/12/Picture-80.png" alt="Øredev" title="Øredev" width="424" height="275" class="alignnone size-full wp-image-3413" /></p>
<p><em>Stefan Li, Jakob Klamra, Mattias Severson</em></p>
<p><em>Originally published in <a href="http://jayway.se/jayview">JayView</a>.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2008/02/01/%c3%b8redev-2007/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

