Miles to go …

October 8, 2009

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

Filed under: frameworks, glassfish, javaee, netbeans, totd, webservices — Tags: , , , , — arungupta @ 2:29 am

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

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

October 2, 2009

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

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

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

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

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

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

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

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

    1. Replace EntityManagerFactory resource injection:

      @PersistenceUnit
      EntityManagerFactory emf;
      

      with:

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

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

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

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

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

A complete archive of all the tips is available here.

Technorati: totd glassfish v3 mysql javaee6 javaserverfaces webbeans jsr299  netbeans

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

October 1, 2009

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

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

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

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

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

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

Lets get started!

  1. Configure GlassFish v3 with JDBC connection

    1. Download and unzip build 63.
    2. Download ojdbc6.jar and copy to "glassfishv3/glassfish/domains/domain1/lib/ext" directory.
    3. Start the Application Server as:

      ./bin/asadmin start-domain --verbose &
      
    4. Create a JDBC connection pool as:

      ./bin/asadmin create-jdbc-connection-pool --datasourceclassname oracle.jdbc.pool.OracleDataSource --restype javax.sql.DataSource --property "User=hr:Password=hr:URL=jdbc\:oracle\:thin\:@localhost\:1521\:orcl" jdbc/hr
      

      and verify the connection pool as:

      ./bin/asadmin ping-connection-pool jdbc/hr
      
    5. Create a JDBC resource as:

      ./bin/asadmin create-jdbc-resource --connectionpoolid jdbc/hr jdbc/hr
      
  2. Configure GlassFish v3 build 63 in NetBeans

    1. In NetBeans IDE "Services" panel, right-click on "Servers" and click on "Add Server…". Choose "GlassFish v3" and provide a name as shown below:

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

      and click on "Finish".

  3. Create the Java EE 6 application

    1. In "Projects" pane, right-click and select "New Project…".
    2. Choose "Java Web" and "Web Application" and click on "Next". Choose the project name as "HelloOracle":

      and click on "Next >".

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

      and click on "Next >". Notice "Java EE 6 Web" profile is chosen as the Java EE version.

    4. Select "JavaServer Faces" on the frameworks page:

      and click on "Finish". Notice the JSF libraries bundled with the App Server are used.

  4. Create the Java Persistence Unit

    1. Right-click on the project, select "New", "Entity Classes from Database…":

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

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

      The related tables are automatically included. Click on "Next >".

    3. Click on "Create Persistence Unit …" and take all the defaults and click on "Create".
    4. Specify the package name as "model":

      and click on "Finish". This generates a JPA-compliant POJO class that provide access to tables in the underlying Oracle database. The class name corresponding to each table is shown in the wizard.

  5. Create Enterprise Java Beans

    1. Right-click on the project and select "New Class…".
    2. Specify the class name as "EmployeesBean" and package as "controller", click on "Finish".
    3. Annotate the class to make it an Enterprise Java Bean and a JSF Managed Bean as:

      @javax.ejb.Stateless
      @javax.faces.bean.ManagedBean
      

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

      Also this application is currently using JSF managed bean but will use JSR 299 (aka Web Beans) in a future blog.

    4. Inject the Persistence Unit by adding the following variable:

      @PersistenceUnit
      EntityManagerFactory emf;
      
    5. Add a new method to retrieve the list of all employees as:

      public List getEmployees() {
       return em.createNamedQuery("Employees.findAll").getResultList();
      }
      

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

      The completed class looks like:

      @Stateless
      @ManagedBean
      public class EmployeesBean {
      
       @PersistenceContext
       EntityManager em;
      
       public List getEmployees() {
       return em.createNamedQuery("Employees.findAll").getResultList();
       }
      }
      
  6. Use EJB in the generated JSF page

    1. JSF 2 uses Facelets as the templating mechanism and NetBeans generate a simple "index.xhtml" file to start with. Expand "Web Pages" and open "index.xhtml".
    2. Replace the body template with:

      <h1>First Java EE 6 app using Oracle database</>
      <h:dataTable var="emp" value="#{employeesBean.employees}" border="1">
       <h:column><h:outputText value="#{emp.lastName}"/>, <h:outputText value="#{emp.firstName}"/></h:column>
       <h:column><h:outputText value="#{emp.email}"/></h:column>
       <h:column><h:outputText value="#{emp.hireDate}"/></h:column>
       </h:dataTable>
      

      It uses JSF value expressions to bind the Enterprise Java Bean and dumps the HTML formatted name, email, and hire date of each employee in the database.

  7. Run the project: Right-click on the project and select "Run" to see the output at "http://localhost:8080/HelloOracle/" as:

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

A complete archive of all the TOTDs is available here.

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

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

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

September 14, 2009

TOTD #102: Java EE 6 (Servlet 3.0 and EJB 3.1) wizards in Eclipse

Filed under: eclipse, glassfish, javaee, totd — Tags: , , , — arungupta @ 2:00 am

The Eclipse community’s WTP release with Java EE 6 support has been delayed to Jun 2010. So how do you do Java EE 6 development in Eclipse until then ?

The GlassFish team is trying to bridge the gap by adding new Java EE 6 wizards that allows you to create Servlet 3.0- (JSR 315) and EJB 3.1- (JSR 318) compliant artifacts. So for the first time, in Eclipse, a Java EE 6 application can be created using the GlassFish plugin for Eclipse (ver 1.0.32)!  GlassFish v3 is the Java EE 6 in making and so Eclipse and GlassFish v3 together provides you a good environment for your Java EE 6 development.

This Tip Of The Day (TOTD) explains how to use those wizards using Eclipse 3.4.2. If you have an earlier version of plugin already installed then update it as described in TOTD #66. Make sure to use ver 1.0.33 (recently released) if you are using Eclipse 3.5.x. If you have an earlier version of GlassFish plugin installed, then you may have to start Eclipse with "-clean" flag, basically as "eclipse -clean", after updating the plugin. This will allow the environment to detect the new plugins.

  1. Using Eclipse 3.4.2, install the latest GlassFish Eclipse plugin (ver 1.0.32 or higher) in "Eclipse IDE for Java EE developers" as explained in screencast #28. The correct version snapshot is shown below:

    Install latest GlassFish v3 promoted build (62 as of this writing):

    specify the location:

    and click on "Finish" to complete the install. Make sure to select "JVM 1.6.0" as the Java Runtime Environment as that is the minimum requirement for GlassFish v3.

  2. Create a new "Dynamic Web Project" named "ee6".
  3. Add Servlet 3.0 using wizard

    1. Right-click on the project, select "New", "Other …", expand the "GlassFish" section and select "Web Servlet (Java EE 6)" as shown below:

      and click on "Next >".

    2. Specify the package name as "server" and servlet name as "HelloServlet" as shown below:

      and click on "Finish".

    3. The generated code looks like as shown:

      Notice the usage of "javax.servlet.annotation.WebServlet" annotation to specify the servlet name and url pattern. Also note that no new entries are made in "WEB-INF/web.xml".

    4. Add a new method in the code as:

      protected void doProcess(HttpServletRequest request, HttpServletResponse response) throws IOException {
              ServletOutputStream out = response.getOutputStream();
              out.print("<html><body>");
              out.print("Request received at: " + request.getContextPath());
              out.print("</body></html>");
        }
      

      and invoke this method from both doGet(…) and doPost(…).

    5. Right-click the project, select "Run As", "Run on Server" and select the recently added GlassFish server as shown below:

      and click on "Finish". This shows the default page "http://localhost:8080/index.jsp". Change the URL to "http://localhost:8080/ee6/HelloServlet" to see the output as:

    6. The "web.xml" and "sun-web.xml" can be conveniently deleted from "WebContent", "WEB-INF" and the deployed page will continue to function as expected because all the information is captured in annotations instead of the deployment descriptors.
  4. Add an EJB 3.1-compliant session bean

    1. Select "New", "Other …", expand the "GlassFish" section and select "Session Bean (Java EE 6)" as shown below:

      The important difference to note is that using this new wizard an EJB can now be packaged in a Web project instead of creating a separate "EJB Project".

    2. Specify the package name as "server" and class name as "HelloBean" as shown below:

      The bean type can be chosen from "Stateless", "Stateful" or "Singleton" and appropriate annotations are added accordingly and click on "Finish".

    3. Add a simple method to the generated bean as:

      public String sayHello(String name) {
              return "Hello " + name;
      }
      
    4. Inject a client in the servlet as:

      @EJB HelloBean bean;
      

      and call the business method on EJB as:

      protected void doProcess(HttpServletRequest request, HttpServletResponse response) throws IOException {
              ServletOutputStream out = response.getOutputStream();
              out.print("<html><body>");
              out.print("Request received at: " + request.getContextPath());
              out.print("<br>" + bean.sayHello("Duke"));
              out.print("</body></html>");
       }
      

      and see the response as:

      This new EJB wizard is different from the one that already exists in Eclipse in the following ways:

      1. Singleton session bean can be created
      2. Local interface is off by default
      3. Allows a session bean in a Web project
      4. Simplified wizard flow

So we built a Java EE 6 application using the newly added Servlet 3.0 and EJB 3.1 wizards in GlassFish Plugin for Eclipse.

Please send your feedback and questions to . Let us know what other Java EE 6 features you’d like to see in Eclipse.

A complete archive of all the tips is available here.

Technorati: totd glassfish v3 eclipse javaee servlet3 ejb

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

September 4, 2009

TOTD #101: Applying Servlet 3.0/Java EE 6 “web-fragment.xml” to Lift – Deploy on GlassFish v3

Filed under: frameworks, glassfish, javaee, totd — Tags: , , , — arungupta @ 3:00 am

TOTD #100 explained how to deploy Lift framework applications on GlassFish v3. As explained in TOTD #91, Java EE 6 defines how the framework configuration deployment descriptor can be defined in “META-INF/web-fragment.xml” in the JAR file of the framework instead of mixing it with "WEB-INF/web.xml" which is intended for application deployment descriptor aspects.

This Tip Of The Day (TOTD) explains how to leverage ”web-fragment.xml” to deploy a Lift application on a Java EE 6 compliant container. The original "lift-*.jar" files are untouched and instead a new JAR file is included that contains only the framework configuration deployment descriptor.

The generated "web.xml" from TOTD #100 looks like:

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
<filter>
 <filter-name>LiftFilter</filter-name>
 <display-name>Lift Filter</display-name>
 <description>The Filter that intercepts lift calls</description>
 <filter-class>net.liftweb.http.LiftFilter</filter-class>
</filter>

<filter-mapping>
 <filter-name>LiftFilter</filter-name>
 <url-pattern>/*</url-pattern>
</filter-mapping>

</web-app>

The deployment descriptor defines a Servlet Filter (LiftFilter) that registers the Lift framework with the Web container. And then it defines a URL mapping to "/*". All of this information is required by the Lift framework for request dispatching. And so that makes this fragment suitable for "web-fragment.xml".

Here are simple steps to make this change:

  1. Remove “src/main/webapp/WEB-INF/web.xml” because no application specific deployment descriptors are required.
  2. Include “lift-web-fragment.jar” in the “WEB-INF/lib” of your application by adding the following fragment in your “pom.xml”:

    <dependencies>
    
    . . .
    
      <!– web-fragment –>
      <dependency>
        <groupId>org.glassfish.extras</groupId>
        <artifactId>lift-web-fragment</artifactId>
        <version>1.0</version>
        <scope>runtime</scope>
      </dependency>
    </dependencies>
    
    . . .
    
    <repositories>
      <repository>
        <id>maven2-repository.dev.java.net</id>
        <name>Java.net Repository for Maven</name>
        <url>http://download.java.net/maven/2/</url>
      </repository>
    </repositories>
    

    This file contains only “META-INF/web-fragment.xml” with the following content:

    <web-fragment>
     <filter>
     <filter-name>LiftFilter</filter-name>
     <display-name>Lift Filter</display-name>
     <description>The Filter that intercepts lift calls</description>
     <filter-class>net.liftweb.http.LiftFilter</filter-class>
     </filter>
    
     <filter-mapping>
     <filter-name>LiftFilter</filter-name>
     <url-pattern>/*</url-pattern>
     </filter-mapping>
    </web-fragment>
    
    
  3. Create the WAR file without “web.xml” by editing “pom.xml” and adding the following fragment:

    <build>
       . . .
      <plugins>
        . . .
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-war-plugin</artifactId>
          <version>2.1-beta-1</version>
          <configuration>
            <failOnMissingWebXml>false</failOnMissingWebXml>
          </configuration>
        </plugin>
      </plugins>
    </build>
    

That’s it, now now you can create a WAR file using “mvn package” and deploy this web application on GlassFish v3 latest promoted build (61 as of today) as explained in TOTD #100.

Technorati: totd glassfish v3 lift scala javaee6 servlet web-fragment

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

September 3, 2009

TOTD #100: Getting Started with Scala Lift on GlassFish v3

Filed under: frameworks, glassfish, javaee, totd — Tags: , , — arungupta @ 5:00 am

Yaaay, 100th tip! Read earlier tips here.

Scala is a strongly typed JVM language that provides benefits of functional programming and dynamic languages on the JVM. As a result you get flexibility of language such as Ruby and performance of Java. Lift is an MVC-based Web framework, based on Scala, that claims to pick the best of Rails (ease of development), Seaside (highly granular sessions and security), Django (access control), and Wicket (designer-friendly templating system).

Lift applications can run inside any Java application server. GlassFish v3 can run Rails and Django applications natively and can also run Wicket applications. This Tip Of The Day (TOTD) explains how to get started with Lift applications and run inside GlassFish v3.

  1. Create a new Lift project using Maven as shown:

    ~/samples/v3/lift >mvn archetype:generate -U -DarchetypeGroupId=net.liftweb
    -DarchetypeArtifactId=lift-archetype-blank -DarchetypeVersion=1.0
    -DremoteRepositories=http://scala-tools.org/repo-releases
    -DgroupId=demo.helloworld -DartifactId=helloworld
    -Dversion=1.0-SNAPSHOT
     [INFO] Scanning for projects...
     [INFO] Searching repository for plugin with prefix: 'archetype'.
     [INFO] org.apache.maven.plugins: checking for updates from central
    
     . . .
    
     [INFO] ------------------------------------------------------------------------
     [INFO] BUILD SUCCESSFUL
     [INFO] ------------------------------------------------------------------------
     [INFO] Total time: 14 seconds
     [INFO] Finished at: Tue Sep 01 16:11:34 PDT 2009
     [INFO] Final Memory: 12M/80M
     [INFO] ------------------------------------------------------------------------
    

    This creates a directory "helloworld" which looks like:

    ~/samples/v3/lift/helloworld >find .
    .
    ./pom.xml
    ./src
    ./src/main
    ./src/main/resources
    ./src/main/scala
    ./src/main/scala/bootstrap
    ./src/main/scala/bootstrap/liftweb
    ./src/main/scala/bootstrap/liftweb/Boot.scala
    ./src/main/scala/demo
    ./src/main/scala/demo/helloworld
    ./src/main/scala/demo/helloworld/comet
    ./src/main/scala/demo/helloworld/comet/.keep
    ./src/main/scala/demo/helloworld/model
    ./src/main/scala/demo/helloworld/model/.keep
    ./src/main/scala/demo/helloworld/snippet
    ./src/main/scala/demo/helloworld/snippet/.keep
    ./src/main/scala/demo/helloworld/snippet/HelloWorld.scala
    ./src/main/scala/demo/helloworld/view
    ./src/main/scala/demo/helloworld/view/.keep
    ./src/main/webapp
    ./src/main/webapp/index.html
    ./src/main/webapp/templates-hidden
    ./src/main/webapp/templates-hidden/default.html
    ./src/main/webapp/WEB-INF
    ./src/main/webapp/WEB-INF/web.xml
    ./src/test
    ./src/test/resources
    ./src/test/scala
    ./src/test/scala/demo
    ./src/test/scala/demo/helloworld
    ./src/test/scala/demo/helloworld/AppTest.scala
    ./src/test/scala/LiftConsole.scala
    ./src/test/scala/RunWebApp.scala
    

    In this directory, "src/main/scala" contains Scala source code, "src/main/webapp" contains the HTML and other related artifacts, and "src/test/scala" contains a simple test case to test the generated application. The "demo/helloworld/model" directory is used for models, "demo/helloworld/snippet" for controller, and "demo/helloworld/view" for views. The Lift Getting Started Guide provides a detailed explanation of how the different components work together to provide the end result.

  2. Create a WAR file of the application as:

    ~/samples/v3/lift/helloworld >mvn package [INFO] Scanning for projects...
     [INFO] ------------------------------------------------------------------------
     [INFO] Building helloworld
     [INFO] task-segment: [package]
     [INFO] ------------------------------------------------------------------------
     [INFO] artifact org.scala-tools:maven-scala-plugin: checking for updates from scala-tools.org
     [INFO] artifact org.scala-tools:maven-scala-plugin: checking for updates from central 
    
     . . . 
    
     [INFO] Building war: /Users/arungupta/samples/v3/lift/helloworld/target/helloworld-1.0-SNAPSHOT.war
     [INFO] ------------------------------------------------------------------------
     [INFO] BUILD SUCCESSFUL
     [INFO] ------------------------------------------------------------------------
     [INFO] Total time: 9 minutes 25 seconds
     [INFO] Finished at: Tue Sep 01 16:42:32 PDT 2009
     [INFO] Final Memory: 24M/80M
     [INFO] ------------------------------------------------------------------------
    

    This generates "target/helloworld-1.0-SNAPSHOT.war" file.

  3. The WAR file can be easily deployed to GlassFish v3. Download the latest GlassFish v3 promoted build (61 as of this writing) and unzip. Start the GlassFish server as:

    ~/tools/glassfish/v3/61/glassfishv3 >./bin/asadmin start-domain --verbose
    
    Sep 2, 2009 3:43:09 PM com.sun.enterprise.admin.launcher.GFLauncherLogger info
    INFO: JVM invocation command line:
    
    . . .
    
    Sep 2, 2009 3:46:01 PM OSGiModuleImpl start
    INFO: Started bundle org.glassfish.security [174]
    Sep 2, 2009 3:46:02 PM OSGiModuleImpl start
    INFO: Started bundle org.glassfish.deployment.javaee-full [51]
    

    and deploy the WAR file as:

    ~/samples/v3/lift/helloworld >~/tools/glassfish/v3/8-31/glassfishv3/bin/asadmin deploy target/helloworld-1.0-SNAPSHOT.war
    
    Command deploy executed successfully.
    

    The app is now accessible at "http://localhost:8080/helloworld-1.0-SNAPSHOT/" and the output looks like:

What application server are you using to deploy your Lift applications ?

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

Technorati: totd scala lift glassfish v3

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

September 1, 2009

Java EE 6, GlassFish, Eclipse, Dynamic Languages & Web Frameworks at Silicon Valley Code Camp 2009

Filed under: django, eclipse, frameworks, glassfish, grails, javaee, rails — Tags: , — arungupta @ 2:52 am
Silicon Valley Code Camp 2009
To the community, By the community, For the community

Here is the list of GlassFish related sessions:

  1. Java EE 6 and GlassFish v3: Paving the path for future
  2. Using Eclipse for Java EE 6 development for the GlassFish™ Application Server
  3. Dynamic Languages & Web Frameworks in GlassFish

The detailed agenda for each session is explained here.

Here are the coordinates:

Date: Oct 3/4, 2009
Venue: Foothill College, Los Altos, CA
Cost: Free but registration required

Read the trip reports from 2008 and 2007.

With more than a month to go, already 120 sessions have been submitted and 855 attendees registered. The final agenda is not ready yet but typically all Java sessions are on a single day.

It’s a free event, with free coffee, food and lots of networking. What’s there to loose ?

See ya there!

Technorati: siliconvalleycodecamp glassfish javaee6 eclipse

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

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

August 25, 2009

FREE GlassFish Webinar: “Java EE 6 Overview” – Aug 26, 2009, 10am PT

Filed under: glassfish, javaee — Tags: , , , — arungupta @ 11:00 pm

Java EE 6 is developed as JSR 316 under the Java Community Process. It breaks the “one size fits all” approach with Profiles and improves on the Java EE 5 developer productivity features. Several existing specifications are getting an extreme makeover such as Java Server Faces 2.0 and Servlet 3.0. GlassFish v3 is the Reference Implementation of Java EE 6.

So you’d like to get an overview of Java EE 6 and start developing with GlassFish v3. Please register for a free webinar with coordinates:

Date: Aug 26, 2009
Time: 10am PT

Register here.

Yep, it’s starting in a few hours so make sure to sign up and be ready with your questions. Several specification leads will be available to field your questions.

Technorati: glassfish javaee webinar

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

August 19, 2009

TOTD #96: GlassFish v3 REST Interface to Monitoring and Management – JSON, XML, and HTML representations

Filed under: admin, totd — Tags: , , , , , , — arungupta @ 11:00 pm

GlassFish Monitoring allows you to monitor the state of various runtime components of the application server. This information is used to identify performance bottlenecks and tuning the system for optimal performance, to aid capacity planning, to predict failures, to do root cause analysis in case of failures and sometimes to just ensure that everything is functioning as expected.

GlassFish Management allows you to manage the running Application Server instance such as query/create/delete resources (JDBC, JMS, etc), stop/restart the instance, rotate the log and other similar functions.

GlassFish v3 exposes Monitoring and Management data using a REST Interface. This Tip Of The Day (TOTD) shows how to play with this new functionality. Rajeshwar’s blog has lot of useful information on this topic.

Most of the functionality available in web-based Admin Console and CLI (asadmin) is now available using the REST interface. Both of these are pre-built tools that ships with the GlassFish bundle. The REST interface is a lower level API that enables toolkit developers and IT administrators to write their custom scripts/clients using language of their choice such as Java, JavaScript, Ruby or Groovy.

The default URL for the REST interface of monitoring is “http://localhost:4848/monitoring/domain” and for the management is “http://localhost:4848/management/domain”. Each URL provides an XML, JSON and HTML representation of the resources. If a web browser is used then a HTML representation is returned and displayed nicely in the browser. Rajeshwar’s blog described a Java client written using Jersey Client APIs that can be used to make all the GET/PUT/POST/DELETE requests. This blog will use something more basic, and extremely popular, to make all the RESTful invocations – cURL.

At this time the monitoring resources are read-only (GET) and management can be done using GET/POST/DELETE methods. POST is used for creating and updating resources/objects and the updates can be partial.

Lets get started.

  1. Download the latest continuous build from the trunk and unzip. This functionality is also available in the Web profile bundle. This blog is using build #2023.
  2. Start the application server as:
    ~/tools/glassfish/v3/2023/glassfishv3 >./bin/asadmin start-domain –verbose

    Aug 19, 2009 9:52:45 AM com.sun.enterprise.admin.launcher.GFLauncherLogger info
    INFO: JVM invocation command line:
    /System/Library/Frameworks/JavaVM.framework/Versions/1.6/Home/bin/java
    -cp

    . . .

    INFO: felix.fileinstall.dir            /Users/arungupta/tools/glassfish/v3/2023/glassfishv3/glassfish/domains/domain1/autodeploy-bundles
    Aug 19, 2009 9:53:05 AM
    INFO: felix.fileinstall.debug          1
    Aug 19, 2009 9:53:05 AM
    INFO: felix.fileinstall.bundles.new.start          true

  3. Monitoring information – Lets monitor this GlassFish instance using the REST interface.
    1. Retrieve JSON information – As mentioned above, the monitoring resources are read-only and so the information can be accessed as:
      ~/tools/glassfish/v3/2023/glassfishv3 >curl -H “Accept: application/json” http://localhost:4848/monitoring/domain -v
      * About to connect() to localhost port 4848 (#0)
      *   Trying ::1… connected
      * Connected to localhost (::1) port 4848 (#0)
      > GET /monitoring/domain HTTP/1.1
      > User-Agent: curl/7.16.3 (powerpc-apple-darwin9.0) libcurl/7.16.3 OpenSSL/0.9.7l zlib/1.2.3
      > Host: localhost:4848
      > Accept: application/json
      >
      < HTTP/1.1 200 OK
      < Content-Type: application/json
      < Transfer-Encoding: chunked
      < Date: Wed, 19 Aug 2009 17:40:29 GMT
      <
      {Domain:{},”child-resources”:["http://localhost:4848/monitoring/domain/server"]}
      * Connection #0 to host localhost left intact
      * Closing connection #0

      The command explicitly asks for JSON representation of the resources. The outbound headers are prepended with “>” and inbound headers with “<”. And the JSON representation is shown in the last line as:

      {Domain:{},”child-resources”:["http://localhost:4848/monitoring/domain/server"]}

      The key element to remember here is “http://localhost:4848/monitoring/domain/server” which can be used to retrieve more monitoring information.

    2. XML represetation: Lets change the command to ask for XML representation as:
      ~/tools/glassfish/v3/2023/glassfishv3 >curl -H “Accept: application/xml” http://localhost:4848/monitoring/domain -v
      * About to connect() to localhost port 4848 (#0)
      *   Trying ::1… connected
      * Connected to localhost (::1) port 4848 (#0)
      > GET /monitoring/domain HTTP/1.1
      > User-Agent: curl/7.16.3 (powerpc-apple-darwin9.0) libcurl/7.16.3 OpenSSL/0.9.7l zlib/1.2.3
      > Host: localhost:4848
      > Accept: application/xml
      >
      < HTTP/1.1 200 OK
      < Content-Type: application/xml
      < Transfer-Encoding: chunked
      < Date: Wed, 19 Aug 2009 17:43:51 GMT
      <
      <Domain>
      <child-resource>http://localhost:4848/monitoring/domain/server</child-resource>
      </Domain>
      * Connection #0 to host localhost left intact
      * Closing connection #0

      The command changes the “Accept” header to “application/xml” and now the XML representation of the monitoring resources is returned as:

      <Domain>
      <child-resource>http://localhost:4848/monitoring/domain/server</child-resource>
      </Domain>
    3. HTML representation: The command can be altered to get the HTML representation as “curl -H “Accept: text/html” http://localhost
      :4848/monitoring/domain -v
      “. But HTML is more pleasant when rendered by a browser and so viewing the page “http://localhost:4848/monitoring/domain” in the browser is shown as:

    4. Get more information: As mentioned above, more information about this GlassFish instance can be accessed by GETing from “http://localhost:4848/monitoring/domain/server” and here is the result:
      </tools/glassfish/v3/2023/glassfishv3 >curl -H “Accept: application/json” http://localhost:4848/monitoring/domain/server -v
      * About to connect() to localhost port 4848 (#0)
      *   Trying ::1… connected
      * Connected to localhost (::1) port 4848 (#0)
      > GET /monitoring/domain/server HTTP/1.1
      > User-Agent: curl/7.16.3 (powerpc-apple-darwin9.0) libcurl/7.16.3 OpenSSL/0.9.7l zlib/1.2.3
      > Host: localhost:4848
      > Accept: application/json
      >
      < HTTP/1.1 200 OK
      < Content-Type: application/json
      < Transfer-Encoding: chunked
      < Date: Wed, 19 Aug 2009 17:56:41 GMT
      <
      {Server:{},”child-resources”:["http://localhost:4848/monitoring/domain/server/webintegration",
      "http://localhost:4848/monitoring/domain/server/transaction-service",
      "http://localhost:4848/monitoring/domain/server/network",
      "http://localhost:4848/monitoring/domain/server/jvm",
      "http://localhost:4848/monitoring/domain/server/web",
      "http://localhost:4848/monitoring/domain/server/realm",
      "http://localhost:4848/monitoring/domain/server/http-service"]}
      * Connection #0 to host localhost left intact
      * Closing connection #0

      An HTML rendering of this representation looks like:

      You can keep clicking on the links and more detailed information about that resource is displayed. This is just one HTML representation and is purposely kept light-weight. You can certainly grab the XML representation and apply an XSLT to generate your own HTML rendering.

      The monitoring levels for different modules can be easily changed using the management REST interface as explained below.

  4. Management of the GlassFish instance
    1. Lets see all the options supported by management REST interface as:
      ~/tools/glassfish/v3/2023/glassfishv3 >curl -X OPTIONS http://localhost:4848/management/domain -v
      * About to connect() to localhost port 4848 (#0)
      *   Trying ::1… connected
      * Connected to localhost (::1) port 4848 (#0)
      > OPTIONS /management/domain HTTP/1.1
      > User-Agent: curl/7.16.3 (powerpc-apple-darwin9.0) libcurl/7.16.3 OpenSSL/0.9.7l zlib/1.2.3
      > Host: localhost:4848
      > Accept: */*
      >
      < HTTP/1.1 200 OK
      < Content-Type: application/json
      < Transfer-Encoding: chunked
      < Date: Wed, 19 Aug 2009 18:07:14 GMT
      <
      {
      “Method”:”GET”

      “Method”:”PUT”
      }
      * Connection #0 to host localhost left intact
      * Closing connection #0

      Specifying “-X OPTIONS” switch displays the various HTTP methods supported by the REST interface. Even though the results show GET and PUT, but it really means GET and POST (issue #9177). Lets try “GET” first.

    2. GET JSON information as:
      ~/tools/glassfish/v3/2023/glassfishv3 >curl -H “Accept: application/json” http://localhost:4848/management/domain -v
      * About to connect() to localhost port 4848 (#0)
      *   Trying ::1… connected
      * Connected to localhost (::1) port 4848 (#0)
      > GET /management/domain HTTP/1.1
      > User-Agent: curl/7.16.3 (powerpc-apple-darwin9.0) libcurl/7.16.3 OpenSSL/0.9.7l zlib/1.2.3
      > Host: localhost:4848
      > Accept: application/json
      >
      < HTTP/1.1 200 OK
      < Content-Type: application/json
      < Transfer-Encoding: chunked
      < Date: Wed, 19 Aug 2009 18:14:46 GMT
      <
      {Domain:{“log-root” : “${com.sun.aas.instanceRoot}/logs”,”application-root” : “${com.sun.aas.instanceRoot}/applications”,”locale” : “”,”version” : “re-continuous”},”child-resources”:["http://localhost:4848/management/domain/configs",
      "http://localhost:4848/management/domain/resources","http://localhost:4848/management/domain/servers",
      "http://localhost:4848/management/domain/property","http://localhost:4848/management/domain/applications",
      "http://localhost:4848/management/domain/system-applications","http://localhost:4848/management/domain/stop",
      "http://localhost:4848/management/domain/restart","http://localhost:4848/management/domain/uptime",
      "http://localhost:4848/management/domain/version","http://localhost:4848/management/domain/rotate-log",
      "http://localhost:4848/management/domain/host-port"]}
      * Connection #0 to host localhost left intact
      * Closing connection #0

      As the result shows, there are several RESTful URLs available (in “child-resources” element) to manage this GlassFish instance. For example:

      1. Show the host/port of GlassFish instance as:
        curl -H “Accept: application/json” http://localhost:4848/management/domain/host-port -v

        will show the result as:

        {“GetHostAndPort”:{“value” : “dhcp-usca14-132-79.SFBay.Sun.COM:8080″}}
      2. Show that web-based Admin Console is pre-installed as system application using:
        curl -H “Accept: application/json” http://localhost:4848/management/domain/system-applications/application/__admingui -v

        will show the result as:

        {__admingui:{“libraries” : “”,”availability-enabled” : “false”,”enabled” : “true”,”context-root” : “”,”location” : “${com.sun.aas.installRootURI}/lib/install/applications/__admingui”,”description” : “”,”name” : “__admingui”,”directory-deployed” : “true”,”object-type” : “system-admin”},”child-resources”:["http://localhost:4848/management/domain/system-applications/application/__admingui/module"]} td>
      3. Query the monitoring levels of different modules as:
        curl -H “Accept: application/json” http://localhost:4848/management/domain/configs/config/server-config/monitoring-service/module-monitoring-levels -v

        to see the result as:

        {ModuleMonitoringLevels:{“transaction-service” : “OFF”,”ejb-container” : “OFF”,”jdbc-connection-pool” : “OFF”,”orb” : “OFF”,”http-service” : “OFF”,”connector-connection-pool” : “OFF”,”jms-service” : “OFF”,”connector-service” : “OFF”,”jvm” : “OFF”,”thread-pool” : “OFF”,”web-container” : “OFF”},”child-resources”:[]}

        And then change the monitoring level of Web container as:

        ~/tools/glassfish/v3/2023/glassfishv3 >curl -X POST -d “web-container=ON” -H “Accept: application/json” http://localhost:4848/management/domain/configs/config/server-config/monitoring-service/module-monitoring-levels -v
        * About to connect() to localhost port 4848 (#0)
        *   Trying ::1… connected
        * Connected to localhost (::1) port 4848 (#0)
        > POST /management/domain/configs/config/server-config/monitoring-service/module-monitoring-levels HTTP/1.1
        > User-Agent: curl/7.16.3 (powerpc-apple-darwin9.0) libcurl/7.16.3 OpenSSL/0.9.7l zlib/1.2.3
        > Host: localhost:4848
        > Accept: application/json
        > Content-Length: 16
        > Content-Type: application/x-www-form-urlencoded
        >
        < HTTP/1.1 200 OK
        < Content-Type: application/json
        < Transfer-Encoding: chunked
        < Date: Wed, 19 Aug 2009 22:01:31 GMT
        <
        * Connection #0 to host localhost left intact
        * Closing connection #0
        “http://localhost:4848/management/domain/configs/config/server-config/monitoring-service/module-monitoring-levels” updated successfully

        The last line shows that the monitoring level is successfull updated and can be verified again as:

        ~/tools/glassfish/v3/2023/glassfishv3 >curl -H “Accept: application/json” http://localhost:4848/management/domain/configs/config/server-config/monitoring-service/module-monitoring-levels -v
        * About to connect() to localhost port 4848 (#0)
        *   Trying ::1… connected
        * Connected to localhost (::1) port 4848 (#0)
        > GET /management/domain/configs/config/server-config/monitoring-service/module-monitoring-levels HTTP/1.1
        > User-Agent: curl/7.16.3 (powerpc-apple-darwin9.0) libcurl/7.16.3 OpenSSL/0.9.7l zlib/1.2.3
        > Host: localhost:4848
        > Accept: application/json
        >
        < HTTP/1.1 200 OK
        < Content-Type: application/json
        < Transfer-Encoding: chunked
        < Date: Wed, 19 Aug 2009 22:36:47 GMT
        <
        * Connection #0 to host localhost left intact
        * Closing connection #0
        {ModuleMonitoringLevels:{“transaction-service” : “OFF”,”ejb-container” : “OFF”,”jdbc-connection-pool” : “OFF”,”orb” : “OFF”,”http-service” : “OFF”,”connector-connection-pool” : “OFF”,”jms-service” : “OFF”,”connector-service” : “OFF”,”jvm” : “OFF”,”thread-pool” : “OFF”,”web-container” : “ON”},”child-resources”:[]}
      4. Stop this GlassFish instance using:
        curl -H “Accept: application/json” http://localhost:4848/management/domain/stop -v

        Or restart the instance using:

        curl -H “Accept: application/json” http://localhost:4848/management/domain/restart -v
      5. Create a JDBC resource using an existing connection pool
        1. Lets see all the resources that are available:
          curl -H “Accept: application/json” http://localhost:4848/management/domain/resources -v

          and the results are shown as:

          {Resources:{},”child-resources”:["http://localhost:4848/management/domain/resources/jdbc-connection-pool",
          "http://localhost:4848/management/domain/resources/jdbc-resource"]}
        2. View all the JDBC connection pools as:
          curl -H “Accept: application/json” http://localhost:4848/management/domain/resources/jdbc/connection-pool -v

          and the results are shown as:

          {JdbcConnectionPool:{},”child-resources”:["http://localhost:4848/management/domain/resources/jdbc-connection-pool/__TimerPool",
          "http://localhost:4848/management/domain/resources/jdbc-connection-pool/DerbyPool"]}
        3. See all the JDBC resources available as:
          curl “Accept: application/json” http://localhost:4848/management/domain/resources/jdbc-resource -v

          and the results are shown as:

          {JdbcResource:{},”child-resources”:["http://localhost:4848/management/domain/resources/jdbc-resource/jdbc/__TimerPool",
          "http://localhost:4848/management/domain/resources/jdbc-resource/jdbc/__default"]}
        4. See all the OPTIONS accepted for JDBC resource creation as:
          curl -X OPTIONS -H “Accept: application/json” http://localhost:4848/management/domain/resources/jdbc-resource -v

          with the result as:

          {
          “Method”:”POST”,
          “Message Parameters”:{
          “id”:{“Acceptable Values”:”",”Default Value”:”",”Type”:”class java.lang.String”,”Optional”:”false”},
          “enabled”:{“Acceptable Values”:”",”Default Value”:”true”,”Type”:”class java.lang.Boolean”,”Optional”:”true”},
          “description”:{“Acceptable Values”:”",”Default Value”:”",”Type”:”class java.lang.String”,”Optional”:”true”},
          “target”:{“Acceptable Values”:”",”Default Value”:”",”Type”:”class java.lang.String”,”Optional”:”true”},
          “property”:{“Acceptable Values”:”",”Default Value”:”",”Type”:”class java.util.Properties”,”Optional”:”true”},
          “connectionpoolid”:{“Acceptable Values”:”",”Default Value”:”",”Type”:”class java.lang.String”,”Optional”:”false”}
          }

          “Method”:”GET”

        5. Finally, create the JDBC resource as:
          ~/tools/glassfish/v3/2023/glassfishv3 >curl -d “id=jdbc/sample&connectionpoolid=DerbyPool” http://localhost:4848/management/domain/resources/jdbc-resource -v
          * About to connect() to localhost port 4848 (#0)
          *   Trying ::1… connected
          * Connected to localhost (::1) port 4848 (#0)
          > POST /management/domain/resources/jdbc-resource HTTP/1.1
          > User-Agent: curl/7.16.3 (powerpc-apple-darwin9.0) libcurl/7.16.3 OpenSSL/0.9.7l zlib/1.2.3
          > Host: localhost:4848
          > Accept: */*
          > Content-Length: 42
          > Content-Type: application/x-www-form-urlencoded
          >
          < HTTP/1.1 201 Created
          < Content-Type: text/html
          < Transfer-Encoding: chunked
          < Date: Wed, 19 Aug 2009 20:45:51 GMT
          <
          * Connection #0 to host localhost left intact
          * Closing connection #0
          “http://localhost:4848/management/domain/resources/jdbc-resource/jdbc/sample” created successfully.

          Note, this is a POST request. The JDBC resource name and JDBC connection pool id are passed as CLI parameters using “-d” switch. The last line shows that the JDBC resource was created successfully.

        6. And finally query the JDBC Resources again as:
          curl -H “Accept: application/json” http://localhost:4848/management/domain/resources/jdbc-resource -v

          to see the updated result as:

          {JdbcResource:{},”child-resources”:["http://localhost:4848/management/domain/resources/jdbc-resource/jdbc/__TimerPool",
          "http://localhost:4848/management/domain/resources/jdbc-resource/jdbc/__default",
          "http://localhost:4848/management/domain/resources/jdbc-resource/jdbc/sample"]}

        Similarly JDBC connection pools can be created.

    3. POST can be used to update the top-level attributes such as “log-root” and “application-root”. The name of these attributes are shown in the result of GET.
    4. As earlier, XML representation of management resources can be obtained as:
      ~/tools/glassfish/v3/2023/glassfishv3 >curl -H “Accept: application/xml” http://localhost:4848/management/domain -v
      * About to connect() to localhost port 4848 (#0)
      *   Trying ::1… connected
      * Connected to localhost (::1) port 4848 (#0)
      > GET /management/domain HTTP/1.1
      > User-Agent: curl/7.16.3 (powerpc-apple-darwin9.0) libcurl/7.16.3 OpenSSL/0.9.7l zlib/1.2.3
      > Host: localhost:4848
      > Accept: application/xml
      >
      < HTTP/1.1 200 OK
      < Content-Type: application/xml
      < Transfer-Encoding: chunked
      < Date: Wed, 19 Aug 2009 18:17:07 GMT
      <
      <Domain log-root=”${com.sun.aas.instanceRoot}/logs” application-root=”${com.sun.aas.instanceRoot}/applications” locale=”" version=”re-continuous”>
      <child-resource>http://localhost:4848/management/domain/configs</child-resource>
      <child-resource>http://localhost:4848/management/domain/resources</child-resource>
      <child-resource>http://localhost:4848/management/domain/servers</child-resource>
      <child-resource>http://localhost:4848/management/domain/property</child-resource>
      <child-resource>http://localhost:4848/management/domain/applications</child-resource>
      <child-resource>http://localhost:4848/management/domain/system-applications</child-resource>
      <child-resource>http://localhost:4848/management/domain/stop</child-resource>
      <child-resource>http://localhost:4848/management/domain/restart</child-resource>
      <child-resource>http://localhost:4848/management/domain/uptime</child-resource>
      <child-resource>http://localhost:4848/management/domain/version</child-resource>
      <child-resource>http://localhost:4848/management/domain/rotate-log</child-resource>
      <child-resource>http://localhost:4848/management/domain/host-port</child-resource>
      * Connection #0 to host localhost left intact
      * Closing connection #0

      Just changing the “Accept” header to “application/xml” did the trick.

    5. And an HTML representation can be obtained by viewing the URL “http://localhost:4848/management/domain” in the browser with result as:

Just like GlassFish v3, the REST interface is extensible as well. So if a new container is plugged in that generates data (possibly through probes) captured in the runtime tree, that is automatically exposed in the RESTful interface.

Now for the Mac users, Safari prefers XML over HTML. Basically a resource, that can be served using both XML and HTML representation (as our Management and Monitoring interface), is served as XML by Safari and HTML by Firefox. So use Firefox on Mac if you want HTML rendering.

How will you use GlassFish RE
ST interface ?

Do your application server provide that level of administration capability ?

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 rest management monitoring jersey

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