<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Gridshore &#187; Stripes</title>
	<atom:link href="http://www.gridshore.nl/tag/stripes/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.gridshore.nl</link>
	<description>A weblog about software engineering, Architecture, Technology an other things we like.</description>
	<lastBuildDate>Tue, 13 Dec 2011 15:36:58 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Using Stripes as a webmvc framework without that thing called xml</title>
		<link>http://www.gridshore.nl/2008/12/13/using-stripes-as-a-webmvc-framework-without-that-thing-called-xml/</link>
		<comments>http://www.gridshore.nl/2008/12/13/using-stripes-as-a-webmvc-framework-without-that-thing-called-xml/#comments</comments>
		<pubDate>Sat, 13 Dec 2008 08:28:22 +0000</pubDate>
		<dc:creator>jettro</dc:creator>
				<category><![CDATA[Frontend Technology]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[mvc]]></category>
		<category><![CDATA[Stripes]]></category>

		<guid isPermaLink="false">http://www.gridshore.nl/?p=507</guid>
		<description><![CDATA[<p></p> <p>For a project we were looking for an appropriate technology stack to create a back end application supporting a REST like architecture together with some screens to test and maintain the application. The application uses REST like urls and JSON as response objects. Some data is persisted in a database and we want [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.gridshore.nl/wp-content/uploads/logo-stripes.png" alt="logo_stripes.png" border="0" width="160" height="42" align="left" /></p>
<p>For a project we were looking for an appropriate technology stack to create a back end application supporting a REST like architecture together with some screens to test and maintain the application. The application uses REST like urls and JSON as response objects. Some data is persisted in a database and we want to use Java as pure as possible. Another requirements was not to use xml. We are very used to using spring framework for dependency injection. We chose another framework though. Most important reason was to lose the xml configuration (yes I know Spring can do that as well), Guice comes with a wel thought out strategy for configuring dependency injection using annotations. Than we needed a front end (MVC framework) without xml configurtion as well. Since there is a pretty easy configuration of Stripes and Guice, we decided to use Stripes. With this blog post I am going to walk you through a the stripes part of the mentioned application. If you want to learn more about Guice and the JPA part, check my other blog item <a href="http://www.gridshore.nl/2008/10/19/one-liter-of-guice-during-spring-break/">One liter of Guice during spring break</a>.
</p>
<p>Read on to find out more about stripes.</p>
<ul>
<li>mvc framework</li>
<li>No xml</li>
<li>Extendability using Interceptors</li>
<li>Test framework of stripes</li>
</ul>
<p>What am I going to create?</p>
<p><span id="more-507"></span><br />
<h2>Configuring stripes</h2>
<p>Within the web.xml (the only xml you really need) we configure a filter and a servlet. You initialize the filter with the starting package for ActionBeans. The servet is a typical mvc dispatcher servlet that receives all requests. One of my requirements to use REST like urls made me change the serlvet mapping a little bit from the more common configuration. I map /rest/* to the servlet. That way all static resources like javascript files and stylesheets are not directed through the dispatcher servlet. Check the following url for an example web.xml. My important change is after the url</p>
<p><strong><a href="http://www.stripesframework.org/display/stripes/Quick+Start+Guide">http://www.stripesframework.org/display/stripes/Quick+Start+Guide</a></strong><br/></p>
<pre class="brush: xml; title: ; notranslate">
&lt;servlet-mapping&gt;
    &lt;servlet-name&gt;StripesDispatcher&lt;/servlet-name&gt;
    &lt;url-pattern&gt;/rest/*&lt;/url-pattern&gt;
&lt;/servlet-mapping&gt;
</pre>
<p>Stripes is an MVC framework, this means we have to do something with a model, controllers and of course view. The dispatcher servlet maps incoming requests to controllers or ActionBeans. This is the first time you have almost no xml configuration to tell Stripes where to find these ActionBeans and how to map them to requests. Within the web.xml you configure the package(s) where it can find ActionBeans. The ActionBeans themselves implement the ActionBean interface. Using a url mapper you can define the url a certain ActionBean responds to. The following code gives an example of one of these mappings.</p>
<pre class="brush: java; title: ; notranslate">
@UrlBinding(&quot;/rest/parcel/{$event}/{parcelId}&quot;)
public class ParcelsActionBean extends BaseActionBean implements ActionBean {
    private int parcelId;
    @HandlesEvent(&quot;all&quot;)
    @DefaultHandler
    public Resolution obtainParcels() {
        ...
    }
    @HandlesEvent(&quot;view&quot;)
    public Resolution viewReadonly() {
        ...
    }
    @HandlesEvent(&quot;edit&quot;)
    public Resolution edit() {
        ...
    }
    @HandlesEvent(&quot;drop&quot;)
    public Resolution dropWithoutConfirm() {
        ...
    }

    public void setParcelId(int parcelId) {
        this.parcelId = parcelId;
    }
}
</pre>
<p>The header for this class shows the @UrlBinding tag, this tags configures the url that this bean responds to. The good part of this url is that you can use parameter binding. The last part <strong>{parcelId}</strong> is used by stripes to call the setter method for parcelId when clients call the appropriate url. Another thing is the <strong>{$event}</strong>. That value is used to determine which method to call. Check out the following examples</p>
<ul>
<li>http://&#8230;/rest/parcel &#8211; returns a collection of Parcel objects by calling the <em>obtainParcels</em> method.</li>
<li>http://&#8230;/rest/parcel/view/1 &#8211; return the parcel with id 1 to view by calling the viewReadOnly method</li>
<li>http://&#8230;/rest/parcel/edit/1 &#8211; updates the parcel with id 1 by calling the edit method.</li>
</ul>
<p>Stripes also supports a nice mechanism for default mapping of urls to ActionBeans. We did not use this however.</p>
<p>One important thing to know about Stripes is that the ActionBeans are not reused. They are recreated for every request to it. Therefore it is no problem to add instance variables to an ActionBean. To make it easier for a jsp developer, the ActionBean is stored in the request under the name <em>actionBean</em>. This makes it very easy to use the standard jstl library to read items from the ActionBean. The following example would format the property squareMeters using the getSquareMeters() method.</p>
<p><strong><fmt:formatNumber groupingUsed="true" value="${actionBean.squareMeters}"/></strong></p>
<p>Our project made use of a JSon interface, therefore there was no need for a lot of jsp&#8217;s or other front end technology. We did have one form, but we used JQuery to submit it to the server. JQuery was also used to receive the result and present it in a normal textare element. The script looks as follows</p>
<pre class="brush: jscript; title: ; notranslate">
function submitForm() {
    $('#solidSpaceFilter').ajaxSubmit(function(data) {
        $(&quot;#reponseText&quot;).val(data);
    });
}
</pre>
<p>The data that is returned was in JSon format, well, actually in a long JSon string. To be ble to read it, we used the page from <a href="http://chris.photobooks.com/json/default.htm">Chris Nielsen</a>. Stripes uses the <strong>Resolution</strong> implementations to create the response. It is a very easy interface with just an execute method. There are a number of Resolutions that come with stripes out of the box. Some of them are: ForwardResolution, StreamingResolution. For the project we have created a JSon resolution. The following code shows the code of this bean.</p>
<pre class="brush: java; title: ; notranslate">
public class JSONResolution implements Resolution {
    private static final Logger logger = LoggerFactory.getLogger(JSONResolution.class);
    private static final String CONTENT_TYPE = &quot;application/json&quot;;
    private String toPrint;

    public JSONResolution(String toPrint) {
        this.toPrint = toPrint;
    }

    public void execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setContentType(CONTENT_TYPE);
        doExecute(request, response);
        response.getOutputStream().print(toPrint);
    }

    protected void doExecute(HttpServletRequest request, HttpServletResponse response) throws IOException {
    }

    protected String getToPrint() {
        return toPrint;
    }

    protected void setToPrint(String toPrint) {
        this.toPrint = toPrint;
    }
}
</pre>
<p>As you can see, this is a very easy class that sets the content type and just writes the content to the outputstream. The class is easy to extend by just overwriting the doExecute(&#8230;) method.</p>
<p>The next thing I want to mention is the test framework that comes with stripes. There are a lot of mock objects available that you can use. There are mocks for HttpServletRequest and HttpServletResponse. That way you can test your action beans. Due to the nature of the action beans it is very easy to call a method of an action bean that you want to test. The following code block shows a test we have created.</p>
<pre class="brush: java; title: ; notranslate">
@Test
public void testView() throws Exception {
    long id = 1L;

    MyService service = createMock(MyService.class);
    expect(service.obtainItemById(id)).andReturn(preparedItem);
    replay(service);

    MyActionBean bean = new MyActionBean();
    bean.setService(service);
    bean.setId(id);

    Resolution resolution = bean.view();
    MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    resolution.execute(new MockHttpServletRequest(&quot;&quot;, &quot;&quot;), mockResponse);
    JSONObject json = JSONObject(mockResponse.getOutputString());

    assertEquals(&quot;Parcel with id '&quot; + nonExistingParcelId + &quot;' does not exist&quot;, json.get(&quot;error&quot;));
}
</pre>
<p>Using the mocks you can prepare your test so it looks like your real application. You can add filters to the MockServletContext. That way you can also test the mapping of requests to your action beans.</p>
<p>The final topic I want to mention is the use of Interceptor classes. Stripes has provided a mechanism to extend the framework by using interceptors. I already discussed this technique in my previous post on integrating stripes and guice. I configured the stripes filter with a special GuiceInterceptor class. Check out the other post for details</p>
<p>That&#8217;s it for now. I think Stripes is a very nice framework. I am not sure if I will be using it a lot. I am so used to spring framework and the spring-mvc project. I do like the way you can do url mapping. This will be introduced in spring 3 as well. But for everybody that thinks spring is to much, or that just want to try out something different, stripes is a very nice product. If you want to learn more about stripes, I recommend the following book.</p>
<div class="amtap-item" lang="en" xml:lang="en"><a href="http://www.amazon.com/Stripes-Development-Pragmatic-Programmers/dp/1934356212%3FSubscriptionId%3D1K0D2VE3R9MFT576B1G2%26tag%3Dgridshore-20%26linkCode%3Dxm2%26camp%3D2025%26creative%3D165953%26creativeASIN%3D1934356212"><img src="http://ecx.images-amazon.com/images/I/41r0-6UKzpL._SL110_.jpg" width="92" height="110" alt=""/></a><br />
<h3><a href="http://www.amazon.com/Stripes-Development-Pragmatic-Programmers/dp/1934356212%3FSubscriptionId%3D1K0D2VE3R9MFT576B1G2%26tag%3Dgridshore-20%26linkCode%3Dxm2%26camp%3D2025%26creative%3D165953%26creativeASIN%3D1934356212">Stripes</a></h3>
<p class="author">Frederic Daoud.					Pragmatic Bookshelf 2008, 					Paperback,				396 pages,				&#36;19.17</p>
</div>
<h2>References</h2>
<ul>
<li><a href="http://www.stripesframework.org/display/stripes/Home">Stripes framework homepage</a></li>
<li><a href="http://www.gridshore.nl/2008/10/19/one-liter-of-guice-during-spring-break/">One liter of Guice during spring break</a></li>
<li><a href="http://chris.photobooks.com/json/default.htm">Visualizing JSon</a></li>
</ul>
<div class='dd_post_share'><div class='dd_buttons'><div class='dd_button'><iframe src='http://widgets.dzone.com/links/widgets/zoneit.html?url=http%3A%2F%2Fwww.gridshore.nl%2F2008%2F12%2F13%2Fusing-stripes-as-a-webmvc-framework-without-that-thing-called-xml%2F&amp;title=Using%20Stripes%20as%20a%20webmvc%20framework%20without%20that%20thing%20called%20xml&amp;t=2' height='25' width='155' frameborder='0' scrolling='no'></iframe></div></div><div style='clear:both'></div></div><!-- Social Buttons Generated by Digg Digg plugin v4.5.3.4, 
    Author : Yong Mook Kim
    Website : http://www.diggdigg2u.com -->]]></content:encoded>
			<wfw:commentRss>http://www.gridshore.nl/2008/12/13/using-stripes-as-a-webmvc-framework-without-that-thing-called-xml/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>One liter of Guice during Spring break</title>
		<link>http://www.gridshore.nl/2008/10/19/one-liter-of-guice-during-spring-break/</link>
		<comments>http://www.gridshore.nl/2008/10/19/one-liter-of-guice-during-spring-break/#comments</comments>
		<pubDate>Sun, 19 Oct 2008 18:09:31 +0000</pubDate>
		<dc:creator>jettro</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[Guice]]></category>
		<category><![CDATA[Stripes]]></category>

		<guid isPermaLink="false">http://www.gridshore.nl/?p=304</guid>
		<description><![CDATA[<p>As you all know, I am a regular springframework user. Especially now that I am working for JTeam, all my projects deal with the springframework. At JTeam we are innovators, so we do check out some other frameworks as well. Therefore I am looking at an alternative for Dependency Injection. Since google is doing [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.gridshore.nl/wp-content/uploads/couldhavebeenguicelogo.png" alt="couldhavebeenguicelogo.png" border="0" width="178" height="130" align="left" />As you all know, I am a regular <a href="http://www.springframework.org">springframework</a> user. Especially now that I am working for <a href="http://www.jteam.nl">JTeam</a>, all my projects deal with the springframework. At JTeam we are innovators, so we do check out some other frameworks as well. Therefore I am looking at an alternative for Dependency Injection. Since google is doing a good job with there <a href="http://code.google.com/p/google-guice">Guice</a> framework, I thought I&#8217;d give it a go. Time for a spring break. Beforehand I do want to stress that this is not going to be a post telling that spring is so bad for some reason and that Guice is much better. If you are looking for that, than there are better posts. I need more time to make a good judgement in that area. Of course where appropriate (or not) I might do some comparison. I do am a persons with an opinion, and I do not mind sharing it <img src='http://www.gridshore.nl/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> .</p>
<p>So what can you expect from this post? First of all a very short description of my first steps with google Guice. Second, I&#8217;ll explain more about the MVC framework called <a href="http://www.stripesframework.org/">Stripes</a>. I&#8217;ll focus on the integration between stripes and Guice. Third a very brief introduction into a back end using the <a href="http://www.wideplay.com/guicewebextensions2">wideplay jpa implementation</a>. Fourth and finally some very careful conclusions.</p>
<p>Read on for the good stuff</p>
<p><span id="more-304"></span>
<p>What is all this Guice about? Guice in itself focusses on Dependency Injection. If you need more than that, you need extensions. If you want a full tutorial about Guice, I recommend the following book and of course a lot of online resources.</p>
<div class="amtap-item" lang="en" xml:lang="en"><a href="http://www.amazon.com/Google-Guice-Lightweight-Dependency-FirstPress/dp/1590599977%3FSubscriptionId%3D1K0D2VE3R9MFT576B1G2%26tag%3Dgridshore-20%26linkCode%3Dxm2%26camp%3D2025%26creative%3D165953%26creativeASIN%3D1590599977"><img src="http://ecx.images-amazon.com/images/I/414TMmulATL._SL110_.jpg" width="89" height="110" alt=""/></a><br />
<h3><a href="http://www.amazon.com/Google-Guice-Lightweight-Dependency-FirstPress/dp/1590599977%3FSubscriptionId%3D1K0D2VE3R9MFT576B1G2%26tag%3Dgridshore-20%26linkCode%3Dxm2%26camp%3D2025%26creative%3D165953%26creativeASIN%3D1590599977">Google Guice</a></h3>
<p class="author">Robbie Vanbrabant.					Apress 2008, 					Paperback,				192 pages,				&#36;17.43</p>
</div>
<p>Next I discuss the most important things I found in this book and in online resource as a springframework user.</p>
<p>The things I discuss are:</p>
<ul>
<li>Module &#8211; Configures the binding of the Interfaces to their implementations. </li>
<li>@Inject &#8211; Annotation used to tell Guice that we need an instance of one of its controlled objects.</li>
<li>Injector &#8211; Object that gives access to all objects under control of Guice.</li>
<li>@ImplementedBy &#8211; annotation on the interface with the default implementation of that interface. This way you do not need it to be configured in a Module. You can overrule this implementation by specifying it in a module.</li>
<li>.asEagerSingleton() &#8211; A singleton object will be instantiated eagerly, meaning during initialization.</li>
<li>Provider &#8211; When you have no control over the classes since they are library classes and/or legacy code.</li>
<li>AOP &#8211; How to use MethodInterceptors using Guice</li>
<li>Persistence using warp persist &#8211; wideplay has created a nice abstraction of JPA for Guice.</li>
<li>Web exposure using Stripes &#8211; Stripes is a framework that takes very little configuration. You can integrate Guice easily with Stripes.</li>
</ul>
<h3>Module</h3>
<p>The binding is configured using an internal DSL. I still like the concept which I talked about before in my <a href="http://www.gridshore.nl/2008/10/02/doing-jaoo-day-3/">report from JAOO</a>.</p>
<p><strong>bind(Service.class).to(ServiceImpl.class).in(Scopes.SINGLETON);</strong></p>
<p>After reading this line of code you can easily understand that we are binding all requests for a service to the ServiceImpl class and make it a singleton. A bit more advanced example.</p>
<p><strong>PersistenceService.usingJpa().across(UnitOfWork.TRANSACTION).transactedWith(TransactionStrategy.LOCAL)<br />
</strong></p>
<p>Here we configure the PersistenceService, it uses JPA to persist, creates sessions across each transaction. The transactions are coming from a local resource (no JTA). There are other configuration options for using AOP method interceptors and for wiring the different Modules. You can easily create a module for all your architectural layers and make them call each other using the install command.</p>
<p>The last thing I want to mention with respect to the Module is the abstract implementation <em>AbstractModule</em>. When you use this as a parent class, you can use the nice DSL for configuration.</p>
<h3>Injector</h3>
<p>As mentioned in the sum up of features, the Injector gives access to all objects that are under control of Guice. There are two different modes in which the Injector can run: Production and Development. By default, the development mode is on. Before going into production, you need to change the creation of the Injector into:</p>
<p><strong>Guice.createInjector(Stage.Production, new MyModule())</strong></p>
<p>I do not really like this, using an environment variable for configuration is better. I also believe that a production stage would be better as a default.</p>
<p>The injector stores all bindings using a Key object. Therefore, obtaining a configured binding is done using this key. There are shortcuts however. The following two lines are the exact same thing</p>
<p><strong>injector.getInstance(Service.class);</strong><br />
<strong>injector.getInstance(Key.get(Service.class));</strong></p>
<p>Why this is important? This is what you must use if you have multiple implementations of the same interface. Imagine you have an interface Service with two implementations: NormalService and SuperService. When requesting an implementation of Service, you need to decide which one to inject. Annotations to the rescue. Annotate the requesting class with you custom annotation that enables Guice to decide which implementation to inject. In our example we could say that detailed objects need to the super service. The following block of code shows the object that gets a dependency injected and the binding configuration. Look for the annotatedWith part.</p>
<pre class="brush: java; title: ; notranslate">
@Inject
public void setService(@Detailed Service service) {...}

bind(Service.class).to(NormalService.class);
bind(Service.class).annotatedWith(Detailed.class).to(SuperService.class);
</pre>
<h3>Provider</h3>
<p>There are occasions where you cannot use the @Inject tag. One of the main reasons is using library classes. To make sure you can use library classes, Guice makes use of the Providers. It is a very easy interface that you need to implement.</p>
<pre class="brush: java; title: ; notranslate">
public interface Provider &lt;T&gt; {
  T get();
}
</pre>
<p>Now instead of injecting the needed object, you inject the provider.</p>
<h3>AOP</h3>
<p>Guice has implemented a very basic AOP model. You can only use the MethodInterceptor interface. This enables you to influence the input arguments as well as results of the actual method. You can even prevent the method from executing, just like you can throw new exceptions. I am not going to explain why AOP is interesting. The following line of code shows an example of wiring a MethodInterceptor to all the methods of implementations of the Service interface.</p>
<p><strong>bindInterceptor(subclassesOf(Service.class),any(),new ServiceLogger());</strong></p>
<p>The bindInterceptor has three arguments, the first matches the classes to wire the aspects around. The second argument matches the methods and the third gives the implementation. The most important part are the matchers. Out of the box Guice comes with a number of standard matchers like: any(), not(), annotatedWith(), subclassesOf, only(), identicalTo(), inPackage(), returns(). You can combine the matchers to come up with the right pointcuts for the aspect.</p>
<h3>Persistence using warp persist</h3>
<p>Guice is a very light weight framework in itself. You need extensions to do some real work. One of the needed extensions is for persisting your objects. Wideplay has created a nice extension to Guice for using JPA. I am not going to reproduce their documentation here. Read the <a href="http://www.wideplay.com/webextensions%3A%3Ajpaintegration">documentation on their website</a>. I do give you the code for a project I am doing together with Frank at JTeam. Frank created the following class and persistence config</p>
<pre class="brush: java; title: ; notranslate">
@JpaUnit
public class DaoModule extends AbstractModule {
    @Override
    protected void configure() {
        initializePersistenceUnit();
        startPersistenceService();
        bindDaos();
    }

    private void initializePersistenceUnit() {
        bindConstant().annotatedWith(JpaUnit.class).to(&quot;jpaUnit&quot;);
        install(PersistenceService.usingJpa()
                .across(UnitOfWork.TRANSACTION)
                .transactedWith(TransactionStrategy.LOCAL)
                .buildModule());
    }

    private void startPersistenceService() {
        bind(PersistenceServiceInitializer.class).asEagerSingleton();
    }

    private void bindDaos() {
        bind(ParcelDao.class).to(JpaParcelDao.class).asEagerSingleton();
    }
}
public class PersistenceServiceInitializer {
    @Inject
    public PersistenceServiceInitializer(PersistenceService service) {
        service.start();
    }
}
</pre>
<p>You also need a persistence.xml</p>
<pre class="brush: xml; title: ; notranslate">
&lt;persistence xmlns=&quot;http://java.sun.com/xml/ns/persistence&quot;
             xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
             xsi:schemaLocation=&quot;http://java.sun.com/xml/ns/persistence

http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd&quot;

             version=&quot;1.0&quot;&gt;
    &lt;persistence-unit name=&quot;solidJpaUnit&quot; transaction-type=&quot;RESOURCE_LOCAL&quot;&gt;
        &lt;provider&gt;org.hibernate.ejb.HibernatePersistence&lt;/provider&gt;
        &lt;class&gt;...entity class 1...&lt;/class&gt;
        &lt;class&gt;...entity class 2...&lt;/class&gt;
        &lt;class&gt;... etc ...&lt;/class&gt;

        &lt;properties&gt;
            &lt;property name=&quot;hibernate.show_sql&quot; value=&quot;true&quot;/&gt;
            &lt;property name=&quot;hibernate.format_sql&quot; value=&quot;true&quot;/&gt;
            &lt;property name=&quot;hibernate.connection.driver_class&quot; value=&quot;com.mysql.jdbc.Driver&quot;/&gt;
            &lt;property name=&quot;hibernate.connection.url&quot; value=&quot;jdbc:mysql://localhost:3306/demo&quot;/&gt;
            &lt;property name=&quot;hibernate.connection.username&quot; value=&quot;demo&quot;/&gt;
            &lt;property name=&quot;hibernate.connection.password&quot; value=&quot;emo&quot;/&gt;
            &lt;property name=&quot;hibernate.dialect&quot; value=&quot;org.hibernate.dialect.MySQL5Dialect&quot;/&gt;
            &lt;property name=&quot;hibernate.connection.autocommit&quot; value=&quot;true&quot;/&gt;
        &lt;/properties&gt;
    &lt;/persistence-unit&gt;
&lt;/persistence&gt;
</pre>
<p>In your dao implementation you inject the EntityManager and you can execute your finders and other data access calls. The following code block gives you a very easy example</p>
<pre class="brush: java; title: ; notranslate">
public class JpaExampleDao implements ExampeDao {
    private final Provider&lt;EntityManager&gt; manager;

    @Inject
    public JpaExampleDao(Provider&lt;EntityManager&gt; manager) {
        this.manager = manager;
    }

    public List&lt;Example&gt; findExamples() {
        return manager.get()
                .createQuery(&quot;SELECT e FROM example e&quot;)
                .getResultList();
    }
}
</pre>
<p>Final thing to mention here is the @Transactional annotation. Using the warp persistence library, you can use this annotation to demarcate your transactions. At the moment there are just READ_ONLY and READ_WRITE configurations.</p>
<h3>Web presence using stripes</h3>
<p>The web front end is the last step for this blog post. I am not going to explain stripes. I use a very small part of it for our project. The only thing that was important to me is the integration of stripes and Guice. There is a project that does the integration called <a href="http://code.google.com/p/stripes-guicer/">stripes-guicer</a>. I had some problems to get this to work. Than I found a <a href="http://article.gmane.org/gmane.comp.java.stripes.user/3418">blog post</a> that did most of the work I needed. Before I go and describe this solution let me explain the problem first.</p>
<p>The problem with a lot of frameworks for the web, is that they control the objects that are created. The ActionBeans or controllers are created by the web framework. You cannot inject Guice controlled beans at construction of these obejcts.</p>
<p>There are two possible solution directions. The first is to get Guice between the actual construction of the framework. Then you can use the normal Guice configuration. Another solution is to let Guice know of these objects right after they are created. Almost all frameworks give you a mechanism to get notified of this phase. The influence Guice can have on these objects is limited. Since they have been constructed already you cannot use constructor injection and you cannot use AOP as provided by Guice. Of course you the scope of these objects is also not controlled by Guice.</p>
<p>Looking at the mentioned framework: stipes-guicer, they got Guice between object creation by Stripes. TO bad this did not work for me. The mentioned blog took the other path and injects the bean into Guice. The following pieces of code show this path as mentioned by <a href="http://article.gmane.org/gmane.comp.java.stripes.user/3418">Stephen Starkey</a></p>
<p>We start off with a ServletContextListener implementation that initializes Guice and puts in on the ServletContext. Than we create a Stripes interceptor that intercepts the LifecycleStage.ActionBeanResolution phase. During this phase we obtain the Guice injector from the ServletContext and inject the current ActionBean using the <strong>injectMembers</strong> method. To make this all happen, we need to add some items to the web.xml.</p>
<pre class="brush: java; title: ; notranslate">
public class GuiceServletContextListener implements ServletContextListener {
    private static final Logger logger = LoggerFactory.getLogger(GuiceServletContextListener.class);

    public static final String KEY = Injector.class.getName();

    public void contextInitialized(ServletContextEvent sce) {
        sce.getServletContext().setAttribute(KEY, getInjector(sce.getServletContext()));
    }

    public void contextDestroyed(ServletContextEvent sce) {
        sce.getServletContext().removeAttribute(KEY);
    }

    private Injector getInjector(ServletContext ctx) {
        try {
            return Guice.createInjector(new WebModule());
        } catch (Exception e) {
            logger.error(&quot;Problem while initializing the guice injector&quot;,e);
            throw new RuntimeException(e);
        }
    }
}
</pre>
<pre class="brush: java; title: ; notranslate">
@Intercepts(LifecycleStage.ActionBeanResolution)
public class GuiceInterceptor implements Interceptor {
    private final static Logger logger = LoggerFactory.getLogger(GuiceInterceptor.class);

    public Resolution intercept(ExecutionContext context) throws Exception {
        Resolution resolution = context.proceed();
        logger.debug(&quot;Running Guice dependency injection for instance of {}&quot;,
                context.getActionBean().getClass().getSimpleName());
        ServletContext ctx = context.getActionBeanContext().getServletContext();
        Injector injector = (Injector) ctx.getAttribute(GuiceServletContextListener.KEY);
        injector.injectMembers(context.getActionBean());

        return resolution;
    }
}
</pre>
<pre class="brush: xml; title: ; notranslate">
    &lt;filter&gt;
        &lt;display-name&gt;Stripes Filter&lt;/display-name&gt;
        &lt;filter-name&gt;StripesFilter&lt;/filter-name&gt;
        &lt;filter-class&gt;net.sourceforge.stripes.controller.StripesFilter&lt;/filter-class&gt;
        &lt;init-param&gt;
            &lt;param-name&gt;ActionResolver.Packages&lt;/param-name&gt;
            &lt;param-value&gt;nl.jteam.stadgenoot.web.action&lt;/param-value&gt;
        &lt;/init&gt;
        &lt;init-param&gt;
            &lt;param-name&gt;Interceptor.Classes&lt;/param-name&gt;
            &lt;param-value&gt;
                nl.jteam.stadgenoot.web.integration.guice.GuiceInterceptor
            &lt;/param-value&gt;
        &lt;/init-param&gt;
    &lt;/filter&gt;
...
    &lt;listener&gt;
        &lt;display-name&gt;GuiceContextListener&lt;/display-name&gt;
        &lt;listener-class&gt;nl.jteam.stadgenoot.web.integration.guice.GuiceServletContextListener&lt;/listener-class&gt;
    &lt;/listener&gt;
</pre>
<h3>Conclusions</h3>
<p>After a week of playing around I can now say, I like Guice. It is the mixing activity that can improve here and there. I am sure people will jump on the wagon there. It does come with a lot of challenges as a springframework veteran. Now I know both, it seems like a good additional tool in my Toolbox. The usage of pure Java is very nice. Simplicity as a goal is very important to a framework lice Guice.</p>
<p>As for the other two frameworks, I like warp persistence. Some additional transaction stuff like specifying that an existing transaction is required would be nice. Stripes is to hard for me to tell, maybe I&#8217;ll spend another post on that in the future.</p>
<p>Hope you liked it, stay tuned for new topics. I understood that a very nice article is coming about a Circuit Breaker implementation.</p>
<p>Ps. a tip for all wordpress users out there, if you post java code with generics or incomplete xml, do not use the option to make wordpress correct xhtml errors. It does not do nice things with your code.</p>
<div class='dd_post_share'><div class='dd_buttons'><div class='dd_button'><iframe src='http://widgets.dzone.com/links/widgets/zoneit.html?url=http%3A%2F%2Fwww.gridshore.nl%2F2008%2F10%2F19%2Fone-liter-of-guice-during-spring-break%2F&amp;title=One%20liter%20of%20Guice%20during%20Spring%20break&amp;t=2' height='25' width='155' frameborder='0' scrolling='no'></iframe></div></div><div style='clear:both'></div></div><!-- Social Buttons Generated by Digg Digg plugin v4.5.3.4, 
    Author : Yong Mook Kim
    Website : http://www.diggdigg2u.com -->]]></content:encoded>
			<wfw:commentRss>http://www.gridshore.nl/2008/10/19/one-liter-of-guice-during-spring-break/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>

