<?xml version="1.0" encoding="UTF-8"?>
<!--
 - JOnAS: Java(TM) Open Application Server
 - Copyright (C) 2008 Bull S.A.S.
 - Contact: jonas-team@ow2.org
 -
 - Licensed under the Creative Commons License (Attribution ShareAlike),
 - Version 2.0 (the "License");
 - You may not use this file except in compliance with the License.
 - You may obtain a copy of the License at
 -
 -     http://creativecommons.org/licenses/by-sa/2.0/
 -
 - $Id$
 -->
<book version="5.0" 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:xhtml="http://www.w3.org/1999/xhtml"
      xmlns:svg="http://www.w3.org/2000/svg"
      xmlns:math="http://www.w3.org/1998/Math/MathML"
      xmlns:db="http://docbook.org/ns/docbook">
  <info>
    <title>Getting started with JOnAS 5</title>

    <authorgroup>
      <author>
        <orgname>JOnAS Team</orgname>
      </author>

      <author>
        <personname><surname>Coq</surname><firstname>Philippe</firstname></personname>
      </author>

      <author>
        <personname><surname>Sauthier</surname><firstname>Guillaume</firstname></personname>
      </author>
    </authorgroup>

    <legalnotice>
      <para>This work is licensed under the Creative Commons
      Attribution-ShareAlike License. To view a copy of this license,visit
      <link
      xlink:href="http://creativecommons.org/licenses/by-sa/2.0/deed.en">http://creativecommons.org/licenses/by-sa/2.0/deed.en</link>
      or send a letter to Creative Commons, 559 Nathan Abbott Way, Stanford,
      California 94305, USA.</para>
    </legalnotice>

    <copyright>
      <year>2007-2009</year>

      <holder>OW2 Consortium</holder>
    </copyright>

    <releaseinfo><xi:include href="variables.xml"
    xpointer="element(jonas.version)" /></releaseinfo>

    <date>March 2009</date>
  </info>

  <preface>
    <info>
      <title>Preface</title>
    </info>

    <para>Welcome new users of <xi:include href="variables.xml"
    xpointer="appserver" /> ! This guide is intended to help you.</para>

    <para><emphasis role="bold"><xref
    linkend="getting.started.first.contact" /></emphasis> shows that a
    downloaded <xi:include href="variables.xml" xpointer="j48ee" /> is usable
    as is.</para>

    <para>The environment to set is truly minimal. It's child's play to run a
    <xi:include href="variables.xml" xpointer="j2ee" /> application.</para>

    <para>This chapter shows not only how to perform some actions but also
    explains why everything runs so easily.</para>

    <para><xi:include href="variables.xml" xpointer="element(j48ee)" /> is
    distributed with examples ready to use. Users can learn a lot by studying
    these examples</para>

    <para><emphasis role="bold"><xref
    linkend="getting.started.learning" /></emphasis></para>

    <para>Theses examples may be used as a tutorial for Java EE 5 technology.
    They are using the simplified programming model, dependency injection,
    Java Persistence API, security and other functionalities available in Java
    EE 5.</para>

    <para>Note that this guide wants to be simple and is not intended to
    resolve all problems that can be encountered in <emphasis>real
    life</emphasis> situtations, which can be very complex.</para>

    <para>For more experimented users that need to perform more complex tasks,
    we recommend taking a look at the <link
    xlink:href="configuration_guide.html">JOnAS 5 Configuration
    guide</link></para>

    <para><emphasis role="bold"><xref linkend="downloadid" /></emphasis>
    summarizes downloading and installing <xi:include href="variables.xml"
    xpointer="appserver" />.</para>

    <para><emphasis role="bold"><xref linkend="distribution" /></emphasis>
    describes what you get when you download and install <xi:include
    href="variables.xml" xpointer="appserver" />.</para>
  </preface>

  <chapter xml:id="getting.started.first.contact">
    <info>
      <title>First contact with JOnAS 5</title>
    </info>

    <para>It is assumed, in this guide, that the first time user has already
    downloaded and installed <xi:include href="variables.xml"
    xpointer="j48ee" />. If this is not the case, please refer to <xref
    linkend="downloadid" />.</para>

    <para>In this chapter an unexperienced user will learn how to run an
    existing <xi:include href="variables.xml" xpointer="element(j2ee)" />
    application with <xi:include href="variables.xml"
    xpointer="element(appserver)" />. He will understand why it is so easy to
    achieve such results with nearly zero configuration.</para>

    <section>
      <info>
        <title>How do I set up a JOnAS environment?</title>
      </info>

      <para>Once you have installed your <xi:include href="variables.xml"
      xpointer="appserver" /> distribution, you have to set up the
      <envar>JONAS_ROOT</envar> environment variable prior to using
      <xi:include href="variables.xml" xpointer="appserver" /> or any of its
      tools. You will also have to update your PATH variable.</para>

      <itemizedlist>
        <listitem>
          <para>Unix platforms</para>

          <para>Open a new terminal and proceed as follows:</para>

          <screen><prompt>bash&gt;</prompt> <userinput>export JONAS_ROOT=&lt;<filename
                class="directory">your_install_dir</filename>&gt;
</userinput><prompt>bash&gt;</prompt> <userinput>export PATH=${PATH}:${JONAS_ROOT}/bin</userinput></screen>

          <para>or</para>
        </listitem>
      </itemizedlist>

      <itemizedlist>
        <listitem>
          <para>Windows platforms</para>

          <para>Open a new DOS window and proceed as follows:</para>

          <screen><prompt>C:&gt;</prompt> <userinput>set JONAS_ROOT=&lt;<filename
                class="directory">your_install_dir</filename>&gt;
</userinput><prompt>C:&gt;</prompt> <userinput>set PATH=%PATH%;%JONAS_ROOT%\bin</userinput></screen>

          <para>To update the path permanently, do the following depending
          upon your Windows version:</para>

          <variablelist>
            <varlistentry>
              <term>Windows XP</term>

              <listitem>
                <para>Go to the Start Menu, then double click on System. In
                the System Control Panel select the Advanced tab and push the
                Environment Variables button. Now, you can look for the
                <envar>PATH</envar> to edit. Append the value
                <literal>;C:\jonas-5.x\bin</literal> (assuming that you
                installed JOnAS in the <filename
                class="directory">C:\jonas-5.x</filename> directory).</para>
              </listitem>
            </varlistentry>
          </variablelist>
        </listitem>
      </itemizedlist>

      <para><xi:include href="variables.xml" xpointer="appserver" />
      distribution contains a number of configuration files in <filename
      class="directory">$JONAS_ROOT/conf</filename> directory. These files can
      be edited to change the default configuration. However, it is
      recommended to put the configuration files needed by a specific
      application running on <xi:include href="variables.xml"
      xpointer="appserver" /> in a separate location. This is done by using an
      additional environment variable called JONAS_BASE.</para>

      <xi:include href="config/jonasbase_creation.xml" />
    </section>

    <section>
      <info>
        <title>How can I check if everything is correct?</title>
      </info>

      <para>JOnAS provides the command <command arch="" condition="">jonas
      check </command>that checks if your environment is set correctly.</para>

      <xi:include href="command_guide.xml"
                  xpointer="commands.jonas.jonascheck" />
    </section>

    <section xml:id="startingjonas">
      <info>
        <title>How can I run a JOnAS server?</title>
      </info>

      <para>Now that your environment seems correct, it is possible to launch
      the <xi:include href="variables.xml" xpointer="appserver" /> server
      simply by typing the following command:</para>

      <screen><prompt>bash&gt;</prompt> <userinput>jonas start</userinput>
      <computeroutput>
OW2 JOnAS 5.1.0 [ http://jonas.ow2.org / jonas@ow2.org ]

JONAS_BASE is set to xxxxx

Welcome to OW2 JOnAS (Running on Felix).
-----------------------------------------------
      </computeroutput>
      </screen>

      <para>As soon as your server is ready, i.e when you can see on your
      terminal something that looks like:</para>

      <screen><computeroutput>J2EEServer.__info : JOnAS AS v5.1 named 'jonas' RUNNING</computeroutput></screen>

      <para>you can use your favorite browser and type in the following
      URL:</para>

      <para><screen>http://localhost:9000/</screen>Here is the web page you
      should see:</para>

      <mediaobject>
        <imageobject role="html">
          <imagedata fileref="../../resources/images/firstpage.gif"></imagedata>
        </imageobject>

        <imageobject role="fo">
          <imagedata fileref="../../resources/images/firstpage.gif" scale="50"></imagedata>
        </imageobject>
      </mediaobject>

      <para>You just have run JOnAS for the first time.</para>

      <para>You are now able to do some interesting things like run a sample
      <xi:include href="variables.xml" xpointer="j2ee" /> application packaged
      in a <filename class="extension">.ear </filename>file (the <emphasis
      role="bold">earsample </emphasis>example), run the web administration
      tool for <xi:include href="variables.xml" xpointer="appserver" />, or
      you can do some other things that we will explain later on.</para>
    </section>

    <section>
      <info>
        <title>How can I run my first Java EE application?</title>
      </info>

      <para>If you have followed the previous steps you are now ready to run
      your first <xi:include href="variables.xml" xpointer="element(j2ee)" />
      application in <xi:include href="variables.xml"
      xpointer="element(appserver)" />.</para>

      <para>First, we need an application to run. We have chosen the <filename
      class="directory">$JONAS_ROOT/examples/javaee5-earsample</filename>
      example.It is a fairly good example that shows some interesting
      functionnalities of the java EE 5 technology. See <xref
      linkend="getting.started.learning" /> for more details.</para>

      <para>You must first compile and generate the Java EE application. This
      is done by using Ant</para>

      <para><screen>bash&gt; cd $JONAS_ROOT/examples/javaee5-earsample

bash&gt; ant</screen></para>

      <para>When you get :</para>

      <para><screen>Build Successfull</screen>You have compiled all the java
      classes, packaged them in an ear archive and copied it under
      $JONAS_BASE/deploy.</para>

      <para>At JOnAS startup time this Java EE application will be
      automatically deployed.</para>

      <para>Now as soon as your JOnAS server is started you can run the
      application by typing the following URL in a browser:</para>

      <para><screen><link xlink:href="http://localhost:9000/javaee5-earsample">http://localhost:9000/javaee5-earsample</link></screen></para>
    </section>

    <section>
      <info>
        <title>Understanding how all of this runs out of the box</title>
      </info>

      <para>There are several reasons why the previous earsample application
      is directly runnable on a freshly installed JOnAS:</para>

      <itemizedlist>
        <listitem>
          <para>Tomcat servlet server is embedded in the distribution</para>
        </listitem>

        <listitem>
          <para>A deployment plan (<filename>ctxroot.xml</filename>)
          triggering the deployment of the web application
          <filename>jonas-ctxroot</filename> is pre-installed in <filename
          class="directory">$JONAS_ROOT/deploy </filename>directory. This
          explains why a web page is displayed when you type:
          <command>http://localhost:9000/</command></para>
        </listitem>

        <listitem>
          <para>The <filename>javaee5-earsample.ear</filename> file has been
          copied in <filename class="directory">$JONAS_BASE/deploy
          </filename>directory. This way, the application has automaticaly
          been deployed when <xi:include href="variables.xml"
          xpointer="appserver" /> starts.</para>
        </listitem>

        <listitem>
          <para>By using <emphasis role="bold">newjb</emphasis> tool JOnAS has
          been correctly configured and default values has been set in
          configuration files located under $JONAS_BASE/conf</para>

          <para>These files are accordingly set in order to:</para>

          <itemizedlist>
            <listitem>
              <para>force <xi:include href="variables.xml"
              xpointer="appserver" /> to use all the services needed for
              correct execution:</para>

              <itemizedlist>
                <listitem>
                  <para><emphasis role="bold">jtm</emphasis>: provides the
                  <classname>TransactionManager</classname> used in the back
                  stage (for EJB methods and SQL execution)</para>
                </listitem>

                <listitem>
                  <para><emphasis role="bold">db</emphasis>: provides an HSQL
                  Database for JPA entities</para>
                </listitem>

                <listitem>
                  <para><emphasis role="bold">security</emphasis>: provides
                  security functionalities</para>
                </listitem>

                <listitem>
                  <para><emphasis role="bold">resource</emphasis>: service for
                  using JMS and JDBC resource adaptors</para>
                </listitem>

                <listitem>
                  <para><emphasis role="bold">ejb3</emphasis>: there is a
                  session bean to be deployed in an ejb3 container</para>
                </listitem>

                <listitem>
                  <para><emphasis role="bold">web</emphasis>: there is a
                  servlet to be deployed in a servlet container</para>
                </listitem>

                <listitem>
                  <para><emphasis role="bold">ear</emphasis>: for deploying
                  the <filename>javaee5-earsample.ear</filename>
                  application</para>
                </listitem>

                <listitem>
                  <para><emphasis role="bold">jaxws</emphasis>: for deploying
                  JAX-WS 2.0 web services</para>
                </listitem>

                <listitem>
                  <para><emphasis role="bold">depmonitor</emphasis> that
                  deploys Java EE modules located in <filename
                  class="directory">$JONAS_BASE/deploy</filename>
                  directory</para>
                </listitem>
              </itemizedlist>

              <para><filename>jonas.properties</filename> is the configuration
              file</para>
            </listitem>

            <listitem>
              <para>set a default port (9000) for the connector HTTP (in
              <filename>$JONAS_BASE/conf/tomcat6-server.xml</filename>
              file)</para>
            </listitem>

            <listitem>
              <para>set a default port (1099) and a default protocol
              (<literal>jrmp</literal>) to be used by the registry (in
              <filename>$JONAS_BASE/conf/carol.properties</filename>
              file)</para>
            </listitem>

            <listitem>
              <para>a JMS resource adaptor correctly configured has been built
              and installed under $JONAS_BASE/deploy</para>
            </listitem>

            <listitem>
              <para>a JDBC resource adaptor for accessing HSQL Database has
              been built and installed under $JONAS_BASE/deploy</para>
            </listitem>
          </itemizedlist>
        </listitem>
      </itemizedlist>
    </section>

    <section xml:id="jonasadmin">
      <info>
        <title>First step in JOnAS administration</title>
      </info>

      <para>Back on the web page displayed previously, you can see the second
      line that says:</para>

      <screen>Go to the JOnAS administration web application.  Use the login/password jonas/jonas</screen>

      <para>This link allows you to run the <xi:include href="variables.xml"
      xpointer="appserver" /> administration tool <emphasis
      role="bold">jonasAdmin</emphasis>.</para>

      <para>After the authentication process is done
      (login=<token>jonas</token>,password=<token>jonas</token>) you have
      access to a page in which the left part shows the Management
      tree.</para>

      <para><informaltable>
          <tgroup cols="2">
            <tbody>
              <row>
                <entry><mediaobject>
                    <imageobject role="html">
                      <imagedata fileref="../../resources/images/admintree.gif"></imagedata>
                    </imageobject>

                    <imageobject role="fo">
                      <imagedata fileref="../../resources/images/admintree.gif"
                                 scale="75"></imagedata>
                    </imageobject>
                  </mediaobject></entry>

                <entry><para>From this tree it is possible
                to:</para><itemizedlist>
                    <listitem>
                      <para>get information on the management domain</para>
                    </listitem>

                    <listitem>
                      <para>get information about the JOnAS server (protocol,
                      JMX, registry, web container, JVM)</para>
                    </listitem>

                    <listitem>
                      <para>get monitoring information (threads,
                      memory)</para>
                    </listitem>

                    <listitem>
                      <para>get or set logging information</para>
                    </listitem>

                    <listitem>
                      <para>get information on existing web connectors or
                      create new ones</para>
                    </listitem>

                    <listitem>
                      <para>get information about JOnAS services</para>
                    </listitem>

                    <listitem>
                      <para>make deployment operations (<phrase
                      remap="action">deploy</phrase>/<phrase
                      remap="action">undeploy</phrase>/<phrase
                      remap="action">upload</phrase>/<phrase
                      remap="action">remove</phrase>) for <filename
                      class="extension">ear</filename>, <filename
                      class="extension">war</filename>, <filename
                      class="extension">ejbjar</filename> and <filename
                      class="extension">rar</filename> files</para>
                    </listitem>

                    <listitem>
                      <para>get configuration information, statistics, or
                      perform operations on resources (data sources)</para>
                    </listitem>

                    <listitem>
                      <para>get securtity configuration information or perform
                      security operations</para>
                    </listitem>

                    <listitem>
                      <para>get configuration information or perform
                      operations on JORAM, our JMS provider.</para>
                    </listitem>

                    <listitem>
                      <para>browse all the deployed MBeans in the
                      server</para>
                    </listitem>
                  </itemizedlist></entry>
              </row>
            </tbody>
          </tgroup>
        </informaltable><link
      xlink:href="http://wiki.jonas.objectweb.org/xwiki/bin/download/Main/Demos/clusterManagement.htm">Here
      </link>is a demonstration of cluster management features in jonasAdmin
      console.</para>
    </section>
  </chapter>

  <chapter xml:id="getting.started.learning">
    <info>
      <title>Learning JOnAS by examples</title>
    </info>

    <para><xi:include href="variables.xml" xpointer="j48ee" /> provides a
    complete example <emphasis role="bold">javaee5-earsample</emphasis> that
    shows the multitiered application model for enterprise applications that a
    Java EE platform must support.</para>

    <para>In this example you will find all the java EE components
    possibles:</para>

    <itemizedlist>
      <listitem>
        <para>Application clients</para>
      </listitem>

      <listitem>
        <para>Web components (servlets)</para>
      </listitem>

      <listitem>
        <para><trademark>Enterprise JavaBeans</trademark></para>
      </listitem>
    </itemizedlist>

    <para>It may be interesting for a user that wants to start developing a
    <xi:include href="variables.xml" xpointer="j2ee" /> application and run it
    in <xi:include href="variables.xml" xpointer="j48ee" /> to look at the
    sample in order to see the new Java EE 5 features.</para>

    <section xml:id="getting.started.earsample">
      <info>
        <title>javaee5-earsample example from a 10.000 foot view</title>
      </info>

      <para>The javaee5-earsample example is a quick-start Java EE application
      that shows usage of new Java EE 5 features, like JPA, EJB3 (Session and
      Message Driven Bean), annotations, JAAS security.</para>

      <para><xi:include href="variables.xml" xpointer="appserver" /> provides
      a little database, embedded in the server, namely HSQLDB. This database
      is helpful for running some examples that use JPA entity beans.</para>

      <note>
        <para>The HSQL database is not appropriate for real life
        applications.</para>
      </note>

      <section>
        <info>
          <title>Java EE Technologies in Use</title>
        </info>

        <para>This sections offers an overview of the different Java EE
        technologies involved in the javaee5-earsample EAR.</para>

        <section>
          <info>
            <title>JPA 1.0</title>
          </info>

          <para>JPA stands for Java Persistence API, that's a specification
          extracted from the EJB 3.0 core that addresses persistency problem.
          Basically, it allows POJOs to be persisted and queried to and from a
          JDBC database.</para>

          <para>Some JPA EntityManager Providers:</para>

          <itemizedlist>
            <listitem>
              <para><xi:include href="variables.xml"
              xpointer="Hibernate" />,</para>
            </listitem>

            <listitem>
              <para><xi:include href="variables.xml"
              xpointer="EclipseLink" />,</para>
            </listitem>

            <listitem>
              <para>etc ...</para>
            </listitem>
          </itemizedlist>
        </section>

        <section>
          <info>
            <title>EJB 3.0</title>
          </info>

          <para><acronym>EJB</acronym> 3.0 is the new <link
          xlink:href="http://java.sun.com/products/ejb/">Enterprise Java Beans
          specification</link> targeting ease of development
          (<acronym>EoD</acronym>), a feature that was lacking in the previous
          version (EJB 2.x). This specification makes heavy use of Java 5
          annotations (<classname>@Stateless</classname>,
          <classname>@Stateful</classname>,
          <classname>@MessageDriven</classname>, ...). One of the main
          advantages is the introduction of the concept of business method
          Interceptors.</para>

          <para>EJBs are packaged in an EjbJar (<filename
          class="extension">.jar</filename>).</para>

          <para><link xlink:href="http://www.easybeans.net">OW2
          EasyBeans</link> is the EJB 3.0 Container used in JOnAS 5.</para>
        </section>

        <section>
          <info>
            <title>JAAS</title>
          </info>

          <para><acronym>JAAS</acronym> is the authentication and
          authorization mechanism of Java EE that manages Principals and
          Roles.It is used in this sample to authenticate one of the
          application's client users.</para>
        </section>

        <section>
          <info>
            <title>JMS 1.1</title>
          </info>

          <para><acronym>JMS</acronym> is the standard for Messaging system
          (MOM) in Java. It is used to asynchronously (using JMS Destinations
          like Queues or Topics) perform calls to the application (usually
          using MessageDriven Beans).</para>

          <para><link xlink:href="http://joram.ow2.org" xlink:show="embed">OW2
          JORAM</link> is the JMS provider used in JOnAS 5.</para>
        </section>

        <section>
          <info>
            <title>Servlet 2.5</title>
          </info>

          <para>Servlets and <acronym>JSP</acronym>s compose the web front-end
          of a classical Java EE application. This is what is accessed when an
          HTTP URL (http://localhost:9000/javaee5-earsample for example) is
          called.</para>

          <para>Servlets/JSPs are packaged in a web application (<filename
          class="extension">.war</filename>).</para>
        </section>

        <section>
          <info>
            <title>Application Client</title>
          </info>

          <para>Application Clients are described in the Java EE specification
          as a way to package code for "heavy-weight" clients (not like web
          applications, usually known as "light-weight") of the application's
          business objects (EJBs, JMS Destinations, ...). Application Clients
          are top level Java EE modules so they benefit from uniform naming
          (<filename>java:comp/env</filename>).</para>

          <para>Application Clients are packaged in <filename
          class="extension">.jar</filename> files.</para>
        </section>

        <section>
          <info>
            <title>Enterprise Application</title>
          </info>

          <para><acronym>EAR</acronym>s do not contain any code but are used
          to package together all the modules composing the application
          (EjbJar + Web Applications + Resource Adapters + Application
          Clients).</para>
        </section>
      </section>

      <section>
        <info>
          <title>javaee5-earsample EAR Sample Architecture</title>
        </info>

        <para>In this section, the sample's architecture will be described,
        execution flow and interactions will be explained.</para>

        <para><figure>
            <info>
              <title>javaee5-earsample Sample Architecture</title>
            </info>

            <mediaobject>
              <imageobject role="html">
                <imagedata fileref="../../resources/images/earsample-architecture.png"></imagedata>
              </imageobject>

              <imageobject role="fo">
                <imagedata fileref="../../resources/images/earsample-architecture.png"
                           scale="35"></imagedata>
              </imageobject>
            </mediaobject>
          </figure>This application provides the following features:</para>

        <itemizedlist>
          <listitem>
            <para>2 separated business interfaces, one allowing write access
            and the other one read only access.</para>
          </listitem>

          <listitem>
            <para>It can receive Book creation orders asynchronously from a
            JMS Queue.</para>
          </listitem>

          <listitem>
            <para>A Web interface allowing to see the Books and Authors, with
            a special section authorized to add new Authors.</para>
          </listitem>
        </itemizedlist>

        <para>The database (<acronym>DB</acronym>) is provided by a JOnAS
        service called <emphasis>db</emphasis> that launches an Hypersonic SQL
        server instance. A JDBC Resource Adapter is provided by JOnAS to allow
        applications to connect to this DB.</para>

        <para>Upon the data tier are located the business data objects. They
        are implemented using the <acronym>JPA</acronym> Entity model (with
        annotations).</para>

        <para>The model represented in this application is super easy:</para>

        <itemizedlist>
          <listitem>
            <para><emphasis>Author</emphasis>: This is the author of a(some)
            Book(s).</para>
          </listitem>

          <listitem>
            <para><emphasis>Book</emphasis>: This Entity represents a book
            written by an Author</para>
          </listitem>

          <listitem>
            <para>An Author can write many Books</para>
          </listitem>

          <listitem>
            <para>A Book is written by only 1 Author</para>
          </listitem>
        </itemizedlist>

        <para>Two EJB3 <classname>@Stateless</classname> beans are constructed
        on top of the business data objects (entities): Reader and
        Writer.</para>

        <para>The <emphasis>Reader</emphasis> bean provides read only methods
        (<methodname>findAuthor</methodname>,
        <methodname>findBook</methodname>, ...) that never change the backed
        data. On the contrary, the <emphasis>Writer</emphasis> bean provides
        write methods (<methodname>addAuthor</methodname>, ...) and thus has
        to be secured.</para>

        <para>On top of theses 2 "low level" EJBs, other, more business
        oriented, EJBs are provided: <emphasis>Mailer</emphasis>,
        <emphasis>Initializer</emphasis>, an <acronym>MDB</acronym>.</para>

        <para>The <emphasis>Initializer</emphasis> bean is a "hidden"
        <acronym>EJB</acronym>, whose role is to initialize, if needed, a
        first set of <acronym>JPA</acronym> Entitites (some well known
        Authors, and some of their Books). This bean is used from almost all
        the clients to ensure that there is something to show to the
        user.</para>

        <para>The <emphasis>Mailer</emphasis> bean can be used by anyone (it's
        does not use security features) and will only access the
        <emphasis>Reader</emphasis> bean to fill up a mail message that will
        be sent to a given mail address.</para>

        <para>The <acronym>MDB</acronym> (MessageDriven Bean) simply creates a
        new Book for each new <emphasis>JMS message</emphasis> received from
        the <acronym>JMS</acronym> Queue.</para>

        <para>The following business oriented functions are, in turn, used by
        the end-user clients:</para>

        <itemizedlist>
          <listitem>
            <para>Web Application offering a web interface (HTTP/HTML)</para>
          </listitem>

          <listitem>
            <para>Java EE 5 Application Clients (runs from the command
            line)</para>
          </listitem>
        </itemizedlist>

        <para>Concerning the web application, it offers 3 pages:</para>

        <itemizedlist>
          <listitem>
            <para>An index page showing basic instructions on how to use the
            web application</para>
          </listitem>

          <listitem>
            <para>An open page (meaning not secured) displaying Books and
            Authors</para>
          </listitem>

          <listitem>
            <para>A secured page (needs user authentication) for new Authors
            addition</para>
          </listitem>
        </itemizedlist>

        <para>There are also multiple standard application clients
        (<acronym>AC</acronym> for short) showing different ways to use the
        application:</para>

        <itemizedlist>
          <listitem>
            <para>Not Secured AC: this client uses the Mailer and Reader bean.
            Using the Reader it displays the Authors and Books, and using the
            Mailer bean, it sends a mail with an equivalent content.</para>
          </listitem>

          <listitem>
            <para>JMS AC: this client mainly interacts with a dedicated JMS
            Queue to sends Book creation orders, then it waits some time and
            uses the Reader bean to see if the new Books were
            persisted.</para>
          </listitem>

          <listitem>
            <para>Secured AC: this clients shows usage of JAAS authentication.
            It uses the Writer bean, which requires a user with the
            "earsample" role in order to insert new Authors and Books.</para>
          </listitem>
        </itemizedlist>
      </section>
    </section>

    <section>
      <info>
        <title>javaee5-earsample example detailed</title>
      </info>

      <para>This section will focus on multiple aspects of the EAR sample:
      some basic server configuration (strictly limited to the elements in use
      for the sample, a more complete description is available in the
      configuration guide), simple programming guide showing JPA, EJB, JNDI
      usage...</para>

      <section>
        <info>
          <title>JOnAS Server Configuration</title>
        </info>

        <para>Here we focus on JOnAS configuration needed by javaee5-earsample
        examples and obtained after having run the newjb command .</para>

        <section>
          <info>
            <title>Required Services</title>
          </info>

          <para>The javaee5-earsample needs the following JOnAS services to be
          activated for a flawless execution:</para>

          <variablelist>
            <varlistentry>
              <term>jtm</term>

              <listitem>
                <para>Provides the transactions support</para>
              </listitem>
            </varlistentry>

            <varlistentry>
              <term>db</term>

              <listitem>
                <para>Provides the HSQL Database</para>
              </listitem>
            </varlistentry>

            <varlistentry>
              <term>mail</term>

              <listitem>
                <para>Provides the mail sending support</para>
              </listitem>
            </varlistentry>

            <varlistentry>
              <term>security</term>

              <listitem>
                <para>Provides the security provider</para>
              </listitem>
            </varlistentry>

            <varlistentry>
              <term>resource</term>

              <listitem>
                <para>Provides the connectivity to the database or the JMS
                provider via resource adapters</para>
              </listitem>
            </varlistentry>

            <varlistentry>
              <term>ejb3</term>

              <listitem>
                <para>Provides the EJB 3.0 Container runtime</para>
              </listitem>
            </varlistentry>

            <varlistentry>
              <term>web</term>

              <listitem>
                <para>Provides the Web container runtime for web applications
                (Servlets/JSP)</para>
              </listitem>
            </varlistentry>

            <varlistentry>
              <term>ear</term>

              <listitem>
                <para>Provides the Enterprise ARchive (<filename
                class="extension">EAR</filename>) container</para>
              </listitem>
            </varlistentry>
          </variablelist>
        </section>

        <section>
          <info>
            <title>DataSource</title>
          </info>

          <para>Access to the dataSource is provided by the resource service
          .</para>

          <para>A resource adapter has been created at the JONAS_BASE creation
          time via newjb tool from the properties found in
          $JONAS_ROOT/build-jb.properties file:</para>

          <para><screen>
rajdbc.hsql.user=jonas
rajdbc.hsql.password=jonas
rajdbc.hsql.url=jdbc:hsqldb:hsql://localhost:9001/db_jonas  <co
                xml:id="jdbc.url" />
rajdbc.hsql.drivername=org.hsqldb.jdbcDriver  <co xml:id="jdbc.driver" />
rajdbc.hsql.jndiname=jdbc_1   <co xml:id="jndi.name" />
rajdbc.hsql.jdbcdriverjarfile=none
rajdbc.hsql.mappername=rdb.hsql
</screen><calloutlist>
              <callout arearefs="jdbc.url">
                <para><acronym>JDBC</acronym> URL of the connection. This is
                one is specific to HSQL and corresponds to the HSQL port and
                DB name provided in the default <emphasis>db</emphasis>
                service configuration.</para>
              </callout>

              <callout arearefs="jdbc.driver">
                <para><acronym>JDBC</acronym> driver fully qualified class
                name (including package name)</para>
              </callout>

              <callout arearefs="jndi.name">
                <para><acronym>JNDI</acronym> name of the
                <classname>DataSource</classname>
                (<classname>DataSource</classname> will be available under
                that name in the <acronym>JNDI</acronym> registry)</para>
              </callout>
            </calloutlist></para>
        </section>
      </section>

      <section>
        <info>
          <title>Data Tier: JPA Entity Beans</title>
        </info>

        <figure>
          <info>
            <title>Author and Book JPA Model</title>
          </info>

          <mediaobject>
            <imageobject role="html">
              <imagedata align="center"
                         fileref="../../resources/images/earsample-jpa-model.png"></imagedata>
            </imageobject>

            <imageobject role="fo">
              <imagedata align="center"
                         fileref="../../resources/images/earsample-jpa-model.png"
                         scale="50"></imagedata>
            </imageobject>
          </mediaobject>
        </figure>

        <para>This figure represents the model of the application. it is
        composed of 2 <acronym>JPA</acronym> Entities:
        <classname>Author</classname> and <classname>Book</classname>. Each
        one has an <literal>id</literal> attribute and are qualified by a
        <literal>name</literal> and a <literal>title</literal> respectively.
        Theses entities have a relationship between them: an Author instance
        knows all the Books he wrote (Author.getBooks()) and a Book knows who
        wrote it (Book.getAuthor()).</para>

        <section>
          <title>Author Bean</title>

          <para>A <acronym>JPA</acronym> Entity bean is a simple class
          considered as a <acronym>POJO</acronym> (Plain Old Java Object).
          That means that the class has a public default constructor (no
          arguments). Moreover, for each attribute/field of the class, a
          getter and a setter method (<methodname>getXYZ()</methodname> and
          <methodname>setXYZ(...)</methodname>) has to be provided.</para>

          <para>A <acronym>JPA</acronym> Entity bean will be annotated with
          the <classname>@Entity</classname> annotation.</para>

          <para>The primary key is defined through an
          <classname>@Id</classname> annotation. In the earsample use case,
          this key has to be auto-generated. Finally, the
          <methodname>getId()</methodname> method should look like
          this:</para>

          <para><screen>    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    public long getId() {
        return this.id;
    }
</screen>The Author bean is in relation with the bean Book, because an Author
          can have many Books (a OneToMany relationship).</para>

          <para>The relation is also defined through an annotation:</para>

          <para><screen>    @OneToMany(mappedBy="author", fetch=FetchType.EAGER, cascade=CascadeType.ALL)
    public Collection&lt;Book&gt; getBooks() {
        return books;
    }
</screen>This relation is of One-To-Many type. The link will be done with the
          entity bean Book on the <literal>author</literal> attribute (owner
          of the relation).</para>

          <para>The fetching type is <literal>EAGER</literal> (it means that
          when the Author instance is constructed, all the linked books are
          fetched). Another choice could have been to use
          <literal>LAZY</literal> fetching (meaning that the Books will only
          be fetched when the getBooks() method will be called). In the
          earsample use case, the entity beans will be accessed from a client
          in another Java VM (detached mode), so, to reduce latencies caused
          by network exchanges, it was decided to not use
          <literal>LAZY</literal> fetching. Because the Author and Books
          classes are usable from the remote JVM, they must implements the
          Serializable interface.</para>

          <para>Finally, the cascading mode is set to <literal>ALL</literal>:
          when the Author bean is be persisted, all the Books related to the
          Author bean will be persisted too.<programlisting>package org.ow2.jonas.examples.ear.entity;

import static org.ow2.jonas.examples.ear.entity.Author.QN.ALL_AUTHORS;
import static org.ow2.jonas.examples.ear.entity.Author.QN.FIND_AUTHOR;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;

/**
 * Author of a book.
 * @author Florent Benoit
 */
<emphasis>@Entity
@NamedQueries({@NamedQuery(name=ALL_AUTHORS, query="select o FROM Author o"),
               @NamedQuery(name=FIND_AUTHOR, query="select o FROM Author o WHERE name = :name")})
</emphasis>public class Author <emphasis>implements Serializable</emphasis> {
    /**
     * Store Query names.
     */
    public static interface QN {
        /**
         * Search all authors.
         */
        String ALL_AUTHORS = "Author.allAuthors";

        /**
         * Search a named author.
         */
        String FIND_AUTHOR = "Author.findAuthor";
    }

    /**
     * Serial Version UID.
     */
    private static final long serialVersionUID = 0L;

    /**
     * Primary key (will be auto generated).
     */
    private long id;

    /**
     * Name of the author.
     */
    private String name = null;

    /**
     * List of books written by the author.
     */
    private Collection&lt;Book&gt; books;

<emphasis>    /**
     * Default constructor.
     */
    public Author() {
        books = new ArrayList&lt;Book&gt;();
    }
</emphasis>
    /**
     * Constructor with a given author name.
     * @param name - the name of the author
     */
    public Author(final String name) {
        this();
        setName(name);
    }

    /**
     * Relation ship (do not using lazy mode).
     * @return books written by this author
     */
<emphasis>    @OneToMany(mappedBy="author", fetch=FetchType.EAGER, cascade=CascadeType.ALL)
</emphasis>    public Collection&lt;Book&gt; getBooks() {
        return books;
    }

    /**
     * Add a book with a given title.
     * @param title - the title of the book
     */
    public void addBook(final String title) {
        Book livre = new Book();
        livre.setTitle(title);
        livre.setAuthor(this);
        getBooks().add(livre);
    }

    /**
     * Sets the collection of books written by this author.
     * @param books the list of the books
     */
    public void setBooks(final Collection&lt;Book&gt; books) {
        this.books = books;
    }

    /**
     * @return name of the author
     */
    public String getName() {
        return name;
    }

    /**
     * Sets the name of the author.
     * @param name - the name of this author
     */
    public void setName(final String name) {
        this.name = name;
    }

    /**
     * @return an id for this object (incremented automatically)
     */
<emphasis>    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
</emphasis>    public long getId() {
        return this.id;
    }

    /**
     * Sets the id of this author object.
     * @param id the given id of this author
     */
    public void setId(final long id) {
        this.id = id;
    }


    /**
     * @return String representation of this entity object.
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder(this.getClass().getName());
        sb.append("[id=");
        sb.append(getId());
        sb.append(", name=");
        sb.append(getName());
        sb.append("]");
        return sb.toString();
    }
}
</programlisting></para>

          <para><note>
              <para>Two <literal>EJB-QL</literal> queries have been defined in
              the bean's class.They will be used to retrieve all the authors
              and an author with a given name respectively.</para>
            </note></para>
        </section>

        <section>
          <title>Book Bean</title>

          <para>The Book bean is also a <acronym>JPA</acronym> entity bean.
          There is a relationship with the Author bean, one book being related
          to only one Author: Many-To-One relationship.</para>

          <para>The @JoinColumn annotation defines the column of the primary
          key to be used for the association between 2 entity beans:</para>

          <para><screen>    @ManyToOne
    @JoinColumn(name="Author_id")
    public Author getAuthor() {
        return author;
    }
</screen>Here is the complete Book class:<programlisting>package org.ow2.jonas.examples.ear.entity;

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;

/**
 * Define a book.
 * @author Florent Benoit
 */
@Entity
@NamedQueries({@NamedQuery(name=Book.QN.ALL_BOOKS, query="select o FROM Book o"),
               @NamedQuery(name=Book.QN.FIND_BOOK, query="select o FROM Book o WHERE name = :name")
})
public class Book implements Serializable {

    /**
     * Defines Query names.
     */
    public static interface QN {
        /**
         * Search all books.
         */
        String ALL_BOOKS = "Book.allBooks";

        /**
         * Search a book.
         */
        String FIND_BOOK = "Book.findBook";
    }

    /**
     * Serial Version UID.
     */
    private static final long serialVersionUID = 0L;

    /**
     * Primary key.
     */
    private long id;

    /**
     * Author's book.
     */
    private Author author;

    /**
     * title of the book.
     */
    private String title;

    /**
     * Default constructor.
     */
    public Book() {

    }

    /**
     * Constructor. Build a new Book with the given title and written by the
     * given author.
     * @param title the given title
     * @param author the given author.
     */
    public Book(final String title, final Author author) {
        setTitle(title);
        setAuthor(author);
    }

    /**
     * @return the Author of this Book.
     */
    @ManyToOne
    @JoinColumn(name="Author_id")
    public Author getAuthor() {
        return author;
    }

    /**
     * Sets the author of this book.
     * @param author the given author.
     */
    public void setAuthor(final Author author) {
        this.author = author;
    }

    /**
     * @return the title of this book.
     */
    public String getTitle() {
        return title;
    }

    /**
     * Set the title of the book.
     * @param title - the title of the book
     */
    public void setTitle(final String title) {
        this.title = title;
    }

    /**
     * @return an id for this object (incremented automatically)
     */
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    public long getId() {
        return this.id;
    }

    /**
     * Sets the id of this author object.
     * @param id the given id of this author
     */
    public void setId(final long id) {
        this.id = id;
    }

    /**
     * @return String representation of this entity object.
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder(this.getClass().getName());
        sb.append("[id=");
        sb.append(getId());
        sb.append(", title=");
        sb.append(getTitle());
        sb.append("]");
        return sb.toString();
    }
}
</programlisting></para>
        </section>

        <section>
          <title>Persistence File</title>

          <para>It is required to have a persistency file
          <filename>META-INF/persistence.xml</filename> to describe useful
          information. For example, the <acronym>JNDI</acronym> name of the
          <interfacename>DataSource</interfacename> to be used for database
          persistency.</para>

          <para><example>
              <title>JPA Entity: META-INF/persistence.xml</title>

              <para><screen>&lt;persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0"&gt;
&lt;persistence-unit name="entity" transaction-type="JTA"&gt;
   &lt;provider&gt;&lt;/provider&gt;
   <emphasis>&lt;jta-data-source&gt;jdbc_1&lt;/jta-data-source&gt;</emphasis>
   &lt;properties&gt;
      &lt;property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect" /&gt;
      &lt;property name="hibernate.hbm2ddl.auto" value="create-drop"/&gt;

      &lt;property name="eclipselink.ddl-generation" value="drop-and-create-tables"/&gt;
      &lt;property name="eclipselink.ddl-generation.output-mode" value="database"/&gt;
      &lt;property name="eclipselink.target-database" value="HSQL"/&gt;

      &lt;property name="toplink.target-database" value="HSQL"/&gt;
      &lt;property name="toplink.ddl-generation" value="drop-and-create-tables"/&gt;
      &lt;property name="toplink.ddl-generation.output-mode" value="database"/&gt;

      &lt;property name="openjpa.jdbc.DBDictionary" value="hsql"/&gt;
      &lt;property name="openjpa.jdbc.SynchronizeMappings" value="buildSchema(ForeignKeys=true)"/&gt;
   &lt;/properties&gt;
&lt;/persistence-unit&gt;
&lt;/persistence&gt;
</screen></para>
            </example></para>
        </section>
      </section>

      <section>
        <info>
          <title>Business Tier: EJB3 Beans</title>
        </info>

        <para>This section will decribe the business parts of the application.
        Session beans provide synchronous RPC interfaces and the MessageDriven
        bean provides the asynchronous interface.</para>

        <section>
          <title>Session Beans</title>

          <para>The Session beans have been separated into two logical parts:
          Writer and Reader beans provide the basic operations (read/write) on
          the entities, while Mailer and Initializer are using the previous
          ones to perform more advanced operations.</para>

          <section>
            <title>Reader Bean</title>

            <para>The Reader Bean is a Stateless Session Bean that provides
            both a Remote and a Local business interface. It is responsible
            for all the read-like operations the application can do on the JPA
            entities. The <methodname>listAllXYZ</methodname> and
            <methodname>findXYZ</methodname> methods return the JPA entity
            beans.</para>

            <example>
              <title>Stateless Session Bean: Reader Business Interface</title>

              <para><screen>package org.ow2.jonas.examples.ear.reader;

import java.util.List;

import org.ow2.jonas.examples.ear.entity.Author;
import org.ow2.jonas.examples.ear.entity.Book;

/**
 * The {@link Reader} business interface is an un-restricted
 * read only view of the entities.
 * @author Guillaume Sauthier
 */
public interface Reader {

    /**
     * @return the list of all the persisted {@link Author}s.
     */
    List&lt;Author&gt; listAllAuthors();

    /**
     * @return the list of all the persisted {@link Book}s.
     */
    List&lt;Book&gt; listAllBooks();

    /**
     * Find a given {@link Author} using it's name as a key.
     * @param name {@link Author}'s name.
     * @return the first {@link Author} that matches the given name.
     */
    Author findAuthor(final String name);

    /**
     * Find a given {@link Book} using it's name as a key.
     * @param name {@link Book}'s name.
     * @return the first {@link Book} that matches the given name.
     */
    Book findBook(final String name);
}
</screen></para>
            </example>

            <para>This bean uses an
            <interfacename>EntityManager</interfacename> (injected through the
            <classname>@PersistenceContext</classname> annotation).</para>

            <para><screen>    /**
     * Entity manager used by this bean.
     */
    @PersistenceContext
    private EntityManager entityManager = null;
</screen>The EntityManager is also used to perform EJB-QL queries (they have
            been defined with the @NamedQuery annotation on top of the JPA
            classes).<screen>    /**
     * @returns the list of all the persisted {@link Author}s.
     */
    public List&lt;Author&gt; listAllAuthors() {
        return entityManager.createNamedQuery(ALL_AUTHORS).getResultList();
    }
</screen></para>

            <para>Here is the code of the Reader EJB:<programlisting>package org.ow2.jonas.examples.ear.reader;

import static org.ow2.jonas.examples.ear.entity.Author.QN.ALL_AUTHORS;
import static org.ow2.jonas.examples.ear.entity.Author.QN.FIND_AUTHOR;
import static org.ow2.jonas.examples.ear.entity.Book.QN.ALL_BOOKS;
import static org.ow2.jonas.examples.ear.entity.Book.QN.FIND_BOOK;

import java.util.List;

import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.ow2.jonas.examples.ear.entity.Author;
import org.ow2.jonas.examples.ear.entity.Book;

/**
 *The {@link ReaderBean} EJB is an unrestricted, read-only, Stateless Bean.
 * @author Guillaume Sauthier
 */
@Stateless
@Local(LocalReader.class)
@Remote(RemoteReader.class)
public class ReaderBean implements LocalReader, RemoteReader {

    /**
     * Entity manager used by this bean.
     */
    @PersistenceContext
    private EntityManager entityManager = null;

    /**
     * Find a given {@link Author} using it's name as a key.
     * @param name {@link Author}'s name.
     * @return the first {@link Author} that matches the given name.
     */
    @SuppressWarnings("unchecked")
    public Author findAuthor(final String name) {
        Query query = entityManager.createNamedQuery(FIND_AUTHOR);
        query.setParameter("name", name);
        List&lt;Author&gt; authors = query.getResultList();
        if (authors != null &amp;&amp; authors.size() &gt; 0) {
            return authors.get(0);
        }
        return null;
    }

    /**
     * Find a given {@link Book} using it's name as a key.
     * @param name {@link Book}'s name.
     * @return the first {@link Book} that matches the given name.
     */
    @SuppressWarnings("unchecked")
    public Book findBook(final String name) {
        Query query = entityManager.createNamedQuery(FIND_BOOK);
        query.setParameter("name", name);
        List&lt;Book&gt; books = query.getResultList();
        if (books != null &amp;&amp; books.size() &gt; 0) {
            return books.get(0);
        }
        return null;
    }

    /**
     * @return the list of all the persisted {@link Author}s.
     */
    @SuppressWarnings("unchecked")
    public List&lt;Author&gt; listAllAuthors() {
        return entityManager.createNamedQuery(ALL_AUTHORS).getResultList();
    }

    /**
     * @return the list of all the persisted {@link Book}s.
     */
    @SuppressWarnings("unchecked")
    public List&lt;Book&gt; listAllBooks() {
        return entityManager.createNamedQuery(ALL_BOOKS).getResultList();
    }

}
</programlisting></para>
          </section>

          <section>
            <title>Writer Bean</title>

            <para>The Writer Bean is also a Stateless Session Bean, with a
            Remote and a Local business interface. This bean provides
            write-like operations (that modify the database content). It is
            also secured to allow access only to a specific role.</para>

            <para><example>
                <title>Stateless Session Bean: Writer business
                Interface</title>

                <para><programlisting>package org.ow2.jonas.examples.ear.writer;

import org.ow2.jonas.examples.ear.entity.Author;
import org.ow2.jonas.examples.ear.entity.Book;

/**
 * Remote interface for the bean Writer.
 * @author JOnAS team
 */
public interface Writer {

    /**
     * Persists a new {@link Author}.
     * @param author {@link Author} to add.
     */
    void addAuthor(final Author author);

    /**
     * Persists a new {@link Book}.
     * @param book {@link Book} to add.
     */
    void addBook(final Book book);

    /**
     * Cascade remove an {@link Author}.
     * @param author {@link Author} to be removed.
     */
    void removeAuthor(final Author author);

    /**
     * Cascade remove a {@link Book}.
     * @param book {@link Book} to be removed.
     */
    void removeBook(final Book book);
}
</programlisting></para>
              </example>Through that interface, clients will be able to add
            new Authors and Books, but will also be able to remove
            them.</para>

            <para>This bean uses (like the Reader) an
            <interfacename>EntityManager</interfacename> (injected through the
            <classname>@PersistenceContext</classname> annotation).</para>

            <para><screen>    /**
     * Entity manager used by this bean.
     */
    @PersistenceContext
    private EntityManager entityManager = null;
</screen>The EntityManager will be used to persists and destroy JPA entity
            instances.<screen>    /**
     * Persists a new {@link Book}.
     * @param book {@link Book} to add.
     */
    public void addBook(final Book book) {
        entityManager.persist(book);
    }

    /**
     * Cascade remove a {@link Book}.
     * @param book {@link Book} to be removed.
     */
    public void removeBook(final Book book) {
        entityManager.remove(book);
    }
</screen></para>

            <para>Security for the Writer bean is provided in a declarative
            way: the class is annotated with @DeclareRoles and
            @RolesAllowed.</para>

            <para><itemizedlist>
                <listitem>
                  <para>@DeclareRoles declares an array of role names that
                  will be used later in the bean</para>
                </listitem>

                <listitem>
                  <para>@RolesAllowed, when placed on the class (instead of a
                  method) specifies the default set of roles that are allowed
                  to call this bean's methods</para>
                </listitem>
              </itemizedlist>In this sample, only the
            <literal>earsample</literal> role is authorized to actually use
            the Writer bean.</para>

            <para>Here is the code of the Writer EJB:<programlisting>package org.ow2.jonas.examples.ear.writer;

import javax.annotation.security.DeclareRoles;
import javax.annotation.security.RolesAllowed;
import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.ow2.jonas.examples.ear.entity.Author;
import org.ow2.jonas.examples.ear.entity.Book;

/**
 * This is an example of Session Bean, stateless, secured, available
 * with a Local and a Remote interface (with the same methods).
 * @author JOnAS team
 */
<emphasis>@Stateless
@Remote(RemoteWriter.class)
@Local(LocalWriter.class)
@DeclareRoles("earsample")
@RolesAllowed("earsample")
</emphasis>public class WriterBean implements LocalWriter, RemoteWriter {

    /**
     * Entity manager used by this bean.
     */
<emphasis>    @PersistenceContext
</emphasis>    private EntityManager entityManager = null;

    /**
     * Persists a new {@link Author}.
     * @param author {@link Author} to add.
     */
    public void addAuthor(final Author author) {
        entityManager.persist(author);
    }

    /**
     * Persists a new {@link Book}.
     * @param book {@link Book} to add.
     */
    public void addBook(final Book book) {
        entityManager.persist(book);
    }

    /**
     * Cascade remove an {@link Author}.
     * @param author {@link Author} to be removed.
     */
    public void removeAuthor(final Author author) {
        entityManager.remove(author);
    }

    /**
     * Cascade remove a {@link Book}.
     * @param book {@link Book} to be removed.
     */
    public void removeBook(final Book book) {
        entityManager.remove(book);
    }

}
</programlisting></para>
          </section>

          <section>
            <title>Mailer Bean</title>

            <para>The Mailer bean provides a business interface supporting
            status e-mail sending.</para>

            <para><example>
                <title>Stateless Session Bean: Mailer Business
                Interface</title>

                <para><screen>package org.ow2.jonas.examples.ear.mail;

/**
 * The {@link Mailer} business interface is used to send a status
 * mail, with all the {@link org.ow2.jonas.examples.ear.entity.Author}s
 * and {@link org.ow2.jonas.examples.ear.entity.Book}s in the library.
 * @author Guillaume Sauthier
 */
public interface Mailer {

    /**
     * Send a mail to the given mail address.
     * @param address target mail address (must be of the form: xyz@abc.z)
     */
    void sendStatusMail(final String address);
}
</screen></para>
              </example>This bean only provides a Remote interface. It is
            binded in the JNDI under the name specified in the mappedName
            attribute of the @Stateless annotation.</para>

            <para><screen>@Stateless(mappedName="myMailerBean")
@Remote(Mailer.class)
public class MailerBean implements Mailer {
</screen></para>

            <para>The Mailer needs some other components to help it to execute
            it's job:</para>

            <para><itemizedlist>
                <listitem>
                  <para>A mail Session and a MimePartDataSource that will be
                  used to create and send the e-mail</para>
                </listitem>

                <listitem>
                  <para>A reference to the Reader bean</para>
                </listitem>
              </itemizedlist>The mail Session and the MimePartDataSource are
            acquired though injection, using the @Resource annotation.</para>

            <para><screen>    /**
     * Mail Session used to send the Mail.
     */
    @Resource(mappedName="mailSession_1")
    private Session mailSession;

    /**
     * Template for the message's content.
     */
    @Resource(mappedName="mailMimePartDS_1")
    private MimePartDataSource mimePartDatasource;
</screen>The mappedName attribute of the @Resource specifies the JNDI name to
            be used when looking up theses components in the JNDI
            registry.</para>

            <para>The reference to the Reader bean is injected with the help
            of the @EJB annotation. Notice that the annotation did not provide
            any JNDI or mapped name value.</para>

            <para><screen>    /**
     * {@link LocalReader} EJB (Local interface).
     */
    @EJB
    private LocalReader reader;
</screen>Here is the complete code of the Mailer bean:<programlisting>package org.ow2.jonas.examples.ear.mail;

import java.util.Collection;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessageContext;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimePartDataSource;

import org.ow2.jonas.examples.ear.entity.Author;
import org.ow2.jonas.examples.ear.entity.Book;
import org.ow2.jonas.examples.ear.reader.LocalReader;

/**
 * @author Guillaume Sauthier
 */
@Stateless(mappedName="myMailerBean")
@Remote(Mailer.class)
public class MailerBean implements Mailer {

    /**
     * Mail Session used to send the Mail.
     */
    @Resource(mappedName="mailSession_1")
    private Session mailSession;

    /**
     * Template for the message's content.
     */
    @Resource(mappedName="mailMimePartDS_1")
    private MimePartDataSource mimePartDatasource;

    /**
     * {@link LocalReader} EJB (Local interface).
     */
    @EJB
    private LocalReader reader;

    /**
     * Send a mail to the given mail address.
     * @param address target mail address (must be of the form: xyz@abc.z)
     * @see org.ow2.jonas.examples.ear.mail.Mailer#sendStatusMail(java.lang.String)
     */
    public void sendStatusMail(final String address) {

        Address mailAddress = null;
        try {
            mailAddress = new InternetAddress(address);
        } catch (AddressException e) {
            System.err.println("Invalid mail address: " + e.getMessage());
            e.printStackTrace();
            return;
        }

        MessageContext context = mimePartDatasource.getMessageContext();
        Message message = context.getMessage();
        try {
            message.setContent(getContent(), "text/plain");
        } catch (MessagingException e) {
            System.err.println("Cannot set message content:" + e.getMessage());
            e.printStackTrace(System.err);
            return;
        }

        Transport transport = null;
        try {
            transport = mailSession.getTransport(mailAddress);
        } catch (NoSuchProviderException e) {
            System.err.println("No provider found for @:" + address);
            e.printStackTrace(System.err);
            return;
        }
        try {
            transport.connect();
            transport.sendMessage(message, new Address[] {mailAddress});
            transport.close();
        } catch (MessagingException e) {
            System.err.println("Cannot send message:" + e.getMessage());
            e.printStackTrace(System.err);
            return;
        }

        System.out.println("Mail successfully sent to: " + address);
    }

    /**
     * Generate the mail's content.
     * @return the mail message content.
     */
    private String getContent() {

        StringBuilder sb = new StringBuilder();

        // Print Header
        sb.append("---------------------------------------------------\n");
        sb.append(" OW2 JOnAS EAR Sample Mailer Bean.\n");
        sb.append("---------------------------------------------------\n");
        sb.append("Generated the " + new Date() + "\n");
        sb.append("\n");

        // Print the Authors
        List&lt;Author&gt; authors = reader.listAllAuthors();
        sb.append("List of all registered Authors (" + authors.size() + ") and their Books:\n");
        for (Author author : authors) {
            sb.append("  * " + author.getName() + " [" + author.getId() + "]\n");
            Collection&lt;Book&gt; books = author.getBooks();
            for (Book book : books) {
                sb.append("    - " + book.getTitle() + "[" + book.getId() + "]\n");
            }
        }

        // Print the Books
        sb.append("\n");
        sb.append("List of all registered Books:\n");
        List&lt;Book&gt; books = reader.listAllBooks();
        for (Book book : books) {
            sb.append("  * " + book.getTitle() + "[" + book.getAuthor().getName() + "]\n");
        }

        // Print the footer
        sb.append("\n");
        sb.append("Enjoy your new JOnAS !\n");
        sb.append("\n");
        sb.append("       -- JOnAS Team\n");

        return sb.toString();
    }

}
</programlisting></para>
          </section>

          <section>
            <title>Initializer Bean</title>

            <para>The Initializer bean is a kind of hidden bean: it does not
            provide operations that should be usable from the clients.</para>

            <para>The purpose of this bean is to ensure that the JPA model is
            initialized with some default values. Subsequent calls to the JPA
            model will then always show JPA entities.</para>

            <para>Since this session bean uses the Writer bean (required,
            because it writes values to the database), it needs to declare
            security.</para>

            <para>Because this bean can be used by any client (secured or
            not), and it uses a secured bean, it will need to have to be
            executed under a given role. This role name is specified with the
            @RunAs annotation:</para>

            <para><screen>@RunAs("earsample")
public class InitializerBean implements Initializer {
</screen>Here is the complete code of the bean:</para>

            <para><programlisting>package org.ow2.jonas.examples.ear.init;

import javax.annotation.security.RunAs;
import javax.ejb.EJB;
import javax.ejb.Remote;
import javax.ejb.Stateless;

import org.ow2.jonas.examples.ear.entity.Author;
import org.ow2.jonas.examples.ear.entity.Book;
import org.ow2.jonas.examples.ear.reader.LocalReader;
import org.ow2.jonas.examples.ear.writer.LocalWriter;

/**
 * The {@link InitializerBean} EJB is here to initialize only once
 * the Database/Entities. It simply checks if there is some {@link Author}s
 * already persisted; if none are found, we will inject defaults values.
 * @author Guillaume Sauthier
 */
@Stateless(mappedName="myInitializerBean")
@Remote(Initializer.class)
@RunAs("earsample")
public class InitializerBean implements Initializer {

    /**
     * Injected reference to the {@link org.ow2.jonas.examples.ear.writer.Writer} EJB.
     */
    @EJB
    private LocalWriter writer;

    /**
     * Injected reference to the {@link org.ow2.jonas.examples.ear.reader.Reader} EJB.
     */
    @EJB
    private LocalReader reader;

    /**
     * Initialize the minimal set of entities needed by the sample.
     * @see org.ow2.jonas.examples.ear.init.Initializer#initializeEntities()
     */
    public void initializeEntities() {

        if (reader.findAuthor("Honore de Balzac") == null) {
            // Balzac was not persited, add it now.
            Author balzac = new Author("Honore de Balzac");
            Book pereGloriot = new Book("Le Pere Goriot", balzac);
            balzac.getBooks().add(pereGloriot);
            Book lesChouans = new Book("Les Chouans", balzac);
            balzac.getBooks().add(lesChouans);

            // Persists the Author and all of his books
            writer.addAuthor(balzac);
        }

        if (reader.findAuthor("Victor Hugo") == null) {
            // Hugo was not persited, add it now.
            Author hugo = new Author("Victor Hugo");
            hugo.addBook("Les Miserables");
            hugo.addBook("Notre-Dame de Paris");

            // Store
            writer.addAuthor(hugo);
        }
    }

}
</programlisting></para>
          </section>
        </section>

        <section xml:id="getting.started.mdb">
          <title>MessageDriven Bean</title>

          <para>The javaee5-earsample application provides a MessageDriven
          bean, aka an <acronym>EJB</acronym> that receives
          <acronym>JMS</acronym> messages. A <acronym>MDB</acronym> does not
          have a business interface, therefore, it is not exposed (through
          <acronym>JNDI</acronym>) to application clients or other
          <acronym>EJB</acronym>s. The only way to interact with them is to
          send messages to the <acronym>JMS</acronym> destination they're
          listening on.</para>

          <para>A <acronym>MDB</acronym> is defined using the @MessageDriven
          annotation. The bean is also configured with the help of the
          @ActivationConfigProperty annotations. In this case, they define the
          <acronym>JNDI</acronym> name of the <acronym>JMS</acronym>
          destination (<literal>"SampleQueue"</literal>) and the destination
          type (can be <interfacename>javax.jms.Queue</interfacename> or
          <interfacename>javax.jms.Topic</interfacename> for
          <acronym>JMS</acronym> destinations). <acronym>MDBs</acronym>
          listening to <acronym>JMS</acronym> destinations need to implement
          the <interfacename>javax.jms.MessageListener</interfacename>
          interface.</para>

          <para><screen>@MessageDriven(activationConfig={
        @ActivationConfigProperty(propertyName="destination",
                                  propertyValue="SampleQueue"),
        @ActivationConfigProperty(propertyName="destinationType",
                                  propertyValue="javax.jms.Queue")
        })
@RunAs("earsample")
public class JMSMessageBean implements MessageListener {
</screen>This bean is also executed with the @RunAs annotation. This is needed
          because (like the Initializer) it uses the Writer bean, which is a
          secured bean.</para>

          <para>Here is the code of the MDB:</para>

          <para><programlisting>package org.ow2.jonas.examples.ear.mdb;

import javax.annotation.security.RunAs;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.EJB;
import javax.ejb.MessageDriven;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

import org.ow2.jonas.examples.ear.entity.Author;
import org.ow2.jonas.examples.ear.entity.Book;
import org.ow2.jonas.examples.ear.reader.LocalReader;
import org.ow2.jonas.examples.ear.writer.LocalWriter;

/**
 * The {@link JMSMessageBean} is a message driven bean activated when a JMS
 * {@link Message} comes to a given Destination.
 * For each new {@link Message}, this bean will create and persists a new
 * {@link Book} instance.
 * This MDB is annotated with {@link RunAs} because it uses a secured
 * business interface.
 * @author Guillaume Sauthier
 */
@MessageDriven(activationConfig={
        @ActivationConfigProperty(propertyName="destination",
                                  propertyValue="SampleQueue"),
        @ActivationConfigProperty(propertyName="destinationType",
                                  propertyValue="javax.jms.Queue")
        })
@RunAs("earsample")
public class JMSMessageBean implements MessageListener {

    /**
     * Secured business interface.
     */
    @EJB
    private LocalWriter writer;

    /**
     * Unsecured {@link LocalReader} business interface.
     */
    @EJB
    private LocalReader reader;

    /**
     * Called when a new JMS {@link Message} is received on the destination.
     * This method will use the {@link LocalWriter} Bean interface to add
     * Books to a given Author.
     * @param message {@link Message} containing {@link Book} title.
     * @see javax.jms.MessageListener#onMessage(javax.jms.Message)
     */
    public void onMessage(final Message message) {

        // TODO to be removed
        System.out.println("Received JMS Message: " + message);

        // Extract Message's text value
        String text = null;
        if (message instanceof TextMessage) {
            TextMessage textMessage = (TextMessage) message;
            try {
                text = textMessage.getText();
            } catch (JMSException e) {
                System.err.println("Unexpected Exception: " + e.getMessage());
                e.printStackTrace(System.err);
                return;
            }
        } else {
            // not a TextMessage, I don't know what to do with it
            return;
        }

        Author edition = reader.findAuthor("Editions XY");
        if (edition == null) {
            edition = new Author("Editions XY");
            writer.addAuthor(edition);
        }

        // Persists a new Book
        Book book = new Book(text, edition);
        writer.addBook(book);

    }

}
</programlisting></para>
        </section>
      </section>

      <section>
        <info>
          <title>Web Tier: Servlets</title>
        </info>

        <para>Servlets are the web front end of the application, that's the
        presentation layer. Servlets are in charge of displaying business
        objects to the user and giving them handles to act on theses data
        objects.</para>

        <para>Following is a screenshot obtained when pressing the "View
        Library Content" button on the home page:</para>

        <para><mediaobject>
            <imageobject role="html">
              <imagedata fileref="../../resources/images/earsample-list-content.png"></imagedata>
            </imageobject>

            <imageobject role="fo">
              <imagedata fileref="../../resources/images/earsample-list-content.png"
                         scale="50"></imagedata>
            </imageobject>
          </mediaobject>The servlet <classname>ExampleServlet</classname> is
        used to generate the above web page.</para>

        <para>As it is only a presentation front end, it does not manage the
        data itself. The servlet uses the Reader EJB to retrieve the content
        of the model.</para>

        <para>The reference to the EJB is injected into the servlet in the
        Java EE 5 way: using annotations.</para>

        <para><screen>    /**
     * Link to the Local Reader bean. The bean will be injected by JOnAS.
     */
    @EJB
    private LocalReader readerBean;
</screen>Thousands of times easier than the old J2EE 1.4 way (InitialContext,
        lookup and narrow) !</para>

        <para>Here is the code of the read-only servlet:<programlisting>package org.ow2.jonas.examples.ear.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.List;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.ow2.jonas.examples.ear.entity.Author;
import org.ow2.jonas.examples.ear.entity.Book;
import org.ow2.jonas.examples.ear.init.Initializer;
import org.ow2.jonas.examples.ear.reader.LocalReader;

/**
 * Defines a servlet that is accessing the two entities through a local session
 * bean.
 * @author Florent Benoit
 */
public class ExampleServlet extends HttpServlet {

    /**
     * Serializable class uid.
     */
    private static final long serialVersionUID = -3172627111841538912L;

    /**
     * Link to the Local Reader bean. Bean will be injected by JOnAS.
     */
    @EJB
    private LocalReader readerBean;

    /**
     * Link to the initializer bean.
     */
    @EJB
    private Initializer initializerBean;

    /**
     * Called by the server (via the service method) to allow a servlet to
     * handle a GET request.
     * @param request an HttpServletRequest object that contains the request the
     *        client has made of the servlet
     * @param response an HttpServletResponse object that contains the response
     *        the servlet sends to the client
     * @throws IOException if an input or output error is detected when the
     *         servlet handles the GET request
     * @throws ServletException if the request for the GET could not be handled
     */
    @Override
    public void doGet(final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException {

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("&lt;!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\"&gt;");
        out.println("&lt;html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\"&gt;");
        out.println("  &lt;head&gt;");
        out.println("    &lt;link type=\"text/css\" href=\"ow2_jonas.css\" rel=\"stylesheet\" id=\"stylesheet\" /&gt;");
        out.println("    &lt;title&gt;Ear Sample of Servlet accessing an EJB&lt;/title&gt;");
        out.println("  &lt;/head&gt;");
        out.println("&lt;body style=\"background : white; color : black;\"&gt;");

        out.println("  &lt;div&gt;&lt;a href=\"http://www.ow2.org\"&gt;&lt;img src=\"img/logoOW2.png\" alt=\"logo\"/&gt;&lt;/a&gt;&lt;/div&gt;");
        out.println("  &lt;div class=\"logos\"&gt;");
        out.println("    &lt;img src=\"img/tomcat.gif\" alt=\"Tomcat Logo\"/&gt;");
        out.println("    &lt;img src=\"img/jetty.gif\" alt=\"Jetty Logo\"/&gt;");
        out.println("    &lt;img src=\"img/ow_jonas_logo.gif\" alt=\"JOnAS Logo\"/&gt;");
        out.println("  &lt;/div&gt;");

        out.println("  &lt;div class=\"titlepage\"&gt;Ear sample of Servlet accessing an EJB&lt;/div&gt;");


        out.println("  &lt;div class=\"links\"&gt;");
        initAuthorBooks(out);
        out.println("    &lt;br /&gt;");
        out.println("  &lt;/div&gt;");

        out.println("  &lt;div class=\"links\"&gt;");
        displayAuthors(out);
        out.println("  &lt;/div&gt;");

        out.println("  &lt;div class=\"links\"&gt;");
        out.println("    &lt;form action=\"secured/Admin\" method=\"get\"&gt;");
        out.println("      &lt;div&gt;&lt;input type=\"submit\" value=\"Modify Library Content\"/&gt;&lt;/div&gt;");
        out.println("    &lt;/form&gt;");
        out.println("  &lt;/div&gt;");

        out.println("  &lt;div class=\"footer\"&gt;");
        out.println("    &lt;p&gt;");
        out.println("      &lt;a href=\"http://validator.w3.org/check/referer\"&gt;");
        out.println("        &lt;img src=\"img/valid-xhtml11.png\" alt=\"Valid XHTML 1.1!\"");
        out.println("             title=\"Valid XHTML 1.1!\" height=\"31\" width=\"88\" /&gt;");
        out.println("      &lt;/a&gt;");
        out.println("      &lt;a href=\"http://jigsaw.w3.org/css-validator/\"&gt;");
        out.println("        &lt;img style=\"border:0;width:88px;height:31px\" src=\"img/vcss.png\"");
        out.println("             title=\"Valid CSS!\" alt=\"Valid CSS!\" /&gt;");
        out.println("      &lt;/a&gt;");
        out.println("    &lt;/p&gt;");
        out.println("  &lt;/div&gt;");

        out.println("&lt;/body&gt;");
        out.println("&lt;/html&gt;");
        out.close();
    }

    /**
     * Init list of authors/books.
     * @param out the given writer
     */
    private void initAuthorBooks(final PrintWriter out) {
        out.println("Initialize authors and their books...&lt;br/&gt;");

        try {
            initializerBean.initializeEntities();
        } catch (Exception e) {
            displayException(out, "Cannot init list of authors with their books", e);
            return;
        }
    }

    /**
     * Display authors.
     * @param out the given writer
     */
    private void displayAuthors(final PrintWriter out) {
        out.println("Get authors");
        out.println("&lt;br /&gt;&lt;br /&gt;");

        // Get list of Authors
        List&lt;Author&gt; authors = null;
        try {
            authors = readerBean.listAllAuthors();
        } catch (Exception e) {
            displayException(out, "Cannot call listAllAuthors on the bean", e);
            return;
        }

        // List for each author, the name of books
        if (authors != null) {
            for (Author author : authors) {
                out.println("List of books with author '" + author.getName() + "' :");
                out.println("&lt;ul&gt;");
                Collection&lt;Book&gt; books = author.getBooks();
                if (books == null) {
                    out.println("&lt;li&gt;No book !&lt;/li&gt;");
                } else {
                    for (Book book : books) {
                        out.println("&lt;li&gt;Title '" + book.getTitle() + "'.&lt;/li&gt;");
                    }
                }
                out.println("&lt;/ul&gt;");

            }
        } else {
            out.println("No author found !");
        }

    }

    /**
     * If there is an exception, print the exception.
     * @param out the given writer
     * @param errMsg the error message
     * @param e the content of the exception
     */
    private void displayException(final PrintWriter out, final String errMsg, final Exception e) {
        out.println("&lt;p&gt;Exception : " + errMsg);
        out.println("&lt;pre&gt;");
        e.printStackTrace(out);
        out.println("&lt;/pre&gt;&lt;/p&gt;");
    }

}
</programlisting></para>

        <para>The web application allows the user to change the model's
        content (ie add new Authors to the list of managed authors). This
        time, this is a write-like operation, so security is required to
        restrict unauthorized users from changing the model.</para>

        <mediaobject>
          <imageobject role="html">
            <imagedata fileref="../../resources/images/earsample-authentication.png"></imagedata>
          </imageobject>

          <imageobject role="fo">
            <imagedata fileref="../../resources/images/earsample-authentication.png"
                       scale="50"></imagedata>
          </imageobject>
        </mediaobject>

        <para>This behaviour is achieved through some additions into the
        <filename>WEB-INF/web.xml</filename>:</para>

        <para><screen>  &lt;servlet&gt;
    &lt;servlet-name&gt;AdminServlet&lt;/servlet-name&gt;
    &lt;servlet-class&gt;org.ow2.jonas.examples.ear.web.AdminServlet&lt;/servlet-class&gt;
  &lt;/servlet&gt;

  &lt;servlet-mapping&gt;
    &lt;servlet-name&gt;AdminServlet&lt;/servlet-name&gt;
    &lt;url-pattern&gt;<emphasis role="bold">/secured/*</emphasis>&lt;/url-pattern&gt;
  &lt;/servlet-mapping&gt;

  &lt;security-constraint&gt;
    &lt;web-resource-collection&gt;
      &lt;web-resource-name&gt;Protected Area&lt;/web-resource-name&gt;
      &lt;!-- Define the context-relative URL(s) to be protected --&gt;
      &lt;url-pattern&gt;<emphasis role="bold">/secured/*</emphasis>&lt;/url-pattern&gt;
      &lt;!-- If you list http methods, only those methods are protected --&gt;
      &lt;http-method&gt;DELETE&lt;/http-method&gt;
      &lt;http-method&gt;GET&lt;/http-method&gt;
      &lt;http-method&gt;POST&lt;/http-method&gt;
      &lt;http-method&gt;PUT&lt;/http-method&gt;
    &lt;/web-resource-collection&gt;
    &lt;auth-constraint&gt;
      &lt;!-- Anyone with one of the listed roles may access this area --&gt;
      &lt;role-name&gt;earsample&lt;/role-name&gt;
    &lt;/auth-constraint&gt;
  &lt;/security-constraint&gt;

  &lt;!-- Default login configuration uses BASIC authentication --&gt;
  &lt;login-config&gt;
    &lt;auth-method&gt;BASIC&lt;/auth-method&gt;
    &lt;realm-name&gt;JOnAS Realm&lt;/realm-name&gt;
  &lt;/login-config&gt;

  &lt;!-- Security roles referenced by this web application --&gt;
  &lt;security-role&gt;
    &lt;role-name&gt;earsample&lt;/role-name&gt;
  &lt;/security-role&gt;
</screen>By defining a <literal>&lt;security-constraint&gt;</literal> element,
        the web developer has decided to protect a given
        <literal>&lt;url-pattern&gt;</literal> (matching the servlet's
        mapping). Protection means that only authenticated users with the
        <literal>earsample</literal> <literal>&lt;role-name&gt;</literal> may
        access that page.</para>

        <para>Then, once the user has authenticated himself (assuming he has
        the <literal>earsample</literal> role), he will be able to access the
        web page, allowing changes to the model:</para>

        <para><mediaobject>
            <imageobject role="html">
              <imagedata fileref="../../resources/images/earsample-add-author.png"></imagedata>
            </imageobject>

            <imageobject role="fo">
              <imagedata fileref="../../resources/images/earsample-add-author.png"
                         scale="50"></imagedata>
            </imageobject>
          </mediaobject></para>
      </section>

      <section xml:id="getting_application_clients">
        <info>
          <title>Application Clients</title>
        </info>

        <para>The Java EE 5 EAR Sample provides multiple application clients
        (<acronym>AC</acronym>) showing how to interact with the application
        in different ways, and under different security levels:</para>

        <para><itemizedlist>
            <listitem>
              <para>Not Secured <acronym>AC</acronym>: this client uses the
              Mailer and Reader bean, using the Reader, it displays the
              Authors and Books, and using the Mailer bean, it sends a mail
              with an equivalent content.</para>
            </listitem>

            <listitem>
              <para>JAAS Secured <acronym>AC</acronym>: this clients shows
              usage of <acronym>JAAS</acronym> authentication. It uses the
              Writer bean, which required a user with the
              "<literal>earsample</literal>" role, to insert new Authors and
              Books.</para>
            </listitem>

            <listitem>
              <para>JMS <acronym>AC</acronym>: this client mainly interacts
              with a dedicated <acronym>JMS</acronym> Queue to sends Book
              creation orders, then it waits some times and uses the Reader
              bean to see if the new Books were persisted.</para>
            </listitem>
          </itemizedlist></para>

        <section>
          <title>Not Secured Application Client</title>

          <para>This AC uses 3 beans that are freely available for anonymous
          usage: Initializer, Reader and Mailer.</para>

          <para>The Client can be launched using the following command
          line:</para>

          <para><screen><prompt>&gt;$</prompt> <userinput>jclient -nowsgen $JONAS_BASE/deploy/javaee5-earsample.ear -jarClient not-secured-application-client.jar</userinput>
ClientContainer.info : Use the application client
'/tmp/client-deployer-coqp/EARDeployableImpl/javaee5-earsample.ear/not-secured-application-client.jar'
of the Ear 'file:/tmp/client-deployer-coqp/EARDeployableImpl/javaee5-earsample.ear/'.
<computeroutput>
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
OW2 JOnAS :: EAR Sample :: Not Secured Application Client
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Initialization ... Done.
Get the RemoteReader Bean reference: org.ow2.jonas.examples.ear.reader.ReaderBean_org.ow2.jonas.examples.ear.reader.RemoteReader/7735352
List of authors, and their books:
 * Honore de Balzac
 -&gt; Le Pere Goriot [id: 1]
 -&gt; Les Chouans [id: 2]
 * Victor Hugo
 -&gt; Les Miserables [id: 3]
 -&gt; Notre-Dame de Paris [id: 4]
List of books:
 * Le Pere Goriot [Honore de Balzac]
 * Les Chouans [Honore de Balzac]
 * Les Miserables [Victor Hugo]
 * Notre-Dame de Paris [Victor Hugo]
Get the Mailer Bean reference: org.ow2.jonas.examples.ear.mail.MailerBean_org.ow2.jonas.examples.ear.mail.Mailer/7735352
Success.</computeroutput>
</screen></para>

          <para>The Initializer, Mailer and Reader beans are get via
          annotation based injection (no JNDI lookup is necessary).</para>

          <para><screen>@EJB
RemoteReader reader;
</screen></para>

          <para></para>

          <para>By default, a mail displaying the library content is sent to
          the <literal>${user.name}@localhost</literal> address. This value
          can be changed by adding another mail address into the command
          line:</para>

          <para><screen><prompt>&gt;$</prompt> <userinput><userinput>jclient -nowsgen $JONAS_BASE/deploy/javaee5-earsample.ear \
           -jarClient not-secured-application-client.jar</userinput> someone@somewhere.org
</userinput></screen><example>
              <title>An example of e-mail</title>

              <para><screen>---------------------------------------------------
 OW2 JOnAS EAR Sample Mailer Bean.
---------------------------------------------------
Generated the Wed May 21 16:58:57 CEST 2008

List of all registered Authors (3) and their Books:
  * Honore de Balzac [1]
    - Le Pere Goriot[1]
    - Les Chouans[2]
  * Victor Hugo [2]
    - Les Miserables[3]
    - Notre-Dame de Paris[4]

List of all registered Books:
  * Le Pere Goriot[Honore de Balzac]
  * Les Chouans[Honore de Balzac]
  * Les Miserables[Victor Hugo]
  * Notre-Dame de Paris[Victor Hugo]

Enjoy your new JOnAS !

       -- JOnAS Team
</screen></para>
            </example></para>

          <para>Here is the not secured application client
          code:<programlisting>package org.ow2.jonas.examples.ear.client;

import java.io.PrintStream;
import java.util.Collection;
import java.util.List;

import javax.ejb.EJB;

import org.ow2.jonas.examples.ear.entity.Author;
import org.ow2.jonas.examples.ear.entity.Book;
import org.ow2.jonas.examples.ear.init.Initializer;
import org.ow2.jonas.examples.ear.mail.Mailer;
import org.ow2.jonas.examples.ear.reader.RemoteReader;

/**
 * Simple Application Client.
 * @author Guillaume Sauthier
 */
public final class NotSecuredApplicationClient {

    /**
     * Empty default constructor for utility class.
     */
    private NotSecuredApplicationClient() {

    }

    /**
      * Link to the initializer bean.
      */
     @EJB
     static private Initializer initializerBean;

    /**
      * Link to the Remote Reader bean. Bean will be injected by JOnAS.
      */
     @EJB
     static private RemoteReader readerBean;

     /**
      * Link to the Mailer bean. Bean will be injected by JOnAS.
      */
     @EJB
     static private Mailer mailerBean;


    /**
     * @param args Command line arguments
     *
     */
    public static void main(final String[] args)  {

        PrintStream out = System.out;

        // Print Header
        out.println("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -");
        out.println("OW2 JOnAS :: EAR Sample :: Not Secured Application Client  ");
        out.println("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -");

        // Init datas if needed
        out.print("Initialization ... ");
        initializerBean.initializeEntities();
        out.println("Done.");


        out.println("The RemoteReader Bean reference is : " + readerBean);

        // List registered authors and their books
        out.println("List of authors, and their books:");
        // retrieve again the authors list (now it has been initialized)
        List&lt;Author&gt; authors = readerBean.listAllAuthors();
        for (Author author : authors) {
            out.println(" * " + author.getName());
            Collection&lt;Book&gt; books = author.getBooks();
            for (Book book : books) {
                out.println(" -&gt; " + book.getTitle() + " [id: " + book.getId() + "]");
            }
        }

        // Only list registered books
        List&lt;Book&gt; books = readerBean.listAllBooks();
        out.println("List of books:");
        for(Book book : books) {
            out.println(" * " + book.getTitle() + " [" + book.getAuthor().getName() + "]");
        }

        // Use the Mailer bean to send
        // Use the first command line argument as a mail address.
        // Fall back to a reasonable default ${user.name}@localhost
        String address = System.getProperty("user.name") + "@localhost";
        if (args.length &gt; 0) {
            // Got an argument, use it ...
            address = args[0];
        }

        out.println("The Mailer Bean reference is : " + mailerBean);

        // Call the Mailer bean to send the expected e-mail.
        mailerBean.sendStatusMail(address);

        // OK, we're done
        out.println("Success.");

    }
}
        </programlisting></para>
        </section>

        <section>
          <title>JAAS Secured Application Client</title>

          <para>This AC is secured using JAAS. It means that the client will
          be authenticated at startup.</para>

          <para>The Client can be launched using the following command
          line:</para>

          <para><screen><prompt>&gt;$</prompt> <userinput>jclient -nowsgen $JONAS_BASE/deploy/javaee5-earsample.ear -jarClient jaas-secured-application-client.jar                            </userinput>
<computeroutput>ClientContainer.info : Use the application client
'/tmp/client-deployer-sauthieg/EARDeployableImpl/javaee5-earsample.ear/jaas-secured-application-client.jar'
of the Ear 'file:/tmp/client-deployer-sauthieg/EARDeployableImpl/javaee5-earsample.ear/'.
ClientContainer.info : Using the login/password specified in the jonas-client.xml file with a specific CallbackHandler
ClientContainer.info : Using JAAS loginContext 'javaee5-earsample'
from the file 'jar:file:/tmp/client-deployer-sauthieg/EARDeployableImpl/javaee5-earsample.ear/jaas-secured-application-client.jar!/jaas.config'.
ClientContainer.info : Starting client...
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
OW2 JOnAS :: EAR Sample :: Secured Application Client
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Initialization ... Done.
Get the RemoteReader Bean reference: org.ow2.jonas.examples.ear.reader.ReaderBean_org.ow2.jonas.examples.ear.reader.RemoteReader/7735352
List of authors, and their books:
 * Honore de Balzac
 -&gt; Le Pere Goriot [id: 1]
 -&gt; Les Chouans [id: 2]
 * Victor Hugo
 -&gt; Les Miserables [id: 3]
 -&gt; Notre-Dame de Paris [id: 4]
Get the RemoteWriter Bean reference: org.ow2.jonas.examples.ear.writer.WriterBean_org.ow2.jonas.examples.ear.writer.RemoteWriter/7735352
Created a new Author:
org.ow2.jonas.examples.ear.entity.Author[id=0, name=Emile Zola]
Updated authors' list:
 * Honore de Balzac
 -&gt; Le Pere Goriot [id: 1]
 -&gt; Les Chouans [id: 2]
 * Victor Hugo
 -&gt; Les Miserables [id: 3]
 -&gt; Notre-Dame de Paris [id: 4]
 * Emile Zola
 -&gt; Germinal [id: 45]
 -&gt; La Bete Humaine [id: 46]
Cleaned added Author.
Success.</computeroutput>
</screen></para>

          <para>This AC has been configured to use the LoginCallbackHandler.
          The CallbackHandler will be configured by JOnAS to use the
          jonas/jonas username and password pair. So, nothing has to be done
          to provide a password interactively.</para>

          <para><example>
              <title>META-INF/application-client.xml</title>

              <para><screen>&lt;application-client
  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/application-client_5.xsd"
  version="5"&gt;
  &lt;display-name&gt;OW2 JOnAS :: EAR Sample :: Secured Application Client&lt;/display-name&gt;
<emphasis role="bold">  &lt;callback-handler&gt;org.ow2.jonas.security.auth.callback.LoginCallbackHandler&lt;/callback-handler&gt;</emphasis>
&lt;/application-client&gt;</screen></para>
            </example><example>
              <title>META-INF/jonas-client.xml</title>

              <para><screen>&lt;jonas-client xmlns="http://www.objectweb.org/jonas/ns"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.objectweb.org/jonas/ns
        http://jonas.ow2.org/ns/jonas-client_5_0.xsd" &gt;

  &lt;jonas-security&gt;
    &lt;jaasfile&gt;jaas.config&lt;/jaasfile&gt;
    &lt;jaasentry&gt;javaee5-earsample&lt;/jaasentry&gt;
    &lt;username&gt;jonas&lt;/username&gt;
    &lt;password&gt;jonas&lt;/password&gt;
  &lt;/jonas-security&gt;

&lt;/jonas-client&gt;
</screen></para>
            </example><example>
              <title>jaas.config</title>

              <para><screen><emphasis role="bold">javaee5-earsample</emphasis> {
    // Login Module to use for the example javaee5-earsample.

    // First, use a LoginModule for the authentication
    // Use the resource memrlm_1
    org.ow2.jonas.security.auth.spi.JResourceLoginModule required
    resourceName="memrlm_1"
    ;

    // Use the login module to propagate security to the JOnAS server
    org.ow2.jonas.security.auth.spi.ClientLoginModule  required
    ;
};</screen></para>
            </example>The <interfacename>CallbackHandler</interfacename> is
          configured using the <literal>jonas-security</literal> element: it
          will load the specified <acronym>JAAS</acronym> configuration file
          (<filename>jaas.config</filename>), then load the entry named
          <literal>javaee5-earsample</literal> and will create a dedicated
          <interfacename>LoginModule</interfacename> chain. The
          ClientContainer will then configure the
          <interfacename>CallbackHandler</interfacename> to provide a
          specified username and password when requested by the
          LoginModules.</para>

          <para>As the authentication is done by the ClientContainer at
          startup, there are no security concerns in the code. The
          ClientContainer guarantees that if this code is executed, it is run
          by an authenticated user. If the user could not authenticate, the
          ClientContainer will exit before running the real client's
          code.</para>

          <para><programlisting>
package org.ow2.jonas.examples.ear.client;

import java.io.PrintStream;
import java.util.Collection;
import java.util.List;
import java.text.MessageFormat;

import javax.ejb.EJB;

import org.ow2.jonas.examples.ear.entity.Author;
import org.ow2.jonas.examples.ear.entity.Book;
import org.ow2.jonas.examples.ear.init.Initializer;
import org.ow2.jonas.examples.ear.reader.RemoteReader;
import org.ow2.jonas.examples.ear.writer.RemoteWriter;

/**
 * Simple Application Client.
 * @author Guillaume Sauthier
 */
public final class SecuredApplicationClient {

    /**
     * Empty default constructor for utility class.
     */
    private SecuredApplicationClient() {

    }

       /**
      * Link to the initializer bean.
      */
     @EJB
     static private Initializer initializerBean;

    /**
      * Link to the Remote Reader bean. Bean will be injected by JOnAS.
      */
     @EJB
     static private RemoteReader readerBean;

     /**
      * Link to the Remote Writer bean. Bean will be injected by JOnAS.
      */
     @EJB
     static private RemoteWriter writerBean;

    /**
     * @param args Command line arguments
     *
     */
    public static void main(final String[] args) {

        PrintStream out = System.out;

        // Print Header
        out.println("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -");
        out.println("OW2 JOnAS :: EAR Sample :: Secured Application Client      ");
        out.println("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -");
        // Init. data if needed
        out.print("Initialization ... ");
        initializerBean.initializeEntities();
        out.println("Done.");

        out.println("The RemoteReader Bean reference is: " + readerBean);

        // List registered authors and their books
        out.println("List of authors, and their books:");
        // retrieve again the authors list (now it has been initialized)
        List&lt;Author&gt; authors = readerBean.listAllAuthors();
        for (Author author : authors) {
            out.println(" * " + author.getName());
            Collection&lt;Book&gt; books = author.getBooks();
            for (Book book : books) {
                out.println(MessageFormat.format(" -&gt; {0} [id: {1}]", book.getTitle(), book.getId()));
            }
        }

        // Use the secured Bean (RemoteWriter)
        // ======================================
        out.println("Get the RemoteWriter Bean reference: " + writerBean);

        // Add another author, and some books
        Author zola = new Author("Emile Zola");
        Book germinal = new Book("Germinal", zola);
        Book beteHumaine = new Book("La Bete Humaine", zola);
        zola.getBooks().add(germinal);
        zola.getBooks().add(beteHumaine);

        // Display Author before storage
        out.println("Created a new Author: ");
        out.println(zola.toString());

        // Persists
        writerBean.addAuthor(zola);

        // See the new content
        out.println("Updated authors' list:");
        authors = readerBean.listAllAuthors();
        for (Author author : authors) {
            out.println(" * " + author.getName());
            Collection&lt;Book&gt; books = author.getBooks();
            for (Book book : books) {
                out.println(MessageFormat.format(" -&gt; {0} [id: {1}]", book.getTitle(), book.getId()));
            }
        }

        // Remove Zola (and its books), so that next time the client
        // is executed, we can add them again.
        writerBean.removeAuthor(zola);
        out.println("Cleaned added Author.");
        out.println("Success.");

    }
}
</programlisting></para>
        </section>

        <section>
          <title>JMS Application Client</title>

          <para>This AC demonstrates how to connect a client to the
          application using <acronym>JMS</acronym> instead of using
          <acronym>RMI</acronym> <acronym>EJB</acronym> objects.</para>

          <para>The Client can be launched using the following command
          line:</para>

          <para><screen><prompt>&gt;$</prompt> <userinput>jclient -nowsgen $JONAS_BASE/deploy/javaee5-earsample.ear</userinput>
<computeroutput>ClientContainer.warn : There are 3 clients in this ear, choosing the first one : jms-application-client.jar
ClientContainer.info : Use the application client '/tmp/client-deployer-sauthieg/EARDeployableImpl/javaee5-earsample.ear/jms-application-client.jar'
of the Ear 'file:/tmp/client-deployer-sauthieg/EARDeployableImpl/javaee5-earsample.ear/'.
ClientContainer.info : Starting client...
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
OW2 JOnAS :: EAR Sample :: Messager Application Client
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Initialization ... Done.
Sended creation order for 'Encyclopedia Universalis Vol.0'
Sended creation order for 'Encyclopedia Universalis Vol.1'
Sended creation order for 'Encyclopedia Universalis Vol.2'
Sended creation order for 'Encyclopedia Universalis Vol.3'
Sended creation order for 'Encyclopedia Universalis Vol.4'
Sended creation order for 'Encyclopedia Universalis Vol.5'
Sended creation order for 'Encyclopedia Universalis Vol.6'
Sended creation order for 'Encyclopedia Universalis Vol.7'
Sended creation order for 'Encyclopedia Universalis Vol.8'
Sended creation order for 'Encyclopedia Universalis Vol.9'
Wait for 2500 ms...
Get Reader Bean ...
 * Honore de Balzac
 -&gt; Le Pere Goriot [id: 1]
 -&gt; Les Chouans [id: 2]
 * Victor Hugo
 -&gt; Les Miserables [id: 3]
 -&gt; Notre-Dame de Paris [id: 4]
 * Editions XY
 -&gt; Encyclopedia Universalis Vol.0 [id: 5]
 -&gt; Encyclopedia Universalis Vol.1 [id: 6]
 -&gt; Encyclopedia Universalis Vol.2 [id: 7]
 -&gt; Encyclopedia Universalis Vol.3 [id: 8]
 -&gt; Encyclopedia Universalis Vol.4 [id: 9]
 -&gt; Encyclopedia Universalis Vol.5 [id: 10]
 -&gt; Encyclopedia Universalis Vol.6 [id: 11]
 -&gt; Encyclopedia Universalis Vol.7 [id: 12]
 -&gt; Encyclopedia Universalis Vol.8 [id: 13]
 -&gt; Encyclopedia Universalis Vol.9 [id: 14]
Success.
</computeroutput></screen></para>

          <para>The client acts as a message producer: it retrieves a
          <acronym>JMS</acronym> <interfacename>Queue</interfacename> object
          (named <literal>SampleQueue</literal>) and a <acronym>JMS</acronym>
          <interfacename>QueueConnectionFactory</interfacename>. Then, it uses
          both to send asynchronous messages to the server.</para>

          <para>Each message represents a book registration order and contains
          the name of the Book to create.</para>

          <para>On the application's side (in other words, on the server),
          there is a dedicated MessageDrivenBean (see the <xref
          linkend="getting.started.mdb" />), that will be invoked for all the
          <acronym>JMS</acronym> messages received by the
          <interfacename>Queue</interfacename>.</para>

          <para>Usage of <acronym>JMS</acronym> objects have to be declared in
          standard and specific deployment descriptors (using
          <literal>resource-ref</literal> and/or
          <literal>resource-env-ref</literal>, respectively
          <literal>jonas-resource</literal> and/or
          <literal>jonas-resource-env</literal>)</para>

          <para>This JMS example shows how to use resource injection via
          @Resource annotation (see JMS client code below).</para>

          <para><example>
              <title>META-INF/application-client.xml</title>

              <para><screen>&lt;application-client
  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/application-client_5.xsd"
  version="5"&gt;

  &lt;display-name&gt;OW2 JOnAS :: EAR Sample :: JMS Application Client&lt;/display-name&gt;

  &lt;!-- The JMS ConnectionFactory to use --&gt;
<emphasis role="bold">  &lt;resource-ref&gt;
    &lt;res-ref-name&gt;jms/QueueConnectionFactory&lt;/res-ref-name&gt;
    &lt;res-type&gt;javax.jms.QueueConnectionFactory&lt;/res-type&gt;
    &lt;res-auth&gt;Container&lt;/res-auth&gt;
  &lt;/resource-ref&gt;
</emphasis>
  &lt;!-- The JMS Queue where Messages will be send --&gt;
<emphasis role="bold">  &lt;resource-env-ref&gt;
    &lt;resource-env-ref-name&gt;jms/SampleQueue&lt;/resource-env-ref-name&gt;
    &lt;resource-env-ref-type&gt;javax.jms.Queue&lt;/resource-env-ref-type&gt;
  &lt;/resource-env-ref&gt;
</emphasis>
&lt;/application-client&gt;</screen></para>
            </example><example>
              <title>META-INF/jonas-client.xml</title>

              <para><screen>&lt;jonas-client xmlns="http://www.objectweb.org/jonas/ns"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.objectweb.org/jonas/ns
        http://jonas.ow2.org/ns/jonas-client_5_0.xsd" &gt;
  &lt;jonas-resource&gt;
    &lt;res-ref-name&gt;jms/QueueConnectionFactory&lt;/res-ref-name&gt;
    &lt;jndi-name&gt;JQCF&lt;/jndi-name&gt;
  &lt;/jonas-resource&gt;

  &lt;jonas-resource-env&gt;
    &lt;resource-env-ref-name&gt;jms/SampleQueue&lt;/resource-env-ref-name&gt;
    &lt;jndi-name&gt;SampleQueue&lt;/jndi-name&gt;
  &lt;/jonas-resource-env&gt;
&lt;/jonas-client&gt;
</screen></para>
            </example>Here is the code of the JMS client:<programlisting>package org.ow2.jonas.examples.ear.client;

import java.io.PrintStream;
import java.util.Collection;
import java.util.List;
import java.text.MessageFormat;

import javax.jms.*;
import javax.ejb.EJB;
import javax.annotation.Resource;

import org.ow2.jonas.examples.ear.entity.Author;
import org.ow2.jonas.examples.ear.entity.Book;
import org.ow2.jonas.examples.ear.init.Initializer;
import org.ow2.jonas.examples.ear.reader.RemoteReader;

/**
 * This application-client shows usage of JMS destinations to
 * interact with the server-side application.
 * @author Guillaume Sauthier
 */
public final class JMSApplicationClient {

    /**
     * Number of Books to be created.
     */
    private static final int ITERATION_NUMBER = 10;

    /**
      * Link to the initializer bean.
      */
     @EJB
     private static  Initializer initializerBean;

    /**
     *  JMS conectionFactoery
     */
    // Resource injection
     @Resource(mappedName="JQCF")
      private static ConnectionFactory factory;

    /**
     *   JMS Queue  SampleQueue
     */
    // Resource injection
     @Resource(mappedName="SampleQueue")
     private static Queue queue;


    /**
      * Link to the Remote Reader bean. Bean will be injected by JOnAS.
      */
     @EJB
     static private RemoteReader readerBean;

    /**
     * Empty default constructor for utility class.
     */
    private JMSApplicationClient() {

    }

    /**
     * @param args Command line arguments
     * @throws Exception JMS
     */
    public static void main(final String[] args) throws Exception {

        PrintStream out = System.out;

        // Print Header
        out.println("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -");
        out.println("OW2 JOnAS :: EAR Sample :: Messager Application Client     ");
        out.println("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -");




        // Init. data if needed
        out.print("Initialization ... ");

        initializerBean.initializeEntities();
        out.println("Done.");

        // Send Book creation Messages
        Connection connection = factory.createConnection();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        MessageProducer messageProducer= session.createProducer(queue);

        for (int i = 0; i &lt; ITERATION_NUMBER; i++) {
            String title = "Encyclopedia Universalis Vol." + i;
            Message message = session.createTextMessage(title);
            messageProducer.send(message);
            out.println("Sended creation order for '" + title + "'");
        }

        // Close JMS objects
        messageProducer.close();
        session.close();
        connection.close();

        // Wait for some time ...
        // Remember JMS is for asynchronous messages :)
        final long period = 2500;
        out.println(MessageFormat.format("Wait for {0} ms...", period));
        Thread.sleep(period);

        out.println(MessageFormat.format("The RemoteReader Bean reference is: {0}", readerBean));
        // List Authors and Books
        List&lt;Author&gt; authors = readerBean.listAllAuthors();
        for (Author author : authors) {
            out.println(MessageFormat.format(" * {0}", author.getName()));
            Collection&lt;Book&gt; books = author.getBooks();
            for (Book book : books) {
                out.println(MessageFormat.format(" -&gt; {0} [id: {1}]", book.getTitle(), book.getId()));
            }
        }

        out.println("Success.");

    }
}
</programlisting></para>
        </section>
      </section>

      <section>
        <info>
          <title>EAR</title>
        </info>

        <para>The <filename>javaee5-earsample.ear</filename> file is the
        enterprise archive wrapping all the Java EE modules into only one
        deployment unit.</para>

        <para>The EAR is all about packaging: there is no code and no
        resources (eg, classes, ...) directly inside of the .ear.</para>

        <para>Here is an overview of the ear structure:</para>

        <para><screen>javaee5-earsample.ear:
  META-INF/application.xml              <co xml:id="application.xml" />
  ejb3.jar                              <co xml:id="ejbjar" />
  javaee5-earsample.war                 <co xml:id="webapp" />
  jms-application-client.jar            <co xml:id="client.jms" />
  not-secured-application-client.jar    <co xml:id="client.not.secured" />
  jaas-secured-application-client.jar   <co xml:id="client.secured" />
</screen><calloutlist>
            <callout arearefs="application.xml">
              <para>Optional, inner jars can be discovered with .ear
              introspection</para>
            </callout>

            <callout arearefs="ejbjar">
              <para>The jar file containing the EJB3</para>
            </callout>

            <callout arearefs="webapp">
              <para>The Web Application archive</para>
            </callout>

            <callout arearefs="client.jms">
              <para>The Application Client using JMS to interact with the
              application</para>
            </callout>

            <callout arearefs="client.not.secured">
              <para>The Application Client using the Reader EJB without
              security</para>
            </callout>

            <callout arearefs="client.secured">
              <para>The Application Client using the Reader and Writer EJBs
              after being authenticated with JAAS</para>
            </callout>
          </calloutlist></para>
      </section>
    </section>
  </chapter>

  <appendix xml:id="downloadid">
    <info>
      <title>Download and installation instructions</title>
    </info>

    <section>
      <info>
        <title>Where can I find JOnAS?</title>
      </info>

      <para>The latest stable binary version can be found on the <link
      xlink:href="http://wiki.jonas.objectweb.org">JOnAS site</link>.</para>

      <para>The binary versions and sources are available at this site.</para>

      <para>The <xi:include href="variables.xml" xpointer="appserver" />
      project is developped using <literal>SVN</literal>. All information for
      getting or browsing the source code can be found <link
      xlink:href="http://forge.objectweb.org/plugins/scmsvn/index.php?group_id=5">here</link>.</para>
    </section>

    <section>
      <info>
        <title>How can I download JOnAS?</title>
      </info>

      <para>The <link
      xlink:href="http://wiki.jonas.objectweb.org/xwiki/bin/view/Main/Downloads">JOnAS
      download page</link> offers links to easily download <xi:include
      href="variables.xml" xpointer="appserver" />.</para>
    </section>

    <section>
      <info>
        <title>How can I install JOnAS?</title>
      </info>

      <para>The JOnAS distribution can be downloaded as a .tar.gz or .zip
      file.</para>

      <para>The installation process simply consists of unzipping the
      downloaded .tar.gz file.</para>

      <para>To install using the .tar.gz file, select a location for JOnAS
      installation, for example <filename
      class="directory">your_install_dir</filename>, and point to it.</para>

      <itemizedlist>
        <listitem>
          <para>Unix platforms</para>

          <screen><prompt>bash&gt;</prompt> <userinput>tar -zxvf &lt;jonas-file-name&gt;.tar.gz</userinput>
<computeroutput> jonas-full-5.x.y/
 jonas-full-5.x.y/conf/
 jonas-full-5.x.y/examples/
 jonas-full-5.x.y/examples/javaee5-earsample/
 jonas-full-5.x.y/examples/javaee5-earsample/etc/
...
</computeroutput></screen>

          <caution>
            <para>Be aware that if the same version of JOnAS has already been
            unpacked in the same directory, the new installation will
            overwrite previous files, and configuration files that have been
            customized may be lost. In this case, it is recommended that these
            files be saved before re-starting the installation process.</para>
          </caution>
        </listitem>

        <listitem>
          <para>Windows platforms</para>

          <para>If the <filename class="extension">.zip </filename>file format
          was downloaded, you must use a utility program such as WinZip or
          <link xlink:href="http://www.izarc.org/">IZArc</link> to extract the
          files from the archive.</para>
        </listitem>
      </itemizedlist>
    </section>

    <section>
      <info>
        <title>Pre-requisites</title>
      </info>

      <para>To be sure <xi:include href="variables.xml"
      xpointer="element(appserver)" /> can be used, the following products
      must be installed:</para>

      <itemizedlist>
        <listitem>
          <para>a J2SE SDK 1.5 Java virtual machine</para>

          <para>Any J2SE certified java platform may be used to run
          <xi:include href="variables.xml"
          xpointer="element(appserver)" />.</para>

          <para>The most commonly used is SUN's <link
          xlink:href="http://java.sun.com/javase/downloads/index_jdk5.jsp">(Java
          2 Platform, Standard Edition</link>), but there are others, such as
          <link xlink:href="http://dev2dev.bea.com/jrockit/">BEA
          JRockit</link>, <link
          xlink:href="http://www-128.ibm.com/developerworks/java/jdk/">IBM
          developper kits</link> or other free/open source certified
          implementations.</para>
        </listitem>

        <listitem>
          <para>Ant 1.7 and BCEL</para>

          <para>The binary version of Ant 1.7 must be downloaded from the
          <link xlink:href="http://ant.apache.org/bindownload.cgi">Apache Ant
          web site</link> and installed</para>

          <screen><prompt>bash&gt;</prompt> <userinput>tar -jxvf apache-ant-1.7.0-bin.tar.bz2</userinput>
or
<prompt>bash&gt;</prompt> <userinput>unzip apache-ant-1.7.0-bin.zip</userinput></screen>

          <para>Set the ANT_HOME environment variable and update the
          path:</para>

          <screen><prompt>on Unix platforms:
bash&gt;</prompt> <userinput>export ANT_HOME=&lt;Ant Installation Directory&gt;
</userinput><prompt>bash&gt;</prompt> <userinput>PATH=$PATH;$ANT_HOME/bin</userinput>

on Windows:
<prompt>C:&gt;</prompt> <userinput>set PATH=%ANT_HOME%/bin;%PATH%</userinput></screen>

          <para><filename>bcel-5.1.tar.gz </filename>must be dowloaded from
          the <link
          xlink:href="http://www.apache.org/dist/jakarta/bcel/binaries/">Apache
          Jakarta web site</link>. The bcel-5.1.jar must be installed in the
          <filename class="directory">$ANT_HOME/lib/</filename>
          directory.</para>
        </listitem>
      </itemizedlist>
    </section>
  </appendix>

  <appendix xml:id="distribution">
    <info>
      <title>JOnAS 5 distribution description</title>
    </info>

    <para>Here we describe the directory tree you get under your installation
    directory (<envar>JONAS_ROOT</envar> environment).</para>

    <xi:include href="config/jonasroot_structure.xml" />
  </appendix>

  <appendix>
    <info>
      <title>Glossary</title>
    </info>

    <xi:include href="Glossary.xml" />

    <para></para>
  </appendix>
</book>
