<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Ralf Wehner&#039;s Blog</title>
	<atom:link href="http://rwehner.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://rwehner.wordpress.com</link>
	<description>Just another WordPress.com weblog</description>
	<lastBuildDate>Sun, 15 Jan 2012 08:10:44 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='rwehner.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Ralf Wehner&#039;s Blog</title>
		<link>http://rwehner.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://rwehner.wordpress.com/osd.xml" title="Ralf Wehner&#039;s Blog" />
	<atom:link rel='hub' href='http://rwehner.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Create JSON response for AJAX request in spring 3.0</title>
		<link>http://rwehner.wordpress.com/2010/06/09/2-ways-to-create-json-response-for-ajax-request-in-spring3/</link>
		<comments>http://rwehner.wordpress.com/2010/06/09/2-ways-to-create-json-response-for-ajax-request-in-spring3/#comments</comments>
		<pubDate>Wed, 09 Jun 2010 10:35:37 +0000</pubDate>
		<dc:creator>rwehner</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[spring 3.0]]></category>

		<guid isPermaLink="false">http://rwehner.wordpress.com/?p=55</guid>
		<description><![CDATA[Within a project pause i was playing with the google chart tools embedded within a spring 3 web project which impressed me well. After playing with some charts i reached a point were it was usedful to fill the TableData Java script object with data provided by an AJAX request. What i needed was to [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=rwehner.wordpress.com&amp;blog=12151074&amp;post=55&amp;subd=rwehner&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Within a project pause i was playing with the <a href="http://code.google.com/intl/de-DE/apis/visualization/documentation/">google chart tools</a> embedded within a spring 3 web project which impressed me well.<br />
After playing with some charts i reached a point were it was usedful to fill the <i>TableData</i> Java script object with data provided by an AJAX request. What i needed was to implent a simple own Data Source.<br />
Using the actual spring 3.0 version i found out two simple solutions to generate a JSON response for AJAX requests.</p>
<h2>Use Jackson JSON processor in combination with spring&#8217;s <i>StringHttpMessageConverter</i></h2>
<p>I used the <a href="http://jackson.codehaus.org/">Jackson JSON processor</a> to generate a JSON string that can be written via the spring&#8217;s <i>StringHttpMessageConverter</i> into the <i>HttpServletResponse</i> response object. To use this functionality we have to add the <a href="http://jackson.codehaus.org/Download">jackson-mapper-asl.jar</a> into our project. For maven projects we have to add following stuff into the pom.xml dependencies:<br />
<pre class="brush: xml;">
		&lt;!-- Jackson JSON Mapper --&gt;
		&lt;dependency&gt;
			&lt;groupId&gt;org.codehaus.jackson&lt;/groupId&gt;
			&lt;artifactId&gt;jackson-mapper-asl&lt;/artifactId&gt;
			&lt;version&gt;1.5.3&lt;/version&gt;
		&lt;/dependency&gt;
</pre><br />
The Jackson processor provides two ways to generate a JSON object stream:</p>
<h3>Simple Data Binding</h3>
<p>You can use <i>Map</i> objects to build the JSON object graph and generate the JSON stream. In a spring web controller this could look like this:<br />
<pre class="brush: java;">
@Controller
public class RestController {

    @RequestMapping(value = &quot;rest/playground/json-user&quot;, method = RequestMethod.GET)
    protected void getJsonDataExampleSimpleDataBinding(HttpServletResponse response) throws JsonGenerationException, JsonMappingException, IOException {
        ObjectMapper mapper = new ObjectMapper();
        Map&lt;String, String&gt; nameStruct = new HashMap&lt;String, String&gt;();
        nameStruct.put(&quot;first&quot;, &quot;Joe&quot;);
        nameStruct.put(&quot;last&quot;, &quot;Sixpack&quot;);
        Map&lt;String, Object&gt; userData = new HashMap&lt;String, Object&gt;();
        userData.put(&quot;name&quot;, nameStruct);
        userData.put(&quot;gender&quot;, &quot;MALE&quot;);
        userData.put(&quot;verified&quot;, Boolean.FALSE);
        userData.put(&quot;userImage&quot;, &quot;Rm9vYmFyIQ==&quot;);
        String jsonString = mapper.writeValueAsString(userData);

        AbstractHttpMessageConverter&lt;String&gt; stringHttpMessageConverter = new StringHttpMessageConverter();
        MediaType jsonMimeType = MediaType.APPLICATION_JSON;
        if (stringHttpMessageConverter.canWrite(String.class, jsonMimeType)) {
            try {
                stringHttpMessageConverter.write(jsonString, jsonMimeType, new ServletServerHttpResponse(response));
            } catch (IOException m_Ioe) {
            } catch (HttpMessageNotWritableException p_Nwe) {
            }
        }
    }
    ...
}
</pre></p>
<h3>Full Data Binding</h3>
<p>In opposite to use Map objects often it makes sense to represent the JSON objects in simple bean classes (POJOs) on the server side and to marshall the POJO back to a JSON string stream. Here is an example:<br />
<pre class="brush: java;">
    @RequestMapping(value = &quot;rest/playground/json-user&quot;, method = RequestMethod.GET)
    protected void getJsonDataExampleFullDataBinding(HttpServletResponse response) throws JsonGenerationException, JsonMappingException, IOException {
        ObjectMapper mapper = new ObjectMapper();
        Object userData = new String(&quot;mock for the json object which have to be replaced with real one&quot;);
        String jsonString = mapper.writeValueAsString(userData);

        AbstractHttpMessageConverter&lt;String&gt; stringHttpMessageConverter = new StringHttpMessageConverter();
        MediaType jsonMimeType = MediaType.APPLICATION_JSON;
        if (stringHttpMessageConverter.canWrite(String.class, jsonMimeType)) {
            try {
                stringHttpMessageConverter.write(jsonString, jsonMimeType, new ServletServerHttpResponse(response));
            } catch (IOException m_Ioe) {
            } catch (HttpMessageNotWritableException p_Nwe) {
            }
        }
    }
</pre><br />
Beside the <i>simple data binding</i> and <i>full data binding</i> there exists two other JSON processing variantes named as <i>Streaming</i> and <i>Tree model</i>. Please have a look at the <a href="http://wiki.fasterxml.com/JacksonDocumentation">documentation</a> if you need more information on how to use Jackson. </p>
<h2>Use the spring&#8217;s <i>MappingJacksonHttpMessageConverter</i></h2>
<p>Another solution to provide JSON response is to use the <i>MappingJacksonHttpMessageConverter</i> which is an implementation of <i>HttpMessageConverter</i> that can read and write JSON using the <a href="http://jackson.codehaus.org/">Jackson&#8217;s</a> ObjectMapper. (Underneath the cover the MappingJacksonHttpMessageConverter uses Jackson as the name implied.) For propper use of this Implementation we have to add the depending artifact <b>jason-mapper-asl.jar</b> into our project as shown in the pom.xml example above.</p>
<h3>Use the MappingJacksonHttpMessageConverter directly in controller&#8217;s request method</h3>
<p>Use the MappingJacksonHttpMessageConverter class directly in the controler&#8217;s request method to build the HttpServeletResponse. This will be show in the example below:<br />
<pre class="brush: java;">
    @RequestMapping(value = &quot;rest/playground/json-example&quot;, method = RequestMethod.GET)
    protected void getJsonDataExample(HttpServletResponse response) {
        MappingJacksonHttpMessageConverter jsonConverter = new MappingJacksonHttpMessageConverter();
        MediaType jsonMimeType = MediaType.APPLICATION_JSON;
        Object jsonBean = new String(&quot;mock for the json object which have to be replaced with real one&quot;);
        if (jsonConverter.canWrite(jsonBean.getClass(), jsonMimeType)) {
            try {
                jsonConverter.write(jsonBean, jsonMimeType, new ServletServerHttpResponse(response));
            } catch (IOException m_Ioe) {
            } catch (HttpMessageNotWritableException p_Nwe) {
            }
        }
    }
</pre><br />
In this code the JSON object is represented in a POJO on the server side and will be serialized and processed into &#8216;application/json&#8217; response by the MappingJacksonHttpMessageConverter. When it becomes necessary to have more control about the serialization/deserialization process a custom-configured <i>ObjectMapper</i> can be set using the method <i>MappingJacksonHttpMessageConverter.setObjectMapper()</i>.</p>
<h3>Use the <i>@ResponseBody</i> Annotation</h3>
<p>A very simple solution is to use the spring&#8217;s @RequestBody Annotation on the return value of a controller method. When using the @RequestBody the return value is indicated to be bound to a web response body which will be automatically done by the spring MVC. In this case, Spring MVC invokes a MappingJacksonHttpMessageConverter  built on the Jackson  JSON processor. This implementation is enabled automatically when you use the <i>mvc:annotation-driven</i> configuration element with Jackson present in your classpath.<br />
So, an approch in code can look like this:<br />
<pre class="brush: java;">
    @RequestMapping(value = &quot;/rest/playground/google-barchart&quot;, method = RequestMethod.GET)
    public @ResponseBody
    GoogleJsonResponse getJsonDataForBarChart(HttpServletResponse response, HttpServletRequest request) {
        response.setStatus(HttpServletResponse.SC_OK);
        GoogleJsonResponse ret = new GoogleJsonResponse();
        ret.addColl(&quot;string&quot;, &quot;Year&quot;);
        ret.addColl(&quot;number&quot;, &quot;Austria&quot;);
        ret.addColl(&quot;number&quot;, &quot;Bulgaria&quot;);
        ret.addColl(&quot;number&quot;, &quot;Denmark&quot;);
        ret.addColl(&quot;number&quot;, &quot;Greece&quot;);
        ret.addRow(new GoogleJsonResponse.Cell(&quot;2003&quot;), new GoogleJsonResponse.Cell(1336060), new GoogleJsonResponse.Cell(400361), new GoogleJsonResponse.Cell(1001582), new GoogleJsonResponse.Cell(
                997974));
        ret.addRow(new GoogleJsonResponse.Cell(&quot;2004&quot;), new GoogleJsonResponse.Cell(1538156), new GoogleJsonResponse.Cell(366849), new GoogleJsonResponse.Cell(1119450), new GoogleJsonResponse.Cell(
                941795));
        ret.addRow(new GoogleJsonResponse.Cell(&quot;2005&quot;), new GoogleJsonResponse.Cell(1576579), new GoogleJsonResponse.Cell(440514), new GoogleJsonResponse.Cell(993360), new GoogleJsonResponse.Cell(
                930593));
        ret.addRow(new GoogleJsonResponse.Cell(&quot;2006&quot;), new GoogleJsonResponse.Cell(1600652), new GoogleJsonResponse.Cell(434552), new GoogleJsonResponse.Cell(1004163), new GoogleJsonResponse.Cell(
                897127));
        ret.addRow(new GoogleJsonResponse.Cell(&quot;2007&quot;), new GoogleJsonResponse.Cell(1968113), new GoogleJsonResponse.Cell(393032), new GoogleJsonResponse.Cell(979198), new GoogleJsonResponse.Cell(
                1080887));
        ret.addRow(new GoogleJsonResponse.Cell(&quot;2008&quot;), new GoogleJsonResponse.Cell(1901067), new GoogleJsonResponse.Cell(517206), new GoogleJsonResponse.Cell(916965), new GoogleJsonResponse.Cell(
                1056036));
        return ret;
    }
</pre><br />
(I&#8217;ve modified a google tool chart example and created the <i>GoogleJsonResponse</i> class which is a simple Java bean with some attributes and setter and getter. This class represents the JSON data that will be wrapped into a google TableData objects in the java script of the jsp.)<br />
<pre class="brush: java;">
public class GoogleJsonResponse {

    class Col {
        String id;
        final String _type;
        final String _label;

        public Col(String type, String label) {
            _type = type;
            _label = label;
        }

        public String getId() {
            return id;
        }

        public String getType() {
            return _type;
        }

        public String getLabel() {
            return _label;
        }
    };

    public static class Cell {
        private final Object _v;

        public Cell(Object v) {
            _v = v;
        }

        public Object getV() {
            return _v;
        }
    }

    class Row {
        List&lt;Cell&gt; _c = new ArrayList&lt;Cell&gt;();

        public void addCells(Cell... cells) {
            _c.addAll(Arrays.asList(cells));
        }

        public List&lt;Cell&gt; getC() {
            return _c;
        }
    };

    /* GoogleResonResponse attributes starts here */
    private List&lt;Col&gt; _cols = new ArrayList&lt;Col&gt;();
    
    private List&lt;Row&gt; _rows = new ArrayList&lt;Row&gt;();

    public void addColl(String type, String label) {
        Col col = new Col(type, label);
        _cols.add(col);
    }

    public void addRow(Cell... cells) {
        Row row = new Row();
        row.addCells(cells);
        _rows.add(row);
    }

    public List&lt;Col&gt; getCols() {
        return _cols;
    }

    public List&lt;Row&gt; getRows() {
        return _rows;
    }
}
</pre></p>
<h2>Conclusion</h2>
<p>The simplest and most straightforward solution to generate an &#8216;application/json&#8217; response seemed to me to use the @ResponseBody annotation as shown above. If you need more control about the serialization of the JSON bean objects on the server side, e.g. if you need a special representation of <i>java.util.Date</i> attributes, you have to use Annotations as described in <a href="http://wiki.fasterxml.com/JacksonAnnotations">Jackson Core</a> documenation.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/rwehner.wordpress.com/55/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/rwehner.wordpress.com/55/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/rwehner.wordpress.com/55/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/rwehner.wordpress.com/55/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/rwehner.wordpress.com/55/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/rwehner.wordpress.com/55/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/rwehner.wordpress.com/55/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/rwehner.wordpress.com/55/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/rwehner.wordpress.com/55/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/rwehner.wordpress.com/55/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/rwehner.wordpress.com/55/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/rwehner.wordpress.com/55/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/rwehner.wordpress.com/55/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/rwehner.wordpress.com/55/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=rwehner.wordpress.com&amp;blog=12151074&amp;post=55&amp;subd=rwehner&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://rwehner.wordpress.com/2010/06/09/2-ways-to-create-json-response-for-ajax-request-in-spring3/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/4305d42eb608425221482144a4642d9e?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">rwehner</media:title>
		</media:content>
	</item>
		<item>
		<title>A simple way to create git repository on a server machine connecting via ssh</title>
		<link>http://rwehner.wordpress.com/2010/03/01/a-simple-way-to-create-git-repository-on-a-server-machine-connecting-via-ssh/</link>
		<comments>http://rwehner.wordpress.com/2010/03/01/a-simple-way-to-create-git-repository-on-a-server-machine-connecting-via-ssh/#comments</comments>
		<pubDate>Mon, 01 Mar 2010 15:35:07 +0000</pubDate>
		<dc:creator>rwehner</dc:creator>
				<category><![CDATA[git]]></category>

		<guid isPermaLink="false">http://rwehner.wordpress.com/?p=41</guid>
		<description><![CDATA[Situation: Let&#8217;s assume following situation: We have a folder ˜/workshop , that contains the project on a local machine Our project folder workshop is not a git repository yet We want to have a server that hosts the workshop project and new developer can get the repository using a &#8216;git clone &#8230;&#8217; command On server [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=rwehner.wordpress.com&amp;blog=12151074&amp;post=41&amp;subd=rwehner&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h2>Situation:</h2>
<p>Let&#8217;s assume following situation:</p>
<ul>
<li>We have a folder <em>˜/workshop</em> , that contains the project on a local machine</li>
<li>Our project folder <em>workshop</em> is not a git repository yet</li>
<li>We want to have a server that hosts the workshop project and new developer can get the repository using a &#8216;git clone &#8230;&#8217; command</li>
<li>On server site, the new repository should be located unter <em>˜/gitrepos/workshop.git</em>.</li>
</ul>
<p>To simplify the following steps i will use the machine <em>localhost</em> as the server machine.</p>
<h2>Create a working copy repository</h2>
<p>First, create a new local git repository and add all files within this folder.</p>
<pre>cd ˜/workshop
git init
git add .
git commit -m "initial repository creation"
</pre>
<h2>Create the bare repository</h2>
<p>Then we have to create a bare repository on the server side. Let&#8217;s assume the user<em> ralfwehner</em> is the repository admin user on server side. For this step i will show two alternative ways:<br />
<strong>a)</strong> We clone the server&#8217;s repositiory on the client machine and copy it via scp up to the server:</p>
<pre>git clone --bare .git ../workshop.git
scp -r ../workshop.git ralfwehner@localhost:/Users/ralfwehner/gitrepos/workspace.git
</pre>
<p><strong>b)</strong> We create a new empty repository on the server side and copy the developer&#8217;s repository from client machine to server (recommended when using difference git versions on server and clients):<br />
So, first create the bare repository on server side:</p>
<pre>sudo -u ralfwehner mkdir -m 770 /Users/ralfwehner/gitrepos/workshop.git
cd /Users/ralfwehner/gitrepos/workshop.git
sudo -u ralfwehner git --bare init --shared=group
</pre>
<p>From client side the developer&#8217;s project must be pushed into the new bare server repository:</p>
<pre>git remote add origin ssh://ralfwehner@dev-server/Users/ralfwehner/gitrepos/workshop.git
git push origin master
</pre>
<p>That&#8217;s it. The project &#8216;workshop&#8217; is now available on the server and can be cloned using the git clone command. E.g.:</p>
<pre>cd /tmp/
git clone ralfwehner@localhost:/Users/ralfwehner/gitrepos/workshop.git myclonedworkshop
</pre>
<h2>Synconize local and server repositories</h2>
<h3>Push developers repository to server</h3>
<p>To synchronize the changes checked in into the local developer&#8217;s project to the server repository:</p>
<pre>git push</pre>
<h3>Pull or merge the server repository into developer&#8217;s one</h3>
<p>This command synchronizes the server&#8217;s repository to the local developer&#8217;s one. By this step changes made from other developers that pushed their stuff up to the server will be merged into the local repository.</p>
<pre>git pull . remotes/origin/master</pre>
<h2>Checkout a project from server</h2>
<p>In git terminology the checkout of a projekt can be understood as a clone of a git repository from a server to the developer&#8217;s local machine. You can do this simply by:</p>
<pre>
mkdir myNewWorkspace &amp;&amp; cd myNewWorkspace
git clone ssh://localhost/Users/ralfwehner/gitrepos/workshop.git
</pre>
<p>The new created project can be pushed and pulled with:</p>
<pre>
cd workshop
... do you changes...
git push
... merge changes made from other users...
git pull
</pre>
<h2>Heads up for Mac OS X users as i&#8217;m, too</h2>
<p>There is a problem using the ssh commands to connecto to the git server which can end in error messages like: &#8216;bash: git-upload-pack: command not found&#8217; on some machines. I&#8217;ve found this <a href="http://pencilcasestudios.github.com/article/2009/04/03/when-git-clone-does-not-work-on-mac-os-x/">article</a> that describe the problem and the solution more precisely.</p>
<p>For short, the solution is to create the symbolic link <em>.bashrc</em> to the <em>.profile</em> file:</p>
<pre>server$ cd ~
server$ ln -s .profile .bashrc
</pre>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/rwehner.wordpress.com/41/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/rwehner.wordpress.com/41/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/rwehner.wordpress.com/41/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/rwehner.wordpress.com/41/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/rwehner.wordpress.com/41/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/rwehner.wordpress.com/41/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/rwehner.wordpress.com/41/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/rwehner.wordpress.com/41/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/rwehner.wordpress.com/41/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/rwehner.wordpress.com/41/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/rwehner.wordpress.com/41/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/rwehner.wordpress.com/41/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/rwehner.wordpress.com/41/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/rwehner.wordpress.com/41/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=rwehner.wordpress.com&amp;blog=12151074&amp;post=41&amp;subd=rwehner&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://rwehner.wordpress.com/2010/03/01/a-simple-way-to-create-git-repository-on-a-server-machine-connecting-via-ssh/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/4305d42eb608425221482144a4642d9e?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">rwehner</media:title>
		</media:content>
	</item>
		<item>
		<title>Mockito &#8211; some programming examples</title>
		<link>http://rwehner.wordpress.com/2010/02/23/mockito-some-useful-programming-examples/</link>
		<comments>http://rwehner.wordpress.com/2010/02/23/mockito-some-useful-programming-examples/#comments</comments>
		<pubDate>Tue, 23 Feb 2010 20:56:52 +0000</pubDate>
		<dc:creator>rwehner</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[JUnit]]></category>
		<category><![CDATA[junit]]></category>
		<category><![CDATA[mockito]]></category>

		<guid isPermaLink="false">http://rwehner.wordpress.com/?p=4</guid>
		<description><![CDATA[My favorite mocking library in JAVA is Mockito. It is absolutely great! So, in this post i want to show some programming examples how to use Mockito in your JUnit test code. I don&#8217;t want to write a tutorial or a howto, this is just a summary of programming examples for JAVA programmers who are [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=rwehner.wordpress.com&amp;blog=12151074&amp;post=4&amp;subd=rwehner&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>My favorite mocking library in JAVA is Mockito. It is absolutely great!</p>
<p>So, in this post i want to show some programming examples how to use Mockito in your JUnit test code. I don&#8217;t want to write a tutorial or a howto, this is just a summary of programming examples for JAVA programmers who are familiar with Mockito.</p>
<p><em><strong>Capturing method arguments from Mocks for further assertions:</strong></em><br />
If you are using the version 1.8 and above you can use the <code>ArgumentCaptor</code>. The ArgumentCapture gives you a way to get one or more Arguments of a mocked method that was called before. Use the ArgumentCapture only if need to evaluate complex objects or objects that were created outside your junit test code. If you just want to verify the proper call of a simple mocked method, its better to use a simple <code>verify(mock).yourMethod()</code>. This makes your test code more readable.</p>
<p>So, start working with ArgumentCaptures with code:</p>
<p><pre class="brush: java;">
package de.wehner.mockito.samples;

import static org.junit.Assert.assertEquals;

import static org.mockito.Matchers.any;
import static org.mockito.Matchers.argThat;

import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
public class MockitoSampleTests {

    @Test
    public void testInvideJohn() {
        ArgumentCaptor&lt;Person&gt; argument = ArgumentCaptor.forClass(Person.class);
        Party party = mock(Party.class);

        Person john = new Person(&quot;John&quot;);
        Person peter = new Person(&quot;Peter&quot;);

        // Peter invites John to the party
        peter.invideToParty(john, party);

        verify(party).addGuest(argument.capture());
        // verify John was invited
        assertEquals(&quot;John&quot;, argument.getValue().getName());
    }
}
</pre></p>
<p>And this is the <em>Person</em>:</p>
<p><pre class="brush: java;">
package de.wehner.mockito.samples;

public class Person {

    private final String _name;

    public Person(String name) {
        super();
        _name = name;
    }

    public String getName() {
        return _name;
    }

    public void invideToParty(Person friend, Party party) {
        party.addGuest(friend);
    }
}
</pre></p>
<p>Another way to solve this problem is to use a helper class (here this this the <em>Holder&lt;&gt;</em>) that is final and must be used in combination with the <em>BaseMatcher&lt;&gt;</em> class from Mockito.</p>
<p><pre class="brush: java;">
package de.wehner.mockito.samples;

import static org.junit.Assert.assertEquals;

import static org.mockito.Matchers.*;

import static org.mockito.Mockito.*;

import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.hamcrest.core.AnyOf;
import org.junit.Test;
import org.mockito.ArgumentCaptor;

public class MockitoSampleTests {

    @Test
    public void testInvideJohn() {
        ...
    }

    public class Holder&lt;T&gt; {
        private T _value;

        public Holder() {
        }

        public Holder(T value) {
            _value = value;
        }

        public T get() {
            return _value;
        }

        public void set(T value) {
            _value = value;
        }
    }

    @Test
    public void testInvideJaneAndJohn() {
        Party party = mock(Party.class);
        Person peter = new Person(&quot;Peter&quot;);
        Person jane = new Person(&quot;Jane&quot;);
        Person john = new Person(&quot;John&quot;);

        // &quot;listen&quot; to invocations of Party.addGuest() method
        final Holder&lt;Person&gt; lastInvited = new Holder&lt;Person&gt;();
        doNothing().when(party).addGuest(argThat(new BaseMatcher&lt;Person&gt;() {

            @Override
            public boolean matches(Object arg0) {
                lastInvited.set((Person) arg0);
                return true;
            }

            @Override
            public void describeTo(Description arg0) {
            }
        }));

        // Peter invites his friends
        peter.invideToParty(jane, party);
        peter.invideToParty(john, party);

        // verify 2 guests are invited and John is the last one
        verify(party, times(2)).addGuest(any(Person.class));
        assertEquals(john, lastInvited.get());
    }
}
</pre></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/rwehner.wordpress.com/4/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/rwehner.wordpress.com/4/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/rwehner.wordpress.com/4/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/rwehner.wordpress.com/4/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/rwehner.wordpress.com/4/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/rwehner.wordpress.com/4/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/rwehner.wordpress.com/4/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/rwehner.wordpress.com/4/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/rwehner.wordpress.com/4/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/rwehner.wordpress.com/4/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/rwehner.wordpress.com/4/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/rwehner.wordpress.com/4/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/rwehner.wordpress.com/4/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/rwehner.wordpress.com/4/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=rwehner.wordpress.com&amp;blog=12151074&amp;post=4&amp;subd=rwehner&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://rwehner.wordpress.com/2010/02/23/mockito-some-useful-programming-examples/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/4305d42eb608425221482144a4642d9e?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">rwehner</media:title>
		</media:content>
	</item>
	</channel>
</rss>
