<?xml version="1.0" encoding="UTF-8"?>
<chapter id="embedded">
   <title>Embedded</title>

   <section id="embedded_overview">
      <title>Overview</title>

      <para>The IronJacamar embedded configuration provides a way of running a JCA container
        in-VM.</para>

      <para>The configuration is useful when you want a</para>

      <itemizedlist spacing="compact">
        <listitem>
          JCA container within your environment
        </listitem>
        <listitem>
          JCA container when doing unit testing
        </listitem>
      </itemizedlist>

      <para>Especially the ability to unit test your resource adapter archives before deploying them
        into a testing or a production environment will benefit developers.</para>

      <para>In order to enhance the experience with working with the embedded configuration the container 
        integrates with the <ulink url="http://www.jboss.org/shrinkwrap">ShrinkWrap</ulink>
        and <ulink url="http://arquillian.org/">Arquillian</ulink> frameworks.</para>

   </section>

   <section id="embedded_configuration">
      <title>Configuration</title>

      <para>You will need all the JAR files located in the</para>

      <programlisting>
$IRON_JACAMAR_HOME/bin
$IRON_JACAMAR_HOME/lib
$IRON_JACAMAR_HOME/lib/embedded
      </programlisting>

      <para>directories on your application class loader - f.ex.</para>

      <programlisting>
java -classpath allthejarfiles.jar yourapp
      </programlisting>

      <para>in order to use the embedded configuration.</para>

      <para>If you want integration with the Arquillian framework you need to add the JAR files located
        in the</para>

      <programlisting>
$IRON_JACAMAR_HOME/lib/embedded/arquillian
      </programlisting>

      <para>directory as well.</para>

      <para>The Arquillian/Byteman integration is located in the</para>

      <programlisting>
$IRON_JACAMAR_HOME/lib/embedded/arquillian/byteman
      </programlisting>

      <para>directory.</para>

      <para>Furthermore you will need to configure Java Naming and Directory Interface (JNDI) and logging
        using for example property files.</para>

      <para>Sample <code>jndi.properties</code> file:</para>
      <programlisting>
java.naming.factory.initial=org.jnp.interfaces.LocalOnlyContextFactory
java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces
      </programlisting>

      <para>Sample <code>logging.properties</code> file:</para>
      <programlisting>
# Additional logger names to configure (root logger is always configured)
loggers=org.jboss.jca,org.jboss,org.jnp,com.arjuna

# Root logger level
logger.level=${iron.jacamar.log.level:INFO}
logger.handlers=CONSOLE, FILE

# org.jboss.jca
logger.org.jboss.jca.level=DEBUG

# org.jboss
logger.org.jboss.level=INFO

# org.jnp
logger.org.jnp.level=INFO

# com.arjuna
logger.com.arjuna.level=INFO

# Console handler configuration
handler.CONSOLE=org.jboss.logmanager.handlers.ConsoleHandler
handler.CONSOLE.properties=autoFlush
handler.CONSOLE.level=${iron.jacamar.log.console.level:INFO}
handler.CONSOLE.autoFlush=true
handler.CONSOLE.formatter=PATTERN

# File handler configuration
handler.FILE=org.jboss.logmanager.handlers.FileHandler
handler.FILE.level=${iron.jacamar.log.file.level:DEBUG}
handler.FILE.properties=autoFlush,fileName
handler.FILE.autoFlush=true
handler.FILE.fileName=${test.dir}/embedded/test.log
handler.FILE.formatter=PATTERN

# Formatter pattern configuration
formatter.PATTERN=org.jboss.logmanager.formatters.PatternFormatter
formatter.PATTERN.properties=pattern
formatter.PATTERN.pattern=%d{HH:mm:ss,SSS} %-5p [%c{1}] %m%n
      </programlisting>

      <para>These files needs to be available to the application classloader.</para>

      <important>
        <para>
          The IronJacamar code generator will generate a test suite based on the Arquillian functionality, so
          that setup can be used as a starting point for your own integration.
        </para>

        <para>
          The setup will also show you how to use dependencies from the JBoss Nexus Maven repository instead
          if you choose the Maven or Ant+Ivy based build environment.
        </para>
      </important>

      <note>Note that, if you want to be able to deploy datasources you will need to deploy the <code>jdbc-local.rar</code>
        for <code>&lt;datasource&gt;</code> support, or <code>jdbc-xa.rar</code>
        for <code>&lt;xa-datasource&gt;</code> support. Both archives can be found in the
        <code>system/</code> directory.</note>

   </section>

   <section id="embedded_usage">
      <title>Usage</title>

      <para>IronJacamar Embedded supports both a simple and an advanced usage model, using pre-assembled
        resource adapter archives (.rar) or dynamic resource adapter archives based on ShrinkWrap.</para>

      <para>The embedded environment supports registering resource adapters and datasources in the platform
        <code>MBeanServer</code> by setting the system property
        <code>ironjacamar.embedded.management</code> to <code>true</code> before starting the environment.</para>

      <section id="embedded_usage_simple">
        <title>Simple usage</title>

        <para>The IronJacamar Embedded container environment supports the following open source
          testing projects:</para>

        <orderedlist>
          <listitem>
            <ulink url="http://arquillian.org/">Arquillian</ulink>
          </listitem>
          <listitem>
            <ulink url="http://www.jboss.org/shrinkwrap">ShrinkWrap</ulink>
          </listitem>
        </orderedlist>

        <para>These extensions allow the developer to use the embedded platform with greater ease
          as there doesn't have to be a physical representation of the resource adapter archive located
          to the disk.</para>

        <para>The Arquillian integration furthermore allows the developer to leave all the embedded container
          setup to the integration layer instead.</para>
          
        <para>
          See the <ulink url="http://arquillian.org/">Arquillian</ulink> and
          <ulink url="http://www.jboss.org/shrinkwrap">ShrinkWrap</ulink> web sites for a detailed description of
          the projects and additional documentation.
        </para>

        <section id="embedded_usage_simple_arquillian_shrinkwrap">
          <title>Arquillian and ShrinkWrap</title>

          <para>The code sample below shows an usage of deploying a ShrinkWrap resource adapter archive
            into the IronJacamar Embedded environment using Arquillian.</para>

          <programlisting language="java">
<xi:include parse="text" href="../../../../arquillian/src/test/java/org/jboss/jca/arquillian/unit/ArquillianTestCase.java" xmlns:xi="http://www.w3.org/2001/XInclude"/>
          </programlisting>

          <para>The class makes use of the <code>org.jboss.jca.embedded.arquillian.Configuration</code> annotation
             in order to specify that the deployed archive should be auto activated through the <code>RAActivator</code>
             bean.</para>

          <note>Note that, the name for the <code>ResourceAdapterArchive</code> must end with the
             <code>.rar</code> extension.</note>

        </section>

        <section id="embedded_usage_simple_arquillian_shrinkwrap_descriptors">
          <title>Arquillian and ShrinkWrap/Descriptors</title>

          <para>
            The code sample below shows how to use Arquillian to deploy a ShrinkWrap resource adapter archive
            and activate the resource adapter using the ShrinkWrap/Descriptors API.
          </para>

          <para>
            This example uses the <code>org.jboss.jca.embedded.arquillian.Configuration</code> annotation
            to explicit say not to auto activate the resource adapter archive.
          </para>

          <programlisting language="java">
<xi:include parse="text" href="../../../../embedded/src/test/java/org/jboss/jca/embedded/unit/ShrinkWrapDescriptorsTestCase.java" xmlns:xi="http://www.w3.org/2001/XInclude"/>
          </programlisting>

        </section>

        <section id="embedded_usage_simple_arquillian_byteman">
          <title>Arquillian and Byteman</title>

          <para>The code sample below shows how to use Arquillian to deploy a ShrinkWrap resource adapter archive
            and change the <code>allocateConnection</code> of <code>org.jboss.jca.core.connectionmanager.AbstractConnectionManager</code>
            to throw a <code>ResourceException</code> when the method is called.</para>

          <para>The framework used to provide this functionality is called Byteman, which allows developers to change
            behavior of a method to for example throw an exception. This is called fault injection and can be used to 
            increase code coverage of your project.</para>

          <programlisting language="java">
<xi:include parse="text" href="../../../../arquillian/src/test/java/org/jboss/jca/arquillian/unit/BytemanBMTestCase.java" xmlns:xi="http://www.w3.org/2001/XInclude"/>
          </programlisting>

          <para>
            See the <ulink url="http://www.jboss.org/byteman">Byteman</ulink> web site for a detailed description of
            the project and additional documentation.
          </para>

        </section>

        <section id="embedded_usage_simple_arquillian_resource">
          <title>Arquillian and @ArquillianResource</title>

          <para>The Arquillian integration allows the internally used <code>org.jboss.jca.embedded.Embedded</code> or
            <code>javax.naming.Context</code> instances to be injected into the test case using</para>

          <programlisting language="java">
<![CDATA[
import org.jboss.jca.embedded.Embedded;
import javax.naming.Context;
import org.jboss.arquillian.test.api.ArquillianResource;

@RunWith(Arquillian.class)
public class ResourceProviderTestCase
{
   @ArquillianResource
   private Embedded embedded;

   @ArquillianResource
   private Context context;
]]>
          </programlisting>

          <para>This will allow direct access to the APIs inside the test case.</para>

        </section>

        <section id="embedded_usage_simple_ironjacamar">
          <title>IronJacamar integration</title>

          <para>The code sample below shows how to use Arquillian to deploy a ShrinkWrap resource adapter archive
            and inject the IronJacamar metadata repository into the test case such that assertions can be made.</para>

          <para>The IronJacamar container features various components that makes up the entire Java EE Connector Architecture
            container. The available list of components can be viewed in the configuration of the container or through
            the management console under the <code>Kernel</code> category.</para>

          <programlisting language="java">
<xi:include parse="text" href="../../../../arquillian/src/test/java/org/jboss/jca/arquillian/unit/InjectTestCase.java" xmlns:xi="http://www.w3.org/2001/XInclude"/>
          </programlisting>

        </section>

      </section>

      <section id="embedded_usage_advanced">
        <title>Advanced usage</title>

        <section id="embedded_usage_advanced_shrinkwrap">
          <title>ShrinkWrap</title>

          <para>The code sample below shows an advanced usage of deploying a ShrinkWrap resource adapter archive
            into the IronJacamar Embedded environment.</para>

          <programlisting language="java">
<xi:include parse="text" href="../../../../embedded/src/test/java/org/jboss/jca/embedded/unit/ShrinkWrapTestCase.java" xmlns:xi="http://www.w3.org/2001/XInclude"/>
          </programlisting>
          
          <note>Note that, the name for the <code>ResourceAdapterArchive</code> must end with the
            <code>.rar</code> extension.</note>
        </section>

        <section id="embedded_usage_advanced_embedded">
          <title>Embedded</title>

          <para>The code sample below shows a simple usage of deploying a pre-assembled resource adapter archive
            into the IronJacamar Embedded environment.</para>

            <programlisting language="java">
import org.jboss.jca.embedded.Embedded;
import org.jboss.jca.embedded.EmbeddedFactory;

import java.net.URL;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;

public class MyTestCase
{
   /** Embedded */
   private static Embedded embedded;

   /** JNDI prefix */
   private static final String JNDI_PREFIX = "java:/eis/";

   /**
    * Simple test to verify deployment of myresourceadapter.rar
    * @throws Throwable throwable exception 
    */
   @Test
   public void testDeployment() throws Throwable
   {
      URL archive = MyTestCase.class.getResource("myresourceadapter.rar");
      Context context = null;
 
      try
      {
         embedded.deploy(archive);

         context = new InitialContext();
         Object o = context.lookup(JNDI_PREFIX + "myresourceadapter");
         assertNotNull(o);
      }
      catch (Throwable t)
      {
         fail(t.getMessage());
      }
      finally
      {
         embedded.undeploy(archive);

         if (context != null)
         {
            try
            {
               context.close();
            }
            catch (NamingException ne)
            {
               // Ignore
            }
         }
      }
   }

   @BeforeClass
   public static void beforeClass() throws Throwable
   {
      // Create an embedded JCA instance
      embedded = EmbeddedFactory.create();

      // Startup
      embedded.startup();
   }

   @AfterClass
   public static void afterClass() throws Throwable
   {
      // Shutdown
      embedded.shutdown();
   }
}
            </programlisting>
            
            <note>Note that, the url for the archive must end with the <code>.rar</code> extension
              - either representing a file or a directory.</note>
            
            <para>See the IronJacamar Embedded API documentation for additional functionality.</para>
        </section>

        <section id="embedded_usage_automaticactivation">
          <title>Automatic activation of archives</title>

          <para>IronJacamar features a bean called <code>RAActivator</code> which will automatic
            create a JNDI binding for connection factories and administration objects. However, 
            sometimes it is of benefit to define these bindings in a <code>-ra.xml</code> file, and therefore
            <code>RAActivator</code> has to be disabled during that deployment phase.</para>
          
          <para>This done by using the following code snippet</para>

          <programlisting language="java">
import org.jboss.jca.deployers.fungal.RAActivator;

// Disable RAActivator
RAActivator raa = embedded.lookup("RAActivator", RAActivator.class);

if (raa == null)
   throw new IllegalStateException("RAActivator not defined");

raa.setEnabled(false);

embedded.deploy("myrar.rar");
embedded.deploy("myrar-ra.xml");

raa.setEnabled(true);
          </programlisting>

          <para>which disables the bean, does the deployments and then reenables the bean again.</para>

        </section>

      </section>

   </section>

</chapter>
