<?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>spiros.blog() &#187; Java</title>
	<atom:link href="http://www.tzavellas.com/techblog/category/java/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.tzavellas.com/techblog</link>
	<description>Spiros Tzavellas’s blog, mostly on software development and Java.</description>
	<lastBuildDate>Fri, 24 Sep 2010 07:42:49 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Statically weaving JPA entities for EclipseLink using Maven</title>
		<link>http://www.tzavellas.com/techblog/2008/10/17/statically-weaving-jpa-entities-for-eclipselink-using-maven/</link>
		<comments>http://www.tzavellas.com/techblog/2008/10/17/statically-weaving-jpa-entities-for-eclipselink-using-maven/#comments</comments>
		<pubDate>Fri, 17 Oct 2008 06:31:07 +0000</pubDate>
		<dc:creator>spiros</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[EclipseLink]]></category>
		<category><![CDATA[jpa]]></category>
		<category><![CDATA[maven]]></category>

		<guid isPermaLink="false">http://www.tzavellas.com/techblog/?p=124</guid>
		<description><![CDATA[EclipseLink provides advanced JPA features such as lazy-loading, change tracking and fetch groups using bytecode weaving. To use bytecode weaving you can either dynamically instrument your entity classes at runtime (via a jvm agent) or use a tool to statically process the .class files after compilation. In this post we will present how to use [...]]]></description>
			<content:encoded><![CDATA[<p><a title="EclipseLink" href="http://eclipse.org/eclipselink">EclipseLink</a> provides advanced JPA features such as lazy-loading, change tracking and fetch groups using bytecode weaving. To use bytecode weaving you can either <a href="http://wiki.eclipse.org/Using_EclipseLink_JPA_Extensions_(ELUG)#How_to_Configure_Dynamic_Weaving_for_JPA_Entities_Using_the_EclipseLink_Agent">dynamically</a> instrument your entity classes at runtime (via a jvm agent) or use a tool to <a href="http://wiki.eclipse.org/Using_EclipseLink_JPA_Extensions_(ELUG)#How_to_Configure_Static_Weaving_for_JPA_Entities">statically</a> process the <em>.class</em> files after compilation. In this post we will present how to use EclipseLink&#8217;s static weaver in a Maven project.</p>
<p>To enable static weaving in a Maven based project we have to add the Eclipselink weaver in the <em>process-classes</em> phase of the <a href="http://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html">Maven&#8217;s build life cycle</a>. The <em>process-classes</em> phase happens after the <em>compile</em> phase and allows the post-processing of files generated in compile phase. In our case, the EclipseLink weaver will post-process the <em>.class</em> files produced by the compiler to add extra bytecodes that implement the desired JPA functionality (lazy-loading, etc).</p>
<p>In the below code we use the <a href="http://maven.apache.org/plugins/maven-antrun-plugin/">Maven AntRun plugin</a> to call (via the <a href="http://ant.apache.org/manual/CoreTasks/java.html">java ANT task</a>) the command line version of the EclipseLink&#8217;s static weaver. Please note that the class name of the weaver is <strong>org.eclipse.persistence.tools.weaving.jpa.StaticWeave</strong> and not <strong>org.eclipse.persistence.tools.weaving.StaticWeave</strong> as the <a href="http://wiki.eclipse.org/Using_EclipseLink_JPA_Extensions_(ELUG)#How_to_Configure_Static_Weaving_for_JPA_Entities">EclipseLink JPA Extensions</a> wiki page says.</p>
<pre>
&lt;build&gt;
 &lt;plugins&gt;
   &lt;plugin&gt;
     &lt;artifactId&gt;maven-antrun-plugin&lt;/artifactId&gt;
     &lt;executions&gt;
       &lt;execution&gt;
         &lt;phase&gt;process-classes&lt;/phase&gt;
         &lt;configuration&gt;
           &lt;tasks&gt;
             &lt;java classname="org.eclipse.persistence.tools.weaving.jpa.StaticWeave"
                   classpathref="maven.runtime.classpath" fork="true"&gt;
               &lt;arg line="-loglevel FINE -persistenceinfo src/main/resources target/classes target/classes"/&gt;
             &lt;/java&gt;
           &lt;/tasks&gt;
         &lt;/configuration&gt;
         &lt;goals&gt;
           &lt;goal&gt;run&lt;/goal&gt;
         &lt;/goals&gt;
       &lt;/execution&gt;
     &lt;/executions&gt;
   &lt;/plugin&gt;
 &lt;/plugins&gt;
&lt;/build&gt;
</pre>
<p>In addition to the <em>pom.xml</em> changes in order to use static weaving in EclipseLink you have to set the <strong>eclipselink.weaving</strong> property to <strong>static</strong> in the <em>META-INF/peristence.xml</em> file.</p>
<pre>
&lt;property name="eclipselink.weaving" value="static" /&gt;
</pre>
<p>For more information about EclipseLink&#8217;s static weaving see the <a href="http://wiki.eclipse.org/Using_EclipseLink_JPA_Extensions_(ELUG)#How_to_Configure_Static_Weaving_for_JPA_Entities">How to Configure Static Weaving for JPA Entities</a> section of the <a href="http://wiki.eclipse.org/Using_EclipseLink_JPA_Extensions_(ELUG)">Using EclipseLink JPA Extensions</a> wiki page.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.tzavellas.com/techblog/2008/10/17/statically-weaving-jpa-entities-for-eclipselink-using-maven/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Using Dependency Injection in Struts2 for stateless EJBs part 2</title>
		<link>http://www.tzavellas.com/techblog/2007/07/03/using-dependency-injection-in-struts2-for-stateless-ejbs-part-2/</link>
		<comments>http://www.tzavellas.com/techblog/2007/07/03/using-dependency-injection-in-struts2-for-stateless-ejbs-part-2/#comments</comments>
		<pubDate>Tue, 03 Jul 2007 10:10:12 +0000</pubDate>
		<dc:creator>spiros</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[ejb]]></category>
		<category><![CDATA[guice]]></category>
		<category><![CDATA[struts]]></category>

		<guid isPermaLink="false">http://www.tzavellas.com/techblog/2007/07/03/using-dependency-injection-in-struts2-for-stateless-ejbs-part-2/</guid>
		<description><![CDATA[This is the second, and last part of the Using Dependency Injection in Struts2 for stateless EJBs series of posts. In this post I will present a utility class that can be used to make the creation of Guice bindings for EJB3s easier. Introducing EjbBinder Our goal is to make an easier API, specifically for [...]]]></description>
			<content:encoded><![CDATA[<p>This is the second, and last part of the <strong>Using Dependency Injection in Struts2 for stateless EJBs</strong> series of posts. In this post I will present a utility class that can be used to make the creation of Guice bindings for EJB3s easier.</p>
<h3>Introducing <code>EjbBinder</code></h3>
<p>Our goal is to make an easier API, specifically for creating bindings of EJB3s, and make the specification of the JNDI name optional, when possible. The below code is a new version of the <code>EjbModule</code> class that uses a new class, called <code>EjbBinder</code>, that we are going to present in this post.</p>
<pre>
public class EjbModule implements Module {

  public void configure(Binder binder) {
    // Bind Context to the default InitialContext.
    binder.bind(Context.class).to(InitialContext.class);

    EjbBinder ejbs = new EjbBinder(binder, new GlassfishEjbJndiNameStrategy());
    ejbs.bindRemote(CurrencyManagerRemote.class);
    ejbs.bind(DatesManagerRemote.class, "com.tzavellas.dates.ejb.DatesManagerBean");
  }
}
</pre>
<p><code>EjbBinder</code> contains two methods named <code>bind</code> and <code>bindRemote</code>. The <code>bind</code> method receives as arguments the expected class and JNDI name and simply uses <code>Binder</code> and <code>JndiItegration</code> to create a binding. The <code>bindRemote</code> method takes as an argument the remote interface of a sesion EJB3 and creates a binding using a JNDI name retrieved from the <code>EjbJndiNameStrategy</code>, that is specified in the <code>EjbBinder</code> constructor (BTW the <code>CurrencyManagerRemote</code> EJB interface in the above code does not relate with the application that we developed in the previous post and it is here to illustrate the <code>bindRemote</code> method).</p>
<p>The definition of the <code>EjbJndiNameStrategy</code>interface:</p>
<pre>
public interface EjbJndiNameStrategy {

  String interfaceToJndiName(Class&lt;?&gt; beanInterface);
}
</pre>
<p>The implementation of <code>EjbBinder</code>:</p>
<pre>
import com.google.inject.Binder;
import com.google.inject.binder.ScopedBindingBuilder;
import static com.google.inject.jndi.JndiIntegration.fromJndi;

public class EjbBinder {

  private Binder binder;
  private EjbJndiNameStrategy jndiNameStrategy;

  public EjbBinder(Binder binder, EjbJndiNameStrategy nameStrategy) {
    this.binder = binder;
    this.jndiNameStrategy = nameStrategy;
  }

  public &lt;T&gt; ScopedBindingBuilder bindRemote(Class&lt;T&gt; beanInterface) {
    return bind(beanInterface,
                jndiNameStrategy.interfaceToJndiName(beanInterface));
  }

  public &lt;T&gt; ScopedBindingBuilder bind(Class&lt;T&gt; beanInterface, String jndiName) {
    return binder.bind(beanInterface)
                 .toProvider(fromJndi(beanInterface, jndiName));
  }
}
</pre>
<h3>Application Server Specific Naming Strategies</h3>
<p>When you create a new EJB and you do not specify a JNDI name, the application server assigns a default name for you. So, if you have an implementation of <code>EjbJndiNameStrategy</code> that uses the naming rules of your application server you could avoid the need to specify a JNDI name when creating the EJB and when creating the binding of the EJB to Guice.</p>
<p>Below we have two implementations of the <code>EjbJndiNameStrategy</code> that can infer the JNDI name of an EJB&#8217;s remote client interface using the remote interface&#8217;s class for the Glassfish and JBoss application servers.</p>
<p>For the Glassfish application server the default global JNDI name of an EJB with a remote interface is the <a href="https://glassfish.dev.java.net/javaee5/ejb/EJB_FAQ.html#SessionBeanGlobalJNDINameAssignment">fully qualified name of the remote interface</a>.</p>
<pre>
public class GlassfishEjbJndiNameStrategy implements EjbJndiNameStrategy {

  public String interfaceToJndiName(Class<?> beanInterface) {
    return beanInterface.getName();
  }
}
</pre>
<p>For the JBoss application server the default JNDI name for the remote interface of an EJB is <em>earName/beanName/remote</em>.</p>
<pre>
//WARNING: Not tested!
public class JbossEjbJndiNameStrategy implements EjbJndiNameStrategy {

  private String earName = "";

  public JbossEjbJndiNameStrategy() { }

  public JbossEjbJndiNameStrategy(String earName) {
    if (earName != null &#038;&#038; "".equals(earName.trim()))
      this.earName = earName + "/";
  }

  public String interfaceToJndiName(Class&lt;?&gt; beanInterface) {
    return earName + interfaceToBeanName(beanInterface) + "/remote";
  }

  protected String interfaceToBeanName(Class&lt;?&gt; beanInterface) {
    String name = beanInterface.getSimpleName();
    if (name.endsWith("Remote"))
      name = name.replace("Remote", "");
    return name + "Bean";
  }
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.tzavellas.com/techblog/2007/07/03/using-dependency-injection-in-struts2-for-stateless-ejbs-part-2/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Using Dependency Injection in Struts2 for stateless EJBs part 1</title>
		<link>http://www.tzavellas.com/techblog/2007/07/03/using-dependency-injection-in-struts2-for-stateless-ejbs-part-1/</link>
		<comments>http://www.tzavellas.com/techblog/2007/07/03/using-dependency-injection-in-struts2-for-stateless-ejbs-part-1/#comments</comments>
		<pubDate>Tue, 03 Jul 2007 09:38:10 +0000</pubDate>
		<dc:creator>spiros</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[ejb]]></category>
		<category><![CDATA[guice]]></category>
		<category><![CDATA[struts]]></category>

		<guid isPermaLink="false">http://www.tzavellas.com/techblog/2007/07/03/using-dependency-injection-in-struts2-for-stateless-ejbs-part-1/</guid>
		<description><![CDATA[In this post I will present a way to use dependency injection of stateless session beans in Struts 2 actions using Guice. I will only write about EJB3, because they have simpler client lookup code, but you might be able to change the presented code to cover older versions of EJB. We will use off [...]]]></description>
			<content:encoded><![CDATA[<p>In this post I will present a way to use dependency injection of stateless session beans in Struts 2 actions using Guice. I will only write about EJB3, because they have simpler client lookup code, but you might be able to change the presented code to cover older versions of EJB.</p>
<p>We will use off the shelf Struts 2 and off the shelf Guice (with the Guice Struts 2 plug-in). No extra &#8220;glue&#8221; code is required to inject stateless EJBs into a Struts actions with Guice. In the next post I will tweak the presented code and make the binding of EJBs in Guice modules simpler.</p>
<p>This post is divided in two sections. In the first section we will create a simple, complete, hello-world type application using Struts 2. The application will consist of only one action that when called will print the current date in a JSP page. Then we will write a stateless session EJB and use Guice to inject the EJB into the action. If you are already familiar with Struts 2 you might want to skip the first section and go directly to the second.</p>
<h2>A basic Struts 2.x application</h2>
<p>Below you will find a series of steps with all code for our mini application.</p>
<h3>1. Project setup</h3>
<p>With your favorite IDE create an enterprise project. You need to create an enterprise project (ear based deployment) and not a web project (war based deployment) because we will create an EJB in the next section.</p>
<p>Now add a web module into your enterprise project and add the following jars to <em>WEB-INF/lib</em>: commons-logging-1.1.jar, freemarker-2.3.8.jar, ognl-2.6.11.jar, struts2-core-2.0.8.jar and xwork-2.0.3.jar.</p>
<p>Although I am a happy Eclipse user I have to admit that Eclipse has very basic support for Java EE 5, so for the code of this post I used Netbeans 6.0 M9 with Glassfish 2 Beta as the application server. Netbeans IMHO is not so good for Java editing but has decent support for the latest Java EE standards. Please keep in mind that the code is only tested with Glassfish 2 Beta.</p>
<h3>2. Edit web.xml</h3>
<p>The below code is the minimum web.xml needed for a Struts 2 application. It contains the Struts 2 filter definition (<code>FilterDispatcher</code>) and a welcome file (<em>index.html</em>) that it is used to redirect the user to the default Struts 2 action.</p>
<pre>
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         version="2.5"&gt;
  &lt;filter&gt;
    &lt;filter-name&gt;struts2&lt;/filter-name&gt;
    &lt;filter-class&gt;org.apache.struts2.dispatcher.FilterDispatcher&lt;/filter-class&gt;
  &lt;/filter&gt;
  &lt;filter-mapping&gt;
    &lt;filter-name&gt;struts2&lt;/filter-name&gt;
    &lt;url-pattern&gt;/*&lt;/url-pattern&gt;
  &lt;/filter-mapping&gt;
  &lt;welcome-file-list&gt;
    &lt;welcome-file&gt;index.html&lt;/welcome-file&gt;
  &lt;/welcome-file-list&gt;
&lt;/web-app&gt;
</pre>
<h3>3. Create struts.xml</h3>
<p>Now we need to create the struts.xml file. This file is located at the root of your classpath. The below code has some basic configuration parameters and includes the <em>dates</em> Struts package that will contain our action.</p>
<pre>
&lt;?xml version="1.0" encoding="UTF-8" ?&gt;
&lt;!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd"&gt;
&lt;struts&gt;
  &lt;constant name="struts.enable.DynamicMethodInvocation" value="false" /&gt;
  &lt;constant name="struts.devMode" value="false" /&gt;
  &lt;!-- Include the package with our actions --&gt;
  &lt;include file="dates.xml"/&gt;
&lt;/struts&gt;
</pre>
<h3>4. Create the dates Struts package</h3>
<p>Create the dates.xml file at the root of your classpath as we specified in the above struts.xml. In this file we define a package named <em>dates</em> and mapped under <em>&lt;context-root&gt;/dates/*</em> URL.</p>
<pre>
&lt;?xml version="1.0" encoding="UTF-8" ?&gt;
&lt;!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
        "http://struts.apache.org/dtds/struts-2.0.dtd"&gt;
&lt;struts&gt;
  &lt;package name="dates" namespace="/dates" extends="struts-default"&gt;
    &lt;action name="CurrentDate" class="com.tzavellas.dates.web.CurrentDateAction"&gt;
      &lt;result&gt;/WEB-INF/jsp/date.jsp&lt;/result&gt;
    &lt;/action&gt;
    &lt;!-- Add more actions here --&gt;
  &lt;/package&gt;
&lt;/struts&gt;
</pre>
<p>The package contains our only action, named <code>CurrentDate</code> and mapped to the URL <em>&lt;context-root&gt;/dates/CurrentDate.action</em>.</p>
<h3>5. Create the welcome file</h3>
<p>Now we will create our welcome file that redirects the user to the Struts action. This is a simple HTML page named index.html (as defined in web.xml) and located under the context root. The page uses a meta tag to redirect to the URL of the action .</p>
<pre>
&lt;html&gt;
  &lt;head&gt;
    &lt;meta http-equiv="Refresh" content="0;URL=dates/CurrentDate.action"&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;p&gt;Loading ...&lt;/p&gt;
  &lt;/body&gt;
&lt;/html&gt;
</pre>
<h3>6. Code the action</h3>
<p>Finally it&#8217;s time for some Java code. The below code is a simple Struts 2 action that when called will set the value of the <code>currentDate</code> property to the current date.</p>
<pre>
package com.tzavellas.dates.web;
import com.opensymphony.xwork2.ActionSupport;
import java.util.Date;

public class CurrentDateAction extends ActionSupport {

  private Date currentDate;

  @Override
  public String execute() throws Exception {
    currentDate = new Date();
    return SUCCESS;
  }

  public Date getCurrentDate() {
    return currentDate;
  }
}
</code></pre>
<p>Note that unlike Servlets or Struts 1 actions, in Struts 2 for every HTTP request a new action instance is created so it is safe to mutate an action property (like the <code>currentDate</code> above) with request specific data.</p>
<h3>7. Create the view</h3>
<p>As we defined in the dates package (<em>dates.xml</em>) the view for the <code>CurrentDateAction</code> is a JSP file localed in <em>WEB-INF/jsp/date.jsp</em>. The below code, for the <em>date.jsp</em> page, uses the Struts 2 tag library to display the value of the <code>currentDate</code> property of the action.</p>
<pre>
&lt;%@ page contentType="text/html" pageEncoding="UTF-8" %&gt;
&lt;%@ taglib prefix="s" uri="/struts-tags" %&gt;
&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd"&gt;
&lt;html&gt;
  &lt;head&gt;
    &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8"&gt;
    &lt;title&gt;The current date&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;h1&gt;The current date is: &lt;s:property value="currentDate"/&gt;&lt;/h1&gt;
  &lt;/body&gt;
&lt;/html&gt;
</pre>
<p>We&#8217;ve just created a simple application with Struts 2. In the next section we are going to define a stateless session EJB3 and wire it with the above action using Guice.</p>
<p>For more information about the Struts 2 web framework visit the <a href="http://cwiki.apache.org/WW/home.html">Struts 2 wiki</a> pages.</p>
<h2>The EJB and the integration with Guice</h2>
<h3>8. Create the stateless session EJB3</h3>
<p>With your favorite IDE add an EJB module to the enterprise project we created in <em>step 1</em>.</p>
<p>Below we define the SLSB with a remote interface and one method that returns the current date. The bean is mapped to the global JNDI name <em>com.tzavellas.dates.ejb.DatesManagerBean</em>.</p>
<pre>
package com.tzavellas.dates.ejb;
import java.util.Date;
import javax.ejb.Stateless;

@Stateless(mappedName="com.tzavellas.dates.ejb.DatesManagerBean")
public class DatesManagerBean implements DatesManagerRemote {

  public Date currentDate() {
    return new Date();
  }
}
</pre>
<pre>
package com.tzavellas.dates.ejb;
import java.util.Date;
import javax.ejb.Remote;

@Remote
public interface DatesManagerRemote {
  Date currentDate();
}
</pre>
<h3>9. Add the Guice jars in the classpath</h3>
<p>Add guice-1.0.jar and guice-struts2-plugin-1.0.1.jar in <em>WEB-INF/lib</em> directory of your web module. The jar file guice-1.0.jar contains the core Guice implementation and  the guice-struts2-plugin-1.0.1.jar file contains the Guice&#8217;s Struts 2 integration code.</p>
<h3>10. Edit struts.xml to include the Guice plug-in</h3>
<p>Struts 2 is a very flexible framework. One of Struts&#8217; many extensions is the <code>ObjectFactory</code> plug-in interface. The responsibility of an  <code>ObjectFactory</code> is to create the objects managed by Struts. An <code>ObjectFactory</code> is usually a dependency injection container like Spring, Pico and Guice.</p>
<p>To define Guice as the <code>ObjectFactory</code> of our Struts 2 application we have to set the <em>struts.objectFactory</em> property to <em>guice</em> in the struts.xml file and Guice will then be responsible for instantiating all the Struts managed objects (actions, interceptors, etc) .</p>
<p>To continue add the following lines in struts.xml.</p>
<pre>
&lt;!-- Use Guice as the ObjectFactory for this application --&gt;
&lt;constant name="struts.objectFactory" value="guice" /&gt;
&lt;!-- When wiring actions use Guice bindings defined in the below module --&gt;
&lt;constant name="guice.module" value="com.tzavellas.dates.web.EjbModule"/&gt;
</pre>
<h3>11. Code the EjbModule</h3>
<p>In the above struts.xml we defined two properties, <code>struts.objectFactory</code> and <code>guice.module</code>. To explain the <code>guice.module</code> property and the concept of Guice modules we have to explain the basics of Guice.</p>
<p>Guice is a, Java 5 based, dependency injection container that does constructor, field and setter injection (Guice also has features like support for AOP Alliance interceptors that we are not going to talk about in this post). To configure Guice you create a set of modules. A module implements the <code>com.google.inject.Module</code> interface and contains bindings. Bindings are created with the <code>com.google.inject.Binder</code> that is passed to the <code>configure(Binder)</code> method of a module. A binding is a pair composed of a type (key) and an implementation. An implementation can be an object, a class or a provider (factory). The bindings are consulted by the Guice <code>Injector</code> when doing dependency injection.</p>
<p>In the Guice Struts 2 plug-in the Guice <code>ObjectFactory</code> creates an <code>Injector</code> that then reads the module from the <code>guice.module</code> property in the <em>struts.xml</em> file and uses the bindings that are specified in that module to do dependency injection in Struts 2 actions and interceptors.</p>
<p>All we have to do to enable our EJB to be injected into an action is to create a binding for the client interface of the bean. We can&#8217;t create a binding to a class or instance, because the EJB&#8217;s instances must be instantiated by the EJB container and not by Guice, so we will use a provider that will lookup the EJB from JNDI. The Guice library includes a JNDI provider that we are going to use that it is located in the <code>com.google.inject.jndi.JndiIntegration</code> class.</p>
<p>The below code is the implementation of the <code>EJBModule</code>, which has  only two bindings. The first binds the <code>javax.naming.Context</code> type to the <code>javax.naming.InitialContext</code> implementation. This means that when the Guice <code>Injector</code> finds a field or parameter of type <code>javax.naming.Context</code>, that needs to be injected (marked with the <code>@Inject</code> annotation), it will create a new object of type <code>javax.naming.InitialContext</code> and inject it. This binding is needed by the JNDI provider that we are going to use in the next binding.</p>
<p>The second binding binds our EJB&#8217;s remote interface to the JNDI provider. The JNDI provider is returned from the call to the static <code>JndiIntegration.fromJndi(Class, String)</code> method. To get a JNDI provider we have to specify the expected class and JNDI name. This binding tells the Guice <code>Injector</code> that when it finds a field or parameter of type <code>com.tzavellas.dates.ejb.DatesManagerRemote</code>, that needs to be injected (marked with the <code>@Inject</code> annotation), it should call the provider&#8217;s <code>get()</code> method to retrieve an instance to inject.</p>
<pre>
package com.tzavellas.dates.web;
import com.google.inject.Binder;
import com.google.inject.Module;
import static com.google.inject.jndi.JndiIntegration.fromJndi;
import com.tzavellas.dates.ejb.DatesManagerRemote;
import javax.naming.Context;
import javax.naming.InitialContext;

public class EjbModule implements Module {

  public void configure(Binder binder) {
    // Bind Context to the default InitialContext.
    binder.bind(Context.class).to(InitialContext.class);
    // Bind the remote interface to the JNDI name using the JNDI Provider
    binder.bind(DatesManagerRemote.class)
          .toProvider(fromJndi(DatesManagerRemote.class, "com.tzavellas.dates.ejb.DatesManagerBean"));
  }
}
</pre>
<p>For more information on how to do dependency injection with Guice see the <a href="http://docs.google.com/View?docid=dd2fhx4z_5df5hw8">Guice User&#8217;s Guide</a>.</p>
<h3>12. Change the action to use the EJB</h3>
<p>Now that Guice instantiates our actions we can use the normal Guice <code>@Inject</code> annotation to mark an injection point in the action class. We can use any of the constructor, setter and field injection mechanisms. The below code uses field injection because it might be more familiar to EJB3 developers.</p>
<pre>
package com.tzavellas.dates.web;
import com.google.inject.Inject;
import com.opensymphony.xwork2.ActionSupport;
import com.tzavellas.dates.ejb.DatesManagerRemote;
import java.util.Date;

public class CurrentDateAction extends ActionSupport {
  // Guice field injection of the SLSB
  @Inject DatesManagerRemote bean;

  private Date currentDate;

  @Override
  public String execute() throws Exception {
    currentDate = bean.currentDate();
    return SUCCESS;
  }

  public Date getCurrentDate() {
    return currentDate;
  }
}
</pre>
<h3>Conclusion</h3>
<p>We are done. We&#8217;ve just coded a simple Struts 2 application that uses Guice to inject stateless session EJB3s to Struts actions. You can follow the instructions outlined above to do the same into your applications.</p>
<h3>Appendix: Quick summary of all the steps</h3>
<p>Assuming that you have a working Struts 2 application, below you will find a series of steps you could follow to do dependency injection of your stateless EJB3s into your Struts 2 actions.</p>
<p>For your project:</p>
<ol>
<li>Include the Guice jars in the <em>WEB-INF/lib</em> directory.</li>
<li>Define a Guice module that will contain the bindings for your EJBs.</li>
<li>Edit the struts.xml to define Guice as your <code>ObjectFactory</code> and include the above module.</li>
</ol>
<p>For every EJB that you want to inject into your Struts actions:</p>
<ol>
<li>Inside the module, define a binding for the EJB using the Guice <code>Provider</code> from <code>com.google.inject.jndi.JndiIntegration</code> class, by specifying the bean&#8217;s client interface and the global JNDI name of the bean (or an ejb-ref if you have one defined in web.xml).</li>
<li>Use the <code>@Inject</code> annotation in the Struts actions where you want the EJBs injected.</li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://www.tzavellas.com/techblog/2007/07/03/using-dependency-injection-in-struts2-for-stateless-ejbs-part-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>C# Extension methods</title>
		<link>http://www.tzavellas.com/techblog/2007/06/02/c-extension-methods/</link>
		<comments>http://www.tzavellas.com/techblog/2007/06/02/c-extension-methods/#comments</comments>
		<pubDate>Sat, 02 Jun 2007 07:45:33 +0000</pubDate>
		<dc:creator>spiros</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://www.tzavellas.com/techblog/2007/06/02/c-extension-methods/</guid>
		<description><![CDATA[Scott Hanselman has a post about a user who doesn&#8217;t get what is cool about Ruby. In the post you can find the below example that compares Java and Ruby in terms of code readability. The Java code: new Date(new Date().getTime() - 20 * 60 * 1000) The Ruby code: 20.minutes.ago The article was interesting [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.hanselman.com/blog/">Scott Hanselman</a> has a <a href="http://www.hanselman.com/blog/ProgrammerIntentOrWhatYoureNotGettingAboutRubyAndWhyItsTheTits.aspx">post</a> about a user who doesn&#8217;t get what is cool about <a href="http://www.ruby-lang.org/en/">Ruby</a>.</p>
<p>In the post you can find the below example that compares <a href="http://java.sun.com">Java</a> and <a href="http://www.ruby-lang.org/en/">Ruby</a> in terms of code readability.</p>
<p>The Java code:</p>
<pre>new Date(new Date().getTime() - 20 * 60 * 1000)</pre>
<p>The Ruby code:</p>
<pre>20.minutes.ago</pre>
<p>The article was interesting but what really caught my attention was some comments from C# programmers who showed how, in a few lines of code, you can mimic the Ruby syntax in C# using extension methods.</p>
<p>The new version of C#, shipped with the <a href="http://msdn2.microsoft.com/en-us/vstudio/aa700830.aspx">Orcas</a> release of Visual Studio, has a new feature called extension methods. Extension methods were added to the .Net languages to support <a href="http://msdn2.microsoft.com/en-us/netframework/aa904594.aspx">LINQ</a> and they provide a way to attach methods to classes without changing their code.</p>
<p>The below code is copied and modified from the comments of Ian Cooper in the  aforementioned <a href="http://www.hanselman.com/blog/ProgrammerIntentOrWhatYoureNotGettingAboutRubyAndWhyItsTheTits.aspx">blog post</a>.</p>
<pre>
public static class TimeExtensions {

  public static TimeSpan Minutes(this int numberOfMinutes) {
    return new TimeSpan(0, numberOfMinutes, 0);
  }

  public static DateTime Ago(this TimeSpan numberOfMinutes) {
    return DateTime.Now.Subtract(numberOfMinutes);
  }
}
</pre>
<p>In the above code we defined a class, called <code>TimeExtensions</code>, which contains two extension methods. Notice the <code>this</code> keyword on the left of the fist parameter (both methods take one parameter in the example code) of the methods. The <code>this</code> keyword tells the C# compiler that a method is an extension method. The parameter annotated with the <code>this</code> keyword is the object on which the extension method is called. If I am correct, the methods are not really added to the classes (you can&#8217;t find them via reflection), the compiler at-compile-time translates them into static method calls.</p>
<p>In our example the first method, called <code>Minutes</code>, will be added to the <code>int</code> class (probably via auto-boxing) and the second method, called <code>Ago</code>, will be added to the <code>TimeSpan</code> class.</p>
<p>Now, to use the extension methods that we defined above we have to import them using the <code>using TimeExtensions</code> statement. This is a really good thing since the usage of extension methods is always explicit. You have to import them to use them and if you don&#8217;t want to use them you don&#8217;t import them.</p>
<pre>
using System;
using TimeExtensions;

public class HelloWorld {
  public static void Main() {
    Console.WriteLine( 20.Minutes().Ago() );
  }
}
</pre>
<p><code>20.Minutes().Ago()</code> is pretty close to <code>20.minutes.ago</code> <img src='http://www.tzavellas.com/techblog/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>For a nice tutorial about C# 3.0 extension methods see: <a href="http://weblogs.asp.net/scottgu/archive/2007/03/13/new-orcas-language-feature-extension-methods.aspx">New &#8220;Orcas&#8221; Language Feature: Extension Methods</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.tzavellas.com/techblog/2007/06/02/c-extension-methods/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Making Maven 2 work with JUnit 4</title>
		<link>http://www.tzavellas.com/techblog/2007/05/16/making-maven-2-work-with-junit-4/</link>
		<comments>http://www.tzavellas.com/techblog/2007/05/16/making-maven-2-work-with-junit-4/#comments</comments>
		<pubDate>Wed, 16 May 2007 04:38:51 +0000</pubDate>
		<dc:creator>spiros</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[junit]]></category>
		<category><![CDATA[maven]]></category>

		<guid isPermaLink="false">http://www.tzavellas.com/techblog/2007/05/16/making-maven-2-work-with-junit-4/</guid>
		<description><![CDATA[The current stable version (2.2) of the maven-surefire-plugin does not support JUnit 4. So Maven, out of the box, does not work with JUnit 4. Luckily if we want to use JUnit 4 in our Maven based projects we have two choices. The first is to use JUnit4TestAdapter as illustrated in this post. The second [...]]]></description>
			<content:encoded><![CDATA[<p>The current stable version (2.2) of the <a href="http://maven.apache.org/plugins/maven-surefire-plugin/">maven-surefire-plugin</a> <a href="http://jira.codehaus.org/browse/SUREFIRE-31">does not support JUnit 4</a>. So Maven, out of the box, does not work with JUnit 4. Luckily if we want to use JUnit 4 in our Maven based projects we have two choices. The first is to use <code>JUnit4TestAdapter</code> as illustrated in <a href="http://www.jroller.com/page/eu?entry=running_junit_4_test_cases">this</a> post. The second is to use the snapshot version (2.3-SNAPSHOT) of the maven-surefire-plugin that has support for JUnit 4. In a small pet-project I am currently implementing I chose the second option and so far my experience was without any problems.</p>
<p>To use the 2.3-SNAPSHOT you first have to add the Maven snapshot plugin repository into your list of plugin repositories. In your <em>pom.xml</em> add the below XML:</p>
<pre>
&lt;pluginRepositories&gt;
  &lt;pluginRepository&gt;
    &lt;id&gt;apache.org&lt;/id&gt;
    &lt;name&gt;Maven Plugin Snapshots&lt;/name&gt;
    &lt;url&gt;http://people.apache.org/repo/m2-snapshot-repository&lt;/url&gt;
    &lt;releases&gt;
      &lt;enabled&gt;false&lt;/enabled&gt;
    &lt;/releases&gt;
    &lt;snapshots&gt;
      &lt;enabled&gt;true&lt;/enabled&gt;
    &lt;/snapshots&gt;
  &lt;/pluginRepository&gt;
&lt;/pluginRepositories&gt;
</pre>
<p>You can also put this configuration into your <em>~/.m2/settings.xml</em> file to enable this repository for all your projects.</p>
<p>Then go to the maven-surefire-plugin configuration section and change the version from <em>2.2</em> to <em>2.3-SNAPSHOT</em>. For example below I have the maven-surefire-plugin configuration that I use in my pet-project:</p>
<pre>
&lt;plugin&gt;
  &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
  &lt;artifactId&gt;maven-surefire-plugin&lt;/artifactId&gt;
  &lt;version&gt;2.3-SNAPSHOT&lt;/version&gt;
  &lt;configuration&gt;
    &lt;includes&gt;
      &lt;include&gt;**/*Test.java&lt;/include&gt;
    &lt;/includes&gt;
    &lt;forkMode&gt;once&lt;/forkMode&gt;
  &lt;/configuration&gt;
&lt;/plugin&gt;
</pre>
<p>That&#8217;s it, you are done. When you run Maven again the new (2.3-SNAPSHOT) version will be downloaded and you can start using JUnit 4 in you project.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.tzavellas.com/techblog/2007/05/16/making-maven-2-work-with-junit-4/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>

