Miles to go …

September 2, 2009

Track your running miles using Apache Wicket, GlassFish, NetBeans, MySQL, and YUI Charts

Filed under: frameworks, glassfish, wicket — Tags: — arungupta @ 2:00 am

Track your running miles using Apache Wicket, GlassFish, NetBeans, MySQL, and YUI Charts

An earlier blog introduced an application that provides basic tracking of your running distance and generate charts to monitor progress.  The idea is to build the same application using different Web frameworks and deploy on GlassFish and then evaluate each framework based upon a pre-defined critieria. The first version was built using JRuby and Ruby-on-Rails. This blog announces the completion of the Apache Wicket version of the application.

All efforts have been applied to ensure a consistent look-and-feel with the original application but there are minor inconsistencies to leverage the default behavior of the framework.

First  here are some snapshots of the application deployed on GlassFish b3 build 61.

The home page looks like:

Here is a summary of all the runlogs:

All the records can be easily paginated through. There are a few validations while adding a new run:

The "datepicker" widget is used for selecting custom dates as shown in the following page:

Here is a line chart of last 30 days of running:

Notice, it also shows the complete summary as well. And finally a barchart for the entire year so far:

The complete instructions to check out and run the Wicket version of this application are available here.

Now comes the time to provide feedback on the Wicket framework based upon my experience of developing this application. The evaluation criteria is explained in detail here.

The feedback may be attributed to my ignorance of the Wicket framework. If so, please feel free to post a comment and I’ll be happy to fix.

  1. MVC separation: Wicket promotes MVC architecture by providing abstract wrappers over model but the actual implementation still needs to be plugged. For example, the controllers need to written from scratch anyway. There is no recommended directory structure that makes MVC inherent. This is related to the fact that Wicket is not a full-stack framework (more on this below).

    The framework provides a clean separation between views in HTML/CSS and business logic using POJO. However a lot (quite a lot) of glue code needs to be written to stitch them together. And it gets verbose really fast because of the multiple inner classes that keeps popping everywhere in the Java code. Also by default POJO and HTML are packaged together and mixing views/models in the same directory is very confusing.

  2. DRY and CoC principles: The framework neither explicitly promote or prohibit DRY or CoC. The standard HTML/CSS/Java techniques can be used to achieve DRY. And because there is no generated code, there is no concept of CoC.
  3. Limited Ajax: The framework provides buttons/links that can make an Ajax request to the back end. But there is no explicit abstraction of XmlHTTPRequest in the framework. And so an external JavaScript library needs to pulled (Prototype in this case) for any direct Ajax invocations.

    The documentation on wicketstuff-prototype is kinda unclear on how the integration works.

  4. ORM: Apache Wicket is a framework for creating UI applications and that’s exactly what it is, nothing beyond. It is not comparable with full stack frameworks like Java EE, Rails or Grails which provides a persistence mechanism, database connectivity, full MVC support, security and other similar features. As a result, this application could not be built using only Wicket. For example, Java Persistence API (JPA) was used for database access and Prototype was used for Ajax functionality. JPA and Prototype are just the chosen ones among other multiple options available.

    1. CRUD generation: Creating a basic CRUD applications required putting together a bunch of POJOs, corresponding HTML pages, JPA controllers and stitching them together.
    2. Table creation: Defined by the chosen persistence library.
    3. Loading data in the table: Defined by the chosen persistence library.
    4. Customizing queries: Defined by the chosen persistence library.
  5. Customization

    1. CSS & JavaScript: Standard HTML, CSS, and JavaScript techniques for packaging are used.
    2. Form Validation & Default Error Handling: There are validators available to enable basic checking like required, number / pattern / range / date validator. Anything above that needs to be custom built and adds to the verbose nature of the framework. For example a "FormValidator" was built to support the validation for each elements of the form. Custom messages for each validation message can be displayed as explained here. More user-friendly messages can be displayed as explained here.
    3. Templates: The template mechanism is really flexible and allows the repetitive code to be easily captured using "markup inheritance".
  6. 3rd Party Libraries: Adding 3rd-party libraries is quite a breeze because standard HTML/CSS/JavaScript integration techniques are used.

    1. Plugins: Wicket-extensions has some components in addition to the core framework. Wicket-stuff provides components that complement the core framework. The core functionality can be extended using wicket-stuff.
    2. Date picker: There are corresponding packages available for YUI, e.g. "org.apache.wicket.extensions.yui.calendar" for adding DatePicker widget.
    3. Pagination was quite simple to implement.
  7. IDEs: NetBeans provides the most advanced support for Wicket development. But the recommended way is to start with a Maven project and NetBeans provide good support for that as well. More on IDE support here. The Edit/Save/Deploy/Refresh cycle required by the Jetty is time consuming though.
  8. Browser Compatibility: The app was tested on Firefox 3.5.2 (on Mac), Safari 4.0.3 (on Mac) and IE 7.0.600.118000 (on Windows Vista) and no issues were encountered.
  9. Production Deployment: Generating a production deployment on GlassFish is very straight forward because of Maven, just create a WAR file using "mvn package" and deploy directly.
  10. Maintainability: The framework requires a good grasp of Object Oriented concepts like inheritance, encapsulation and inner classes. Even though these concepts are very powerful but they can be a maintenance nightmare. Also, the verbose nature of framework will likely make it cumbersome as a maintenance effort. However there is no real experience or feedback in this area.
  11. Any outstanding feature ? – The response time on the Wicket user list is truly outstanding. Most of my issues encountered during the development phase were resolved by asking questions there.
  12. Any pain point ? – As with any new framework, there is always a learning curve. The framework has a large set of APIs and so it takes a while to figure how the pieces fit together and can be assembled together to create a solution. If you are developing with Wicket, then the official documentation is pretty minimal and not much helpful. The very first link in the documentation actually points to Books on Wicket which is indeed a key resource. I borrowed "Wicket in Action" book from a colleague and it turned out to be helpful. But unfortunately the API has evolved since the book was released and so some of the recommendations from the book are already deprecated. The Wicket user list is definitely a very responsive resource and help me build a better understanding of the framework. Wicket Stuff provides a good set of examples as well with complete source code. But even here some of the samples are using deprecated APIs. Another pain point is that "search engine-driven development" paradigm cannot be applied easily because the search results are a mix from the pre- and post-Apache versions of blogs/docs/etc.

The latest version of this evaluation is available here.

TOTD #86 explains how to get started with using Apache Wicket and GlassFish. All other Wicket related entries on this blog are here.

Technorati: wicket glassfish netbeans mysql yahoo yui chart running miles framework

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

August 30, 2009

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

Filed under: eclipse, general, javaee, totd — Tags: , , , , — arungupta @ 11:00 am

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

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

    July 28, 2009

    Track your running miles using JRuby, Ruby-on-Rails, GlassFish, NetBeans, MySQL, and YUI Charts

    Filed under: glassfish, netbeans, rails, running — Tags: , — arungupta @ 11:00 pm

    This blog introduces a new application that will provide basic tracking of your running distance and generate charts to monitor progress. There are numerous similar applications that are already available/hosted and this is a very basic application. What’s different about this ?

    The first version of this application is built using JRuby, Ruby-on-Rails, GlassFish Gem, MySQL, and NetBeans IDE. This combination of technologies is a high quality Rails stack that is used in production deploymnet at various places. Still nothing different ?

    A similar version of this application will be built using a variety of Web frameworks such as Java EEGrails, Wicket, Spring and Struts2 (in no particular order). The goal is to provide a similar application, slightly bigger than “Hello World,” built using different frameworks and deploy on GlassFish. Each framework will then be evaluated based upon the criteria ranging from the basic principles of framework, ease-of-use in design/development/testing/debugging/production of this web app, database interaction, tools support, ability to add 3rd party libraries, browser compatibility and other points. 

    An important point to note is that this is not an exhaustive evaluation of different Web frameworks and the scope is limited only to this application.

    A complete list of frameworks planned is available here. The criteria used to evaluate each framework is described here. Your feedback in terms of Web frameworks and evaluation criteria is highly appreciated.  Please share your feedback on the users list.

    Now the first version of application. The complete instructions to check out and run the Rails version of this application are available here.

    Here are some charts generated using the application:

    and

    YUI is used for all the charting capabilities.

    And here is a short video that explains how the application work:

    If you are a runner, check out the application and use it for tracking your miles. A sample runlog is available in “test/fixtures/runlogs.yml” and races in “test/fixtures/races.yml”.

    If you know Rails, please provide feedback if the application is DRY and using the right set of helpers.

    If you’d like the existing list of web frameworks to be pruned or include another one to the list, let us know.

    Share you feedback at users@runner.kenai.com.

    Technorati: jruby rubyonrails glassfish netbeans mysql yahoo yui chart running miles framework

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

    June 26, 2009

    Digital TV-based Banking using GlassFish, NetBeans and MySQL – Ginga community in Brazil

    Filed under: glassfish, netbeans — Tags: — arungupta @ 4:00 pm

    Learn how GlassFish and NetBeans helped Ginga community to build a TV Banking application in Brazil. See a live demo of the product, it’s really exciting!

    Why GlassFish ? – They love how NetBeans tooling completely hides the complexity of what’s happening underneath and the ease-of-use with GlassFish.


    Thanks Hugo Lavalle for the interview and good luck with your product!

    Technorati: conf fisl brazil glassfish story netbeans mysql ginga digitaltv banking

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

    May 4, 2009

    TOTD #81: How to configure “database.yml” to be used with both JRuby and MRI ?

    Filed under: rails, totd — Tags: , — arungupta @ 9:57 am

    In JRuby-on-Rails tutorial at Rails Conf 2009, Nick Sieger shared a nice little tip on how to configure “database.yml” to be usable with both JRuby and MRI:

    <% jdbc = defined?(JRUBY_VERSION) ? ‘jdbc’ : ” %>
    development:
      adapter: <%= jdbc %>mysql
      encoding: utf8
      reconnect: false
      database: myapp_development
      pool: 5
      username: root
      password:
      socket: /tmp/mysql.sock
    # …

    “JRUBY_VERSION” is defined only if your using JRuby and so the right database adapter is picked up accordingly.

    The complete slides for the tutorial are available here. Learn about other related talks here.

    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: conf railsconf lasvegas tutorial jruby ruby rubyonrails

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

    April 29, 2009

    TOTD #80: Sinatra CRUD application using Haml templates with JRuby and GlassFish Gem

    Filed under: glassfish, netbeans, sinatra, totd — Tags: , , — arungupta @ 2:00 am

    TOTD #79 showed how to run a trivial Sinatra application using GlassFish Gem. Sinatra provides support for Haml, Erb, Builder, Sass, and Inline templates as described here. This TOTD will show how to get started with creating a Sinatra CRUD application using Haml templates.

    Haml is based on one primary principle – Markup should be beautiful because beauty makes you faster.

    Get started by installing the Haml gem as:

    /tools/jruby-1.2.0 >./bin/jruby -S gem install haml –no-ri –no-rdoc
    JRuby limited openssl loaded. gem install jruby-openssl for full support.
    http://wiki.jruby.org/wiki/JRuby_Builtin_OpenSSL
    Successfully installed haml-2.0.9
    1 gem installed

    And follow the tutorial, documentation, and reference page for more details.

    Sinatra is ORM-agnostic and so any Ruby ORM framework such as ActiveRecord, DataMapper, Sequel, and others. DataMapper with JRuby requires work so this TOTD will show how to use ActiveRecord instead. There is sinatras-hat which allows to create RESTy CRUD apps with Sinatra. There probably are mutiple other ways to create this application but I prefer to understanding the wiring so this blog will use a bare minimal structure.

    Anyway, lets get started!

    1. Create the database as:

      ~/tools/jruby/samples/sinatra-sample >mysql –user root
      Welcome to the MySQL monitor.  Commands end with ; or \g.
      Your MySQL connection id is 664
      Server version: 5.1.30 MySQL Community Server (GPL)

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

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

      mysql> use hello_development;
      Database changed
      mysql> CREATE TABLE `runners` (`id` int(11) DEFAULT NULL auto_increment PRIMARY KEY, `distance` float, `minutes` int(11), `created_at` datetime, `updated_at` datetime);             
      Query OK, 0 rows affected (0.06 sec)

    2. Update “hello.rb” from TOTD #79 such that it looks like:
      require ‘rubygems’
      require ’sinatra’
      require ‘activerecord’

      ## Setup

      ActiveRecord::Base.establish_connection(
        :adapter  => “jdbcmysql”,
        :host     => “localhost”,
        :username => “root”,
        :password => “”,
        :database => “hello_development”
      )

      ## Models

      class Runner < ActiveRecord::Base
      end

      ## Controller Actions

      get ‘/hi’ do
        “Hello World!”
      end

      get ‘/’ do
        @runner = Runner.find(:all)
        haml :index
      end

      get ‘/new’ do
        haml :new
      end

      get ‘/:id’ do
        @runner = Runner.find(params[:id])
        if (@runner)
          haml :show
        else
          redirect ‘/’
        end
      end

      post ‘/’ do
        @runner = Runner.new(:distance => params[:distance], :minutes => params[:minutes])
        if @runner.save
          redirect “/#{@runner.id}”
        else
          redirect ‘/’
        end
      end

      Firstly, it pulls in the ActiveRecord dependency. Then “ActiveRecord::Base.establish_connection” is used to establish a connection with the previously created database. “Runner” is tagged as a model class by inheriting from “ActiveRecord::Base” and uses the default table name (“runners” in this case). Add four new methods:

      1. Three GET methods to show all the runners, a form to enter new data, and show a particular log entry. Each method requires a HAML template (will be created in next step) to render the information.
      2. One POST method to save the newly created log entry in the database.
    3. Create a new directory “views” and create the following files in that directory. Each file serves as a view and rendered from an action in “hello.rb”.
      1. “index.haml”: Show all the runners

        %h1 Listing all runners …
        %table
          %tr
            %th Distance
            %th Minutes
          – @runner.each do |r|
            %tr
              %td= r.distance
              %td= r.minutes
        %br
        %a{:href=>”/new”}
          New Runner

      2. “new.haml”: Enter a new entry
        %h1 Adding a new runner log …
        %form{:method=>”post”, :action=>”/”}
          Distance:
          %input{:type=>”text”, :name=>”distance”}
          %br
          Minutes:
          %input{:type=>”text”, :name=>”minutes”}
          %br
          %input{:type=>”submit”, :value=>”Submit”}
          %br

      3. “show.haml”: Show a particular log entry
        %h1 Showing a runner log …

        Distance:
        = @runner.distance
        %br
        Minutes:
        = @runner.minutes
        %br
        %br
        %a{:href=>”/”}= “Show All!”

        The complete directory structure looks like:

        .
        ./hello.rb
        ./views
        ./views/index.haml
        ./views/new.haml
        ./views/show.haml

    That’s it, now run the application as:

    ~/tools/jruby/samples/sinatra-sample >../../bin/jruby -S glassfish
    Starting GlassFish server at: 192.168.1.145:3000 in development environment…
    Writing log messages to: /Users/arungupta/tools/jruby-1.2.0/samples/sinatra-sample/log/development.log.
    Press Ctrl+C to stop.

    The main page is available at “http://localhost:3000/” and looks like:

    Clicking on “New Runner” gives …

    Enter the data, and click on “Submit” to show …

    Click on “Show All!” to see all the entries added so far …

    And after adding few entries the main page looks like …

    This application shows Create and Read from the CRUD, it’s fairly easy to add Update and Delete functionality as well but that’s an excercise left for the readers :-)

    You’ll hear all about it at Develop with Pleasure, Deploy with Fun: GlassFish and NetBeans for a Better Rails Experience at Rails Conf next week.

    Technorati: totd glassfish jruby sinatra crud

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

    April 22, 2009

    MySQL Users Conference 2009 Day 3 – Cloud Shootout

    Filed under: general — Tags: — arungupta @ 11:52 am

    I arrived at the MySQL Users Conference just in time for the The Great Open Cloud Shootout.

    Kaj Arno was asking questions to the invited panelists shown in the picture above. Here is a partial discussion:

    What is cloud ?

    Thorsten Fully automatbale computing infrastructure, changes the way production scale deployments operate, saves time/cost, increases reliability
    Chander Elasiticity is an important aspect, Can “shoot for the moon without shooting foot”, accessing a pool of resources which is infinite from an individual/organization perspective
    Monty Much like electricity/network bandwidth, applying that same model to computing resources
    Jeremy Virtualization is an important piece
    Lew Not new technology, rather a new way of delivery. As a developer, provision the application through the code.

    Who is it for ?

    Monty It’s for you
    Thorsten Amazon launched, mostly for geeks. 2007 -> Amazon skeptical and RightScale gets VC funding, 2008 -> some common usage, 2009 -> Top-down from CIOs. Basically everybody, cross-organiation, vertical
    Mike Horizontal technology opportunity, starting to see mainstream applications including ISVs/primary line of business, interest/adoption is growing
    Chander Definitely growing for ISVs, makes backup sexy, “Even though running a backup company, expected to be entertaining”
    Jeremy Power outlets are shaped differently, technology has not matured enough. Next few years standardization will happen.
    Monty People will never notice it exists, but able to access the information
    Prashant Putting/Sharing the data on cloud

    Why use the cloud ?

    Monty All of a sudden facebook traffic, leverage a collective of people who are already investing in an effort
    Lew Cloud computing based on virtualization
    Mike More & more enterprises moving in the cloud, gain durability & resilience which was not an option because of a single data center
    Jeremy Legacy apps are easiest to move into cloud, they are better understood and can scale easily
    Prashant Cloud is the right approach/dream, not there yet. Traditional apps can be moved into cloud.
    Thorsten Flexibility in development and tests, DBA clone another slave server with exactly the same setup to test out schema changes
    Monty Spin up EC2 instances, run the tests and shut them down … everything in approx $1. Give it back to the cloud and make it more efficient for the world in general.
    Lew We are making it so affordable, cost can be 10% of what it was before.


    Cloud adoption barrier

    Chander Performance, a customer requested a refund where they were trying to shove a 1TB in an hour. US is 6Mbps, needs to significantly increase before it can be utilized.
    Thorsten Compute needs to move where the data is.
    Chander Most businesses will find bandwidth/redundancy limited. Customer always need to customer where not to use cloud and set expectations accordingly

    What apps will never move to cloud ?

    Lew Financially sensitive applications, owning your own data center
    Chander Trust and privacy, it’s more about education though. Encryption is going tobe a key.
    Jeremy Competitiion, unless other companies battle it out and making it easy to to migrate from one service to other, it’ll be difficult. Avoid vendor lock
    in.

    Are there cloud standards ?

    Mike Based on open industry standards,  no deep rooted concern in the user community
    Thorsten Way to operate across different clouds, API is not the most important level. What is a server ? Can I hibernate it, mount it, how much storage volume is allowed, cross-data center boundary are a better abstraction.
    Lew Very early to lock the standards, everybody is currently in a stage of experiementation
    Monty Potential downside to premature standardization, too early to jump to standards
    Chander Open standards are a definite key to success. S3 fostered innovation.
    Thorsten S3 is a good standard but not an open API. It will be doubly nice if it’s “free” or “open” or whatever the word is.
    Mike Standards dont really matter if the performance cannot be met. When innovating at a rapid rate, it’ difficult to make everybody agree upon standards.
    Lew At least publish the API where everybody can use them.
    Chander Showing backup to Sun cloud, Sun has S3 compatible APIs, also compatible to WebDAV.

    Cloud Business Opportunities

    Monty You can
    Mike Very unique and compelling business opportunity. Amazon Dev Pay: Buy infrastructure on demand, setup your software on AMI, set your own price and then customers can use it, “Software as a Innuity”
    Chander Traditional backup vendors will be worried.
    Prashant Database on the cloud
    Lew Seeing an explosion in the amount of data/compute required, accordingly analytics. Tremendous amount of opportunity when Cassandra & Drizzle are cloud-enabled.
    Mike More ISVs in the cloud.
    Jeremy How to do performance tuning and optimizations in cloud, do that for major cloud infrastructure.
    Monty Freedom to work from anywhere, don’t need to be physically at the datacenter, enables multinational consulting
    Chander When more clouds become available, it’ll be explosion which will happen later this year.

    How is cloud measured ?

    Jeremy CPU time in terms of use, storage centric clouds pay for integrity
    Lew Creating Data centers with loading docks.
    Monty Paying for CPU cycle, like mainframe model.
    Thorsten Cloud is like mainframe but very elastic.
    Chander Billing is not a challenge, storage clouds are better because of pricing, compute is challenging

    Databases & Clouds

    Thorsten Flexibility of moving to the next volume, master, slave makes is very refreshing
    Monty Start out thinking M x N problems, never think about one database instance in cloud, there will be X > 1

    And the shootout had to be shutdown because the timing estimates were slightly misjudged

    But all in all, an interesting discussion!

    Come meet us at the GlassFish booth in the Exhibit Floor. Or you can stop by at room #205 for the Whisper Suite for a more personal and 1-1 conversation.

    Technorati: conf mysqlconf mysql santaclara glassfish cloud

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

    The views expressed on this blog are my own and do not necessarily reflect the views of Oracle.
    Powered by WordPress