Miles to go …

October 2, 2009

TOTD #109: How to convert a JSF managed bean to JSR 299 bean (Web Beans) ?

Filed under: frameworks, glassfish, javaee, javaserverfaces, totd — Tags: , — arungupta @ 1:34 pm

This entry is a follow up to TOTD #95 and shows how to use the recent integrations of JSR 299 in GlassFish v3 to convert a JSF managed bean to a JSR 299 bean (aka Web Beans). The TOTD #95 describes a simple Java EE 6 web application that uses Java Server Faces 2.0 components for displaying the results of a database query conducted by EJB 3.1 and JPA 2.0 classes.

The EJB class, which also acts as the JSF managed bean, looks like:

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

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

Three changes are required to convert this class into a JSR 299 compliant bean (Web Bean) as listed below:

  1. Add an empty "beans.xml" to the WEB-INF directory.
  2. Replace "@ManagedBean" with "@javax.inject.Named annotation". "@javax.inject" annotations are defined by JSR 330.
  3. Resource injection does not work with JPA classes, yet, so populate EntityManager explicitly as explained below:

    1. Replace EntityManagerFactory resource injection:

      @PersistenceUnit
      EntityManagerFactory emf;
      

      with:

      EntityManager emf = Persistence.createEntityManagerFactory("HelloEclipseLinkPU");
      
    2. Add the required entity classes explicitly to "persistence.xml". If the persistence unit is injected then the container automatically scans the web application root for any entity classes.

      1. Expand "Configuration Files" and edit "persistence.xml".
      2. Uncheck "Include All Entity Classes in …" check box.
      3. Click on "Add Class…", select "state.States", and click on "OK".

That’s it, re-deploy your application and now you are using the Web Beans integration in GlassFish v3 instead of JSF managed bean. The output is available at "http://localhost:8080/HelloEclipseLink/forwardToJSF.jsp" as shown:

This is the exact same output as shown in TOTD #95.

Now, one-by-one, JPA, EJB, Transactions and other components will start working. Read Roger’s blog for another example of Web Beans in GlassFish.

A complete archive of all the tips is available here.

Technorati: totd glassfish v3 mysql javaee6 javaserverfaces webbeans jsr299  netbeans

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

October 1, 2009

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

Filed under: frameworks, glassfish, javaee, javaserverfaces, netbeans, totd — Tags: , — arungupta @ 11:00 am

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 {
      
       @PersistenceContext
       EntityManager em;
      
       public List getEmployees() {
       return em.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

Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DZone
  • email
  • 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

Filed under: glassfish, javaserverfaces, netbeans, totd — Tags: , , , , — arungupta @ 3:00 am

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
  • email
  • 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

Filed under: glassfish, javaserverfaces, netbeans, totd — Tags: , , , , — arungupta @ 3:00 am

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>
  4. 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
  • email
  • 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

Filed under: glassfish, javaserverfaces, netbeans, totd — Tags: , , , , — arungupta @ 3:00 am

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
    • email
    • StumbleUpon
    • Technorati
    • Twitter
    • Slashdot

    October 24, 2008

    TOTD #51: Embedding Google Maps in Java Server Faces using GMaps4JSF

    Filed under: javaserverfaces, netbeans, totd — arungupta @ 4:00 am


    GMaps4JSF allows Google Maps to be easily integrated with any JSF application. This blog shows how to use this library with Mojarra – JSF implementation delivered from the GlassFish community.

    TOTD #50 explains how to create a simple JSF 2.0 application and deploy on GlassFish v3 prelude using Mojarra 2.0 EDR2. The application allows to create a database of cities/country that you like. It uses integrated Facelets and the newly introduced JavaScript APIs to expose Ajax functionality. This blog shows how to extend that application to display a Google Map and Street View of the entered city using this library.

    1. Configure GMapsJSF library in the NetBeans project (created as described in TOTD #50)
      1. Download gmaps4jsf-core-1.1.jar.
      2. In the existing NetBeans project, right-click on the project, select Properties, Libraries, click on “Add JAR/Folder” and point to the recently download JAR.
      3. Configure Facelets support for this library. This is an important step since Facelets are the default viewing technology in JSF 2.0.
    2. In the NetBeans project, create a new Java class “server.CityCoordinates” that will use Google Geocoding APIs to retrieve latitude and longitude of the entered city. It also create a “details” entry by concatenating city and country name. Use the code listed below:
          private float latitude;
          private float longitude;
          private String details;
          @ManagedProperty(value=”#{cities}”)
          private Cities cities;

          private final String BASE_GEOCODER_URL = “http://maps.google.com/maps/geo?”;
          private final String ENCODING = “UTF-8″;
          private final String GOOGLE_MAPS_KEY = “GOOGLE_MAPS_API_KEY”;
          private final String OUTPUT_FORMAT = “CSV”;

          public String getLatLong() throws IOException {
              details = cities.getCityName() + “, ” + cities.getCountryName();

              String GEOCODER_REQUEST =
                      BASE_GEOCODER_URL +
                      “q=” + URLEncoder.encode(details, ENCODING) +
                      “&key=” + GOOGLE_MAPS_KEY +
                      “&output=” + OUTPUT_FORMAT;
              BufferedReader reader = new BufferedReader(
                      new InputStreamReader(
                          new URL(GEOCODER_REQUEST).openStream()));
              String line = null;
              int statusCode = -1;
              while ((line = reader.readLine()) != null) {
                  // 200,4,37.320052,-121.877636
                  // status code,accuracy,latitude,longitude
                  statusCode = Integer.parseInt(line.substring(0, 3));
                  if (statusCode == 200) {
                      int secondComma = line.indexOf(“,”, 5);
                      int lastComma = line.lastIndexOf(“,”);
                      latitude = Float.valueOf(line.substring(secondComma+1, lastComma));
                      longitude = Float.valueOf(line.substring(lastComma+1));
                      System.out.println(“Latitude: ” + latitude);
                      System.out.println(“Longitude: ” + longitude);
                  }
              }

              return “map”;
          }

          // getters and setters

      “getLatLong()” method retrieves geocoding information using HTTP by passing the city and country name, Google Maps API key and CSV output format. The result is then processed to retrieve status code, latitude and longitude. Add the following annotation to this class:

      @ManagedBean(name=”coords”, scope=”request”)

      This ensures that “server.CityCoordinates” is injected as a managed bean in the runtime.

    3. Add a new button in “welcome.xhtml” right after “submit” button as:
      <h:commandButton action=”#{coords.getLatLong}” value=”map”/>
    4. Add a new page “map.xhtml” as:
      <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
      <html xmlns=”http://www.w3.org/1999/xhtml”
            xmlns:h=”http://java.sun.com/jsf/html”
            xmlns:m=”http://code.google.com/p/gmaps4jsf/”>
          <head>
              <script src=”http://maps.google.com/maps?file=api&amp;v=2&amp;key=ABQIAAAAF9QYjrVEsD9al2QCyg8e-hTwM0brOpm-All5BF6PoaKBxRWWERRHQdtsJnNsqELmKZCKghs54I-0Uw” type=”text/javascript”> </script>
          </head>
        &nbsp
      ; <body>
              <m:map
                  latitude=”#{coords.latitude}”
                  longitude=”#{coords.longitude}”
                  width=”500px”
                  height=”300px”
                  zoom=”14″
                  addStretOverlay=”true”>
                  <m:marker draggable=”true”>
                      <m:eventListener eventName=”dragend” jsFunction=”showStreet”/>
                  </m:marker>
                  <m:htmlInformationWindow htmlText=”#{coords.details}”/>
                  <m:mapControl name=”GLargeMapControl” position=”G_ANCHOR_BOTTOM_RIGHT”/>
                  <m:mapControl name=”GMapTypeControl”/>
              </m:map>
              <br/> <br/>
              <m:streetViewPanorama width=”500px” height=”200px”
                                    latitude=”#{coords.latitude}” longitude=”#{coords.longitude}”
                                    jsVariable=”pano1″ />

              <script type=”text/javascript”>
                  function showStreet(latlng) {
                      pano1.setLocationAndPOV(latlng);
                  }

              </script>
              <form jsfc=”h:form”>
                  <input jsfc=”h:commandButton” action=”back” value=”Back”/>
              </form>
          </body>
      </html>

      The code is borrowed and explained in An Introduction to GMaps4JSF. Basically the code displays a Google Map and Street View where the latitude and longitude are bound by “server.CityCoordinates” managed bean. And these attributes are populated using the geocoding information earlier. The Street View corresponds to marker in the Map which is draggable. So if the marker is dropped to a different location in the map then the Street View changes accordingly.

    5. Add new navigation rules to “faces-config.xml” as:
          <navigation-rule>
              <from-view-id>/welcome.xhtml</from-view-id>
              <navigation-case>
                  <from-outcome>map</from-outcome>
                  <to-view-id>/map.xhtml</to-view-id>
              </navigation-case>
          </navigation-rule>
          <navigation-rule>
              <from-view-id>/map.xhtml</from-view-id>
              <navigation-case>
                  <from-outcome>back</from-outcome>
                  <to-view-id>/welcome.xhtml</to-view-id>
              </navigation-case>
          </navigation-rule>

    That’s it, now your application is ready!

    Now when a city and country name are entered on “welcome.xhtml” and “map” button is clicked then the corresponding Google Map along with the street view are shown in next page.

    If “San Jose” is entered on “http://localhost:8080/Cities/faces/welcome.xhtml” then the following page is shown:

    Clicking on “map” button shows the following page:

    If the marker is drag/dropped to 280 and 87 junction, then the page looks like:

    Some other useful pointers:

    Have you tried your JSF 1.2 app on Mojarra 2.0 ? Drop a comment on this blog if you have.

    File JSF related bugs here using “2.0.0 EDR2″ version and ask your questions on webtier@glassfish.dev.java.net.

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

    Technorati: totd javaserverfaces mojarra glassfish v3 netbeans gmaps4jsf googlemaps

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

    October 23, 2008

    TOTD #50: Mojarra 2.0 EDR2 is now available – Try them with GlassFish v3 and NetBeans 6.5

    Filed under: javaserverfaces, netbeans, totd — arungupta @ 7:00 am

    Yaaay, 50th tip!! The previous 49 tips are available here.

    Mojarra EDR2 is now available – download binary and/or source bundle!

    GlassFish v2 UR2 ships with Mojarra 1.2.0_04 and v3 prelude comes with 1.2.0_10. The Mojarra binaries in both v2 and v3 can be easily replaced by the new ones as described in Release Notes. Additionally, TOTD# 47 explains how to get started with Mojarra 2.0 on GlassFish v2. This blog will guide you through the steps of installing these bits on GlassFish v3 Prelude and show how to use them with NetBeans IDE.

    1. Download latest GlassFish v3 prelude and unzip.
    2. Start Updatetool from “bin” directory. The first run of the tool downloads and installs the tool. Start the tool by typing the command again to see the screen shown below:

    3. Click on “Update”, “Accept” the license and the component is then installed in GlassFish directory. Optionally, you can click on “Installed Components” and then verify that bits are installed correctly.
    4. An EDR2 compliant application can now be directly deployed in these GlassFish v3 bits. There is some work required in order to use code completion, auto-fixing of Imports  and similar features in NetBeans 6.5 RC. The steps below describe that.
      1. In “Tools”, “Libraries”, click on “New Library …”, enter the name “JSF2.0″ as shown:

      2. Click on “OK”, “Add JAR/Folder…” and pick “glassfishv3-prelude/glassfish/modules/jsf-api.jar”, click on “OK”.
      3. Right-click on the NetBeans project, select “Properties”, “Libraries” and remove “JSTL1.1″ and “JSF1.2″ libraries.
      4. Click on “Add Library …”, select the newly created “JSF2.0″ library, click “Add Library” and then “OK”.
    5. In order to run “Cities” application on these GlassFish bits copy MySQL Connector/J jar in “glassfishv3-prelude/glassfish/lib” directory and then deploy the application.

    Here are some pointers to get started:

    Have you tried your JSF 1.2 app on Mojarra 2.0 ? Drop a comment on this blog if you have.

    File JSF related bugs here using “2.0.0 EDR2″ version and ask your questions on webtier@glassfish.dev.java.net.

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

    Technorati: totd javaserverfaces mojarra glassfish v3 netbeans

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

    October 17, 2008

    TOTD #49: Converting a JSF 1.2 application to JSF 2.0 – @ManagedBean

    Filed under: javaserverfaces, netbeans, totd — arungupta @ 9:46 am

    This is a follow up to TOTD #48 which showed how to convert a JSF 1.2 application to use new features of JSF 2.0. In this blog, we’ll talk about a new annotation added to the JSF 2.0 specification – @ManagedBean.

    @ManagedBean is a new annotation in the JSF 2.0 specification. The javadocs (bundled with the nightly) clearly defines the purpose of this annotation:

    The presence of this annotation on a class automatically registers the class with the runtime as a managed bean class. Classes must be scanned for the presence of this annotation at application startup, before any requests have been serviced.

    Essentially this is an alternative to <managed-bean> fragment in “faces-config.xml”. This annotation injects a class in the runtime as a managed bean and then can be used accordingly.

    Using this annotation, the following “faces-config.xml” fragment from our application:

    <managed-bean>
            <managed-bean-name>cities</managed-bean-name>
            <managed-bean-class>server.Cities</managed-bean-class>
            <managed-bean-scope>request</managed-bean-scope>
        </managed-bean>
        <managed-bean>
            <managed-bean-name>dbUtil</managed-bean-name>
            <managed-bean-class>server.DatabaseUtil</managed-bean-class>
            <managed-bean-scope>request</managed-bean-scope>
            <managed-property>
                <property-name>cities</property-name>
                <value>#{cities}</value>
            </managed-property>
        </managed-bean>

    is simplified to

    @Entity
    @Table(name = “cities”)
    @ManagedBean(name=”cities”, scope=”request”)
    @NamedQueries({@NamedQuery(…)})
    public class Cities implements Serializable {

    and

    @ManagedBean(name=”dbUtil”, scope=”request”)
    public class DatabaseUtil {

        @ManagedProperty(value=”#{cities}”)
        private Cities cities;

    The specification defines that managed bean declaration in “faces-config.xml” overrides the annotation.

    A worthy addition to this annotation is “eager” attribute. Specifying this attribute on the annotation as @ManagedProperty(…, eager=”true”) allows the class to be instantiated when the application is started. In JSF 1.2 land, developers write their own ServletContextListeners to perform this kind of task. And this can of course be specified in “faces-config.xml” as <managed-bean eager=”true”>.

    Section 11.5.1 of JSF 2.0 EDR2 specification defines several similar annotations that can be used to simplify “faces-config.xml”.

    Have you tried your JSF 1.2 app on Mojarra 2.0 ? Drop a comment on this blog if you have.

    File JSF related bugs here using “2.0.0 EDR1″ version and ask your questions on webtier@glassfish.dev.java.net.

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

    Technorati: totd javaserverfaces glassfish mojarra netbeans

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

    October 15, 2008

    TOTD #48: Converting a JSF 1.2 application to JSF 2.0 – Facelets and Ajax

    Filed under: javaserverfaces, netbeans, totd — arungupta @ 5:00 am

    TOTD #47 showed how to deploy a JSF 1.2 application (using Facelets and Ajax/JSF Extensions) on Mojarra 2.0-enabled GlassFish.  In this blog we’ll use new features added in JSF 2.0 to simplify our application:

    Let’s get started!

    • Re-create the app as defined in TOTD #47. This app is built using JSF 1.2 core components and Facelets. It uses JSF Extensions for adding Ajax capabilities. Lets change this app to use newer features of JSF 2.0.
    • Edit “faces-config.xml” and change the value of faces-config/@version from “1.2″ to “2.0″.
    • Remove the following fragment from “faces-config.xml”:
          <application>
              <view-handler>com.sun.facelets.FaceletViewHandler</view-handler>
          </application>

      This fragment is no longer required because Facelets is the default view technology in JSF 2.0. But it’s important to remember that JSF 2.0 Facelets is disabled by default if “WEB-INF/faces-config.xml” is versioned at 1.2 or older.

    • Remove the following code fragment from “web.xml”:
              <init-param>
                <param-name>javax.faces.LIFECYCLE_ID</param-name>
                <param-value>com.sun.faces.lifecycle.PARTIAL</param-value>
              </init-param>

      This is only required if JSF Extensions APIs are used.

    • Edit “welcome.xhtml” and replace code with:
      <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
      <html xmlns=”http://www.w3.org/1999/xhtml”
            xmlns:ui=”http://java.sun.com/jsf/facelets”
            xmlns:h=”http://java.sun.com/jsf/html”>
          <ui:composition>
              <h:head>
                  <h1><h:outputText value=”What city do you like ?” /></h1>
              </h:head>
             
              <h:body>
                  <h:form prependId=”false”>
                      <h:panelGrid columns=”2″>
                          <h:outputText value=”CityName:”/>
                          <h:inputText value=”#{cities.cityName}”
                                       title=”CityName”
                                       id=”cityName”
                                       required=”true”
                                       onkeyup=”javax.faces.Ajax.ajaxRequest(this, event, { execute: ‘cityName’, render: ‘city_choices’});“/>
                          <h:outputText value=”CountryName:”/>
                          <h:inputText value=”#{cities.countryName}” title=”CountryName” id=”countryName” required=”true”/>
                      </h:panelGrid>
                     
                      <h:commandButton action=”#{dbUtil.saveCity}” value=”submit”/>
                      <br/><br/>
                      <h:outputText id=”city_choices” value=”#{dbUtil.cityChoices}”></h:outputText>
                     
                      <br/><br/>
                      <h:message for=”cityName” showSummary=”true” showDetail=”false” style=”color: red”/><br/>
                      <h:message for=”countryName” showSummary=”true” showDetail=”false” style=”color: red”/>
                  </h:form>
              </h:body>
              <h:outputScript name=”ajax.js” library=”javax.faces” target=”header”/>
          </ui:composition>
         
      </html>

      The differences are highlighted in bold and explained below:

      • “template.xhtml” is no longer required because standard tags are used to identify “head” and “body”.
      • <h:head> and <h:body> are new tags defined in JSF 2.0. These tags define where the nested resources need to be rendered.
      • <h:outputScript> is a new tag defined in JSF 2.0 and allows an external JavaScript file to be referenced. In this case, it is referencing “ajax.js” script and is rendered in “head”. The script file itself is bundled in “jsf-api.jar” in “META-INF/resources/javax.faces” directory. It adds Ajax functionality to the application. li>
      • “javax.faces.Ajax.ajaxRequest” function is defined in the JavaScript file “ajax.js”. This particular function invocation ensures that “city_choices” is rendered when execute portion of the request lifecycle is executed for “cityName” field. The complete documentation is available in “ajax.js”. Read more details about what happens in the background here.

      Notice how the Facelet is so simplified.

    • Refactor “result.xhtml” such that the code looks like as shown below:

      The changes are explained in the previous step, basically a clean Facelet using standard <h:head> and <h:body> tags and everything else remains as is.

    And that’s it, just hit “Undeploy and Deploy” in NetBeans IDE and your application should now get deployed on Mojarra 2.0-enabled GlassFish. To reiterate, the main things highlighted in this blog are:

    • Facelets are integrated in Mojarra 2.0.
    • New tags for resource re-location allow a simpler and cleaner facelet embedded in a JSF application.
    • JavaScript APIs provide a clean way to expose Ajax functionality in JSF app.

    And all of these features are defined in the JSF 2.0 specification. So if you are using Mojarra then be assured that you are developing a standards compliant user interface.

    Have you tried your JSF 1.2 app on Mojarra 2.0 ? Drop a comment on this blog if you have.
    File JSF related bugs here using “2.0.0 EDR1″ version and ask your questions on webtier@glassfish.dev.java.net.

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

    Technorati: totd javaserverfaces glassfish mojarra netbeans

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

    October 14, 2008

    TOTD #47: Getting Started with Mojarra 2.0 nightly on GlassFish v2

    Filed under: javaserverfaces, netbeans, totd — arungupta @ 5:53 am

    Java Server Faces 2.0 specification (JSR 314, EDR2) and implementation (soon to be EDR2) are brewing. This blog shows how to get started with Mojarra – Sun’s implementation of JSF.

    GlassFish v2 comes bundled with Mojarra 1.2_04 which allows you to deploy a JSF 1.2 application. This blog explains how you can update GlassFish v2 to use Mojarra 2.0 nightly. And then it deploys a simple JSF 1.2-based application on this updated GlassFish instance, there by showing that your existing JSF 1.2 apps will continue to work with Mojarra 2.0-enabled GlassFish. This is an important step because it ensures no regression, unless it was a compatibility fix :)

    1. Re-create a simple JSF 1.2 application as described in TOTD #42, TOTD #45 and TOTD #46. This application allows to create a list of cities and store them in a backend database. It uses JSF Extensions to show suggestions, using Ajax, based upon the cities already entered and also uses Facelets as the view technology. Alternatively you can use any pre-existing JSF 1.2 application.
    2. Download Mojarra 2.0 latest nightly.
    3. Follow Release Notes to install the binary, the steps are summarized here for convenience (GlassFish installed in GF_HOME):
      1. Backup “GF_HOME/lib/jsf-impl.jar”.
      2. Copy the new “jsf-api” and “jsf-impl” JARs from the unzipped Mojarra distribution to “GF_HOME/lib”.
      3. Edit “GF_HOME/domains/<domain-name>/config/domain.xml” and add (or update the existing “classpath-prefix”) ‘classpath-prefix=”${com.sun.aas.installRoot}/lib/jsf-api.jar” in the java-config element.
      4. Restart your server.
    4. Deploy the application on Mojarra 2.0-enabled GlassFish, that’s it!

    The application is accessible at “http://localhost:8080/Cities/faces/welcome.xhtml”. Some of the screen captures are shown below.

    If only “S” is entered in the city name, then the following output is shown:

    Now with “San” …

    And another one with “De” …

    With JSF 2.0, Ajax capabilities and Facelets are now part of the specification and have already been integrated in Mojarra. A follow up blog entry will show how to use that functionality.

    The downloaded Mojarra bundle has some samples (in “samples” folder) to get you started, have a look at them as well!

    File JSF related bugs here using “2.0.0 EDR1″ version and ask your questions on webtier@glassfish.dev.java.net.

    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 javaserverfaces glassfish mojarra netbeans

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

    Powered by WordPress