<?xml version="1.0" encoding="UTF-8"?>
<chapter version="5.0" xml:id="howto-use-cdi" xml:lang="en"
         xmlns="http://docbook.org/ns/docbook"
         xmlns:xlink="http://www.w3.org/1999/xlink"
         xmlns:xi="http://www.w3.org/2001/XInclude"
         xmlns:svg="http://www.w3.org/2000/svg"
         xmlns:mml="http://www.w3.org/1998/Math/MathML"
         xmlns:html="http://www.w3.org/1999/xhtml"
         xmlns:db="http://docbook.org/ns/docbook">
  <title>Use CDI in JOnAS</title>

  <section>
    <title>Java Context and Dependency Injection (CDI)</title>

    <para></para>

    <section>
      <title>What is this all about ?</title>

      <para>In a nutshell, the <emphasis>Java Context and Dependency
      Injection</emphasis> (<acronym>CDI</acronym> for short) is a
      <emphasis>Java EE 6 specification</emphasis> that defines a powerful set
      of complementary services that help improve the structure of application
      code.</para>

      <para><itemizedlist>
          <listitem>
            <para>A well-defined lifecycle for stateful objects bound to
            lifecycle contexts, where the set of contexts is extensible</para>
          </listitem>

          <listitem>
            <para>A sophisticated, typesafe dependency injection mechanism,
            including the ability to select dependencies at either development
            or deployment time, without verbose configuration</para>
          </listitem>

          <listitem>
            <para>Support for Java EE modularity and the Java EE component
            architecture - the modular structure of a Java EE application is
            taken into account when resolving dependencies between Java EE
            components</para>
          </listitem>

          <listitem>
            <para>Integration with the Unified Expression Language
            (<acronym>EL</acronym>), allowing any contextual object to be used
            directly within a <acronym>JSF</acronym> or <acronym>JSP</acronym>
            page</para>
          </listitem>

          <listitem>
            <para>The ability to decorate injected objects</para>
          </listitem>

          <listitem>
            <para>The ability to associate interceptors to objects via
            typesafe interceptor bindings</para>
          </listitem>

          <listitem>
            <para>An event notification model</para>
          </listitem>

          <listitem>
            <para>A web conversation context in addition to the three standard
            web contexts defined by the Java Servlets specification</para>
          </listitem>

          <listitem>
            <para>An <acronym>SPI</acronym> allowing portable extensions to
            integrate cleanly with the container</para>
          </listitem>
        </itemizedlist></para>

      <para><acronym>CDI</acronym> can be seen as a standard alternative to
      proprietary containers (Spring framework, Guice, ...).</para>

      <para></para>
    </section>
  </section>

  <section>
    <title>CDI Services</title>

    <para>Here is a quick description of the major features of the
    <acronym>CDI</acronym> programming model.</para>

    <section>
      <title>Injection</title>

      <para><acronym>CDI</acronym> injection is based on the Dependency
      Injection specification (<link
      xlink:href="http://jcp.org/en/jsr/detail?id=330">JSR 330</link>) that
      defines basic injection capabilities. <acronym>CDI</acronym> extends
      this specification by adding the Qualifier annotation concept that helps
      to disambiguate between 2 possible injection targets.</para>

      <para>It provides means to assemble your application components very
      easily, using only annotations, in a type-safe way.</para>

      <para>Definition of a qualifier <classname>@Synchronous</classname>
      annotation:</para>

      <para><programlisting>@Qualifier
@Retention(RUNTIME)
@Target({METHOD, FIELD, PARAMETER, TYPE})
public @interface Synchronous {}
</programlisting>Placed on top of a bean class, it qualifies the bean.</para>

      <para><programlisting language="java">/**
 * Declaration of a PaymentProcessor bean qualified with @Synchronous.
 */
@Synchronous
class SynchronousPaymentProcessor
        implements PaymentProcessor {
    ...
}
</programlisting>It's used at the injection point to help the container choose
      the right <classname>PaymentProcessor</classname> bean to inject.</para>

      <para><programlisting language="java">/**
 * Declared a dependency on a PaymentProcessor bean qualified with @Synchronous
 */
@Inject @Synchronous PaymentProcessor paymentProcessor;
</programlisting></para>
    </section>

    <section>
      <title>Interception</title>

      <para>Interception in the <acronym>CDI</acronym> model is also
      annotation based. Any <acronym>CDI</acronym> bean can be intercepted
      using the Java EE 5 interception mechanism
      (<classname>@AroundInvoke</classname>).</para>

      <para>Interceptors allow common, cross-cutting concerns to be applied to
      beans via custom annotations. Interceptor types may be individually
      enabled or disabled at deployment time.</para>

      <para>The <classname>AuthorizationInterceptor</classname> class defines
      a custom authorization check:</para>

      <para><programlisting language="java">@Secure @Interceptor
public class AuthorizationInterceptor {
    @Inject @LoggedIn User user;
    @Inject Logger log;
    @AroundInvoke
    public Object authorize(InvocationContext ic) throws Exception {
        try {
            if ( !user.isBanned() ) {
                log.fine("Authorized");
                return ic.proceed();
            }
            else {
                log.fine("Not authorized");
                throw new NotAuthorizedException();
            }
        }
        catch (NotAuthenticatedException nae) {
            log.fine("Not authenticated");
            throw nae;
        }
    }
}
</programlisting>The <classname>@Interceptor</classname> annotation,
      identifies the <classname>AuthorizationInterceptor</classname> class as
      an interceptor. The <classname>@Secure</classname> annotation is a
      custom interceptor binding type.</para>

      <para><programlisting>@Inherited
@InterceptorBinding
@Target({TYPE, METHOD})
@Retention(RUNTIME)
public @interface Secure {}
</programlisting>The <classname>@Secure</classname> annotation is used to
      apply the interceptor to a bean:</para>

      <para><programlisting>@Model
public class DocumentEditor {
    @Inject Document document;
    @Inject @LoggedIn User user;
    @Inject @Documents EntityManager em;
    @Secure
    public void save() {
        document.setCreatedBy(currentUser);
        em.persist(document);
    }
}
</programlisting></para>

      <para><note>
          <para>By default interceptors are not activated. They have to be
          explicitely declared in the <filename>beans.xml</filename>
          file.</para>

          <para><programlisting language="xml">&lt;beans 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/beans_1_0.xsd"&gt;
  &lt;interceptors&gt;
    &lt;!-- Interceptors are only activated if listed in the beans.xml file --&gt;
    &lt;class&gt;org.ow2.jonas.examples.cdi.interceptor.AroundMethodLogInterceptor&lt;/class&gt;
  &lt;/interceptors&gt;
&lt;/beans&gt;</programlisting></para>
        </note></para>
    </section>

    <section>
      <title>Decoration</title>

      <para>The <acronym>CDI</acronym> programming model eases the usage of
      the <link
      xlink:href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator
      pattern</link>.</para>

      <para>An abstract bean type (implementing an interface) can be annoted
      with <classname>@Decorator</classname>, it has a
      <classname>@Delegate</classname> annotated member and overrides one (or
      more) methods of the interface.</para>

      <para><programlisting>public interface User {
    String getName();
    String getCompanyName();
}
</programlisting></para>

      <para>The <classname>LongNameUserDecorator</classname> will be applied
      on all <classname>User</classname> beans.</para>

      <para><programlisting>@Decorator
public abstract class LongNameUserDecorator implements User {

    @Inject
    @Delegate
    private User delegate;

    public String getName() {
        return delegate.getName() + " (Last name added with @Decorator)";
    }

</programlisting></para>

      <para><note>
          <para>Like interceptors, decorators may be easily enabled or
          disabled at deployment time with the <filename>beans.xml</filename>
          file.</para>

          <para><programlisting language="xml">&lt;beans 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/beans_1_0.xsd"&gt;
  &lt;decorators&gt;
    &lt;!-- Decorators are only activated if listed in the beans.xml file --&gt;
    &lt;class&gt;org.ow2.jonas.examples.cdi.user.decorator.LongNameUserDecorator&lt;/class&gt;
  &lt;/decorators&gt;
&lt;/beans&gt;</programlisting></para>
        </note></para>
    </section>

    <section>
      <title>Eventing</title>

      <para><acronym>CDI</acronym> comes with a full featured eventing
      support. It nicely decouple the observed object from the observers: the
      container links each of them together.</para>

      <para></para>

      <section>
        <title>Observed Element</title>

        <para><programlisting>@SessionScoped @Model
public class Login implements Serializable {
    @Inject Credentials credentials;
    @Inject @Users EntityManager userDatabase;
    @Inject @LoggedIn Event&lt;User&gt; userLoggedInEvent;
    ...
    private User user;

    @Inject
    void initQuery(@Users EntityManagerFactory emf) {
        ...
    }

    public void login() {
         List&lt;User&gt; results = ... ;
         if ( !results.isEmpty() ) {
             user = results.get(0);
             userLoggedInEvent.fire(user);
         }
    }
    @Produces @LoggedIn User getCurrentUser() {
         ...
    }
}
</programlisting>The Login class is injected with an
        <classname>Event&lt;User&gt;</classname> instance (notice the
        <classname>@LoggedIn</classname> qualifier annotation).</para>

        <para>When the <classname>User</classname> gets logged in,
        <methodname>userLoggedInEvent.fire(user)</methodname> is executed and
        all observer methods will be synchronously invoked.</para>
      </section>

      <section>
        <title>Observer Method</title>

        <para><programlisting>@SessionScoped
public class Permissions implements Serializable {
    @Produces
    private Set&lt;Permission&gt; permissions = new HashSet&lt;Permission&gt;();
    @Inject @Users EntityManager userDatabase;
    Parameter&lt;String&gt; usernameParam;

    ...

    void onLogin(@Observes @LoggedIn User user) {
        permissions = new HashSet&lt;Permission&gt;(
           userDatabase.createQuery(query)
                       .setParameter(usernameParam, user.getUsername())
                       .getResultList() );
    }
}
</programlisting>Notice the <methodname>onLogin()</methodname> method, it's an
        observer method because of the <classname>@Observes</classname>
        parameter annotation. This method will be invoked when a
        <classname>User</classname> event will be fired by a
        <classname>@LoggedIn</classname> annotated
        <classname>Event&lt;User&gt;</classname> field.</para>
      </section>
    </section>

    <section>
      <title>Scoping/Context</title>

      <para>Instance's life-cycle is bound to a scope (request, session,
      application).</para>

      <para>Beans can de declared to be bound in one scope</para>

      <para><programlisting>@SessionScoped
public class Order { ... }
</programlisting></para>

      <para>Injection/Producers points can also be annotated with scope
      requirements:</para>

      <para><programlisting>public class Shop {
   @Produces @ApplicationScoped @All
   public List&lt;Product&gt; getAllProducts() { ... }
   @Produces @SessionScoped @WishList
   public List&lt;Product&gt; getWishList() { ..... }
}
</programlisting></para>
    </section>
  </section>

  <section>
    <title>Activation</title>

    <para>In order to activate <acronym>CDI</acronym> on JOnAS, the 'cdi'
    service must be declared in the
    <filename>$JONAS_BASE/conf/jonas.properties</filename> in the
    <literal>jonas.services</literal> property.</para>

    <para><programlisting>jonas.services    registry,jmx,... ,cdi
</programlisting>JOnAS is using Weld (the CDI reference implementation) under
    the hood.<warning>
        <para>Current CDI support in JOnAS is limited to web applications.
        Future versions will enable EJB and EAR support.</para>
      </warning></para>
  </section>

  <section>
    <title>Resources</title>

    <para><itemizedlist>
        <listitem>
          <para>Dependency Injection Specification (<link
          xlink:href="http://jcp.org/en/jsr/detail?id=330">JSR
          330</link>)</para>
        </listitem>

        <listitem>
          <para>@Inject <link
          xlink:href="http://code.google.com/p/atinject/">Google
          project</link></para>
        </listitem>

        <listitem>
          <para>Java Context and Dependency Injection Specification (<link
          xlink:href="http://jcp.org/en/jsr/detail?id=299">JSR
          299</link>)</para>
        </listitem>

        <listitem>
          <para>RedHat <link xlink:href="http://seamframework.org/Weld">JBoss
          Weld</link> (Reference Implementation) + <link
          xlink:href="http://docs.jboss.org/weld/reference/1.1.0.Final/en-US/html/">Documentation</link></para>
        </listitem>

        <listitem>
          <para><link xlink:href="http://openwebbeans.apache.org/">Apache
          WebBeans</link> (ASL2 Licensed Implementation) + <link
          xlink:href="http://openwebbeans.apache.org/1.0.0-SNAPSHOT/documentation.html">Documentation</link></para>
        </listitem>

        <listitem>
          <para>JOnAS CDI Sample (in <filename
          class="directory">examples/</filename> or <link
          xlink:href="http://websvn.ow2.org/listing.php?repname=jonas&amp;path=%2Fsandbox%2Fsauthieg%2Fjonas-cdi-webapp%2F">online</link>)</para>
        </listitem>
      </itemizedlist></para>
  </section>
</chapter>
