--> « Previous PageNext Page »

September 14, 2009

TOTD #102: Java EE 6 (Servlet 3.0 and EJB 3.1) wizards in Eclipse

Categories: eclipse, glassfish, javaee, totd
Tags: , , ,

The Eclipse community’s WTP release with Java EE 6 support has been delayed to Jun 2010. So how do you do Java EE 6 development in Eclipse until then ?

The GlassFish team is trying to bridge the gap by adding new Java EE 6 wizards that allows you to create Servlet 3.0- (JSR 315) and EJB 3.1- (JSR 318) compliant artifacts. So for the first time, in Eclipse, a Java EE 6 application can be created using the GlassFish plugin for Eclipse (ver 1.0.32)!  GlassFish v3 is the Java EE 6 in making and so Eclipse and GlassFish v3 together provides you a good environment for your Java EE 6 development.

This Tip Of The Day (TOTD) explains how to use those wizards using Eclipse 3.4.2. If you have an earlier version of plugin already installed then update it as described in TOTD #66. Make sure to use ver 1.0.33 (recently released) if you are using Eclipse 3.5.x. If you have an earlier version of GlassFish plugin installed, then you may have to start Eclipse with "-clean" flag, basically as "eclipse -clean", after updating the plugin. This will allow the environment to detect the new plugins.

  1. Using Eclipse 3.4.2, install the latest GlassFish Eclipse plugin (ver 1.0.32 or higher) in "Eclipse IDE for Java EE developers" as explained in screencast #28. The correct version snapshot is shown below:

    Install latest GlassFish v3 promoted build (62 as of this writing):

    specify the location:

    and click on "Finish" to complete the install. Make sure to select "JVM 1.6.0" as the Java Runtime Environment as that is the minimum requirement for GlassFish v3.

  2. Create a new "Dynamic Web Project" named "ee6".
  3. Add Servlet 3.0 using wizard

    1. Right-click on the project, select "New", "Other …", expand the "GlassFish" section and select "Web Servlet (Java EE 6)" as shown below:

      and click on "Next >".

    2. Specify the package name as "server" and servlet name as "HelloServlet" as shown below:

      and click on "Finish".

    3. The generated code looks like as shown:

      Notice the usage of "javax.servlet.annotation.WebServlet" annotation to specify the servlet name and url pattern. Also note that no new entries are made in "WEB-INF/web.xml".

    4. Add a new method in the code as:

      protected void doProcess(HttpServletRequest request, HttpServletResponse response) throws IOException {
              ServletOutputStream out = response.getOutputStream();
              out.print("<html><body>");
              out.print("Request received at: " + request.getContextPath());
              out.print("</body></html>");
        }
      

      and invoke this method from both doGet(…) and doPost(…).

    5. Right-click the project, select "Run As", "Run on Server" and select the recently added GlassFish server as shown below:

      and click on "Finish". This shows the default page "http://localhost:8080/index.jsp". Change the URL to "http://localhost:8080/ee6/HelloServlet" to see the output as:

    6. The "web.xml" and "sun-web.xml" can be conveniently deleted from "WebContent", "WEB-INF" and the deployed page will continue to function as expected because all the information is captured in annotations instead of the deployment descriptors.
  4. Add an EJB 3.1-compliant session bean

    1. Select "New", "Other …", expand the "GlassFish" section and select "Session Bean (Java EE 6)" as shown below:

      The important difference to note is that using this new wizard an EJB can now be packaged in a Web project instead of creating a separate "EJB Project".

    2. Specify the package name as "server" and class name as "HelloBean" as shown below:

      The bean type can be chosen from "Stateless", "Stateful" or "Singleton" and appropriate annotations are added accordingly and click on "Finish".

    3. Add a simple method to the generated bean as:

      public String sayHello(String name) {
              return "Hello " + name;
      }
      
    4. Inject a client in the servlet as:

      @EJB HelloBean bean;
      

      and call the business method on EJB as:

      protected void doProcess(HttpServletRequest request, HttpServletResponse response) throws IOException {
              ServletOutputStream out = response.getOutputStream();
              out.print("<html><body>");
              out.print("Request received at: " + request.getContextPath());
              out.print("<br>" + bean.sayHello("Duke"));
              out.print("</body></html>");
       }
      

      and see the response as:

      This new EJB wizard is different from the one that already exists in Eclipse in the following ways:

      1. Singleton session bean can be created
      2. Local interface is off by default
      3. Allows a session bean in a Web project
      4. Simplified wizard flow

So we built a Java EE 6 application using the newly added Servlet 3.0 and EJB 3.1 wizards in GlassFish Plugin for Eclipse.

Please send your feedback and questions to . Let us know what other Java EE 6 features you’d like to see in Eclipse.

A complete archive of all the tips is available here.

Technorati: totd glassfish v3 eclipse javaee servlet3 ejb

Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DZone
  • StumbleUpon
  • Technorati
  • Twitter
  • Slashdot

September 4, 2009

TOTD #101: Applying Servlet 3.0/Java EE 6 “web-fragment.xml” to Lift – Deploy on GlassFish v3

TOTD #100 explained how to deploy Lift framework applications on GlassFish v3. As explained in TOTD #91, Java EE 6 defines how the framework configuration deployment descriptor can be defined in “META-INF/web-fragment.xml” in the JAR file of the framework instead of mixing it with "WEB-INF/web.xml" which is intended for application deployment descriptor aspects.

This Tip Of The Day (TOTD) explains how to leverage ”web-fragment.xml” to deploy a Lift application on a Java EE 6 compliant container. The original "lift-*.jar" files are untouched and instead a new JAR file is included that contains only the framework configuration deployment descriptor.

The generated "web.xml" from TOTD #100 looks like:

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
<filter>
 <filter-name>LiftFilter</filter-name>
 <display-name>Lift Filter</display-name>
 <description>The Filter that intercepts lift calls</description>
 <filter-class>net.liftweb.http.LiftFilter</filter-class>
</filter>

<filter-mapping>
 <filter-name>LiftFilter</filter-name>
 <url-pattern>/*</url-pattern>
</filter-mapping>

</web-app>

The deployment descriptor defines a Servlet Filter (LiftFilter) that registers the Lift framework with the Web container. And then it defines a URL mapping to "/*". All of this information is required by the Lift framework for request dispatching. And so that makes this fragment suitable for "web-fragment.xml".

Here are simple steps to make this change:

  1. Remove “src/main/webapp/WEB-INF/web.xml” because no application specific deployment descriptors are required.
  2. Include “lift-web-fragment.jar” in the “WEB-INF/lib” of your application by adding the following fragment in your “pom.xml”:

    <dependencies>
    
    . . .
    
      <!– web-fragment –>
      <dependency>
        <groupId>org.glassfish.extras</groupId>
        <artifactId>lift-web-fragment</artifactId>
        <version>1.0</version>
        <scope>runtime</scope>
      </dependency>
    </dependencies>
    
    . . .
    
    <repositories>
      <repository>
        <id>maven2-repository.dev.java.net</id>
        <name>Java.net Repository for Maven</name>
        <url>http://download.java.net/maven/2/</url>
      </repository>
    </repositories>
    

    This file contains only “META-INF/web-fragment.xml” with the following content:

    <web-fragment>
     <filter>
     <filter-name>LiftFilter</filter-name>
     <display-name>Lift Filter</display-name>
     <description>The Filter that intercepts lift calls</description>
     <filter-class>net.liftweb.http.LiftFilter</filter-class>
     </filter>
    
     <filter-mapping>
     <filter-name>LiftFilter</filter-name>
     <url-pattern>/*</url-pattern>
     </filter-mapping>
    </web-fragment>
    
    
  3. Create the WAR file without “web.xml” by editing “pom.xml” and adding the following fragment:

    <build>
       . . .
      <plugins>
        . . .
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-war-plugin</artifactId>
          <version>2.1-beta-1</version>
          <configuration>
            <failOnMissingWebXml>false</failOnMissingWebXml>
          </configuration>
        </plugin>
      </plugins>
    </build>
    

That’s it, now now you can create a WAR file using “mvn package” and deploy this web application on GlassFish v3 latest promoted build (61 as of today) as explained in TOTD #100.

Technorati: totd glassfish v3 lift scala javaee6 servlet web-fragment

Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DZone
  • StumbleUpon
  • Technorati
  • Twitter
  • Slashdot

September 3, 2009

TOTD #100: Getting Started with Scala Lift on GlassFish v3

Categories: frameworks, glassfish, javaee, totd
Tags: , ,

Yaaay, 100th tip! Read earlier tips here.

Scala is a strongly typed JVM language that provides benefits of functional programming and dynamic languages on the JVM. As a result you get flexibility of language such as Ruby and performance of Java. Lift is an MVC-based Web framework, based on Scala, that claims to pick the best of Rails (ease of development), Seaside (highly granular sessions and security), Django (access control), and Wicket (designer-friendly templating system).

Lift applications can run inside any Java application server. GlassFish v3 can run Rails and Django applications natively and can also run Wicket applications. This Tip Of The Day (TOTD) explains how to get started with Lift applications and run inside GlassFish v3.

  1. Create a new Lift project using Maven as shown:

    ~/samples/v3/lift >mvn archetype:generate -U -DarchetypeGroupId=net.liftweb
    -DarchetypeArtifactId=lift-archetype-blank -DarchetypeVersion=1.0
    -DremoteRepositories=http://scala-tools.org/repo-releases
    -DgroupId=demo.helloworld -DartifactId=helloworld
    -Dversion=1.0-SNAPSHOT
     [INFO] Scanning for projects...
     [INFO] Searching repository for plugin with prefix: 'archetype'.
     [INFO] org.apache.maven.plugins: checking for updates from central
    
     . . .
    
     [INFO] ------------------------------------------------------------------------
     [INFO] BUILD SUCCESSFUL
     [INFO] ------------------------------------------------------------------------
     [INFO] Total time: 14 seconds
     [INFO] Finished at: Tue Sep 01 16:11:34 PDT 2009
     [INFO] Final Memory: 12M/80M
     [INFO] ------------------------------------------------------------------------
    

    This creates a directory "helloworld" which looks like:

    ~/samples/v3/lift/helloworld >find .
    .
    ./pom.xml
    ./src
    ./src/main
    ./src/main/resources
    ./src/main/scala
    ./src/main/scala/bootstrap
    ./src/main/scala/bootstrap/liftweb
    ./src/main/scala/bootstrap/liftweb/Boot.scala
    ./src/main/scala/demo
    ./src/main/scala/demo/helloworld
    ./src/main/scala/demo/helloworld/comet
    ./src/main/scala/demo/helloworld/comet/.keep
    ./src/main/scala/demo/helloworld/model
    ./src/main/scala/demo/helloworld/model/.keep
    ./src/main/scala/demo/helloworld/snippet
    ./src/main/scala/demo/helloworld/snippet/.keep
    ./src/main/scala/demo/helloworld/snippet/HelloWorld.scala
    ./src/main/scala/demo/helloworld/view
    ./src/main/scala/demo/helloworld/view/.keep
    ./src/main/webapp
    ./src/main/webapp/index.html
    ./src/main/webapp/templates-hidden
    ./src/main/webapp/templates-hidden/default.html
    ./src/main/webapp/WEB-INF
    ./src/main/webapp/WEB-INF/web.xml
    ./src/test
    ./src/test/resources
    ./src/test/scala
    ./src/test/scala/demo
    ./src/test/scala/demo/helloworld
    ./src/test/scala/demo/helloworld/AppTest.scala
    ./src/test/scala/LiftConsole.scala
    ./src/test/scala/RunWebApp.scala
    

    In this directory, "src/main/scala" contains Scala source code, "src/main/webapp" contains the HTML and other related artifacts, and "src/test/scala" contains a simple test case to test the generated application. The "demo/helloworld/model" directory is used for models, "demo/helloworld/snippet" for controller, and "demo/helloworld/view" for views. The Lift Getting Started Guide provides a detailed explanation of how the different components work together to provide the end result.

  2. Create a WAR file of the application as:

    ~/samples/v3/lift/helloworld >mvn package [INFO] Scanning for projects...
     [INFO] ------------------------------------------------------------------------
     [INFO] Building helloworld
     [INFO] task-segment: [package]
     [INFO] ------------------------------------------------------------------------
     [INFO] artifact org.scala-tools:maven-scala-plugin: checking for updates from scala-tools.org
     [INFO] artifact org.scala-tools:maven-scala-plugin: checking for updates from central 
    
     . . . 
    
     [INFO] Building war: /Users/arungupta/samples/v3/lift/helloworld/target/helloworld-1.0-SNAPSHOT.war
     [INFO] ------------------------------------------------------------------------
     [INFO] BUILD SUCCESSFUL
     [INFO] ------------------------------------------------------------------------
     [INFO] Total time: 9 minutes 25 seconds
     [INFO] Finished at: Tue Sep 01 16:42:32 PDT 2009
     [INFO] Final Memory: 24M/80M
     [INFO] ------------------------------------------------------------------------
    

    This generates "target/helloworld-1.0-SNAPSHOT.war" file.

  3. The WAR file can be easily deployed to GlassFish v3. Download the latest GlassFish v3 promoted build (61 as of this writing) and unzip. Start the GlassFish server as:

    ~/tools/glassfish/v3/61/glassfishv3 >./bin/asadmin start-domain --verbose
    
    Sep 2, 2009 3:43:09 PM com.sun.enterprise.admin.launcher.GFLauncherLogger info
    INFO: JVM invocation command line:
    
    . . .
    
    Sep 2, 2009 3:46:01 PM OSGiModuleImpl start
    INFO: Started bundle org.glassfish.security [174]
    Sep 2, 2009 3:46:02 PM OSGiModuleImpl start
    INFO: Started bundle org.glassfish.deployment.javaee-full [51]
    

    and deploy the WAR file as:

    ~/samples/v3/lift/helloworld >~/tools/glassfish/v3/8-31/glassfishv3/bin/asadmin deploy target/helloworld-1.0-SNAPSHOT.war
    
    Command deploy executed successfully.
    

    The app is now accessible at "http://localhost:8080/helloworld-1.0-SNAPSHOT/" and the output looks like:

What application server are you using to deploy your Lift applications ?

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

Technorati: totd scala lift glassfish v3

Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DZone
  • StumbleUpon
  • Technorati
  • Twitter
  • Slashdot

September 1, 2009

Java EE 6, GlassFish, Eclipse, Dynamic Languages & Web Frameworks at Silicon Valley Code Camp 2009

Silicon Valley Code Camp 2009
To the community, By the community, For the community

Here is the list of GlassFish related sessions:

  1. Java EE 6 and GlassFish v3: Paving the path for future
  2. Using Eclipse for Java EE 6 development for the GlassFish™ Application Server
  3. Dynamic Languages & Web Frameworks in GlassFish

The detailed agenda for each session is explained here.

Here are the coordinates:

Date: Oct 3/4, 2009
Venue: Foothill College, Los Altos, CA
Cost: Free but registration required

Read the trip reports from 2008 and 2007.

With more than a month to go, already 120 sessions have been submitted and 855 attendees registered. The final agenda is not ready yet but typically all Java sessions are on a single day.

It’s a free event, with free coffee, food and lots of networking. What’s there to loose ?

See ya there!

Technorati: siliconvalleycodecamp glassfish javaee6 eclipse

Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DZone
  • StumbleUpon
  • Technorati
  • Twitter
  • Slashdot

August 30, 2009

TOTD #99: Creating a Java EE 6 application using MySQL, JPA 2.0 and Servlet 3.0 with GlassFish Tools Bundle for Eclipse

Categories: eclipse, general, javaee, totd
Tags: , , , ,

TOTD #97 showed how to install GlassFish Tools Bundle for Eclipse 1.1. Basically there are two options – either install Eclipse 3.4.2 with WTP and pre-bundled/configured with GlassFish v2/v3, MySQL JDBC driver and other features. Or if you are using Eclipse 3.5, then you can install the plug-in separately and get most of the functionality.

TOTD #98 showed how to create a simple Metro/JAX-WS compliant Web service using that bundle and deploy on GlassFish.

This Tip Of The Day (TOTD) shows how to create a simple Java EE 6 application that reads data from a MySQL database using JPA 2.0 and Servlet 3.0 and display the results. A more formal support of Java EE 6/Servlet 3.0 is coming but in the meanwhile the approach mentioned below will work.

Lets get started!

  1. Configure database connection – The key point to notice here is that the MySQL Connector/J driver is already built into the tool so there is no need to configure it explicitly.

    1. From "Window", "Show Perspective", change to the database perspective as shown below:

    2. In the "Data Source Explorer", right-click and click on "Database Connections" and select "New …":

    3. Search for "mysql" and type the database name as "sakila":

      This blog uses MySQL sample database sakila. So please download and install the sample database before proceeding further.

    4. Click on "Next >" and specify the database configuration:

      Notice the "Drivers" indicate that the JDBC driver is pre-bundled so there is no extra configuration required. If you are using a stand-alone Eclipse bunde and installing the plugin separately, then you need to configure the MySQL JDBC driver explictily.

      The URL indicates the application is connecting to the sakila database. Click on "Test Connection" to test connection with the database and see the output as:

      and click on "Finish" to complete. The expanded database in the explorer looks like:

      The expanded view shows all the tables in the database.

  2. Create the Web project & configure JPA

    1. Switch to JavaEE perspective by clicking "Window", "Choose Perspective", "Other …" and choosing "Java EE".
    2. Create a new dynamic web project with the following settings:

      Only the project name needs to be specified and everything else is default. Notice the target runtime indicates that this is a Java EE 6 application. Click on "Finish".

    3. Right-click on the project, search for "facets" and enable "Java Persistence" as shown below:

    4. Click on "Further configuration available …" and modify the facet as shown below:

      Make sure to disable "orm.xml" since we are generating a standard Java EE 6 web application. Choose "sakila" as the database. Click on "OK" and again on "OK" to complete the dialog.

  3. Generate the JPA entities

    1. Right-click on the project, select "JPA Tools", "Generate Entities" as shown:

    2. Choose the schema "sakila":

      and click on "Next >". If no values are shown in the schema drop-down, then click on "Reconnect …".

    3. Specify a package name for the generated entities as "model" and select "film" and "language" table:

      and click on "Finish". The "film" and "language" table are related so it would be nice if all the related tables can be identified and picked accordingly.

      Anyway this generates "model.Film" and "model.Language" classes and "persistence.xml" as shown below:

      Also notice that "web.xml" and "sun-web.xml" have been explicitly removed since they are not required by a Java EE 6 application.

    4. "model.Film" class needs to modified slightly because one of the columns is mapped to "Object" which is not a Serializable obect. So change the type of "specialFeatures" from Object to String and also change the corresponding getters/setters accordingly. The error message clearly conveyed during the initial deployment and so could be fixed. But it would be nice to generate the classes that will work out-of-the-box.
  4. Create a Servlet client to retrieve/display data from the database

    1. Right-click on the project, select "New", "Class" and specify the values as:

      and click on "Finish". This class will be our Servlet client.

    2. Change the class such that it looks like:
      @WebServlet(urlPatterns="/ServletClient")
      public class ServletClient extends HttpServlet {
        @PersistenceUnit
        EntityManagerFactory factory;
      
        protected void doGet(HttpServletRequest req, HttpServletResponse resp)
               throws ServletException, IOException {
          ServletOutputStream out = resp.getOutputStream();
          List list = factory.createEntityManager().createQuery("select f from Film f where f.title like 'GL%';").getResultList();
          out.println("<html><table>");
          for (Object film : list) {
            out.print("<tr><td>" + ((Film)film).getTitle() + "</tr></td>");
          }
          out.println("</table></html>");
        }
      }
      

      and the imports as:

      import java.io.IOException;
      import java.util.List;
      
      import javax.persistence.EntityManagerFactory;
      import javax.persistence.PersistenceUnit;
      import javax.servlet.ServletException;
      import javax.servlet.ServletOutputStream;
      import javax.servlet.annotation.WebServlet;
      import javax.servlet.http.HttpServlet;
      import javax.servlet.http.HttpServletRequest;
      import javax.servlet.http.HttpServletResponse;
      
      import model.Film;
      

      Basically, this is a Servlet 3.0 specification compliant Servlet that uses @WebServlet annotation. It uses @PersistenceUnit to inject the generated JPA Persistence Unit which is then used to query the database. The database query return all the movies whose title start with "GL" and the response is displayed in an HTML formatted table.

    3. Right-click on the project and select "Run As", "Run on Server" and select GlassFish v3 latest promoted build (this blog used build 61) as:

      and click on "Finish". The output at "http://localhost:8080/HelloJPA/ServletClient" looks like:

Simple, easy and clean!

How are you using Eclipse and GlassFish – the consolidated bundle or standalone Eclipse + GlassFish plugin ?

Download GlassFish Tools Bundle for Eclipse now.

Please send your questions and comments to .

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

Technorati: glassfish eclipse mysql jpa database

Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DZone
  • StumbleUpon
  • Technorati
  • Twitter
  • Slashdot

August 25, 2009

FREE GlassFish Webinar: “Java EE 6 Overview” – Aug 26, 2009, 10am PT

Categories: glassfish, javaee
Tags: , , ,

Java EE 6 is developed as JSR 316 under the Java Community Process. It breaks the “one size fits all” approach with Profiles and improves on the Java EE 5 developer productivity features. Several existing specifications are getting an extreme makeover such as Java Server Faces 2.0 and Servlet 3.0. GlassFish v3 is the Reference Implementation of Java EE 6.

So you’d like to get an overview of Java EE 6 and start developing with GlassFish v3. Please register for a free webinar with coordinates:

Date: Aug 26, 2009
Time: 10am PT

Register here.

Yep, it’s starting in a few hours so make sure to sign up and be ready with your questions. Several specification leads will be available to field your questions.

Technorati: glassfish javaee webinar

Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DZone
  • StumbleUpon
  • Technorati
  • Twitter
  • Slashdot

August 17, 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

Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DZone
  • StumbleUpon
  • Technorati
  • Twitter
  • Slashdot

August 14, 2009

TOTD #94: A simple Java Server Faces 2.0 + JPA 2.0 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. JPA 2.0 + Eclipselink was used for the database connectivity and Servlet 3.0 was used for displaying the results to the user. The sample demonstrated how the two technologies can be mixed to create a simple web application. But Servlets are meant for server-side processing rather than displaying the results to end user. JavaServer Faces 2 (another new specification in Java EE 6) is designed to fulfill that purpose.

This Tip Of The Day (TOTD) shows how to enhance the application created in TOTD #93 and use JSF 2 for displaying the results.

  1. Right-click on the project, select “Properties”, select “Frameworks”, click on “Add …” as shown below:

    Select “JavaServer Faces” and click on “OK”. The following configuration screen is shown:

    Click on “OK” to complete the dialog. This generates a whole bunch of files (7 to be accurate) in your project. Most of these files are leftover from previous version of NetBeans and will be cleaned up. For example, “faces-config.xml” is now optional and “forwardToJSF.jsp” is redundant.

  2. Anyway, lets add a POJO class that will be our managed bean. Right-click on “server” package and select “New”, “Java Class …”, give the name as “StateList”. Change the class such that it looks like:
    package server;

    import java.util.List;
    import javax.faces.bean.ManagedBean;
    import javax.persistence.EntityManagerFactory;
    import javax.persistence.PersistenceUnit;
    import states.States;

    /**
    * @author arungupta
    */
    @ManagedBean
    public class StateList {
    @PersistenceUnit
    EntityManagerFactory emf;

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

    Here are the main characterisitcs of this class:

    1. This is a POJO class with @ManagedBean annotation. This annotation makes this class a managed bean that can be used in the JSF pages. As no other annotations or parameters are specified, this is a request-scoped managed bean with the name “stateList” and lazily initialized. More details about this annotation are available in the javadocs.
    2. The persistence unit created in TOTD #93 is injected using @PersistenceUnit annotation.
    3. The POJO has one getter method that queries the database and return the list of all the states.
  3. In the generated file “template-client.xhtml”, change the “head” template to:
    Show States

    and “body” template to:

    <h:dataTable var=”state” value=”#{stateList.states}” border=”1″>
    <h:column><h:outputText value=”#{state.abbrev}”/></h:column>
    <h:column><h:outputText value=”#{state.name}”/></h:column>
    </h:dataTable>

    This uses the standard JSF “dataTable”, “column”, and “outputText” tags and uses the value expression to fetch the values from the managed bean.

If the application is already running from TOTD #93, then Deploy-on-Save would have automatically deployed the entire application. Otherwise right-click on the project and select Run (default shortcut “F6″). 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 updated directory structure looks like:

There were multiple files added by the JSF framework support in NetBeans. But as I said earlier, they will be cleaned up before the final release.

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 netbeans

Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DZone
  • StumbleUpon
  • Technorati
  • Twitter
  • Slashdot

August 13, 2009

TOTD #93: Getting Started with Java EE 6 using NetBeans 6.8 M1 & GlassFish v3 – A simple Servlet 3.0 + JPA 2.0 app

NetBeans 6.8 M1 introduces support for creating Java EE 6 applications … cool!

This Tip Of The Day (TOTD) shows how to create a simple web application using JPA 2.0 and Servlet 3.0 and deploy on GlassFish v3 latest promoted build (58 as of this writing). If you can work with the one week older build then NetBeans 6.8 M1 comes pre-bundled with 57. The example below should work fine on that as well.

  1. Create the database, table, and populate some data into it as shown below:
    ~/tools/glassfish/v3/58/glassfishv3/bin >sudo mysql –user root
    Password:
    Welcome to the MySQL monitor.  Commands end with ; or \g.
    Your MySQL connection id is 1592
    Server version: 5.1.30 MySQL Community Server (GPL)

    Type ‘help;’ or ‘\h’ for help. Type ‘\c’ to clear the buffer.

    mysql> create database states;
    Query OK, 1 row affected (0.02 sec)

    mysql> CREATE USER duke IDENTIFIED by ‘glassfish’;
    Query OK, 0 rows affected (0.00 sec)

    mysql> GRANT ALL on states.* TO duke;
    Query OK, 0 rows affected (0.24 sec)

    mysql> use states;
    Database changed

    mysql> CREATE TABLE STATES (
    ->       id INT,
    ->       abbrev VARCHAR(2),
    ->       name VARCHAR(50),
    ->       PRIMARY KEY (id)
    -> );
    Query OK, 0 rows affected (0.16 sec)

    mysql> INSERT INTO STATES VALUES (1, “AL”, “Alabama”);
    INSERT INTO STATES VALUES (2, “AK”, “Alaska”);

    . . .

    mysql> INSERT INTO STATES VALUES (49, “WI”, “Wisconsin”);
    Query OK, 1 row affected (0.00 sec)

    mysql> INSERT INTO STATES VALUES (50, “WY”, “Wyoming”);
    Query OK, 1 row affected (0.00 sec)

    The complete INSERT statement is available in TOTD #38. Most of this step can be executed from within the IDE as well as explained in TOTD #38.

  2. Download and unzip GlassFish v3 build 58. Copy the latest MySQL Connector/J jar in “domains/domain1/lib” directory of GlassFish and start the application server as:
    ~/tools/glassfish/v3/58/glassfishv3/bin >asadmin start-domain
  3. Create JDBC connection pool and JNDI resource as shown below:
    ~/tools/glassfish/v3/58/glassfishv3/bin >./asadmin create-jdbc-connection-pool –datasourceclassname com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource –restype javax.sql.DataSource –property “User=duke:Password=glassfish:URL=jdbc\:mysql\://localhost/states” jdbc/states

    Command create-jdbc-connection-pool executed successfully.
    ~/tools/glassfish/v3/58/glassfishv3/bin >./asadmin ping-connection-pool jdbc/states

    Command ping-connection-pool executed successfully.
    ~/tools/glassfish/v3/58/glassfishv3/bin >./asadmin create-jdbc-resource –connectionpoolid jdbc/states jdbc/jndi_states

    Command create-jdbc-resource executed successfully.

  4. Download NetBeans 6.8 M1 and install “All” version. Expand “Servers” node and add the recently installed GlassFish server.
  5. Create a new Web project and name it “HelloEclipseLink”. Make sure to choose “GlassFish v3″ as the server and “Java EE 6 Web” as the Java EE version as shown below:

    Take defaults elsewhere.

  6. Create the Persistence Unit
    1. Right-click on the newly created project and select “New”, “Entity Classes from Database …”. Choose the earlier created data source “jdbc/jndi_states” as shown below:

    2. Select “STATES” table in “Available Tables:” and click on “Add >” and then “Next >”.
    3. Click on “Create Persistence Unit …”, take all the defaults and click on “Create”. “EclipseLink” is the Reference Implementation for JPA 2.0 is the default choosen Persistence Provider as shown below:
    4. Enter the package name as “server” and click on “Finish”.
  7. Create a Servlet to retrieve and display all the information from the database
    1. Right click on the project, “New”, “Servlet …”.
    2. Give the Servlet name “ShowStates” and package “server”.
    3. Even though you can take all the defaults and click on “Finish” but instead click on “Next >” and the following screen is shown:

      Notice “Add information to deployment descriptor (web.xml)” checkbox. Servlet 3.0 makes “web.xml” optional in most of the common cases by providing corresponding annotations and NetBeans 6.8 leverages that functionality. As a result, no “web.xml” will be bundled in our WAR file. Click on “Finish” now.

      The generated servlet code looks like:

      Notice @WebServlet annotation, this makes “web.xml” optional. TOTD #82 provide another example on how to use Servlet 3.0 with EJB 3.1.

    4. Inject the Persistence Unit as:
      @PersistenceUnit
      EntityManagerFactory emf;

      right above “processRequest” method.

    5. Change the “try” block of “processRequest” method to:
      List<States> list = emf.createEntityManager().createNamedQuery(”States.findAll”).getResultList();
      out.println(”<table border=\”1\”>”);
      for (States state : list) {
      out.println(”<tr><td>” + state.getAbbrev() +
      “</td><td>” + state.getName() +
      “</td></tr>”);
      }
      out.println(”</table>”);

      This uses a predefined query to retrieve all rows from the table and then display them in a simple formatted HTML table.

  8. Run the project
      1. Right click on the project, select “Properties” and change the “Relative URL” to “/ShowStates”. This is the exact URL that you specified earlier.

      2. Right-click on the project and select “Run” to see the following output:

    So we created a simple web application that uses Servlet 3.0, JPA 2.0, EclipseLink and deployed on GlassFish v3 using NetBeans 6.8 M1. NetBeans provides reasonable defaults making you a lazy programmer. Believe this is more evident when you start playing with Java EE support in other IDEs ;-)

    Finally, lets look at the structure of the generated WAR file:

    It’s very clean – no “web.xml”, only the relevant classes and “persistence.xml”.

    Also refer to other Java EE 6 blog entries. A future blog entry will show how to use JSF 2.0 instead of Servlet for displaying the results.

    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 servlet3 jpa2 netbeans

    Share and Enjoy:
    • Print
    • Digg
    • Sphinn
    • del.icio.us
    • Facebook
    • Google Bookmarks
    • DZone
    • StumbleUpon
    • Technorati
    • Twitter
    • Slashdot

    August 11, 2009

    TOTD #91: Applying Java EE 6 “web-fragment.xml” to Apache Wicket – Deploy on GlassFish v3

    “Extensibility” is a major theme of Java EE 6. This theme enables seamless pluggability of other popular Web frameworks with Java EE 6.

    Before Java EE 6, these frameworks have to rely upon registering servlet listeners/filters in “web.xml” or some other similar mechanism to register the framework with the Web container. Thus your application and framework deployment descriptors are mixed together. As an application developer you need to figure out the magical descriptors of the framework that will make this registration.

    What if you are using multiple frameworks ? Then “web.xml” need to have multiple of those listeners/servlets. So your deployment descriptor becomes daunting and maintenance nightmare even before any application deployment artifacts are added.

    Instead you should focus on your application descriptors and let the framework developer provide the descriptors along with their jar file so that the registration is indeed magical.

    For that, the Servlet 3.0 specification introduces “web module deployment descriptor fragment” (aka “web-fragment.xml”). The spec defines it as:

    A web fragment is a logical partitioning of the web app in such a way that the frameworks being used within the web app can define all the artifacts without asking devlopers to edit or add information in the web.xml.

    Basically, the framework configuration deployment descriptor can now be defined in “META-INF/web-fragment.xml” in the JAR file of the framework. The Web container picks up and use the configuration for registering the framework. The spec clearly defines the rules around ordering, duplicates and other complexities.

    TOTD #86 explained how to get started with Apache Wicket on GlassFish. This Tip Of The Day (TOTD) explains how to leverage ”web-fragment.xml” to deploy a Wicket application on GlassFish v3. The basic concepts are also discussed here.

    For the “Hello World” app discussed in TOTD #86, the generated “web.xml” looks like:

    <?xml version=”1.0″ encoding=”ISO-8859-1″?>
    <web-app xmlns=”http://java.sun.com/xml/ns/j2ee”
             xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
             xsi:schemaLocation=”http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd”
             version=”2.4″>

            <display-name>helloworld</display-name>

             <!– 
                  There are three means to configure Wickets configuration mode and they are
                  tested in the order given.
                  1) A system property: -Dwicket.configuration
                  2) servlet specific <init-param>
                  3) context specific <context-param>
                  The value might be either “development” (reloading when templates change)
                  or “deployment”. If no configuration is found, “development” is the default.
            –>

            <filter>
                    <filter-name>wicket.helloworld</filter-name>
                    <filter-class>org.apache.wicket.protocol.http.WicketFilter</filter-class>
                    <init-param>
                            <param-name>applicationClassName</param-name>
                            <param-value>org.glassfish.samples.WicketApplication</param-value>
                    </init-param>
            </filter>

     <filter-mapping>
      <filter-name>wicket.helloworld</filter-name>
            <url-pattern>/*</url-pattern>
     </filter-mapping>

    </web-app>

    This deployment descriptor defines a Servlet Filter (wicket.helloworld) that registers the Wicket framework with the Web container. The filter specifies an initialization parameter that specifies the class name of the Wicket application to be loaded. And it also contains some other information that is also relevant to the framework. None of this application is either required or specified by the application. And so that makes this fragment a suitable candidate for “web-fragment.xml”.

    Here are the simple steps to make this change:

    1. Remove “src/main/webapp/WEB-INF/web.xml” because no application specific deployment descriptors are required.
    2. Include “wicket-quickstart-web-fragment.jar” in the “WEB-INF/lib” directory of your application by adding the following fragment in your “pom.xml”:
          <dependencies>

              . . .
              <!– web-fragment –>
              <dependency>
                  <groupId>org.glassfish.extras</groupId>
                  <artifactId>wicket-quickstart-web-fragment</artifactId>
                  <version>1.0</version>
                  <scope>runtime</scope>
              </dependency>
          </dependencies>

         . . .

          <repositories>
              <repository>
                  <id>maven2-repository.dev.java.net</id>
                  <name>Java.net Repository for Maven</name>
               &nbsp
      ;  <url>http://download.java.net/maven/2/</url>
              </repository>
          </repositories>

      This file contains only “META-INF/web-fragment.xml” with the following content:

      <web-fragment>
              <filter>
                      <filter-name>wicket.helloworld</filter-name>
                      <filter-class>org.apache.wicket.protocol.http.WicketFilter</filter-class>
                      <init-param>
                              <param-name>applicationClassName</param-name>
                              <param-value>org.glassfish.samples.WicketApplication</param-value>
                      </init-param>
              </filter>

              <filter-mapping>
                      <filter-name>wicket.helloworld</filter-name>
                      <url-pattern>/*</url-pattern>
              </filter-mapping>
      </web-fragment>

    3. Create the WAR file without “web.xml” by editing “pom.xml” and adding the following fragment:
            <plugins>
                  . . .
                  <plugin>
                      <groupId>org.apache.maven.plugins</groupId>
                      <artifactId>maven-war-plugin</artifactId>
                      <version>2.1-beta-1</version>
                      <configuration>
                          <failOnMissingWebXml>false</failOnMissingWebXml>
                      </configuration>
                  </plugin>
                  . . .
            </plugins>

    That’s it, now you can create a WAR file using “mvn package” and deploy this web application on GlassFish v3 latest promoted build (58 as of today) as explained in TOTD #86.

    The updated WAR file structure looks like:

    helloworld-1.0-SNAPSHOT
    helloworld-1.0-SNAPSHOT/META-INF
    helloworld-1.0-SNAPSHOT/WEB-INF
    helloworld-1.0-SNAPSHOT/WEB-INF/classes
    helloworld-1.0-SNAPSHOT/WEB-INF/classes/log4j.properties
    helloworld-1.0-SNAPSHOT/WEB-INF/classes/org
    helloworld-1.0-SNAPSHOT/WEB-INF/classes/org/glassfish
    helloworld-1.0-SNAPSHOT/WEB-INF/classes/org/glassfish/samples
    helloworld-1.0-SNAPSHOT/WEB-INF/classes/org/glassfish/samples/HomePage.class
    helloworld-1.0-SNAPSHOT/WEB-INF/classes/org/glassfish/samples/HomePage.html
    helloworld-1.0-SNAPSHOT/WEB-INF/classes/org/glassfish/samples/WicketApplication.class
    helloworld-1.0-SNAPSHOT/WEB-INF/lib
    helloworld-1.0-SNAPSHOT/WEB-INF/lib/log4j-1.2.14.jar
    helloworld-1.0-SNAPSHOT/WEB-INF/lib/slf4j-api-1.4.2.jar
    helloworld-1.0-SNAPSHOT/WEB-INF/lib/slf4j-log4j12-1.4.2.jar
    helloworld-1.0-SNAPSHOT/WEB-INF/lib/wicket-1.4.0.jar
    helloworld-1.0-SNAPSHOT/WEB-INF/lib/wicket-quickstart-web-fragment-1.0.jar

    Notice, there is no “web.xml” and the additional “wicket-quickstart-web-fragment-1.0.jar” and everything works as is!

    It would be nice if the next version of wicket-*.jar can include “META-INF/web-fragment.xml” then everything will work out-of-the-box :)

    Here is a snapshot of the deployed application:

    Are you deploying your Wicket applications on GlassFish ?

    Technorati: totd glassfish v3 wicket javaee6 servlet web-fragment

    Share and Enjoy:
    • Print
    • Digg
    • Sphinn
    • del.icio.us
    • Facebook
    • Google Bookmarks
    • DZone
    • StumbleUpon
    • Technorati
    • Twitter
    • Slashdot
    « Newer PostsOlder Posts »

    Powered by WordPress
    186665 visits from Sep 11, 2009