Sunday Aug 16, 2009

TOTD #95: EJB 3.1 + Java Server Faces 2.0 + JPA 2.0 web application - Getting Started with Java EE 6 using NetBeans 6.8 M1 & GlassFish v3


TOTD #93 showed how to get started with Java EE 6 using NetBeans 6.8 M1 and GlassFish v3 by building a simple Servlet 3.0 + JPA 2.0 web application. TOTD #94 built upon it by using Java Server Faces 2 instead of Servlet 3.0 for displaying the results. However we are still using a POJO for all the database interactions. This works fine if we are only reading values from the database but that's not how a typical web application behaves. The web application would typically perform all CRUD operations. More typically they like to perform one or more CRUD operations within the context of a transaction. And how do you do transactions in the context of a web application ? Java EE 6 comes to your rescue.

The EJB 3.1 specification (another new specification in Java EE 6) allow POJO classes to be annotated with @EJB and bundled within WEB-INF/classes of a WAR file. And so you get all transactional capabilities in your web application very easily.

This Tip Of The Day (TOTD) shows how to enhance the application created in TOTD #94 and use EJB 3.1 instead of the JSF managed bean for performing the business logic. There are two ways to achieve this pattern as described below.

Lets call this TOTD #95.1
  1. The easiest way to back a JSF page with an EJB is to convert the managed bean into an EJB by adding @javax.ejb.Stateless annotation. So change the  "StateList" class from TOTD #94 as shown below:

    @javax.ejb.Stateless
    @ManagedBean
    public class StateList {
        @PersistenceUnit
        EntityManagerFactory emf;

        public List<States> getStates() {
            return emf.createEntityManager().createNamedQuery("States.findAll").getResultList();
        }
    }

    The change is highlighted in bold, and that's it!
Because of "Deploy-on-save" feature in NetBeans and GlassFish v3, the application is autodeployed. Otherwise right-click on the project and select Run (default shortcut "F6"). As earlier, the results can be seen at "http://localhost:8080/HelloEclipseLink/forwardToJSF.jsp" or "http://localhost:8080/HelloEclipseLink/faces/template-client.xhtml" and looks like:



The big difference this time is that the business logic is executed by an EJB in a fully transactional manner. Even though the logic in this case is a single read-only operation to the database, but you get the idea :)

Alternatively, you can use the delegate pattern in the managed bean as described below. Lets call this #95.2.
  1. Right-click on the project, select "New", "Session Bean ..." and create a stateless session bean by selecting the options as shown below:



    This creates a stateless session with the name "StateBeanBean" (bug #170392 for redundant "Bean" in the name).
  2. Simplify your managed bean by refactoring all the business logic to the EJB as shown below:

    @Stateless
    public class StateBeanBean {
        @PersistenceUnit
        EntityManagerFactory emf;
        
        public List<States> getStates() {
            return emf.createEntityManager().createNamedQuery("States.findAll").getResultList();
        }
    }

    and

    @ManagedBean
    public class StateList {
        @EJB StateBeanBean bean;

        public List<States> getStates() {
            return bean.getStates();
        }
    }

    In fact the EJB code can be further simplified to:

    @Stateless
    public class StateBeanBean {
        @PersistenceContext
        EntityManager em;
       
        public List<States> getStates() {
            return em.createNamedQuery("States.findAll").getResultList();
        }
    }

    The changes are highlighted in bold.
If the application is already running then Deploy-on-Save would have automatically deployed the entire application. Otherwise right-click on the project and select Run (default shortcut "F6"). Again, the results can be seen at "http://localhost:8080/HelloEclipseLink/forwardToJSF.jsp" or "http://localhost:8080/HelloEclipseLink/faces/template-client.xhtml" and are displayed as shown in the screenshot above.

The updated directory structure looks like:



The important point to note is that our EJB is bundled in the WAR file and no additional deployment descriptors were added or existing ones modified to achieve that. Now, that's really clean :)

The next blog in this series will show how managed beans can be replaced with WebBeans, err JCDI.

Also refer to other Java EE 6 blog entries.

Please leave suggestions on other TOTD that you'd like to see. A complete archive of all the tips is available here.

Technorati: totd glassfish v3 mysql javaee6 javaserverfaces jpa2 ejb netbeans

Thursday Apr 02, 2009

TOTD # 77: Running Seam examples with GlassFish

Seam is a full-stack solution to assemble complex web applications using simple annotated classes, a rich set of UI components, and very little XML. It integrates Ajax and Business Process Modeling with several Java EE technologies such as Java Server Faces (JSF), Java Persistence API (JPA), and Enterprise Java Beans (EJB 3.0).

GlassFish is a Java EE compliant application server so it's natural to pick GlassFish as your deployment platform for Seam applications :)

This blog is going to show how Seam samples can be easily run on GlassFish.
  1. Download Seam 2.1.1 GA from here and unzip.
  2. Build "examples/jpa" sample as:

    ~/tools/jboss-seam-2.1.1.GA/examples/jpa >ant glassfish
    Buildfile: build.xml

    glassfish:

    initcopy:

    initpoms:
         [echo] Setting up dependencies
        [mkdir] Created dir: /Users/arungupta/tools/jboss-seam-2.1.1.GA/classes/poms
         [copy] Copying 1 file to /Users/arungupta/tools/jboss-seam-2.1.1.GA/classes/poms
    [artifact:install] [INFO] Installing /Users/arungupta/tools/jboss-seam-2.1.1.GA/classes/poms/root.pom to . . .

    . . .

    init.war:

    war:
         [copy] Copying 27 files to /Users/arungupta/tools/jboss-seam-2.1.1.GA/examples/jpa/exploded-archives-glassfish/jboss-seam-jpa.war
         [copy] Copying 7 files to /Users/arungupta/tools/jboss-seam-2.1.1.GA/examples/jpa/exploded-archives-glassfish/jboss-seam-jpa.war/WEB-INF/lib

    noejb.war:
         [copy] Copying 18 files to /Users/arungupta/tools/jboss-seam-2.1.1.GA/examples/jpa/exploded-archives-glassfish/jboss-seam-jpa.war/WEB-INF/lib
         [copy] Copying 2 files to /Users/arungupta/tools/jboss-seam-2.1.1.GA/examples/jpa/exploded-archives-glassfish/jboss-seam-jpa.war
         [copy] Copying 4 files to /Users/arungupta/tools/jboss-seam-2.1.1.GA/examples/jpa/exploded-archives-glassfish/jboss-seam-jpa.war

    distributable.war:

    noejb.archive:
          [jar] Building jar: /Users/arungupta/tools/jboss-seam-2.1.1.GA/examples/jpa/dist-glassfish/jboss-seam-jpa.war

    BUILD SUCCESSFUL
    Total time: 5 seconds
  3. Deploy the sample as:

    ~/tools/jboss-seam-2.1.1.GA/examples/jpa >~/tools/glassfish/v2.1/glassfish/bin/asadmin deploy dist-glassfish/jboss-seam-jpa.war
    Command deploy executed successfully.

    The app is now accessible at "http://localhost:8080/jboss-seam-jpa" and here are some of the captured screenshots:







    Simple and easy!
  4. Build "examples/hibernate" as:

    ~/tools/jboss-seam-2.1.1.GA/examples/hibernate >ant glassfish
    Buildfile: build.xml

    glassfish:

    initcopy:

    initpoms:
         [echo] Setting up dependencies
         [copy] Copying 1 file to /Users/arungupta/tools/jboss-seam-2.1.1.GA/classes/poms
    [artifact:install] [INFO] Installing /Users/arungupta/tools/jboss-seam-2.1.1.GA/classes/poms/root.pom to /Users/arungupta/.m2/repository/org/jboss/seam/root/2.1.1.GA/root-2.1.1.GA.pom

     . . .

    distributable.war:

    noejb.archive:
          [jar] Building jar: /Users/arungupta/tools/jboss-seam-2.1.1.GA/examples/hibernate/dist-glassfish/jboss-seam-hibernate.war

    BUILD SUCCESSFUL
    Total time: 6 seconds

  5. Deploy the sample as:

    ~/tools/jboss-seam-2.1.1.GA/examples/hibernate >~/tools/glassfish/v2.1/glassfish/bin/asadmin deploy dist-glassfish/jboss-seam-hibernate.war
    Command deploy executed successfully.

    The app is now accessible at "http://localhost:8080/jboss-seam-hibernate" and has exactly similar snapshots as shown in "jboss-seam-jpa" sample. Simple and easy, yet again!
  6. Build "examples/jee5/booking" and deploy as:

    ~/tools/jboss-seam-2.1.1.GA/examples/jee5/booking >ant
    Buildfile: build.xml

    initcopy:

    initpoms:
         [echo] Setting up dependencies
         [copy] Copying 1 file to /Users/arungupta/tools/jboss-seam-2.1.1.GA/classes/poms
    [artifact:install] [INFO] Installing /Users/arungupta/tools/jboss-seam-2.1.1.GA/classes/poms/root.pom to /Users/arungupta/.m2/repository/org/jboss/seam/root/2.1.1.GA/root-2.1.1.GA.pom
         [copy] Copying 1 file to /Users/arungupta/tools/jboss-seam-2.1.1.GA/classes/poms

    . . .

    archive:
          [jar] Building jar: /Users/arungupta/tools/jboss-seam-2.1.1.GA/examples/jee5/booking/dist/jboss-seam-jee5-booking.jar
          [jar] Building jar: /Users/arungupta/tools/jboss-seam-2.1.1.GA/examples/jee5/booking/dist/jboss-seam-jee5-booking.war
          [jar] Building jar: /Users/arungupta/tools/jboss-seam-2.1.1.GA/examples/jee5/booking/dist/jboss-seam-jee5-booking.ear

    BUILD SUCCESSFUL
    Total time: 5 seconds
    ~/tools/jboss-seam-2.1.1.GA/examples/jee5/booking >~/tools/glassfish/v2.1/glassfish/bin/asadmin deploy dist/jboss-seam-jee5-booking.ear
    Command deploy executed successfully.

    The application is now accessible at "http://localhost:8080/seam-jee5-booking". Wow, that's simple and easy as well!
So we have deployed multiple Seam samples on GlassFish v2.1 - simple and easy!

Here are some more useful pointers realted to Seam and GlassFish:
  • Chapter 39 of the Seam Community Documentation even describes how to deploy an application created using seam-gen on GlassFish.
  • Dan Allen, the author of Manning's Seam in Action, presented a webinar at TheAquarium Online.
  • Several other Seam entries @ TA.
  • Deploying a seam-gen project to GlassFish (blog entry) - Here is a quote from the blog:

    GlassFish has a very sexy administrative console, but it also has a very sexy commandline tool known as asadmin. The asadmin tool gives you virtually unbounded control over the application server, including core tasks such as starting and stopping the application server, deploying and undeploying applications, and setting up database connection pools, amidst a plethora of other controls. You'll see that my modified seam-gen tool takes advantage of a handful of these commands.

    And another one ...

    GlassFish gives you efficiency through automation, which is undoubtedly the most effective way to become efficient. ... GlassFish volunteers itself to participate in a script and is the reason why I choose it as my preferred application server.
  • GlassFish support added to seam-gen: It is certainly exciting to know that there are targets like "gf-deploy-datasource", "gf-deploy-hibernate", and "gf-prepare" available to Seam developers out-of-the-box.
  • Sample Application using JSF, Seam, and Java Persistence APIs on GlassFish - detailed step-by-step blog explaining how to run Seam applications on GlassFish
The other samples in the bundle (that I tried) rely upon non-Java EE jars in the App Server's classpath. A slight build file tweaking can bundle those jars in the application itself and will allow to run them as well.

Are you deploying your Seam applications on GlassFish ?

Happy Seaming on GlassFish!

Please leave suggestions on other TOTD (Tip Of The Day) that you'd like to see. A complete archive of all the tips is available here.

Technorati: totd seam glassfish javaee javaserverfaces ejb jpa

Sunday Jan 18, 2009

EJBs in a WAR - Simplified packaging defined by EJB 3.1, Available in GlassFish v3


The EJB 3.1 specification says:

An enterprise bean class with a component-defining annotation defines an enterprise bean component when packaged within the WEB-INF/classes directory or in a .jar file within WEB-INF/lib.

In simple English it means, an EJB can be a POJO annotated with EJB annotations (such as @javax.ejb.Stateless) and bundled within WEB-INF/classes inside a WAR.

This feature is available in GlassFish v3 for some time now.

Imagine the ramifications, you now have Container Managed Persistence, Transacations, Security, and all other standard benefits of EJB - only this time in a WAR file.

The default configuration of GlassFish v3 Prelude does not include an EJB container. Lets first install it!

The EJB container in GlassFish v3 Prelude can be installed in couple of ways:
  • Using Update Center as described here.
  • Or using the "pkg" command which is described below
The "pkg" command shipped with GlassFish is platform-independent and runs on all the supported platforms. You can use the standard "pkg-get" command with OpenSolaris but that requires more options to be specified. For simplicity, we'll use the "pkg" command bundled with GlassFish as shown below:

arun@opensolaris:~/glassfishv3-prelude/bin$ ./pkg

The software needed for this command (pkg) is not installed.

When this tool interacts with package repositories, some system information
such as your system's IP address and operating system type and version
is sent to the repository server. For more information please see:

http://wiki.updatecenter.java.net/Wiki.jsp?page=UsageMetricsUC2

Once installation is complete you may re-run this command.

Would you like to install this software now (y/n): y

Install image: /export/home/arun/glassfishv3-prelude/bin/..
Installing pkg packages.
Installing: [pkg:/pkg@1.0.7,0-15.1269:20081008T211255Z,
pkg:/python2.4-minimal@2.4.4.0,0-15.1269:20081008T211307Z]
Initialization complete.

Software successfully installed. You may now re-run this command (pkg).

Install the EJB container as:

arun@opensolaris:~/glassfishv3-prelude/bin$ ./pkg install glassfish-ejb
DOWNLOAD                                    PKGS       FILES     XFER (MB)
Completed                                    1/1       11/11     0.45/0.45
PHASE                                        ACTIONS
Install Phase                                  24/24

And verify as ...

arun@opensolaris:~/glassfishv3-prelude/bin$ ./pkg list
NAME (AUTHORITY)                              VERSION         STATE      UFIX
felix                                         1.2.2-0         installed  ----
glassfish-amx                                 3.0-28.3        installed  ----
glassfish-api                                 3.0-28.3        installed  ----
glassfish-common                              3.0-28.3        installed  ----
glassfish-ejb                                 3.0-28.3        installed  ----
glassfish-grizzly                             1.8.6.2-0       installed  ----
glassfish-gui                                 3.0-28.3        installed  ----
glassfish-hk2                                 3.0-28.3        installed  ----
glassfish-jca                                 3.0-28.3        installed  ----
glassfish-jdbc                                3.0-28.3        installed  ----
glassfish-jdbc-gui                            3.0-28.3        installed  ----
glassfish-jdbc-management                     3.0-28.3        installed  ----
glassfish-jpa                                 3.0-28.3        installed  ----
glassfish-jsf                                 1.2.10-1        installed  u---
glassfish-jta                                 3.0-28.3        installed  ----
glassfish-management                          3.0-28.3        installed  ----
glassfish-nucleus                             3.0-28.3        installed  ----
glassfish-registration                        3.0-28.3        installed  ----
glassfish-scripting                           3.0-28.3        installed  ----
glassfish-web                                 3.0-28.3        installed  ----
glassfish-web-gui                             3.0-28.3        installed  ----
glassfish-web-management                      3.0-28.3        installed  ----
javadb                                        10.2.2.1-0      installed  ----
pkg                                           1.0.7-15.1269   installed  ----
pkg-java                                      1.0.7-15.1269   installed  ----
python2.4-minimal                             2.4.4.0-15.1269 installed  ----

As shown above, "glassfish-ejb" module with version "3.0.28.3" is now installed.

Now your GlassFish v3 Prelude is ready to serve EJBs!

Next, lets create a simple web application and package EJB there. Using the NetBeans IDE, create a template Web application. Lets say the project is named "ReallySimpleEJB".

  1. Create a POJO, choose the class name as "HelloEJB" and package as "server" as shown


  2. Declare a public method "sayHello" and add @javax.ejb.Stateless annotation to mark it a stateless EJB as shown

  3. Create a new Servlet by selecting the option as shown



    and specify the name as "EJBClient" in "client" package



    and click on "Finish".
  4. In the generated Servlet, declare a dependency on the EJB using @javax.ejb.EJB as shown

  5. Invoke the EJB by uncommenting the code in "processRequest" method and add "ejbClient.sayHell("Duke")" invocation as shown:



If the application is pre-deployed then saving this file will auto-deploy it as shown in screencast #27. Otherwise right-click on the project and select "Deploy".

And finally invoking the servlet at "http://localhost:8080/ReallySimpleEJB/EJBClient" shows the following output:



EJBs in a WAR - simple and easy to use :)

Download GlassFish v3 Prelude and get started!

Technorati: glassfish v3 ejb netbeans war ear

Wednesday Aug 22, 2007

TOTD #4: How to convert a Session EJB to a Web service ?

This TOTD describes how to convert a stateless session EJB to a Web service and uses information from this thread.

  1. Add @javax.jws.WebService annotation at the top of your EJB class. The modified code looks like:

    @javax.ejb.Stateless
    @javax.jws.WebService
    public class HelloSessionBean implements server.HelloSessionLocal {
        public String sayHello(String name) {
            return "Hello " + name + " from session bean";
        }
    }

    The new annotation is shown in this color.
  2. Re-build your project and redeploy it.

That's it!

There is no need to specify any additional deployment descriptor or parameters.The WSDL exposed by the EJB Web service endpoint is available at "http://localhost:8080/HelloSessionBeanService/HelloSessionBean?wsdl". The generated WSDL looks like:

<?xml version="1.0" encoding="UTF-8"?>
<!-- Published by JAX-WS RI at http://jax-ws.dev.java.net. RI's version is JAX-WS RI 2.1.2-hudson-182-RC1. -->
<!-- Generated by JAX-WS RI at http://jax-ws.dev.java.net. RI's version is JAX-WS RI 2.1.2-hudson-182-RC1. -->
<definitions
  xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
  xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy"
  xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
  xmlns:tns="http://server/"
  xmlns:xsd="http://www.w3.org/2001/XMLSchema"
  xmlns="http://schemas.xmlsoap.org/wsdl/"
  targetNamespace="http://server/"
  name="HelloSessionBeanService">
  <wsp:UsingPolicy></wsp:UsingPolicy>
  <wsp:Policy wsu:Id="HelloSessionBeanPortBinding_sayHello_WSAT_Policy">
    <wsp:ExactlyOne>
      <wsp:All>
        <ns1:ATAlwaysCapability xmlns:ns1="http://schemas.xmlsoap.org/ws/2004/10/wsat" wsp:Optional="false"></ns1:ATAlwaysCapability>
        <ns2:ATAssertion xmlns:ns3="http://schemas.xmlsoap.org/ws/2002/12/policy"
                         xmlns:ns2="http://schemas.xmlsoap.org/ws/2004/10/wsat" ns3:Optional="true"
                         wsp:Optional="true"></ns2:ATAssertion>
      </wsp:All>
    </wsp:ExactlyOne>
  </wsp:Policy>
  <types>
    <xsd:schema>
      <xsd:import namespace="http://server/" schemaLocation="http://localhost:8080/HelloSessionBeanService/HelloSessionBean?xsd=1"></xsd:import>
    </xsd:schema>
  </types>
  <message name="sayHello">
    <part name="parameters" element="tns:sayHello"></part>
  </message>
  <message name="sayHelloResponse">
    <part name="parameters" element="tns:sayHelloResponse"></part>
  </message>
  <portType name="HelloSessionBean">
    <operation name="sayHello">
      <input message="tns:sayHello"></input>
      <output message="tns:sayHelloResponse"></output>
    </operation>
  </portType>
  <binding name="HelloSessionBeanPortBinding" type="tns:HelloSessionBean">
    <soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="document"></soap:binding>
    <operation name="sayHello">
      <wsp:PolicyReference URI="#HelloSessionBeanPortBinding_sayHello_WSAT_Policy"></wsp:PolicyReference>
      <soap:operation soapAction=""></soap:operation>
      <input>
        <soap:body use="literal"></soap:body>
      </input>
      <output>
        <soap:body use="literal"></soap:body>
      </output>
    </operation>
  </binding>
  <service name="HelloSessionBeanService">
    <port name="HelloSessionBeanPort" binding="tns:HelloSessionBeanPortBinding">
      <soap:address location="http://localhost:8080/HelloSessionBeanService/HelloSessionBean"></soap:address>
    </port>
  </service>
</definitions>

Few points to notice:

  1. A reasonable set of defaults are chosen for portType/@name, binding/@name, service/@name and even the soap:address/@location. Most of these values can be changed by specifying a different value in the @WebService annotation.

  2. Accordingly to EJB 3.0 specification, if @TransactionAttribute is not specified on the method then a default value of REQUIRED is applied. This default value is automatically converted to ATAlwaysCapability and ATAssertion policy assertions.

  3. Accordingly to Web Services for Java EE, Version 1.2, webservices.xml is optional so there is no need to write any other deployment descriptor.

  4. Be careful not to deploy a WAR file with the context root generated (HelloSessionBeanService) for the Web service endpoint. The EJB Web service endpoint will be inaccessible after that.

Please leave suggestions on other TOTD that you'd like to see. A complete archive is available here.

Technorati: totd webservices ejb glassfish

About

profile image
Arun Gupta is a technology enthusiast, a passionate runner, author, and a community guy who works for Oracle Corp.


Java EE 7 Samples

Stay Connected

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today