<?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; Jan Kronquist</title>
	<atom:link href="http://blog.jayway.com/author/jankronquist/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>Changing an index in MongoDB</title>
		<link>http://blog.jayway.com/2011/12/15/changing-an-index-in-mongodb/</link>
		<comments>http://blog.jayway.com/2011/12/15/changing-an-index-in-mongodb/#comments</comments>
		<pubDate>Thu, 15 Dec 2011 08:27:51 +0000</pubDate>
		<dc:creator>Jan Kronquist</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[mongodb]]></category>
		<category><![CDATA[morphia]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=11589</guid>
		<description><![CDATA[We are using the @Indexed annotation in Morphia and when we changed to @Indexed(unique=true) we were first surprised when nothing happened. Our first thought was that this might be a problem in Morphia. However, on second thought automatically changing an existing index is probably not a good idea! Although I couldn't find anything in the [...]]]></description>
			<content:encoded><![CDATA[<p>We are using the @Indexed annotation in <a href="http://code.google.com/p/morphia/">Morphia</a> and when we changed to @Indexed(unique=true) we were first surprised when nothing happened. Our first thought was that this might be a problem in Morphia. However, on second thought automatically changing an existing index is probably not a good idea! Although I couldn't find anything in the <a href="http://www.mongodb.org/display/DOCS/Indexes">documentation</a>, <a href="http://www.mongodb.org/">MongoDB</a> will not change the index if it already exists. </p>
<p>Have a look at the following to see what happens:</p>
<p><code><br />
> db.Person.save({"name" : "foo" })<br />
> db.Person.ensureIndex({"name":1})<br />
> db.Person.getIndexes()<br />
[<br />
	{<br />
		"v" : 1,<br />
		"key" : {<br />
			"_id" : 1<br />
		},<br />
		"ns" : "test.Person",<br />
		"name" : "_id_"<br />
	},<br />
	{<br />
		"v" : 1,<br />
		"key" : {<br />
			"name" : 1<br />
		},<br />
		"ns" : "test.Person",<br />
		"name" : "name_1"<br />
	}<br />
]<br />
> db.Person.save({"name" : "foo" })<br />
> db.Person.find()<br />
{ "_id" : ObjectId("4ee9ab58e57f00e1f3ca95c7"), "name" : "foo" }<br />
{ "_id" : ObjectId("4ee9ab63e57f00e1f3ca95c9"), "name" : "foo" }<br />
> db.Person.ensureIndex({"name":1},{"unique":true, "dropDups":true})<br />
> db.Person.find()<br />
{ "_id" : ObjectId("4ee9ab58e57f00e1f3ca95c7"), "name" : "foo" }<br />
{ "_id" : ObjectId("4ee9ab63e57f00e1f3ca95c9"), "name" : "foo" }<br />
> db.Person.getIndexes()<br />
[<br />
	{<br />
		"v" : 1,<br />
		"key" : {<br />
			"_id" : 1<br />
		},<br />
		"ns" : "test.Person",<br />
		"name" : "_id_"<br />
	},<br />
	{<br />
		"v" : 1,<br />
		"key" : {<br />
			"name" : 1<br />
		},<br />
		"ns" : "test.Person",<br />
		"name" : "name_1"<br />
	}<br />
]<br />
</code></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/12/15/changing-an-index-in-mongodb/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Autowiring Morphia entities</title>
		<link>http://blog.jayway.com/2011/12/07/autowiring-morphia-entities/</link>
		<comments>http://blog.jayway.com/2011/12/07/autowiring-morphia-entities/#comments</comments>
		<pubDate>Wed, 07 Dec 2011 15:02:11 +0000</pubDate>
		<dc:creator>Jan Kronquist</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[mongodb]]></category>
		<category><![CDATA[morphia]]></category>
		<category><![CDATA[spring]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=11364</guid>
		<description><![CDATA[My current project is using Morphia to handle object mapping to/from mongoDB and I wanted to add dependency injection using Spring to my entities like this: @Entity public class MyEntity { ... @Autowired @Transient private SomeService someService; } Notice the @Transient annotation that tells Morphia to avoid persisting this field! I solved this problem by [...]]]></description>
			<content:encoded><![CDATA[<p>My current project is using <a href="http://code.google.com/p/morphia/">Morphia</a> to handle object mapping to/from <a href="http://www.mongodb.org/">mongoDB</a> and I wanted to add dependency injection using <a href="http://www.springsource.org/spring-core">Spring</a> to my entities like this:</p>
<pre class="brush:java">
@Entity
public class MyEntity {
...
    @Autowired @Transient
    private SomeService someService;

}
</pre>
<p>Notice the @Transient annotation that tells Morphia to avoid persisting this field! I solved this problem by adding an EntityInterceptor that autowires all entities:</p>
<pre class="brush:java">
public class SpringAutowiringEntityInterceptor extends AbstractEntityInterceptor {
	@Autowired
	private ApplicationContext applicationContext;

    @Autowired
    private Morphia morphia;

	@PostConstruct
	public void postConstruct() {
		morphia.getMapper().addInterceptor(this);
	}

	@Override
	public void preLoad(Object ent, DBObject dbObj, Mapper mapr) {
		applicationContext.getAutowireCapableBeanFactory().autowireBean(ent);
	}
}
</pre>
<p>Here is the complete source code <a href="https://gist.github.com/1443114">SpringAutowiringEntityInterceptor.java</a>. Let me know what you think!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/12/07/autowiring-morphia-entities/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Apache Camel automatic type conversion</title>
		<link>http://blog.jayway.com/2011/08/12/apache-camel-automatic-type-conversion/</link>
		<comments>http://blog.jayway.com/2011/08/12/apache-camel-automatic-type-conversion/#comments</comments>
		<pubDate>Fri, 12 Aug 2011 08:05:58 +0000</pubDate>
		<dc:creator>Jan Kronquist</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[camel]]></category>
		<category><![CDATA[integration]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=9172</guid>
		<description><![CDATA[Apache Camel has good support for type conversion and it is easy to add your own type converters. In this blog post I'll show how to create a generic type converter using reflection. Type conversion is done by Camel either when you explicitly tell Camel to perform conversion or in some cases where Camel detects [...]]]></description>
			<content:encoded><![CDATA[<p>Apache Camel has good support for type conversion and it is easy to add your own type converters. In this blog post I'll show how to create a generic type converter using reflection.</p>
<p>Type conversion is done by Camel either when you explicitly tell Camel to perform conversion or in some cases where Camel detects that a type conversion is needed. For example in this case Camel tries to perform type conversion from SourceType to TargetType:</p>
<pre class="brush:java">
public class SourceType {
    private final int value;

    public SourceType(int value) {
        this.value = value;
    }
}
public class TargetType {
    private final int value;

    public TargetType(int value) {
        this.value = value;
    }
}
public interface Service {
    public void call(TargetType value);
}
...
from("direct:call").bean(service, "call");
...
template.requestBody("direct:call", new SourceType(17));
</pre>
<p>This will fail since there is no type converter registered to handle conversion to TargetType. What if TargetType has a constructor taking a SourceType:</p>
<pre class="brush:java">
public TargetType(SourceType source) {
    this.value = source.getValue();
}
</pre>
<p>But this will also fail! My solution is to add a FallbackConverter that can handle this scenario, that is the target type having a single argument constructor taking the source type. The code looks like this:</p>
<pre class="brush:java">
package com.jayway.camel.typeconverter;

@Converter
public class UsingConstructor {
    @SuppressWarnings("unchecked")
    @FallbackConverter
    public static &lt;T> T convertTo(Class&lt;T> type, Object value, TypeConverterRegistry registry) throws Throwable {
        for (Constructor&lt;?> c : type.getConstructors()) {
            Class&lt;?>[] types = c.getParameterTypes();
            if (types.length == 1 && types[0].isAssignableFrom(value.getClass())) {
                    return (T) c.newInstance(value);
            }
        }
        return null;
    }
}
</pre>
<p>A couple of things to notice:</p>
<ul>
<li>The class has the @Converter annotation</li>
<li>The method has the @FallbackConverter</li>
<li>The signature of the method</li>
</ul>
<p>You also need to include file <i>META-INF/services/org/apache/camel/TypeConverter</i> in your classpath that contains the package name. This allows Camel to automatically discover the type converter class.</p>
<pre class="brush:java">
com.jayway.camel.typeconverter
</pre>
<p>Here is an <a href="https://github.com/jankronquist/AirportWeather/blob/master/src/test/java/com/jayway/camel/typeconverter/UsingReflectionIntegrationTest.java">integration test showing this example</a>. I have also implemented a type converter that checks if the source type has a no argument method returning the target type. The source code for <a href="https://github.com/jankronquist/AirportWeather/tree/master/src/main/java/com/jayway/camel/typeconverter">both type converters</a> are available at GitHub.</p>
<p>Notice that this is just a demo of the capabilities of fallback converters. You have to decide if this approach is appropriate in your project. It might not be desirable to have a direct dependency between the TargetType and the SourceType. The overhead of reflection might be too high or it might have unintended consequences. For example the <a href="https://github.com/jankronquist/AirportWeather/blob/master/src/main/java/com/jayway/camel/typeconverter/UsingMethod.java">UsingMethod</a> converter has the unintended consequence of finding and using the toString() method when a conversion to String is needed. The <a href="https://github.com/jankronquist/AirportWeather/blob/master/src/main/java/com/jayway/camel/typeconverter/UsingConstructor.java">UsingConstructor</a> is probably faster and safer since there are usually fewer constructors than public methods. </p>
<p>See the <a href="http://camel.apache.org/type-converter.html">Camel documentation for type converts</a> for more information.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/08/12/apache-camel-automatic-type-conversion/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>OSGi quick start</title>
		<link>http://blog.jayway.com/2011/07/15/osgi-quick-start/</link>
		<comments>http://blog.jayway.com/2011/07/15/osgi-quick-start/#comments</comments>
		<pubDate>Fri, 15 Jul 2011 15:20:04 +0000</pubDate>
		<dc:creator>Jan Kronquist</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Deployment]]></category>
		<category><![CDATA[karaf]]></category>
		<category><![CDATA[osgi]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=9109</guid>
		<description><![CDATA[OSGi has been looking promising for a long time, but I have felt that getting started have been really complicated and deploying dependencies have been messy, in particular for transitive dependencies. While I was looking into deployment options for Apache Camel I realized that a lot has happened with OSGi since last I looked. In [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://en.wikipedia.org/wiki/OSGi">OSGi</a> has been looking promising for a long time, but I have felt that getting started have been really complicated and deploying dependencies have been messy, in particular for transitive dependencies. While I was looking into deployment options for Apache Camel I realized that a lot has happened with OSGi since last I looked. In particular <a href="http://karaf.apache.org/">Apache Karaf</a> really simplifies OSGi deployment with two useful <a href="http://karaf.apache.org/manual/2.2.2/users-guide/provisioning.html">provisioning features</a>:</p>
<ul>
<li><b>Maven URL handler</b> that allows deployment directly from a Maven repository</li>
<li><b>Features</b> that allow grouping of OSGi bundles</li>
</ul>
<p>Although these features are not part of the OSGi standard, it at least makes my life easier and I believe that something similar will become part of the standard since Spring DM and Apache Aries also have similar concepts. I'll just show how to create a blank OSGi project and deploy in Karaf:</p>
<pre>
mvn org.ops4j:maven-pax-plugin:create-bundle -Dpackage=com.jayway.osgi.helloworld
cd com.jayway.osgi.helloworld/
mvn clean install
</pre>
<p>Now you need to <a href="http://karaf.apache.org/index/community/download.html">download Karaf</a>, unzip and then:</p>
<pre>
cd $KARAF_HOME
bin/karaf
osgi:install --start mvn:com.jayway/com.jayway.osgi.helloworld/1.0-SNAPSHOT
</pre>
<p>The output will be (it is not a completely blank project!):</p>
<pre>
STARTING com.jayway.osgi.helloworld
REGISTER com.jayway.osgi.helloworld.ExampleService
</pre>
<p>To generate an Eclipse project:</p>
<pre>
mvn org.ops4j:maven-pax-plugin:eclipse
</pre>
<p>Some links:</p>
<ul>
<li>Apache Karaf have a good <a href="http://karaf.apache.org/manual/2.2.2/quick-start.html">quick start page</a></li>
<li><a href="http://camel.apache.org/tutorial-osgi-camel-part1.html">Apache Camel OSGi tutorial</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/07/15/osgi-quick-start/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Apache Camel and SOAP</title>
		<link>http://blog.jayway.com/2011/07/14/apache_camel_and_soap/</link>
		<comments>http://blog.jayway.com/2011/07/14/apache_camel_and_soap/#comments</comments>
		<pubDate>Thu, 14 Jul 2011 16:13:37 +0000</pubDate>
		<dc:creator>Jan Kronquist</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[camel]]></category>
		<category><![CDATA[integration]]></category>
		<category><![CDATA[sample]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=9090</guid>
		<description><![CDATA[To learn more about Apache Camel I have implemented a non-trivial integration scenario using freely available SOAP web services to create a service that can return the weather at an airport. The webservices are: The Airport Information Webservice to find the location of an airport The National Digital Forecast Database Webservice provided by http://www.weather.gov/ to [...]]]></description>
			<content:encoded><![CDATA[<p>To learn more about <a href="http://camel.apache.org/">Apache Camel</a> I have implemented a non-trivial integration scenario using freely available SOAP web services to create a service that can return the weather at an airport. </p>
<p>The webservices are:</p>
<ul>
<li>The <a href="http://www.webservicex.net/WS/WSDetails.aspx?WSID=20&CATID=7">Airport Information Webservice</a> to find the location of an airport</li>
<li>The <a href="http://www.nws.noaa.gov/forecasts/xml/">National Digital Forecast Database Webservice</a> provided by http://www.weather.gov/ to find the weather at a location</li>
</ul>
<p>My goals have been:</p>
<ul>
<li>Use web services from different providers</li>
<li>Be able to test the routes</li>
<li>Include error handling</li>
<li>Try various methods for transformation</li>
</ul>
<p>So far I'm quite happy with the results and impressed with the flexibility of Apache Camel. Have a look at the code available at <a href="https://github.com/jankronquist/AirportWeather">AirportWeather project @ GitHub</a> and let me know what you think.</p>
<h2>Routes</h2>
<p>The complete route looks like this:</p>
<pre class="brush:java">
from("direct:getMaximumTemperaturAtAirport")
	.to("direct:getAirportInformationByAirportCode")
	.to("direct:fromAirportInformationToLocation")
	.to("direct:fromLocationToNDFD")
	.to("direct:fromNDFDToTempInCelcius");
</pre>
<p>The flow is synchronous and each step is implemented in a separate route to be testable, for example I can stub out entire steps of the route.   </p>
<p>A step can be further broken down into even smaller routes, for example separating the call to the web service and the error handling:</p>
<pre class="brush:java">
from("direct:getAirportInformationByAirportCode")
	.to("direct:invokeGetAirportInformationByAirportCode")
	.choice()
		.when().xpath("count(/NewDataSet/Table)=0").rollback("No Airport found")
		.otherwise();
</pre>
<h2>Calling a SOAP web service</h2>
<p>To call the web service I use <a href="http://camel.apache.org/spring-web-services.html">Spring WS</a>. The reason I didn't use <a href="http://camel.apache.org/cxf.html">CXF</a> is that the NDFD is using RPC encoding which is an old web standard <a href="http://stackoverflow.com/questions/412772/java-rpc-encoded-wsdls-are-not-supported-in-jaxws-2-0">not supported by the current version of CXF</a>. The XML payload is generated using a <a href="http://camel.apache.org/velocity.html">Velocity template</a>. This works well in this case, but later I want to compare this to JAXB generated objects from an XML schema.</p>
<pre class="brush:java">
from("direct:invokeGetAirportInformationByAirportCode")
    .to("velocity:getAirportInformationByAirportCode.vm")
    .to("spring-ws:http://www.webservicex.net/airport.asmx?soapAction=http://www.webserviceX.NET/
</pre>
<h2>Transformation</h2>
<p>Camel has very flexible support for transformation and un/marshalling. I have tried a couple of different variations. Registering a object and simply calling a method:</p>
<pre class="brush:java">
SimpleRegistry registry = new SimpleRegistry();
registry.put("temperatureTransformer", new TemperatureTransformer());
...
.transform().method("temperatureTransformer", "fromFahrenheitToCelsius");
</pre>
<p>Let Camel figure out which method to call:</p>
<pre class="brush:java">
registry.put("cdataTransformer", new CDataTransformer());
...
.transform().method("cdataTransformer");
</pre>
<p>XML unmarshalling using <a href="http://camel.apache.org/xstream.html">XStream</a>:</p>
<pre class="brush:java">
XStreamDataFormat xmlToAirPortLocation() {
    XStream xstream = new MissingFieldIgnoringXStream();
    xstream.alias("Table", AirportLocation.class);
    XStreamDataFormat dataFormat = new XStreamDataFormat(xstream);
    return dataFormat;
}
...
.unmarshal(xmlToAirPortLocation())
</pre>
<p><a href="http://camel.apache.org/xpath.html">XPath</a> transformation:</p>
<pre class="brush:java">
.transform().xpath("/NewDataSet/Table[1]")
</pre>
<p>Let Camel figure out <a href="http://camel.apache.org/type-converter.html">how to perform the conversion</a>:</p>
<pre class="brush:java">
.convertBodyTo(Integer.class)
</pre>
<h2>Stubbing routes</h2>
<p>When testing I used <a href="http://camel.apache.org/advicewith.html">AdviceWith</a> to stub out a route in the test case. I'm not really sure if this is the best way, but it works. </p>
<pre class="brush:java">
context.getRouteDefinitions().get(0).adviceWith(context, new AdviceWithRouteBuilder() {
    @Override
    public void configure() throws Exception {
        interceptSendToEndpoint(someEndpoint)
            .skipSendToOriginalEndpoint().to("velocity:AirportResult-empty.xml");
    }
});
</pre>
<p>To make the stub actually override the endpoint it is important to call skipSendToOriginalEndpoint. I use <a href="http://camel.apache.org/velocity.html">Velocity</a> to generate a static reply.  See the <a href="https://github.com/jankronquist/AirportWeather/blob/master/src/test/java/com/jayway/airportweather/AirportWeatherTest.java">AirportWeatherTest</a> for more details.</p>
<h2>Handling bad results</h2>
<p>To verify the result of the invoked web service I have used a choice and rollback to signal the error, for example when the airport does not exist:</p>
<pre class="brush:java">
.choice()
    .when().xpath("count(/NewDataSet/Table)=0").rollback("No Airport found")
    .otherwise();
</pre>
<h2>Future Camel rides</h2>
<p>Things I will investigate further:</p>
<ul>
<li>Other ways to stub out routes</li>
<li>Making use of <a href="http://camel.apache.org/camel-test.html">camel-test</a></li>
<li>Use CXF and JAXB to avoid creating XML payloads using Velocity (perhaps for some other web service)</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/07/14/apache_camel_and_soap/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Developing Minecraft Plugins</title>
		<link>http://blog.jayway.com/2011/05/22/developing-minecraft-plugins/</link>
		<comments>http://blog.jayway.com/2011/05/22/developing-minecraft-plugins/#comments</comments>
		<pubDate>Sun, 22 May 2011 15:03:21 +0000</pubDate>
		<dc:creator>Jan Kronquist</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[game]]></category>
		<category><![CDATA[maven]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=8507</guid>
		<description><![CDATA[Minecraft is the most interesting gaming concept I've seen in many years. It is sort of a digital equivalent of Lego and allows people to build and experience amazing worlds. With well over 2 million copies sold and 1.2 million YouTube videos you quickly realize that people like this kind of game. Using just the [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.minecraft.net/">Minecraft</a> is the most interesting gaming concept I've seen in many years. It is sort of a digital equivalent of Lego and allows people to build and experience amazing worlds. With well over <a href="http://www.minecraft.net/stats.jsp">2 million copies sold</a> and <a href="http://www.youtube.com/results?search_query=minecraft">1.2 million YouTube videos</a> you quickly realize that people like this kind of game. Using just the basic game is enough to create all kinds of cool stuff, for example <a href="http://www.youtube.com/watch?v=7sNge0Ywz-M">this computer</a>. </p>
<p>What is my interest in all this except that I'm really into cool gaming ideas? Well, Minecraft is written in Java and it is easy to write plugins. Currently there is no official support for mods or plugins, although there <a href="http://notch.tumblr.com/post/4955141617/the-plan-for-mods">probably will be in the future</a>. However, there is lots of unofficial mods and the most promising server side mod seems to be <a href="http://bukkit.org/">Bukkit</a> which supports plugins. Their wiki includes <a href="http://wiki.bukkit.org/Setting_Up_Your_Workspace">descriptions how to setup your workspace</a> and <a href="http://wiki.bukkit.org/HUGE_Plugin_Tutorial">how to write a plugin</a>. The best way to learn is probably to take a look at the source of one of the many <a href="http://plugins.bukkit.org/">existing plugins</a>. </p>
<p>There is a sample project available called <a href="https://github.com/Bukkit/SamplePlugin">SamplePlugin</a> which you can use to get started quickly. <a href="https://github.com/Bukkit/SamplePlugin/pull/7/files">I have added a simple maven profile</a> that makes it even easier to get started:<br />
<code><br />
git clone https://github.com/jankronquist/SamplePlugin.git<br />
cd SamplePlugin<br />
mvn package -Pstart-server<br />
</code></p>
<p>Happy hacking!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2011/05/22/developing-minecraft-plugins/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Developing JMeter plugins using Maven</title>
		<link>http://blog.jayway.com/2010/07/07/developing-jmeter-plugins-using-maven/</link>
		<comments>http://blog.jayway.com/2010/07/07/developing-jmeter-plugins-using-maven/#comments</comments>
		<pubDate>Wed, 07 Jul 2010 15:44:22 +0000</pubDate>
		<dc:creator>Jan Kronquist</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[jmeter]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[test]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=5814</guid>
		<description><![CDATA[I have been using JMeter for load testing and I needed to create a custom plugin to handle parsing JSON results but I couldn't find a simple guide how to do this. I wanted a simple solution that didn't require manual installation in my repository or a repository manager such as Nexus. ]]></description>
			<content:encoded><![CDATA[<p>I have been using <a href="http://jakarta.apache.org/jmeter/">JMeter</a> for load testing and I needed to create a custom plugin to handle parsing JSON results but I couldn't find a simple guide how to do this. I wanted a simple solution that didn't require manual installation in my repository or a repository manager such as <a href="http://nexus.sonatype.org/">Nexus</a>. </p>
<h3>Building the plugin</h3>
<p>Building a plugin using maven is easy, simply add the following to your pom:</p>
<pre class="xml">&nbsp;
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;properties<span style="font-weight: bold; color: black;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;jmeter</span>.home<span style="font-weight: bold; color: black;">&gt;</span></span>installation directory of jmeter<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/jmeter</span>.home<span style="font-weight: bold; color: black;">&gt;</span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/properties<span style="font-weight: bold; color: black;">&gt;</span></span></span>
&nbsp;
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;dependencies<span style="font-weight: bold; color: black;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;dependency<span style="font-weight: bold; color: black;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;groupId<span style="font-weight: bold; color: black;">&gt;</span></span></span>org.apache.jmeter<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/groupId<span style="font-weight: bold; color: black;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;artifactId<span style="font-weight: bold; color: black;">&gt;</span></span></span>jmeter-core<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/artifactId<span style="font-weight: bold; color: black;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;version<span style="font-weight: bold; color: black;">&gt;</span></span></span>2.3.4<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/version<span style="font-weight: bold; color: black;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;scope<span style="font-weight: bold; color: black;">&gt;</span></span></span>system<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/scope<span style="font-weight: bold; color: black;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;systemPath<span style="font-weight: bold; color: black;">&gt;</span></span></span>${jmeter.home}/lib/ext/ApacheJMeter_core.jar<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/systemPath<span style="font-weight: bold; color: black;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/dependency<span style="font-weight: bold; color: black;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;dependency<span style="font-weight: bold; color: black;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;groupId<span style="font-weight: bold; color: black;">&gt;</span></span></span>org.apache.jmeter<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/groupId<span style="font-weight: bold; color: black;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;artifactId<span style="font-weight: bold; color: black;">&gt;</span></span></span>jmeter-jorphan<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/artifactId<span style="font-weight: bold; color: black;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;version<span style="font-weight: bold; color: black;">&gt;</span></span></span>2.3.4<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/version<span style="font-weight: bold; color: black;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;scope<span style="font-weight: bold; color: black;">&gt;</span></span></span>system<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/scope<span style="font-weight: bold; color: black;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;systemPath<span style="font-weight: bold; color: black;">&gt;</span></span></span>${jmeter.home}/lib/jorphan.jar<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/systemPath<span style="font-weight: bold; color: black;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/dependency<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/dependencies<span style="font-weight: bold; color: black;">&gt;</span></span></span></pre>
<p>You probably want to put <code>jmeter.home</code> in your <code>settings.xml</code> instead.</p>
<h3>Testing the plugin</h3>
<p>Whenever I develop something I want to have a quick build/test cycle. In this case I want to to start the JMeter UI without having to update the JMeter installation or any other manual work. I didn't get <a href="http://mojo.codehaus.org/chronos-maven-plugin/">chronos</a> to add my plugin to the UI. It seems chronos copied the jar files to <code>JMETER_HOME/lib/junit</code> and this probably works for running an already created test, but not for creating the test. I also failed to the the <a href="http://mojo.codehaus.org/exec-maven-plugin/index.html">maven exec plugin</a> to create the command line arguments I needed. Instead I added a small ant script to start JMeter:</p>
<pre class="xml"><span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;build<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;plugins<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;plugin<span style="font-weight: bold; color: black;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;groupId<span style="font-weight: bold; color: black;">&gt;</span></span></span>org.apache.maven.plugins<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/groupId<span style="font-weight: bold; color: black;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;artifactId<span style="font-weight: bold; color: black;">&gt;</span></span></span>maven-antrun-plugin<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/artifactId<span style="font-weight: bold; color: black;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;configuration<span style="font-weight: bold; color: black;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;tasks<span style="font-weight: bold; color: black;">&gt;</span></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;runtime_classpath&quot;</span>
           <span style="color: #000066;">refid</span>=<span style="color: #ff0000;">&quot;maven.runtime.classpath&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
          <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;exec</span> <span style="color: #000066;">executable</span>=<span style="color: #ff0000;">&quot;${jmeter.home}/bin/jmeter.bat&quot;</span><span style="font-weight: bold; color: black;">&gt;</span></span>
            <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;arg</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;-Jsearch_paths=${runtime_classpath}&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
          <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/exec<span style="font-weight: bold; color: black;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/tasks<span style="font-weight: bold; color: black;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/configuration<span style="font-weight: bold; color: black;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/plugin<span style="font-weight: bold; color: black;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/plugins<span style="font-weight: bold; color: black;">&gt;</span></span></span>
<span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;/build<span style="font-weight: bold; color: black;">&gt;</span></span></span></pre>
<p>To run the jmeter gui simply run <code>mvn antrun:run</code>. This only works for Windows, I leave other platforms as an exercise to the reader <img src='http://blog.jayway.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> . </p>
<h3>Using the plugin</h3>
<p>I ended up copying the plugin jar and dependencies to the JMeter installation and used then this modified JMeter distribution when performing the tests. The reason was that I didn't have maven installed on some of the test clients. To copy dependencies you can use <a href="http://maven.apache.org/plugins/maven-dependency-plugin/copy-dependencies-mojo.html">mvn dependency:copy-dependencies</a>.<br />
If you want to run JMeter using maven you probably want to look at <a href="http://mojo.codehaus.org/chronos-maven-plugin/index.html">chronos</a> (although it is not released it seems to work fine):</p>
<ul><a href="http://gabenell.blogspot.com/2009/11/using-maven-chronos-without-external.html">Using Maven Chronos Without an External JMeter Install</a></ul>
<ul><a href="http://blogs.atlassian.com/developer/2009/10/automated_performance_testing_using_jmeter_and_maven.html">Automated performance testing using JMeter and Maven</a></ul>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/07/07/developing-jmeter-plugins-using-maven/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Sneaky throw</title>
		<link>http://blog.jayway.com/2010/01/29/sneaky-throw/</link>
		<comments>http://blog.jayway.com/2010/01/29/sneaky-throw/#comments</comments>
		<pubDate>Fri, 29 Jan 2010 15:10:03 +0000</pubDate>
		<dc:creator>Jan Kronquist</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[exception]]></category>
		<category><![CDATA[jayview]]></category>
		<category><![CDATA[tricks]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=4517</guid>
		<description><![CDATA[The latest issue of our magazine Jayview is out with brand new look and feel. My contribution was a cool piece of code that gets rid of those annoying exceptions. However, during layouting the link to the source disappeared. Credit should of course go to Reinier Zwitserloot and his mail on Java Posse. public class [...]]]></description>
			<content:encoded><![CDATA[<p>The latest issue of <a href="http://jayway.com/jayculture/jayview">our magazine Jayview</a> is out with brand new look and feel. My contribution was a cool piece of code that gets rid of those annoying exceptions. However, during layouting the link to the source disappeared. Credit should of course go to <a href="http://zwitserloot.com/">Reinier Zwitserloot</a> and <a href="http://www.mail-archive.com/javaposse@googlegroups.com/msg05984.html">his mail on Java Posse</a>. </p>
<pre class="brush:java">
public class Sneak {
    public static RuntimeException sneakyThrow(Throwable t) {
        if ( t == null ) throw new NullPointerException("t");
        Sneak.&lt;RuntimeException&gt;sneakyThrow0(t);
        return null;
    }

    @SuppressWarnings("unchecked")
    private static &lt;T extends Throwable&gt; void sneakyThrow0(Throwable t) throws T {
        throw (T)t;
    }
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/01/29/sneaky-throw/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Getting around static typing in Scala</title>
		<link>http://blog.jayway.com/2010/01/23/getting-around-static-typing-in-scala/</link>
		<comments>http://blog.jayway.com/2010/01/23/getting-around-static-typing-in-scala/#comments</comments>
		<pubDate>Sat, 23 Jan 2010 19:43:12 +0000</pubDate>
		<dc:creator>Jan Kronquist</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[collections]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=4503</guid>
		<description><![CDATA[I really like static typing, but sometimes it can get in your way. For instance if you have a collection of objects and you want to perform an operation on the objects of a certain subclass you can run into problems. ]]></description>
			<content:encoded><![CDATA[<p>I really like static typing, but sometimes it can get in your way. For instance if you have a collection of objects and you want to perform an operation on the objects of a certain subclass you can run into problems. I've run the following code in Scala 2.8</p>
<pre class="brush:scala">
// this is easy since everything are Strings
scala> List("one", "two", "three")
res0: List[java.lang.String] = List(one, two, three)

scala> res0.foreach(x => println(x.length()))
3
3
5

// with a mixed collection it gets harder
scala> List("one", 2, "three", 4.0)
res2: List[Any] = List(one, 2, three, 4.0)

scala> res2.foreach(x => println(x.length()))
&lt;console&gt;:6: error: value length is not a member of Any

// it is not enough to just filter out the objects that are Strings
scala> res2.filter(_.isInstanceOf[String])
res4: List[Any] = List(one, three)

// as we still have a List of Any
scala> res4.foreach(x => println(x.length()))
&lt;console&gt;:7: error: value length is not a member of Any

// both filtering and mapping is needed
scala> res2.filter(_.isInstanceOf[String]).map(_.asInstanceOf[String])
res6: List[String] = List(one, three)

// finally it works
scala> res6.foreach(x => println(x.length()))
3
5

// another option is to use pattern matching
scala> res2.foreach(_ match { case x:String => println(x.length); case _ => })
3
5
</pre>
<p>I wanted a more elegant solution with less boiler plate so after playing around with <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=179766">implicit conversions</a> and <a href="http://scala-blogs.org/2008/10/manifests-reified-types.html">reified types</a> I managed to come up with rather nice solution:</p>
<pre class="brush:scala">
// define a class that implements a restrictTo method
scala> class IterableWithRestrictTo[A](from:Iterable[A]) {
     | def restrictTo[B](implicit m: scala.reflect.Manifest[B]) = {
     | from.filter(m.erasure.isInstance(_)).map(_.asInstanceOf[B])
     | }
     | }
defined class IterableWithRestrictTo

// define implicit conversion
scala> implicit def makeIterableWithRestrictTo[A](from : Iterable[A]) = {
     | new IterableWithRestrictTo(from)
     | }
makeIterableWithRestrictTo: [A](from: Iterable[A])IterableWithRestrictTo[A]

scala> List("one", 2, "three", 4.0)
res0: List[Any] = List(one, 2, three, 4.0)

// restrict to objects of type String
scala> res0.restrictTo[String]
res1: Iterable[String] = List(one, three)

// works since the collection have correct type
scala> res1.foreach(x => println(x.length()))
3
5
</pre>
<p>Using the name restrictTo clearly shows that not only is there a type conversion, but also a restriction to a subset of the elements. Notice that the manifest is needed to get the reified type, since the type B is actually erased at compile time. Read more about <a href="http://scala-blogs.org/2008/10/manifests-reified-types.html">reified types in Scala</a>.</p>
<p>Let me know you have another solution! </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/01/23/getting-around-static-typing-in-scala/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>WebLogic 10.3 JMX</title>
		<link>http://blog.jayway.com/2009/04/09/weblogic-103-jmx/</link>
		<comments>http://blog.jayway.com/2009/04/09/weblogic-103-jmx/#comments</comments>
		<pubDate>Thu, 09 Apr 2009 09:05:46 +0000</pubDate>
		<dc:creator>Jan Kronquist</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[jmx]]></category>
		<category><![CDATA[tools]]></category>
		<category><![CDATA[weblogic]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=1533</guid>
		<description><![CDATA[I have been using <a href="http://www.oracle.com/technology/products/weblogic/index.html">Oracle WebLogic 10.3</a> for a while in my current assignment. I wanted to publish my own custom MBeans and be able to see and edit properties and invoke methods on them. However, the built-in management console does not support custom MBeans (without adding custom configuration). I ended up using <a href="http://www.jmanage.org/">JManage</a> which is an open source management console implemented as a web application.]]></description>
			<content:encoded><![CDATA[<p>I have been using <a href="http://www.oracle.com/technology/products/weblogic/index.html">Oracle WebLogic 10.3</a> for a while in my current assignment. I wanted to publish my own custom MBeans and be able to see and edit properties and invoke methods on them. However, the built-in management console does not support custom MBeans (without adding custom configuration). I ended up using <a href="http://www.jmanage.org/">JManage</a> which is an open source management console implemented as a web application.</p>
<p>The problem was that JManage 2.0-RC1 does not support WebLogic 10.3 and their last release was made two years ago. However, since they support version 9 I figured it might be possible to upgrade the jar files to make it work with 10.3. This is how you do it:</p>
<p>In the folder <code>$JMANAGE_HOME/modules/weblogic9</code> remove wljmxclient.jar and add wlfullclient.jar and com.bea.core.descriptor.wl_1.1.0.0.jar instead. Here are the instructions <a href="http://edocs.bea.com/wls/docs103/client/jarbuilder.html">how to create the wlfullclient.jar</a>. The other jar is included in <code>$BEA_HOME/modules</code>.</p>
<p>I have also tried jconsole, <a href="http://edocs.bea.com/wls/docs103/wldf_console_ext/install_display.html">the built-in WLDF console extension</a> and <a href="http://wlnav.open.collab.net/">wlnav</a> but all of them had problems:</p>
<li>To make jconsole work remotely you must <a href="http://www.performanceengineer.com/blog/monitoring-weblogic-using-jmx/">change how the WebLogic server is started</a>. As I really want to use the standard installation package this won't work</li>
<li>The WLDF console does not allow method invocations and I can only get it to show the built-in MBeans</li>
<li>wlnav is built on <a href="http://edocs.bea.com/wls/docs103/config_scripting/using_WLST.html">wlst</a> and seemed very powerful, but was quite ugly and I couldn't find my custom MBeans</li>
<p>Although JManage is good enough for my current purposes I am interested in other alternatives for remote JMX management of WebLogic!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/04/09/weblogic-103-jmx/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>PowerMock 1.0 released</title>
		<link>http://blog.jayway.com/2008/11/21/powermock-10-released/</link>
		<comments>http://blog.jayway.com/2008/11/21/powermock-10-released/#comments</comments>
		<pubDate>Fri, 21 Nov 2008 20:54:42 +0000</pubDate>
		<dc:creator>Jan Kronquist</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[easymock]]></category>
		<category><![CDATA[junit]]></category>
		<category><![CDATA[mock]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[oredev]]></category>
		<category><![CDATA[powermock]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=456</guid>
		<description><![CDATA[We have released 1.0 of PowerMock just in time for the Øredev conference! PowerMock is an open source mock framework based on EasyMock that allow you to mock static methods, private methods and even constructors. Our intent is mainly to allow unit testing of legacy code and people really seemed to appreciate this idea at the conference.]]></description>
			<content:encoded><![CDATA[<p>We have released 1.0 of <a href="http://www.powermock.org">PowerMock</a> just in time for the <a href="http://www.oredev.org/">Øredev</a> conference! PowerMock is an open source mock framework based on <a href="http://www.easymock.org/">EasyMock</a> that allow you to mock static methods, private methods and even constructors. Our intent is mainly to allow unit testing of legacy code and people really seemed to appreciate this idea at the conference.</p>
<p>We now think that the API is stable enough and we have also tested PowerMock in a couple of projects, but of course since we were presenting at the conference it is no coincidence that we released PowerMock 1.0 just days before. <img src='http://blog.jayway.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>The details of the changes can be found in the <a href="http://powermock.googlecode.com/svn/trunk/changelog.txt">changelog</a> but here are some of the highlights since <a href="http://blog.jayway.com/2008/10/27/powermock-08-released/">PowerMock 0.8</a>:</p>
<ul>
<li>The ability to <a href="http://code.google.com/p/powermock/wiki/BypassEncapsulation">set and get internal state</a> based on an object type. This means that you get more refactor friendly code while still being able to set internal state. </li>
<li>Implemented <a href="http://code.google.com/p/powermock/wiki/ReplayAllAndVerifyAll">replayAll and verifyAll</a>. These can be used to replay and verify all mocks created by PowerMock without having to explicitly specify each and everyone. Thanks to <a href="http://www.agilejava.eu/">Ivar Grimstad</a> for suggesting this!</li>
<li>Added support for specifying parameter types for expectNew. <a href="http://code.google.com/p/powermock/wiki/MockConstructor">Mocking constructor calls</a> is a unique feature of PowerMock that people typically find very cool!</li>
</ul>
<p>During the conference I talked to several people and got really good feedback. Everybody seemed to like the idea of being able to unit test legacy code and code that haven't been designed for testing. <a href="http://www.two-sdg.demon.co.uk/curbralan/kevlin.html">Kevlin Henney</a> made a good job of <a href="http://www.oredev.org/topmenu/program/tracktest/kevlinhenney.4.3efb083311ac562f9fe800011931.html">defining and describing various types of unit testing</a> during his talk at Øredev and we talked about the difference between essentially untestable code and accidentally untestable code. PowerMock solves the problem with code being untestable for technical reasons (part of the accidentally untestable). With all the great sessions and good discussions Øredev was yet again a great experience!</p>
<p>I have made <a href="http://powermock.googlecode.com/files/PowerMockAtOredev.pdf">the slides from the presentation</a> available at <a href="http://powermock.org">powermock.org</a>. Note that the demo we showed was actually from the trunk and not from the 1.0 release!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2008/11/21/powermock-10-released/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Azul</title>
		<link>http://blog.jayway.com/2008/10/20/azul/</link>
		<comments>http://blog.jayway.com/2008/10/20/azul/#comments</comments>
		<pubDate>Mon, 20 Oct 2008 19:58:46 +0000</pubDate>
		<dc:creator>Jan Kronquist</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[concurrency]]></category>
		<category><![CDATA[hardware]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=363</guid>
		<description><![CDATA[We have got the privilege to borrow an Azul Vega 1 which is the smallest of <a href="http://www.azulsystems.com/">Azul</a>'s monster machines. This evening a bunch of us Jaywayers gathered to try it out. Installing the Azul JVM was painless and all of us were up and running very quickly. Read more...]]></description>
			<content:encoded><![CDATA[<p>We have got the privilege to borrow an Azul Vega 1 which is the smallest of <a href="http://www.azulsystems.com/">Azul</a>'s monster machines. This evening a bunch of us Jaywayers gathered to try it out. Installing the Azul JVM was painless and all of us were up and running very quickly.</p>
<p>Here is screenshot from the management console showing 81 active CPUs and 23 GB free memory:</p>
<p><a href="http://blog.jayway.com/wordpress/wp-content/uploads/2008/10/azul.png" rel="lightbox"><img src="http://blog.jayway.com/wordpress/wp-content/uploads/2008/10/azul.png" alt="" title="azul" width="600" height="250" class="alignnone size-medium wp-image-364" /></a></p>
<p>I tried some <a href="http://www.scala-lang.org/node/242">Scala actors</a> which worked very well. By running some CPU intensive calculations I concluded that it scaled linearly up to the number of CPUs. No surprise, but very cool when you are running 80 threads at full speed! Also cool to see that Scala runs smoothly which means that neither Scala nor Azul does anything strange. Just pure bytecode.</p>
<p>Somebody tried to configure the Azul JVM in Eclipse and was able to run JUnit tests on Azul. We were also able to run maven without any problems.</p>
<p>We tried to allocate lots of memory. No problem there either, although we had to specify -Xmx10G or something. By default you only get 1.6 GB....</p>
<p>A colleague started tomcat, produced lots of garbage and tried garbage collection at 8 GB of heap. No pause! However, there was some synchronization problem with Log4j since all 16 CPUs had to coordinate their work.</p>
<p>We encountered two problems:</p>
<ul>
<li>xstream apparently had a dependency to Unsafe which is not supported on Azul</li>
<li>the program must be headless, so no Swing</li>
</ul>
<p>A quick rewrite later and we had generated a 64 megapixel mandelbrot calculated in parallel on 40 CPUs. The only problem was saving the PNG file which was a single threaded operation...</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2008/10/20/azul/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>JAOO 2008 in AArhus</title>
		<link>http://blog.jayway.com/2008/10/02/jaoo-2008-in-aarhus/</link>
		<comments>http://blog.jayway.com/2008/10/02/jaoo-2008-in-aarhus/#comments</comments>
		<pubDate>Thu, 02 Oct 2008 07:07:57 +0000</pubDate>
		<dc:creator>Jan Kronquist</dc:creator>
				<category><![CDATA[Events]]></category>
		<category><![CDATA[conference]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=321</guid>
		<description><![CDATA[This year at JAOO all 5 keynote speakers were language designers so there was a clear trend talking about new languages, for example Scala, F# and Fortress. What motivates this is the trend toward more parallel computing with more cores per machine and also to increasing popularity in cloud computing. That is, parallel computing applies [...]]]></description>
			<content:encoded><![CDATA[<p>This year at JAOO all 5 keynote speakers were language designers so there was a clear trend talking about new languages, for example <a href="http://www.scala-lang.org/">Scala</a>, <a href="http://research.microsoft.com/fsharp/fsharp.aspx">F#</a> and <a href="http://projectfortress.sun.com/Projects/Community">Fortress</a>. What motivates this is the trend toward more parallel computing with more cores per machine and also to increasing popularity in cloud computing. That is, parallel computing applies to both desktop applications and scalable enterprise applications. For example previously the focus have been to run multiple applications on the same CPU and therefore we have the synchronized keyword in Java to prevent concurrency problems. But in the future we might have more CPUs than applications so different mindsets and constructs are needed to be able to harness the increased parallel nature of computing.</p>
<p>Guy Steele pointed out that what is good practice for sequential programming might be very bad practice for parallel programming. For example in parallel algorithms you want to limit synchronization and avoid communication between parallel computations and therefore it is ok to use more memory and more CPU cycles to avoid this. Erik Meijer tried to brainwash us all to use <a href="http://www.haskell.org/">Haskell</a>, and succeeded in some ways as people started talking about <a href="http://en.wikipedia.org/wiki/Monad_(functional_programming)">monads</a> and IO<T> all evening.</p>
<p>Gregor Hohpe talked about what Google is doing to create extremely scalable systems. He talked about a new definition of ACID in cloud computing. Associative (the order the operations are combined is not important), Commutative (order of execution is not important), Idempotent (when an operation is executed multiple is has the same result every time)  and Distributed. He also recommended <a href="http://www-db.cs.wisc.edu/cidr/cidr2007/papers/cidr07p15.pdf">Pat Helland's excellent paper</a> on near infinity scalability.</p>
<p>Another cool presentation was Michele Lanza's code visualization tools based on ideas around iconic memory, ie that you should be able to immediately understand and see what is going on. Check out <a href="http://www.inf.unisi.ch/phd/wettel/codecity.html">CodeCity</a> and <a href="http://atelier.inf.unisi.ch/~malnatij/xray.php">X-Ray</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2008/10/02/jaoo-2008-in-aarhus/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Development 13 years ago</title>
		<link>http://blog.jayway.com/2008/09/22/development-13-years-ago/</link>
		<comments>http://blog.jayway.com/2008/09/22/development-13-years-ago/#comments</comments>
		<pubDate>Mon, 22 Sep 2008 17:00:07 +0000</pubDate>
		<dc:creator>Jan Kronquist</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[game]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[retrospective]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=314</guid>
		<description><![CDATA[Back in 1994-1995 me and a friend wrote a game called Gravity Force 2 on the Amiga. It got very popular and we still get the occasional email about it. Some people have requested to look at the source code and now it is finally released! ]]></description>
			<content:encoded><![CDATA[<p>Back in 1994-1995 me and a friend wrote a game called <a href="http://www.lysator.liu.se/~jensa/gf2/">Gravity Force 2</a> on the Amiga. It got very popular and we still get the occasional email about it. Some people have requested to look at the source code and now it is finally released! </p>
<p>This weekend I was unpacking two of the last boxes in my new apartment and I finally found my old Amiga 1200. Since it have been stored in the attic for a couple of years and in before that it was stored in the cellar, I decided that it was time to check if it was still working. It took me a quite some time to configure the TV(!) to correctly show the display, but everything else worked like a charm. It had not been booted for over 10 years! </p>
<p>Anyway I found the source code in some random folder, created an LHA archive, found an old floppy disk and using an USB floppy drive I managed to transfer the archive to my PC. Some facts:</p>
<ul>
<li>The code had not been touched since march 1995</li>
<li>It is more than 12 000 lines of (more or less) undocumented assembly code mostly in a single file</li>
<li>The labels are things like s, s2, fl, bid, cnl2 and so on</li>
<li>We didn't use a version control system. Instead all files were transfered on floppy disk between our computers</li>
</ul>
<p>Yet we were still able to create a fun computer game that worked on all the different versions of the Amiga hardware. With todays powerful hardware, different programming languages, good IDEs and the large number of frameworks I simply don't know where to start. Why is that? </p>
<p>Perhaps the fact that we were very focused on what we wanted to do and not interested in how, we were able to overcome the complexity and simply get it done.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2008/09/22/development-13-years-ago/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Mocking Static Methods</title>
		<link>http://blog.jayway.com/2007/05/01/mocking-static-methods/</link>
		<comments>http://blog.jayway.com/2007/05/01/mocking-static-methods/#comments</comments>
		<pubDate>Tue, 01 May 2007 13:58:54 +0000</pubDate>
		<dc:creator>Jan Kronquist</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[automated testing]]></category>
		<category><![CDATA[jayview]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=3445</guid>
		<description><![CDATA[Mock objects is a very useful technique for unit testing as it allows you to focus your testing efforts on the class being tested instead of on its collaborators. Unfortunately, not everything is an object and therefore you cannot always use mock objects. This article will show how mocking can be generalized to include more [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Mock objects is a very useful technique for unit testing as it allows you to focus your testing efforts on the class being tested instead of on its collaborators. Unfortunately, not everything is an object and therefore you cannot always use mock objects. This article will show how mocking can be generalized to include more things than just objects. </strong></p>
<h2>Motivation</h2>
<p>When unit testing we would like to test only a single unit of code without any exter-<br />
nal dependencies. However, an object seldom lives in isolation and often has one or<br />
more collaborators, which it communicates with using method calls. Mock objects<br />
is a well known technique (1) that that can be used to simulate the collaborators<br />
and thereby create a totally controlled environment. Mock objects together with<br />
test driven development is also very useful for improving the design as you discover<br />
how your class should be used.<br />
So everything is fine? Well, not everything is an object, even in Java. Sometimes<br />
static methods are used and it is no longer possible to use the mock object technique<br />
as there no longer is an object. But that has a simple solution: “Don’t use static<br />
methods” - right? Sure, if you write all code yourself that is possible, but almost all<br />
projects have external dependencies outside of the project’s control. It is even worse<br />
than you might initially think as Java standard APIs often have lots of static methods.<br />
Some examples: </p>
<pre>
•Java	SE:	System.getProperty(String name)
•Java	ME:	RecordStore.openRecordStore(String recordStoreName,
                boolean	createIfNecessary) 
</pre>
<h2>Example </h2>
<p>In the last issue of JayView there was an article about a tool called MockME that<br />
makes it possible to mock the static methods that are abundant in the Java ME<br />
APIs (2). This article tries to solve this problem in a more general way.<br />
Let us use the same code example which uses the RecordStore from Java ME and<br />
examine	the	problem	again.	For	those	of	you	unfamiliar	with	Java	ME,	RecordStore<br />
is an API for storing byte array records persistently on the phone. </p>
<pre>public class RecordStore {
  public static RecordStore openRecordStore(String recordStoreName,
                                            boolean createIfNecessary)
      throws RecordStoreException,
             RecordStoreFullException,
             RecordStoreNotFoundException {
    // implementation goes here
  }
    // ...
}</pre>
<p>We now implement a data access object (DAO) that we use to store messages.<br />
It will allow us to store and access messages from a RecordStore without bothering<br />
with the details how the message is stored. </p>
<pre>public class MessageDao {
  private static final String RECORD_STORE_NAME = “MessageDao”; 

  public void addMessage(Message message) throws RecordStoreException {
    RecordStore recordStore = null;
    try {
      // This static method invocation is normally hard to mock
      recordStore = RecordStore.openRecordStore(RECORD_STORE_NAME, true);
      byte[] bytes = encodeMessage(message);
      if (message.getId() == -1) {
        message.getId() = recordStore.addRecord(bytes, 0, bytes.length);
      } else {
        recordStore.setRecord(message.getId(), bytes, 0, bytes.length);
      }
    } finally {
      if (recordStore != null) {
        recordStore.closeRecordStore();
      }
    }
  }
}
</pre>
<h2>Desired Solution</h2>
<p>In this unit test of MessageDao we only test the happy-flow (when everything goes<br />
fine) to show the principle of static mocking. Please compare this to the MockME<br />
solution. </p>
<pre>public class MessageDaoTest extends TestCase {
  private MessageDao messageDao;        // Object under test
  private RecordStore recordStoreMock;  // Mock object 

  // Called by JUnit to initialize the test
  public void setUp() {
    // Create mock object for RecordStore as usual
    recordStoreMock = createMock(RecordStore.class);
    // tell mocking framework that static methods of class RecordStore
    // should be mocked
    staticMock(RecordStore.class); 

    // Create object under test
    messageDao = new MessageDao();
  } 

  // Called by JUnit to clean up after each test run
  public void tearDown() {
    messageDao = null;
  } 

  public void testAddMessage() throws Exception {
    // Set up expected behaviour
    // (This usually doesn’t work)
    expectStatic(RecordStore.openRecordStore(“MessageDao”, true))
      .andReturn(recordStoreMock);
    byte[] expectEncMess = “\u0004from\u0004text”.getBytes();
    expect(recordStoreMock.addRecord(aryEq(expectEncMess), eq(0), eq(10)))
      .andReturn(42);
    recordStoreMock.closeRecordStore(); 

    // Put the mocks in test state
    replayStatic(RecordStore.class);
    replay(recordStoreMock); 

    // Executing the code we want to test
    Message message = new Message(“from”, “text”);
    messageDao.addMessage(message);
    assertEquals(“Wrong message ID”, 42, message.getId()); 

    // Verify the behaviour
    verifyStatic(RecordStore.class);
    verify(recordStoreMock);
  }
}
</pre>
<p>This test sets up the expected method calls on RecordStore, then invokes the<br />
DAO and finally verifies its behavior. But unfortunately it is not possible to mock<br />
static methods as the binding is done at compile time. Or is it? </p>
<h2>Aspects to the rescue </h2>
<p>It	turns	out	that	this	is	possible.	Using	Aspect	Oriented	Programming	(AOP)	we<br />
can change the static methods to become mockable. Without going too much into<br />
details, AOP allows us to change the behavior of classes and methods after they have<br />
been compiled. Three things are needed: </p>
<ul>
<li>	A	pointcut	that	specifies	which	methods	the	aspect	should	change	(that	is	all<br />
static methods)
<li>	An	advice	that	that	allows	mocking	to	replace	the	original	behavior
<li>	An	implementation	of	the	mock,	replay,	verify	methods	that	allows	mocking<br />
classes
</ul>
<p>Let us start with the setup methods. To keep track of which classes we have<br />
mocked we create a Map that contains an EasyMock MockInvocationHandler for<br />
each class that we mock. MockInvocationHandler is a proxy object that performs<br />
the actual mocking and will receive method invocations instead of the real object.<br />
Notice the use of a Hashtable to make the map accesses thread safe. </p>
<pre>public class StaticMock {
    static Map<Class, MockInvocationHandler> mocks =
        new HashTable<Class, MockInvocationHandler>(); 

    public static void mock(Class type) {
        MockInvocationHandler h
        = new MockInvocationHandler((MocksControl) EasyMock.createControl());
        mocks.put(type, h);
    } 

    public static void replay(Class type) {
        mocks.get(type).getControl().replay();
    } 

    public static void verify(Class type) {
        mocks.remove(type).getControl().verify();
    } 

}
</pre>
<p>Then once we intercept a method call to a static method, find out if there is a<br />
MockInvocationHandler associated with that class and if so redirect the call to it.<br />
This method should not be static to avoid infinite recursion. The following advice<br />
does the trick: </p>
<pre>public	Object	mockMethodAdvice(ProceedingJoinPoint	jp) throws Throwable {
        // find the InvocationHandler associated with the class
        Class type = jp.getSignature().getDeclaringType();
        InvocationHandler h = mocks.get(type); 

        // if there is no InvocationHandler let the method call proceed
        // as normal
        if (h == null) {
            return jp.proceed();
        } 

        // otherwise redirect the method call to the proxy
        MethodSignature methodSignature
            = ((MethodSignature)jp.getSignature());
        return h.invoke(type, methodSignature.getMethod(), jp.getArgs());
    } </pre>
<p>Finally	we	need	to	tell	AspectJ	which	methods	it	should	apply	the	above	advice<br />
to. The following aspect uses a pointcut that catches ALL calls to ALL static meth-<br />
ods (call(static * *(..))). It might be a bit aggressive, but it works! If you want you can<br />
implement your own aspect with a more specialized pointcut, for example specific<br />
to your own application. </p>
<pre>
@Aspect
public class StaticMockAll extends StaticMock {
    @Pointcut(“call(static * *(..))”)
    public void anyStaticOperation() {}
    @Around(“anyStaticOperation()”)
    public Object aroundStaticMethods(ProceedingJoinPoint jp)
        throws Throwable
    {
        return mockMethodAdvice(jp);
    } 

}
</pre>
<p>Things to note: </p>
<ul>
<li>	Static	methods	can	be	mocked!
<li>	Native	methods	can	also	be	mocked	this	way!	By	using	the	“call”	pointcut	we<br />
change all code that tries to call the native methods and not the native method<br />
itself.	However,	note	that	class	loading	issues	are	not	avoided.	For	example,	Java<br />
ME implementations typically require that native libraries are loaded which<br />
can cause problems when unit testing.
<li>	AspectJ	is	required	to	make	this	work.	I	have	been	using	Eclipse	AJDT	plugin<br />
when writing and testing this code.
</ul>
<p>Please download and view the sample code for a simple working example of<br />
using this technique. Go to <a href="www.jayway.se/jayview">www.jayway.se/jayview</a> and download the zip file as-<br />
sociated with  this issue. </p>
<h2>Discussion </h2>
<p>There	are	other	are	ways	to	get	around	this	problem.	For	example	you	could	write<br />
small wrappers around these static methods and then consistently use the wrappers<br />
instead of the underlying implementation. This works, but each project will have<br />
its own wrappers which will probably make it harder to understand than using<br />
standard APIs.<br />
The approach taken by MockME is also an option, especially for handling stand-<br />
ard APIs such as the APIs for Java ME. However, this adds slightly more complexity<br />
to writing the tests, as you need to use the MockME specific methods.<br />
This new solution proposal is still very experimental, but using AOP or some<br />
other technique for bytecode manipulation seems to be a very promising solution<br />
to the problem of mocking static methods. However, to be successful a packaged<br />
solutions needs to: </p>
<ul>
<li>be a drop in jar file
<li>	work well with any IDE
<li> work with build systems such as ant or maven
</ul>
<h2>Conclusion </h2>
<p>So now static method are no longer bad design since we can mock them? No, not<br />
really. Static methods are still bad, but we no longer have to sacrifice or complicate<br />
testability when we are forced to use static methods. When writing new code you<br />
should use an object oriented design and use mock objects for your unit tests. The<br />
mocking techniques presented in this article are only a tool for testing things that<br />
weren’t testable before. This allows us to further increase the possible code coverage<br />
of our tests, but our design rules should not change. </p>
<h2>References</h2>
<p>Sample code available <a href="http://www.jayway.se/jayview/14/MockingStaticMethods.zip ">here</a></p>
<p>1. <a href="http://www.mockobjects.com/files/endotesting.pdf">Endo-Testing: Unit Testing with Mock Objects  </a><br />
2. JayView 13 - Java ME Testing Done Right<br />
3. <a href="http://www.easymock.org/">EasyMock</a><br />
4. <a href="http://junit.sourceforge.net/ ">JUnit</a><br />
5. <a href="http://www.eclipse.org/aspectj/">AspectJ</a><br />
6. <a href="http://www.eclipse.org/ajdt/">Eclipse AJDT</a><br />
7. <a href="http://en.wikipedia.org/wiki/Aspect-oriented_programming">AOP</a> </p>
<p><em>Originally published in <a href="http://jayway.se/jayview">JayView</a>.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2007/05/01/mocking-static-methods/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Static Mock using AspectJ</title>
		<link>http://blog.jayway.com/2007/02/16/static-mock-using-aspectj/</link>
		<comments>http://blog.jayway.com/2007/02/16/static-mock-using-aspectj/#comments</comments>
		<pubDate>Fri, 16 Feb 2007 09:00:08 +0000</pubDate>
		<dc:creator>Jan Kronquist</dc:creator>
				<category><![CDATA[Testing]]></category>
		<category><![CDATA[aop]]></category>
		<category><![CDATA[aspectj]]></category>
		<category><![CDATA[easymock]]></category>
		<category><![CDATA[mock]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=284</guid>
		<description><![CDATA[After seeing <a href="http://mockme.org/">MockME</a> developed by some of my colleagues I started thinking about how this could be made in a generic way.]]></description>
			<content:encoded><![CDATA[<p>After seeing <a href="http://mockme.org/">MockME</a> developed by some of my colleagues I started thinking about how this could be made in a generic way. For example how would we mock the following class?</p>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> StupidSingleton <span style="color: #66cc66;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</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> doStatic<span style="color: #66cc66;">&#40;</span><span style="color: #993333;">int</span> i<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AUnsupportedOperationException+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">UnsupportedOperationException</span></a><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;method not implemented yet...&quot;</span><span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #993333;">void</span> sayHello<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3ASystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">System</span></a>.<span style="color: #006600;">out</span>.<span style="color: #006600;">println</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Hello&quot;</span><span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">native</span> <span style="color: #993333;">void</span> nativeMethod<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>We would like to write something like this:</p>
<pre class="java">&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> testMocking<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		mock<span style="color: #66cc66;">&#40;</span>StupidSingleton.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>;
		expect<span style="color: #66cc66;">&#40;</span>StupidSingleton.<span style="color: #006600;">doStatic</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">17</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><span style="color: #ff0000;">&quot;17&quot;</span><span style="color: #66cc66;">&#41;</span>;
		StupidSingleton.<span style="color: #006600;">sayHello</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
		StupidSingleton.<span style="color: #006600;">nativeMethod</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
		replay<span style="color: #66cc66;">&#40;</span>StupidSingleton.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
		assertEquals<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;17&quot;</span>, StupidSingleton.<span style="color: #006600;">doStatic</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">17</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
		StupidSingleton.<span style="color: #006600;">sayHello</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
		StupidSingleton.<span style="color: #006600;">nativeMethod</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
		verify<span style="color: #66cc66;">&#40;</span>StupidSingleton.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>After playing around with <a href="http://www.eclipse.org/aspectj/">AspectJ</a> I discovered that this is actually possible! Two things are needed:<br />
* An aspect that allows us to catch calls to static methods!<br />
* An implementation of the mock, replay, verify for classes</p>
<p>This turns out to be really easy! The following aspect catches ALL calls to ALL static methods. Might be a bit aggressive, but it works! If you want you can implement your own aspect with a more specialized pointcut.</p>
<pre class="java">&nbsp;
@Aspect
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> StaticMockAll <span style="color: #000000; font-weight: bold;">extends</span> StaticMockAspect <span style="color: #66cc66;">&#123;</span>
	@Pointcut<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;call(static * *(..))&quot;</span><span style="color: #66cc66;">&#41;</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">void</span> anyStaticOperation<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span><span style="color: #66cc66;">&#125;</span>
&nbsp;
	@Around<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;anyStaticOperation()&quot;</span><span style="color: #66cc66;">&#41;</span>
	<span style="color: #000000; font-weight: bold;">public</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AObject+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Object</span></a> aroundStaticMethods<span style="color: #66cc66;">&#40;</span>ProceedingJoinPoint jp<span style="color: #66cc66;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AThrowable+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Throwable</span></a> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">super</span>.<span style="color: #006600;">aroundStaticMethods</span><span style="color: #66cc66;">&#40;</span>jp<span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>The mock, replay, verify methods turns out to be trivial:</p>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> StaticMock <span style="color: #66cc66;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">static</span> Map&lt;Class, MockInvocationHandler&gt; mocks = <span style="color: #000000; font-weight: bold;">new</span> HashMap&lt;Class, MockInvocationHandler&gt;<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">synchronized</span> <span style="color: #993333;">void</span> mock<span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">Class</span> type<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		MockInvocationHandler h = <span style="color: #000000; font-weight: bold;">new</span> MockInvocationHandler<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#40;</span>MocksControl<span style="color: #66cc66;">&#41;</span> EasyMock.<span style="color: #006600;">createControl</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
		mocks.<span style="color: #006600;">put</span><span style="color: #66cc66;">&#40;</span>type, h<span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">synchronized</span> <span style="color: #993333;">void</span> replay<span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">Class</span> type<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		mocks.<span style="color: #006600;">get</span><span style="color: #66cc66;">&#40;</span>type<span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">getControl</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">replay</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">synchronized</span> <span style="color: #993333;">void</span> verify<span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">Class</span> type<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		mocks.<span style="color: #006600;">remove</span><span style="color: #66cc66;">&#40;</span>type<span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">getControl</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">verify</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>Finally, the base class for the aspect that does the actual work is also quite simple:</p>
<pre class="java">&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> StaticMockAspect <span style="color: #66cc66;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">public</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AObject+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Object</span></a> aroundStaticMethods<span style="color: #66cc66;">&#40;</span>ProceedingJoinPoint jp<span style="color: #66cc66;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AThrowable+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">Throwable</span></a> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">Class</span> type = jp.<span style="color: #006600;">getSignature</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">getDeclaringType</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
		<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3AInvocationHandler+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #aaaadd; font-weight: bold;">InvocationHandler</span></a> h = getInvocationHandler<span style="color: #66cc66;">&#40;</span>type<span style="color: #66cc66;">&#41;</span>;
		<span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>h == <span style="color: #000000; font-weight: bold;">null</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
			<span style="color: #000000; font-weight: bold;">return</span> jp.<span style="color: #006600;">proceed</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
		<span style="color: #66cc66;">&#125;</span>
		MethodSignature methodSignature = <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#40;</span>MethodSignature<span style="color: #66cc66;">&#41;</span>jp.<span style="color: #006600;">getSignature</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
		<span style="color: #000000; font-weight: bold;">return</span> h.<span style="color: #006600;">invoke</span><span style="color: #66cc66;">&#40;</span>type, methodSignature.<span style="color: #006600;">getMethod</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>, jp.<span style="color: #006600;">getArgs</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> MockInvocationHandler getInvocationHandler<span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">Class</span> type<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">synchronized</span> <span style="color: #66cc66;">&#40;</span>StaticMock.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
			<span style="color: #000000; font-weight: bold;">return</span> StaticMock.<span style="color: #006600;">mocks</span>.<span style="color: #006600;">get</span><span style="color: #66cc66;">&#40;</span>type<span style="color: #66cc66;">&#41;</span>;
		<span style="color: #66cc66;">&#125;</span>
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
<span style="color: #66cc66;">&#125;</span>
&nbsp;</pre>
<p>h3. Notes</p>
<p>Things to note and think about:<br />
* Static methods and native methods can be mocked! By using the "call" pointcut we change all code that tries to call the native methods and not the native method itself.<br />
* AspectJ is required to make this work. I have been using <a href="http://www.eclipse.org/ajdt/">Eclipse AJDT</a><br />
* It should be possible to replace the Aspect with "plain" byte code manipulation and "just" reload the class. </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2007/02/16/static-mock-using-aspectj/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Problems with object creation</title>
		<link>http://blog.jayway.com/2007/02/01/problems-with-object-creation/</link>
		<comments>http://blog.jayway.com/2007/02/01/problems-with-object-creation/#comments</comments>
		<pubDate>Thu, 01 Feb 2007 08:30:37 +0000</pubDate>
		<dc:creator>Jan Kronquist</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[jayview]]></category>
		<category><![CDATA[jvm]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=3532</guid>
		<description><![CDATA[Every programming language has tricky details that you need to be aware of. This article will look at several such issues in Java related to the Java compiler. Test your Java skills and see if you know the answer! The problem A while ago a colleague of mine discovered a weird behavior when writing some [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Every programming language has tricky details that you need to be aware of. This article will look at several such issues in Java related to the Java compiler. Test your Java skills and see if you know the answer!<br />
</strong></p>
<h2>The problem</h2>
<p>A while ago a colleague of mine discovered a weird behavior when writing some integration tests. He ﬁ rst noticed that the test worked in JDeveloper, but not in Eclipse. Then he noticed that he could make a small change to the test setup and the test would pass. Another small change and it would fail again. He got some help and managed to reduce the problem to the following: </p>
<h3>Original code </h3>
<pre>import junit.framework.TestCase;
public class ObjectCreationTest extends TestCase {
        class MyObject {
                Object temp;
                public MyObject() {
                        set();
                }
                void set() {
                }
                Object get() {
                        return temp;
                }
        }
        public void testWithNewString() throws Throwable {
                ﬁ nal String value = new String(”Value”);
                assertEquals(”Value”, value); 

                MyObject tested = new MyObject() {
                        void set() {
                                temp = value;
                        }
                };
                String result = (String) tested.get();
                assertEquals(”Value”, result);
        }
}
</pre>
<p>This test fails in some environments and works in others. When the test fails it is<br />
because result is null. How can this be?  But it gets even stranger: By changing how<br />
the value is initialized the test always pass: </p>
<h3>Using a String constant </h3>
<pre>public void testWithConstant() throws Throwable {
        ﬁ nal String value = ”Value”;
        assertEquals(”Value”, value); 

        MyObject tested = new MyObject() {
                void set() {
                        temp = value;
                }
        };
        String result = (String) tested.get();
        assertEquals(”Value”, result);
}
</pre>
<p>This test works for all environments. Why does the initialization of value affect<br />
result? Very strange indeed!<br />
Finally, by changing the type of the value we are back to the situation where the test<br />
case fails in some environments, but not all. </p>
<h3>Using Object instead of String </h3>
<pre>public void testWithObject() throws Throwable {
        ﬁ nal Object value = ”Value”;
        assertEquals(”Value”, value); 

        MyObject tested = new MyObject() {
                void set() {
                        temp = value;
                }
        };
        String result = (String) tested.get();
        assertEquals(”Value”, result);
}</pre>
<h2>Challenge</h2>
<p>Here are some challenges for you! Try to solve them before reading the solution! </p>
<ul>
<li>Explain the difference between the middle test case and the other two (easy).
<li>Explain why the initial test case fails in some environments and works in others (hard).
<li>Find the bad design that might cause problems (and indeed does in this case!).
</ul>
<p>I can give you a hint. The differences are both related to the Java compiler. Don’t<br />
cheat! You should at least be able to answer the irst question before reading on. </p>
<h2>Solution</h2>
<p>There are several things going on here. I’ll start by explaining what is going on when<br />
we change the variable named ”value” and then I’ll look more closely at anonymous<br />
inner classes. Finally I will describe the problem with the design. </p>
<h3>Constant variablConstant variables</h3>
<p>Here are the three cases again: </p>
<pre>final String value1 = new String(”Value”);
final String value2 = ”Value”;
final Object value3 = ”Value”;
</pre>
<p>According to the Java Language Speciﬁ cation (JLS) ”We call a variable, of primitive<br />
type or type String, that is ﬁ nal and initialized with a compile-time constant expres-<br />
sion (§15.28) a constant variable”. Lets go through each variable: </p>
<ul>
<li>”value1” is not a constant since it does not have a compile-time constant expres-<br />
sion! That is, the compiler does not know what the String constructor is doing and<br />
therefore assumes that this needs to be evaluated at runtime.
<li>”value2” is a constant variable since it is clearly of type String and also initialized with a compile-time constant value.
<li>”value3” is not a constant since it is not a primitive type or a String. Yes, the object it refers to is a String, but the variable itself is an Object.
</ul>
<p>This means that only the middle case is a constant. When the compiler spots a<br />
constant it automatically replaces all references with the constant value, ie in the<br />
compiled class a constant variable is never referenced! The result is that the next<br />
problem I will describe does not occur and the test case works. </p>
<h3>Anonymous inner classes </h3>
<p>As you know an inner class is able to access not only ﬁ elds in the creating instance<br />
but also ﬁ nal variables in the method that creates the class. Did you ever wonder<br />
how this magic is done? Maybe you have also noticed that it is not possible for an<br />
anonymous class to have a constructor. When you create an anonymous inner class<br />
the compiler actually creates the constructor for you. Let’s decompile the original<br />
version and see what is going on.</p>
<p><strong>Decompiled the original version (using JAD and javap)</strong></p>
<pre>ﬁnal class ObjectCreationTest$1 extends MyObject {
        ﬁ nal ObjectCreationTest this$0;
        private ﬁ nal Object val$value;
        ObjectCreationTest$1(ObjectCreationTest that, Object obj)
                this$0 = that;
                val$value = obj;
                super();
        }
        void set() {
                temp = val$value;
        }
}
public void testWithNewString() throws Throwable{
        ﬁ nal Object value = new String(”value”);
        MyObject tested = new ObjectCreationTest$1(this, value);
        Object result = tested.get();
        assertEquals(value, result);
}
</pre>
<p>Now it is easy to see that there is no magic going on! The compiler has simply added<br />
a constructor and two instance variables. The set method is not using the ﬁ nal vari-<br />
able from the method, instead it is simply using its own reference to the value.<br />
Well, this is all very nice, but why did the test case fail in some environments?<br />
Notice how the generated constructor ﬁ rst initializes the members and then calls super. This is normally not allowed in Java, but consider what would happen if the<br />
compiler didn’t work this way. MyObject constructor would be called, which then<br />
calls set and tries to use val$value which has not been initialized yet. Because of a<br />
bug in the compiler this is exactly what happened in Java compilers before release<br />
1.4.<br />
OK, so if this problem is ﬁ xed in 1.4 and later, why should you care? Take a look<br />
at the next problem! </p>
<h3>Bad design </h3>
<p>The problem with the design is that the base class MyObject is calling methods in the<br />
anonymous subclass before the subclass instance variables have been created. Unfor-<br />
tunately this is not only a problem with anonymous classes, but a problem in general.<br />
Take a look at the following test case and see if you know what will happen. </p>
<pre>
public class BaseCallingSubTest extends TestCase {
        class Base {
                Base() {
                        doStuff();
                }
                void doStuff() {
                }
        }
        class Sub extends Base {
                private ﬁ nal int ﬁ nalField = 5;
                private int normalField = 5;
                void doStuff() {
                        assertEquals(5, ﬁ nalField);
                        assertEquals(5, normalField);
                }
        } 

        public void testSub() {
                Sub s = new Sub();
        }
}
</pre>
<p>The test case will fail at the second assertEquals. Why? Two things are happening.<br />
First of all ”ﬁ nalField” is a constant variable and the compiler automatically uses 5<br />
instead of referencing the variable, see above. Secondly, the constructor for Base is<br />
called before the ﬁ elds of Sub are initialized! Things are actually happening in this<br />
order: </p>
<p>1. The ﬁelds in Base are initialized<br />
2. Base constructor is run<br />
3. The ﬁ elds in Sub are initialized<br />
4. Sub constructor is run </p>
<p>This is not a bug! This is exactly according to JLS ”§12.5 Creation of New Class<br />
Instances”. The following is perhaps even more surprising: </p>
<pre>public class BaseCallingSub2Test extends TestCase {
        class Base {
                Base() {
                        doStuff();
                }
                void doStuff() {
                }
        }
        class Sub extends Base {
                private int normalField = 5;
                void doStuff() {
                        normalField = 7;
                }
        } 

        public void testBase() {
                Sub s = new Sub();
                assertEquals(7, s.normalField);
        }
}
</pre>
<p>This test case also fails because after Base and doStuff have been called, Sub is ini-<br />
tialized and the normalField is assigned to 5. This is possible to solve by not initial-<br />
izing normalField. </p>
<pre>class Sub extends Base {
        private int normalField;
        void doStuff() {
                normalField = 7;
        }
}</pre>
<p>This works as expected. However, try to avoid constructions like this as it is very<br />
easy to forget that the ﬁ elds might not be initialized yet. There are actually more<br />
problems with this construction as it might affect thread safety. For instance if the<br />
subclass starts a thread in the overridden method this thread might be given access<br />
to the uninitialized object. Brian Goetz (author of ”Java Concurrency in Practice”)<br />
goes as far as calling this ”not properly constructed”. </p>
<h3>Lessons learned</h3>
<ul>
<li>Make sure you understand constant variables and how they are used by the compiler
<li>Use a recent version of Java compiler. Sun is constantly adding improvements and<br />
ﬁxing bugs.
<li>Avoid calling non ﬁ nal methods from the constructor. If you have to, be aware<br />
that the object might not be initialized yet.
<li>Do not perform unnecessary initialization of ﬁelds.
</ul>
<p><em>Originally published in <a href="http://jayway.se/jayview">JayView</a>.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2007/02/01/problems-with-object-creation/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

