<?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>The Ironism &#187; guice</title>
	<atom:link href="http://www.larsan.net/tag/guice/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.larsan.net</link>
	<description>of Lars J. Nilsson</description>
	<lastBuildDate>Sat, 03 Dec 2011 21:41:41 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1</generator>
		<item>
		<title>Unit Tests with Guice and Warp Persist</title>
		<link>http://www.larsan.net/2010/04/unit-tests-with-guice-and-warp-persist/</link>
		<comments>http://www.larsan.net/2010/04/unit-tests-with-guice-and-warp-persist/#comments</comments>
		<pubDate>Sun, 25 Apr 2010 10:02:22 +0000</pubDate>
		<dc:creator>fungrim</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[guice]]></category>
		<category><![CDATA[jpa]]></category>
		<category><![CDATA[testng]]></category>
		<category><![CDATA[unit test]]></category>
		<category><![CDATA[warp persist]]></category>

		<guid isPermaLink="false">http://www.cubeia.com/index.php?option=com_wordpress&#038;p=93&#038;Itemid=41</guid>
		<description><![CDATA[Note: this post is cross-posted on Cubeia.com. Yesterday I needed to do some unit testing for a project using Guice and Warp Persist. And one thing that seems to be lacking, or wasn&#8217;t to be found be me yesterday, is the kind of unit testing you can do with Spring, where each method is wrapped ]]></description>
			<content:encoded><![CDATA[<p><em>Note: this post is cross-posted on Cubeia.com.</em></p>
<p>Yesterday I needed to do some unit testing for a project using <a href="http://code.google.com/p/google-guice/">Guice</a> and <a href="http://code.google.com/p/warp-persist/">Warp Persist</a>. And one thing that seems to be lacking, or wasn&#8217;t to be found be me yesterday, is the kind of unit testing you can do with Spring, where each method is wrapped by a transaction which is rolled back when the method ends.</p>
<p>To simplify, it enables you to do this:</p>
<pre>@Test
public void createUser() {
    User u = userService.createUserWithId(1);
}

@Test
public void createUserWithSameId() {
    User u = userService.createUserWithId(1);
}</pre>
<p>If you assume the &#8220;userService&#8221; is transactional, we&#8217;re on a database that spans multiple methods, and that the user ID must be unique, the above pseudo-code should fail as we&#8217;re trying to create two users with the same ID. If, however, there was a transaction wrapping both methods, and that transaction was rolled back, we&#8217;d be fine.</p>
<p>So, can you do it with Guice and Warp Persist? Sure you can!</p>
<p>(I&#8217;m using <a href="http://testng.org/">TestNG</a> and JPA by the way, but you&#8217;ll get the point).</p>
<p>We&#8217;ll create a base class that sets up the Guice context as well as handles the transactions for us. Let&#8217;s start with creating the methods we need:</p>
<pre>public abstract class JpaTestBase {

    @BeforeClass
    public void setUpJpa() throws Exception {
        // setup guice + jpa here here
    }

    @AfterClass
    public void tearDownJpa() throws Exception {
        // stop jpa here
    }

    /*
     * Return the module needed for the test.
     */
    protected abstract List&lt;? extends Module&gt; testModules();

    @BeforeMethod
    public void setupTransaction() throws Exception {
        // create "session in view"
    }

    @AfterMethod
    public void cleanTransaction() throws Exception {
        // rollback transaction and close session
    }
}</pre>
<p>We&#8217;re using the TestNG &#8220;before&#8221; and &#8220;after&#8221; class to setup and tear down JPA. If the test was in a bigger suite you could probably do it around all test classes, but this will do for now. I&#8217;m also including a &#8220;testModules&#8221; method that subclasses should use to make sure their own test classes are setup correctly.</p>
<p>Before we go on, I&#8217;ll add some dependencies which will be explained later:</p>
<pre>@Inject
protected PersistenceService service;

@Inject
protected WorkManager workManager;

@Inject
protected Provider&lt;EntityManagerFactory&gt; emfProvider;</pre>
<p>We&#8217;ll setup the Guice context and the JPA persistence service in the &#8220;setUpJpa&#8221; method:</p>
<pre>@BeforeClass
public void setUpJpa() throws Exception {
    // create list with subclass modules
    List&lt;Module&gt; list = new LinkedList&lt;Module&gt;(testModules());
    // add persistence module
    list.add(PersistenceService.usingJpa()
        .across(UnitOfWork.REQUEST)
        .forAll(Matchers.annotatedWith(Transactional.class), Matchers.any())
        .buildModule());
    // modules to array and create
    GuiceModule[] arr = list.toArray(new Module[list.size()]);
    injector = Guice.createInjector(arr);
    // make sure we get our dependencies
    injector.injectMembers(this);
    // NB: we need to start the service (injected)
    service.start();
}</pre>
<p>The persistence service will work across <em>UnitOfWork.REQUEST </em>as that&#8217;s what we&#8217;re emulating here. I&#8217;m also matching the transaction for any classes, this enables me to mark an entire class as transactional, as opposed to single methods, which I find handy.</p>
<p>All we need to do to shut down is to close the service, like so:</p>
<pre>@AfterClass
public void tearDownJpa() throws Exception {
    service.shutdown();
}</pre>
<p>Now, let&#8217;s wrap the methods. Remember our dependency injections earlier? Well, here&#8217;s where they come in handy. The <em>WorkManager</em> is used by Warp Persist to manage a session, we can tell it to start and end &#8220;work&#8221; and this will correspond to an <em>EntityManager</em> bound to the current thread. Let&#8217;s start with that:</p>
<pre>@BeforeMethod
public void setupTransaction() throws Exception {
    workManager.beginWork();
}

@AfterMethod
public void cleanTransaction() throws Exception {
    workManager.endWork();
}</pre>
<p>So before each method we&#8217;ll open a new <em>EntityManager</em> which will be closed when the method ends. So far so good. Now, in order to enable a rollback when the method ends we first need to wrap the entire execution in a transaction, which means we need to get hold of the <em>EntityManager</em>. Luckily, Warp Persist has a class called <em>ManagedContext</em> which holds currently bound objects (a bit like a custom scope), in which we&#8217;ll find our EntityManager keyed to it&#8217;s persistence context, ie. the <em>EntityManagerFactory</em> that created it. Take a look again at the injected dependencies we injected above: As the test only handles one persistence context we can safely let Guice inject a <em>Provider </em>for an <em>EntityManagerFactory</em> for us  and assume it is going to be the right one.</p>
<p>Still with me? OK, let&#8217;s do it then:</p>
<pre>@BeforeMethod
public void setupTransaction() throws Exception {
    // begin work
    workManager.beginWork();
    // get the entity manager, using it's factory
    EntityManagerFactory emf = emfProvider.get();
    EntityManager man = ManagedContext.getBind(EntityManager.class, emf);
    // begin transactionman.getTransaction().begin();
}

@AfterMethod
public void cleanTransaction() throws Exception {
    // get the entity manager, using its factory
    EntityManagerFactory emf = emfProvider.get();
    EntityManager man = ManagedContext.getBind(EntityManager.class, emf);
    // rollback transaction
    man.getTransaction().rollback();
    // end work
    workManager.endWork();
}</pre>
<p>And that&#8217;s it! Each test method is now within a transaction that will be rolled back when the method ends. Now all you need to do is to write the actual tests&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.larsan.net/2010/04/unit-tests-with-guice-and-warp-persist/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Guice Support in Firebase</title>
		<link>http://www.larsan.net/2010/03/guice-support-in-firebase/</link>
		<comments>http://www.larsan.net/2010/03/guice-support-in-firebase/#comments</comments>
		<pubDate>Thu, 04 Mar 2010 16:46:23 +0000</pubDate>
		<dc:creator>fungrim</dc:creator>
				<category><![CDATA[Firebase]]></category>
		<category><![CDATA[guice]]></category>
		<category><![CDATA[ioc]]></category>

		<guid isPermaLink="false">http://www.cubeia.com/index.php?option=com_wordpress&#038;p=57&#038;Itemid=41</guid>
		<description><![CDATA[I&#8217;ve always wanted to add dependency injection support to Firebase, and today we released a candidate for Guice! And if you ask me, it&#8217;s very cool indeed.The documentation is a bit sparse at the moment, but can be found on our wiki. The rest of the post I&#8217;ll just show how a small fictional game ]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve always wanted to add dependency injection support to <a href="http://www.cubeia.org/">Firebase</a>, and today we released a candidate for <a href="http://code.google.com/p/google-guice/">Guice</a>! And if you ask me, it&#8217;s very cool indeed.The documentation is a bit sparse at the moment, but can be found on our <a href="http://www.cubeia.org/wiki/index.php/Dev/guice">wiki</a>. The rest of the post I&#8217;ll just show how a small fictional game would look using Guice.To start with, the Guice support comes in a set of abstract base classes, one for each Firebase artefact. And to use those you&#8217;d have to add a dependency to you Maven build (I&#8217;ll assume Maven here, you can of course use whatever you&#8217;d like):
<pre>&lt;dependency&gt;&lt;groupId&gt;com.cubeia.firebase&lt;/groupId&gt;&lt;artifactId&gt;guice-support&lt;/artifactId&gt;&lt;version&gt;1.0-RC.1&lt;/version&gt;&lt;/dependency&gt;</pre>
<p>And if you haven&#8217;t already got it, you&#8217;d need our repository as well:
<pre>&lt;repository&gt;&lt;id&gt;cubeia-nexus&lt;/id&gt;&lt;url&gt;http://m2.cubeia.com/nexus/content/groups/public/&lt;/url&gt;&lt;releases&gt;&lt;enabled&gt;true&lt;/enabled&gt;&lt;/releases&gt;&lt;snapshots&gt;&lt;enabled&gt;true&lt;/enabled&gt;&lt;/snapshots&gt;&lt;/repository&gt;</pre>
<p>Now your all set to go, just extend <em>GuiceGame</em> and return the class of you game processor within the configuration, like so:
<pre>public class MyGame extends GuiceGame {public Configuration getConfigurationHelp() {return new ConfigurationAdapter() {public Class getGameProcessorClass() {return MyProcessor.class;}};}}</pre>
<p>So what&#8217;s the magic then? It is this: The class <em>MyProcessor</em> will be instantiated by Guice and can therefore contain injections. And further, it will be done in a custom scope, per event, thus isolating instances nicely.You can also add your own modules to the injection context, again by overriding a method in <em>GuiceGame</em>:
<pre>protected void preInjectorCreation(List list) {list.add(new MyGameModule());}</pre>
<p>Which means, you can inject not only stuff from the current table but also, your own classes. So if we continue:
<pre>public class MyProcessor implements MyProcessor {/** This is probably configured in the "MyGameModule" configured* in the guice game extension.*/@Injectprivate MyHandler handler;/** This is a speciality, you can inject Firebase services* right into your classes.*/@Serviceprivate ScriptSupport support;/** And another shortcut, if you use Log4j, we have a* a helper annotation for you...*/@Log4jprivate Logger log;public void handle(GameDataAction action, Table table) {// do something here eh?}[...]}</pre>
<p>That should give you the idea. You can inject Firebase services as well as a logger (and remember, if you don&#8217;t use Log4j, Guice support the Java utility logging package from scratch). There&#8217;s a couple of things not shown here, for example, you can inject table members directly into the classes and the state object, so you don&#8217;t have to pass those around.Any catch? Well, when you create your own modules you&#8217;ll need to keep in mind that the processor will only work in a custom scope, called <em>EventScope</em>. So if you have something which needs to be bound not as a singleton or in the default scope, you&#8217;ll probably need to do something like this:
<pre>bind(MyHandler.class).to(MyHandlerImpl.class).in(EventScoped.class);</pre>
<p>And that&#8217;s it! In a few days we&#8217;ll release our script support, which is as you might imagine built on top of the Guice support. And so far? I love it!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.larsan.net/2010/03/guice-support-in-firebase/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Brain Scan</title>
		<link>http://www.larsan.net/2008/11/brain-scan/</link>
		<comments>http://www.larsan.net/2008/11/brain-scan/#comments</comments>
		<pubDate>Sat, 01 Nov 2008 19:55:26 +0000</pubDate>
		<dc:creator>fungrim</dc:creator>
				<category><![CDATA[Personal]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[aop]]></category>
		<category><![CDATA[cep]]></category>
		<category><![CDATA[eda]]></category>
		<category><![CDATA[guice]]></category>
		<category><![CDATA[ioc]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[jta]]></category>
		<category><![CDATA[soa]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[wicket]]></category>

		<guid isPermaLink="false">http://fungrim.wordpress.com/?p=395</guid>
		<description><![CDATA[My brain&#8217;s hurting. I must be getting old.For reference, this is some of the programming topics I&#8217;ve read up on (or at least tried) lately: Guice and Spring Declarative transactions and JTA EDA, Pipelines and CEP SOA and ESB and NMR Column databases and distributed file systems Wicket and various related Ajax components OSGi in ]]></description>
			<content:encoded><![CDATA[<p>My brain&#8217;s hurting. I must be getting old.For reference, this is <em>some</em> of the <em>programming</em> topics I&#8217;ve read up on (or at least tried) lately:
<ul>
<li>Guice and Spring</li>
<li>Declarative transactions and JTA</li>
<li>EDA, Pipelines and CEP</li>
<li>SOA and ESB and NMR</li>
<li>Column databases and distributed file systems</li>
<li>Wicket and various related Ajax components</li>
<li>OSGi in various permutations with the above</li>
<li>BI, in-memory BI and CEP (again)</li>
<li>AOP and/or IoC patterns</li>
</ul>
<p>And now I&#8217;m contemplating the fultility of programming.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.larsan.net/2008/11/brain-scan/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Google IoC Framework; Apparently released</title>
		<link>http://www.larsan.net/2007/03/google-ioc-framework-apparently-released/</link>
		<comments>http://www.larsan.net/2007/03/google-ioc-framework-apparently-released/#comments</comments>
		<pubDate>Mon, 12 Mar 2007 18:46:35 +0000</pubDate>
		<dc:creator>fungrim</dc:creator>
				<category><![CDATA[Blogging]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[guice]]></category>
		<category><![CDATA[ioc]]></category>

		<guid isPermaLink="false">http://fungrim.wordpress.com/2007/03/12/google-ioc-framework-apparently-released/</guid>
		<description><![CDATA[Regarding my last post about Spring. The crazed man himself tells me that Google now have released its own IoC framework. Hum&#8230; I&#8217;ll have to check it out when I get time]]></description>
			<content:encoded><![CDATA[<p>Regarding my last <a href="http://fungrim.wordpress.com/2007/03/11/count-me-in-i-dont-get-spring-either/">post</a> about Spring. The crazed man himself tells me that Google now have <a href="http://crazybob.org/2007/03/guice-10.html">released</a> its own IoC framework. Hum&#8230; I&#8217;ll have to check it out when I get time.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.larsan.net/2007/03/google-ioc-framework-apparently-released/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

