Thursday Oct 20, 2011

Oracle Public Cloud - Java, Database, Social Network, Fusion CRM, Fusion HCM

The Oracle Public Cloud is a suite of Oracle Applications, Middleware and Database offerings delivered in a self-service, subscription-based, elastically scalable, reliable, highly available and secure manner. Oracle provides hosting, management, software updates, and world-class support for these offerings.

The Oracle Public Cloud includes the following services:
Why Oracle Public Cloud is a better offering than others ?
  • It can be used for enterprise business applications because of the complete (applications, database, middleware), open (based on standards), and flexible (cloud and on-premise deployment with the ability to move applications back-and-forth)
  • Applications are fully integrated and ready to use
  • New applications can be built using standards like Java EE and SQL without locking you into a framework
  • Based upon Exalogic and Exadata offering superior reliability, peformance, and elastic capacity
Read more details at Why Oracle ?.

Watch an interesting set of short introductory videos recorded on some of the services. The first one is an introduction on Oracle Public Cloud:



The next one explains the Oracle Java Cloud Service:



Read more about the Java Service at Reza's blog. See a live demo of the Java Service below:



Then the Oracle Database Cloud Service:



And finally the Oracle Social Network Cloud Service:



Read more details about Oracle Social Network Service. How do you get started ?
Here are some more links for you:
The service will be offered from the US-based data centers and then expanding to EMEA and APAC based upon demand.

Sunday Jun 26, 2011

TOTD #166: Using NoSQL database in your Java EE 6 Applications on GlassFish - MongoDB for now!

The Java EE 6 platform includes Java Persistence API to work with RDBMS. The JPA specification defines a comprehensive API that includes, but not restricted to, how a database table can be mapped to a POJO and vice versa, provides mechanisms how a PersistenceContext can be injected in a @Stateless bean and then be used for performing different operations on the database table and write typesafe queries.

There are several well known advantages of RDBMS but the NoSQL movement has gained traction over past couple of years. The NoSQL databases are not intended to be a replacement for the mainstream RDBMS. As Philosophy of NoSQL explains, NoSQL database was designed for casual use where all the features typically provided by an RDBMS are not required. The name "NoSQL" is more of a category of databases that is more known for what it is not rather than what it is.

The basic principles of NoSQL database are:

  1. No need to have a pre-defined schema and that makes them a schema-less database. Addition of new properties to existing objects is easy and does not require ALTER TABLE. The unstructured data gives flexibility to change the format of data any time without downtime or reduced service levels. Also there are no joins happening on the server because there is no structure and thus no relation between them.
  2. Scalability and performance is more important than the entire set of functionality typically provided by an RDBMS. This set of databases provide eventual consistency and/or transactions restricted to single items but more focus on CRUD.
  3. Not be restricted to SQL to access the information stored in the backing database.
  4. Designed to scale-out (horizontal) instead of scale-up (vertical). This is important knowing that databases, and everything else as well, is moving into the cloud. RBDMS can scale-out using sharding but requires complex management and not for the faint of heart.
  5. Unlike RBDMS which require a separate caching tier, most of the NoSQL databases comes with integrated caching.
  6. Designed for less management and simpler data models lead to lower administration as well.
There are primarily three types of NoSQL databases:
  1. Key-Value stores (e.g. Cassandra and Riak)
  2. Document databases (MongoDB or CouchDB)
  3. Graph databases (Neo4J)
You may think NoSQL is panacea but as I mentioned above they are not meant to replace the mainstream databases and here is why:
  • RDBMS have been around for many years, very stable, and functionally rich. This is something CIOs and CTOs can bet their money on without much worry. There is a reason 98% of Fortune 100 companies run Oracle :-) NoSQL is cutting edge, brings excitement to developers, but enterprises are cautious about them.
  • Commercial databases like Oracle are well supported by the backing enterprises in terms of providing support resources on a global scale. There is a full ecosystem built around these commercial databases providing training, performance tuning, architecture guidance, and everything else. NoSQL is fairly new and typically backed by a single company not able to meet the scale of these big enterprises.
  • NoSQL databases are good for CRUDing operations but business intelligence is extremely important for enterprises to stay competitive. RDBMS provide extensive tooling to generate this data but that was not the original intention of NoSQL databases and is lacking in that area. Generating any meaningful information other than CRUDing require extensive programming.
  • Not suited for complex transactions such as banking systems or other highly transactional applications requiring 2-phase commit.
  • SQL cannot be used with NoSQL databases and writing simple queries can be involving.
Enough talking, lets take a look at some code.
This blog has published multiple blogs on how to access a RDBMS using JPA in a Java EE 6 application. This Tip Of The Day (TOTD) will show you can use MongoDB (a document-oriented database) with a typical 3-tier Java EE 6 application.
Lets get started! The complete source code of this project can be downloaded here.
  1. Download MongoDB for your platform from here (1.8.2 as of this writing) and start the server as:

    arun@ArunUbuntu:~/tools/mongodb-linux-x86_64-1.8.2/bin$./mongod
    ./mongod --help for help and startup options
    Sun Jun 26 20:41:11 [initandlisten] MongoDB starting : pid=11210
    port=27017 dbpath=/data/db/ 64-bit
    Sun Jun 26 20:41:11 [initandlisten] db version v1.8.2, pdfile version
    4.5
    Sun Jun 26 20:41:11 [initandlisten] git version:
    433bbaa14aaba6860da15bd4de8edf600f56501b
    Sun Jun 26 20:41:11 [initandlisten] build sys info: Linux
    bs-linux64.10gen.cc 2.6.21.7-2.ec2.v1.2.fc8xen #1 SMP Fri Nov 20
    17:48:28 EST 2009 x86_64 BOOST_LIB_VERSION=1_41
    Sun Jun 26 20:41:11 [initandlisten] waiting for connections on port 27017
    Sun Jun 26 20:41:11 [websvr] web admin interface listening on port 28017

    The default directory for the database is /data/db and needs to be created as:

    sudo mkdir -p /data/db/
    sudo chown `id -u` /data/db

    You can specify a different directory using "--dbpath" option. Refer to Quickstart for your specific platform.
  2. Using NetBeans, create a Java EE 6 project and make sure to enable CDI and add JavaServer Faces framework.
  3. Download MongoDB Java Driver (2.6.3 of this writing) and add it to the project library by selecting "Properties", "LIbraries", "Add Library...", creating a new library by specifying the location of the JAR file, and adding the library to the created project.
  4. Edit the generated "index.xhtml" such that it looks like:

    <h1>Add a new movie</h1>
    <h:form>
    Name: <h:inputText value="#{movie.name}" size="20"/><br/>
    Year: <h:inputText value="#{movie.year}" size="6"/><br/>
    Language: <h:inputText value="#{movie.language}" size="20"/><br/>
    <h:commandButton actionListener="#{movieSessionBean.createMovie}"
    action="show"
    title="Add"
    value="submit"/>
    </h:form>
    This page has a simple HTML form with three text boxes and a submit button. The text boxes take name, year, and language of a movie and the submit button invokes the "createMovie" method of "movieSessionBean" and then render "show.xhtml".
  5. Create "show.xhtml" ("New" -> "Other..." -> "Other" -> "XHTML File") such that it looks like:
     <head>
    <title><h1>List of movies</h1></title>
    </head>
    <body>
    <h:form>
    <h:dataTable value="#{movieSessionBean.movies}" var="m" >
    <h:column><f:facet name="header">Name</f:facet>#{m.name}</h:column>
    <h:column><f:facet name="header">Year</f:facet>#{m.year}</h:column>
    <h:column><f:facet name="header">Language</f:facet>#{m.language}</h:column>
    </h:dataTable>
    </h:form>

    This page shows the name, year, and language of all movies stored in the database so far. The list of movies is returned by "movieSessionBean.movies" property.
  6. Now create the "Movie" class such that it looks like:

    import com.mongodb.BasicDBObject;
    import com.mongodb.BasicDBObject;
    import com.mongodb.DBObject;
    import javax.enterprise.inject.Model;
    import javax.validation.constraints.Size;

    /**
    * @author arun
    */
    @Model
    public class Movie {
    @Size(min=1, max=20)
    private String name;

    @Size(min=1, max=20)
    private String language;

    private int year;

    // getters and setters for "name", "year", "language"

    public BasicDBObject toDBObject() {
    BasicDBObject doc = new BasicDBObject();

    doc.put("name", name);
    doc.put("year", year);
    doc.put("language", language);

    return doc;
    }

    public static Movie fromDBObject(DBObject doc) {
    Movie m = new Movie();

    m.name = (String)doc.get("name");
    m.year = (int)doc.get("year");
    m.language = (String)doc.get("language");

    return m;
    }

    @Override
    public String toString() {
    return name + ", " + year + ", " + language;
    }
    }

    Other than the usual boilerplate code, the key methods here are "toDBObject" and "fromDBObject". These methods provide a conversion from "Movie" -> "DBObject" and vice versa. The "DBObject" is a MongoDB class that comes as part of the mongo-2.6.3.jar file and which we added to our project earlier.  The complete javadoc for 2.6.3 can be seen here. Notice, this class also uses Bean Validation constraints and will be honored by the JSF layer.
  7. Finally, create "MovieSessionBean" stateless EJB with all the business logic such that it looks like:
    package org.glassfish.samples;

    import com.mongodb.BasicDBObject;
    import com.mongodb.DB;
    import com.mongodb.DBCollection;
    import com.mongodb.DBCursor;
    import com.mongodb.DBObject;
    import com.mongodb.Mongo;
    import java.net.UnknownHostException;
    import java.util.ArrayList;
    import java.util.List;
    import javax.annotation.PostConstruct;
    import javax.ejb.Stateless;
    import javax.inject.Inject;
    import javax.inject.Named;

    /**
    * @author arun
    */
    @Stateless
    @Named
    public class MovieSessionBean {

    @Inject Movie movie;

    DBCollection movieColl;

    @PostConstruct
    private void initDB() throws UnknownHostException {
    Mongo m = new Mongo();
    DB db = m.getDB("movieDB");
    movieColl = db.getCollection("movies");
    if (movieColl == null) {
    movieColl = db.createCollection("movies", null);
    }
    }

    public void createMovie() {
    BasicDBObject doc = movie.toDBObject();
    movieColl.insert(doc);
    }

    public List<Movie> getMovies() {
    List<Movie> movies = new ArrayList();
    DBCursor cur = movieColl.find();
    System.out.println("getMovies: Found " + cur.size() + " movie(s)");
    for (DBObject dbo : cur.toArray()) {
    movies.add(Movie.fromDBObject(dbo));
    }

    return movies;
    }
    }

    The database is initialized in @PostConstruct. Instead of a working with a database table, NoSQL databases work with a schema-less document. The "Movie" class is the document in our case and stored in the collection "movies". The collection allows us to perform query functions on all movies. The "getMovies" method invokes "find" method on the collection which is equivalent to the SQL query "select * from movies" and then returns a List<Movie>.

    Also notice that there is no "persistence.xml" in the project.
  8. Right-click and run the project to see the output as:



    Enter some values in the text box and click on enter to see the result as:



    If you reached here then you've successfully used MongoDB in your Java EE 6 application, congratulations!
Some food for thought and further play ...
In terms of this project, here are some tasks that can be tried:
  1. Encapsulate database management in a JPA persistence provider. Is it even worth it because the capabilities are going to be very different ?
  2. MongoDB uses "BSonObject" class for JSON representation, add @XmlRootElement on a POJO and how a compatible JSON representation can be generated. This will make the fromXXX and toXXX methods redundant.

Monday Jun 06, 2011

TOTD #164: JDBC Statement Leak Detection and Reclaim in GlassFish

If a JDBC Statement is not closed after use then the application will eventually run out of cursors. Enabling JDBC statement leak detection identifies such statements. These statements can be reclaimed as well, and cursors closed. Shalini blogged about how statement leakage can be detected and reclaimed. More details about this feature can also be found in Oracle GlassFish Server Online Docs.

This Tip Of The Day (TOTD) will show you can detect JDBC statement leakage and reclaim them using GlassFish 3.1.

  1. Edit the “glassfish/domains/domain1/config.xml” file and search for “jdbc-connection-pool” element with the name “DerbyPool”. Add the following attributes to the element:
    connection-leak-timeout-in-seconds="10" statement-timeout-in-seconds="6" 
    statement-leak-timeout-in-seconds="2"
    

    The attribute names are intuitive and specify the timeout options for JDBC statement and connection leakage. Notice, it follows the criteria of:
    statement-leak-timeout-in-seconds < statement-timeout-in-seconds < connection-leak-timeout-in-seconds
    Save the changes and (re)start the application server in NetBeans.
  2. Create a Java EE 6 project using NetBeans. Right-click on the project and select “New”, “Session Bean...”, select “Singleton” and specify the name as “TestBean”, a package name of “org.glassfish.samples” and click on “Finish”.
  3. Mark the bean for eager initialization by specifying the "@javax.ejb.Startup" at the class. This ensures that the bean is loaded during application deployment.
  4. Add the following method to the generated bean:
    @javax.annotation.PostConstruct
     void startup() {
       Connection c = null;
       Statement s = null;
       try {
         InitialContext ctx = new InitialContext();
         DataSource ds = (DataSource)ctx.lookup("jdbc/__default");
         c = ds.getConnection();
         s = c.createStatement();
       } catch (SQLException ex) {
         System.err.println("ouch!");
       } catch (NamingException ex) {
         System.err.println("ouch!");
       } finally {
         try {
           if (s != null)
             s.close();
           if (c != null)
             c.close();
         } catch (SQLException ex) {
           System.err.println("ouch!");;
         }
       }
     }
    


    This is a working version of the code with JDBC connection and statements correctly closed.
  5. Deploy the project by right-clicking and selecting “Deploy”. Now comment the two lines in the “finally” block where the statement is checked for null and closed. The project gets autodeployed and the bean is initialized. The following message is displayed in the GlassFish logs in NetBeans:
    
    WARNING: A potential statement leak detected for connection pool DerbyPool. The
     stack trace of the thread is provided below :
    com.sun.gjc.spi.base.StatementWrapper.(StatementWrapper.java:81)
    com.sun.gjc.spi.jdbc40.StatementWrapper40.(StatementWrapper40.java:68)
    com.sun.gjc.spi.jdbc40.ConnectionWrapper40.createStatement(ConnectionWrapper40.java:75)
    org.glassfish.samples.TestBean.startup(TestBean.java:37)
    

    This ensures that JDBC statement leak detection is working. Notice the exact line where the statement is leaked is also highlighted in the stack trace.
  6. Now uncomment the lines previously commented and comment the lines where the connection is checked for null and closed. The following message is displayed in the GlassFish logs in NetBeans:
    
    WARNING: A potential connection leak detected for connection pool DerbyPool. The 
    stack trace of the thread is provided below : com.sun.enterprise.resource.pool.ConnectionPool.setResourceStateToBusy(ConnectionPool.java:324)
    com.sun.enterprise.resource.pool.ConnectionPool.getResourceFromPool(ConnectionPool.java:754)
    com.sun.enterprise.resource.pool.ConnectionPool.getUnenlistedResource(ConnectionPool.java:632)
    

    This ensures that JDBC connection leak detection is working.
  7. Edit “glassfish/domains/domain1/config/domain.xml” and add the following attribute:
    
    statement-leak-reclaim=”true”
    

    to the “jdbc-connection-pool” element with the name “DerbyPool”. This will ensure that the leaked statement is reclaimed and the cursor is closed. Similarly adding

    connection-leak-reclaim=”false”

    ensures that the JDBC connection is reclaimed and returned to the pool.

Monday Feb 01, 2010

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

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

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

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

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

Technorati: netbeans jax-ws metro webservice glassfish jpa database

Thursday Oct 08, 2009

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

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

Lets get started!

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



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



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

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



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



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



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


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



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



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


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



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



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



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



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



      And even a POST request can be generated.

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

A complete archive of all the TOTDs is available here.

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

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

Wednesday Oct 07, 2009

TOTD #111: Rails Scaffold for a pre-existing table using Oracle and GlassFish

TOTD #110 explained how to create a brand new Rails application using Oracle database and run it using GlassFish v Gem. This Tip Of The Day explains how to create a scaffold for a sample schema that ships with Oracle database. Even though Rails Scaffold are good for, well, scaffolding but they do get you started easily. This blog will use the sample HR schema that comes along with Oracle database.

Lets get started!

  1. Copy the reverse_scaffold script in the "script" directory of your application created in TOTD #110. This script generates Model and Forms from a pre-existing database table. More details about this script are here.
  2. Edit "config/database.yml" and change the "development" section to:

    development:
    adapter: oracle_enhanced
    host: localhost
    database: orcl
    username: hr
    password: hr


    The changes are highlighted in bold, only the username and password values are changed to reflect the default values used with the sample database.
  3. Generate the models and forms for "departments" table as:
    ~/samples/v3/rails/oracle/bookstore >~/tools/jruby/bin/jruby script/reverse_scaffold departments department
    JRuby limited openssl loaded. gem install jruby-openssl for full support.
    http://wiki.jruby.org/wiki/JRuby_Builtin_OpenSSL
    JRuby limited openssl loaded. gem install jruby-openssl for full support.
    http://wiki.jruby.org/wiki/JRuby_Builtin_OpenSSL
     exists app/models/
     exists app/controllers/
     exists app/helpers/
     create app/views/departments
     exists app/views/layouts/
     exists test/functional/
     exists test/unit/
     create test/unit/helpers/
     exists public/stylesheets/
     create app/views/departments/index.html.erb
     create app/views/departments/show.html.erb
     create app/views/departments/new.html.erb
     create app/views/departments/edit.html.erb
     create app/views/layouts/departments.html.erb
     create public/stylesheets/scaffold.css
     create app/controllers/departments_controller.rb
     create test/functional/departments_controller_test.rb
     create app/helpers/departments_helper.rb
     create test/unit/helpers/departments_helper_test.rb
     route map.resources :departments
     dependency model
     exists app/models/
     exists test/unit/
     exists test/fixtures/
     create app/models/department.rb
     create test/unit/department_test.rb
     create test/fixtures/departments.yml
    
  4. Edit "app/models/department.rb" and specify the primary key to "department_id" column by adding:
    set_primary_key "department_id"
    

  5. Run the application as:
    ~/samples/v3/rails/oracle/bookstore >~/tools/jruby/bin/jruby -S glassfish -l
    Starting GlassFish server at: 129.145.133.197:3000 in development environment...
    Writing log messages to: /Users/arungupta/samples/v3/rails/oracle/bookstore/log/development.log.
    Press Ctrl+C to stop.
    Oct 6, 2009 2:14:19 PM com.sun.enterprise.v3.services.impl.GrizzlyProxy start
    INFO: Listening on port 3000
    
    . . .
    

    The application is now accessible at "http://localhost:3000/departments" and looks like:
  6. Similarly, create the model and forms for "employees" table as:

    ~/samples/v3/rails/oracle/bookstore >~/tools/jruby/bin/jruby script/reverse_scaffold employees employee
    JRuby limited openssl loaded. gem install jruby-openssl for full support.
    http://wiki.jruby.org/wiki/JRuby_Builtin_OpenSSL
    JRuby limited openssl loaded. gem install jruby-openssl for full support.
    http://wiki.jruby.org/wiki/JRuby_Builtin_OpenSSL
     exists app/models/
     exists app/controllers/
     exists app/helpers/
     create app/views/employees
     exists app/views/layouts/
     exists test/functional/
     exists test/unit/
     exists test/unit/helpers/
     exists public/stylesheets/
     create app/views/employees/index.html.erb
     create app/views/employees/show.html.erb
     create app/views/employees/new.html.erb
     create app/views/employees/edit.html.erb
     create app/views/layouts/employees.html.erb
     identical public/stylesheets/scaffold.css
     create app/controllers/employees_controller.rb
     create test/functional/employees_controller_test.rb
     create app/helpers/employees_helper.rb
     create test/unit/helpers/employees_helper_test.rb
     route map.resources :employees
     dependency model
     exists app/models/
     exists test/unit/
     exists test/fixtures/
     create app/models/employee.rb
     create test/unit/employee_test.rb
     create test/fixtures/employees.yml
    

    Specify the primary key to "employee_id" by adding the following to "app/models/employee.rb" as:
    set_primary_key "employee_id"
    

    The scaffolded table is now available at "http://localhost:3000/employees" and looks like:

So we created a simple Rails CRUD application accessing information from a pre-existing table in the Oracle database server.

Thanks to @mediachk for all the help!

A complete archive of all the TOTDs is available here. The complete list of Rails blog entries are available here.

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

Technorati: totd oracle database glassfish v3 jruby rails oow

Tuesday Oct 06, 2009

TOTD #110: JRuby on Rails application using Oracle on GlassFish

GlassFish v3 is the Reference Implementation for Java EE 6. Following the "extensibility" principle of Java EE 6, it also allows Ruby-on-Rails, Groovy and Grails and Python/Django applications to be seamlessly deployed as well, without any additional packaging. This blog has published multiple entries on deploying a Rails application on GlassFish as given below:

  • TOTD #105: Monitor Rails application using JavaScript
  • TOTD #104: Redmine, Typo, Substruct on GlassFish v3
  • TOTD #84: Apache + mod_proxy_balancer to load balance Rails applications on GlassFish
  • TOTD #81: nginx to load balance Rails applications on GlassFish Gem
  • TOTD #73: Deploying Rails application as WAR on GlassFish v2.1
  • TOTD #72: Deploying Rails application on GlassFish v3
  • TOTD #70: Deploying Rails application on GlassFish Gem

All the existing applications have used JavaDB, SQLite3, or MySQL as the database so far. In the process of getting ready for the upcoming Oracle Open World 2009, this Tip Of The Day will show how to use an Oracle database with a JRuby-on-Rails application deployed on GlassFish v3.

Lets get started!

  1. Install Oracle database as explained in TOTD #106.
  2. Configure JRuby/Rails in GlassFish v3 using one of the mechanisms explained in TOTD #104. Alternatively you can also install the GlassFish gem as:
    >./bin/jruby -S gem install glassfish
    JRuby limited openssl loaded. gem install jruby-openssl for full support.
    http://wiki.jruby.org/wiki/JRuby_Builtin_OpenSSL
    Successfully installed rack-1.0.0
    Successfully installed glassfish-0.9.5-universal-java
    2 gems installed
    Installing ri documentation for rack-1.0.0...
    Installing ri documentation for glassfish-0.9.5-universal-java...
    Installing RDoc documentation for rack-1.0.0...
    Installing RDoc documentation for glassfish-0.9.5-universal-java...
    

    This blog will use GlassFish Gem for running the application described below.
  3. Create a new database user and grant rights using SQL\*Plus as shown:
    Macintosh-187:~ oracle$ sqlplus "/ as sysdba"
    SQL\*Plus: Release 10.2.0.4.0 - Production on Thu Oct 1 12:32:33 2009
    
    Copyright (c) 1982, 2007, Oracle.  All Rights Reserved.
    
    
    Connected to:
    Oracle Database 10g Release 10.2.0.4.0 - Production
    
    SQL> CREATE USER glassfish IDENTIFIED BY glassfish DEFAULT tablespace users TEMPORARY tablespace temp;
    
    User created.
    
    SQL> GRANT CONNECT TO glassfish IDENTIFIED BY glassfish;
    
    Grant succeeded.
    
    SQL> GRANT UNLIMITED TABLESPACE TO glassfish;
    
    Grant succeeded.
    
    SQL> GRANT CREATE TABLE TO glassfish;
    
    Grant succeeded.
    
    SQL> GRANT CREATE SEQUENCE TO glassfish;
    
    Grant succeeded.
    SQL> exit
    Disconnected from Oracle Database 10g Release 10.2.0.4.0 - Production
    
    
    The user name and password are chosen as "glassfish" for simplicity. This is not a recommended setting for production usage though.
  4. Copy Oracle JDBC drivers (odjc6.jar) in JRUBY_HOME/lib directory.
  5. Create a simple Rails application
    1. Make sure the following gems are pre-installed:
      rails (2.3.4)
      activerecord-jdbc-adapter (0.9.2)
      glassfish (0.9.5)
      

      If not, then install them as:
      jruby -S gem install rails activercord-jdbc-adapter glassfish
      
    2. Create a simple Rails application as:
      jruby -S rails bookstore -d oracle
      

    3. Using the normal "jdbc" adapter will give the following error later:

      ActionView::TemplateError (book_url failed to generate from {:controller=>"books", :action=>"show", :id=>#<Book id: #<BigDecimal:3feef1eb,'10000.0',1(8)>, title: "Ultramarathon Man", author: "Dean Karnazes", created_at: "2009-10-06 00:03:14", updated_at: "2009-10-06 00:03:14">}, expected: {:controller=>"books", :action=>"show"}, diff: {:id=>#<Book id: #<BigDecimal:459bdb65,'10000.0',1(8)>, title: "Ultramarathon Man", author: "Dean Karnazes", created_at: "2009-10-06 00:03:14", updated_at: "2009-10-06 00:03:14">}) on line #13 of app/views/books/index.html.erb:
      


      As evident, the "id" column is returned as BigDecimal where as it should be integer. Fortunately the fix is simple, install the "oracle_enhanced_adapter" (docs) as:

      bookstore >~/tools/jruby/bin/jruby -S gem install activerecord-oracle_enhanced-adapter
      JRuby limited openssl loaded. gem install jruby-openssl for full support.
      http://wiki.jruby.org/wiki/JRuby_Builtin_OpenSSL
      Successfully installed activerecord-oracle_enhanced-adapter-1.2.2
      1 gem installed
      Installing ri documentation for activerecord-oracle_enhanced-adapter-1.2.2...
      Installing RDoc documentation for activerecord-oracle_enhanced-adapter-1.2.2...
      

      Using this "enhanced adapter" is highly recommended for connecting with Oracle databases from Rails applications.
    4. Edit "config/database.yml" and change the "development" section to:
      development:
       adapter: oracle_enhanced
       host: localhost
       database: orcl
       username: glassfish
       password: glassfish
      

      Notice, the username and password values are the same as chosen in the SQL statements above.
    5. Generate a scaffold as:

      bookstore >~/tools/jruby/bin/jruby script/generate scaffold book title:string author:string
      JRuby limited openssl loaded. gem install jruby-openssl for full support.
      http://wiki.jruby.org/wiki/JRuby_Builtin_OpenSSL
       exists app/models/
       exists app/controllers/
       exists app/helpers/
       create app/views/books
       exists app/views/layouts/
       exists test/functional/
       exists test/unit/
       create test/unit/helpers/
       exists public/stylesheets/
       create app/views/books/index.html.erb
       create app/views/books/show.html.erb
       create app/views/books/new.html.erb
       create app/views/books/edit.html.erb
       create app/views/layouts/books.html.erb
       create public/stylesheets/scaffold.css
       create app/controllers/books_controller.rb
       create test/functional/books_controller_test.rb
       create app/helpers/books_helper.rb
       create test/unit/helpers/books_helper_test.rb
       route map.resources :books
       dependency model
       exists app/models/
       exists test/unit/
       exists test/fixtures/
       create app/models/book.rb
       create test/unit/book_test.rb
       create test/fixtures/books.yml
       create db/migrate
       create db/migrate/20091005233152_create_books.rb
      
      
    6. Prepare your application for JDBC as:
      bookstore >~/tools/jruby/bin/jruby script/generate jdbc
      JRuby limited openssl loaded. gem install jruby-openssl for full support.
      http://wiki.jruby.org/wiki/JRuby_Builtin_OpenSSL
       exists config/initializers
       create config/initializers/jdbc.rb
       exists lib/tasks
       create lib/tasks/jdbc.rake
      

    7. Migrate the database as:
      ~/samples/v3/rails/oracle/bookstore >~/tools/jruby/bin/jruby -S rake db:migrate
      (in /Users/arungupta/samples/v3/rails/oracle/bookstore)
      == CreateBooks: migrating ====================================================
      -- create_table(:books)
       -> 0.0740s
       -> 0 rows
      == CreateBooks: migrated (0.0750s) ===========================================
      

  6. Lets run the application as:
    ~/samples/v3/rails/oracle/bookstore >~/tools/jruby/bin/jruby -S glassfish -l
    Starting GlassFish server at: 129.145.133.197:3000 in development environment...
    Writing log messages to: /Users/arungupta/samples/v3/rails/oracle/bookstore/log/development.log.
    Press Ctrl+C to stop.
    Oct 6, 2009 9:45:51 AM com.sun.enterprise.v3.services.impl.GrizzlyProxy start
    INFO: Listening on port 3000
    
    . . .
    


    he application is now accessible at "http://localhost:3000/books" and looks like:



    Click on "New Book" and enter the values as shown:



    Click on "Create" to see the output as:



    Click on "Back" to see the main page as:



    After adding another book, this page looks like:



    And another book ...



So we created a brand new JRuby/Rails application and ran it using GlassFish and Oracle backend. A subsequent blog entry will show how to create a similar application using an existing database.

A complete archive of all the TOTDs is available here. The complete list of Rails blog entries are available here.

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

Technorati: totd oracle database glassfish v3 jruby rails oow

Thursday Oct 01, 2009

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

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

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

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

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

Lets get started!

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

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


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



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



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



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



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


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



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



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



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


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

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

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

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

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

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

A complete archive of all the TOTDs is available here.

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

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

Monday Sep 28, 2009

TOTD #106: How to install Oracle Database 10g on Mac OS X (Intel) ?

This Tip Of The Day (TOTD) will explain how to install Oracle Database 10g on Mac OS X.

The official documentation is available here and is very well suited for folks with lots of time and patience. But all I wanted was to install Oracle database server up & running on my localhost so that I can start experimenting with it. All my previous entries have used either JavaDB or MySQL so far, but it's about time ;-)

I started preparing a brief tutorial after following the lengthy documentation but then found this excellent blog entry. And realized the content is looking exactly similar :-) Anyway, below are the instructions I followed and additionally also provide a snapshot of the installer windows.

For the brave of heart, complete installation guide is available in HTML and PDF. Read on for an abbreviated, and yet working version, of the instructions.
  1. Download Oracle database 10g R2 (10.2.0.4.0) from here and unzip.
  2. Check hardware/software requirements. (10.5.4+ required)
  3. Create required groups/users (complete details):
    1. Create Oracle inventory group as:

      # dscl . -create /groups/oinstall
      # dscl . -append /groups/oinstall gid 100
      # dscl . -append /groups/oinstall passwd "\*"
      
    2. Create Oracle software owner as:
      # dscl . -create /users/oracle
      # dscl . -append /users/oracle uid uid_number
      # dscl . -append /users/oracle gid oinstall_gid
      # dscl . -append /users/oracle shell /bin/bash
      # dscl . -append /users/oracle home /Users/oracle
      # dscl . -append /users/oracle realname "Oracle software owner"
      
    3. Create the home directory for Oracle user as:
      # mkdir /Users/oracle
      # chown oracle:oinstall /Users/oracle
      
    4. Set the password for Oracle user:
      # passwd oracle
      
  4. Configure kernel parameters (complete details) by editing "/etc/sysctl.conf" and adding the contents:
    kern.sysv.semmsl=87381
    kern.sysv.semmns=87381
    kern.sysv.semmni=87381
    kern.sysv.semmnu=87381
    kern.sysv.semume=10
    kernel.shmall=2097152
    kernel.sys.shmmax=2147483648
    kernel.sys.shmmni=4096
    kern.maxfiles=65536
    kern.maxfilesperproc=65536
    net.inet.ip.portrange.first=1024
    net.inet.ip.portrange.last=65000
    kern.corefile=core
    kern.maxproc=2068
    kern.maxprocperuid=2068
    
    and reboot the machine for these parameters to take effect.
  5. Configure Oracle user's environment (complete details). In the "oracle" user's home directory, create ".bash_profile" and add the following lines:
    export DISPLAY=:0.0
    export ORACLE_BASE=$HOME
    export ORACLE_SID=orcl
    umask 022
    ulimit -Hn 65536
    ulimit -Sn 65536
    
  6. The "Basic Installation" of "Standard Edition" in an "Interactive" mode can be performed using the "Oracle Universal Installer". This installer is invoked using the script "db/Disk01/runInstaller" (complete details). The screen snapshots are shown below:

















    Choose "oracle" as the database password for simplicity.





    and finally click on "Install" to begin the installation.









    Click on "Password Management..." to unlock the sample database user ...





    The output of these scripts look like:
    ~ > sudo /Users/oracle/oraInventory/orainstRoot.sh
    Changing permissions of /Users/oracle/oraInventory to 770.
    Changing groupname of /Users/oracle/oraInventory to oinstall.
    The execution of the script is complete

    and
    ~ > sudo /Users/oracle/product/10.2.0/db_1/root.sh
    Running Oracle 10g root.sh script ...
    
    The following environment variables are set as:
         ORACLE_OWNER= oracle
         ORACLE_HOME= /Users/oracle/oracle/product/10.2.0/db_1
    Enter the full pathname of the local bin directory: [/usr/local/bin]:
        Copying dbhome /usr/local/bin ...
        Copying oraenv to /usr/local/bin ...
        Copying coraenv to /usr/local/bin ...
    Creating /etc/oratab file...
    Entries will be added to the /etc/oratab file as needed by
    Database Configuration Assistant when a database is created
    Finished running generic part of root.sh script.
    Now product-specific root actions will be performed.




    Click on "Installed Products..." to see the list of Oracle products installed.

  7. There are some more steps before you can start the Oracle listener process.
    1. Edit ".bash_profile" of "oracle" user and add the following settings:
      export ORACLE_HOME=/Users/oracle/oracle/product/10.2.0/db_1
      export PATH=$PATH:$ORACLE_HOME/bin
      export DYLD_LIBRARY_PATH=$ORACLE_HOME/lib
      Not setting DYLD_LIBRARY_PATH gives the following error:
      ~ oracle$ lsnrctl start
      dyld: Library not loaded: /b/227/network/lib/libnnz10.dylib
        Referenced from: /Users/oracle/oracle/product/10.2.0/db_1/bin/lsnrctl
        Reason: image not found
      Trace/BPT trap
      This was not obvious but Googling helped. Make sure to relogin for these changes to take effect.
    2. If your Mac is using DHCP (most likely) then you may see the error shown below:
      ~ oracle$ lsnrctl start
      
      LSNRCTL for MacOS X Server: Version 10.2.0.4.0 - Production on 28-SEP-2009 14:48:49
      
      Copyright (c) 1991, 2007, Oracle.  All rights reserved.
      
      Starting /Users/oracle/oracle/product/10.2.0/db_1/bin/tnslsnr: please wait...
      
      TNSLSNR for MacOS X Server: Version 10.2.0.4.0 - Production
      System parameter file is /Users/oracle/oracle/product/10.2.0/db_1/network/admin/listener.ora
      Log messages written to /Users/oracle/oracle/product/10.2.0/db_1/network/log/listener.log
      Listening on: (DESCRIPTION=(ADDRESS=(PROTOCOL=ipc)(KEY=EXTPROC1)))
      Error listening on: (DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=dhcp-usca14-133-197.SFBay.Sun.COM)(PORT=1521)))
      TNS-12545: Connect failed because target host or object does not exist
       TNS-12560: TNS:protocol adapter error
        TNS-00515: Connect failed because target host or object does not exist
         MacOS X Server Error: 49: Can't assign requested address
      
      Listener failed to start. See the error message(s) above...


      This error occurs because your MacBook may be running on a different IP address if rebooted after the installation and before starting the server. Fortunately, the error message is very intuitive and it's easy to fix the error by editing "$ORACLE_HOME/network/admin/listener.ora" as shown below:
      # listener.ora Network Configuration File: /Users/oracle/oracle/product/10.2.0/db_1/network/admin/listener.ora
      # Generated by Oracle configuration tools.
      
      SID_LIST_LISTENER =
        (SID_LIST =
          (SID_DESC =
            (SID_NAME = PLSExtProc)
            (ORACLE_HOME = /Users/oracle/oracle/product/10.2.0/db_1)
            (PROGRAM = extproc)
          )
          (SID_DESC =
            (SID_NAME = orcl)
            (ORACLE_HOME = /Users/oracle/oracle/product/10.2.0/db_1)
          )
        )
      
      LISTENER =
        (DESCRIPTION_LIST =
          (DESCRIPTION =
            (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1))
            (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
          )
        )
      

      The changes are highlighted in the bold. Basically, add a new SID referring to "orcl". And for DHCP users the value of HOST key needs to be changed from dynamically assigned IP address to "localhost". Strangely, the Installing on DHCP Computers section of the installation guide says nothing about it :(
    3. Additionally, for DHCP users, you need to change "$ORACLE_HOME/network/admin/tnsnames.ora" as:
      # tnsnames.ora Network Configuration File: /Users/oracle/oracle/product/10.2.0/db_1/network/admin/tnsnames.ora
      # Generated by Oracle configuration tools.
      
      ORCL =
        (DESCRIPTION =
          (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
          (CONNECT_DATA =
            (SERVER = DEDICATED)
            (SERVICE_NAME = orcl)
          )
        )
      The changes are highlighted in bold. And here as well change the value of HOST key to "localhost".
  8. And finally, start the database using SQL\*Plus as:
    ~ oracle$ sqlplus "/ as sysdba"
    
    SQL\*Plus: Release 10.2.0.4.0 - Production on Mon Sep 28 17:44:40 2009
    
    Copyright (c) 1982, 2007, Oracle.  All Rights Reserved.
    Connected to an idle instance.
    
    SQL> startup nomount
    ORACLE instance started.
    
    Total System Global Area  612368384 bytes
    Fixed Size                  2085872 bytes
    Variable Size             167775248 bytes
    Database Buffers          436207616 bytes
    Redo Buffers                6299648 bytes
    SQL> alter database mount;
    
    Database altered.
    SQL> alter database open;
    Database altered.
    
    SQL> ALTER USER HR IDENTIFIED BY hr ACCOUNT UNLOCK;
    User altered.
    
    SQL> exit
    Disconnected from Oracle Database 10g Release 10.2.0.4.0 - Production
    The last step of unlocking the account should not be required because we explicitly unlocked the account during installation but that apparently didn't work. And I hit ORA-01033, ORA-01034, ORA-12514, ORA-12541, ORA-12547, and ORA-27101 trying different combinations to get the app working.

    Anyway now re-connect to the HR sample database as:
    
    ~ oracle$ sqlplus hr/hr@orcl
    
    SQL\*Plus: Release 10.2.0.4.0 - Production on Mon Sep 28 17:46:19 2009
    
    Copyright (c) 1982, 2007, Oracle.  All Rights Reserved.
    
    Connected to:
    Oracle Database 10g Release 10.2.0.4.0 - Production
    
    SQL> select table_name from user_tables;
    TABLE_NAME
    ------------------------------
    REGIONS
    LOCATIONS
    DEPARTMENTS
    JOBS
    COUNTRIES
    EMPLOYEES
    JOB_HISTORY
    
    7 rows selected.
    
    SQL> desc regions;
     Name                                      Null?    Type
     ----------------------------------------- -------- ----------------------------
     REGION_ID                                 NOT NULL NUMBER
     REGION_NAME                                        VARCHAR2(25)
    
    SQL> select \* from regions;
     REGION_ID REGION_NAME
    ---------- -------------------------
             1 Europe
             2 Americas
             3 Asia
             4 Middle East and Africa
    

    Note: If the database is not shutdown properly then it can be forced to do so using the command "shutdown abort" using SQL\*Plus.

A complete archive of all the tips is available here.


Technorati: totd oracle database mac osxtips leopard installation

Sunday Aug 30, 2009

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

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

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

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

Lets get started!

  1. Configure database connection - The key point to notice here is that the MySQL Connector/J driver is already built into the tool so there is no need to configure it explicitly.
    1. From "Window", "Show Perspective", change to the database perspective as shown below:

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

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



      This blog uses MySQL sample database sakila. So please download and install the sample database before proceeding further.
    4. Click on "Next >" and specify the database configuration:



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

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



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



      The expanded view shows all the tables in the database.
  2. Create the Web project & configure JPA
    1. Switch to JavaEE perspective by clicking "Window", "Choose Perspective", "Other ..." and choosing "Java EE".
    2. Create a new dynamic web project with the following settings:



      Only the project name needs to be specified and everything else is default. Notice the target runtime indicates that this is a Java EE 6 application. Click on "Finish".
    3. Right-click on the project, search for "facets" and enable "Java Persistence" as shown below:

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



      Make sure to disable "orm.xml" since we are generating a standard Java EE 6 web application. Choose "sakila" as the database. Click on "OK" and again on "OK" to complete the dialog.
  3. Generate the JPA entities
    1. Right-click on the project, select "JPA Tools", "Generate Entities" as shown:

    2. Choose the schema "sakila":



      and click on "Next >". If no values are shown in the schema drop-down, then click on "Reconnect ...".
    3. Specify a package name for the generated entities as "model" and select "film" and "language" table:



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

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



      Also notice that "web.xml" and "sun-web.xml" have been explicitly removed since they are not required by a Java EE 6 application.
    4. "model.Film" class needs to modified slightly because one of the columns is mapped to "Object" which is not a Serializable obect. So change the type of "specialFeatures" from Object to String and also change the corresponding getters/setters accordingly. The error message clearly conveyed during the initial deployment and so could be fixed. But it would be nice to generate the classes that will work out-of-the-box.
  4. Create a Servlet client to retrieve/display data from the database
    1. Right-click on the project, select "New", "Class" and specify the values as:



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

      and the imports as:
      import java.io.IOException;
      import java.util.List;
      
      import javax.persistence.EntityManagerFactory;
      import javax.persistence.PersistenceUnit;
      import javax.servlet.ServletException;
      import javax.servlet.ServletOutputStream;
      import javax.servlet.annotation.WebServlet;
      import javax.servlet.http.HttpServlet;
      import javax.servlet.http.HttpServletRequest;
      import javax.servlet.http.HttpServletResponse;
      
      import model.Film;
      
      
      Basically, this is a Servlet 3.0 specification compliant Servlet that uses @WebServlet annotation. It uses @PersistenceUnit to inject the generated JPA Persistence Unit which is then used to query the database. The database query return all the movies whose title start with "GL" and the response is displayed in an HTML formatted table.
    3. Right-click on the project and select "Run As", "Run on Server" and select GlassFish v3 latest promoted build (this blog used build 61) as:



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

Simple, easy and clean!

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

Download GlassFish Tools Bundle for Eclipse now.

Please send your questions and comments to users@glassfishplugins.dev.java.net.

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

Technorati: glassfish eclipse mysql jpa database

About

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


Java EE 7 Samples

Stay Connected

Search

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