<?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>Angelo&#039;s Blog</title>
	<atom:link href="http://angelozerr.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://angelozerr.wordpress.com</link>
	<description>@Repository about my passion</description>
	<lastBuildDate>Sun, 02 Jun 2013 14:33:50 +0000</lastBuildDate>
	<language>fr</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='angelozerr.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Angelo&#039;s Blog</title>
		<link>http://angelozerr.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://angelozerr.wordpress.com/osd.xml" title="Angelo&#039;s Blog" />
	<atom:link rel='hub' href='http://angelozerr.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Mongo JEE [step6]</title>
		<link>http://angelozerr.wordpress.com/2013/05/15/mongo_jee_step6/</link>
		<comments>http://angelozerr.wordpress.com/2013/05/15/mongo_jee_step6/#comments</comments>
		<pubDate>Wed, 15 May 2013 21:41:30 +0000</pubDate>
		<dc:creator>angelozerr</dc:creator>
				<category><![CDATA[Apache CXF]]></category>
		<category><![CDATA[Mongo JEE]]></category>
		<category><![CDATA[MongoDB]]></category>

		<guid isPermaLink="false">http://angelozerr.wordpress.com/?p=7337</guid>
		<description><![CDATA[In [step5] we have modified our JAX-RS LogsService to returns List of Pojo by using : MongoJack to get List of Pojo from Mongo DB. Apache CXF JSONProvider based on Jettison to serialize the Pojo Log to JSON stream. With Pojo Mapper MongoJack, the LogsService looks like this: When I have studied how to use [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=angelozerr.wordpress.com&#038;blog=10338309&#038;post=7337&#038;subd=angelozerr&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>In <a href="http://angelozerr.wordpress.com/2013/05/14/mongo_jee_step5/">[step5]</a> we have modified our JAX-RS LogsService to returns List of Pojo by using :</p>
<ul>
<li><a href="http://mongojack.org/">MongoJack</a> to get List of Pojo from Mongo DB.
  </li>
<li><a href="http://cxf.apache.org/docs/jax-rs.html">Apache CXF</a> <strong>JSONProvider</strong> based on <a href="http://jettison.codehaus.org/">Jettison</a> to serialize the Pojo Log to JSON stream.
</ul>
<p>With Pojo Mapper MongoJack, the LogsService looks like this: </p>
<pre class="brush: java; title: ; notranslate">@GET
@Path(&quot;/all&quot;)
@Produces(MediaType.APPLICATION_JSON)
public List&lt;Log&gt; findAll() {
	DB db = MongoHolder.connect().getDB(&quot;websites&quot;);
	DBCollection dbColl = db.getCollection(&quot;logs&quot;);
	JacksonDBCollection&lt;Log, String&gt; coll = JacksonDBCollection.wrap(
          dbColl, Log.class, String.class);
	return coll.find().toArray();
}</pre>
<p>When I have studied how to use Mongo in JEE Application with JAX-RS, I have read the great article <a href="http://architects.dzone.com/articles/modern-web-apps-using-jax-rs">Modern Web Apps using JAX-RS, MongoDB, JSON, and jQuery</a>. After reading this article, I told me &quot;why we need to use a Pojo Mapper with JAX-RS although Mongo manages their data with BSON representation?&quot;, on other words why we could not develop our JAX-RS service like this : </p>
<pre class="brush: java; title: ; notranslate">@GET
@Path(&quot;/all&quot;)
@Produces(MediaType.APPLICATION_JSON)
public DBCursor findAll() {
	DB db = MongoHolder.connect().getDB(&quot;websites&quot;);
	DBCollection coll = db.getCollection(&quot;logs&quot;);
	return coll.find();
}</pre>
<p>Using DBCursor avoids to create a Pojo and avoids to serialize the Pojo to JSON. So I have decided to create <a href="https://github.com/angelozerr/mongo-jee">Mongo JEE</a> project. In this article we will modify our JAX-RS LogsService to use Mongo DBCursor in the service by using the JAX-RS provider of the Mongo JEE.</p>
<p><span id="more-7337"></span></p>
<h2>Download</h2>
<p>You can download <a href="https://dl.dropboxusercontent.com/u/2903680/wordpress-blog/tutoriels/java/mongo-jee/step6.zip">step6.zip</a> which hosts the Eclipse Project which contains the explained sources in this article. To use it, unzip it and import this project in your Eclipse workspace. As soon as you will do that, your workspace will look like this : </p>
<p><img src="http://angelozerr.files.wordpress.com/2013/05/mongojee_step61.png?w=595" /></p>
<p>This Eclipse project contains: </p>
<ul>
<li><a href="#LogService">LogService</a> is JAX-RS service which returns Mongo DBCursor.
  </li>
<li><a href="#MyJaxrsApplication">MyJaxrsApplication</a> is JAX-RS application which register the JAX-RS LogsService and Mongo JEE JAX-RS providers.
  </li>
<li><a href="#web.xml">web.xml</a> declares the Apache CXF JAX-RS implementation and set MyJaxrsApplication as JAX-RS Application
  </li>
</ul>
<h3>Download JARs with maven</h3>
<p>This project contains the same dependencies than <a href="http://angelozerr.wordpress.com/2013/05/14/mongo_jee_step4/">step4</a> (no need to use MongoJack and Apache CXF JSONProvider).</p>
<h2>LogsService &#8211; DBCursor</h2>
<p>Modify org.samples.mongodb.services.<strong>LogsService</strong> like this: </p>
<pre class="brush: java; title: ; notranslate">package org.samples.mongodb.services;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.jee.MongoHolder;

@Path(&quot;/logs&quot;)
public class LogsService {

	@GET
	@Path(&quot;/all&quot;)
	@Produces(MediaType.APPLICATION_JSON)
	public DBCursor findAll() {
		DB db = MongoHolder.connect().getDB(&quot;websites&quot;);
		DBCollection coll = db.getCollection(&quot;logs&quot;);
		return coll.find();
	}

}</pre>
<h2>Without Mongo JEE</h2>
<p>In this step we will not use Mongo JEE to manage DBCursor with JAX-RS. We will see the problem without JAX-RS provider and we will fix it by developping our own JAX-RS provider.</p>
<h3>MyJaxrsApplication  &#8211; with problems</h3>
<p>At this step we will use the MyJaxrsApplication of the previous article <a href="http://angelozerr.wordpress.com/2013/05/14/mongo_jee_step5/‎">[step5]</a> : </p>
<pre class="brush: java; title: ; notranslate">package org.samples.mongodb.jaxrs;

import java.util.HashSet;
import java.util.Set;

import javax.ws.rs.core.Application;

import org.samples.mongodb.services.LogsService;

public class MyJaxrsApplication extends Application {

	private final Set&lt;Object&gt; singletons;

	public MyJaxrsApplication() {
		singletons = new HashSet&lt;Object&gt;();
		addSingleton(new LogsService());
	}

	protected void addSingleton(Object singleton) {
		singletons.add(singleton);
	}

	@Override
	public Set&lt;Object&gt; getSingletons() {
		return singletons;
	}
}</pre>
<h3 id="test">Test LogsService &#8211; with problem</h3>
<ul>
<li>run the StartServer class to start the server.</li>
<li>access with your webbrowser to the URL <a href="http://localhost:8081/mongo/jaxrs/logs/all">http://localhost:8081/mongo/jaxrs/logs/all/</a> and you will see the following error :
<pre class="brush: plain; title: ; notranslate">No message body writer has been found for response class DBCursor.</pre>
</li>
</ul>
<p>This error occurs because Apache CXF <strong>doesn&rsquo;t find JAX-RS provider to serialize the DBCursor to JSON</strong>. Mongo JEE provides those JAX-RS provider but before using it, it can be interesting to develop it (with simply mean).</p>
<h3>MyDBCursorProvider</h3>
<p>To fix the previous problem, create JAX-RS provider org.samples.mongodb.jaxrs.<strong>MyDBCursorProvider</strong> to serialize DBCursor to JSON like this:</p>
<pre class="brush: java; title: ; notranslate">package org.samples.mongodb.jaxrs;

import java.io.IOException;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import javax.ws.rs.Consumes;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyWriter;
import javax.ws.rs.ext.Provider;

import com.mongodb.DBCursor;
import com.mongodb.jee.util.JSON;

@Provider
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class MyDBCursorProvider implements MessageBodyWriter&lt;DBCursor&gt; {

	@Override
	public boolean isWriteable(Class&lt;?&gt; atype, Type genericType,
			Annotation[] annotations, MediaType mediaType) {
		if (DBCursor.class.isAssignableFrom(atype)) {
			// the given class type is DBCursor
			return true;
		}
		return false;
	}

	public void writeTo(DBCursor cursor, Class&lt;?&gt; type, Type genericType,
			Annotation[] annotations, MediaType mediaType,
			MultivaluedMap&lt;String, Object&gt; httpHeaders,
			OutputStream entityStream) throws IOException,
			WebApplicationException {

		// Write the DBCursor as JSON array stream.
		JSON.serialize(cursor, entityStream);
	}

	@Override
	public long getSize(DBCursor t, Class&lt;?&gt; type, Type genericType,
			Annotation[] annotations, MediaType mediaType) {
		// Return -1 if the content length cannot be determined
		return -1;
	}

}</pre>
<p>To use our JAX-RS provider, we need to register it in the JAX-RS Application. To do that modify org.samples.mongodb.jaxrs.<strong>MyJaxrsApplication</strong> like this: </p>
<pre class="brush: java; title: ; notranslate">package org.samples.mongodb.jaxrs;

import java.util.HashSet;
import java.util.Set;

import javax.ws.rs.core.Application;

import org.samples.mongodb.services.LogsService;

public class MyJaxrsApplication extends Application {

	private final Set&lt;Class&lt;?&gt;&gt; classes;
	private final Set&lt;Object&gt; singletons;

	public MyJaxrsApplication() {
		classes = new HashSet&lt;Class&lt;?&gt;&gt;();
		addClass(MyDBCursorProvider.class);
		 
		singletons = new HashSet&lt;Object&gt;();
		addSingleton(new LogsService());
	}

	@Override
	public Set&lt;Class&lt;?&gt;&gt; getClasses() {
		return classes;
	}

	protected void addClass(Class&lt;?&gt; clazz) {
		classes.add(clazz);
	}

	protected void addSingleton(Object singleton) {
		singletons.add(singleton);
	}

	@Override
	public Set&lt;Object&gt; getSingletons() {
		return singletons;
	}
}</pre>
<h3 id="test">Test LogsService &#8211; MyDBCursorProvider</h3>
<p>Now we can test our JAX-RS provider : </p>
<ul>
<li>run the StartServer class to start the server.</li>
<li>access with your webbrowser to the URL <a href="http://localhost:8081/mongo/jaxrs/logs/all">http://localhost:8081/mongo/jaxrs/logs/all/</a> to see the JSON array of logs and see the &quot;application/json&quot; of the content type :<br />
<img src="http://angelozerr.files.wordpress.com/2013/05/mongojee_jaxrs_streamingoutput_chrome.png?w=595" />
  </li>
</ul>
<p>You can check that the JSON array is the same than the Mongo JSON array like (see <a href="http://angelozerr.wordpress.com/2013/05/14/mongo_jee_step4/">[step4]</a>).</p>
<h2>With Mongo JEE</h2>
<p>Mongo JEE provides <a href="https://github.com/angelozerr/mongo-jee/tree/master/mongo-jee/src/main/java/com/mongodb/jee/jaxrs/providers">several JAX-RS providers for Mongo</a> and provides too a JAX-RS Application <a href="https://github.com/angelozerr/mongo-jee/blob/master/mongo-jee/src/main/java/com/mongodb/jee/jaxrs/JaxrsMongoApplication.java">JaxrsMongoApplication</a> which registers Mongo JAX-RS providers.</p>
<h3>MyJaxrsApplication &#8211; JaxrsMongoApplication</h3>
<p>Modify MyJaxrsApplication to extend JaxrsMongoApplication  like this: </p>
<pre class="brush: java; title: ; notranslate">package org.samples.mongodb.jaxrs;

import org.samples.mongodb.services.LogsService;

import com.mongodb.jee.jaxrs.JaxrsMongoApplication;

public class MyJaxrsApplication extends JaxrsMongoApplication {

	public MyJaxrsApplication() {
		super.addSingleton(new LogsService());
	}

}</pre>
<p>Run the StartServer class to start the server and check that service works again.</p>
<h3>Remove _id</h3>
<p>The returned JSON stream to the browser, contains  the &quot;_id&quot; key. But it&rsquo;s possible to remove &quot;_id&quot; property .</p>
<p>Modify LogsService like this:</p>
<pre class="brush: java; title: ; notranslate">package org.samples.mongodb.services;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.jee.MongoHolder;

@Path(&quot;/logs&quot;)
public class LogsService {

	@GET
	@Path(&quot;/all&quot;)
	@Produces(MediaType.APPLICATION_JSON)
	public DBCursor findAll() {
		DB db = MongoHolder.connect().getDB(&quot;websites&quot;);
		DBCollection coll = db.getCollection(&quot;logs&quot;);
		BasicDBObject fieldsToIgnore = new BasicDBObject(&quot;_id&quot;, false);
		return coll.find(null, fieldsToIgnore);
	}

}</pre>
<p>Restart the server and test it to check that every thing is working again.</p>
<h2>Conclusion</h2>
<p>In this article we have seen how to manage Mongo structure with JAX-RS service by using Mongo JEE. </p>
<p>In the next article [step7] we will add a new method service to return paginated logs list.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/angelozerr.wordpress.com/7337/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/angelozerr.wordpress.com/7337/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=angelozerr.wordpress.com&#038;blog=10338309&#038;post=7337&#038;subd=angelozerr&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://angelozerr.wordpress.com/2013/05/15/mongo_jee_step6/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/4c3176f508ba2f224d3b00dce0ca6c2a?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">akrogen</media:title>
		</media:content>

		<media:content url="http://angelozerr.files.wordpress.com/2013/05/mongojee_step61.png" medium="image" />

		<media:content url="http://angelozerr.files.wordpress.com/2013/05/mongojee_jaxrs_streamingoutput_chrome.png" medium="image" />
	</item>
		<item>
		<title>Mongo JEE [step5]</title>
		<link>http://angelozerr.wordpress.com/2013/05/14/mongo_jee_step5/</link>
		<comments>http://angelozerr.wordpress.com/2013/05/14/mongo_jee_step5/#comments</comments>
		<pubDate>Tue, 14 May 2013 22:42:57 +0000</pubDate>
		<dc:creator>angelozerr</dc:creator>
				<category><![CDATA[Apache CXF]]></category>
		<category><![CDATA[Mongo JEE]]></category>
		<category><![CDATA[MongoDB]]></category>

		<guid isPermaLink="false">http://angelozerr.wordpress.com/?p=7335</guid>
		<description><![CDATA[In [step4] we have tranformed our LogsServlet to a JAX-RS LogsService which uses JAX-RS StreamingOutput. At this step the service returns JAX-RS Response : It&#8217;s very difficult to use this service in other context than JAX-RS (like using the service in fat client, using the service in a JUnit etc). Imagine you wish to write [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=angelozerr.wordpress.com&#038;blog=10338309&#038;post=7335&#038;subd=angelozerr&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>In <a href="http://angelozerr.wordpress.com/2013/05/14/mongo_jee_step4/">[step4]</a> we have tranformed our LogsServlet to a JAX-RS LogsService which uses JAX-RS StreamingOutput. At this step the service returns JAX-RS Response :</p>
<pre class="brush: java; title: ; notranslate">@Path(&quot;/logs&quot;)
public class LogsService {

  @Path(&quot;/all&quot;)
  public Response findAll() {
    ...
  }
}
</pre>
<p>It&rsquo;s very difficult to use this service in other context than JAX-RS (like using the service in fat client, using the service in a JUnit etc). Imagine you wish to write some JUnits which tests that our LogsService service returns some logs. With our current logs service, it&rsquo;s hard to write that : </p>
<pre class="brush: java; title: ; notranslate">
@Test
public void testNotEmptyLogs() {
  LogsService service = new LogsService();
  Response jaxrsResponse = service.findAll();
  // How to get the list of logs to test that logs are not empty?
}
</pre>
<p>When you develop a service, the best mean is that you don&rsquo;t link it to a framework. For instance : </p>
<ul>
<li>if your service returns list of Pojo :
<pre class="brush: java; title: ; notranslate">@Path(&quot;/logs&quot;)
public class LogsService {

  @Path(&quot;/all&quot;)
  public List&lt;Log&gt; findAll() {
    ...
  }
}
</pre>
<p>you can write this test : </p>
<pre class="brush: java; title: ; notranslate">
@Test
public void testNotEmptyLogs() {
  LogsService service = new LogsService();
  List&lt;Pojo&gt; pojoList = service.findAll();
  Assert.assertFalse(pojoList.isEmpty());
}
</pre>
</li>
<li>if your service returns a Mongo DBCursor :
<pre class="brush: java; title: ; notranslate">@Path(&quot;/logs&quot;)
public class LogsService {

  @Path(&quot;/all&quot;)
  public DBCursor findAll() {
    ...
  }
}
</pre>
<p>you can write this test : </p>
<pre class="brush: java; title: ; notranslate">
@Test
public void testNotEmptyLogs() {
  LogsService service = new LogsService();
  DBCursor cursor= service.findAll();
  Assert.assertFalse(cursor.toArray().isEmpty());
}
</pre>
</li>
</ul>
<p>With JAX-RS you can write <strong>services which returns anything</strong> (List of Pojo, Mongo DBCursor), but it&rsquo;s not magic and <strong>you need JAX-RS provider</strong> to serialize (in our case) List of Pojo, DBCursor etc into JSON stream : </p>
<ul>
<li>in this article we will see how to <strong>manage JAX-RS service with Pojo</strong>. We will use <a href="http://mongojack.org/">MongoJack</a> to get list of Log Pojo from Mongo DB and the Apache CXF JSONProvider, the JAX-RS provider to serialize Pojo to a JSON stream.
  </li>
<li>in the next article <a href="http://angelozerr.wordpress.com/2013/05/15/mongo_jee_step6/">[step6]</a> we will see how to <strong>manage JAX-RS service with Mongo DBCursor</strong> by using the <a href="https://github.com/angelozerr/mongo-jee">Mongo JEE</a> JAX-RS providers.
  </li>
</ul>
<p><span id="more-7335"></span></p>
<h2>Download</h2>
<p>You can download <a href="https://dl.dropboxusercontent.com/u/2903680/wordpress-blog/tutoriels/java/mongo-jee/step5.zip">step5.zip</a> which hosts the Eclipse Project which contains the explained sources in this article. To use it, unzip it and import this project in your Eclipse workspace. As soon as you will do that, your workspace will look like this : </p>
<p><img src="http://angelozerr.files.wordpress.com/2013/05/mongojee_step51.png?w=595" /></p>
<p>This Eclipse project contains: </p>
<ul>
<li><a href="#LogService">LogService</a> is JAX-RS service which returns list of Pojo by using MongoJack.
  </li>
<li><a href="#MyJaxrsApplication">MyJaxrsApplication</a> is JAX-RS application which register the JAX-RS LogsService.
  </li>
<li><a href="#web.xml">web.xml</a> declares the Apache CXF JAX-RS implementation and set MyJaxrsApplication as JAX-RS Application
  </li>
</ul>
<h3>Download JARs with maven</h3>
<p>This project contains the same dependencies than <a href="http://angelozerr.wordpress.com/2013/05/14/mongo_jee_step4/">step4</a>, and additional dependencies :</p>
<ul>
<li>in our case we need org.apache.cxf.jaxrs.provider.json.<strong>JSONProvider</strong>, the JAX-RS provider of Apache CXF used to serialize/deserialize Pojo (which are annotated with JAXB annotations) to JSON stream :
<pre class="brush: xml; title: ; notranslate">&lt;dependency&gt;
	&lt;groupId&gt;org.apache.cxf&lt;/groupId&gt;
	&lt;artifactId&gt;cxf-rt-rs-extension-providers&lt;/artifactId&gt;
	&lt;version&gt;2.7.4&lt;/version&gt;
&lt;/dependency&gt;
</pre>
</li>
<li>JSONProvider of Apache CXF uses <a href="http://jettison.codehaus.org/">jettison</a> to manage JSON read/write :
<pre class="brush: xml; title: ; notranslate">&lt;dependency&gt;
	&lt;groupId&gt;org.codehaus.jettison&lt;/groupId&gt;
	&lt;artifactId&gt;jettison&lt;/artifactId&gt;
	&lt;version&gt;1.3.3&lt;/version&gt;
&lt;/dependency&gt;
</pre>
<li>Pojo Mapper MongoJack is used to get Pojo from Mongo DB like we have explained in the <a href="http://angelozerr.wordpress.com/2013/05/10/mongo_jee_step1/#MongoJack">step1</a>:
<pre class="brush: xml; title: ; notranslate">&lt;dependency&gt;
	&lt;groupId&gt;org.mongojack&lt;/groupId&gt;
	&lt;artifactId&gt;mongojack&lt;/artifactId&gt;
	&lt;version&gt;2.0.0-RC5&lt;/version&gt;
&lt;/dependency&gt;</pre>
</li>
<ul>
<h2>What is JAX-RS provider?</h2>
<p>I suggest you to read <a href="http://stackoverflow.com/questions/13557442/what-does-provider-in-jax-rs-mean">What does Provider in JAX-RS mean</a>? In our case we will need <strong>Entity Providers</strong></p>
<p><cite>These providers control the mapping of data representations (like XML, JSON, CSV) to their Java object equivalents.</cite></p>
<p>We will use Apache CXF org.apache.cxf.jaxrs.provider.json.<strong>JSONProvider</strong> which uses <a href="http://jettison.codehaus.org/">jettison</a>.</p>
<h2>Pojo Log</h2>
<p>Create a Pojo Log like we have explained in the <a href="http://angelozerr.wordpress.com/2013/05/10/mongo_jee_step1/">[step1]</a> and add the <strong>JAXB @XmlRootElement</strong> annotation : </p>
<pre class="brush: java; title: ; notranslate">package org.samples.mongodb.services;

import java.util.Date;

import javax.persistence.Id;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Log {

	@Id
	private String id;

	private String url;
	private Date created;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public Date getCreated() {
		return created;
	}

	public void setCreated(Date created) {
		this.created = created;
	}

}
</pre>
<h2>LogsService</h2>
<p>Create the org.samples.mongodb.services.<strong>LogsService</strong> which uses MongoJack and returns list of Pojo Log like this : </p>
<pre class="brush: java; title: ; notranslate">package org.samples.mongodb.services;

import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.mongojack.JacksonDBCollection;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.jee.MongoHolder;

@Path(&quot;/logs&quot;)
public class LogsService {

	@GET
	@Path(&quot;/all&quot;)
	@Produces(MediaType.APPLICATION_JSON)
	public List&lt;Log&gt; findAll() {

		DB db = MongoHolder.connect().getDB(&quot;websites&quot;);
		DBCollection dbColl = db.getCollection(&quot;logs&quot;);

		JacksonDBCollection&lt;Log, String&gt; coll = JacksonDBCollection.wrap(
				dbColl, Log.class, String.class);
		return coll.find().toArray();
	}

}
</pre>
<h2 id="test">Test LogsService</h2>
<ul>
<li>run the StartServer class to start the server.</li>
<li>access with your webbrowser to the URL <a href="http://localhost:8081/mongo/jaxrs/logs/all">http://localhost:8081/mongo/jaxrs/logs/all/</a> to see the JSON array of logs and see the &quot;application/json&quot; of the content type :<br />
<img src="http://angelozerr.files.wordpress.com/2013/05/mongojee_jaxrs_pojomapper_chrome.png?w=595" />
  </li>
</ul>
<p>You can check that the JSON array is not the same than the Mongo JSON array like (see <a href="http://angelozerr.wordpress.com/2013/05/14/mongo_jee_step4/">[step4]</a>) : </p>
<pre class="brush: java; title: ; notranslate">{&quot;log&quot;:
  [{&quot;created&quot;:&quot;2013-05-10T16:17:37.515+02:00&quot;,
    &quot;id&quot;:&quot;518d01813bfe01bef797d031&quot;,
    &quot;url&quot;:&quot;http:\/\/www.mongodb.org\/&quot;}
  ...
  ]
}
</pre>
<h2>JSONProvider Troubleshooting</h2>
<p>When I have tried to develop this article, I have spent a long time to use correctly JSONProvider. I had every time the error : </p>
<pre class="brush: plain; title: ; notranslate">No message body writer has been found for response class ArrayList.</pre>
<p>Here the 3 rules to respect, when your service returns a List of Pojo, to avoid this error : </p>
<ol>
<li>check org.apache.cxf.jaxrs.provider.json.<strong>JSONProvideris in the classpath</strong>. Since 2.6.x, this JAX-RS provider is hosted in the <strong>cxf-rt-rs-extension-providers*.jar</strong>.
  </li>
<li>check that <strong>Jettison*.jar is in the classpath</strong>. JSONProvider uses Jettison to read/write JSON.
  </li>
<li>check that your Pojo is annotated with <strong>JAXB @XmlRootElement annotation</strong>.
  </li>
</ol>
<h2>Conclusion</h2>
<p>In this article we have modified our LogsService to return a List of Pojo getted from the Mongo DB with MongoJack. Apache CXF JSONProvider is used in this case to serialize list of Pojo to a JSON array. Using Pojo witth Mongo and JAX-RS works great but :</p>
<ul>
<li>you need to create a Pojo.
  </li>
<li>you need to annotate the Pojo with JAXB annotation.
  </li>
<li>you need to serialize the Pojo to a JSON stream.
  </li>
</ul>
<p>Mongo stores their data with BSON representation (looks like JSON), so .., why we could not to use this stream instead of creating a Pojo? In the next article <a href="http://angelozerr.wordpress.com/2013/05/15/mongo_jee_step6/">[step6]</a>, we will modify our LogsService to use Mongo DBCuror instead of List of Pojo.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/angelozerr.wordpress.com/7335/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/angelozerr.wordpress.com/7335/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=angelozerr.wordpress.com&#038;blog=10338309&#038;post=7335&#038;subd=angelozerr&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://angelozerr.wordpress.com/2013/05/14/mongo_jee_step5/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/4c3176f508ba2f224d3b00dce0ca6c2a?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">akrogen</media:title>
		</media:content>

		<media:content url="http://angelozerr.files.wordpress.com/2013/05/mongojee_step51.png" medium="image" />

		<media:content url="http://angelozerr.files.wordpress.com/2013/05/mongojee_jaxrs_pojomapper_chrome.png" medium="image" />
	</item>
		<item>
		<title>Mongo JEE [step4]</title>
		<link>http://angelozerr.wordpress.com/2013/05/14/mongo_jee_step4/</link>
		<comments>http://angelozerr.wordpress.com/2013/05/14/mongo_jee_step4/#comments</comments>
		<pubDate>Tue, 14 May 2013 13:16:48 +0000</pubDate>
		<dc:creator>angelozerr</dc:creator>
				<category><![CDATA[Apache CXF]]></category>
		<category><![CDATA[Mongo JEE]]></category>

		<guid isPermaLink="false">http://angelozerr.wordpress.com/?p=7291</guid>
		<description><![CDATA[In [step3] we have improved our LogsServlet by using Mongo JEE. Servlet works well but it&#8217;s an old school mean. Using servlet in this case will causes problem when you will wish to manage several operations (find all logs, find paginated logs, insert logs, etc). To manage that, you will have to create a servlet [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=angelozerr.wordpress.com&#038;blog=10338309&#038;post=7291&#038;subd=angelozerr&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>In <a href="http://angelozerr.wordpress.com/2013/05/12/mongo_jee_step3/">[step3]</a> we have improved our LogsServlet by using <a href="https://github.com/angelozerr/mongo-jee">Mongo JEE</a>. Servlet works well but it&rsquo;s an old school mean. </p>
<p><strong>Using servlet</strong> in this case will causes problem when you will <strong>wish to manage several operations</strong>  (find all logs, find paginated logs, insert logs, etc). To manage that, you will have to <strong>create a servlet per operations</strong> or <strong>manage this dispatch at hand</strong> (for instance with a HTTP request dispatch parameter) like this : </p>
<pre class="brush: java; title: ; notranslate">protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  DBCursor cursor = null;
  String dispatch = request.getParameter(&quot;dispatch&quot;);
  if (&quot;all&quot;.equals(dispatch) {
	DB db = mongo.getDB(&quot;websites&quot;);
	DBCollection coll = db.getCollection(&quot;logs&quot;);

	DBCursor cursor = coll.find();
	ServletHelper.writeJson(cursor, response);
  } else if (&quot;page&quot;.equals(dispatch) {
     ...
  }
}</pre>
<p>It exists a lot of Java Web Framwework (<a href="http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/mvc.html">Spring MVC</a>, <a href="https://developers.google.com/web-toolkit/?hl=fr">GWT</a>, <a href="http://wicket.apache.org/">Wicket</a>, <a href="http://www.playframework.com/">Play</a>!, <a href="http://www.oracle.com/technetwork/java/javaee/javaserverfaces-139869.html">JSF</a>, <a href="http://struts.apache.org/development/2.x/">Struts2</a>, etc) which provides a controller framework which fix this problem. <a href="https://jax-rs-spec.java.net/">JAX-RS</a> provides too an elegant mean to fix that : <strong>you develop a service class and you create a method for each operations</strong>. Here a JAX-RS sample : </p>
<pre class="brush: java; title: ; notranslate">@Path(&quot;/logs&quot;)
public class LogsService {

	@Path(&quot;/all&quot;)
	public Response findAll() {
	...
	}
	
	@Path(&quot;/page&quot;)
	public Response findPage() {
	...
	}
	
}</pre>
<p>Once this JAX-RS service will be deployed, you will able to call :</p>
<ul>
<li><a href="http://localhost:8081/mongo/jaxrs/logs/all" rel="nofollow">http://localhost:8081/mongo/jaxrs/logs/all</a> to returns list of logs.
  </li>
<li><a href="http://localhost:8081/mongo/jaxrs/logs/page" rel="nofollow">http://localhost:8081/mongo/jaxrs/logs/page</a> to returns list of paginated logs.
  </li>
</ul>
<p>In this article we will transform our LogsServlet with JAX-RS <a href="#LogsService">LogsService</a>. We will use <a href="http://cxf.apache.org/docs/jax-rs.html">Apache CXF</a> as JAX-RS implementation.</p>
<p><span id="more-7291"></span></p>
<h2>Download</h2>
<p>You can download <a href="https://dl.dropboxusercontent.com/u/2903680/wordpress-blog/tutoriels/java/mongo-jee/step4.zip">step4.zip</a> which hosts the Eclipse Project which contains the explained sources in this article. To use it, unzip it and import this project in your Eclipse workspace. As soon as you will do that, your workspace will look like this : </p>
<p><img src="http://angelozerr.files.wordpress.com/2013/05/mongojee_step4.png?w=595" /></p>
<p>This Eclipse project contains: </p>
<ul>
<li><a href="#LogService">LogService</a> is JAX-RS service which uses JAX-RS StreamingOutput.
  </li>
<li><a href="#MyJaxrsApplication">MyJaxrsApplication</a> is JAX-RS application which register the JAX-RS LogsService.
  </li>
<li><a href="#web.xml">web.xml</a> declares the Apache CXF JAX-RS implementation and set MyJaxrsApplication as JAX-RS Application
  </li>
</ul>
<h3>Download JARs with maven</h3>
<p>This project contains the same dependencies than <a href="http://angelozerr.wordpress.com/2013/05/12/mongo_jee_step3/">step3</a>, and additional dependencies :</p>
<li>Apache CXF as JAX-RS implementation. To do that I use this maven dependency :
<pre class="brush: xml; title: ; notranslate">&lt;dependency&gt;
	&lt;groupId&gt;org.apache.cxf&lt;/groupId&gt;
	&lt;artifactId&gt;cxf-rt-frontend-jaxrs&lt;/artifactId&gt;
	&lt;version&gt;2.7.4&lt;/version&gt;
&lt;/dependency&gt;</pre>
</li>
</ol>
<p>The project contains the JARs in the lib, but if you wish to download it with maven , see <a href="http://angelozerr.wordpress.com/2013/05/10/mongo_jee_step1/#download-mvn">Download JARs with maven [step1]</a>.</p>
<h2>JAX-RS Overview</h2>
<p><cite>JAX-RS: Java API for RESTful Web Services is a Java programming language API that provides support in creating web services according to the Representational State Transfer (REST) architectural pattern. JAX-RS uses annotations, introduced in Java SE 5, to simplify the development and deployment of web service clients and endpoints.</cite></p>
<p>It exists several JAX-RS implementation like : </p>
<ul>
<li><a href="http://cxf.apache.org/docs/jax-rs.html">Apache CXF</a>.
  </li>
<li><a href="https://jersey.java.net/">Jersey</a>.
  </li>
<li><a href="http://www.jboss.org/resteasy">RESTeasy</a>.
  </li>
<li><a href="http://restlet.org/">Restlet</a>.
  </li>
</ul>
<p>In this article we will use <a href="http://cxf.apache.org/docs/jax-rs.html">Apache CXF</a> but the code of our JAX-RS service is not linked to Apache CXF and other JAX-RS implementation could be used.</p>
<h2 id="LogService">JAX-RS LogsService</h2>
<p>Create org.samples.mongodb.services.<strong>LogsService</strong> like this:</p>
<pre class="brush: java; title: ; notranslate">package org.samples.mongodb.services;

import java.io.IOException;
import java.io.OutputStream;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.StreamingOutput;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.jee.MongoHolder;

@Path(&quot;/logs&quot;)
public class LogsService {

	@GET
	@Path(&quot;/all&quot;)
	@Produces(MediaType.APPLICATION_JSON)
	public Response findAll() {
		DB db = MongoHolder.connect().getDB(&quot;websites&quot;);
		DBCollection coll = db.getCollection(&quot;logs&quot;);
		final DBCursor cursor = coll.find();

		StreamingOutput output = new StreamingOutput() {
			public void write(OutputStream out) throws IOException,
					WebApplicationException {
				com.mongodb.jee.util.JSON.serialize(cursor, out);
			}
		};
		return Response.ok(output).build();
	}

}</pre>
<p>Here some explanation about this code : </p>
<ul>
<li>To tell that a service should be deployed as JAX-RS service, the class must be annoted with javax.ws.rs.<strong>@Path</strong>.<br />
Here we use /logs :</p>
<pre class="brush: java; title: ; notranslate">@Path(&quot;/logs&quot;)
public class LogsService...
</pre>
<p>It means that the URL which will consumes the service will starts with <a href="http://localhost:8080/jaxrs/logs/" rel="nofollow">http://localhost:8080/jaxrs/logs/</a>. If we declare with empty quote @Path(&quot;&quot;), the URL will start with <a href="http://localhost:8080/jaxrs" rel="nofollow">http://localhost:8080/jaxrs</a>.
  </li>
<li>The method findAll is annotated with <strong>@GET</strong>, it means that our service will be available with HTTP GET method.
  </li>
<li>The method findAll is annotated with <strong>@Path(&quot;/all&quot;)</strong>, it means that the service will be available with the following URL <a href="http://localhost:8080/jaxrs/logs/all" rel="nofollow">http://localhost:8080/jaxrs/logs/all</a>
  </li>
<li>The method findAll is annotated with <strong>@Produces(MediaType.APPLICATION_JSON)</strong>, it means that our service will update the HTTP response <strong>content type</strong> with <strong>&quot;application/json&quot;</strong>.
  </li>
<li>javax.ws.rs.core.<strong>StreamingOutput#write</strong> is called when service must write some content in the HTTP response OutputStream. In our case<br />
  we implement it like this to write the mongo cursor as JSON array :  </p>
<pre class="brush: java; title: ; notranslate">  
StreamingOutput output = new StreamingOutput() {
	public void write(OutputStream out) throws IOException,
			WebApplicationException {
		com.mongodb.jee.util.JSON.serialize(cursor, out);
	}
};
</pre>
</li>
</ul>
<h2 id="MyJaxrsApplication">MyJaxrsApplication &#8211; getClasses</h2>
<p>At this step we have defined our JAX-RS LogsService. Now we must indicate to the JAX-RS processor that it must deploy the service. To do that, there are several means (according the JAX-RS processor implementation). A generic mean which works with any JAX-RS processor is to extend  the javax.ws.rs.core.<strong>Application</strong> which provides : </p>
<ul>
<li><strong>getClasses</strong>() which must return a Set of classes of JAX-RS services (and providers : we will see  this notion of JAX-RS provider in the next article <a href="http://angelozerr.wordpress.com/2013/05/14/mongo_jee_step5/">[step5]</a>). The whole JAX-RS services classes which are included in the Set will be instantiated for each request (as soon as the service is called).
  </li>
<li><strong>getSingletons</strong>() which must return a Set of instance which must be singleton. The whole JAX-RS services classes which are included in the Set will be instantiated just one time.  </li>
</ul>
<p>Here we start using getClasses. Create Java class org.samples.mongodb.jaxrs.<strong>MyJaxrsApplication</strong> like this: </p>
<pre class="brush: java; title: ; notranslate">package org.samples.mongodb.jaxrs;

import java.util.HashSet;
import java.util.Set;

import javax.ws.rs.core.Application;

import org.samples.mongodb.services.LogsService;

public class MyJaxrsApplication extends Application {

	private final Set&lt;Class&lt;?&gt;&gt; classes;

	public MyJaxrsApplication() {
		classes = new HashSet&lt;Class&lt;?&gt;&gt;();
		addClass(LogsService.class);
	}

	@Override
	public Set&lt;Class&lt;?&gt;&gt; getClasses() {
		return classes;
	}

	protected void addClass(Class&lt;?&gt; clazz) {
		classes.add(clazz);
	}
}</pre>
<p>In our case we override Application#getClasses() to add our LogsService class. </p>
<h2>web.xml</h2>
<p>At this step we have created our JAX-RS LogsService and registered it in our JAX-RS Application MyJaxrsApplication. Now we must configure the web.xml to declare the Apache CXF servlet which manages JAX-RS  : </p>
<ul>
<li>we should declare the Apache CXF servlet by setting our JAX-RS Application :
<pre class="brush: xml; title: ; notranslate">&lt;servlet&gt;
	&lt;servlet-name&gt;CXFServlet&lt;/servlet-name&gt;
	&lt;servlet-class&gt;org.apache.cxf.jaxrs.servlet.CXFNonSpringJaxrsServlet&lt;/servlet-class&gt;
	&lt;init-param&gt;
		&lt;param-name&gt;javax.ws.rs.Application&lt;/param-name&gt;
		&lt;param-value&gt;
			org.samples.mongodb.jaxrs.MyJaxrsApplication
		&lt;/param-value&gt;
	&lt;/init-param&gt;
&lt;/servlet&gt;
</pre>
</li>
<li>In our case we wish to deploy our JAX-RS service with URL which starts with <strong>/jaxrs/*</strong> :
<pre class="brush: xml; title: ; notranslate">&lt;servlet-mapping&gt;
	&lt;servlet-name&gt;CXFServlet&lt;/servlet-name&gt;
	&lt;url-pattern&gt;/jaxrs/*&lt;/url-pattern&gt;
&lt;/servlet-mapping&gt;
</pre>
</li>
</ul>
<p>Here the full code of web.xml : </p>
<pre class="brush: xml; title: ; notranslate">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;web-app xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
	xmlns=&quot;http://java.sun.com/xml/ns/javaee&quot; xmlns:web=&quot;http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd&quot;
	xsi:schemaLocation=&quot;http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd&quot;
	id=&quot;WebApp_ID&quot; version=&quot;2.5&quot;&gt;
	&lt;display-name&gt;Mongo JEE&lt;/display-name&gt;

	&lt;servlet&gt;
		&lt;servlet-name&gt;CXFServlet&lt;/servlet-name&gt;
		&lt;servlet-class&gt;org.apache.cxf.jaxrs.servlet.CXFNonSpringJaxrsServlet&lt;/servlet-class&gt;
		&lt;init-param&gt;
			&lt;param-name&gt;javax.ws.rs.Application&lt;/param-name&gt;
			&lt;param-value&gt;
				org.samples.mongodb.jaxrs.MyJaxrsApplication
			&lt;/param-value&gt;
		&lt;/init-param&gt;
	&lt;/servlet&gt;

	&lt;servlet-mapping&gt;
		&lt;servlet-name&gt;CXFServlet&lt;/servlet-name&gt;
		&lt;url-pattern&gt;/jaxrs/*&lt;/url-pattern&gt;
	&lt;/servlet-mapping&gt;

	&lt;listener&gt;
		&lt;listener-class&gt;com.mongodb.jee.servlet.MongoServletContextListener&lt;/listener-class&gt;
	&lt;/listener&gt;

	&lt;context-param&gt;
		&lt;param-name&gt;mongoURI&lt;/param-name&gt;
		&lt;param-value&gt;mongodb://localhost:27017&lt;/param-value&gt;
	&lt;/context-param&gt;

&lt;/web-app&gt;</pre>
<h2 id="test">Test LogsService</h2>
<ul>
<li>run the StartServer class to start the server.</li>
<li>access with your webbrowser to the URL <a href="http://localhost:8081/mongo/jaxrs/logs/all">http://localhost:8081/mongo/jaxrs/logs/all/</a> to see the JSON array of logs and see the &quot;application/json&quot; of the content type :<br />
<img src="http://angelozerr.files.wordpress.com/2013/05/mongojee_jaxrs_streamingoutput_chrome.png?w=595" />
  </li>
</ul>
<p><H2>LogsService &#8211; MongoStreamingOutput</h2>
<p><a href="https://github.com/angelozerr/mongo-jee">Mongo JEE</a> provides the com.mongodb.jee.jaxrs.<strong>MongoStreamingOutput</strong> classes. So you can replace this code :</p>
<pre class="brush: java; title: ; notranslate">StreamingOutput output = new StreamingOutput() {
	public void write(OutputStream out) throws IOException, WebApplicationException {
		com.mongodb.jee.util.JSON.serialize(cursor, out);
	}
};</pre>
<p>with MongoStreamingOutput :</p>
<pre class="brush: java; title: ; notranslate">StreamingOutput output = new MongoStreamingOutput(cursor);</pre>
<h2>MyJaxrsApplication &#8211; getSingletons</h2>
<p>At this step, our logs service is instantiated as soon as is called. To test that, you can add a counter in the LogsService constructor : </p>
<pre class="brush: java; title: ; notranslate">private static int i = 0;

  public LogsService() {
    System.err.println(i++);
}
</pre>
<p>You will see on the console that each time you call <a href="http://localhost:8081/mongo/jaxrs/logs/all">http://localhost:8081/mongo/jaxrs/logs/all</a>, the i variable is incremented, it means that LogsService is instanciated for each request.</p>
<p>In our case it&rsquo;s not interesting, and <strong>LogsService can be a singleton</strong>. To do that, Application#getSingletons() should be override to return an instance of LogsService.</p>
<p>Modify the JAX-RS Application MyJaxrsApplication like this : </p>
<pre class="brush: java; title: ; notranslate">package org.samples.mongodb.jaxrs;

import java.util.HashSet;
import java.util.Set;

import javax.ws.rs.core.Application;

import org.samples.mongodb.services.LogsService;

public class MyJaxrsApplication extends Application {

	private final Set&lt;Object&gt; singletons;

	public MyJaxrsApplication() {
		singletons = new HashSet&lt;Object&gt;();
		addSingleton(new LogsService());
	}

	protected void addSingleton(Object singleton) {
		singletons.add(singleton);
	}

	@Override
	public Set&lt;Object&gt; getSingletons() {
		return singletons;
	}
}</pre>
<p><a href="#test">Restart the server</a> to check that counter is called just one time.</p>
<h2>Conclusion</h2>
<p>In this article we have seen how to transform our LogsServlet with a <strong>JAX-RS LogsService which uses StreamingOutput</strong>. Our LogsService is more elegant than LogServlet but code is linked to the JAX-RS API because it returns javax.ws.rs.core.Response. So <strong>it&rsquo;s difficult to test the result of the LogService</strong> with a simple JUnit. </p>
<p>In the next article <a href="http://angelozerr.wordpress.com/2013/05/14/mongo_jee_step5/">[step5]</a> we will fix this problem by changing the signature of the findAll method to return a <strong>Pojo Log</strong> instead of returning a JAX-RS Response.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/angelozerr.wordpress.com/7291/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/angelozerr.wordpress.com/7291/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=angelozerr.wordpress.com&#038;blog=10338309&#038;post=7291&#038;subd=angelozerr&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://angelozerr.wordpress.com/2013/05/14/mongo_jee_step4/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/4c3176f508ba2f224d3b00dce0ca6c2a?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">akrogen</media:title>
		</media:content>

		<media:content url="http://angelozerr.files.wordpress.com/2013/05/mongojee_step4.png" medium="image" />

		<media:content url="http://angelozerr.files.wordpress.com/2013/05/mongojee_jaxrs_streamingoutput_chrome.png" medium="image" />
	</item>
		<item>
		<title>Mongo JEE [step3]</title>
		<link>http://angelozerr.wordpress.com/2013/05/12/mongo_jee_step3/</link>
		<comments>http://angelozerr.wordpress.com/2013/05/12/mongo_jee_step3/#comments</comments>
		<pubDate>Sun, 12 May 2013 11:21:53 +0000</pubDate>
		<dc:creator>angelozerr</dc:creator>
				<category><![CDATA[Mongo JEE]]></category>
		<category><![CDATA[MongoDB]]></category>

		<guid isPermaLink="false">http://angelozerr.wordpress.com/?p=7289</guid>
		<description><![CDATA[In [step2] we have used mongo in a servlet to return the JSON array of the logs collection. In this article we will use Mongo JEE to improve it : use com.mongodb.jee.MongoHolder#connect() to avoid hard coding the mongo URI in the servlet. use com.mongodb.jee.util.JSON to manage JSON streaming when mongo cusor is serialized as JSON [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=angelozerr.wordpress.com&#038;blog=10338309&#038;post=7289&#038;subd=angelozerr&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>In <a href="http://angelozerr.wordpress.com/2013/05/11/mongo_jee_step2/">[step2]</a> we have used mongo in a servlet to return the JSON array of the logs collection. In this article we will use <a href="https://github.com/angelozerr/mongo-jee">Mongo JEE</a> to improve it :</p>
<ul>
<li>use com.mongodb.jee.<a href="#MongoHolder">MongoHolder#connect()</a> to <strong>avoid hard coding the mongo URI</strong> in the servlet.</li>
<li>use com.mongodb.jee.util.<a href="#JSON">JSON</a> to manage <strong>JSON streaming</strong> when mongo cusor is serialized as JSON and is written in the HTTP response.</li>
<li>use com.mongodb.jee.servlet.<a href="#ServletHelper">ServletHelper</a> to <strong>simplify the code </strong>which set response as JSON and write the JSON stream in the HTTP response.</li>
</ul>
<p><span id="more-7289"></span></p>
<h2>Download</h2>
<p>You can download <a href="https://dl.dropboxusercontent.com/u/2903680/wordpress-blog/tutoriels/java/mongo-jee/step3.zip">step3.zip</a> which hosts the Eclipse Project which contains the explained sources in this article. To use it, unzip it and import this project in your Eclipse workspace. As soon as you will do that, your workspace will look like this : </p>
<p><img src="http://angelozerr.files.wordpress.com/2013/05/mongojee_step3.png?w=595" /></p>
<h3>Download JARs with maven</h3>
<p>In this article we use :</p>
<ol>
<li>the Mongo Java Driver. To do that I use this maven dependency :
<pre class="brush: xml; title: ; notranslate">&lt;dependency&gt;
	&lt;groupId&gt;org.mongodb&lt;/groupId&gt;
	&lt;artifactId&gt;mongo-java-driver&lt;/artifactId&gt;
	&lt;version&gt;2.11.1&lt;/version&gt;
&lt;/dependency&gt;
</pre>
</li>
<li>the Embedded Jetty as server. To do that I use this maven dependency :
<pre class="brush: xml; title: ; notranslate">&lt;dependency&gt;
	&lt;groupId&gt;org.eclipse.jetty&lt;/groupId&gt;
	&lt;artifactId&gt;jetty-webapp&lt;/artifactId&gt;
	&lt;version&gt;8.1.10.v20130312&lt;/version&gt;
	&lt;scope&gt;test&lt;/scope&gt;
&lt;/dependency&gt;
</pre>
</li>
<li><a href="https://github.com/angelozerr/mongo-jee">Mongo JEE</a>. To do that I use this maven dependency :
<pre class="brush: xml; title: ; notranslate">&lt;dependency&gt;
	&lt;groupId&gt;fr.opensagres.mongodb&lt;/groupId&gt;
	&lt;artifactId&gt;mongo-jee&lt;/artifactId&gt;
	&lt;version&gt;1.0.0&lt;/version&gt;
&lt;/dependency&gt;
</pre>
</li>
</ol>
<p>The project contains the JARs in the lib, but if you wish to download it with maven , see <a href="http://angelozerr.wordpress.com/2013/05/10/mongo_jee_step1/#download-mvn">Download JARs with maven [step1]</a>.</p>
<h2 id="MongoHolder">MongoHolder#connect()</h3>
<p>In <a href="http://angelozerr.wordpress.com/2013/05/11/mongo_jee_step2/">[step2]</a>:</p>
<ol>
<li>the mongo client is created on the init of logs servlet:
<pre class="brush: java; title: ; notranslate">private MongoClient mongo = null;

@Override
public void init() throws ServletException {
	super.init();

	// Connect to Mongo DB
	MongoClientURI mongoURI = new MongoClientURI(
			&quot;mongodb://localhost:27017&quot;);
	try {
		mongo = new MongoClient(mongoURI);
	} catch (UnknownHostException e) {
		throw new ServletException(e);
	}
}
</pre>
</li>
<li>the mongo client is closed on the destroy of logs servlet:
<pre class="brush: java; title: ; notranslate">@Override
public void destroy() {
	super.destroy();
	if (mongo != null) {
		mongo.close();
	}
}
</pre>
</li>
</ol>
<p>This code works, but there are some problems :</p>
<ul>
<li>the<strong> mongo URI is hard coded</strong>. If you wish to change the mongo URI, you must recompile the servlet.</li>
<li>if you wish to add a new servlet like logs servlet, it&rsquo;s not possible to use the mongo pool of the logs servlet. A best design is to <strong>delegate the mongo lyfecycle</strong> (create and close) in other classes than logs servlet.</li>
</ul>
<p><a href="https://github.com/angelozerr/mongo-jee">Mongo JEE</a> resolves this 2 problems with the <strong>MongoHolder</strong>. To use it, you must </p>
<ol>
<li>configure the default mongo URI of the MongoHolder :
<pre class="brush: java; title: ; notranslate">
MongoClientURI mongoURI = ...;
boolean defaultMongo = true;
MongoHolder.connect(mongoURI, defaultMongo);
</pre>
<p>You can configure it in your web.xml with the JEE ServletContextListener com.mongodb.jee.servlet.<strong>MongoServletContextListener</strong> like this : </p>
<pre class="brush: xml; title: ; notranslate">&lt;listener&gt;
	&lt;listener-class&gt;com.mongodb.jee.servlet.MongoServletContextListener&lt;/listener-class&gt;
&lt;/listener&gt;

&lt;context-param&gt;
	&lt;param-name&gt;mongoURI&lt;/param-name&gt;
	&lt;param-value&gt;mongodb://localhost:27017&lt;/param-value&gt;
&lt;/context-param&gt;
</pre>
<ul>
<li>on ServletContextListener#contextInitialized, MongoHolder is initialized with default mongoURI declared in the web.xml.
  </li>
<li>on ServletContextListener#contextDestroyed, all instance of Mongo registered in the MongoHolder are closed.
  </li>
</ul>
</li>
<li>after having configurated the default mongo URI, you can do that :
<pre class="brush: java; title: ; notranslate">Mongo mongo = MongoHolder.connect();
</pre>
</li>
</ol>
<h3>web.xml</h3>
<p>Modify the web.xml to declare com.mongodb.jee.servlet.<strong>MongoServletContextListener</strong> and the default mongo URI like this :</p>
<pre class="brush: xml; title: ; notranslate">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;web-app xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
	xmlns=&quot;http://java.sun.com/xml/ns/javaee&quot; xmlns:web=&quot;http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd&quot;
	xsi:schemaLocation=&quot;http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd&quot;
	id=&quot;WebApp_ID&quot; version=&quot;2.5&quot;&gt;
	&lt;display-name&gt;Mongo JEE&lt;/display-name&gt;

	&lt;servlet&gt;
		&lt;servlet-name&gt;LogsServlet&lt;/servlet-name&gt;
		&lt;servlet-class&gt;org.samples.mongodb.servlet.LogsServlet&lt;/servlet-class&gt;
	&lt;/servlet&gt;

	&lt;servlet-mapping&gt;
		&lt;servlet-name&gt;LogsServlet&lt;/servlet-name&gt;
		&lt;url-pattern&gt;/servlet/logs/*&lt;/url-pattern&gt;
	&lt;/servlet-mapping&gt;

	&lt;listener&gt;
		&lt;listener-class&gt;com.mongodb.jee.servlet.MongoServletContextListener&lt;/listener-class&gt;
	&lt;/listener&gt;

	&lt;context-param&gt;
		&lt;param-name&gt;mongoURI&lt;/param-name&gt;
		&lt;param-value&gt;mongodb://localhost:27017&lt;/param-value&gt;
	&lt;/context-param&gt;

&lt;/web-app&gt;</pre>
<h3>LogsServlet &#8211; MongoHolder</h3>
<p>Modify org.samples.mongodb.servlet.<strong>LogsServlet</strong> to use <strong>MongoHolder#connect()</strong> like this :</p>
<pre class="brush: java; title: ; notranslate">package org.samples.mongodb.servlet;

import java.io.IOException;
import java.io.Writer;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.Mongo;
import com.mongodb.jee.MongoHolder;
import com.mongodb.util.JSON;

public class LogsServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		Mongo mongo = MongoHolder.connect();
		// Get DB collection
		DB db = mongo.getDB(&quot;websites&quot;);
		DBCollection coll = db.getCollection(&quot;logs&quot;);

		DBCursor cursor = coll.find();

		// HTTP response is JSON
		response.setCharacterEncoding(&quot;UTF-8&quot;);
		response.setContentType(&quot;application/json&quot;);

		// Loop for DB cursor and write each DB document in the HTTP writer
		Writer writer = response.getWriter();

		StringBuilder buf = new StringBuilder();
		JSON.serialize(cursor, buf);
		writer.write(buf.toString());

		writer.flush();

	}

}</pre>
<p><a href="http://angelozerr.wordpress.com/2013/05/11/mongo_jee_step2#test">Restart the server</a> to check the servlet logs works again.</p>
<h2 id="JSON">com.mongodb.jee.util.JSON</h2>
<p>In <a href="http://angelozerr.wordpress.com/2013/05/11/mongo_jee_step2/">[step2]</a> the mongo cursor <strong>is serialized (by using StringBuilder)</strong> as JSON in the HTTP response like this:</p>
<pre class="brush: java; title: ; notranslate">Writer writer = response.getWriter();

StringBuilder buf = new StringBuilder();
com.mongodb.util.JSON.serialize(cursor, buf);
writer.write(buf.toString());
</pre>
<p>Problem with this code is that you <strong>must create a StringBuilder</strong> instance <strong>before writing in the HTTP response</strong>. To avoid this problem, you can use Mongo JEE which provides the same <strong>JSON helper but with Writer as parameter</strong>. So you can do that :</p>
<pre class="brush: java; title: ; notranslate">Writer writer = response.getWriter();

com.mongodb.jee.util.JSON.serialize(cursor, writer);
</pre>
<h3>LogsServlet &#8211; JSON</h3>
<p>Modify org.samples.mongodb.servlet.<strong>LogsServlet</strong> to use com.mongodb.jee.util.JSON like this :</p>
<pre class="brush: java; title: ; notranslate">package org.samples.mongodb.servlet;

import java.io.IOException;
import java.io.Writer;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.Mongo;
import com.mongodb.jee.MongoHolder;
import com.mongodb.util.JSON;

public class LogsServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		Mongo mongo = MongoHolder.connect();
		// Get DB collection
		DB db = mongo.getDB(&quot;websites&quot;);
		DBCollection coll = db.getCollection(&quot;logs&quot;);

		DBCursor cursor = coll.find();

		// HTTP response is JSON
		response.setCharacterEncoding(&quot;UTF-8&quot;);
		response.setContentType(&quot;application/json&quot;);

		// Loop for DB cursor and write each DB document in the HTTP writer
		Writer writer = response.getWriter();

		//StringBuilder buf = new StringBuilder();
		com.mongodb.jee.util.JSON.serialize(cursor, writer);
		//writer.write(buf.toString());

		writer.flush();
	}

}</pre>
<p><a href="http://angelozerr.wordpress.com/2013/05/11/mongo_jee_step2#test">Restart the server</a> to check the servlet logs works again.</p>
<h2 id="ServletHelper">ServletHelper</h2>
<p>You can notice that the code :</p>
<pre class="brush: java; title: ; notranslate">// HTTP response is JSON
response.setCharacterEncoding(&quot;UTF-8&quot;);
response.setContentType(&quot;application/json&quot;);

// Loop for DB cursor and write each DB document in the HTTP writer
Writer writer = response.getWriter();

//StringBuilder buf = new StringBuilder();
com.mongodb.jee.util.JSON.serialize(cursor, writer);
//writer.write(buf.toString());

writer.flush();</pre>
<p>is generic. You can do the same thing with the Mongo JEE com.mongodb.jee.servlet.<strong>ServletHelper</strong> :</p>
<pre class="brush: java; title: ; notranslate">// Write in the HHTP response the JSON array of the cursor.
ServletHelper.writeJson(cursor, response);</pre>
<h3>LogsServlet &#8211; ServletHelper</h3>
<p>Modify org.samples.mongodb.servlet.<strong>LogsServlet</strong> to use com.mongodb.jee.servlet.<strong>ServletHelper</strong> like this :</p>
<pre class="brush: java; title: ; notranslate">package org.samples.mongodb.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.Mongo;
import com.mongodb.jee.MongoHolder;
import com.mongodb.jee.servlet.ServletHelper;

public class LogsServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		Mongo mongo = MongoHolder.connect();
		// Get DB collection
		DB db = mongo.getDB(&quot;websites&quot;);
		DBCollection coll = db.getCollection(&quot;logs&quot;);

		DBCursor cursor = coll.find();

		// Write in the HHTP response the JSON array of the cursor.
		ServletHelper.writeJson(cursor, response);
	}

}</pre>
<p><a href="http://angelozerr.wordpress.com/2013/05/11/mongo_jee_step2#test">Restart the server</a> to check the servlet logs works again.</p>
<h2>Conclusion</h2>
<p>In this article we have seen how to Mongo JEE can improve code with servlet which uses Mongo. In the next article <a href="http://angelozerr.wordpress.com/2013/05/14/mongo_jee_step4/">[step4]</a>, we will replace our logs servlet with a JAX-RS logs service by using javax.ws.rs.core.<strong>StreamingOutput</strong>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/angelozerr.wordpress.com/7289/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/angelozerr.wordpress.com/7289/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=angelozerr.wordpress.com&#038;blog=10338309&#038;post=7289&#038;subd=angelozerr&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://angelozerr.wordpress.com/2013/05/12/mongo_jee_step3/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/4c3176f508ba2f224d3b00dce0ca6c2a?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">akrogen</media:title>
		</media:content>

		<media:content url="http://angelozerr.files.wordpress.com/2013/05/mongojee_step3.png" medium="image" />
	</item>
		<item>
		<title>Mongo JEE [step2]</title>
		<link>http://angelozerr.wordpress.com/2013/05/11/mongo_jee_step2/</link>
		<comments>http://angelozerr.wordpress.com/2013/05/11/mongo_jee_step2/#comments</comments>
		<pubDate>Sat, 11 May 2013 23:16:01 +0000</pubDate>
		<dc:creator>angelozerr</dc:creator>
				<category><![CDATA[MongoDB]]></category>

		<guid isPermaLink="false">http://angelozerr.wordpress.com/?p=7254</guid>
		<description><![CDATA[In [step1] we have seen how to execute mongo operations (find, insert, remove) with Java code by using Mongo Java Driver and the Pojo Mapper MongoJack. In this article we will create a WebApp application composed with a Servlet which connects to the Mongo DB and returns the JSON stream array of the logs collection [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=angelozerr.wordpress.com&#038;blog=10338309&#038;post=7254&#038;subd=angelozerr&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>In <a href="http://angelozerr.wordpress.com/2013/05/10/mongo_jee_step1/">[step1]</a> we have seen how to <strong>execute mongo operations (find, insert, remove) with Java code</strong> by using <a href="https://github.com/mongodb/mongo-java-driver">Mongo Java Driver</a> and the Pojo Mapper <a href="http://mongojack.org/">MongoJack</a>. In this article we will create a <strong>WebApp application</strong> composed with a <strong>Servlet which connects to the Mongo</strong> DB and returns the JSON stream array of the logs collection in the HTTP response, on other words when the following URL will be called : </p>
<p><a href="http://localhost:8081/mongo/servlet/logs/">http://localhost:8081/mongo/servlet/logs/</a> the servlet will return the JSON stream array : </p>
<pre class="brush: plain; title: ; notranslate">[ 
{ &quot;_id&quot; : { &quot;$oid&quot; : &quot;518d01813bfe01bef797d031&quot;} , 
  &quot;url&quot; : &quot;http://www.mongodb.org/&quot; , 
  &quot;created&quot; : { &quot;$date&quot; : &quot;2013-05-10T14:17:37.515Z&quot;}} , 
{ &quot;_id&quot; : { &quot;$oid&quot; : &quot;518d01813bfe01bef797d032&quot;} , 
  &quot;url&quot; : &quot;http://www.mongodb.org/&quot; , 
  &quot;created&quot; : { &quot;$date&quot; : &quot;2013-05-10T14:17:37.515Z&quot;}} ,
...]</pre>
<p>To do that, we will  :</p>
<ul>
<li>use <a href="http://wiki.eclipse.org/Jetty/Tutorial/Embedding_Jetty">Embedded Jetty</a> as HTTP server to start the WebApp with simple Java main.</li>
<li>use <a href="https://github.com/mongodb/mongo-java-driver">Mongo Java Driver</a>.</li>
<li>create the <a href="#LogsServlet">LogsServlet</a>, the <strong>servlet which returns the JSON stream array of the logs</strong>.</li>
</ul>
<p><span id="more-7254"></span></p>
<h2>Download</h2>
<p>You can download <a href="https://dl.dropboxusercontent.com/u/2903680/wordpress-blog/tutoriels/java/mongo-jee/step2.zip">step2.zip</a> which hosts the Eclipse Project which contains the explained sources in this article. To use it, unzip it and import this project in your Eclipse workspace. As soon as you will do that, your workspace will look like this : </p>
<p><img src="http://angelozerr.files.wordpress.com/2013/05/mongojee_step21.png?w=595" /></p>
<ul>
<li>org.samples.mongodb.servlet.<a href="#LogsServlet">LogsServlet</a> is the logs servlet which returns the JSON array.</li>
<li><a href="#web.xml">web.xml</a> declares the logs servlet.
<li>org.samples.mongodb.server.<a href="#StartServer">StartServer</a> starts the embedding Jetty which hosts the WebApp.</li>
</ul>
<h3 id="download-mvn">Download JARs with maven</h3>
<p>In this article we use the Mongo Java Driver. To do that I use this maven dependency :</p>
<pre class="brush: xml; title: ; notranslate">&lt;dependency&gt;
	&lt;groupId&gt;org.mongodb&lt;/groupId&gt;
	&lt;artifactId&gt;mongo-java-driver&lt;/artifactId&gt;
	&lt;version&gt;2.11.1&lt;/version&gt;
&lt;/dependency&gt;
</pre>
<p>and the Embedded Jetty as server. To do that I use this maven dependency :</p>
<pre class="brush: xml; title: ; notranslate">&lt;dependency&gt;
	&lt;groupId&gt;org.eclipse.jetty&lt;/groupId&gt;
	&lt;artifactId&gt;jetty-webapp&lt;/artifactId&gt;
	&lt;version&gt;8.1.10.v20130312&lt;/version&gt;
	&lt;scope&gt;test&lt;/scope&gt;
&lt;/dependency&gt;
</pre>
<p>The project contains the JARs in the lib, but if you wish to download it with maven , see <a href="http://angelozerr.wordpress.com/2013/05/10/mongo_jee_step1/#download-mvn">Download JARs with maven [step1]</a>.</p>
<h2>WebApp</h2>
<h3 id="LogsServlet">LogsServlet</h3>
<p>Create the org.samples.mongodb.servlet.<strong>LogsServlet</strong> servlet like this:</p>
<pre class="brush: java; title: ; notranslate">package org.samples.mongodb.servlet;

import java.io.IOException;
import java.io.Writer;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.util.JSON;

public class LogsServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		// Connect to Mongo DB
		MongoClientURI mongoURI = new MongoClientURI(
				&quot;mongodb://localhost:27017&quot;);
		MongoClient mongo = new MongoClient(mongoURI);
		try {

			// Get &quot;logs&quot; collection from the &quot;websites&quot; DB.
			DB db = mongo.getDB(&quot;websites&quot;);
			DBCollection coll = db.getCollection(&quot;logs&quot;);

			// Find all DB object from the DB collection
			DBCursor cursor = coll.find();

			// HTTP response is JSON
			response.setCharacterEncoding(&quot;UTF-8&quot;);
			response.setContentType(&quot;application/json&quot;);

			// Write in the HTTP response, the JSON array of the cursor.
			Writer writer = response.getWriter();
			StringBuilder buf = new StringBuilder();
			JSON.serialize(cursor, buf);
			writer.write(buf.toString());
			writer.flush();

		} finally {
			mongo.close();
		}
	}
}</pre>
<h3 id="web.xml">web.xml</h3>
<p>Declare the servlet in the src/main/webapp/WEB-INF/<strong>web.xml</strong> like this :</p>
<pre class="brush: xml; title: ; notranslate">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;web-app xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
	xmlns=&quot;http://java.sun.com/xml/ns/javaee&quot; xmlns:web=&quot;http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd&quot;
	xsi:schemaLocation=&quot;http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd&quot;
	id=&quot;WebApp_ID&quot; version=&quot;2.5&quot;&gt;
	&lt;display-name&gt;Mongo JEE&lt;/display-name&gt;

	&lt;servlet&gt;
		&lt;servlet-name&gt;LogsServlet&lt;/servlet-name&gt;
		&lt;servlet-class&gt;org.samples.mongodb.servlet.LogsServlet
		&lt;/servlet-class&gt;
	&lt;/servlet&gt;

	&lt;servlet-mapping&gt;
		&lt;servlet-name&gt;LogsServlet&lt;/servlet-name&gt;
		&lt;url-pattern&gt;/servlet/logs/*&lt;/url-pattern&gt;
	&lt;/servlet-mapping&gt;

&lt;/web-app&gt;</pre>
<h2>Server</h2>
<h3 id="StartServer">StartServer</h3>
<p>Create the Java main org.samples.mongodb.server.<strong>StartServer</strong> which starts the embedding Jetty which hosts the WebApp : </p>
<pre class="brush: java; title: ; notranslate">package org.samples.mongodb.server;

import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.ContextHandlerCollection;
import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.webapp.WebAppContext;

public class StartServer {

	public static void main(String[] args) throws Exception {
		Server server = new Server(8081);

		WebAppContext webappcontext = new WebAppContext(&quot;src/main/webapp&quot;,
				&quot;/mongo&quot;);

		ContextHandlerCollection servlet_contexts = new ContextHandlerCollection();
		webappcontext.setClassLoader(Thread.currentThread()
				.getContextClassLoader());
		HandlerCollection handlers = new HandlerCollection();
		handlers.setHandlers(new Handler[] { servlet_contexts, webappcontext,
				new DefaultHandler() });
		server.setHandler(handlers);

		server.start();
		server.join();
	}
}</pre>
<p>This Java main starts an embedding Jetty on the 8081 port and configures a WebApp where sources are hosted in the src/main/webapp folder (where web.xml is hosted).</p>
<h3 id="test">Test LogsServlet</h3>
<ul>
<li>run the StartServer class to start the server.</li>
<li>access with your webbrowser to the URL <a href="http://localhost:8081/mongo/servlet/logs/">http://localhost:8081/mongo/servlet/logs/</a> to see the JSON array of logs:<br />
<img src="http://angelozerr.files.wordpress.com/2013/05/mongojee_step2_jsonlogs.png?w=595" />
  </li>
</ul>
<h3>LogsServlet &#8211; Mongo pool</h3>
<p>According the <a href="http://docs.mongodb.org/ecosystem/tutorial/getting-started-with-java-driver/">Getting Started with Java Driver</a> article :</p>
<p><cite>Note The MongoClient instance actually represents a pool of connections to the database; you will only need one instance of class MongoClient even with multiple threads. See the concurrency doc page for more information.</cite></p>
<p>In our current code of LogsServlet we create a MongoClient instance and close it for each HTTP request. We can improve that by creating a MongoClient and close it just one time (not for each HTTP request). Modify the LogsServlet like this : </p>
<pre class="brush: java; title: ; notranslate">package org.samples.mongodb.servlet;

import java.io.IOException;
import java.io.Writer;
import java.net.UnknownHostException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.util.JSON;

public class LogsServlet extends HttpServlet {

	private MongoClient mongo = null;

	@Override
	public void init() throws ServletException {
		super.init();

		// Connect to Mongo DB
		MongoClientURI mongoURI = new MongoClientURI(
				&quot;mongodb://localhost:27017&quot;);
		try {
			mongo = new MongoClient(mongoURI);
		} catch (UnknownHostException e) {
			throw new ServletException(e);
		}
	}

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		// Get &quot;logs&quot; collection from the &quot;websites&quot; DB.
		DB db = mongo.getDB(&quot;websites&quot;);
		DBCollection coll = db.getCollection(&quot;logs&quot;);

		// Find all DB object from the DB collection
		DBCursor cursor = coll.find();

		// HTTP response is JSON
		response.setCharacterEncoding(&quot;UTF-8&quot;);
		response.setContentType(&quot;application/json&quot;);

		// Write in the HTTP response, the JSON array of the cursor.
		Writer writer = response.getWriter();
		StringBuilder buf = new StringBuilder();
		JSON.serialize(cursor, buf);
		writer.write(buf.toString());
		writer.flush();

	}

	@Override
	public void destroy() {
		super.destroy();
		if (mongo != null) {
			mongo.close();
		}
	}

}</pre>
<h2>Conclusion</h2>
<p>In this article we have seen how to use Mongo in a JEE Servlet. In the next article <a href="http://angelozerr.wordpress.com/2013/05/12/mongo_jee_step3/">[step3]</a> we will see how to we can improve this LogsServlet with <a href="https://github.com/angelozerr/mongo-jee">Mongo JEE</a>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/angelozerr.wordpress.com/7254/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/angelozerr.wordpress.com/7254/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=angelozerr.wordpress.com&#038;blog=10338309&#038;post=7254&#038;subd=angelozerr&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://angelozerr.wordpress.com/2013/05/11/mongo_jee_step2/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/4c3176f508ba2f224d3b00dce0ca6c2a?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">akrogen</media:title>
		</media:content>

		<media:content url="http://angelozerr.files.wordpress.com/2013/05/mongojee_step21.png" medium="image" />

		<media:content url="http://angelozerr.files.wordpress.com/2013/05/mongojee_step2_jsonlogs.png" medium="image" />
	</item>
		<item>
		<title>Mongo JEE [step1]</title>
		<link>http://angelozerr.wordpress.com/2013/05/10/mongo_jee_step1/</link>
		<comments>http://angelozerr.wordpress.com/2013/05/10/mongo_jee_step1/#comments</comments>
		<pubDate>Fri, 10 May 2013 15:56:27 +0000</pubDate>
		<dc:creator>angelozerr</dc:creator>
				<category><![CDATA[Dojo]]></category>
		<category><![CDATA[Mongo JEE]]></category>
		<category><![CDATA[MongoDB]]></category>

		<guid isPermaLink="false">http://angelozerr.wordpress.com/?p=7215</guid>
		<description><![CDATA[In [step0] we have introduced Mongo JEE articles, install and initialize Mongo DB websites database with Mongo Shell scripts. In this article we will do the same thing with Java code by using : the Mongo Java Driver. the Pojo Mapper MongoJack. Download You can download step1.zip which hosts the Eclipse Project which contains the [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=angelozerr.wordpress.com&#038;blog=10338309&#038;post=7215&#038;subd=angelozerr&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>In <a href="http://angelozerr.wordpress.com/2013/05/10/mongo_jee_step0/">[step0]</a> we have introduced <a href="http://angelozerr.wordpress.com/about/mongo_jee">Mongo JEE articles</a>, <strong>install and initialize</strong> Mongo DB websites database with <strong>Mongo Shell</strong> scripts. In this article we will do the same thing with Java code by using : </p>
<ul>
<li>the <a href="https://github.com/mongodb/mongo-java-driver">Mongo Java Driver</a>.</li>
<li>the Pojo Mapper <a href="http://mongojack.org/">MongoJack</a>.</li>
</ul>
<p><span id="more-7215"></span></p>
<h2>Download</h2>
<p>You can download <a href="https://dl.dropboxusercontent.com/u/2903680/wordpress-blog/tutoriels/java/mongo-jee/step1.zip">step1.zip</a> which hosts the Eclipse Project which contains the explained sources in this article. To use it, unzip it and import this project in your Eclipse workspace. As soon as you will do that, your workspace will look like this : </p>
<p><img src="http://angelozerr.files.wordpress.com/2013/05/mongojee_step1.png?w=595" /></p>
<ul>
<li><strong>scripts</strong> folder contains the Javascript mongo operation (insert, remove etc) with Mongo Shell explained in the <a href="http://angelozerr.wordpress.com/2013/05/10/mongo_jee_step0/">[step0]</a>.
  </li>
<li>the Java package <strong>org.samples.mongodb.operations.javadriver</strong> contains the same Java mongo operations with Java Mongo Driver.
  </li>
<li>the Java package <strong>org.samples.mongodb.operations.pojomapper.mongojack</strong> contains the same Java mongo operations with Pojo Mapper MongoJack.
  </li>
</ul>
<h3 id="download-mvn">Download JARs with maven</h3>
<p>Each step*. project that I will provide use JARs. I could download at hand the JARs (awfull work), but I prefer <strong>using maven to manage dependencies</strong>. </p>
<p>So each step* project contains a <strong>pom.xml</strong>.</p>
<p>But as maven is not used by the whole people, the step* project contains the lib folder which hosts JARs and classpath of the eclipse project uses those JARs. </p>
<p>If you wish to download the JARs, you can do it with the command :</p>
<pre class="brush: plain; title: ; notranslate">mvn process-resources</pre>
<p>This command download the JARs from the central maven repository, and copy them in the lib folder.</p>
<h2>Mongo Operations</h2>
<h3 id="java">Mongo Java Driver</h3>
<p>In this section we use the <a href="https://github.com/mongodb/mongo-java-driver">Mongo Java Driver</a>. I suggest you to read the <a href="http://docs.mongodb.org/ecosystem/tutorial/getting-started-with-java-driver/">Getting Started with Java Driver</a> article which list the basic features of the driver.</p>
<h4>Download driver</h4>
<p>The driver is managed with the <strong>lib/mongo-java-driver-2.11.1.jar</strong>. To download it, I have used this maven dependency :</p>
<pre class="brush: xml; title: ; notranslate">&lt;dependency&gt;
	&lt;groupId&gt;org.mongodb&lt;/groupId&gt;
	&lt;artifactId&gt;mongo-java-driver&lt;/artifactId&gt;
	&lt;version&gt;2.11.1&lt;/version&gt;
&lt;/dependency&gt;</pre>
<p>Here the full pom.xml: </p>
<pre class="brush: xml; title: ; notranslate">&lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
	xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd&quot;&gt;
	&lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
	&lt;groupId&gt;org.samples.mongodb&lt;/groupId&gt;
	&lt;artifactId&gt;step1&lt;/artifactId&gt;
	&lt;packaging&gt;pom&lt;/packaging&gt;
	&lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;

	&lt;build&gt;
		&lt;plugins&gt;
			&lt;plugin&gt;
				&lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
				&lt;artifactId&gt;maven-dependency-plugin&lt;/artifactId&gt;
				&lt;version&gt;2.1&lt;/version&gt;
				&lt;executions&gt;
					&lt;execution&gt;
						&lt;id&gt;copy-dependencies&lt;/id&gt;
						&lt;phase&gt;process-resources&lt;/phase&gt;
						&lt;goals&gt;
							&lt;goal&gt;copy-dependencies&lt;/goal&gt;
						&lt;/goals&gt;
						&lt;configuration&gt;
							&lt;outputDirectory&gt;lib&lt;/outputDirectory&gt;
							&lt;overWriteReleases&gt;true&lt;/overWriteReleases&gt;
							&lt;overWriteSnapshots&gt;true&lt;/overWriteSnapshots&gt;
							&lt;overWriteIfNewer&gt;true&lt;/overWriteIfNewer&gt;
							&lt;excludeTypes&gt;libd&lt;/excludeTypes&gt;
						&lt;/configuration&gt;
					&lt;/execution&gt;
				&lt;/executions&gt;
			&lt;/plugin&gt;
		&lt;/plugins&gt;
	&lt;/build&gt;

	&lt;dependencies&gt;

		&lt;dependency&gt;
			&lt;groupId&gt;org.mongodb&lt;/groupId&gt;
			&lt;artifactId&gt;mongo-java-driver&lt;/artifactId&gt;
			&lt;version&gt;2.11.1&lt;/version&gt;
		&lt;/dependency&gt;
		
	&lt;/dependencies&gt;

&lt;/project&gt;</pre>
<h4>InsertLogsWithMongoJavaDriver.java</h4>
<p>In the <a href="http://angelozerr.wordpress.com/2013/05/10/mongo_jee_step0/">[step0]</a>, we have inserted logs with the following Javascript Mongo Shell : </p>
<pre class="brush: jscript; title: ; notranslate">for ( var i = 0; i &lt; 100; i++) {
    db.logs.insert({
        &quot;url&quot; : &quot;http://www.mongodb.org/&quot;,
        &quot;created&quot; : new Date()
    })
}</pre>
<p>Here the same code with Java Mongo Driver : </p>
<pre class="brush: java; title: ; notranslate">package org.samples.mongodb.operations.javadriver;

import java.net.UnknownHostException;
import java.util.Calendar;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;

public class InsertLogsWithMongoJavaDriver {

	public static void main(String[] args) throws UnknownHostException {

		// Connect to Mongo DB
		MongoClientURI mongoURI = new MongoClientURI(
				&quot;mongodb://localhost:27017&quot;);
		MongoClient mongo = new MongoClient(mongoURI);
		try {

			// Get &quot;logs&quot; collection from the &quot;websites&quot; DB.
			DB db = mongo.getDB(&quot;websites&quot;);
			DBCollection coll = db.getCollection(&quot;logs&quot;);

			// Insert logs with DB object
			DBObject log = null;
			for (int i = 0; i &lt; 100; i++) {
				log = new BasicDBObject();
				log.put(&quot;url&quot;, &quot;https://github.com/angelozerr/mongo-jee&quot;);
				log.put(&quot;created&quot;, Calendar.getInstance().getTime());
				coll.insert(log);
			}

		} finally {
			mongo.close();
		}

	}
}</pre>
<p>An interesting test to do, is to start this Java main without starting the Mongo DB. The following exception is thrown : </p>
<pre class="brush: plain; title: ; notranslate">ATTENTION: Exception executing isMaster command on localhost/127.0.0.1:27017
java.net.ConnectException: Connection refused: connect
	at java.net.PlainSocketImpl.socketConnect(Native Method)</pre>
<p>by the line code : </p>
<pre class="brush: java; title: ; notranslate">coll.insert(log);</pre>
<p>So getting connection and getting DB collection code doesn&rsquo;t throw exception even if DB is not started.</p>
<h4>FindLogsWithMongoJavaDriver.java</h4>
<p>In the <a href="http://angelozerr.wordpress.com/2013/05/10/mongo_jee_step0/">[step0]</a>, we have displayed the total logs with the following Javascript Mongo Shell : </p>
<pre class="brush: jscript; title: ; notranslate">db.logs.find()</pre>
<p>Here the same code with Java Mongo Driver : </p>
<pre class="brush: java; title: ; notranslate">package org.samples.mongodb.operations.javadriver;

import java.net.UnknownHostException;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;

public class FindLogsWithMongoJavaDriver_0 {

	public static void main(String[] args) throws UnknownHostException {

		// Connect to Mongo DB
		MongoClientURI mongoURI = new MongoClientURI(
				&quot;mongodb://localhost:27017&quot;);
		MongoClient mongo = new MongoClient(mongoURI);
		try {

			// Get &quot;logs&quot; collection from the &quot;websites&quot; DB.
			DB db = mongo.getDB(&quot;websites&quot;);
			DBCollection coll = db.getCollection(&quot;logs&quot;);

			// Find all DB object from the DB collection
			DBObject log = null;
			DBCursor cursor = coll.find();
			
			// Loop for each db object of the cursor.
			while (cursor.hasNext()) {
				log = cursor.next();
				System.err.println(log.toString());
			}
		} finally {
			// close mongo connection
			mongo.close();
		}

	}
}</pre>
<p>If you execute it, you will see in the console the following JSON stream : </p>
<pre class="brush: plain; title: ; notranslate">
{ &quot;_id&quot; : { &quot;$oid&quot; : &quot;518d01813bfe01bef797d031&quot;} , 
  &quot;url&quot; : &quot;http://www.mongodb.org/&quot; , 
  &quot;created&quot; : { &quot;$date&quot; : &quot;2013-05-10T14:17:37.515Z&quot;}}
{ &quot;_id&quot; : { &quot;$oid&quot; : &quot;518d01813bfe01bef797d032&quot;} , 
  &quot;url&quot; : &quot;http://www.mongodb.org/&quot; , 
  &quot;created&quot; : { &quot;$date&quot; : &quot;2013-05-10T14:17:37.515Z&quot;}}
...
</pre>
<p>You can notice a little difference JSON representation with Mongo Shell : </p>
<pre class="brush: plain; title: ; notranslate">
{ &quot;_id&quot; : ObjectId(&quot;518d01813bfe01bef797d031&quot;), 
  &quot;url&quot; : &quot;http://www.mongodb.org/&quot;, 
  &quot;created&quot; : ISODate(&quot;2013-05-10T14:17:37.515Z&quot;) }
{ &quot;_id&quot; : ObjectId(&quot;518d01813bfe01bef797d032&quot;), 
  &quot;url&quot; : &quot;http://www.mongodb.org/&quot;, 
  &quot;created&quot; : ISODate(&quot;2013-05-10T14:17:37.515Z&quot;) }
</pre>
<p>It&rsquo;s just the JSON representation which changes. For more information, please read <a href="http://docs.mongodb.org/manual/reference/mongodb-extended-json/">MongoDB Extended JSON</a>.</p>
<p>The Java JSON stream is not a valid JSON array (it miss the [] characters and , character between each JSON log.) The driver provides the com.mongodb.util.<strong>JSON</strong> helper which is used to serialize object as JSON. To generate a JSON array,  replace the following code:</p>
<pre class="brush: java; title: ; notranslate">while (cursor.hasNext()) {
	log = cursor.next();
	System.err.println(log.toString());
}</pre>
<p>with : </p>
<pre class="brush: java; title: ; notranslate">StringBuilder buf = new StringBuilder();
JSON.serialize(cursor, buf);
System.err.println(buf.toString());</pre>
<p>Here the full Java code : </p>
<pre class="brush: java; title: ; notranslate">package org.samples.mongodb.operations.javadriver;

import java.net.UnknownHostException;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.util.JSON;

public class FindLogsWithMongoJavaDriver {

	public static void main(String[] args) throws UnknownHostException {

		// Connect to Mongo DB
		MongoClientURI mongoURI = new MongoClientURI(
				&quot;mongodb://localhost:27017&quot;);
		MongoClient mongo = new MongoClient(mongoURI);
		try {

			// Get &quot;logs&quot; collection from the &quot;websites&quot; DB.
			DB db = mongo.getDB(&quot;websites&quot;);
			DBCollection coll = db.getCollection(&quot;logs&quot;);

			// Find all DB object from the DB collection
			DBCursor cursor = coll.find();

			// Generate JSON array of the cursor.
			StringBuilder buf = new StringBuilder();
			JSON.serialize(cursor, buf);
			System.err.println(buf.toString());

		} finally {
			// close mongo connection
			mongo.close();
		}

	}
}</pre>
<p>If you execute this class, you will see the following JSON array stream, on the console : </p>
<pre class="brush: plain; title: ; notranslate">[ 
{ &quot;_id&quot; : { &quot;$oid&quot; : &quot;518d01813bfe01bef797d031&quot;} , 
  &quot;url&quot; : &quot;http://www.mongodb.org/&quot; , 
  &quot;created&quot; : { &quot;$date&quot; : &quot;2013-05-10T14:17:37.515Z&quot;}} , 
{ &quot;_id&quot; : { &quot;$oid&quot; : &quot;518d01813bfe01bef797d032&quot;} , 
  &quot;url&quot; : &quot;http://www.mongodb.org/&quot; , 
  &quot;created&quot; : { &quot;$date&quot; : &quot;2013-05-10T14:17:37.515Z&quot;}} ,
...]</pre>
<h4>RemoveLogsWithMongoJavaDriver.java</h4>
<p>In the <a href="http://angelozerr.wordpress.com/2013/05/10/mongo_jee_step0/">[step0]</a>, we have removed all logs with the following Javascript Mongo Shell : </p>
<pre class="brush: jscript; title: ; notranslate">db.logs.remove()</pre>
<p>Here the same code with Java Mongo Driver : </p>
<pre class="brush: java; title: ; notranslate">package org.samples.mongodb.operations.javadriver;

import java.net.UnknownHostException;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;

public class RemoveLogsWithMongoJavaDriver {

	public static void main(String[] args) throws UnknownHostException {

		// Connect to Mongo DB
		MongoClientURI mongoURI = new MongoClientURI(
				&quot;mongodb://localhost:27017&quot;);
		MongoClient mongo = new MongoClient(mongoURI);
		try {

			// Get &quot;logs&quot; collection from the &quot;websites&quot; DB.
			DB db = mongo.getDB(&quot;websites&quot;);
			DBCollection coll = db.getCollection(&quot;logs&quot;);

			// remove all logs
			coll.remove(new BasicDBObject());

		} finally {
			// close mongo connection
			mongo.close();
		}

	}
}</pre>
<h4>FindPaginatedLogsWithMongoJavaDriver.java</h4>
<p>In the <a href="http://angelozerr.wordpress.com/2013/05/10/mongo_jee_step0/">[step0]</a>, we have displayed paginated logs with the following Javascript Mongo Shell :</p>
<pre class="brush: jscript; title: ; notranslate">var pageIndex = 0;
var pageSize = 5;
db.logs.find().skip(pageIndex).limit(pageSize);</pre>
<p>Here the same code with Java Mongo Driver : </p>
<pre class="brush: java; title: ; notranslate">package org.samples.mongodb.operations.javadriver;

import java.net.UnknownHostException;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.util.JSON;

public class FindPaginatedLogsWithMongoJavaDriver {

	public static void main(String[] args) throws UnknownHostException {

		// Connect to Mongo DB
		MongoClientURI mongoURI = new MongoClientURI(
				&quot;mongodb://localhost:27017&quot;);
		MongoClient mongo = new MongoClient(mongoURI);
		try {

			// Get &quot;logs&quot; collection from the &quot;websites&quot; DB.
			DB db = mongo.getDB(&quot;websites&quot;);
			DBCollection coll = db.getCollection(&quot;logs&quot;);

			// Find paginated DB object from the DB collection
			int pageIndex = 0;
			int pageSize = 5;
			DBCursor cursor = coll.find().skip(pageIndex).limit(pageSize);

			// Generate JSON array of the cursor.
			StringBuilder buf = new StringBuilder();
			JSON.serialize(cursor, buf);
			System.err.println(buf.toString());

		} finally {
			// close mongo connection
			mongo.close();
		}

	}
}</pre>
<h3 id="MongoJack">Pojo Mapper MongoJack</h3>
<p>Pojo Mapper gives you the capability to <strong>use Pojo instead of using Mongo DBObject</strong>. It follows the same idea than JPA. </p>
<p>It exists several Pojo Mapper that you can see <a href="http://docs.mongodb.org/ecosystem/drivers/java/#pojo-mappers">here</a>. </p>
<p>There are not a specification for Pojo Mapper Mongo (compared to JPA), so each Pojo Mapper <strong>provides their annotations to map the Pojo fields with Mongo JSON properties</strong>.</p>
<p>The whole Pojo Mappers uses the Mongo Java Driver. </p>
<p>I have choosen to use <a href="http://mongojack.org/">MongoJack</a> as Pojo Mapper in my article because I think it&rsquo;s the <strong>more fast than other Pojo Mappers</strong>. Indeed, it implements their own com.mongodb.DBDecoder (see org.mongojack.internal.stream.JacksonDBDecoder). </p>
<p>The other Pojo Mapper that I have studied uses the default DBDecoder of the driver : the pojo mapper uses this decoder to get DBObject and build a Pojo from this DBObject. With Mongojack, the JacksonDBDecoder creates directly the Pojo without creating an instance of DBObject.</p>
<h4>Download MongoJack</h4>
<p>To download MongoJack, I have used this maven dependency :</p>
<pre class="brush: xml; title: ; notranslate">&lt;dependency&gt;
	&lt;groupId&gt;org.mongojack&lt;/groupId&gt;
	&lt;artifactId&gt;mongojack&lt;/artifactId&gt;
	&lt;version&gt;2.0.0-RC5&lt;/version&gt;
&lt;/dependency&gt;</pre>
<h4>Pojo Log</h4>
<p>To use the Pojo Mapper Mongojack, we need to create a Pojo Log like this: </p>
<pre class="brush: java; title: ; notranslate">package org.samples.mongodb.operations.pojomapper.mongojack;

import java.util.Date;

import javax.persistence.Id;

public class Log {

	@Id
	private String id;

	private String url;
	private Date created;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public Date getCreated() {
		return created;
	}

	public void setCreated(Date created) {
		this.created = created;
	}

}
</pre>
<p>You can notice that the annotation <strong>javax.persistence.Id</strong> is used to map it with ObjectId.</p>
<h4>InsertLogsWithMongoJack</h4>
<p>Here the code to insert logs with Pojo Mapper Mongojack : </p>
<pre class="brush: java; title: ; notranslate">package org.samples.mongodb.operations.pojomapper.mongojack;

import java.net.UnknownHostException;
import java.util.Calendar;

import org.mongojack.JacksonDBCollection;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;

public class InsertLogsWithMongoJack {

	public static void main(String[] args) throws UnknownHostException {

		// Connect to Mongo DB
		MongoClientURI mongoURI = new MongoClientURI(
				&quot;mongodb://localhost:27017&quot;);
		MongoClient mongo = new MongoClient(mongoURI);
		try {

			// Get &quot;logs&quot; collection from the &quot;websites&quot; DB.
			DB db = mongo.getDB(&quot;websites&quot;);
			DBCollection dbColl = db.getCollection(&quot;logs&quot;);

			// Use Pojo Mapper MongoJack
			JacksonDBCollection&lt;Log, String&gt; coll = JacksonDBCollection.wrap(
					dbColl, Log.class, String.class);

			// Insert logs with Pojo Log
			Log log = null;
			for (int i = 0; i &lt; 100; i++) {
				log = new Log();
				log.setUrl(&quot;http://mongojack.org/&quot;);
				log.setCreated(Calendar.getInstance().getTime());
				coll.insert(log);
			}

		} finally {
			// close mongo connection
			mongo.close();
		}

	}
}</pre>
<h4>FindLogsWithMongoJack</h4>
<p>Here the code to find total logs with Pojo Mapper Mongojack : </p>
<pre class="brush: java; title: ; notranslate">package org.samples.mongodb.operations.pojomapper.mongojack;

import java.io.IOException;

import org.mongojack.DBCursor;
import org.mongojack.JacksonDBCollection;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;

public class FindLogsWithMongoJack {

	public static void main(String[] args) throws JsonGenerationException,
			JsonMappingException, IOException {

		// Connect to Mongo DB
		MongoClientURI mongoURI = new MongoClientURI(
				&quot;mongodb://localhost:27017&quot;);
		MongoClient mongo = new MongoClient(mongoURI);
		try {

			// Get &quot;logs&quot; collection from the &quot;websites&quot; DB.
			DB db = mongo.getDB(&quot;websites&quot;);
			DBCollection dbColl = db.getCollection(&quot;logs&quot;);

			// Use Pojo Mapper MongoJack
			JacksonDBCollection&lt;Log, String&gt; coll = JacksonDBCollection.wrap(
					dbColl, Log.class, String.class);

			// Find all Pojo Log from the MongoJack collection
			DBCursor&lt;Log&gt; cursor = coll.find();

			// Serialize list of Log as JSON
			ObjectMapper om = new ObjectMapper();
			om.writer().writeValue(System.err, cursor.toArray());

		} finally {
			// close mongo connection
			mongo.close();
		}

	}
}</pre>
<h4>RemoveLogsWithMongoJack</h4>
<p>Here the code to remove total logs with Pojo Mapper Mongojack : </p>
<pre class="brush: java; title: ; notranslate">package org.samples.mongodb.operations.pojomapper.mongojack;

import java.net.UnknownHostException;

import org.mongojack.JacksonDBCollection;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;

public class RemoveLogsWithMongoJack {

	public static void main(String[] args) throws UnknownHostException {

		// Connect to Mongo DB
		MongoClientURI mongoURI = new MongoClientURI(
				&quot;mongodb://localhost:27017&quot;);
		MongoClient mongo = new MongoClient(mongoURI);
		try {

			// Get &quot;logs&quot; collection from the &quot;websites&quot; DB.
			DB db = mongo.getDB(&quot;websites&quot;);
			DBCollection dbColl = db.getCollection(&quot;logs&quot;);

			// Use Pojo Mapper MongoJack
			JacksonDBCollection&lt;Log, String&gt; coll = JacksonDBCollection.wrap(
					dbColl, Log.class, String.class);

			// remove all logs
			coll.remove(new BasicDBObject());

		} finally {
			// close mongo connection
			mongo.close();
		}

	}
}</pre>
<h4>FindPaginatedLogsWithMongoJack</h4>
<p>Here the code to return paginated logs with Pojo Mapper Mongojack : </p>
<pre class="brush: java; title: ; notranslate">package org.samples.mongodb.operations.pojomapper.mongojack;

import java.io.IOException;

import org.mongojack.DBCursor;
import org.mongojack.JacksonDBCollection;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;

public class FindPaginatedLogsWithMongoJack {

	public static void main(String[] args) throws JsonGenerationException,
			JsonMappingException, IOException {

		// Connect to Mongo DB
		MongoClientURI mongoURI = new MongoClientURI(
				&quot;mongodb://localhost:27017&quot;);
		MongoClient mongo = new MongoClient(mongoURI);
		try {

			// Get &quot;logs&quot; collection from the &quot;websites&quot; DB.
			DB db = mongo.getDB(&quot;websites&quot;);
			DBCollection dbColl = db.getCollection(&quot;logs&quot;);

			// Use Pojo Mapper MongoJack
			JacksonDBCollection&lt;Log, String&gt; coll = JacksonDBCollection.wrap(
					dbColl, Log.class, String.class);

			// Find paginated Pojo Log from the MongoJack collection
			int pageIndex = 0;
			int pageSize = 5;
			DBCursor&lt;Log&gt; cursor = coll.find().skip(pageIndex).limit(pageSize);

			// Serialize list of Log as JSON
			ObjectMapper om = new ObjectMapper();
			om.writer().writeValue(System.err, cursor.toArray());

		} finally {
			// close mongo connection
			mongo.close();
		}

	}
}</pre>
<h2>Conclusion</h2>
<p>In this article we have seen how to manage with Java code basic mongo operations (insert, remove etc) with Mongo Java Driver and Pojo Mapper. Pojo Mapper requires to create a Pojo. </p>
<p>In the next article <a href="http://angelozerr.wordpress.com/2013/05/11/mongo_jee_step2/">[step2]</a>, we will use Mongo in a JEE Servlet.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/angelozerr.wordpress.com/7215/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/angelozerr.wordpress.com/7215/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=angelozerr.wordpress.com&#038;blog=10338309&#038;post=7215&#038;subd=angelozerr&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://angelozerr.wordpress.com/2013/05/10/mongo_jee_step1/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/4c3176f508ba2f224d3b00dce0ca6c2a?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">akrogen</media:title>
		</media:content>

		<media:content url="http://angelozerr.files.wordpress.com/2013/05/mongojee_step1.png" medium="image" />
	</item>
		<item>
		<title>Mongo JEE [step0]</title>
		<link>http://angelozerr.wordpress.com/2013/05/10/mongo_jee_step0/</link>
		<comments>http://angelozerr.wordpress.com/2013/05/10/mongo_jee_step0/#comments</comments>
		<pubDate>Fri, 10 May 2013 09:09:19 +0000</pubDate>
		<dc:creator>angelozerr</dc:creator>
				<category><![CDATA[Apache CXF]]></category>
		<category><![CDATA[Dojo]]></category>
		<category><![CDATA[Mongo JEE]]></category>
		<category><![CDATA[MongoDB]]></category>

		<guid isPermaLink="false">http://angelozerr.wordpress.com/?p=7243</guid>
		<description><![CDATA[Several months ago, I have studied how to use Mongo DB in a JEE Application. I read the great article Modern Web Apps using JAX-RS, MongoDB, JSON, and jQuery which explains how to develop modern Web Apps : on client side, AJAX with jQuery is used to consume JSON by calling a REST service. on [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=angelozerr.wordpress.com&#038;blog=10338309&#038;post=7243&#038;subd=angelozerr&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>Several months ago, I have studied how to <strong>use Mongo DB in a JEE Application</strong>. I read the great article <a href="http://architects.dzone.com/articles/modern-web-apps-using-jax-rs">Modern Web Apps using JAX-RS, MongoDB, JSON, and jQuery</a> which explains how to develop modern Web Apps : </p>
<ul>
<li>on client side, <strong>AJAX with jQuery</strong> is used to <strong>consume JSON by calling a REST service</strong>.
  </li>
<li>on server side, <strong>REST service managed with JAX-RS produces JSON stream</strong> coming <strong>from MongoDB</strong>. The REST service calls MongoDB with <a href="https://github.com/vznet/mongo-jackson-mapper">mongo-jackson-mapper</a> which gets JSON stream from MongoDB (which stores their data with BSON format which looks like JSON) and serializes the JSON to build a Pojo. The REST service returns the Pojo and JAX-RS implementation deserializes the Pojo to produce JSON for the jQuery client.
  </li>
</ul>
<p>On other words, the <strong>server produces JSON</strong> and not the whole HTML page and the <strong>client consumes JSON</strong> to refresh the UI.</p>
<p>I like this architecture, but I tell me why we could to use directly the JSON stream from MongoDB instead of serialize/deserialize a Pojo. That&rsquo;s why I have created <a href="https://github.com/angelozerr/mongo-jee">Mongo JEE</a> project which <strong>helps you to use Mongo in a JEE Application</strong>. </p>
<p>I have decided to write <a href="http://angelozerr.wordpress.com/about/mongo_jee">Mongo JEE articles</a> which shows in action the feature of <a href="https://github.com/angelozerr/mongo-jee">Mongo JEE</a>. Those articles will explain step by step how to develop a <strong>Dojo Grid with pagination</strong> which <strong>consumes a JAX-RS REST</strong> service which produces JSON coming <strong>directly from the MongoDB</strong> <strong>with Java Driver and not with Pojo-Mapper</strong>. At the end of those articles we will have a paginated grid populated with logs data : </p>
<p><img src="http://angelozerr.files.wordpress.com/2013/05/mongojee_dojo.png?w=587" /></p>
<ul>
<li>step [1] : the user call the index.htm page.
  </li>
<li>step [2] : the server returns the content of the index.htm page which contains the code of the Dojo grid (without the data).
  </li>
<li>step [3] : once the dojo grid is built, it calls the REST service to populate the grid by sending on the HTTP Header the &quot;Range&quot; parameter (ex : items=0-9). This Range parameter tells to the server the from and to item index that grid needs to populate data.
  </li>
<li>step [4] : the REST service request the MongoDB and returns the JSON coming from the MongoDB to the Web client. The dojo grid receives the JSON and populate the grid. When page link is clicked, the step [3] and [4] are re-played.
  </li>
</ul>
<p>In this article, we will install and initialize MongoDB by creating a <strong>websites database</strong> which contains <strong>logs collection</strong>. A logs is just composed with date created and url.</p>
<p><span id="more-7243"></span></p>
<h2>MongoDB Install</h2>
<h3>Choose the mongo distribution</h3>
<p>MongoDB Install is very easy, you must just <a href="http://www.mongodb.org/downloads">download</a> the well distribution according your OS. In my case, I have Windows XP, and <a href="http://docs.mongodb.org/manual/release-notes/2.2/#windows-specific-changes">since 2.2, MongoDB doesn&rsquo;t support Windows XP</a>. </p>
<p>So if you <strong>use Windows XP</strong>, the last version of MongoDB that you can use is the <strong>2.0.8</strong> that you can download <a href="http://downloads.mongodb.org/win32/mongodb-win32-i386-2.0.8.zip">mongodb-win32-i386-2.0.8.zip</a>.</p>
<h3>Unzip mongo distribution</h3>
<p>Unzip <a href="http://downloads.mongodb.org/win32/mongodb-win32-i386-2.0.8.zip">mongodb-win32-i386-2.0.8.zip</a> in any folder of your hard disk. In my case I have unzipped it in the <strong>D:/MongoDB</strong> : </p>
<p><img src="http://angelozerr.files.wordpress.com/2012/12/webappsmongodb_install1.png?w=595" /></p>
<h3>Create data folder</h3>
<p>MongoDB needs a folder to store data of the database. By default it search the data in the <strong>/data/db</strong> folder. In my case as I have installed my Mongo in <strong>D:</strong> folder, so I must create the data folder <strong>D:\data\db</strong> : </p>
<p><img src="http://angelozerr.files.wordpress.com/2012/12/webappsmongodb_install2.png?w=595"></p>
<h2>Start mongo</h2>
<p>At this step, MongoDB is installed and now we can start it. To do that open a DOS command prompt and go at bin folder of the Mongo</p>
<p>In my case : </p>
<pre class="brush: plain; title: ; notranslate">
D:
cd D:\MongoDB\mongodb-win32-i386-2.0.8\bin
</pre>
<p>And after start the Mongo process by typing :</p>
<pre class="brush: plain; title: ; notranslate">
mongod
</pre>
<p><img src="http://angelozerr.files.wordpress.com/2012/12/webappsmongodb_start1.png?w=595" /></p>
<p>This process starts the MongoDB and listen by default to the 27017 port :</p>
<p><img src="http://angelozerr.files.wordpress.com/2012/12/webappsmongodb_start2.png?w=595" /></p>
<p>If you see the data folder, you will notice that a <strong>mongod.lock</strong> file is created with 1Ko:</p>
<p><img src="http://angelozerr.files.wordpress.com/2013/05/mongo_start1.png?w=595" /></p>
<p>It means that Mongo DB lock the files of the data folder.</p>
<p>When you stop the Mongo DB (with Ctrl+C) : </p>
<p><img src="http://angelozerr.files.wordpress.com/2013/05/mongo_start2.png?w=595" /></p>
<p>The <strong>mongod.lock</strong> file is updated with 0Ko:</p>
<p><img src="http://angelozerr.files.wordpress.com/2013/05/mongo_start3.png?w=595" /></p>
<p>I have noticed that if MongoDB is not stopped with clean mean (eg : Mongo DB crashes), the <strong>mongod.lock</strong> file can have 1Ko and it&rsquo;s impossible to restart the Mongo.<br />
To fix this problem, you must remove at hand this file before trying to restart it.</p>
<h2>Initialize DB</h2>
<p>Just for information, Mongo DB is composed with : </p>
<ul>
<li>several <strong>databases</strong></li>
<li>each database contains several <strong>collections</strong> (it&rsquo;s like Table for SQL).</li>
<li>each collection contains several document (or object) which are structured with JSON format (BSON) (it&rsquo;s like record for SQL).</li>
</ul>
<p>At this step we can initialize the DB by creating a <strong>websites database</strong> which contains <strong>BSON document log</strong> in the <strong>logs collection</strong>. To do that we can do it with several means (in a Java world) : </p>
<ul>
<li>Mongo Shell scripts</li>
<li>Java code which uses <a href="https://github.com/mongodb/mongo-java-driver">Mongo Java Driver</a></li>
<li><a href="http://www.mongodb.org/display/DOCS/Java+Language+Center#JavaLanguageCenter-POJOMappers">Pojo Mapper</a>. You can compare Pojo Mapper to JPA. Pojo Mapper uses the <a href="https://github.com/mongodb/mongo-java-driver">Mongo Java Driver</a> to connect to the Mongo and create a Pojo. Each Pojo Mapper provides their own annotations to manage the mapping between getter/setter of the Pojo and the BSON document property.</li>
</ul>
<p>In this article we will use <a href="#shell">Mongo Shell scripts</a> and in the next article <a href="http://angelozerr.wordpress.com/2013/05/10/mongo_jee_step1/">[step1]</a> Mongo Java Driver, and a Pojo Mapper.</p>
<h3 id="shell">Mongo Shell scripts</h3>
<p><cite>The <a href="http://docs.mongodb.org/manual/mongo/">mongo shell</a>  is an interactive JavaScript shell for MongoDB, and is part of all MongoDB distributions.</cite></p>
<p>To use it, open a DOS command prompt and go at bin folder of the Mongo</p>
<p>In my case : </p>
<pre class="brush: plain; title: ; notranslate">
D:
cd D:\MongoDB\mongodb-win32-i386-2.0.8\bin
</pre>
<p>And after start the Mongo shell by typing :</p>
<pre class="brush: plain; title: ; notranslate">
mongo
</pre>
<p><img src="http://angelozerr.files.wordpress.com/2013/05/mongo_shell1.png?w=595" /></p>
<p>This command open the Mongo Shell and connect it to &quot;test&quot; database. It doesn&rsquo;t exists some commands to create a database. The database is created as soon as a first document is created.<br />
In our case we wish to have <strong>websites</strong> database which contains <strong>logs</strong> collection. To do that, type this command :</p>
<pre class="brush: plain; title: ; notranslate">
use websites
</pre>
<p><img src="http://angelozerr.files.wordpress.com/2013/05/mongo_shell2.png?w=595" /></p>
<p>If you see the data folder, you will notice that websites files is not created.</p>
<h4>InsertLogsWithMongoShell.js</h4>
<p>To insert logs with Mongo shell copy/paste this javascript in the shell : </p>
<pre class="brush: jscript; title: ; notranslate">for ( var i = 0; i &lt; 100; i++) {
	db.logs.insert({
		&quot;url&quot; : &quot;http://www.mongodb.org/&quot;,
		&quot;created&quot; : new Date()
	})
}</pre>
<p>Key &quot;Enter&quot; to execute this script.</p>
<p><img src="http://angelozerr.files.wordpress.com/2013/05/mongo_shell3.png?w=595" /></p>
<p>You can notice that there are no commit, because Mongo DB is not transactional.</p>
<p>If you see the data folder you will notice that websites* files which contains data are created : </p>
<p><img src="http://angelozerr.files.wordpress.com/2013/05/mongo_start4.png?w=595" /></p>
<h4>FindLogsWithMongoShell.js</h4>
<p>To check that our logs was inserted correctly, copy/paste this script :</p>
<pre class="brush: jscript; title: ; notranslate">db.logs.find()</pre>
<p>Key &quot;Enter&quot; to execute this script  and you will see the data logs as JSON format : </p>
<p><img src="http://angelozerr.files.wordpress.com/2013/05/mongo_shell4.png?w=595" /></p>
<p>You can notice that there are &quot;_id&quot; property (that we have not filled). Each JSON document have an unique &quot;_id&quot; (that you can fill it if you wish).</p>
<h4>RemoveLogsWithMongoShell.js</h4>
<p>Here a script which removes logs:</p>
<pre class="brush: jscript; title: ; notranslate">db.logs.remove()</pre>
<h4>FindPaginatedLogsWithMongoShell.js</h4>
<p>In your case we will need pagination logs. Here the script which manage pagination for logs collection : </p>
<pre class="brush: jscript; title: ; notranslate">var pageIndex = 0;
var pageSize = 5;
db.logs.find().skip(pageIndex).limit(pageSize);</pre>
<h2>Conclusion</h2>
<p>In this step we have introduce <a href="http://angelozerr.wordpress.com/about/mongo_jee">Mongo JEE articles</a>, install and initialize Mongo DB websites database with Mongo Shell scripts. In the next article <a href="http://angelozerr.wordpress.com/2013/05/10/mongo_jee_step1/">[step1]</a>, we will use Java Mongo Driver and a Pojo Mapper to do the same thing.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/angelozerr.wordpress.com/7243/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/angelozerr.wordpress.com/7243/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=angelozerr.wordpress.com&#038;blog=10338309&#038;post=7243&#038;subd=angelozerr&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://angelozerr.wordpress.com/2013/05/10/mongo_jee_step0/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/4c3176f508ba2f224d3b00dce0ca6c2a?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">akrogen</media:title>
		</media:content>

		<media:content url="http://angelozerr.files.wordpress.com/2013/05/mongojee_dojo.png?w=587" medium="image" />

		<media:content url="http://angelozerr.files.wordpress.com/2012/12/webappsmongodb_install1.png" medium="image" />

		<media:content url="http://angelozerr.files.wordpress.com/2012/12/webappsmongodb_install2.png" medium="image" />

		<media:content url="http://angelozerr.files.wordpress.com/2012/12/webappsmongodb_start1.png" medium="image" />

		<media:content url="http://angelozerr.files.wordpress.com/2012/12/webappsmongodb_start2.png" medium="image" />

		<media:content url="http://angelozerr.files.wordpress.com/2013/05/mongo_start1.png" medium="image" />

		<media:content url="http://angelozerr.files.wordpress.com/2013/05/mongo_start2.png" medium="image" />

		<media:content url="http://angelozerr.files.wordpress.com/2013/05/mongo_start3.png" medium="image" />

		<media:content url="http://angelozerr.files.wordpress.com/2013/05/mongo_shell1.png" medium="image" />

		<media:content url="http://angelozerr.files.wordpress.com/2013/05/mongo_shell2.png" medium="image" />

		<media:content url="http://angelozerr.files.wordpress.com/2013/05/mongo_shell3.png" medium="image" />

		<media:content url="http://angelozerr.files.wordpress.com/2013/05/mongo_start4.png" medium="image" />

		<media:content url="http://angelozerr.files.wordpress.com/2013/05/mongo_shell4.png" medium="image" />
	</item>
		<item>
		<title>How to convert docx/odt to pdf/html with Java?</title>
		<link>http://angelozerr.wordpress.com/2012/12/06/how-to-convert-docxodt-to-pdfhtml-with-java/</link>
		<comments>http://angelozerr.wordpress.com/2012/12/06/how-to-convert-docxodt-to-pdfhtml-with-java/#comments</comments>
		<pubDate>Thu, 06 Dec 2012 12:26:25 +0000</pubDate>
		<dc:creator>angelozerr</dc:creator>
				<category><![CDATA[XDocReport]]></category>
		<category><![CDATA[Apache ODFDOM]]></category>
		<category><![CDATA[Apache POI]]></category>
		<category><![CDATA[docx4j]]></category>
		<category><![CDATA[FOP]]></category>
		<category><![CDATA[iText]]></category>
		<category><![CDATA[JODConverter]]></category>

		<guid isPermaLink="false">http://angelozerr.wordpress.com/?p=7020</guid>
		<description><![CDATA[How to convert docx/odt to pdf/html with Java? This question comes up all the time in any forum like stackoverflow. So I decided to write an article about this topic to enumerate the Java (open source) frameworks which manages that. Here some paid product which manages docx/odt to pdf/html converters : Aspose.Words for Java which [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=angelozerr.wordpress.com&#038;blog=10338309&#038;post=7020&#038;subd=angelozerr&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><strong>How to convert docx/odt to pdf/html with Java?</strong> This question comes up all the time in any forum like <a href="http://stackoverflow.com">stackoverflow</a>. So I decided to write an article about this topic to enumerate the Java (open source) frameworks which manages that. </p>
<p>Here some <strong>paid product</strong> which manages docx/odt to pdf/html converters :</p>
<ul>
<li><a href="http://www.aspose.com/categories/java-components/aspose.words-for-java/default.aspx">Aspose.Words for Java</a> which manages only docx converter.
  </li>
<li><a href="http://www.docmosis.com/">Docmosis</a> which manages docx and odt converters.
  </li>
<li><a href="http://www.muhimbi.com/Products/PDF-Converter-Services/summary.aspx">Muhimbi PDF Converter Services</a>.
  </li>
</ul>
<p>To be honest with you, I have not tried those solution because it&rsquo;s not free. I will not speak about them in this article.</p>
<p>Here some <strong>open source product</strong> which manages docx/odt to pdf/html converters :</p>
<ul>
<li><a href="http://code.google.com/p/jodconverter/">JODConverter</a> : <cite>JODConverter automates conversions between office document formats using OpenOffice.org or LibreOffice. Supported formats include OpenDocument, PDF, RTF, HTML, Word, Excel, PowerPoint, and Flash. It can be used as a Java library, a command line tool, or a web application.</cite>
  </li>
<li><a href="http://www.docx4java.org/trac/docx4j">docx4j</a>: <cite>docx4j is a Java library for creating and manipulating Microsoft Open XML (Word docx, Powerpoint pptx, and Excel xlsx) files. It is similar to Microsoft&rsquo;s OpenXML SDK, but for Java. docx4j uses JAXB to create the in-memory object representation.</cite>
  </li>
<li><a href="http://code.google.com/p/xdocreport/wiki/Converters">XDocReport</a> which provides:
<ul>
<li><a href="http://code.google.com/p/xdocreport/wiki/XWPFConverter">docx converters</a> which works with <a href="http://poi.apache.org/hwpf/index.html">Apache POI XWPF</a> and <a href="http://itextpdf.com/">iText</a> 2.3.7 for PDF.
      </li>
<li><a href="http://code.google.com/p/xdocreport/wiki/ODFDOMConverter">odt converters</a> which works with <a href="http://incubator.apache.org/odftoolkit/odfdom/index.html">ODFDOM</a> and <a href="http://itextpdf.com/">iText</a> 2.3.7 for PDF.
      </li>
</li>
</ul>
</li>
</ul>
<p>Here criteria that I think which are important for converters : </p>
<ul>
<li><strong>best renderer</strong> : the converter must not loose some formatting information.</li>
<li><strong>fast</strong> : the converter must be the more fast.</li>
<li><strong>less memory intensive</strong> to avoid OutOfMemory problem.</li>
<li><strong>streaming</strong>: use InputStream/OutputStream instead of File. Using streaming instead of File, avoids some problems (hard disk is not used, no need to have write right on the hard disk)</li>
<li><strong>easy to install</strong>: no need to install OpenOffice/LibreOffice, MS Word on the server to manage converter.</li>
</ul>
<p>In this article I will introduce those 3 Java frameworks converters and I will compare it to give Pros/Cons for each framework and try to be more frankly because I&rsquo;m one of <a href="http://code.google.com/p/xdocreport/">XDocReport</a> developer.</p>
<p>If you want to compare result of conversion, performance, etc of docx4j and XDocReport quickly, you can play with our <a href="http://xdocreport-converter.opensagres.cloudbees.net/">live demo</a> which provides a <a href="http://code.google.com/p/xdocreport/wiki/RESTSOAPConverters">JAX-RS REST converter service</a>. </p>
<p><span id="more-7020"></span></p>
<h2>Sorry with my English!</h2>
<p>Before starting to read this article, I would like to apologize me with my bad English. I don&rsquo;t want to say &quot;XDocReport is the best&quot; and I don&rsquo;t want to have some offence with JODConverter, docx4j, FOP guys. Goal of this article is to introduce those 3 frameworks converters and share my skills about odt and docx converters to PDF.</p>
<h2>Download</h2>
<p>You can download samples of docx/odt converters explained in this article : </p>
<ul>
<li><a href="http://dl.dropbox.com/u/2903680/wordpress-blog/tutoriels/java/converters/org.samples.docxconverters.jodconverter.zip">org.samples.docxconverters.jodconverter.zip</a> : samples of conversion docx to PDF/HTML with JODConverter.
  </li>
<li><a href="http://dl.dropbox.com/u/2903680/wordpress-blog/tutoriels/java/converters/org.samples.docxconverters.docx4j.zip">org.samples.docxconverters.docx4j.zip</a> samples of conversion docx to PDF/HTML with docx4j.
  </li>
<li><a href="http://dl.dropbox.com/u/2903680/wordpress-blog/tutoriels/java/converters/org.samples.docxconverters.xdocreport.zip">org.samples.docxconverters.xdocreport.zip</a> samples of conversion docx to PDF/HTML with XDocReport (Apache POI XWPF).
  </li>
</ul>
<h2>How to manage PDF with Java?</h2>
<p>Here the 3 best famous Java PDF libraries: </p>
<ul>
<li><a href="http://xmlgraphics.apache.org/fop/">Apache FOP</a>: <cite>Apache FOP (Formatting Objects Processor) is a print formatter driven by XSL formatting objects (XSL-FO) and an output independent formatter. It is a Java application that reads a formatting object (FO) tree and renders the resulting pages to a specified output. Output formats currently supported include PDF, PS, PCL, AFP, XML (area tree representation), Print, AWT and PNG, and to a lesser extent, RTF and TXT. The primary output target is PDF.</cite>
  </li>
<li><a href="http://pdfbox.apache.org/">Apache PDFBox</a>: <cite>The Apache PDFBox library is an open source Java tool for working with PDF documents. This project allows creation of new PDF documents, manipulation of existing documents and the ability to extract content from documents. Apache PDFBox also includes several command line utilities. Apache PDFBox is published under the Apache License v2.0</cite>
  </li>
<li><a href="http://itextpdf.com/">iText</a>: <cite>iText is a library that allows you to create and manipulate PDF documents. It enables developers looking to enhance web- and other applications with dynamic PDF document generation and/or manipulation.</cite>
<p>With iText, there are 2 versions: </p>
<ul>
<li>2.3.x which is MPL License.
	  </li>
<li>5.x which is AGPL License.
	  </li>
</ul>
</li>
</ul>
<h2>How to convert docx/odt to pdf/html with Java?</h2>
<p>Just for information, docx and odt files are a zip which is composed with:</p>
<ul>
<li><strong>several xml entries</strong> like word/document.xml (docx), content.xml (odt) which describes with XML the content of the document, styles.xml which describes used styles, etc.
<li><strong>binary data for image</strong>.
  </li>
</ul>
<p>To compare performance between JODConverter, docx4j, XDocReport framework converters, tests must follow 2 rules: </p>
<ul>
<li><strong>logs must be disabled</strong> to ignore time of generated log (ex: docx4j generates a lot of logs which degrade the performance).
  </li>
<li><strong>convert twice the docx/odt to html/pdf</strong>, to <strong>ignore time of the initialization of the framework converter</strong> (ex: ignore time of connection to LibreOffice with JODConverter, ignore time of the load of JAXB classes of docx4j, etc). To compare our converters frameworks, we will convert twice the docx and will retain the last elapsed time.
  </li>
</ul>
<p>To compare the result quality of the conversion, I have tried to use on each samples converters project, several docx which are designed with Table (border, rows/cols span), Header/Footer, images etc. In this article we will just study simple docx HelloWorld.docx :</p>
<p><img src="http://angelozerr.files.wordpress.com/2012/12/helloworddocx.png?w=595" /></p>
<p>But you can launch the other docx of each Java Eclipse Project to see the result of html and pdf conversion.</p>
<h3>JODConverter with docx</h3>
<p>To test and <strong>use JODConverter, you need to install OpenOffice or LibreOffice</strong>. In my case I have installed <strong>LibreOffice 3.5 on Windows</strong>. </p>
<p><strong>org.samples.docxconverters.jodconverter</strong> Eclipse project that you can <a href="http://dl.dropbox.com/u/2903680/wordpress-blog/tutoriels/java/converters/org.samples.docxconverters.jodconverter.zip">download here</a> is sample of docx converter with JODConverter. This project contains: </p>
<ul>
<li><strong>docx</strong> folder which contains several docx to convert. Those docx comes from the <a href="http://code.google.com/p/xdocreport/source/browse/#git%2Fthirdparties-extension%2Forg.apache.poi.xwpf.converter.pdf%2Fsrc%2Ftest%2Fresources%2Forg%2Fapache%2Fpoi%2Fxwpf%2Fconverter%2Fcore">XDocReport Git</a> that we use to test our converter.
  </li>
<li><strong>pdf and html folders</strong> where docx will be converted.
  </li>
<li><strong>lib folder whith JODConverter and dependencies JARs</strong>.
  </li>
</ul>
<p><img src="http://angelozerr.files.wordpress.com/2012/12/javaconverters_jodconverteproject.png?w=595" /></p>
<h4>Download JARs</h4>
<p>To download JODConverter JARs, <a href="https://code.google.com/p/jodconverter/downloads/list">download </a> the zip <a href="https://code.google.com/p/jodconverter/downloads/detail?name=jodconverter-core-3.0-beta-4-dist.zip&amp;can=2&amp;q=">jodconverter-core-3.0-beta-4-dist.zip</a>, unzip it and copy paste the lib folder of the zip to your Eclipse Java project. Add those JARs in your classpath.</p>
<p>My test was done with LibreOffice 3.5 and the official distribution doesn&rsquo;t work with LibreOffice 3.5 (see <a href="http://code.google.com/p/jodconverter/issues/detail?id=103">issue 103</a>).<br />
To fix this problem, I have replaced the official JARs <strong>jodconverter-core-3.0-beta-4.jar</strong> with <a href="https://devtools.jahia.com/nexus/content/groups/public/org/artofsolving/jodconverter/jodconverter-core/3.0-beta-4-jahia2/jodconverter-core-3.0-beta-4-jahia2.jar">jodconverter-core-3.0-beta-4-jahia2.jar</a>.</p>
<h4>HTML converter</h4>
<p>Here the JODConverter Java code which converts twice the &quot;docx/HelloWorld.docx&quot; to &quot;html/HelloWorld.html&quot;: </p>
<pre class="brush: java; title: ; notranslate"> 
package org.samples.docxconverters.jodconverter.html;

import java.io.File;

import org.artofsolving.jodconverter.OfficeDocumentConverter;
import org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration;
import org.artofsolving.jodconverter.office.OfficeManager;

public class HelloWorldToHTML {

	public static void main(String[] args) {

		// 1) Start LibreOffice in headless mode.
		OfficeManager officeManager = null;
		try {
			officeManager = new DefaultOfficeManagerConfiguration()
					.setOfficeHome(new File(&quot;C:/Program Files/LibreOffice 3.5&quot;))
					.buildOfficeManager();
			officeManager.start();

			// 2) Create JODConverter converter
			OfficeDocumentConverter converter = new OfficeDocumentConverter(
					officeManager);

			// 3) Create HTML
			createHTML(converter);
			createHTML(converter);

		} finally {
			// 4) Stop LibreOffice in headless mode.
			if (officeManager != null) {
				officeManager.stop();
			}
		}
	}

	private static void createHTML(OfficeDocumentConverter converter) {
		try {
			long start = System.currentTimeMillis();
			converter.convert(new File(&quot;docx/HelloWorld.docx&quot;), new File(
					&quot;html/HelloWorld.html&quot;));
			System.err.println(&quot;Generate html/HelloWorld.html with &quot;
					+ (System.currentTimeMillis() - start) + &quot;ms&quot;);
		} catch (Throwable e) {
			e.printStackTrace();
		}
	}
}
</pre>
<p>You can notice that code uses java.io.File for docx input and html output because JODConverter cannot work with Streaming.</p>
<p>After running this class, you will see on the console few JODConverter logs and the elapsed time of the conversion : </p>
<pre class="brush: plain; title: ; notranslate">
Generate html/HelloWorld.html with 12109ms
Generate html/HelloWorld.html with 391ms
</pre>
<p>JODConverter converts a simple HelloWorld.docx to HTML with 391ms. The quality of the conversion is perfect.</p>
<p>Note that, in my case the connection to LibreOffice takes a long time (5219ms) and disconnection too.</p>
<h4>PDF converter</h4>
<p>Here the JODConverter Java code which converts twice the &quot;docx/HelloWorld.docx&quot; to &quot;pdf/HelloWorld.pdf&quot;: </p>
<pre class="brush: java; title: ; notranslate">

package org.samples.docxconverters.jodconverter.pdf;

import java.io.File;

import org.artofsolving.jodconverter.OfficeDocumentConverter;
import org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration;
import org.artofsolving.jodconverter.office.OfficeManager;

public class HelloWorldToPDF {

	public static void main(String[] args) {

		// 1) Start LibreOffice in headless mode.
		OfficeManager officeManager = null;
		try {
			officeManager = new DefaultOfficeManagerConfiguration()
					.setOfficeHome(new File(&quot;C:/Program Files/LibreOffice 3.5&quot;))
					.buildOfficeManager();
			officeManager.start();

			// 2) Create JODConverter converter
			OfficeDocumentConverter converter = new OfficeDocumentConverter(
					officeManager);

			// 3) Create PDF
			createPDF(converter);
			createPDF(converter);

		} finally {
			// 4) Stop LibreOffice in headless mode.
			if (officeManager != null) {
				officeManager.stop();
			}
		}
	}

	private static void createPDF(OfficeDocumentConverter converter) {
		try {
			long start = System.currentTimeMillis();
			converter.convert(new File(&quot;docx/HelloWorld.docx&quot;), new File(
					&quot;pdf/HelloWorld.pdf&quot;));
			System.err.println(&quot;Generate pdf/HelloWorld.pdf with &quot;
					+ (System.currentTimeMillis() - start) + &quot;ms&quot;);
		} catch (Throwable e) {
			e.printStackTrace();
		}
	}
}
</pre>
<p>After running this class, you will see on the console few JODConverter logs and the elapsed time of the conversion : </p>
<pre class="brush: plain; title: ; notranslate">
Generate pdf/HelloWorld.pdf with 3172ms
Generate pdf/HelloWorld.pdf with 468ms
</pre>
<p>JODConverter converts a simple HelloWorld.docx to PDF with 468ms. The quality of the conversion is perfect.</p>
<h3>docx4j</h3>
<p>dox4j provides several docx converters : </p>
<ul>
<li>docx to HTML converter.
  </li>
<li>docx to PDF converter based on XSL-FO and FOP.
  </li>
</ul>
<p><strong>org.samples.docxconverters.docx4j</strong> Eclipse project that you can <a href="http://dl.dropbox.com/u/2903680/wordpress-blog/tutoriels/java/converters/org.samples.docxconverters.docx4j.zip">download here</a> is sample of docx converter with docx4j. This project contains: </p>
<ul>
<li><strong>docx</strong> folder which contains several docx to convert. Those docx comes from the <a href="http://code.google.com/p/xdocreport/source/browse/#git%2Fthirdparties-extension%2Forg.apache.poi.xwpf.converter.pdf%2Fsrc%2Ftest%2Fresources%2Forg%2Fapache%2Fpoi%2Fxwpf%2Fconverter%2Fcore">XDocReport Git</a> that we use to test our converter.
  </li>
<li><strong>pdf and html folders</strong> where docx will be converted.
  </li>
<li><strong>lib folder whit docx4j and dependencies JARs</strong>.
  </li>
</ul>
<p><img src="http://angelozerr.files.wordpress.com/2012/12/javaconverters_docx4jproject.png?w=595" /></p>
<p>For docx4j, logs must be disabled because it generates a lot of logs which degrade the performance. To do that : </p>
<ul>
<li>create <strong>src/docx4j.properties</strong> like this :
<pre class="brush: plain; title: ; notranslate">docx4j.Log4j.Configurator.disabled=true</pre>
</li>
<li>create <strong>src/log4j.properties</strong> like this :
<pre class="brush: plain; title: ; notranslate">log4j.rootLogger=ERROR</pre>
</li>
</ul>
<h4>Donload</h4>
<h3>with maven</h3>
<p>To download docx4j and their dependencies JARS, the best mean is to use maven with this pom:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
	xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd&quot;&gt;
	&lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
	&lt;groupId&gt;org.samples.docxconverters.docx4j&lt;/groupId&gt;
	&lt;artifactId&gt;org.samples.docxconverters.docx4j&lt;/artifactId&gt;
	&lt;packaging&gt;pom&lt;/packaging&gt;
	&lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;

	&lt;build&gt;
		&lt;plugins&gt;
			&lt;plugin&gt;
				&lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
				&lt;artifactId&gt;maven-dependency-plugin&lt;/artifactId&gt;
				&lt;version&gt;2.1&lt;/version&gt;
				&lt;executions&gt;
					&lt;execution&gt;
						&lt;id&gt;copy-dependencies&lt;/id&gt;
						&lt;phase&gt;process-resources&lt;/phase&gt;
						&lt;goals&gt;
							&lt;goal&gt;copy-dependencies&lt;/goal&gt;
						&lt;/goals&gt;
						&lt;configuration&gt;
							&lt;outputDirectory&gt;lib&lt;/outputDirectory&gt;
							&lt;overWriteReleases&gt;true&lt;/overWriteReleases&gt;
							&lt;overWriteSnapshots&gt;true&lt;/overWriteSnapshots&gt;
							&lt;overWriteIfNewer&gt;true&lt;/overWriteIfNewer&gt;
							&lt;excludeTypes&gt;libd&lt;/excludeTypes&gt;
						&lt;/configuration&gt;
					&lt;/execution&gt;
				&lt;/executions&gt;
			&lt;/plugin&gt;
		&lt;/plugins&gt;
	&lt;/build&gt;

	&lt;dependencies&gt;

		&lt;dependency&gt;
			&lt;groupId&gt;org.docx4j&lt;/groupId&gt;
			&lt;artifactId&gt;docx4j&lt;/artifactId&gt;
			&lt;version&gt;2.8.1&lt;/version&gt;
		&lt;/dependency&gt;

	&lt;/dependencies&gt;

&lt;/project&gt;
</pre>
<p>After you can do :</p>
<pre class="brush: plain; title: ; notranslate">
mvn process-resources
</pre>
<p>and it will download the well JARs and will copy it to the lib folder.</p>
<h3>without maven</h3>
<p>Go at <a>docx4j downloads</a>.</p>
<h4>HTML converter</h4>
<p>Here the docx4j Java code which converts twice the &quot;docx/HelloWorld.docx&quot; to &quot;html/HelloWorld.html&quot;: </p>
<pre class="brush: java; title: ; notranslate"> 
package org.samples.docxconverters.docx4j.html;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import javax.xml.transform.stream.StreamResult;

import org.docx4j.convert.out.html.AbstractHtmlExporter;
import org.docx4j.convert.out.html.AbstractHtmlExporter.HtmlSettings;
import org.docx4j.convert.out.html.HtmlExporterNG2;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;

public class HelloWorldToHTML {

	public static void main(String[] args) {
		createHTML();
		createHTML();
	}

	private static void createHTML() {
		try {
			long start = System.currentTimeMillis();

			// 1) Load DOCX into WordprocessingMLPackage
			InputStream is = new FileInputStream(new File(
					&quot;docx/HelloWorld.docx&quot;));
			WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage
					.load(is);

			// 2) Prepare HTML settings
			HtmlSettings htmlSettings = new HtmlSettings();

			// 3) Convert WordprocessingMLPackage to HTML
			OutputStream out = new FileOutputStream(new File(
					&quot;html/HelloWorld.html&quot;));
			AbstractHtmlExporter exporter = new HtmlExporterNG2();
			StreamResult result = new StreamResult(out);
			exporter.html(wordMLPackage, result, htmlSettings);

			System.err.println(&quot;Generate html/HelloWorld.html with &quot;
					+ (System.currentTimeMillis() - start) + &quot;ms&quot;);

		} catch (Throwable e) {
			e.printStackTrace();
		}
	}

}
</pre>
<p>You can notice that code uses InputStream/OutputStream (Streaming) for docx input and html output.</p>
<p>After running this class, you will see on the console the elapsed time of the conversion : </p>
<pre class="brush: plain; title: ; notranslate">
Generate html/HelloWorld.html with 5109ms
Generate html/HelloWorld.html with 47ms
</pre>
<p>docx4j converts a simple HelloWorld.docx to HTML with 47ms. The quality of the conversion is perfect.</p>
<h4>PDF converter</h4>
<p>Here the docx4j Java code which converts twice the &quot;docx/HelloWorld.docx&quot; to &quot;pdf/HelloWorld.pdf&quot;: </p>
<pre class="brush: java; title: ; notranslate"> 
package org.samples.docxconverters.docx4j.pdf;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import org.docx4j.convert.out.pdf.PdfConversion;
import org.docx4j.convert.out.pdf.viaXSLFO.PdfSettings;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;

public class HelloWorld2PDF {

	public static void main(String[] args) {
		createPDF();
		createPDF();
	}

	private static void createPDF() {
		try {
			long start = System.currentTimeMillis();

			// 1) Load DOCX into WordprocessingMLPackage
			InputStream is = new FileInputStream(new File(
					&quot;docx/HelloWorld.docx&quot;));
			WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage
					.load(is);

			// 2) Prepare Pdf settings
			PdfSettings pdfSettings = new PdfSettings();

			// 3) Convert WordprocessingMLPackage to Pdf
			OutputStream out = new FileOutputStream(new File(
					&quot;pdf/HelloWorld.pdf&quot;));
			PdfConversion converter = new org.docx4j.convert.out.pdf.viaXSLFO.Conversion(
					wordMLPackage);
			converter.output(out, pdfSettings);

			System.err.println(&quot;Generate pdf/HelloWorld.pdf with &quot;
					+ (System.currentTimeMillis() - start) + &quot;ms&quot;);

		} catch (Throwable e) {
			e.printStackTrace();
		}
	}

}
</pre>
<p>You can notice that code uses InputStream/OutputStream (Streaming) for docx input and pdf output.</p>
<p>After running this class, you will see on the console the elapsed time of the conversion : </p>
<pre class="brush: plain; title: ; notranslate">
Generate pdf/HelloWorld.pdf with 16156ms
Generate pdf/HelloWorld.pdf with 219ms
</pre>
<p>docx4j converts a simple HelloWorld.docx to PDF with 219ms. The quality of the conversion is perfect.</p>
<h3>XDocReport (Apache POI XWPF)</h3>
<p>XDocReport provides docx converters based on Apache POI XWPF: </p>
<ul>
<li><a href="http://code.google.com/p/xdocreport/wiki/XWPFConverterXHTML">docx to html converter</a> based on SAX (and not DOM).
  </li>
<li><a href="http://code.google.com/p/xdocreport/wiki/XWPFConverterPDFViaIText">docx to pdf converter</a> based on iText 2.3.7.
  </li>
</ul>
<p>Pay attention, this converter works only with docx and not with doc format. If you wish convert doc format, please see the official converter of Apache POI.</p>
<p>The basic idea with XDocReport (Apache POI XWPF) is to </p>
<ol>
<li><strong>load docx with XWPFDocument</strong> Apache POI XWPF.
  </li>
<li>loop for each XWPF Java structures (XWPFParagraph, XWPFTable etc) of the loaded XWPFDocument to
<ul>
<li>generate HTML with SAX for html converter.
      </li>
<li>generate PDF with iText structure (Paragraph, table etc).
      </li>
</ul>
</li>
</ol>
<p><strong>org.samples.docxconverters.xdocreport</strong> Eclipse project that you can <a href="http://dl.dropbox.com/u/2903680/wordpress-blog/tutoriels/java/converters/org.samples.docxconverters.xdocreport.zip">download here</a> is sample of docx converter with XDocReport (Apache POI XWPF). This project contains: </p>
<ul>
<li><strong>docx</strong> folder which contains several docx to convert. Those docx comes from the <a href="http://code.google.com/p/xdocreport/source/browse/#git%2Fthirdparties-extension%2Forg.apache.poi.xwpf.converter.pdf%2Fsrc%2Ftest%2Fresources%2Forg%2Fapache%2Fpoi%2Fxwpf%2Fconverter%2Fcore">XDocReport Git</a> that we use to test our converter.
  </li>
<li><strong>pdf and html folders</strong> where docx will be converted.
  </li>
<li><strong>lib folder whit XDocReport and dependencies JARs</strong>.
  </li>
</ul>
<p><img src="http://angelozerr.files.wordpress.com/2012/12/javaconverters_xdocreportproject.png?w=595" /></p>
<h4>Donload</h4>
<h3>with maven</h3>
<p>To download XDocReport (Apache POI XWPF) and their JARs dependencies the best mean is to use maven with this pom:</p>
<pre class="brush: xml; title: ; notranslate">&lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
	xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd&quot;&gt;
	&lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
	&lt;groupId&gt;org.samples.docxconverters.xdocreport&lt;/groupId&gt;
	&lt;artifactId&gt;org.samples.docxconverters.xdocreport&lt;/artifactId&gt;
	&lt;packaging&gt;pom&lt;/packaging&gt;
	&lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;

	&lt;build&gt;
		&lt;plugins&gt;
			&lt;plugin&gt;
				&lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
				&lt;artifactId&gt;maven-dependency-plugin&lt;/artifactId&gt;
				&lt;version&gt;2.1&lt;/version&gt;
				&lt;executions&gt;
					&lt;execution&gt;
						&lt;id&gt;copy-dependencies&lt;/id&gt;
						&lt;phase&gt;process-resources&lt;/phase&gt;
						&lt;goals&gt;
							&lt;goal&gt;copy-dependencies&lt;/goal&gt;
						&lt;/goals&gt;
						&lt;configuration&gt;
							&lt;outputDirectory&gt;lib&lt;/outputDirectory&gt;
							&lt;overWriteReleases&gt;true&lt;/overWriteReleases&gt;
							&lt;overWriteSnapshots&gt;true&lt;/overWriteSnapshots&gt;
							&lt;overWriteIfNewer&gt;true&lt;/overWriteIfNewer&gt;
							&lt;excludeTypes&gt;libd&lt;/excludeTypes&gt;
						&lt;/configuration&gt;
					&lt;/execution&gt;
				&lt;/executions&gt;
			&lt;/plugin&gt;
		&lt;/plugins&gt;
	&lt;/build&gt;

	&lt;dependencies&gt;
		&lt;dependency&gt;
			&lt;groupId&gt;fr.opensagres.xdocreport&lt;/groupId&gt;
			&lt;artifactId&gt;org.apache.poi.xwpf.converter.xhtml&lt;/artifactId&gt;
			&lt;version&gt;1.0.0&lt;/version&gt;
		&lt;/dependency&gt;
		&lt;dependency&gt;
			&lt;groupId&gt;fr.opensagres.xdocreport&lt;/groupId&gt;
			&lt;artifactId&gt;org.apache.poi.xwpf.converter.pdf&lt;/artifactId&gt;
			&lt;version&gt;1.0.0&lt;/version&gt;
		&lt;/dependency&gt;
	&lt;/dependencies&gt;

&lt;/project&gt;
</pre>
<p>After you can do :</p>
<pre class="brush: plain; title: ; notranslate">
mvn process-resources
</pre>
<p>and it will download the well JARs and will copy it to the lib folder.</p>
<h3>without maven</h3>
<p>You can <a href="http://code.google.com/p/xdocreport/downloads/list">download </a> <strong>docx.converters-xxx-sample.zip</strong> which contains the well JARs.</p>
<h4>HTML converter</h4>
<p>Here the XDocReport (Apache POI XWPF) Java code which converts twice the &quot;docx/HelloWorld.docx&quot; to &quot;html/HelloWorld.html&quot;: </p>
<pre class="brush: java; title: ; notranslate"> 
package org.samples.docxconverters.xdocreport.html;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.poi.xwpf.converter.xhtml.XHTMLConverter;
import org.apache.poi.xwpf.converter.xhtml.XHTMLOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

public class HelloWorldToHTML {

	public static void main(String[] args) {
		createHTML();
		createHTML();
	}

	private static void createHTML() {
		try {
			long start = System.currentTimeMillis();

			// 1) Load DOCX into XWPFDocument
			InputStream is = new FileInputStream(new File(
					&quot;docx/HelloWorld.docx&quot;));
			XWPFDocument document = new XWPFDocument(is);

			// 2) Prepare Html options
			XHTMLOptions options = XHTMLOptions.create();

			// 3) Convert XWPFDocument to HTML
			OutputStream out = new FileOutputStream(new File(
					&quot;html/HelloWorld.html&quot;));
			XHTMLConverter.getInstance().convert(document, out, options);

			System.err.println(&quot;Generate html/HelloWorld.html with &quot;
					+ (System.currentTimeMillis() - start) + &quot;ms&quot;);

		} catch (Throwable e) {
			e.printStackTrace();
		}
	}
}
</pre>
<p>You can notice that code uses InputStream/OutputStream (Streaming) for docx input and html output.</p>
<p>After running this class, you will see on the console the elapsed time of the conversion : </p>
<pre class="brush: plain; title: ; notranslate">
Generate html/HelloWorld.html with 828ms
Generate html/HelloWorld.html with 32ms
</pre>
<p>XDocReport (Apache POI XWPF) converts a simple HelloWorld.docx to HTML with 32ms. The quality of the conversion is perfect.</p>
<h4>PDF converter</h4>
<p>Here the XDocReport (Apache POI XWPF) Java code which converts twice the &quot;docx/HelloWorld.docx&quot; to &quot;pdf/HelloWorld.pdf&quot;: </p>
<pre class="brush: java; title: ; notranslate"> 
package org.samples.docxconverters.xdocreport.pdf;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.poi.xwpf.converter.pdf.PdfConverter;
import org.apache.poi.xwpf.converter.pdf.PdfOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

public class HelloWorldToPDF {

	public static void main(String[] args) {
		createPDF();
		createPDF();
	}

	private static void createPDF() {
		try {
			long start = System.currentTimeMillis();

			// 1) Load DOCX into XWPFDocument
			InputStream is = new FileInputStream(new File(
					&quot;docx/HelloWorld.docx&quot;));
			XWPFDocument document = new XWPFDocument(is);

			// 2) Prepare Pdf options
			PdfOptions options = PdfOptions.create();

			// 3) Convert XWPFDocument to Pdf
			OutputStream out = new FileOutputStream(new File(
					&quot;pdf/HelloWorld.pdf&quot;));
			PdfConverter.getInstance().convert(document, out, options);
			
			System.err.println(&quot;Generate pdf/HelloWorld.pdf with &quot;
					+ (System.currentTimeMillis() - start) + &quot;ms&quot;);
			
		} catch (Throwable e) {
			e.printStackTrace();
		}
	}
}
</pre>
<p>You can notice that code uses InputStream/OutputStream (Streaming) for docx input and pdf output.</p>
<p>After running this class, you will see on the console the elapsed time of the conversion : </p>
<pre class="brush: plain; title: ; notranslate">
Generate pdf/HelloWorld.pdf with 1375ms
Generate pdf/HelloWorld.pdf with 63ms
</pre>
<p>XDocReport (Apache POI XWPF) converts a simple HelloWorld.docx to PDF with 63ms. The quality of the conversion is perfect.</p>
<h3>Comparison</h3>
<h4>docx converters with HelloWorld</h4>
<table>
<tr>
<th>Framework</td>
<th>Fast for HTML?</td>
<th>Fast for PDF?</td>
<th>Less memory intensive</td>
<th>Streaming</td>
<th>Easy to install?</td>
</tr>
<tr>
<td>JODConverter</td>
<td>391ms</td>
<td>468ms</td>
<td>Don&rsquo;t know how to test that?</td>
<td>No</td>
<td>No because it requires installation of OpenOffice/LibreOffice</td>
</tr>
<tr>
<td>docx4j</td>
<td>47ms</td>
<td>219ms</td>
<td>OutOffMemory when memory is not enough</td>
<td>Yes</td>
<td>Yes</td>
</tr>
<tr>
<td>XDocReport</td>
<td>32ms</td>
<td>63ms</td>
<td>Yes</td>
<td>Yes</td>
<td>Yes</td>
</tr>
</table>
<h4>what about with complex docx conversion?</h4>
<p>At this step we have seen how to convert a simple docx to html and pdf with JODConverter, docx4j and XDocReport (Apache POI XWPF).</p>
<p>But docx can be more complex like table, paragraph, header footer, image etc. To compare the result of html and pdf conversion, you can start the other classes *ToHTML and *ToPDF inluded in the 3 projects. </p>
<p>It&rsquo;s difficult to tell which framework converter is the best : it depends of the content of docx :</p>
<ul>
<li>JODConverter doesn&rsquo;t manage correctly border table (see FormattingTests.docx).
  </li>
<li>docx4j have problems with table border styled for first/end row (see AdvancedTable.docx).
  </li>
<li>XDocReport has problems with bulleted list (see Resume.docx)
  </li>
</ul>
<p>If you have problem with XDocReport, please <a href="http://code.google.com/p/xdocreport/issues/list">create an issuse</a> with your attached docx or odt by explaining your problem.</p>
<h3>Conclusion</h3>
<h4>JODConverter</h4>
<p>The Pros with JODConverter is that it is based on <strong>OpenOffice/LibreOffice which is a powerfull software to manage the write and convert document</strong>. The quality of the conversion is very good.</p>
<p>However, in my case with LibreOffice 3.5, I have <strong>several problems with docx conversion to pdf with table borders</strong> (see FormattingTests.docx), rows/cols spans (see TableWithRowsColsSpanToPDF).</p>
<p>The Cons with JODConverter is:</p>
<ul>
<li>you<strong> must install OpenOffice/LibreOffice</strong> on your server side
  </li>
<li>you <strong>must have write rights on your server side</strong>, because it doesn&rsquo;t manage Streaming.
  </li>
<li><strong>performance is not very good</strong>.
  </li>
</ul>
<h4>docx4j</h4>
<p>Pros for docx4j is a great library to manage docx (merge several docx, compare it, etc). It provides several implemention for Conversion to PDF like FOP and iText which manages streaming and are easy to install (no need to install MS Word or OpenOffice/LibreOffice). But iText version is not official and have not a good renderer. Conversion with FOP have a good renderer.</p>
<p>The Cons with docx converter with FOP is:</p>
<ul>
<li><strong>FOP is more slow than iText</strong>.
  </li>
<li>with <strong>FOP you can have problems with OutOfMemory</strong>. In our case we needed to add memory on the Tomcat Server on Cloudbee for our <a href="http://xdocreport-converter.opensagres.cloudbees.net/">live demo</a> to avoid OutOfMemory.
  </li>
</ul>
<p>More it uses some XSLT (for XSL-FO). I&rsquo;m not a big fan with XSL :  debugging XSL is very hard (debugging Java is easy). I think docx4j should switch to iText conversion implementation instead of FOP. FOP is very powerfull, but in the case of odt/docx converter I think it&rsquo;s better to use iText.</p>
<p>I think FOP should provide the capability to create PDF with Java model like iText and not only with FO. I have posted my suggestion on <a href="http://mail-archives.apache.org/mod_mbox/xmlgraphics-fop-users/201111.mbox/%3CCAKLdLg8hcLBGew-Qi0T57JqutFUnFjd+RrTgOJeQxHGxwO_gSA@mail.gmail.com%3E">FOP forum</a> but I had had none answer.</p>
<h4>XDocReport</h4>
<p>Since <a href="http://code.google.com/p/xdocreport/wiki/XDocReport100">XDocReport 1.0.0</a>, odt/docx converters was improved a lot. There are <strong>fast, uses less memory intensive, manage streaming and are easy to install</strong> (no need to install MS Word or OpenOffice/LobreOffice).</p>
<p>The quality of the renderer manage a lot of cases, but it&rsquo;s not magic and there are again problems like with table border, bullet-ed/numbered list shapes which are not managed. </p>
<p>HTML converters should be more improved (manage table border, bullet-ed/numbered list etc).</p>
<p>Note that XDocReport provides a <a href="http://code.google.com/p/xdocreport/wiki/RESTSOAPConverters">REST Converter services</a> (you can use XDocReport (Apache POI XWPF) or docx4j). With this feature you can use those converter with any technologies like PHP, C#, Python, etc by developping a REST client.</p>
<h4>What about with odt converter?</h4>
<p>To convert odt to PDF or HTML, you can use :</p>
<ul>
<li>JODConverter.
  </li>
<li><a href="http://code.google.com/p/xdocreport/wiki/ODFDOMConverter">XDocReport (ODFDOM) converter</a> for convert odt to PDF or HTML. To test those converter you can :
<ul>
<li>play with our <a href="http://xdocreport-converter.opensagres.cloudbees.net/">live demo</a>.
      </li>
<li><a href="http://code.google.com/p/xdocreport/downloads/list">download</a> XDocReport (ODFDOM) converter samples in the <strong>odt.converters-xxx-sample.zip</strong>.
      </li>
</ul>
</li>
</ul>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/angelozerr.wordpress.com/7020/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/angelozerr.wordpress.com/7020/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=angelozerr.wordpress.com&#038;blog=10338309&#038;post=7020&#038;subd=angelozerr&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://angelozerr.wordpress.com/2012/12/06/how-to-convert-docxodt-to-pdfhtml-with-java/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/4c3176f508ba2f224d3b00dce0ca6c2a?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">akrogen</media:title>
		</media:content>

		<media:content url="http://angelozerr.files.wordpress.com/2012/12/helloworddocx.png" medium="image" />

		<media:content url="http://angelozerr.files.wordpress.com/2012/12/javaconverters_jodconverteproject.png" medium="image" />

		<media:content url="http://angelozerr.files.wordpress.com/2012/12/javaconverters_docx4jproject.png" medium="image" />

		<media:content url="http://angelozerr.files.wordpress.com/2012/12/javaconverters_xdocreportproject.png" medium="image" />
	</item>
		<item>
		<title>Eclipse RCP/RAP and Remoting with JAX-RS, Spring Data JPA and CXF DOSGi [step4]</title>
		<link>http://angelozerr.wordpress.com/2012/06/18/eclipse_spring_dosgi_step4/</link>
		<comments>http://angelozerr.wordpress.com/2012/06/18/eclipse_spring_dosgi_step4/#comments</comments>
		<pubDate>Mon, 18 Jun 2012 07:30:33 +0000</pubDate>
		<dc:creator>angelozerr</dc:creator>
				<category><![CDATA[Apache CXF]]></category>
		<category><![CDATA[DOSGi]]></category>
		<category><![CDATA[Eclipse RAP]]></category>
		<category><![CDATA[Eclipse RCP]]></category>
		<category><![CDATA[Equinox ServletBridge]]></category>
		<category><![CDATA[Libra]]></category>
		<category><![CDATA[WAR Product]]></category>

		<guid isPermaLink="false">http://angelozerr.wordpress.com/?p=6732</guid>
		<description><![CDATA[In [step3] we have managed our UserService on Client and Server side with JAX-RS and Apache CXF DOSGi. Embedding an HTTP server in Equinox At this step the server side works with the HTTP Server Jetty which is an OSGi bundles. This mode is called Embedding an HTTP server in OSGi container : it means [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=angelozerr.wordpress.com&#038;blog=10338309&#038;post=6732&#038;subd=angelozerr&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>In <a href="http://angelozerr.wordpress.com/2012/06/06/eclipse_spring_dosgi_step3/">[step3]</a> we have managed our <strong>UserService</strong> on <strong>Client and Server side</strong> with <strong>JAX-RS</strong> and <a href="http://cxf.apache.org/distributed-osgi.html">Apache CXF DOSGi</a>. </p>
<h2>Embedding an HTTP server in Equinox</h2>
<p>At this step the server side works with the <strong>HTTP Server Jetty</strong> which is an <strong>OSGi bundles</strong>. This mode is called <strong>Embedding an HTTP server in OSGi container</strong> : it means that HTTP server and WEB application are OSGi bundles. The OSGi container starts the HTTP server bundle. <a href="http://www.eclipse.org/equinox/server/http_in_equinox.php">Embedding an HTTP server in Equinox</a> explains how this mean is done with Equinox.</p>
<p>You can resume &quot;embedding an HTTP server in OSGi container&quot; like this : </p>
<p><strong>OSGi container -&gt; HTTP Server (bundle) -&gt; WEB Application (bundle)</strong>.</p>
<h2>Equinox in a Servlet Container (ServletBridge)</h2>
<p>It works great but sometimes you have not the luck to have an HTTP Server which supports OSGi like <a href="http://tomcat.apache.org/">Apache Tomcat</a>. For instance in our case, when we wished to deploy our <a href="http://xdocreport-rap.opensagres.cloudbees.net/xdocreport?startup=fr.opensagres.xdocreport.eclipse.ui.application">XDocReport RAP Application</a> on <a href="http://www.cloudbees.com/">CloudBees</a>, whish provides an Non OSGI HTTP Server <a href="http://tomcat.apache.org/">Apache Tomcat</a>.</p>
<p>Fortunatly, <a href="http://www.eclipse.org/equinox/server/">Server-Side Equinox</a> provides Embedding OSGi container in a servlet container</strong> mode : it means that it&rsquo;s a WEB Application which contains the OSGi container (and another bundles) which start the OSGi container. <a href="http://www.eclipse.org/equinox/server/http_in_container.php">Equinox in a Servlet Container</a> explains how this mean is done with Equinox.<br />
You can resume &quot;embedding OSGi container in a servlet container&quot; like this : </p>
<p><strong>HTTP Server -&gt; WEB Application -&gt; OSGi container</strong>.</p>
<p>To manage this mode you must create a classic WAR which hosts your OSGi plugins and ServletBridge. In this article we will explain how to create a WAR with our UserService on server side with the Eclipse Plug-In <a href="http://eclipse.org/libra/">Libra</a> <strong>WAR Product</strong> which was created for creating WAR from RAP Application launches. But it can be used too with OSGi launches (like we need in this article).</p>
<p>To create a WAR of CXF DOSGi application (server side), you must : </p>
<ul>
<li>register your JAX-RS service with HttpService :
<pre class="brush: xml; title: ; notranslate">
&lt;!-- HttpService --&gt;
&lt;entry key=&quot;org.apache.cxf.rs.httpservice.context&quot; value=&quot;/UserService&quot; /&gt;
</pre>
</li>
<li>create a WAR which hosts OSGi bundles and ServletBridge. <strong>WAR Product</strong> gives you the capability to create a <strong>*.warproduct</strong> file from a launch (RAP, RCP, OSGi lanches, etc). This <strong>*.warproduct</strong> file is used to export it into a WAR to generate WAR.
  </li>
</ul>
<p>At the end of this article we will create the the <strong>cxf-dosgi-jpa.war</strong> WAR. I have deployed this WAR on the <a href="http://www.cloudbees.com/">CloudBees</a> to see it on action. You can test for instance go at <a href="http://cxf-dosgi-war.opensagres.cloudbees.net/UserService/user/findAll">http://cxf-dosgi-war.opensagres.cloudbees.net/UserService/user/findAll</a> to see JSON of the all users.</p>
<p><span id="more-6732"></span></p>
<h2>Download</h2>
<h3>WAR</h3>
<p>You can download the following WAR that we will create in this article:</p>
<ul>
<li><a href="http://dl.dropbox.com/u/2903680/wordpress-blog/tutoriels/eclipse/eclipsespring/remoting/dosgi/step4/cxf-dosgi-jpa.war">cxf-dosgi-jpa.war</a>
  </li>
</ul>
<h3>Bundles</h3>
<p>You can download <a href="http://dl.dropbox.com/u/2903680/wordpress-blog/tutoriels/eclipse/eclipsespring/remoting/dosgi/step4/eclipse_spring_dosgi_step4.zip">eclipse_spring_dosgi_step4.zip</a> which contains the bundles and JARs explained in this article.</p>
<p>To use this zip, unzip it : </p>
<ol>
<li>import those projects in a workspace.
  </li>
<li>open the TargetPlatform/<strong>eclipsespring.target</strong> file and click on <strong>Set as Target Platform</strong>. If you have problem with Target Definition, please read <a href="http://angelozerr.wordpress.com/2012/04/16/eclipse_spring_step9/#problemTP">Problem with Install with Nebula (Incubation) P2</a>.
  </li>
<li>select TargetPlatform/launch/<strong>Server Remoting – JAXRS DOSGi – JPA Dao.launch</strong> to test the Remoting UserService JAX-RS with Mock Dao and Run it.
  </li>
<li>select TargetPlatform/launch/<strong>Server Remoting – JAXRS DOSGi – JPA Dao.launch</strong> to test the Remoting UserService JAX-RS with JPA Dao and Run it.
  </li>
<li>select TargetPlatform/launch/<strong>Client Remoting – JAXRS DOSGi – Simple OSGi Client.launch</strong> to test the Client Remoting UserService JAX-RS and Run it.
  </li>
</ol>
<h2>Prerequisite</h2>
<h3>Install WAR Product Plug-in</h3>
<p>To follow this article you must install Eclipse Plug-In <a href="http://eclipse.org/libra/">Libra</a> <strong>WAR Product</strong>. To do that, please read <a href="http://angelozerr.wordpress.com/2012/06/12/warproduct_step1#install">Install WAR Product</a> article.</p>
<h3>Install RAP Target Platform.</h3>
<p>To create a WAR from a WAR Product created by an OSGi launches, we need ServletBridge. The more easy mean is to install RAP Target Platform. To do that, open the TargetPlatform/<strong>eclipsespring_rap.target</strong> file and click on <strong>Set as Target Platform</strong>. If you have problem with Target Definition, please read <a href="http://angelozerr.wordpress.com/2012/04/16/eclipse_spring_step9/#problemTP">Problem with Install with Nebula (Incubation) P2</a> :</p>
<p><img src="http://angelozerr.files.wordpress.com/2012/06/eclipsespring_dosgiwarsetraptp.png?w=595" /></p>
<h3>Server Remoting &#8211; JAXRS DOSGi &#8211; JPA Dao [RAP TP]</h3>
<p>The launch works with with <strong>Embedding an HTTP server in OSGi container</strong> mode, on other words the HTTP Server (Jetty) is an OSGi bundle. The OSGi container (Equinox) starts the HTTP Server which is a n OSGi bundle.</p>
<p>The <a href="http://angelozerr.wordpress.com/2012/05/29/eclipse_spring_dosgi_step1/#serverJpa">Server Remoting &#8211; JAXRS DOSGi &#8211; JPA Dao</a> launch was created when RCP Target Platform was activated. Now we have activated RAP Target Platform, so we need adjust a little this launch. To do that duplicate <a href="http://angelozerr.wordpress.com/2012/05/29/eclipse_spring_dosgi_step1/#serverJpa">Server Remoting &#8211; JAXRS DOSGi &#8211; JPA Dao</a> to <strong>Server Remoting &#8211; JAXRS DOSGi &#8211; JPA Dao [RAP TP]</strong>.</p>
<p>After that, you must modify the launch, by selecting:</p>
<ul>
<li><strong>javax.servlet</strong>.
  </li>
</ul>
<p>and selecting:  </p>
<ul>
<li><strong>org.eclipse.equinox.console</strong>.
  </li>
<li><strong>org.apache.felix.gogo.shell</strong>.
  </li>
<li><strong>org.apache.felix.gogo.runtime</strong>.
  </li>
</ul>
<p>to avoid having this error : </p>
<pre class="brush: plain; title: ; notranslate">
!MESSAGE Could not find bundle: org.eclipse.equinox.console
!STACK 0
org.osgi.framework.BundleException: Could not find bundle: org.eclipse.equinox.console
	at org.eclipse.osgi.framework.internal.core.ConsoleManager.checkForConsoleBundle(ConsoleManager.java:211)
fr.opensagres.dao.jpa.eclipselink
</pre>
<p>Run the launch, open a WEB Browser and go at <a href="http://127.0.0.1:9000/fr/opensagres/services/UserService/user/findAll">http://127.0.0.1:9000/fr/opensagres/services/UserService/user/findAll</a> , you will see JSON content : </p>
<p><img src="http://angelozerr.files.wordpress.com/2012/05/eclipsespring_dosgijsonfindall.png?w=595" /></p>
<pre class="brush: plain; title: ; notranslate">
{&quot;user&quot;:[{&quot;firstName&quot;:&quot;Angelo&quot;,&quot;lastName&quot;:&quot;Zerr&quot;},{&quot;firstName&quot;:&quot;Pascal&quot;,&quot;lastName&quot;:&quot;Leclercq&quot;},{&quot;firstName&quot;:&quot;Amine&quot;,&quot;lastName&quot;:&quot;Bousta&quot;},{&quot;firstName&quot;:&quot;Mickael&quot;,&quot;lastName&quot;:&quot;Baron&quot;},{&quot;firstName&quot;:&quot;Jawher&quot;,&quot;lastName&quot;:&quot;Moussa&quot;},{&quot;firstName&quot;:&quot;Arnaud&quot;,&quot;lastName&quot;:&quot;Cogoluegnes&quot;},{&quot;firstName&quot;:&quot;Lars&quot;,&quot;lastName&quot;:&quot;Vogel&quot;},{&quot;firstName&quot;:&quot;Olivier&quot;,&quot;lastName&quot;:&quot;Gierke&quot;},{&quot;firstName&quot;:&quot;Tom&quot;,&quot;lastName&quot;:&quot;Schindl&quot;},{&quot;firstName&quot;:&quot;Wim&quot;,&quot;lastName&quot;:&quot;Jongman&quot;}]}
</pre>
<h3>Server Remoting &#8211; JAXRS DOSGi &#8211; Mock Dao [RAP TP]</h3>
<p>You can do the same thing for the Mock Dao by creating the <strong>Server Remoting &#8211; JAXRS DOSGi &#8211; Mock Dao [RAP TP]</strong> by duplicating the <a href="http://angelozerr.wordpress.com/2012/05/29/eclipse_spring_dosgi_step1/#serverMock">Server Remoting &#8211; JAXRS DOSGi &#8211; Mock Dao</a> launch.</p>
<h3>Modify fr.opensagres.dao.jpa.eclipselink</h3>
<p>Remove the <strong>.qualifier</strong> used in the OSGi Fragment <strong>fr.opensagres.dao.jpa.eclipselink</strong> for Hosts:</p>
<p><img src="http://angelozerr.files.wordpress.com/2012/06/warproduct_createwarfromwarproduct6.png?w=595" /></p>
<p>to avoid having this error </p>
<p><img src="http://angelozerr.files.wordpress.com/2012/06/warproduct_createwarfromwarproduct4.png?w=595" /></p>
<p>when WAR will be generated. For more information please read <a href="http://angelozerr.wordpress.com/2012/06/13/warproduct_step3/">Create a WAR from RAP Application with Libra WAR Product [step3]</a>.</p>
<h2>HttpService</h2>
<p>ServletBridge works with &quot;Equinox in a Servlet Container (ServletBridge)&quot; mode, it means that it&rsquo;s classic WEB Application with <strong>web.xml</strong> which <strong>declares ServletBridge servlet</strong>. This servlet <strong>starts</strong> the OSGi container <strong>Equinox</strong>. This ServletBridge <strong>provides too an implementation of HttpService</strong> which is registered in the OSGi services registry. The HttpService gives the capability to register/unregister a Servlet. </p>
<p>To use ServletBridge with CXF DOSGi, the <strong>JAX-RS service must be registered in the HttpService</strong>.</p>
<h3>Manage ONLY Equinox in a Servlet Container (ServletBridge)</h3>
<p>The section <a href="http://cxf.apache.org/distributed-osgi-reference.html#DistributedOSGiReference-ServiceProviderpropertiesForConfiguringRESTfulJAXRSbasedendpointsandconsumers">Service Provider properties For Configuring RESTful JAXRS-based endpoints and consumers</a> shows you that it&rsquo;s possible to do that with the <strong>org.apache.cxf.rs.httpservice.context</strong> property.</p>
<p>In our case we will do that: </p>
<pre class="brush: xml; title: ; notranslate">
&lt;!-- HttpService --&gt;
&lt;entry key=&quot;org.apache.cxf.rs.httpservice.context&quot; value=&quot;/UserService&quot; /&gt;
</pre>
<p>and our service will be available with <strong>/UserService</strong> path like <a href="http://cxf-dosgi-war.opensagres.cloudbees.net/UserService?_wadl">http://cxf-dosgi-war.opensagres.cloudbees.net/UserService?_wadl</a> whish shows you the WADL of the UserService on the <a href="http://www.cloudbees.com/">CloudBees</a>.</p>
<p>Modify the META-INF/spring/<strong>module-osgi-context.xml</strong> of the <strong>fr.opensagres.remoting.exporter.dosgi.jaxrs</strong> bundle like this:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
	xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xmlns:osgi=&quot;http://www.springframework.org/schema/osgi&quot;
	xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                      http://www.springframework.org/schema/osgi http://www.springframework.org/schema/osgi/spring-osgi.xsd&quot;&gt;

	&lt;osgi:reference id=&quot;userService&quot; interface=&quot;fr.opensagres.services.UserService&quot; /&gt;

	&lt;osgi:service interface=&quot;fr.opensagres.services.UserService&quot;&gt;
		&lt;osgi:service-properties&gt;
			&lt;entry key=&quot;service.exported.interfaces&quot; value=&quot;*&quot; /&gt;
			&lt;entry key=&quot;service.exported.configs&quot; value=&quot;org.apache.cxf.rs&quot; /&gt;
			&lt;entry key=&quot;service.exported.intents&quot; value=&quot;HTTP&quot; /&gt;
			&lt;entry key=&quot;org.apache.cxf.rs.databinding&quot; value=&quot;jaxb&quot; /&gt;
			&lt;!-- Logs --&gt;
			&lt;entry key=&quot;org.apache.cxf.rs.in.interceptors&quot; value=&quot;org.apache.cxf.interceptor.LoggingInInterceptor&quot; /&gt;
			&lt;entry key=&quot;org.apache.cxf.rs.out.interceptors&quot; value=&quot;org.apache.cxf.interceptor.LoggingOutInterceptor&quot; /&gt;
			&lt;!-- JAXB Context --&gt;
			&lt;entry key=&quot;org.apache.cxf.rs.provider&quot;&gt;
				&lt;array&gt;
					&lt;ref bean=&quot;jsonProvider&quot; /&gt;
				&lt;/array&gt;
			&lt;/entry&gt;
			&lt;!-- HttpService --&gt;
			&lt;entry key=&quot;org.apache.cxf.rs.httpservice.context&quot; value=&quot;/UserService&quot; /&gt;
		&lt;/osgi:service-properties&gt;
		&lt;ref bean=&quot;userService&quot; /&gt;
	&lt;/osgi:service&gt;

	&lt;bean id=&quot;jsonProvider&quot; class=&quot;org.apache.cxf.jaxrs.provider.JSONProvider&quot;&gt;
		&lt;property name=&quot;singleJaxbContext&quot; value=&quot;true&quot; /&gt;
		&lt;property name=&quot;extraClass&quot;&gt;
			&lt;list&gt;
				&lt;value&gt;fr.opensagres.domain.User&lt;/value&gt;
			&lt;/list&gt;
		&lt;/property&gt;
	&lt;/bean&gt;

&lt;/beans&gt;
</pre>
<p>At this step we can create a WAR Product to export after the WAR, but we will do that after.</p>
<h3>Manage &quot;Embedding an HTTP server in OSGi container&quot; and &quot;Equinox in a Servlet Container (ServletBridge)&quot; both</h3>
<p>At this step, our JAX-RS UserService works with HttpService. If you start the launch <strong>Server Remoting &#8211; JAXRS DOSGi &#8211; JPA Dao [RAP TP]</strong> you will see this error : </p>
<pre class="brush: plain; title: ; notranslate">
INFO: ListenerHookImpl: skipping import request for excluded classs [org.osgi.service.http.HttpService]
6094 [pool-1-thread-1] INFO  org.apache.cxf.dosgi.dsw.service.RemoteServiceAdminCore  - found handler for fr.opensagres.services.UserService  -&gt; org.apache.cxf.dosgi.dsw.handlers.JaxRSHttpServiceConfigurationTypeHandler@d3199e
Exception in thread &quot;pool-1-thread-1&quot; org.osgi.framework.ServiceException: CXF DOSGi: No HTTP Service could be found to publish CXF endpoint in.
	at org.apache.cxf.dosgi.dsw.handlers.HttpServiceConfigurationTypeHandler.getHttpService(HttpServiceConfigurationTypeHandler.java:235)
...
</pre>
<p>This error comes from that there is none HttpService registered because we are in <strong>Embedding an HTTP server in OSGi container</strong> mode. It&rsquo;s possible to manage the both mode by setting the property <strong>org.apache.cxf.rs.httpservice.context</strong> with dynamic mean: </p>
<pre class="brush: xml; title: ; notranslate">
&lt;!-- HttpService --&gt;
&lt;entry key=&quot;${httpservice-config.key}&quot; value=&quot;/UserService&quot; /&gt;
</pre>
<p>The (optional) <strong>${httpservice-config.key}</strong> value :</p>
<ul>
<li>for <strong>Embedding an HTTP server in OSGi container</strong> mode: is not defined. It means that you will do that :
<pre class="brush: xml; title: ; notranslate">
&lt;!-- HttpService --&gt;
&lt;entry key=&quot;${httpservice-config.key}&quot; value=&quot;/UserService&quot; /&gt;
</pre>
<p>and HttpService for CXF DOSGi will be disabled.
  </li>
<li>for <strong>Equinox in a Servlet Container (ServletBridge)</strong> mode : it comes from a property file <strong>httpservice-config.properties</strong> which is hosted by the <strong>fr.opensagres.remoting.exporter.dosgi.jaxrs-httpservice</strong> fragment linked to the <strong>fr.opensagres.remoting.exporter.dosgi.jaxrs</strong> bundle with this content :
<pre class="brush: plain; title: ; notranslate">
httpservice-config.key=org.apache.cxf.rs.httpservice.context
</pre>
<p>It means that you will do that : </p>
<pre class="brush: xml; title: ; notranslate">
&lt;!-- HttpService --&gt;
&lt;entry key=&quot;org.apache.cxf.rs.httpservice.context&quot; value=&quot;/UserService&quot; /&gt;
</pre>
<p>and HttpService will be used to register our UserService with CXF DOSGi with /UserService path.
  </li>
</ul>
<h4>Use ${httpservice-config.key}</h4>
<p>To use optional ${httpservice-config.key} we need to define a <strong>property-placeholder</strong> like this: </p>
<pre class="brush: xml; title: ; notranslate">
&lt;context:property-placeholder location=&quot;classpath:httpservice-config.properties&quot;
		ignore-resource-not-found=&quot;true&quot; ignore-unresolvable=&quot;true&quot; /&gt;
</pre>
<p>The attribute :</p>
<ul>
<li><strong>ignore-resource-not-found=&quot;true&quot;</strong> means that if <strong>httpservice-config.properties</strong> field is not found, Spring doesn&rsquo;t throw an error (in the case of <strong>Embedding an HTTP server in OSGi container</strong> mode.
  </li>
<li><strong>ignore-unresolvable=&quot;true&quot;</strong> means that the use of ${httpservice-config.key} will not throw an error if it doesn&rsquo;t found (in the case of <strong>Embedding an HTTP server in OSGi container</strong> mode.
  </li>
</ul>
<p>Modify the META-INF/spring/<strong>module-osgi-context.xml</strong> of the <strong>fr.opensagres.remoting.exporter.dosgi.jaxrs</strong> bundle like this: </p>
<pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
	xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xmlns:osgi=&quot;http://www.springframework.org/schema/osgi&quot;
	xmlns:context=&quot;http://www.springframework.org/schema/context&quot;
	xsi:schemaLocation=&quot;http://www.springframework.org/schema/osgi  

http://www.springframework.org/schema/osgi/spring-osgi-1.0.xsd


http://www.springframework.org/schema/beans


http://www.springframework.org/schema/beans/spring-beans.xsd


http://www.springframework.org/schema/context


http://www.springframework.org/schema/context/spring-context.xsd&quot;&gt;

	&lt;context:property-placeholder location=&quot;classpath:httpservice-config.properties&quot;
		ignore-resource-not-found=&quot;true&quot; ignore-unresolvable=&quot;true&quot; /&gt;
		
	&lt;osgi:reference id=&quot;userService&quot; interface=&quot;fr.opensagres.services.UserService&quot; /&gt;

	&lt;osgi:service interface=&quot;fr.opensagres.services.UserService&quot;&gt;
		&lt;osgi:service-properties&gt;
			&lt;entry key=&quot;service.exported.interfaces&quot; value=&quot;*&quot; /&gt;
			&lt;entry key=&quot;service.exported.configs&quot; value=&quot;org.apache.cxf.rs&quot; /&gt;
			&lt;entry key=&quot;service.exported.intents&quot; value=&quot;HTTP&quot; /&gt;
			&lt;entry key=&quot;org.apache.cxf.rs.databinding&quot; value=&quot;jaxb&quot; /&gt;
			&lt;!-- Logs --&gt;
			&lt;entry key=&quot;org.apache.cxf.rs.in.interceptors&quot; value=&quot;org.apache.cxf.interceptor.LoggingInInterceptor&quot; /&gt;
			&lt;entry key=&quot;org.apache.cxf.rs.out.interceptors&quot; value=&quot;org.apache.cxf.interceptor.LoggingOutInterceptor&quot; /&gt;
			&lt;!-- JAXB Context --&gt;
			&lt;entry key=&quot;org.apache.cxf.rs.provider&quot;&gt;
				&lt;array&gt;
					&lt;ref bean=&quot;jsonProvider&quot; /&gt;
				&lt;/array&gt;
			&lt;/entry&gt;
			&lt;!-- HttpService --&gt;
			&lt;entry key=&quot;${httpservice-config.key}&quot; value=&quot;/UserService&quot; /&gt;
		&lt;/osgi:service-properties&gt;
		&lt;ref bean=&quot;userService&quot; /&gt;
	&lt;/osgi:service&gt;

	&lt;bean id=&quot;jsonProvider&quot; class=&quot;org.apache.cxf.jaxrs.provider.JSONProvider&quot;&gt;
		&lt;property name=&quot;singleJaxbContext&quot; value=&quot;true&quot; /&gt;
		&lt;property name=&quot;extraClass&quot;&gt;
			&lt;list&gt;
				&lt;value&gt;fr.opensagres.domain.User&lt;/value&gt;
			&lt;/list&gt;
		&lt;/property&gt;
	&lt;/bean&gt;

&lt;/beans&gt;
</pre>
<p>If you start the launch <strong>Server Remoting &#8211; JAXRS DOSGi &#8211; JPA Dao [RAP TP]</strong> you will see that it&rsquo;s work.</p>
<h4>fr.opensagres.remoting.exporter.dosgi.jaxrs-httpservice</h4>
<p>Create the <a href="http://angelozerr.wordpress.com/2012/04/06/eclipse_spring_step1/#configureLog4j">OSGI fragment</a> <strong>fr.opensagres.remoting.exporter.dosgi.jaxrs-httpservice</strong> linked to the <strong>fr.opensagres.remoting.exporter.dosgi.jaxrs</strong> OSGi bundle.</p>
<p>In this fragment, create the src/<strong>httpservice-config.properties</strong> with this content: </p>
<pre class="brush: plain; title: ; notranslate">
httpservice-config.key=org.apache.cxf.rs.httpservice.context
</pre>
<h2>Create WAR Product</h2>
<p>In this section we will create WAR Product from the OSGi <strong>Server Remoting – JAXRS DOSGi – JPA Dao [RAP TP]</strong> launch like explained in the <a href="http://angelozerr.wordpress.com/2012/06/13/warproduct_step2/#createWARProduct">Create WAR Product</a> article. Once the WAR Product will be created, we will add the fragment <strong>fr.opensagres.remoting.exporter.dosgi.jaxrs-httpservice</strong> to the WAR Product Configuration.</p>
<p>Create the TargetPlatform/warproducts/<strong>cxf-dosgi-jpa</strong> folder which will hosts the <strong>cxf-dosgi-jpa.warproduct</strong> : </p>
<p><img src="http://angelozerr.files.wordpress.com/2012/06/eclipsespring_dosgicreatewarproduct1.png?w=595" /></p>
<p>Go to the <strong>File/New/Other&#8230;</strong> menu item, select Plug-in Development/<strong>WAR Product Configuration</strong> and click on <strong>Next</strong> button:</p>
<p><img src="http://angelozerr.files.wordpress.com/2012/06/warproduct_createwarproduct3.png?w=595" /></p>
<p>The <strong>New WAR Product Configuration</strong> wizard is displayed:</p>
<p><img src="http://angelozerr.files.wordpress.com/2012/06/eclipsespring_dosgicreatewarproduct3.png?w=595" /></p>
<ol>
<li>Select the TargetPlatform/warproducts/<strong>cxf-dosgi-jpa</strong> folder.
  </li>
<li>fill <strong>File name</strong> field with <strong>cxf-dosgi-jpa.warproduct</strong>.
  </li>
<li>select the <strong>Server Remoting &#8211; JAXRS DOSGi &#8211; JPA Dao  [RAP TP]</strong> launch because we will create a WAR Product from this launch.
  </li>
</ol>
<p>Click on <strong>Finish</strong> button to generate the WAR Product:</p>
<p><img src="http://angelozerr.files.wordpress.com/2012/06/eclipsespring_dosgicreatewarproduct4.png?w=595" /></p>
<p>With the WAR Product Editor, Add the f<strong>r.opensagres.remoting.exporter.dosgi.jaxrs-httpservice</strong> fragment (to register the UserService with HttpService) with the <strong>Add</strong> button :</p>
<p><img src="http://angelozerr.files.wordpress.com/2012/06/eclipsespring_dosgicreatewarproduct5.png?w=595" /></p>
<h2>Create WAR</h2>
<p>At this step we can generate the WAR by following the <a href="http://angelozerr.wordpress.com/2012/06/13/warproduct_step3/">Create a WAR from RAP Application with Libra WAR Product [step3]</a> article.</p>
<h3>Validate WAR product</h3>
<p>Before creating WAR, click on <strong>Validate WAR product</strong> menu item to check you have not problem with Plug-Ins/Fragments of the WAR Product:</p>
<p><img src="http://angelozerr.files.wordpress.com/2012/06/eclipsespring_dosgicreatewar11.png?w=595" /></p>
<h3>Export WAR product</h3>
<p>If you have none errors, we can start exporting the WAR. To do that, click on <strong>Export WAR product</strong> menu item:</p>
<p><img src="http://angelozerr.files.wordpress.com/2012/06/eclipsespring_dosgicreatewar2.png?w=595" /></p>
<p>This action opens the <strong>Export</strong> dialog : </p>
<p><img src="http://angelozerr.files.wordpress.com/2012/06/eclipsespring_dosgicreatewar3.png?w=595" /></p>
<ul>
<li><strong>choose the file name</strong> of the generated WAR (here we will export WAR to generate the C:\cxf-dosgi-jpa.war).
  </li>
<li>select the &quot;<strong>Allow for binary cycles in target platform</strong>&quot; checkbox.
  </li>
</ul>
<p>Click on <strong>Finish</strong> button which starts the export of the WAR.</p>
<h2>Test WAR cxf-dosgi-jpa.war</h2>
<p>At this step we can test our WAR. In my case, I have tested the WAR with <a href="http://tomcat.apache.org/">Apache Tomcat</a> and follow thoses steps:</p>
<ul>
<li>Install <a href="http://tomcat.apache.org/">Apache Tomcat</a>.
  </li>
<li>Copy/paste the <strong>cxf-dosgi-jpa.war</strong> in the <strong>webapps</strong> folder of the root of the Tomcat.
  </li>
<li>Start the Tomcat on the <strong>8080 </strong>port by using the bin/<strong>startup.bat</strong> (or <strong>startup.sh</strong>).
  </li>
</ul>
<h3>Web Browser</h3>
<p>Once the HTTP Server has deployed the war, tries to go to the URL <a href="http://127.0.0.1:8080/cxf-dosgi-jpa/UserService/user/findAll">http://127.0.0.1:8080/cxf-dosgi-jpa/UserService/user/findAll</a> and you will see the JSON of the user list : </p>
<pre class="brush: plain; title: ; notranslate">
{&quot;user&quot;:[{&quot;firstName&quot;:&quot;Angelo&quot;,&quot;lastName&quot;:&quot;Zerr&quot;},{&quot;firstName&quot;:&quot;Pascal&quot;,&quot;lastName&quot;:&quot;Leclercq&quot;},{&quot;firstName&quot;:&quot;Amine&quot;,&quot;lastName&quot;:&quot;Bousta&quot;},{&quot;firstName&quot;:&quot;Mickael&quot;,&quot;lastName&quot;:&quot;Baron&quot;},{&quot;firstName&quot;:&quot;Jawher&quot;,&quot;lastName&quot;:&quot;Moussa&quot;},{&quot;firstName&quot;:&quot;Arnaud&quot;,&quot;lastName&quot;:&quot;Cogoluegnes&quot;},{&quot;firstName&quot;:&quot;Lars&quot;,&quot;lastName&quot;:&quot;Vogel&quot;},{&quot;firstName&quot;:&quot;Olivier&quot;,&quot;lastName&quot;:&quot;Gierke&quot;},{&quot;firstName&quot;:&quot;Tom&quot;,&quot;lastName&quot;:&quot;Schindl&quot;},{&quot;firstName&quot;:&quot;Wim&quot;,&quot;lastName&quot;:&quot;Jongman&quot;}]}
</pre>
<p>Our CXF DOSGi application works now with a WAR!</p>
<h3>JAX-RS Clients</h3>
<p>Now we will test our WAR with our OSGI, RCP and RAP launches. To do that we need just modify the module-osgi-context.xml of the <strong>fr.opensagres.remoting.importer.dosgi.jaxrs</strong> bundle :</p>
<pre class="brush: xml; title: ; notranslate">
&lt;jaxrs:client id=&quot;jaxrsUserService&quot;
	address=&quot;${jaxrs-config.base-url}/fr/opensagres/services/UserService&quot;
</pre>
<p>with this new content :</p>
<pre class="brush: xml; title: ; notranslate">
&lt;jaxrs:client id=&quot;jaxrsUserService&quot;
	address=&quot;${jaxrs-config.base-url}/UserService&quot;
</pre>
<h3>Equinox in a Servlet Container (ServletBridge) &#8211; Localhost</h3>
<p>To test with your Local Apache Tomcat, modify the base-url like this : </p>
<pre class="brush: plain; title: ; notranslate">
jaxrs-config.base-url=http://127.0.0.1:8080/cxf-dosgi-jpa/
</pre>
<p>Start the <strong>Client Remoting &#8211; JAXRS DOSGi &#8211; Simple OSGi Client</strong> or (<strong>Client Remoting &#8211; JAXRS DOSGi &#8211; Simple OSGi Client [RAP TP]</strong> if you have RAP Target Platform activated) launch, to check it works. You can test too RCP (<strong>Client Remoting &#8211; JAXRS DOSGI &#8211; RCP Client</strong>) and RAP (<strong>Client Remoting &#8211; JAXRS DOSGI &#8211; RAP Client</strong>) launches.</p>
<h3>Cloudbees</h3>
<p>The <strong>cxf-dosgi-jpa.war</strong> was deployed on <a href="http://www.cloudbees.com/">CloudBees</a>. You can test URLs with Web Browser like:</p>
<ul>
<li><a href="http://cxf-dosgi-war.opensagres.cloudbees.net/UserService?_wadl">http://cxf-dosgi-war.opensagres.cloudbees.net/UserService?_wadl</a> to displays the WADL of the UserService.
  </li>
<li><a href="http://cxf-dosgi-war.opensagres.cloudbees.net/UserService/user/findAll">http://cxf-dosgi-war.opensagres.cloudbees.net/UserService/user/findAll</a> to display the user list as JSON format.
  </li>
</ul>
<p>To test with WAR deployed on CloudBees, modify the base-url like this : </p>
<pre class="brush: plain; title: ; notranslate">
jaxrs-config.base-url=http://cxf-dosgi-war.opensagres.cloudbees.net
</pre>
<p>Start the <strong>Client Remoting &#8211; JAXRS DOSGi &#8211; Simple OSGi Client</strong> or (<strong>Client Remoting &#8211; JAXRS DOSGi &#8211; Simple OSGi Client [RAP TP]</strong> if you have RAP Target Platform activated) launch, to check it works. You can test too RCP (<strong>Client Remoting &#8211; JAXRS DOSGI &#8211; RCP Client</strong>) and RAP (<strong>Client Remoting &#8211; JAXRS DOSGI &#8211; RAP Client</strong>) launches.</p>
<h3>Embedding an HTTP server in Equinox &#8211; Localhost with Jetty</h3>
<p>To test with OSGI Jetty (launch Server Remoting &#8211; JAXRS DOSGi &#8211; JPA Dao  [RAP TP]), modify the base-url like this : </p>
<pre class="brush: plain; title: ; notranslate">
jaxrs-config.base-url=http://127.0.0.1:9000/fr/opensagres/services
</pre>
<p>Start the <strong>Client Remoting &#8211; JAXRS DOSGi &#8211; Simple OSGi Client</strong> or (<strong>Client Remoting &#8211; JAXRS DOSGi &#8211; Simple OSGi Client [RAP TP]</strong> if you have RAP Target Platform activated) launch, to check it works. You can test too RCP (<strong>Client Remoting &#8211; JAXRS DOSGI &#8211; RCP Client</strong>) and RAP (<strong>Client Remoting &#8211; JAXRS DOSGI &#8211; RAP Client</strong>) launches.</p>
<h2>Conclusion</h2>
<p>In this article we have seen how to create a WAR for a CXF DOSGi Application by using WAR Product which is created from OSGi launches and give you the capability to export a WAR with ServletBridge.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/angelozerr.wordpress.com/6732/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/angelozerr.wordpress.com/6732/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=angelozerr.wordpress.com&#038;blog=10338309&#038;post=6732&#038;subd=angelozerr&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://angelozerr.wordpress.com/2012/06/18/eclipse_spring_dosgi_step4/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/4c3176f508ba2f224d3b00dce0ca6c2a?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">akrogen</media:title>
		</media:content>

		<media:content url="http://angelozerr.files.wordpress.com/2012/06/eclipsespring_dosgiwarsetraptp.png" medium="image" />

		<media:content url="http://angelozerr.files.wordpress.com/2012/05/eclipsespring_dosgijsonfindall.png" medium="image" />

		<media:content url="http://angelozerr.files.wordpress.com/2012/06/warproduct_createwarfromwarproduct6.png" medium="image" />

		<media:content url="http://angelozerr.files.wordpress.com/2012/06/warproduct_createwarfromwarproduct4.png" medium="image" />

		<media:content url="http://angelozerr.files.wordpress.com/2012/06/eclipsespring_dosgicreatewarproduct1.png" medium="image" />

		<media:content url="http://angelozerr.files.wordpress.com/2012/06/warproduct_createwarproduct3.png" medium="image" />

		<media:content url="http://angelozerr.files.wordpress.com/2012/06/eclipsespring_dosgicreatewarproduct3.png" medium="image" />

		<media:content url="http://angelozerr.files.wordpress.com/2012/06/eclipsespring_dosgicreatewarproduct4.png" medium="image" />

		<media:content url="http://angelozerr.files.wordpress.com/2012/06/eclipsespring_dosgicreatewarproduct5.png" medium="image" />

		<media:content url="http://angelozerr.files.wordpress.com/2012/06/eclipsespring_dosgicreatewar11.png" medium="image" />

		<media:content url="http://angelozerr.files.wordpress.com/2012/06/eclipsespring_dosgicreatewar2.png" medium="image" />

		<media:content url="http://angelozerr.files.wordpress.com/2012/06/eclipsespring_dosgicreatewar3.png" medium="image" />
	</item>
		<item>
		<title>Create a WAR from RAP Application with Libra WAR Product [step3]</title>
		<link>http://angelozerr.wordpress.com/2012/06/13/warproduct_step3/</link>
		<comments>http://angelozerr.wordpress.com/2012/06/13/warproduct_step3/#comments</comments>
		<pubDate>Wed, 13 Jun 2012 07:27:45 +0000</pubDate>
		<dc:creator>angelozerr</dc:creator>
				<category><![CDATA[Eclipse RAP]]></category>
		<category><![CDATA[Libra]]></category>
		<category><![CDATA[WAR Product]]></category>

		<guid isPermaLink="false">http://angelozerr.wordpress.com/?p=6875</guid>
		<description><![CDATA[In [step2] we have created WAR Product files from RAP launches. In this article we will generate WAR by using the export WAR feature of the WAR Product to generates two WARs: rap-jpa.war that you can download here. rap-mock.war that you can download here. We will deploy generated WARs in a non OSGi HTTP Server [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=angelozerr.wordpress.com&#038;blog=10338309&#038;post=6875&#038;subd=angelozerr&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>In <a href="http://angelozerr.wordpress.com/2012/06/13/warproduct_step2/">[step2]</a> we have created WAR Product files from RAP launches. In this article we will generate WAR by using the <strong>export WAR</strong> feature of the WAR Product to generates two WARs:</p>
<ul>
<li><a href="#rap-jpa.war">rap-jpa.war</a> that you can download <a href="http://dl.dropbox.com/u/2903680/wordpress-blog/tutoriels/eclipse/eclipsespring/warproduct/rap-jpa.war">here</a>.
  </li>
<li><a href="#rap-mock.war">rap-mock.war</a> that you can download <a href="http://dl.dropbox.com/u/2903680/wordpress-blog/tutoriels/eclipse/eclipsespring/warproduct/rap-mock.war">here</a>.
  </li>
</ul>
<p>We will deploy generated WARs in a non OSGi HTTP Server Apache Tomcat. You can see the online demo of the <strong>rap-jpa.war</strong> created with WAR Product deployed on <a href="http://www.cloudbees.com/">CloudBees</a> which provides an <a href="http://tomcat.apache.org/">Apache Tomcat</a> at <a href="http://rap-war.opensagres.cloudbees.net/eclipsespring">http://rap-war.opensagres.cloudbees.net/eclipsespring</a>.</p>
<p>We will see in this article that projects of <a href="dl.dropbox.com/u/2903680/wordpress-blog/tutoriels/eclipse/eclipsespring/step10/eclipsespring_step10.zip">eclipsespring_step10.zip</a> contains 2 problems when WAR will be exported and deployed:</p>
<ul>
<li><strong>.qualifier</strong> must not used in the <strong>Host</strong> of fragments.
  </li>
<li>pay attention with <strong>build.properties</strong> of Plug-in /Fragments which must include the whole files (META-INF, fragment.xml, plugin.xml, etc).
  </li>
</ul>
<p>Those 2 errors are interesting because it works with RAP launch but not with WAR Product.</p>
<p><span id="more-6875"></span></p>
<h2>Download</h2>
<h3>WAR Products</h3>
<p>You can download <a href="http://dl.dropbox.com/u/2903680/wordpress-blog/tutoriels/eclipse/eclipsespring/warproduct/eclipse_spring_warproduct.zip">eclipse_spring_warproduct.zip</a> which contains the two WAR Products created in this article.</p>
<h3>WARs</h3>
<ul>
<li><a href="http://dl.dropbox.com/u/2903680/wordpress-blog/tutoriels/eclipse/eclipsespring/warproduct/rap-mock.war">rap-mock.war</a>
  </li>
<li><a href="http://dl.dropbox.com/u/2903680/wordpress-blog/tutoriels/eclipse/eclipsespring/warproduct/rap-jpa.war">rap-jpa.war</a>
  </li>
</ul>
<h3 id="rap-jpa.war">Create WAR rap-jpa.war of &quot;RAP Client &#8211; JPA Dao&quot;</h3>
<p>In this section we use the features of WAR Product Editor to create the <strong>rap-jpa.war</strong> WAR. To do that Open the rap-jpa.warproduct with the WAR Product Editor.</p>
<h4>Validate WAR product</h4>
<p>Before creating WAR, click on <strong>Validate WAR product</strong> menu item to check you have not problem with Plug-Ins/Fragments of the WAR Product:</p>
<p><img src="http://angelozerr.files.wordpress.com/2012/06/warproduct_createwarfromwarproduct1.png?w=595" /></p>
<h4>Export WAR product</h4>
<p>If you have none errors, we can start exporting the WAR. To do that, click on <strong>Export WAR product</strong> menu item:</p>
<p><img src="http://angelozerr.files.wordpress.com/2012/06/warproduct_createwarfromwarproduct2.png?w=595" /></p>
<p>This action opens the <strong>Export</strong> dialog : </p>
<p><img src="http://angelozerr.files.wordpress.com/2012/06/warproduct_createwarfromwarproduct3.png?w=595" /></p>
<ul>
<li><strong>choose the file name</strong> of the generated WAR (here we will export WAR to generate the C:\rap-jpa.war).
  </li>
<li>select the &quot;<strong>Allow for binary cycles in target platform</strong>&quot; checkbox.
  </li>
</ul>
<p>NOTE: here My WAR Product is used and display a checkbox &quot;Allow for binary cycles in target platform&quot; which is required to fix problem with cycle that we have with Spring.</p>
<p>Click on <strong>Finish</strong> button which starts the export of the WAR, but it fails with this error:</p>
<p><img src="http://angelozerr.files.wordpress.com/2012/06/warproduct_createwarfromwarproduct4.png?w=595" /></p>
<p>This error is interesting because this problem doesn&rsquo;t occur when RAP launch is used. The problem comes from the OSGi Fragment <strong>fr.opensagres.dao.jpa.eclipselink</strong><br />
linked to OSGI bundle <strong>fr.opensagres.dao.jpa</strong> which defines version with <strong>.qualifier</strong>. The OSGi Fragment <strong>fr.opensagres.dao.jpa.eclipselink</strong><br />
uses the <strong>.qualifier</strong> at this step:</p>
<p><img src="http://angelozerr.files.wordpress.com/2012/06/warproduct_createwarfromwarproduct5.png?w=595" /></p>
<p>Remove the <strong>.qualifier</strong> used in the OSGi Fragment <strong>fr.opensagres.dao.jpa.eclipselink</strong> for Hosts:</p>
<p><img src="http://angelozerr.files.wordpress.com/2012/06/warproduct_createwarfromwarproduct6.png?w=595" /></p>
<p>Export the WAR, and you will see that <strong>rap-jpa.war</strong> will be generated with success.</p>
<h4>Test WAR rap-jpa.war</h4>
<p>At this step we can test our WAR. In my case, I have tested the WAR with Apache Tomcat and follow thoses steps:</p>
<ul>
<li>Install Tomcat.
  </li>
<li>Copy/paste the rap-jpa.war in the webapps folder of the root of the Tomcat.
  </li>
<li>Start the Tomcat on the 8080 port by using the bin/<strong>startup.bat</strong> (or <strong>startup.sh</strong>).
  </li>
</ul>
<h4>build.propertries problem</h4>
<p>Once the HTTP Server has deployed the war, tries to go to the URL <a href="http://127.0.0.1:8080/rap-jpa/eclipsespring">http://127.0.0.1:8080/rap-jpa/eclipsespring</a>, but you will have this 404 error:</p>
<p><img src="http://angelozerr.files.wordpress.com/2012/06/warproduct_testwar1.png?w=595" /></p>
<p>But if you go at <a href="http://127.0.0.1:8080/rap-jpa/rap?startup=fr.opensagres.richclient.application">http://127.0.0.1:8080/rap-jpa/rap?startup=fr.opensagres.richclient.application</a> it works:</p>
<p><img src="http://angelozerr.files.wordpress.com/2012/06/warproduct_testwar4.png?w=595" /></p>
<p>It means that the eclipsespring servlet that we have defined in the <strong>fragment.xml</strong> of the bundle <strong>fr.opensagres.richclient.config.rap</strong> is not used:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;extension
      point=&quot;org.eclipse.rap.ui.branding&quot;&gt;
   &lt;branding
         servletName=&quot;eclipsespring&quot;
         themeId=&quot;org.eclipse.rap.design.example.business.theme&quot;
         defaultEntrypointId=&quot;fr.opensagres.richclient.application&quot;
         title=&quot;RAP Application&quot;
         id=&quot;fr.opensagres.richclient.branding&quot;&gt;
   &lt;/branding&gt;
&lt;/extension&gt;
</pre>
<p>If you unzip the JAR of the rap-jpa/WEB-INF/plugins/<strong>fr.opensagres.richclient.config.rap</strong> you will see that fragment.xml doesn&rsquo;t exists. The reason of that<br />
is that build.properties of the <strong>fr.opensagres.richclient.config.rap</strong> bundle, doesn&rsquo;t include the fragment.xml.</p>
<p>To resolve this problem, open the MANIFEST-MF of this bundle, go to the Build tab and select fragment.xml : </p>
<p><img src="http://angelozerr.files.wordpress.com/2012/06/warproduct_testwar2.png?w=595" /></p>
<p>Rebuild the WAR and deploy it.</p>
<h4>URL and branding</h4>
<p>As we use the <strong>org.eclipse.rap.design.example</strong> Plug-In in the WAR Product, we can benefit from branding features of RAP which provides several themes.</p>
<h5>Custom branding</h5>
<p>Now if you go to the URL <a href="http://127.0.0.1:8080/rap-jpa/eclipsespring">http://127.0.0.1:8080/rap-jpa/eclipsespring</a>, you will see:</p>
<p><img src="http://angelozerr.files.wordpress.com/2012/06/warproduct_testwar3.png?w=595" /></p>
<p>You can test that with online demo at <a href="http://rap-war.opensagres.cloudbees.net/eclipsespring">http://rap-war.opensagres.cloudbees.net/eclipsespring</a>.</p>
<h5>RAP branding</h5>
<p>if you go to the URL <a href="http://127.0.0.1:8080/rap-jpa/rap?startup=fr.opensagres.richclient.application">http://127.0.0.1:8080/rap-jpa/rap?startup=fr.opensagres.richclient.application</a>, you will see:</p>
<p><img src="http://angelozerr.files.wordpress.com/2012/06/warproduct_testwar4.png?w=595" /></p>
<p>You can test that with online demo at <a href="http://rap-war.opensagres.cloudbees.net/rap?startup=fr.opensagres.richclient.application">http://rap-war.opensagres.cloudbees.net/rap?startup=fr.opensagres.richclient.application</a>.</p>
<h5>Fancy branding</h5>
<p>if you go to the URL <a href="http://127.0.0.1:8080/rap-jpa/fancy?startup=fr.opensagres.richclient.application">http://127.0.0.1:8080/rap-jpa/fancy?startup=fr.opensagres.richclient.application</a>, you will see:</p>
<p><img src="http://angelozerr.files.wordpress.com/2012/06/warproduct_testwar5.png?w=595" /></p>
<p>You can test that with online demo at <a href="http://rap-war.opensagres.cloudbees.net/fancy?startup=fr.opensagres.richclient.application">http://rap-war.opensagres.cloudbees.net/fancy?startup=fr.opensagres.richclient.application</a>.</p>
<h5>Business branding</h5>
<p>if you go to the URL <a href="http://127.0.0.1:8080/rap-jpa/business?startup=fr.opensagres.richclient.application">http://127.0.0.1:8080/rap-jpa/business?startup=fr.opensagres.richclient.application</a>, you will see:</p>
<p><img src="http://angelozerr.files.wordpress.com/2012/06/warproduct_testwar6.png?w=595" /></p>
<p>You can test that with online demo at <a href="http://rap-war.opensagres.cloudbees.net/business?startup=fr.opensagres.richclient.application">http://rap-war.opensagres.cloudbees.net/business?startup=fr.opensagres.richclient.application</a>.</p>
<h3 id="rap-mock.war">Create WAR rap-mock.war of &quot;RAP Client &#8211; Mock Dao&quot;</h3>
<p>You can generate the rap-mock.war with the rap-mock.warproduct by exporting the WAR like explained below.</p>
<h2>OSGi console</h2>
<p>With WAR Product, HTTP Server starts the OSGi container. Is it possible to access to the OSGi console? The answer is yes. You must just configure web.xml to tell to the ServletBridge servlet which starts the OSGi container that OSGi console must be available by adding <strong>-console</strong> in the commandline.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;init-param&gt;
      &lt;param-name&gt;commandline&lt;/param-name&gt;
      &lt;param-value&gt;-registryMultiLanguage -console -ws rap&lt;/param-value&gt;     
    &lt;/init-param&gt;
</pre>
<p>When you will start the bin/startup.bat, you will see some Tomcat logs and OSGi console will be launched too.</p>
<h2>Conclusion</h2>
<p>In this article we have exported the WAR from WAR Product to generate WAR. We have seen how it&rsquo;s very easy to generate WAR from RAP launches.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/angelozerr.wordpress.com/6875/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/angelozerr.wordpress.com/6875/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=angelozerr.wordpress.com&#038;blog=10338309&#038;post=6875&#038;subd=angelozerr&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://angelozerr.wordpress.com/2012/06/13/warproduct_step3/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/4c3176f508ba2f224d3b00dce0ca6c2a?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">akrogen</media:title>
		</media:content>

		<media:content url="http://angelozerr.files.wordpress.com/2012/06/warproduct_createwarfromwarproduct1.png" medium="image" />

		<media:content url="http://angelozerr.files.wordpress.com/2012/06/warproduct_createwarfromwarproduct2.png" medium="image" />

		<media:content url="http://angelozerr.files.wordpress.com/2012/06/warproduct_createwarfromwarproduct3.png" medium="image" />

		<media:content url="http://angelozerr.files.wordpress.com/2012/06/warproduct_createwarfromwarproduct4.png" medium="image" />

		<media:content url="http://angelozerr.files.wordpress.com/2012/06/warproduct_createwarfromwarproduct5.png" medium="image" />

		<media:content url="http://angelozerr.files.wordpress.com/2012/06/warproduct_createwarfromwarproduct6.png" medium="image" />

		<media:content url="http://angelozerr.files.wordpress.com/2012/06/warproduct_testwar1.png" medium="image" />

		<media:content url="http://angelozerr.files.wordpress.com/2012/06/warproduct_testwar4.png" medium="image" />

		<media:content url="http://angelozerr.files.wordpress.com/2012/06/warproduct_testwar2.png" medium="image" />

		<media:content url="http://angelozerr.files.wordpress.com/2012/06/warproduct_testwar3.png" medium="image" />

		<media:content url="http://angelozerr.files.wordpress.com/2012/06/warproduct_testwar4.png" medium="image" />

		<media:content url="http://angelozerr.files.wordpress.com/2012/06/warproduct_testwar5.png" medium="image" />

		<media:content url="http://angelozerr.files.wordpress.com/2012/06/warproduct_testwar6.png" medium="image" />
	</item>
	</channel>
</rss>
