Tag: JSP/Servlets

Invoking a Local Stateless Bean from a Servlet in JBoss AS7

Hi,

Here in this demo we will see how to lookup Local EJB3 stateless Bean from a separate Web Application’s Servlet. Where as the EAR containing the Stateless EJB3 and the WAR are separately deployed on the same JBoss AS7 instance. Here we will also discuss the use of different JNDI Names.

The JNDI names for EJB session beans are assigned by the container via the following scheme:

1). Global JNDI
java:global[/<app-name>l]/<module-name>/<bean-name>l[!<fully-qualified-interface-name>l]

java:global JNDI can be used to lookup a resource which is deployed on the same server but as part of a separate application.

2). Application JNDI
java:app/<module-name>l/<bean-name>l[!<fully-qualified-interface-name>l]

java:app JNDI can be used to lookup a resource which is deployed on the same server but as part of the same application.

3). Module JNDI
java:module/<bean-name>l[!<fully-qualified-interface-name>l]

java:module allows a component executing within a Java EE application to access a namespace rooted below the portion of the namespace corresponding to its module.

More details about portable JNDI can be found in the EJB3.1 JSR-318 specification: http://jcp.org/en/jsr/detail?id=318

In this example we will mainly focus on following points

Point-1). Here we are using JBoss AS7 latest build “jboss-as-7.1.0.Alpha2-SNAPSHOT” Download Location :  https://ci.jboss.org/jenkins/job/JBoss-AS-7.x-latest/

Point-2). How to use and develop Servlets without defining servlet-mapping inside the “web.xml” file, while using the @javax.servlet.annotation.WebServlet annotation.

Point-3). How to perform a Local EJB lookup which is deployed as part of a Separate EAR file, with the help of Global JNDI lookup using @javax.ejb.EJB (lookup=””) annotation.

=========

Step1). Create a directory somewhere in your filesystem like “/home/userone/EJB3_LocalLookup_Demo” where we will place our application build related stuff. Then create another directory “src” inside “/home/userone/EJB3_LocalLookup_Demo” where we will be placing our source codes for EJB and WAR files.

Step2). Now we will create a Local Bean Interface “CallerLocal.java” file and Place this file as wll inside the “/home/userone/EJB3_LocalLookup_Demo/src” directory as following:

package caller;
import javax.ejb.*;
@Remote
public interface CallerLocal
{
     public String testMethod(String name);
}

Step3). Now we will create a Simple Stateless EJB with a simple business method to test whether we can invoke this EJB Locally or not. so provide a class inside “/home/userone/EJB3_LocalLookup_Demo/src” directory with name “TestAsyncStatelessSessionBean.java” as following:

package caller;
import javax.ejb.*;
import javax.naming.*;
import java.util.*;
@Stateless(name = "CallerName", mappedName = "CallerMappedName")
public class CallerBean implements CallerLocal
 {
     public String testMethod(String name)
	    {
		   System.out.println("nnt Bean's testMethod(String name) called....");
		   return "[CallerBean] returned Hello "+name;
	    }
 }

Step4). Now we will write the “application.xml” file inside the “/home/userone/EJB3_LocalLookup_Demo” directory to define the EAR application and to define the EJB module inside it as following:

<?xml version="1.0" encoding="UTF-8"?>

<application xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:application="http://java.sun.com/xml/ns/javaee/application_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/application_5.xsd" id="Application_ID" version="5">
  <display-name>EJB3_localCallDemo</display-name>
  <module>
    <ejb>localEJB.jar</ejb>
  </module>
</application>

Step5). Create Servlet class “TestServlet.java” as following inside the “/home/userone/EJB3_LocalLookup_Demo/src” directory.

package servlets;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.ejb.*;
import javax.servlet.annotation.WebServlet;

@WebServlet(value="/TestServlet")
public class TestServlet extends HttpServlet
  {
     @EJB(lookup="java:global/TestLocalEJBEAR/localEJB/CallerName!caller.CallerLocal")
     private caller.CallerLocal local;
     public void service(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException
       {
            PrintWriter out=res.getWriter();
            out.println("caller.CallerLocal local = "+local);
            out.println("nn");
            out.println("local.testMethod() = "+local.testMethod("MiddlewareMagic"));
       }
  }

Step6). Now the most important part, here we are going to develop “build.xml” ANT file, which will build and deploy our EAR and the WAR applications separately on the JBoss AS7.1 Server, so write the following “build.xml” file inside “/home/userone/EJB3_LocalLookup_Demo” directory.

<project name="SingletonStartupService" default="all">
<property name="jboss.home" value="/home/userone/jboss-as-7.1.0.Alpha2-SNAPSHOT" />
<property name="jboss.module.dir" value="${jboss.home}/modules" />
<property name="basedir" value="." />
<property name="tmp.dir" value="tmp" />
<property name="src.dir" value="src" />
<property name="output.dir" value="build" />
<property name="ear.name" value="TestLocalEJBEAR.ear" />
<property name="war.name" value="TestWebApp.war" />
<property name="ejb.jar" value="localEJB.jar" />

   <path id="jboss.classpath">
     <fileset dir="${jboss.module.dir}">
        <include name="**/*.jar"/>
     </fileset>  
   </path>

        <target name="init">
           <delete dir="${output.dir}" />
           <mkdir dir="${output.dir}" />
           <delete dir="${tmp.dir}" />
           <mkdir dir="${tmp.dir}" />
        </target>
	 
        <target name="all" depends="deploy" />

        <target name="build_ear">
           <delete dir="${tmp.dir}" />
           <mkdir dir="${tmp.dir}" />
           <javac srcdir="${src.dir}" destdir="${tmp.dir}"  includes="*.java" classpathref="jboss.classpath"/>

           <jar jarfile="${tmp.dir}/${ejb.jar}" basedir="${tmp.dir}" compress="true" />

           <delete includeEmptyDirs="true">
              <fileset dir="${tmp.dir}/caller"/>
           </delete> 
           <mkdir dir="${tmp.dir}/META-INF"/>
           <copy todir="${tmp.dir}/META-INF">
                <fileset dir="${src.dir}/">
                  <include name="application.xml"/> 
                </fileset>
           </copy>           
           <jar jarfile="${tmp.dir}/${ear.name}" basedir="${tmp.dir}" compress="true" />
           <delete includeEmptyDirs="true">
              <fileset dir="${tmp.dir}/META-INF"/>
           </delete> 
           <delete file="${tmp.dir}/${ejb.jar}"/>

           <copy file="${tmp.dir}/${ear.name}" tofile="${output.dir}/${ear.name}"/>
           <delete file="${tmp.dir}/${ear.name}"/>
        </target>


        <target name="build_war">
           <delete dir="${tmp.dir}" />
           <mkdir dir="${tmp.dir}/WEB-INF/classes" />
           <javac srcdir="${src.dir}" destdir="${tmp.dir}/WEB-INF/classes"  includes="CallerLocal.java,TestServlet.java" classpathref="jboss.classpath"/>
           <jar jarfile="${output.dir}/${war.name}" basedir="${tmp.dir}" compress="true" />
        </target>        

        <target name="deploy" depends="build_ear,build_war">
            <echo message="*******************  Deploying the EAR file ${ear.name} *********************" />  
            <echo message="********** ${output.dir}/${ear.name} to ${jboss.home}/standalone/deployments **********" />  
            <copy todir="${jboss.home}/standalone/deployments/">
                <fileset dir="${output.dir}/">
                  <include name="${ear.name}"/> 
                </fileset>
            </copy>
            <echo message="*******************  Deployed Successfully   *********************" />  
            <echo message="*******************  Deploying the WAR file ${war.name} *********************" />  
            <echo message="********** ${output.dir}/${war.name} to ${jboss.home}/standalone/deployments **********" />  
            <copy todir="${jboss.home}/standalone/deployments/">
                <fileset dir="${output.dir}/">
                  <include name="${war.name}"/> 
                </fileset>
            </copy>
            <echo message="*******************  Deployed Successfully   *********************" />  

        </target>
</project>


NOTE: The only change in the above file you need to do is to change the “jboss.home” directory path in the second line of the above script is to point to your own JBoss AS7 directory home directory.

Step7). Now before running your ANT script to build and deploy the above webapplication you should have the ANT as well as JAVA set in the $PATH variable of the Shell / command prompt as following:

For Unix Based OS:
export PATH=/home/userone/jdk1.6.0_21/bin:/home/userone/org.apache.ant_1.6.5/bin:$PATH

For Windows Based OS:
set PATH=C:/jdk1.6.0_21/bin;C:/org.apache.ant_1.6.5/bin;%PATH%

Step8). Now once the PATH is set In the command/Shell prompt you can move inside the directory “/home/userone/EJB3_LocalLookup_Demo” and then run the ant to build the webservice. by running the command “ant build”

[userone@localhost EJB3_LocalLookup_Demo]$ ant deploy
Buildfile: build.xml

build_ear:
   [delete] Deleting directory /home/userone/EJB3_LocalLookup_Demo/tmp
    [mkdir] Created dir: /home/userone/EJB3_LocalLookup_Demo/tmp
    [javac] Compiling 3 source files to /home/userone/EJB3_LocalLookup_Demo/tmp
      [jar] Building jar: /home/userone/EJB3_LocalLookup_Demo/tmp/localEJB.jar
    [mkdir] Created dir: /home/userone/EJB3_LocalLookup_Demo/tmp/META-INF
     [copy] Copying 1 file to /home/userone/EJB3_LocalLookup_Demo/tmp/META-INF
      [jar] Building jar: /home/userone/EJB3_LocalLookup_Demo/tmp/TestLocalEJBEAR.ear
   [delete] Deleting: /home/userone/EJB3_LocalLookup_Demo/tmp/localEJB.jar
     [copy] Copying 1 file to /home/userone/EJB3_LocalLookup_Demo/build
   [delete] Deleting: /home/userone/EJB3_LocalLookup_Demo/tmp/TestLocalEJBEAR.ear

build_war:
   [delete] Deleting directory /home/userone/EJB3_LocalLookup_Demo/tmp
    [mkdir] Created dir: /home/userone/EJB3_LocalLookup_Demo/tmp/WEB-INF/classes
    [javac] Compiling 2 source files to /home/userone/EJB3_LocalLookup_Demo/tmp/WEB-INF/classes
      [jar] Building jar: /home/userone/EJB3_LocalLookup_Demo/build/TestWebApp.war

deploy:
     [echo] *******************  Deploying the EAR file TestLocalEJBEAR.ear *********************
     [echo] ********** build/TestLocalEJBEAR.ear to /home/userone/jboss-as-7.1.0.Alpha2-SNAPSHOT/standalone/deployments **********
     [copy] Copying 1 file to /home/userone/jboss-as-7.1.0.Alpha2-SNAPSHOT/standalone/deployments
     [echo] *******************  Deployed Successfully   *********************
     [echo] *******************  Deploying the WAR file TestWebApp.war *********************
     [echo] ********** build/TestWebApp.war to /home/userone/jboss-as-7.1.0.Alpha2-SNAPSHOT/standalone/deployments **********
     [copy] Copying 1 file to /home/userone/jboss-as-7.1.0.Alpha2-SNAPSHOT/standalone/deployments
     [echo] *******************  Deployed Successfully   *********************

all:

BUILD SUCCESSFUL
Total time: 2 seconds

Step9). Now you will see the following kind of output on your JBoss AS7.1 console which means the applications EAR and the WAR are deployed successfully :

15:39:18,399 INFO  [org.jboss.as.server.deployment] (MSC service thread 1-1) Starting deployment of "TestLocalEJBEAR.ear"
15:39:18,407 INFO  [org.jboss.as.server.deployment] (MSC service thread 1-8) Starting deployment of "localEJB.jar"
15:39:18,438 INFO  [org.jboss.as.ejb3.deployment.processors.EjbJndiBindingsDeploymentUnitProcessor] (MSC service thread 1-6) JNDI bindings for session bean named CallerName in deployment unit subdeployment "localEJB.jar" of deployment "TestLocalEJBEAR.ear" are as follows:

	java:global/TestLocalEJBEAR/localEJB/CallerName!caller.CallerLocal
	java:app/localEJB/CallerName!caller.CallerLocal
	java:module/CallerName!caller.CallerLocal
	java:global/TestLocalEJBEAR/localEJB/CallerName
	java:app/localEJB/CallerName
	java:module/CallerName

15:39:18,468 INFO  [org.jboss.web] (MSC service thread 1-3) registering web context: /TestWebApp
15:39:18,483 INFO  [org.jboss.as.server.controller] (DeploymentScanner-threads - 2) Replaced deployment "TestLocalEJBEAR.ear" with deployment "TestLocalEJBEAR.ear"
15:39:18,483 INFO  [org.jboss.as.server.controller] (DeploymentScanner-threads - 2) Replaced deployment "TestWebApp.war" with deployment "TestWebApp.war"

Step10). Now access the WebApplication like following : http://localhost:8080//TestWebApp/TestServlet Now you will be able to access the TestServlet which is internally invoking a Business Method of a Local Stateless Bean deployed as part of a Separate EAR file.

NOTE: JBoss AS7 is a Community release and we always recommend you to use the RedHat Supported JBoss Enterprise Application Platform, There are various reasons behind this. Please refer to the Video: http://www.youtube.com/watch?v=iNFV0r9v14g&feature=player_detailpage

.
.
Thanks
Middleware Magic Team


JBoss AS7 with Async Servlet And Async EJB3

Hi,

As JBoss AS7 is very new And most powerful application server with many changes in it. Here we are going to see a very simple demo of how we can develop, build, deploy and test a simple Asynchronous Servlet and Asynchronous EJB3 inside a WAR file. (Which is the New Feature of Servlet Specification 3.0). One of the major changes in the Servlet Specification 3.0 is the support for Asynchronous Servlets: http://jcp.org/en/jsr/detail?id=315 …

This feature is very much desired when we invoke a long running process (like an EJB) from our Servlet, we want that the servlet should start the EJB execution in a separate process and should get back to the client as soon as possible.

In this example we will mainly focus on following points

Point-1). Here we are using JBoss AS7 latest build “jboss-as-7.1.0.Alpha2-SNAPSHOT”

Point-2). How to use and develop Asynchronous Servlets.

Point-3). How to use and develop Asynchronous EJBs with the help of javax.ejb.Asynchronous annotation.

Point-4). Also we will see how to place an Stateless Session Bean inside a WAR file.

Point-5). How to invoke an EJB3 from a Servlet which are present inside the same application. Using javax.ejb.EJB anotations lookup attribute.

Point-6). How to develop a Web Application without writing “web.xml”, rather using the Annotations to provide the servlet mapping and declaration.

Step1). Create a directory somewhere in your filesystem like “/home/userone/EE6_Async_Servlet_Demo” where we will place our application build related stuff. Then create another directory “src” inside “/home/userone/EE6_Async_Servlet_Demo” where we will be placing our source codes and JSPs.

Step2). Create Servlet class “TestAsyncServlet.java” as following inside the “/home/userone/EE6_Async_Servlet_Demo/src” directory.

package servlets;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.inject.Inject;
import javax.servlet.AsyncContext;
import javax.servlet.annotation.WebServlet;
import javax.ejb.EJB;

@WebServlet(value="/TestAsyncServletURL", asyncSupported=true)
public class TestAsyncServlet extends HttpServlet
  {
       @EJB (lookup="java:module/TestAsyncStatelessSessionBean!ejb3.TestAsyncStatelessSessionBean")
       private ejb3.TestAsyncStatelessSessionBean testAsyncStatelessSessionBean;

       public void service(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException
        {
            Logger logger = Logger.getLogger(TestAsyncServlet.class.getName());
            PrintWriter out=response.getWriter();

            logger.log(Level.INFO, "TestAsyncServlet inside service(req,res)");
            logger.log(Level.INFO, "TestAsyncServlet inside ThreadName : "+Thread.currentThread().getName());

            // Calling startAsync() method on servlet indicates that we are associating request in Async Mode
            AsyncContext asyncContext = request.startAsync();

            // Here the main execution of the following EJB method will run in a separate thread
            testAsyncStatelessSessionBean.executeLongTask(asyncContext);
            String data="";
            for(int i=0;i<10;i++)
             {
                String threadName=Thread.currentThread().getName();
                System.out.println("tTestAsyncServlet service() at "+new java.util.Date()+"t"+threadName);
                try{   Thread.sleep(500); } catch(Exception e){ e.printStackTrace(); }
             }
            out.println("ServletRequest is Processed ... !!!<font color=red>But EJB still might be processing</font>");
            out.close();
        }
  }

Step3). Now we will create a Simple Stateless EJB with a Long running Method so provide a class inside “/home/userone/EE6_Async_Servlet_Demo/src” directory with name “TestAsyncStatelessSessionBean.java” as following:

package ejb3;
import javax.ejb.Asynchronous;
import javax.ejb.Stateless;
import javax.servlet.AsyncContext;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;

@Stateless
public class TestAsyncStatelessSessionBean
  {
     private Logger logger = Logger.getLogger(TestAsyncStatelessSessionBean.class.getName());

     @Asynchronous
     public void executeLongTask(AsyncContext asyncContext)
      {
           String data="";
           try {
                 for(int i=0;i<10;i++)
                  {
                     String threadName=Thread.currentThread().getName();
                     logger.log(Level.INFO,i+"t EJB3 executeLongTask(asyncContext) at "+new java.util.Date()+"t"+threadName);
                     Thread.sleep(2000);
                     data=data+"n"+i+"t EJB3 executeLongTask(asyncContext) at "+new java.util.Date()+"t"+threadName;
                  }
           System.out.println("[EJB Processing is done] : "+data);
           asyncContext.complete();

       } catch (Exception e) {
           logger.log(Level.SEVERE, e.getMessage(), e);
       }
      }
  }

Step4). Now we will write a simple “index.jsp” page just to point to the Servlet, Place this file as wll inside the “/home/userone/EE6_Async_Servlet_Demo/src” directory as following:

<html>
   <body>
     <center>
        <h1> Welcome Page </h1>
        <h3><font color=maroon><a href="TestAsyncServletURL">Click Here to Access TestAsyncServlet</a></font></h3>
     </center>
  </body>
</html>

Step5). Now the most important part, here we are going to develop “build.xml” ANT file, which will build, deployour webapplication on the JBoss AS7.1 Server, so write the following “build.xml” file inside “/home/userone/EE6_Async_Servlet_Demo” directory.

<project name="SingletonStartupService" default="deploy">
<property name="jboss.home" value="/home/userone/jboss-as-7.1.0.Alpha2-SNAPSHOT" />
<property name="jboss.module.dir" value="${jboss.home}/modules" />
<property name="basedir" value="." />
<property name="tmp.dir" value="tmp" />
<property name="output.dir" value="build" />
<property name="src.dir" value="src" />
<property name="war.name" value="EE6Feature_AsyncServletAndEJB.war" />

   <path id="jboss.classpath">
     <fileset dir="${jboss.module.dir}">
        <include name="**/*.jar"/>
     </fileset>
   </path>

        <target name="init">
           <delete dir="${output.dir}" />
           <mkdir dir="${output.dir}" />
           <delete dir="${tmp.dir}" />
           <mkdir dir="${tmp.dir}" />
        </target>

        <target name="build" depends="init">
           <mkdir dir="${tmp.dir}/WEB-INF/classes"/>
           <javac srcdir="${src.dir}" destdir="${tmp.dir}/WEB-INF/classes"  includes="*.java" classpathref="jboss.classpath" />

          <copy file="${src.dir}/index.jsp" tofile="${tmp.dir}/index.jsp"/>
          <copy file="${src.dir}/TestAsyncServlet.java" tofile="${tmp.dir}/WEB-INF/classes"/>
          <copy file="${src.dir}/TestAsyncStatelessSessionBean.java" tofile="${tmp.dir}/WEB-INF/classes"/>

           <jar jarfile="${tmp.dir}/${war.name}" basedir="${tmp.dir}" compress="true" />
           <copy file="${tmp.dir}/${war.name}" tofile="${output.dir}/${war.name}"/>
           <delete includeEmptyDirs="true">
              <fileset dir="${tmp.dir}"/>
           </delete>
        </target>

        <target name="deploy" depends="build">
            <echo message="*******************  Deploying the WAR file ${war.name} *********************" />
            <echo message="********** ${output.dir}/${war.name} to ${jboss.home}/standalone/deployments **********" />
            <copy todir="${jboss.home}/standalone/deployments/">
                <fileset dir="${output.dir}/">
                  <include name="${war.name}"/>
                </fileset>
            </copy>
            <echo message="*******************  Deployed Successfully   *********************" />
        </target>
</project>

NOTE: The only change in the above file you need to do is to change the “jboss.home” directory path in the second line of the above script, to point to your own JBoss AS7 directory.

Step6). Now before running your ANT script to build and deploy the above webapplication you should have the ANT as well as JAVA set in the $PATH variable of the Shell / command prompt as following:

For Unix Based OS:
export PATH=/home/userone/jdk1.6.0_21/bin:/home/userone/org.apache.ant_1.6.5/bin:$PATH

For Windows Based OS:
set PATH=C:/jdk1.6.0_21/bin;C:/org.apache.ant_1.6.5/bin;%PATH%

Step7). Now once the PATH is set In the command/Shell prompt you can move inside the directory “/home/userone/EE6_Async_Servlet_Demo” and then run the ant to build the webservice. by running the command “ant build”

[userone@localhost EE6_Async_Servlet_Demo]$ ant deploy
Buildfile: build.xml

init:
   [delete] Deleting directory /home/userone/EE6_Async_Servlet_Demo/build
    [mkdir] Created dir: /home/userone/EE6_Async_Servlet_Demo/build
    [mkdir] Created dir: /home/userone/EE6_Async_Servlet_Demo/tmp

build:
    [mkdir] Created dir: /home/userone/EE6_Async_Servlet_Demo/tmp/WEB-INF/classes
    [javac] Compiling 2 source files to /home/userone/EE6_Async_Servlet_Demo/tmp/WEB-INF/classes
     [copy] Copying 1 file to /home/userone/EE6_Async_Servlet_Demo/tmp
      [jar] Building jar: /home/userone/EE6_Async_Servlet_Demo/tmp/EE6Feature_AsyncServletAndEJB.war
     [copy] Copying 1 file to /home/userone/EE6_Async_Servlet_Demo/build

deploy:
     [echo] *******************  Deploying the WAR file EE6Feature_AsyncServletAndEJB.war *********************
     [echo] ********** build/EE6Feature_AsyncServletAndEJB.war to /home/userone/jboss-as-7.1.0.Alpha2-SNAPSHOT/standalone/deployments **********
     [copy] Copying 1 file to /home/userone/jboss-as-7.1.0.Alpha2-SNAPSHOT/standalone/deployments
     [echo] *******************  Deployed Successfully   *********************

BUILD SUCCESSFUL

Step8). Now you will see the following kind of output on your JBoss AS7.1 console which means the application is deployed successfully:

12:46:26,905 INFO  [org.jboss.as.server.deployment] (MSC service thread 1-8) Starting deployment of "EE6Feature_AsyncServletAndEJB.war"
12:46:26,928 INFO  [org.jboss.as.ejb3.deployment.processors.EjbJndiBindingsDeploymentUnitProcessor] (MSC service thread 1-6) JNDI bindings for session bean named TestAsyncStatelessSessionBean in deployment unit deployment "EE6Feature_AsyncServletAndEJB.war" are as follows:

	java:global/EE6Feature_AsyncServletAndEJB/TestAsyncStatelessSessionBean!ejb3.TestAsyncStatelessSessionBean
	java:app/EE6Feature_AsyncServletAndEJB/TestAsyncStatelessSessionBean!ejb3.TestAsyncStatelessSessionBean
	java:module/TestAsyncStatelessSessionBean!ejb3.TestAsyncStatelessSessionBean
	java:global/EE6Feature_AsyncServletAndEJB/TestAsyncStatelessSessionBean
	java:app/EE6Feature_AsyncServletAndEJB/TestAsyncStatelessSessionBean
	java:module/TestAsyncStatelessSessionBean

12:46:26,966 INFO  [org.jboss.web] (MSC service thread 1-2) registering web context: /EE6Feature_AsyncServletAndEJB
12:46:26,974 INFO  [org.jboss.as.server.controller] (DeploymentScanner-threads - 1) Replaced deployment "EE6Feature_AsyncServletAndEJB.war" with deployment "EE6Feature_AsyncServletAndEJB.war"

Step9). Now access the WebApplication like following : http://localhost:8080/EE6Feature_AsyncServletAndEJB

As soon as you will access the Servlet “http://localhost:8080/EE6Feature_AsyncServletAndEJB/TestAsyncServletURL” you will see the following kind of output …which indicates that the Servlet is being executed by Thread “http-localhost-127.0.0.1-8080-3” whereas the EJB invocation which is done through the Servlet is being executed by a Separate Thread “pool-8-thread-10”

12:48:13,063 INFO  [servlets.TestAsyncServlet] (http-localhost-127.0.0.1-8080-3) TestAsyncServlet inside service(req,res)
12:48:13,064 INFO  [servlets.TestAsyncServlet] (http-localhost-127.0.0.1-8080-3) TestAsyncServlet inside ThreadName : http-localhost-127.0.0.1-8080-3
12:48:13,065 INFO  [stdout] (http-localhost-127.0.0.1-8080-3) 	TestAsyncServlet service() at Sun Nov 20 12:48:13 IST 2011	http-localhost-127.0.0.1-8080-3
12:48:13,065 INFO  [ejb3.TestAsyncStatelessSessionBean] (pool-8-thread-10) 0	 EJB3 executeLongTask(asyncContext) at Sun Nov 20 12:48:13 IST 2011	pool-8-thread-10
12:48:13,566 INFO  [stdout] (http-localhost-127.0.0.1-8080-3) 	TestAsyncServlet service() at Sun Nov 20 12:48:13 IST 2011	http-localhost-127.0.0.1-8080-3
12:48:14,067 INFO  [stdout] (http-localhost-127.0.0.1-8080-3) 	TestAsyncServlet service() at Sun Nov 20 12:48:14 IST 2011	http-localhost-127.0.0.1-8080-3
12:48:14,567 INFO  [stdout] (http-localhost-127.0.0.1-8080-3) 	TestAsyncServlet service() at Sun Nov 20 12:48:14 IST 2011	http-localhost-127.0.0.1-8080-3
12:48:15,066 INFO  [ejb3.TestAsyncStatelessSessionBean] (pool-8-thread-10) 1	 EJB3 executeLongTask(asyncContext) at Sun Nov 20 12:48:15 IST 2011	pool-8-thread-10
12:48:15,068 INFO  [stdout] (http-localhost-127.0.0.1-8080-3) 	TestAsyncServlet service() at Sun Nov 20 12:48:15 IST 2011	http-localhost-127.0.0.1-8080-3
12:48:15,608 INFO  [stdout] (http-localhost-127.0.0.1-8080-3) 	TestAsyncServlet service() at Sun Nov 20 12:48:15 IST 2011	http-localhost-127.0.0.1-8080-3
12:48:16,108 INFO  [stdout] (http-localhost-127.0.0.1-8080-3) 	TestAsyncServlet service() at Sun Nov 20 12:48:16 IST 2011	http-localhost-127.0.0.1-8080-3
12:48:16,609 INFO  [stdout] (http-localhost-127.0.0.1-8080-3) 	TestAsyncServlet service() at Sun Nov 20 12:48:16 IST 2011	http-localhost-127.0.0.1-8080-3
12:48:17,067 INFO  [ejb3.TestAsyncStatelessSessionBean] (pool-8-thread-10) 2	 EJB3 executeLongTask(asyncContext) at Sun Nov 20 12:48:17 IST 2011	pool-8-thread-10
12:48:17,110 INFO  [stdout] (http-localhost-127.0.0.1-8080-3) 	TestAsyncServlet service() at Sun Nov 20 12:48:17 IST 2011	http-localhost-127.0.0.1-8080-3
12:48:17,610 INFO  [stdout] (http-localhost-127.0.0.1-8080-3) 	TestAsyncServlet service() at Sun Nov 20 12:48:17 IST 2011	http-localhost-127.0.0.1-8080-3
12:48:19,068 INFO  [ejb3.TestAsyncStatelessSessionBean] (pool-8-thread-10) 3	 EJB3 executeLongTask(asyncContext) at Sun Nov 20 12:48:19 IST 2011	pool-8-thread-10
12:48:21,068 INFO  [ejb3.TestAsyncStatelessSessionBean] (pool-8-thread-10) 4	 EJB3 executeLongTask(asyncContext) at Sun Nov 20 12:48:21 IST 2011	pool-8-thread-10
12:48:23,069 INFO  [ejb3.TestAsyncStatelessSessionBean] (pool-8-thread-10) 5	 EJB3 executeLongTask(asyncContext) at Sun Nov 20 12:48:23 IST 2011	pool-8-thread-10
12:48:25,070 INFO  [ejb3.TestAsyncStatelessSessionBean] (pool-8-thread-10) 6	 EJB3 executeLongTask(asyncContext) at Sun Nov 20 12:48:25 IST 2011	pool-8-thread-10
12:48:27,071 INFO  [ejb3.TestAsyncStatelessSessionBean] (pool-8-thread-10) 7	 EJB3 executeLongTask(asyncContext) at Sun Nov 20 12:48:27 IST 2011	pool-8-thread-10
12:48:29,072 INFO  [ejb3.TestAsyncStatelessSessionBean] (pool-8-thread-10) 8	 EJB3 executeLongTask(asyncContext) at Sun Nov 20 12:48:29 IST 2011	pool-8-thread-10
12:48:31,073 INFO  [ejb3.TestAsyncStatelessSessionBean] (pool-8-thread-10) 9	 EJB3 executeLongTask(asyncContext) at Sun Nov 20 12:48:31 IST 2011	pool-8-thread-10

NOTE:  JBoss AS7 is a Community release  and we always recommend you to use the RedHat Supported JBoss Enterprise Application Platform, There are various reasons behind this. Please refer to the Video:  http://www.youtube.com/watch?v=iNFV0r9v14g&feature=player_detailpage

.
Thanks
Middleware Magic Team


EE6 feature @Resource(lookup=”string”) in JBoss AS7

Hi,

Here we are going to see the usecase of EE6 specific javax.annotation.Resource annotation in JBoss AS7, The Resource annotation marks a resource that is needed by the application. This annotation may be applied to an application component class, or to fields or methods of the component class. When the annotation is applied to a field or method, the container will inject an instance of the requested resource into the application component when the component is initialized. If the annotation is applied to the component class, the annotation declares a resource that the application will look up at runtime.

More informations about this annotation can be found in the following link: http://download.oracle.com/javaee/6/api/javax/annotation/Resource.html#lookup() . Here we will discuss a very common issue related to the usecase of this annotation because most of the developers fall into Compilation issue while using this annotation inside their application code. As following:

build:
    [mkdir] Created dir: /home/userone/TestEE6FeatureApp/tmp/WEB-INF/classes
    [javac] Compiling 1 source file to /home/userone/TestEE6FeatureApp/tmp/WEB-INF/classes
    [javac] /home/userone/TestEE6FeatureApp/src/TestServlet.java:8: cannot find symbol
    [javac] symbol  : method lookup()
    [javac] location: @interface javax.annotation.Resource
    [javac]        @Resource(lookup="java:app/env/testing")
    [javac]                  ^
    [javac] 1 error

OR

TestServlet.java:8: cannot find symbol
symbol  : method lookup()
location: @interface javax.annotation.Resource
       @Resource(lookup="java:app/env/testing")

NOTE: the compile time issue occurs because the JDK API’s “javax.annotation.Resource” annotation does not contain any attribute with name “lookup”. So we need to make sure that you include the “jboss-annotations-api_1.1_spec-1.0.0.Final.jar” location in the “-endorseddirs” endorsed directory argument of the Java Comiler because the JDK APIs also contains the annotation “@javax.annotation.Resource”..but the JDK APIs do not have the “lookup” attribute in ther annotations.

Location of the JAR in JBoss AS7:
/home/userone/jboss-as-7.0.1.Final/modules/javax/annotation/api/main/jboss-annotations-api_1.1_spec-1.0.0.Final.jar

Example of Compilation:
javac -endorseddirs /home/userone/boss-as-7.0.1.Final/modules/javax/annotation/api/main -d . TestServlet.java

Here we will see how to compile and test the same application using ANT script in JBoss AS7.
Step1). Create a directory somewhere in your file system like “/home/userone/TestEE6FeatureApp”

Step2). Now create a directory with name “src” inside the “/home/userone/TestEE6FeatureApp” and then place the following kind of “web.xml” file inside the “src” folder.

<?xml version="1.0"?>
<web-app version="2.5"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
   <servlet>
       <servlet-name>TestServlet</servlet-name>
       <servlet-class>servlets.TestServlet</servlet-class>
   </servlet>
   <servlet-mapping>
       <servlet-name>TestServlet</servlet-name>
       <url-pattern>/TestServlet</url-pattern>
   </servlet-mapping>

   <welcome-file-list>
      <welcome-file>index.jsp</welcome-file>
   </welcome-file-list>

   <env-entry>
      <description>Application Log Directory and fileName</description>
      <env-entry-name>java:app/env/testing</env-entry-name>
      <env-entry-type>java.lang.String</env-entry-type>
      <env-entry-value>/home/userone/TestApp/app.log</env-entry-value>
   </env-entry>
</web-app>

Step3). Now write a Servlet where we will try to lookup the mentioned in the above web.xml file. So we will create a Servlet with name “TestServlet.java” inside “/home/userone/TestEE6FeatureApp/src” directory as following:

package servlets;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import javax.annotation.Resource;
public class TestServlet extends HttpServlet
  {
       @Resource(lookup="java:app/env/testing")
       private String logFile;
       public void service(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException
        {
            PrintWriter out=response.getWriter();
            out.println("@javax.annotation.Resource(lookup="java:app/env/testing") ");
            out.println("private String logFile;");
            out.println("Got the logFile = "+logFile);
        }
  }

/*
How to compile above program ?
Make sure that you include the "jboss-annotations-api_1.1_spec-1.0.0.Final.jar" location in the "-endorseddirs" endorsed directory argument of the Java Comiler because the JDK APIs also contains the annotation "@javax.annotation.Resource"..but the JDK APIs do not have the "lookup" attribute in ther annotations.

Location of the JAR:
/home/userone/jboss-as-7.0.1.Final/modules/javax/annotation/api/main/jboss-annotations-api_1.1_spec-1.0.0.Final.jar

Example:
javac -endorseddirs /home/userone/boss-as-7.0.1.Final/modules/javax/annotation/api/main -d . TestServlet.java
*/

Step4). Now we will simply write a Simle JSP “index.jsp” to invoke this Servlet. Place the following JSP file inside “/home/userone/TestEE6FeatureApp/src”

<html>
<body>
<center><h1> Welcome Page </h1>
<h3><font color=maroon><a href="TestServlet">Click Here to Access TestServlet</a>
To check following code is working or not</font></h3>
</center>

<BR>
@javax.annotation.Resource(lookup="java:app/env/testing");
<BR>
private String logFile;
</body>
</html>

Step5). Now we will write a Simple ANT Build script “build.xml” file to build the WAR file and then to deploy the application on JBoss AS7. place the following “build.xml” file inside “/home/userone/TestEE6FeatureApp”

<project name="SingletonStartupService" default="deploy">
<property name="jboss.home" value="/home/userone/boss-as-7.0.1.Final" />
<property name="jboss.module.dir" value="${jboss.home}/modules" />
<property name="basedir" value="." />
<property name="tmp.dir" value="tmp" />
<property name="output.dir" value="build" />
<property name="src.dir" value="src" />
<property name="war.name" value="TestEE6Feature.war" />

   <path id="jboss.classpath">
     <fileset dir="${jboss.module.dir}">
        <include name="**/*.jar"/>
     </fileset>
   </path>

        <target name="init">
           <delete dir="${output.dir}" />
           <mkdir dir="${output.dir}" />
           <delete dir="${tmp.dir}" />
           <mkdir dir="${tmp.dir}" />
        </target>

        <target name="build" depends="init">
           <mkdir dir="${tmp.dir}/WEB-INF/classes"/>
           <javac srcdir="${src.dir}" destdir="${tmp.dir}/WEB-INF/classes"  includes="*.java" classpathref="jboss.classpath">
                <compilerarg value="-Djava.endorsed.dirs=${jboss.module.dir}/javax/annotation/api/main"/>
               <!--
                NOTE:
                   Make sure that you include the "jboss-annotations-api_1.1_spec-1.0.0.Final.jar" location in the
                   "-endorseddirs" endorsed directory argument of the Java Comiler because the JDK APIs also contains
                   the annotation "@javax.annotation.Resource"..but the JDK APIs do not have the "lookup" attribute in ther annotations.

                   Location of the JAR:
                   jboss-as-7.0.1.Final/modules/javax/annotation/api/main/jboss-annotations-api_1.1_spec-1.0.0.Final.jar

                   Example:
                   javac -endorseddirs /home/userone/boss-as-7.0.1.Final/modules/javax/annotation/api/main -d . TestServlet.java
               -->
           </javac>

           <copy todir="${tmp.dir}/WEB-INF">
                <fileset dir="${src.dir}/">
                  <include name="web.xml"/>
                </fileset>
           </copy>
          <copy file="${src.dir}/index.jsp" tofile="${tmp.dir}/index.jsp"/>
          <copy file="${src.dir}/TestServlet.java" tofile="${tmp.dir}/WEB-INF/classes/TestServlet.java"/>
           <copy todir="${tmp.dir}/WEB-INF">
                <fileset dir="${src.dir}/">
                  <include name="web.xml"/>
                </fileset>
           </copy>
           <jar jarfile="${tmp.dir}/${war.name}" basedir="${tmp.dir}" compress="true" />
           <copy file="${tmp.dir}/${war.name}" tofile="${output.dir}/${war.name}"/>
           <delete includeEmptyDirs="true">
              <fileset dir="${tmp.dir}"/>
           </delete>
        </target>

        <target name="deploy" depends="build">
            <echo message="*******************  Deploying the WAR file ${war.name} *********************" />
            <echo message="********** ${output.dir}/${war.name} to ${jboss.home}/standalone/deployments **********" />
            <copy todir="${jboss.home}/standalone/deployments/">
                <fileset dir="${output.dir}/">
                  <include name="${war.name}"/>
                </fileset>
            </copy>
            <echo message="*******************  Deployed Successfully   *********************" />
        </target>
</project>

NOTICE: In the above ANT script we have set the Compiler argument with the endorsed directory PATH as <compilerarg value=”-Djava.endorsed.dirs=${jboss.module.dir}/javax/annotation/api/main”/>

Step6). Now open a Shell prompt and then set the PATH pointing to the ANT bin directory and the JDK bin directory … like following and the just run the “ant” command:

For Unix Based OS:
export PATH=/home/userone/jdk1.6.0_21/bin:/home/userone/org.apache.ant_1.6.5/bin:$PATH

OR

For Windows Based OS:
set PATH=C:/jdk1.6.0_21/bin;C:/org.apache.ant_1.6.5/bin;%PATH%

[userone@localhost TestEE6Feature]$ ant
Buildfile: build.xml

init:
   [delete] Deleting directory /home/userone/TestEE6FeatureApp/build
    [mkdir] Created dir: /home/userone/TestEE6FeatureApp/build
    [mkdir] Created dir: /home/userone/TestEE6FeatureApp/tmp

build:
    [mkdir] Created dir: /home/userone/TestEE6FeatureApp/tmp/WEB-INF/classes
    [javac] Compiling 1 source file to /home/userone/TestEE6FeatureApp/tmp/WEB-INF/classes
     [copy] Copying 1 file to /home/userone/TestEE6FeatureApp/tmp/WEB-INF
     [copy] Copying 1 file to /home/userone/TestEE6FeatureApp/tmp
     [copy] Copying 1 file to /home/userone/TestEE6FeatureApp/tmp/WEB-INF/classes
      [jar] Building jar: /home/userone/TestEE6FeatureApp/tmp/TestEE6Feature.war
     [copy] Copying 1 file to /home/userone/TestEE6FeatureApp/build
   [delete] Deleting 5 files from /home/userone/TestEE6FeatureApp/tmp
   [delete] Deleted 4 directories from /home/userone/TestEE6FeatureApp/tmp

deploy:
     [echo] *******************  Deploying the WAR file TestEE6Feature.war *********************
     [echo] ********** build/TestEE6Feature.war to /home/userone/boss-as-7.0.1.Final/standalone/deployments **********
     [copy] Copying 1 file to /home/userone/boss-as-7.0.1.Final/standalone/deployments
     [echo] *******************  Deployed Successfully   *********************

BUILD SUCCESSFUL
Total time: 2 seconds

The only change you will need to make is to change the “jboss.home” value in the above ANT build.xml file to point to your own JBoss AS& directory.

Step7). Start the JBoss AS& like following from inside your “/home/userone/jboss-as-7.0.1.Final/bin” directory.

   ./standalone.sh --server-config standalone-preview.xml

.
.
Thanks
Middleware Magic Team


Copyright © 2010-2012 Middleware Magic. All rights reserved. |