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

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