Monday Feb 01, 2010

Screencast #29: Web service using NetBeans 6.8 and GlassFish v3 (Accessing database in business method)

GlassFish v3 comes bundled with Metro - a secure, reliable, transactional, and .NET interoperable Web services stack. Metro is compliant with JAX-WS and provides additional quality of service attributes that can be easily enabled using NetBeans IDE.

This blog contains a screencast that shows how to create a simple Web service using NetBeans 6.8, implement the business logic by accessing a database table using Java Persistence API, and deploy on GlassFish v3.

Please post your questions to users@glassfish.dev.java.net.

Several other screencasts on GlassFish v3and related topics are available here.

Technorati: netbeans jax-ws metro webservice glassfish jpa database

Thursday Oct 08, 2009

TOTD #112: Exposing Oracle database tables as RESTful entities using JAX-RS, GlassFish, and NetBeans

This Tip Of The Day explains how to expose an existing Oracle database table as a RESTful Web service endpoint using NetBeans tooling and deployed on GlassFish.

Lets get started!

  1. Configure GlassFish v3 10/7 or a later nightly in a recent NetBeans 6.8 build (latest nightly). As issue# 9885 is fixed, so copy ojdbc6.jar in the "domains/domain1/lib/ext" directory.
  2. Create a Web application
    1. Create a new "Web application" and name the project "RestfulOracle":



      click on "Next >".
    2. Choose the newly added server and "Java EE 6 Web" as the Java EE version:



      and click on "Finish".
  3. Create JPA entities for "HR" schema. The steps outlined below uses NetBeans solely for creating the JPA entities. Alternatively, TOTD #108 explains how to define a JDBC connection pool and JDBC resource using "asadmin" CLI and then use that resource from within NetBeans. Either way, the JDBC resource is stored in the underlying "domain.xml".
    1. Right-click on the project and select "New", "Entity Classes from Database...".
    2. In "Data Source:" select "New Data Source..." as shown below:

    3. Specify the JNDI name as "jdbc/hr" and choose the pre-configured database connection as shown below:



      TOTD #107 explains how to configure Oracle database in NetBeans.
    4. In the list of "Available Tables:", select "EMPLOYEES" and click on "Add >" to see the following:



      Notice the list of related tables are included as well. Click on "Next >".
    5. Specify the package name as "model".
    6. Click on "Create Persistence Unit...", take the defaults, and click on "Create":



      and click on "Finish". Notice EclipseLink, the reference implementation for JPA 2.0, is used as the persistence provider. This generates POJOs that provide database access using JPA 2.0 APIs. These APIs are included as part of the Java EE 6 platform.
  4. Create RESTful entities
    1. Right-click on the project and select "RESTful Web Services from Entity Classes...":


    2. Select "Employees (model.Employees)" from "Available Entity Classes:" and click on "Add >" to see the following:



      click on "Next >", take the defaults, and click on "Finish". This generates a bunch of wrapper classes using JAX-RS to expose the JPA Entity classes as RESTful Web services. JAX-RS 1.1 is also included as part of the Java EE 6 platform.
  5. Run the Web service
    1. Right-click the project and select "Test RESTful Web Services":



      This deploys the created Web application on the selected GlassFish build and displays the following page in the default browser:


    2. Click on "deparmentss" and then on "Test" button to see the output as:



      Clicking the "Test" button issues a GET request to "http://localhost:8080/RestfulOracle/resources/departmentss". This uses the generated JAX-RS wrapper classes to talk to the database using JPA entity classes and query the first 10 rows from the "DEPARTMENTS" table. The response is then JSON formatted using JAX-RS wrapper classes and is returned to the requesting page which then displays it nicely formatted in the table. It also shows l-level deep department's relationship to other entities. If the "expandLevel" on the above page is set to "0", then the following output is shown:



      The "Raw View" (JSON data) of the original output looks like:



      Notice this is the raw JSON output generated by the JAX-RS wrapper classes. The "Http Monitor" traffic looks like:



      The format of data returned can be changed from "application/json" to "application/xml" as shown below:



      And even a POST request can be generated.

Do you have the need to expose your Oracle database tables as RESTful entities ?

A complete archive of all the TOTDs is available here.

This and other similar applications will be demonstrated at the upcoming Oracle Open World.

Technorati: totd oracle database glassfish v3 netbeans javaee jax-rs jpa rest

Thursday Oct 01, 2009

TOTD #108: Java EE 6 web application (JSF 2.0 + JPA 2.0 + EJB 3.1) using Oracle, NetBeans, and GlassFish

TOTD #106 explained how to install Oracle database 10g R2 on Mac OS X. TOTD #107 explained how to connect this Oracle database using NetBeans. This Tip Of The Day will explain how to use the sample HR database (that comes with Oracle database server) to write a simple Java EE 6 application.

This application will use Java Server Faces 2.0 for displaying the results, Enterprise Java Beans 3.1 + Java Persistence API 2.0 for middle tier, and Oracle database server + GlassFish v3 as the backend. The latest promoted build (65 of this writing) will not work because of the issue #9885 so this blog will use build 63 instead.

Several improvements have been made over NetBeans 6.8 M1 build and this blog is using the nightly build of 9/27. The environment used in this blog is:

  • NetBeans 9/27 nightly
  • GlassFish v3 build 63
  • Oracle database server 10.2.0.4.0 R2 on Mac OS X
  • Oracle JDBC Driver type 4 (ojdbc6.jar)

Lets get started!

  1. Configure GlassFish v3 with JDBC connection
    1. Download and unzip build 63.
    2. Download ojdbc6.jar and copy to "glassfishv3/glassfish/domains/domain1/lib/ext" directory.
    3. Start the Application Server as:
      ./bin/asadmin start-domain --verbose &
      
    4. Create a JDBC connection pool as:
      ./bin/asadmin create-jdbc-connection-pool --datasourceclassname oracle.jdbc.pool.OracleDataSource --restype javax.sql.DataSource --property "User=hr:Password=hr:URL=jdbc\\:oracle\\:thin\\:@localhost\\:1521\\:orcl" jdbc/hr
      

      and verify the connection pool as:
      ./bin/asadmin ping-connection-pool jdbc/hr
      
    5. Create a JDBC resource as:
      ./bin/asadmin create-jdbc-resource --connectionpoolid jdbc/hr jdbc/hr
      
  2. Configure GlassFish v3 build 63 in NetBeans
    1. In NetBeans IDE "Services" panel, right-click on "Servers" and click on "Add Server...". Choose "GlassFish v3" and provide a name as shown below:


    2. Click on "Next >" and specify the unzipped GlassFish location as:



      and click on "Finish".
  3. Create the Java EE 6 application
    1. In "Projects" pane, right-click and select "New Project...".
    2. Choose "Java Web" and "Web Application" and click on "Next". Choose the project name as "HelloOracle":



      and click on "Next >".
    3. Select the recently added GlassFish v3 server and choose "Java EE 6 Web" profile:



      and click on "Next >". Notice "Java EE 6 Web" profile is chosen as the Java EE version.
    4. Select "JavaServer Faces" on the frameworks page:



      and click on "Finish". Notice the JSF libraries bundled with the App Server are used.
  4. Create the Java Persistence Unit
    1. Right-click on the project, select "New", "Entity Classes from Database...":


    2. From the Data Source, select "jdbc/hr" as shown:



      This is the same JDBC resource created earlier. Select "EMPLOYEES" from the Available Table, click on "Add >" to see the output as:



      The related tables are automatically included. Click on "Next >".
    3. Click on "Create Persistence Unit ..." and take all the defaults and click on "Create".
    4. Specify the package name as "model":



      and click on "Finish". This generates a JPA-compliant POJO class that provide access to tables in the underlying Oracle database. The class name corresponding to each table is shown in the wizard.
  5. Create Enterprise Java Beans
    1. Right-click on the project and select "New Class...".
    2. Specify the class name as "EmployeesBean" and package as "controller", click on "Finish".
    3. Annotate the class to make it an Enterprise Java Bean and a JSF Managed Bean as:
      @javax.ejb.Stateless
      @javax.faces.bean.ManagedBean
      


      Notice, the EJB is bundled in the WAR file and no special type of modules are required. Java EE 6 provides simplified packaging of EJB which makes it really ease to use.

      Also this application is currently using JSF managed bean but will use JSR 299 (aka Web Beans) in a future blog.
    4. Inject the Persistence Unit by adding the following variable:
      @PersistenceUnit
      EntityManagerFactory emf;
      
    5. Add a new method to retrieve the list of all employees as:
      public List getEmployees() {
       return em.createNamedQuery("Employees.findAll").getResultList();
      }
      

      "Employees.findAll" is a default NamedQuery generated by NetBeans and makes it easy to query the database. Several other queries are generated for each mapped JPA class, such as "Employees.findByEmployeeId" and "Employees.findByFirstName". Custom queries can also be created and specified on the POJO class.

      The completed class looks like:
      @Stateless
      @ManagedBean
      public class EmployeesBean {
      
       public List getEmployees() {
       return emf.createEntityManager().createNamedQuery("Employees.findAll").getResultList();
       }
      }
      
  6. Use EJB in the generated JSF page
    1. JSF 2 uses Facelets as the templating mechanism and NetBeans generate a simple "index.xhtml" file to start with. Expand "Web Pages" and open "index.xhtml".
    2. Replace the body template with:
      <h1>First Java EE 6 app using Oracle database</>
      <h:dataTable var="emp" value="#{employeesBean.employees}" border="1">
       <h:column><h:outputText value="#{emp.lastName}"/>, <h:outputText value="#{emp.firstName}"/></h:column>
       <h:column><h:outputText value="#{emp.email}"/></h:column>
       <h:column><h:outputText value="#{emp.hireDate}"/></h:column>
       </h:dataTable>
      

      It uses JSF value expressions to bind the Enterprise Java Bean and dumps the HTML formatted name, email, and hire date of each employee in the database.
  7. Run the project: Right-click on the project and select "Run" to see the output at "http://localhost:8080/HelloOracle/" as:

So we can easily create a Java EE 6 application using NetBeans, Oracle, and GlassFish.

A complete archive of all the TOTDs is available here.

This and other similar applications will be demonstrated at the upcoming Oracle Open World.

Technorati: totd oracle database glassfish v3 javaee javaserverfaces ejb jpa netbeans oow

Sunday Aug 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

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 users@glassfishplugins.dev.java.net.

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

Monday Aug 17, 2009

LOTD #22: How to inject JPA resources ? - PersistenceUnit vs PersistenceContext


Java Persistence API defines a standard object/relational mapping using POJOs. In JPA, a persistence unit is described using "persistence.xml", bundled with the web application, injected into your web application and then POJOs are used to access all the information from the underlying persistence mechanism such as a database.

JPA can injected into your application couple of different ways as shown below:

@PersistenceUnit
EntityManagerFactory emf;

and

@PersistenceContext
EntityManager manager;

Which one is preferred, why, and pros/cons are very clearly explained in (slightly old but very relevant) this blog. It also discusses a JNDI approach.

In case you are interested in the summary:
  • Use "@PersistenceUnit EntityManagerFactory" for Servlets because of thread safety
  • Use "@PersistenceContext EntityManager" in EJBs for simpler/cleaner code
Read other JPA related entries.
All previous entries in this series are archived at LOTD.

Technorati: lotd glassfish jpa javaee persistence

Thursday Apr 09, 2009

LOTD #20: How to create a JPA application using GlassFish Tools Bundle for Eclipse ?


Here is a great screencast (from the community) that shows how to create a JPA application using EclipseLink and deploy on GlassFish v2.1 - all using GlassFish Tools Bundle for Eclipse.

Click on the image below for the video:



Thanks!

I'll work on a MySQL version of it :)

All previous links in this series are archived at LOTD.

Technorati: lotd glassfish eclipse jpa javadb screencast

Tuesday Apr 07, 2009

TOTD #78: GlassFish, EclipseLink, and MySQL efficient pagination using LIMIT

EclipseLink JPA replaces TopLink Essentials as the JPA implementation in GlassFish v3. One of the benefits of using EclipseLink is that it provides efficient pagination support for the MySQL database by generating native SQL statements such as "SELECT ... FROM <table> LIMIT <offset>, <rowcount>".

The MySQL LIMIT clause definition says:

The LIMIT clause can be used to constrain the number of rows returned by the SELECT statement. LIMIT takes one or two numeric arguments, which must both be non-negative integer constants (except when using prepared statements).

With two arguments, the first argument specifies the offset of the first row to return, and the second specifies the maximum number of rows to return. The offset of the initial row is 0 (not 1):

SELECT \* FROM tbl LIMIT 5,10;  # Retrieve rows 6-15

So instead of fetching all rows from the database and then filtering from row 6-15, only rows 6 through 15 are fetched.

This TOTD (Tip Of The Day) explains how to create a JPA Persistence Unit for sakila (MySQL sample database) using NetBeans, use EclipseLink as the Persistence Provider, and then write a JPA query to leverage the pagination support - all on GlassFish v3.
  1. Create a Persistence Unit for "sakila" as explained in this blog using bullets #1 - 3. The differences are explained below:
    1. In 2.1, choose "GlassFish v3 Prelude" as the server. Even though "GlassFish v3 Prelude" is chosen as the server but it will be replaced with a recent promoted build because pagination feature is not implemented in the Prelude. Alternatively you can use NetBeans 6.7 M3 and GlassFish v3 as explained here.
    2. In 3.3, EclipseLink is shown as the default Persistence Provider as shown below:

    3. In 3.5, there is no need to specify the properties for "user" and "password as the JDBC resource is stored in the server configuration. Instead specify the following property:

      <properties>
          <property name="eclipselink.logging.level" value="FINE"/>
      </properties>

      This will log any SQL statement sent by JPA to the underlying persistence provider (EclipseLink in this case).
  2. If GlassFish v3 was configured using NetBeans 6.7 M3, then the JDBC Connection Pool and JDBC resource were created in the server directly. If not, then download and unzip the latest GlassFish v3 latest promoted build (b43 as of this writing). Create the JDBC Connection Pool as:

    ./asadmin create-jdbc-connection-pool --datasourceclassname com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource --property user=duke:password=glassfish:ServerName=localhost:portNumber=3306:databaseName=sakila jdbc-mysql-pool

    and the JDBC resource:

    ./asadmin create-jdbc-resource --connectionpoolid jdbc-mysql-pool jndi/sakila

    GlassFish v3 b43 bundles "Eclipse Persistence Services - 2.0.0.r3652-M1". A later blog will explain how to replace the bundled EclipseLink version with a newer/different EclipseLink version.
  3. Create a new Servlet "QueryServlet". Inject the javax.persistence.EntityManagerFactory resource:

        @PersistenceUnit
        EntityManagerFactory emf;

    and change the "processRequest" operation to:

            EntityManager em = emf.createEntityManager();

            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            try {
                int startRow = Integer.valueOf(request.getParameter("start_row"));
                int howMany = Integer.valueOf(request.getParameter("how_many"));
                Query q = em.createNamedQuery("Film.findAll");

                q.setFirstResult(startRow);
                q.setMaxResults(startRow + howMany);
                for (Object film : q.getResultList()) {
                    out.print(((Film)film).toString() + "<br/>");
                }
            } finally {
                out.close();
            }

    This Servlet reads two parameters from the request and sets parameters on the JPA Query to enable pagination.
  4. Deploy the application on GlassFish v3.
    1. Using NetBeans 6.7 M3, select "Deploy" from the context-sensitive menu.
    2. Using NetBeans 6.5.1, select "Clean and Build" and then manually deploy the WAR file using "asadmin deploy dist/Pagination.war".
If the project name was "Pagination", then the Servlet is accessible at "http://localhost:8080/Pagination/QueryServlet?start_row=1&how_many=10" and shows ten rows starting at index "1". The output looks like:



The log file in "domains/domain1/logs/server.log" show the following SQL query generated by EclipseLink:

[#|2009-04-07T14:01:12.815-0700|FINE|glassfish|org.eclipse.persistence.session.file: /Users/arungupta/tools/glassfish/v3/b43/glassfishv3/glassfish/domains/domain1/applications/Pagination/WEB-INF/classes/-PaginationPU.sql| _ThreadID=15;_ThreadName=Thread-1;ClassName=null;MethodName=null;|SELECT film_id AS film_id1, special_features AS special_features2, last_update AS last_update3, rental_duration AS rental_duration4, release_year AS release_year5, title AS title6, description AS description7, replacement_cost AS replacement_cost8, length AS length9, rating AS rating10, rental_rate AS rental_rate11, language_id AS language_id12, original_language_id AS original_language_id13 FROM film LIMIT ?, ?
        bind => [1, 11]|#]

As you can see, the query uses the LIMIT clause which optimizes the data returned from the table.

If a different database, for example Derby, is used then the generated SQL query looks like as:

[#|2009-04-07T17:00:34.210-0700|FINE|glassfish|org.eclipse.persistence.session.file: /Users/arungupta/tools/glassfish/v3/b43/glassfishv3/glassfish/domains/domain1/applications/Pagination/WEB-INF/classes/-PaginationPU.sql| _ThreadID=15;_ThreadName=Thread-1;ClassName=null;MethodName=null;|SELECT film_id, special_features, last_update, rental_duration, release_year, title, description, replacement_cost, length, rating, rental_rate, language_id, original_language_id FROM film|#]

In this case, the entire table is fetched and the rows are filtered based upon the critieria specified on the client side.

If the number of rows is huge (a typical case for enterprise) then MySQL provides efficient fetching of records. And GlassFish v3, with EclipseLink JPA integrated, makes it much seamless for you.

Thanks to Mr GlassFish Persistence (aka Mitesh :) for helping me understand the inner workings.

Discuss this more at Creating Quick and Powerful Web Applications with MySQL, GlassFish, and NetBeans technical session in the upcoming MySQL Users Conference!

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 glassfish v3 eclipselink jpa mysql

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

Tuesday Aug 05, 2008

TOTD #40: jQuery Autcomplete widget with MySQL, GlassFish, NetBeans

TOTD #39 explained how to create an Autocomplete widget (server-powered autocompleting of text fields, similar to Google Suggest) using Prototype/Script.aculo.us libraries with NetBeans, GlassFish and MySQL. This Tip Of The Day (TOTD) builds upon that project and shows how same functionality can be achieved using jQuery Library.
  1. Use the NetBeans project created in TOTD #39. Right-clicking on the project, select "New", "JSP...", enter the name as "index2" and click on "Finish".
  2. Download jquery JavaScript library from here (1.2.6 (minified) as of this writing) and copy into the "javascripts" folder of your NetBeans project.
  3. Copy contents from "index.jsp" into "index2.jsp".
  4. Borrowing the code from AjaxCompleter Tutorial, replace <script> tags in "index2.jsp" with the following code fragment:

            <script src="javascripts/jquery-1.2.6.min.js" type="text/javascript"></script>
            <script type="text/javascript">
                function autocomplete(autocomplete) {
                    if (autocomplete.length == 0) {
                        $('#autocomplete_choices').hide();
                    } else {
                        $.post("/Autocomplete/StatesServlet", { autocomplete_parameter: "" + autocomplete + ""},
                            function(data) {
                                if (data.length > 0) {
                                    $('#autocomplete_choices').show();
                                    $('#autocomplete_choices').html(data);
                                }
                            });
                    }
                }
            </script>

And here are couple of output screenshots:





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

Technorati: totd mysql jpa persistenceunit netbeans glassfish jquery autocomplete

Thursday Jul 24, 2008

TOTD #38: Creating a MySQL Persistence Unit using NetBeans IDE


This TOTD (Tip Of The Day) shows how to create a Persistence Unit (PU) for a MySQL database using NetBeans IDE. This PU can then be used in any of Java EE artifacts (JSP, Servlet, EJB, ...) for database interaction.
  1. In NetBeans IDE, create a new project
    1. Create a new NetBeans Web project and enter the values ("Autocomplete") as shown:



      and click on "Next".
    2. Choose GlassFish v2 as the deployment server and then click on "Finish".
  2. Set up the database
    1. Start the database as:

      ~ >sudo mysqld_safe --user root
      Password:<YOUR PASSWORD>
      Starting mysqld daemon with databases from /usr/local/mysql/data

    2. Create a user, create the database and grant the privileges to newly created user as:

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

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

      mysql> GRANT ALL on states.\* TO duke;
      Query OK, 0 rows affected (0.00 sec)
    3. In NetBeans IDE, Services panel, right-click on Databases and click on "New Connection..." and enter the values as shown:



      and click on "OK" and again on "OK".
    4. Right-click on the newly created database and select "Execute Command ..." as shown:


    5. Create the database table as:

      CREATE TABLE STATES (
            id INT,
            abbrev VARCHAR(2),
            name VARCHAR(50),
            PRIMARY KEY (id)
      );

      and click on the green button to run the query as shown here:


    6. Following the same instructions, populate the table using the following SQL:

      INSERT INTO STATES VALUES (1, "AL", "Alabama");
      INSERT INTO STATES VALUES (2, "AK", "Alaska");
      INSERT INTO STATES VALUES (3, "AZ", "Arizona");
      INSERT INTO STATES VALUES (4, "AR", "Arkansas");
      INSERT INTO STATES VALUES (5, "CA", "California");
      INSERT INTO STATES VALUES (6, "CO", "Colorado");
      INSERT INTO STATES VALUES (7, "CT", "Connecticut");
      INSERT INTO STATES VALUES (8, "DE", "Delaware");
      INSERT INTO STATES VALUES (9, "GL", "Florida");
      INSERT INTO STATES VALUES (10, "GA", "Georgia");
      INSERT INTO STATES VALUES (11, "HI", "Hawaii");
      INSERT INTO STATES VALUES (12, "ID", "Idaho");
      INSERT INTO STATES VALUES (13, "IL", "Illinois");
      INSERT INTO STATES VALUES (14, "IN", "Indiana");
      INSERT INTO STATES VALUES (15, "IA", "Iowa");
      INSERT INTO STATES VALUES (16, "KS", "Kansas");
      INSERT INTO STATES VALUES (17, "KY", "Kentucky");
      INSERT INTO STATES VALUES (18, "LA", "Louisiana");
      INSERT INTO STATES VALUES (19, "ME", "Maine");
      INSERT INTO STATES VALUES (20, "MD", "Maryland");
      INSERT INTO STATES VALUES (21, "MA", "Massachussetts");
      INSERT INTO STATES VALUES (22, "MI", "Michigan");
      INSERT INTO STATES VALUES (23, "MN", "Minnesota");
      INSERT INTO STATES VALUES (24, "MS", "Mississippi");
      INSERT INTO STATES VALUES (25, "MO", "Missouri");
      INSERT INTO STATES VALUES (26, "MT", "Montana");
      INSERT INTO STATES VALUES (27, "NE", "Nebraska");
      INSERT INTO STATES VALUES (28, "NV", "Nevada");
      INSERT INTO STATES VALUES (29, "NH", "New Hampshire");
      INSERT INTO STATES VALUES (30, "NJ", "New Jersey");
      INSERT INTO STATES VALUES (31, "NM", "New Mexico");
      INSERT INTO STATES VALUES (32, "NY", "New York");
      INSERT INTO STATES VALUES (33, "NC", "North Carolina");
      INSERT INTO STATES VALUES (34, "ND", "North Dakota");
      INSERT INTO STATES VALUES (35, "OH", "Ohio");
      INSERT INTO STATES VALUES (36, "OK", "Oklahoma");
      INSERT INTO STATES VALUES (37, "OR", "Orgeon");
      INSERT INTO STATES VALUES (38, "PA", "Pennsylvania");
      INSERT INTO STATES VALUES (39, "RI", "Rhode Island");
      INSERT INTO STATES VALUES (40, "SC", "South Carolina");
      INSERT INTO STATES VALUES (41, "SD", "South Dakota");
      INSERT INTO STATES VALUES (42, "TN", "Tennessee");
      INSERT INTO STATES VALUES (43, "TX", "Texas");
      INSERT INTO STATES VALUES (44, "UT", "Utah");
      INSERT INTO STATES VALUES (45, "VT", "Vermont");
      INSERT INTO STATES VALUES (46, "VA", "Virginia");
      INSERT INTO STATES VALUES (47, "WA", "Washington");
      INSERT INTO STATES VALUES (48, "WV", "West Virignia");
      INSERT INTO STATES VALUES (49, "WI", "Wisconsin");
      INSERT INTO STATES VALUES (50, "WY", "Wyoming");
  3. Create and configure the persistence unit
    1. Right-click on the newly created project and select "New", "Entity Classes from Database ..." as shown:


    2. In DataSource, select "New Data Source..." and enter the JNDI name "jndi/states" as shown:


    3. Select "STATES" table in "Available Tables:" and click on "Add >" and then "Next >".
    4. Click on "Create Persistence Unit ...", take all the defaults and click on "Create".
    5. Enter the package name as "server" and click on "Finish".
    6. Expand "Configuration File", open "persistence.xml". Unselect "Include All Entity Classes" check box, click on "Add Class...", select "server.States" and click on OK. The updated view looks like:

    7. Select the XML view and replace <properties/> with

          <properties>
              <property name="toplink.jdbc.user" value="duke"/>
              <property name="toplink.jdbc.password" value="duke"/>
          </properties>

      The username and password values must match the ones specified during database creation. The updated "persistence.xml" looks like:

      <?xml version="1.0" encoding="UTF-8"?>
      <persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
        <persistence-unit name="AutocompletePU" transaction-type="JTA">
          <jta-data-source>jndi/states</jta-data-source>
          <class>server.States</class>
          <exclude-unlisted-classes>true</exclude-unlisted-classes>
          <properties>
            <property name="toplink.jdbc.user" value="duke"/>
            <property name="toplink.jdbc.password" value="duke"/>
          </properties>
        </persistence-unit>
      </persistence>
  4. Create a Servlet to perform the database operations
    1. Right-click on the project, select "New", "Servlet".
    2. Enter the class name as "StatesServlet" and package as "server" and click on "Finish".
    3. Add the following fragment in the beginning of the class:

          EntityManager em;

          @Override
          public void init() throws ServletException {
              EntityManagerFactory emf = Persistence.createEntityManagerFactory("AutocompletePU");
              em = emf.createEntityManager();
          }

      Alternatively, you can use resource injection to populate the EntityManager. Use the following fragment, instead of the above, to achieve that:

          @PersistenceContext(unitName="AutocompletePU")
          EntityManager em;
    4. Replace the commented code in "processRequest" with the following fragment:

                  String abbrev = request.getParameter("abbrev");

                  List<States> list = em.createNamedQuery("States.findByAbbrev").
                          setParameter("abbrev", abbrev).
                          getResultList();

                  if (list.size() > 0) {
                      States s = list.get(0);
                      out.println("Found " + s.getName() + " with abbrev \\"" + abbrev + "\\"");
                  } else {
                      out.println("No matching state found with \\"" + abbrev + "\\"");
                  }

      and fix the imports by right-clicking in editor pane and selecting "Fix Imports".
    5. Right-click on the project and select "Undeploy and Deploy".
Now let's try it!

Invoking "curl http://localhost:8080/Autocomplete/StatesServlet?abbrev=CA" shows the following output on command prompt:

Found California with abbrev "CA"

Alternatively, you can enter this URL in browser as well to see the output as:



Invoking "http://localhost:8080/Autocomplete/StatesServlet?abbrev=CB" shows the output:



Even though MySQL is used as the database in this case, any other database can be easily used for creating this portable PU.

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

Technorati: totd mysql jpa persistenceunit netbeans glassfish
Technorati: totd mysql jpa persistenceunit netbeans glassfish jquery autocomplete
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