Miles to go …

February 26, 2010

Oracle at EclipseCon 2010 – Java EE 6, OSGi, GlassFish, EclipseLink, JPA 2.0/Dali, …

Filed under: General — arungupta @ 5:02 pm
EclipseCon 2010 Oracle is a strategic developer & board member of the Eclipse Foundation and is a gold sponsor of Eclipse Con 2010. See the complete list of Eclipse projects at Oracle.

When ? Mar 22nd – 25th, 2010
Where ? Santa Clara, California
How to register ? Register Now – Use the coupon code ORACLE10 (before Mar 2) for 10% off registration.
What ? Program Schedule

Oracle certainly has a lot to talk about Java EE 6, OSGi/GlassFish, JPA 2.0 and Dali, Future of App Servers, Future of Enterprise Java, Eclipse RT and WTP Reloaded tutorials and many other sessions. See the complete details about Oracle’s participation here.

Also don’t miss the keynote by Steve Harris and Jeet Kaul on Community and Adaptation. Hear these two industry leaders and prolific speakers talk about how Java has empowered community, engendered new forms of adaptation and will continue to blaze the trails.

And then there is Members and Committers reception on Monday evening sponsored by Oracle. Visit us at booth #8 to speak with technical experts, see demos and get information about Oracle’s Eclipse technology and Project participation.

OSGi DevCon 2010 is happening on the same dates/venue and is covered with Eclipse Con registration.

And last, but not the least, let that runner in you have some fun and run with fellow attendees. Yep, there are even prizes!

Keep checking eclipsecon.org for the latest updates.

Unfortunately, I’ll be speaking elsewhere in a different part of the world during exact same dates and so will miss all the fun. More on that later but here are some key members of the Eclipse Foundation:

Feel free to greet and thank them for running the show :-)

Read about 2009 participation here.

Technorati: conf oracle glassfish javaee oepe eclipsecon santaclara

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

February 24, 2010

Oracle GlassFish Server 3 – New Datasheet available

Filed under: General — arungupta @ 12:03 pm
Oracle announced a new datasheet for "Oracle GlassFish Server 3", yep no "v"!

Here are some key points from the datasheet:

BENEFITS

  • Light weight and flexibility, with fast startup of only those services required by deployed applications
  • Support available from Oracle’s world-class services organization
  • Easy-to-use administration console and command-line tool
  • Microsoft .NET interoperability
  • Compatibility with the Java EE 6 and Java EE 6 Web Profile, improving application portability and developer productivity
  • Tomcat developers’ ability to begin with the more capable Java EE 6 Web Profile and then grow to a more feature-rich, standardized platform as needed, using only the resources necessary

. . .

Oracle GlassFish Server is the world’s first implementation of the  Java Platform, Enterprise Edition (Java EE) 6 specification. Built with the open source GlassFish Project reference implementation, Oracle GlassFish Server is a flexible, lightweight, and extensible Java EE 6–compatible server. Completely supported for commercial  deployment and available standalone or packaged with other Oracle Fusion Middleware offerings, Oracle GlassFish Server delivers a small-footprint, fully featured Java EE application server.

. . .

Oracle GlassFish Server is part of the Oracle Fusion Middleware application grid portfolio and is ideally suited for applications requiring lightweight infrastructure with the most up-to-date implementation of enterprise Java, Java EE 6, and Java Web services. Oracle GlassFish Server complements Oracle WebLogic Server, which is designed to run the broader portfolio of Oracle Fusion Middleware and large-scale enterprise applications.

. . .

Please visit oracle.com/sun or call +1.800.786.0404 to speak to an Oracle representative.

Lot more details in the datasheet, download now! More details about Oracle GlassFish Server are on oracle.com. A Java EE 6 whitepaper is also available on oracle.com.

Additionally, you can watch the webcast on GlassFish Strategy by Oracle or attend a Oracle+Sun welcome event in a city near you.

Technorati: oracle glassfish javaee datasheet

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

February 23, 2010

Java EE 6 & GlassFish swimming to DevNexus/Atlanta – Mar 8/9 & Dallas – Apr 5

Filed under: General — arungupta @ 11:28 am

Here is an opportunity to hear the latest & greatest about Java EE 6 & GlassFish in Atlanta and Dallas.

Where ? When ? Participate ?
Atlanta Mar 8/9, 2010 DevNexus
Dallas Apr 5, 2010 FREE Invite
The Atlanta event is happening at DevNexus, a developer conference organized by the Atlanta Java Users Group. The topics in this year’s conference range from Java EE 6, Spring 3.0, Grails, Google App Engine, Google Wave, Context & Dependency Injection, Hudson and many others.

See the complete list of speakers and schedule. Seats are limited and pre-registration is required, so register now! Follow @devnexus for more details.

The Dallas event is organized by Oracle University in association with GCA.net Technology Services and is dedicated to Java EE 6 & GlassFish.

Register today!

In both the events, you’ll learn how Java EE 6 provides a flexible technology stack, takes ease-of-development to a new level by following convention-over-configuration and using defaults, improves developer productivity by intuitive tooling, new/updated specifications in the platform and many other features.

The talk will be accompanied by numerous live code samples showing the benefits of Java EE 6 platform and GlassFish.

More details about both the events are available here.

Technorati: javaee glassfish atlanta dallas conf

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

February 18, 2010

TOTD #124: Using CDI + JPA with JAX-RS and JAX-WS

Filed under: General — arungupta @ 10:36 am

This is a follow up blog to TOTD #120 and TOTD #123. These two blogs together have created a simple Java EE 6 application and showed the following features so far:

  • No-interface view for EJB
  • EJBs packaged in a WAR file
  • Optional "faces-config.xml" for Java Server Faces
  • FacesServlet registered using Servlet 3.0 programmatic registration APIs
  • Java Server Faces navigation rules using convention-over-configuration
  • Optional "web.xml" for Servlets 3.0
  • Add database access using Java Persistence API 2.0
  • Show type-safe Criteria API from JPA 2.0
  • Use Context & Dependency Injection for JSF managed beans
  • Add Ajax effects from Java Server Faces 2.0
  • Add Bean Validation to the JSF managed bean

GlassFish v3 is the Java EE 6 Reference Implementation and comes bundled with a complete SOAP Web services stack (Metro/JAX-WS) and a RESTful stack (JAX-RS/Jersey). This blog will update the previously created Maven project with:

  • A SOAP Web service using JAX-WS
  • A RESTful Web service using JAX-RS
  • Use Context & Dependency Injection with JAX-WS and JAX-RS
  • Query the database using JPA 2 based upon criteria from the Web service invocation

Lets get started!

  1. Use the Maven project from TOTD #123 and update the directory structure as follows:
    src
    src/main
    src/main/java
    src/main/java/org
    src/main/java/org/glassfish
    src/main/java/org/glassfish/samples
    src/main/java/org/glassfish/samples/ActorResource.java
    src/main/java/org/glassfish/samples/RESTApplication.java
    src/main/java/org/glassfish/samples/SakilaBean.java
    src/main/java/org/glassfish/samples/SimpleBean.java
    src/main/java/org/glassfish/samples/SimpleEJB.java
    src/main/java/org/glassfish/samples/SimpleServlet.java
    src/main/java/org/glassfish/samples/SOAPService.java
    src/main/resources
    src/main/webapp
    src/main/webapp/index.jsp
    src/main/webapp/index.xhtml
    src/main/webapp/sakila.xhtml
    src/main/webapp/show.xhtml
    src/main/webapp/WEB-INF
    src/main/webapp/WEB-INF/beans.xml
    src/main/webapp/WEB-INF/web.xml
    

    The changes are:

    • "ActorResource.java" is added for the RESTful representation of Actor table.
    • "SOAPSevice.java" is added to invoke the SOAP-based Web service.
    • "SakilaBean.java" is updated to query the database for an Actor identified by "id".
  2. The updated files are explained below.
    • A new method is added to SakilaBean.java as shown below:
      public Actor findActorById(int id) {
      EntityManager em = emf.createEntityManager();
      CriteriaBuilder cb = emf.getCriteriaBuilder();
      CriteriaQuery<Actor> criteria = cb.createQuery(Actor.class);
      // FROM clause
      Root<Actor> actor = criteria.from(Actor.class);
      // SELECT clause
      criteria.multiselect(actor.<Short>get("actorId"),
      actor.<String>get("firstName"),
      actor.<String>get("lastName"));
      // WHERE clause
      criteria.where(cb.equal(actor.<Short>get("actorId"), id));
      Query q = em.createQuery(criteria);
      ((org.eclipse.persistence.jpa.JpaQuery)q).getDatabaseQuery().dontMaintainCache();
      return (Actor)q.getResultList().get(0);
      }
      

      This method queries the database for an actor by his id and uses the typesafe Criteria API to achieve the purpose. The FROM, SELECT, and WHERE clause are highlighted in the code. A cast to EclipseLink specific class is required because of the bug #303205.

    • SOAPService.java
      package org.glassfish.samples;
      import javax.inject.Inject;
      import javax.jws.WebService;
      import sakila.Actor;
      @WebService
      public class SOAPService {
      @Inject SakilaBean bean;
      public String sayHello(int id) {
      Actor a = bean.findActorById(id);
      return "Hello " + a.getFirstName();
      }
      }
      

      The key points in the code are:

      • Standard JAX-WS annotations from "javax.jws.*" package are used to represent the Web service.
      • The Web service has only one method "sayHello" that concatenates the string "Hello" with the first name of "Actor" identified by "id".
      • No deployment descriptor modifications are required to publish this Web service.
      • "SakilaBean" is injected using @Inject annotation and used to query the database. This allows to encapsulate all the database details in one class and injected in a typesafe manner.
    • RESTApplication.java
      package org.glassfish.samples;
      import javax.ws.rs.ApplicationPath;
      import javax.ws.rs.core.Application;
      @ApplicationPath("/sakila")
      public class RESTApplication extends Application {
      }
      

      This is a marker class to inform Jersey of the root resource to be registered. By default, all classes with @Path and @Provider annotations are included. It also specifies the base path at which all resources are accessible.

      An alternative to this class is to specify the required information in "web.xml" as:

      <servlet>
           <servlet-name>Jersey Web Application</servlet-name>
           <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
      </servlet>
      <servlet-mapping>
           <servlet-name>Jersey Web Application</servlet-name>
           <url-pattern>/sakila/*</url-pattern>
      </servlet-mapping>
      

      So only one of RESTApplication.java or changes in "web.xml" are required.

    • ActorResource.java
      package org.glassfish.samples;
      import javax.enterprise.context.RequestScoped;
      import javax.inject.Inject;
      import javax.ws.rs.GET;
      import javax.ws.rs.Path;
      import javax.ws.rs.Produces;
      import javax.ws.rs.PathParam;
      import sakila.Actor;
      @Path("/actor/{id}")
      @RequestScoped
      public class ActorResource {
      @Inject SakilaBean sakila;
      @GET
      @Produces("application/json")
      public Actor getActor(@PathParam("id") int id) {
      return sakila.findActorById(id);
      }
      }
      

      The key points in the code are:

      • Standard JAX-RS annotations from "javax.ws.rs" package are used to represent the RESTful resource.
      • "getActor" method is invoked when the resource is accessed using HTTP GET.
      • The resource is accessible at "/actor/{id}" URL where "{id}" is mapped to the "id" parameter of "getActor" method.
      • SakilaBean is injected in a typesafe manner using @Inject annotation. This bean is then used to query the database using the "id" parameter.
      • "getActor" method produces JSON representation, as defined by the "@Produces" annotation. This is easily achieved by updating our Persistence Unit (PU) created in TOTD #122 and adding "@javax.xml.bind.annotation.XmlRootElement" as the class level annotation on "sakila.Actor" class. Make sure to install the updated PU to your local Maven repository.

Package and deploy the application as:

mvn clean package
./bin/asadmin deploy --force=true ~/samples/javaee6/simplewebapp/target/simplewebapp-1.0-SNAPSHOT.war

Now the SOAP web service is accessible at "http://localhost:8080/simplwebapp-1.0-SNAPSHOT/SOAPServiceService" and looks like:


Notice, the URL in your case may be different if the Web service class name was different. The default URL is "http://<HOST>:<PORT>/<CONTEXT ROOT><WEB SERVICE CLASS NAME>Service".

This Web service can be easily tested by using the in-built tester accessible at "http://localhost:8080/simplwebapp-1.0-SNAPSHOT/SOAPServiceService?tester" and looks like:

The WSDL describing the Web service can be seen by clicking on the "WSDL File" link. The Web service method can be invoked by entering a value ("id" of the Actor) in the text box and clicking on "sayHello" button. Here is a sample run:

Clicking on "Submit" invokes the Web service which then uses the injected "SakilaBean" to query the database using the parameter specified. The first name from the response from the database is then extracted, concatenated with the string "Hello" and returned as Web service response.

The RESTful resource is accessible at "http://localhost:8080/simplwebapp-1.0-SNAPSHOT/sakila/actor/5" and looks like:

As in the SOAP-based Web service, the "5" in the URL is mapped to a parameter in the "ActorResource.java", the injected "SakilaBean" is then used to query the database and returns the JSON representation. Specifying a different number in the URL will show the RESTful JSON representation for that particular actor.

More Java EE 6 features will be covered in subsequent blogs. Are you interested in any particular ones ?

Technorati: jaxws metro webservices jaxrs rest jersey glassfish v3 cdi jsr299 weld

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

February 15, 2010

Latest features of Java Persistence 2.0 with MySQL – FREE webinar, Feb 23, 2010

Filed under: General — arungupta @ 10:12 am

Want to learn the latest features of Java Persistence 2.0 (JSR 317) with MySQL ?

JPA 2 provides an object/relational mapping facility for the Java application developer using a Java domain model to manage a relational database. JPA got a major facelift as part of Java EE 6 specification and has been expanded to include several key new features – improved object/relational mapping and modeling additions, the query language facilities, the new criteria API, pessimistic locking, and support for validation.

Learn what these features mean in context of MySQL in an upcoming webinar on Feb 23, 2010.

Linda DeMichiel (specification lead of JPA2) and I will be talking about them and showing live code samples to get you started.

Register now!

Technorati: jpa mysql webinar glassfish netbeans

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

February 11, 2010

TOTD #123: f:ajax, Bean Validation for JSF, CDI for JSF and JPA 2.0 Criteria API – all in one Java EE 6 sample application

Filed under: General — arungupta @ 11:23 pm

Taking TOTD #120 forward, we’ll add the following features to our application:

  • Add database access using Java Persistence API 2.0
  • Show type-safe Criteria API from JPA 2.0
  • Use Context & Dependency Injection for JSF managed beans
  • Add Ajax effects from Java Server Faces 2.0
  • Add Bean Validation to the JSF managed bean

Lets get started!

  1. Use the Maven project created in TOTD #120 and update the directory such that it looks like:
    src
    src/main
    src/main/java
    src/main/java/org
    src/main/java/org/glassfish
    src/main/java/org/glassfish/samples
    src/main/java/org/glassfish/samples/SakilaBean.java
    src/main/java/org/glassfish/samples/SimpleBean.java
    src/main/java/org/glassfish/samples/SimpleEJB.java
    src/main/java/org/glassfish/samples/SimpleServlet.java
    src/main/webapp
    src/main/webapp/index.jsp
    src/main/webapp/index.xhtml
    src/main/webapp/sakila.xhtml
    src/main/webapp/show.xhtml
    src/main/webapp/WEB-INF
    src/main/webapp/WEB-INF/beans.xml
    src/main/webapp/WEB-INF/web.xml
    

    The key differences are:

    1. "beans.xml" is an empty file to enable Context & Dependency Injection bean discovery.
    2. The JPA Persistence Unit is copied and installed in local Maven repository as explained in TOTD #122.
    3. "web.xml" is added to bootstrap the Java Server Faces runtime. This is required because "@ManagedBean" annotation on "SimpleBean" class is now changed to "@javax.inject.Named". The JSF runtime is automatically registered and booted if any bean in the webapp is annotated with "@ManagedBean" or one of the JSF common classes (such as Converter, Validator, or Renderer) is implemented or extended. If none of these "hints" are available in the application, and it’s required, then it needs to enabled explicitly.

Here are the updated files, changes are highlighted in bold and explained after each fragment:

index.xhtml

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtm
l1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html">
<h:head>
<title>Enter Name &amp; Age</title>
</h:head>
<h:body>
<h1>Enter Name &amp; Age</h1>
<h:form>
<h:panelGrid columns="3">
<h:outputText value="Name:"/>
<h:inputText value="#{simplebean.name}" title="name" id="name" required="true"/>
<h:message for="name" style="color: red"/>
<h:outputText value="Age:"/>
<h:inputText value="#{simplebean.age}" title="age" id="age" required="true"/>
<h:message for="age" style="color: red"/>
</h:panelGrid>
<h:commandButton action="show" value="submit"/>
</h:form>
</h:body>
</html>

Changed the panelGrid from "2" columns to "3". This allows for any validation messages to be displayed right next to the source. Also added "<h:message …/>" to display the validation messages.

SimpleBean.java

package org.glassfish.samples;
import javax.inject.Named;
import javax.enterprise.context.RequestScoped;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.validation.constraints.Min;

@Named("simplebean")
@RequestScoped
public class SimpleBean {
@NotNull
@Size(min=2, message="Name must be at least 2 characters")
 private String name;
@NotNull
@Min(5)
 private int age;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
}

The changes to the above code are listed below:

  • Replaced "@ManagedBean" with "@Named" annotation defined in JSR 330 and used by CDI.
  • Using constraints defined by Bean Validation APIs (JSR 303) to check for
    • Both bean properties to be non-null
    • Name to be at least 2 characters
    • A minimum age of 5
    • There are several other pre-defined constraints in "javax.validation.constraints" package and new constraints can be easily defined as well.

SakilaBean.java

package org.glassfish.samples;
import java.util.List;
import javax.enterprise.context.RequestScoped;
import javax.faces.event.ActionEvent;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceUnit;
import javax.persistence.EntityManagerFactory;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import sakila.Actor;
@Named("sakilabean")
@RequestScoped
public class SakilaBean {
@PersistenceUnit(unitName="SakilaPU")
EntityManagerFactory emf;
private List<Actor> actors;
private int length;
private int totalActors;
// getters & setters
public List<Actor> getActors() { return actors; }
public void setActors(List<Actor> actors) { this.actors = actors; }
public int getLength() { return length; }
public void setLength(int length) { this.length = length; }
public int getTotalActors() { return totalActors; }
public void setTotalActors(int totalActors) { this.totalActors = totalActors; }
public void findActors(ActionEvent evt) {
EntityManager em = emf.createEntityManager();
CriteriaBuilder cb = emf.getCriteriaBuilder();
CriteriaQuery<Actor> criteria = cb.createQuery(Actor.class);
// FROM clause
Root<Actor> actor = criteria.from(Actor.class);
// SELECT clause
criteria.select(actor);
// WHERE clause
criteria.where(cb.greaterThan(
cb.length(actor.get("firstName").as(String.class)), length));
// FIRE
actors = em.createQuery(criteria).getResultList();
totalActors = actors.size();
}
}

The key points:

  • This is a CDI bean marked by @Named and used in the JSF view (shown next), with the name "sakilabean"
  • EntityManagerFactory is injected using @PersistenceUnit
  • "findActors" method builds the query using Criteria API. Returns actors’ names limited by the number of characters in their first name.
  • Queries "Actor" table from the database and set bean properties "actors" and "totalActors".
  • Uses "length" bean property (set from the JSF view) to restrict the number of characters in the name.

sakila.xhtml

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtm
l1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html">
<h:head>
<title>Sakila - Actors Listing</title>
</h:head>
<h:body>
<h1>Sakila - Actors Listing</h1>
<h:form>
<h:outputText value="Show actors with first name's length &lt;"/>
<h:inputText value="#{sakilabean.length}" id="length" required="true" size="5"/>
<h:commandButton actionListener="#{sakilabean.findActors}" value="submit">
<f:ajax execute="length" render="actorTable totalActors"/>
</h:commandButton><br/>
Total actors found: <h:outputText value="#{sakilabean.totalActors}" id="totalActors"/><p/>
<h:dataTable var="actor" value="#{sakilabean.actors}" border="1" id="actorTable">
<h:column><h:outputText value="#{actor.firstName}"/>, <h:outputText value="#{actor.lastName}"/></h:column>
</h:dataTable>
</h:form>
</h:body>
</html>

Key points:

  • This JSF view shows a form that accepts a number used for restricting the length of actors’ first name. The value of this attribute is bound to "length" property of the underlying bean.
  • Command Button is tied to a JSF Action Listener which is then bound to "findActors" method in the bean. This method executes the JPA query explained above.
  • "f:ajax" is a newly introduced tag in JSF 2.0 and means an Ajax request is performed on the "onClick" event of the rendered button, "findActors" method in the bean in this case. The tag also specifies other tags in the page, "actorTable" and "totalActors" in this case, that needs to be rendered after the request is completed. The input parameter to the Ajax request is specified using "execute" attribute. Read more about this tag here or section 10.4.1.1 of the JSF 2 specification.

Package and deploy the application as:

mvn clean package
./bin/asadmin deploy --force=true ~/samples/javaee6/simplewebapp/target/simplewebapp-1.0-SNAPSHOT.war

The application is now accessible at "http://localhost:8080/simplewebapp-1.0-SNAPSHOT/sakila.jsf" and looks like:

Enter a value of "4" in the text box and hit "Submit":

Only the HTML table of names and the total count of actors is refreshed showcasing partial page refresh.

Now enter a value of "8" and hit "Submit":

Enjoy!

More Java EE 6 features to be shown in subsequent blogs.

Technorati: totd javaee glassfish v3 javaserverfaces ajax jpa cdi beanvalidation

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

February 10, 2010

Oracle+Sun Welcome Events

Filed under: General — arungupta @ 10:00 am

Want to learn how Oracle+Sun are transforming the industry ? What the combination means to you ?

Hear from Oracle and Sun executives in multiple cities all around the world and learn the strategy.

Here is an email flier from my inbox showing some of the North America cities, more cities are being added every day.

Oracle+Sun Welcome Events

In the meanwhile, check out:

  • Larry Ellison and other execs on Oracle + Sun strategy
  • Oracle + Sun Product Strategy Webcast Series (Detailed notes on GlassFish & Developer Tools)
  • Developer Community FAQ

Technorati: oracle sun welcome

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

February 9, 2010

TOTD #122: Creating a JPA Persistence Unit using NetBeans 6.8

Filed under: General — arungupta @ 11:08 pm

Taking TOTD #121 forward, this blog explains how to create a JPA Persistence Unit for a MySQL sample database and package it as a library. This JAR file can then be easily included in other web applications.

Lets get started!

  1. Configure GlassFish for using the MySQL sample database (sakila) as described in TOTD #121.
  2. Add the GlassFish instance in NetBeans IDE using "Services" panel.
  3. Create JPA entities using NetBeans IDE.
    1. Create a Java class library:

      Our ultimate goal is to create a reusable JAR file and that’s why this project type is chosen.

    2. Specify the name of project as "SakilaPU":

    3. Right-click on the project and select "New", "Entity Classes from Database …" to initiate the process of entity generation:

    4. Choose the database connection as:

      If not configured, then can be easily done by clicking on "New Database Connection …" in the list box.

      1. Click on "Add All >>" to generate the mapped JPA entities for all tables and views.
      2. The views do not have primary keys and will need to be appropriately annotated (described later).
      3. Click on "Next >".
    5. Give the package name as:

      and specify the package name as "sakila". Click on "Create Persistence Unit …".

    6. Change the default PU name from "SakilaPUPU" to "SakilaPU":

      and click on "Finish". Notice that "EclipseLink", the Reference Implementation of JPA 2.0, is used as the persistence library.

    7. Add "@javax.persistence.Id" annotation to the following class/field combination:
      Class Field
      sakila.SalesByFilmCategory category
      sakila.ActorInfo actorId
      sakila.FilmList fid
      sakila.CustomerList id
      sakila.NicerButSlowerFilmList fid
      sakila.StaffList id
      sakila.SalesByStore store

      This is required because none of the "views" are defined with a primary key.

    8. Right-click on the project and select "Clean & Build". This generates "dist/SakilaPU.jar" and the structure looks like:

This JAR file can now be included in any web application. The pre-built JAR file can also be downloaded here.

In order for this PU to be used in an application server (such as GlassFish) that is pre-configured with a JDBC resource, the "persistence.xml" needs to be changed to:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="SakilaPU" transaction-type="JTA">
<jta-data-source>jdbc/sakila</jta-data-source>
<properties/>
</persistence-unit>
</persistence>

The JDBC resource name is specified using <jta-data-source>.

The key items to note about this pre-built JAR:

  • Persistence Unit Name: "SakilaPU"
  • All classes are in "sakila.*" package.
  • Each class has a pre-defined "<CLASS-NAME>.findAll" named query that returns all elements from the underlying view/table.

This JAR can be installed to your local Maven repository as:

mvn install:install-file -Dfile=SakilaPU.jar -DgroupId=org.glassfish.samples -DartifactId=sakilapu -Dversion=1.0 -Dpackaging=jar -DgeneratePom=true

and then included in your "pom.xml" as:

<dependency>
<groupId>org.glassfish.samples</groupId>
<artifactId>sakilapu</artifactId>
<version>1.0</version>
<scope>compile</scope>
</dependency>

Even though this blog uses a MySQL sample database, these steps can be easily followed for any other database such as Oracle or JavaDB.

Technorati: totd javaee glassfish v3 jpa eclipselink persistenceunit mysql sakila netbeans

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

February 8, 2010

TOTD #121: JDBC resource for MySQL and Oracle sample database in GlassFish v3

Filed under: General — arungupta @ 11:00 pm

This blog clearly explains how to configure the MySQL sample database (sakila) with GlassFish. Even though the instructions use a specific database but should work for other databases (such as Oracle, JavaDB, PostgreSQL, and others) as well. The second half of the blog provide specific syntax for the Oracle sample database.

  1. Download sakila sample database and unzip the archive.
  2. Install the database as described here – basically load and run "sakila-schema.sql" and "sakila-data.sql" extracted from the archive.
  3. Create a new MySQL user account using MySQL CLI Admin and assign the privileges
    1. Using "root" user (sudo mysql –user root)
      CREATE USER glassfish IDENTIFIED BY 'glassfish';
      GRANT ALL PRIVILEGES ON *.* TO 'glassfish'@'localhost' IDENTIFIED BY 'glassfish';
      FLUSH PRIVILEGES;
      
    2. Using "glassfish" user (sudo mysql –user glassfish)
      source sakila-schema.sql;
      source sakila-data.sql;
      
  4. Download Connector/J, unzip and copy "mysql-connector-java-5.x.x-bin.jar" to "glassfish/domains/domain1/lib/ext" directory.
  5. Start GlassFish server as:
    asadmin start-domain
    
  6. Create a JDBC resource
    1. Create JDBC connection pool as:
      asadmin create-jdbc-connection-pool --datasourceclassname com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource --restype javax.sql.DataSource --property "User=glassfish:Password=glassfish:URL=jdbc\:mysql\://localhost/sakila" jdbc/sakilaPool
      
    2. Test the JDBC connection pool as:
      asadmin ping-connection-pool jdbc/sakilaPool
      
    3. Create the JDBC resource as:
      asadmin create-jdbc-resource --connectionpoolid jdbc/sakilaPool jdbc/sakila
      

That’s it!

Creating a JDBC resource for any other database requires the following updates to the steps mentioned above. Lets consider modifying these steps for the Oracle sample database.

  1. Use the client interface SQL*PLus and connect as:
    sqlplus "/ as sysdba"
    

    create user and grant the privileges as:

    CREATE USER glassfish IDENTIFIED BY glassfish DEFAULT tablespace users TEMPORARY tablespace temp;
    GRANT CONNECT TO glassfish IDENTIFIED BY glassfish;
    GRANT UNLIMITED TABLESPACE TO glassfish;
    GRANT CREATE TABLE TO glassfish;
    GRANT CREATE SEQUENCE TO glassfish;
    
  2. Copy the appropriate JDBC driver (ojdbc6.jar).
  3. Create the JDBC resource as:
    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
    asadmin ping-connection-pool jdbc/hr
    asadmin create-jdbc-resource --connectionpoolid jdbc/hr jdbc/hr
    

    as explained in TOTD #108.

Here are a few other related entries:

  • RESTful representation of sakila using NetBeans and GlassFish

  • JPA + Servlet 3.0 Application using Sakila in Eclipse

  • JSF + JPA + EJB Application using Oracle, NetBeans, and GlassFish

Technorati: totd javaee glassfish v3 jpa mysql sakila oracle

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

February 5, 2010

TOTD #120: Deployment Descriptor-free Java EE 6 application using JSF 2.0 + EJB 3.1 + Servlets 3.0

Filed under: General — arungupta @ 2:00 pm

Here is trivial Java EE 6 application that is keeping you away from any deployment descriptors. It uses Java Server Faces 2.0, Enterprise Java Beans 3.1, and Servlet 3.0. This application shows the following Java EE 6 features:

  1. No-interface view for EJB
  2. EJBs packaged in a WAR file
  3. Optional "faces-config.xml" for Java Server Faces
  4. FacesServlet registered using Servlet 3.0 programmatic registration APIs
  5. Java Server Faces navigation rules using convention-over-configuration
  6. Optional "web.xml" for Servlets 3.0

The WAR file structure is:

./index.jsp
./index.xhtml
./META-INF
./show.xhtml
./WEB-INF
./WEB-INF/classes
./WEB-INF/classes/org
./WEB-INF/classes/org/glassfish
./WEB-INF/classes/org/glassfish/samples
./WEB-INF/classes/org/glassfish/samples/SimpleBean.class
./WEB-INF/classes/org/glassfish/samples/SimpleEJB.class
./WEB-INF/classes/org/glassfish/samples/SimpleServlet.class

Look ma, no deployment descriptors!

So how do you create this application:

mvn archetype:create -DarchetypeGroupId=org.apache.maven.archetypes -DgroupId=org.glassfish.samples -DartifactId=simplewebapp

This application is purposely not generated as a web application (missing "-DarchetypeArtifactId=maven-archetype-webapp"). If you specify this property then it will generate "WEB-INF/web.xml" which we don’t intend to use.

Change "pom.xml" to:

<project xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <groupId>org.glassfish.samples</groupId>
   <artifactId>simplewebapp</artifactId>
   <packaging>war</packaging>
   <version>1.0-SNAPSHOT</version>
   <name>simplewebapp</name>
   <url>http://maven.apache.org</url>
   <repositories>
     <repository>
       <id>glassfish-repository</id>
       <name>Java.net Repository for Glassfish</name>
       <url>http://download.java.net/maven/glassfish</url>
     </repository>
   </repositories>
   <build>
     <plugins>
       <plugin>
         <groupId>org.apache.maven.plugins</groupId>
         <artifactId>maven-compiler-plugin</artifactId>
         <version>2.0.2</version>
         <configuration>
           <source>1.5</source>
           <target>1.5</target>
         </configuration>
       </plugin>
       <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>
   <dependencies>
     <dependency>
       <groupId>junit</groupId>
       <artifactId>junit</artifactId>
       <version>3.8.1</version>
       <scope>test</scope>
     </dependency>
    <dependency>
       <groupId>javax</groupId>
       <artifactId>javaee-api</artifactId>
       <version>6.0</version>
       <scope>provided</scope>
    </dependency>
   </dependencies>
</project>

In the above code:

  • "maven-compiler-plugin" needs to be specified as the default source level for Maven compile plugin is JDK 1.3. It’s been over 9 years JDK 1.3 was released, not even listed on Java SE standard downloads page, EOLed many years ago. Vote/Comment for the issue MCOMPILER-80 if you’d like this bug to be fixed.
  • Adding "failOnMissingWebXml" ensures that Maven packages the WAR file even though no "web.xml" is present.
  • The complete list of Maven coordinates for GlassFish are available here.

Create the directory structure as:

./src/main
./src/main/java
./src/main/java/org
./src/main/java/org/glassfish
./src/main/java/org/glassfish/samples
./src/main/java/org/glassfish/samples/SimpleBean.java
./src/main/java/org/glassfish/samples/SimpleEJB.java
./src/main/java/org/glassfish/samples/SimpleServlet.java
./src/main/webapp
./src/main/webapp/index.jsp
./src/main/webapp/index.xhtml
./src/main/webapp/show.xhtml

Once again, there are no deployment descriptors, just plain Java files and XHTML/JSP pages.

Here are the different source files with explanation after each one of them:

SimpleBean.java

package org.glassfish.samples;
import javax.faces.bean.ManagedBean;
@ManagedBean(name="simplebean")
public class SimpleBean {
    private String name;
    private int age;
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public int getAge() { return age; }
    public void setAge(int age) { this.age = age; }
}

This is currently a simple JSF managed bean. TOTD #109 explains how to convert a JSF managed bean to use CDI. A future blog will show how to convert this sample to use CDI.

SimpleEJB.java

package org.glassfish.samples;
import javax.ejb.Stateless;
@Stateless
public class SimpleEJB {
    public String sayHello(String name) {
        return "Hello " + name + "!!!";
    }
}

The session bean has no interface, just the @Stateless annotation.

SimpleServlet.java

package org.glassfish.samples;
import javax.ejb.EJB;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.annotation.WebServlet;
import java.io.PrintWriter;
import java.io.IOException;
/**
* Hello world!
*/
@WebServlet(urlPatterns={"/SimpleServlet"})
public class SimpleServlet extends HttpServlet {
@EJB SimpleEJB bean;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h2>Serving at: " + request.getContextPath() + "</h2>");
out.println("<h2>Invoking EJB: " + bean.sayHello("Duke") + "</h2>");
out.println("</body></html>");
}
}

The servlet injects the EJB in the application, display the servlet context and the result of invoking the business operation of the EJB.

index.jsp

<html>
<body>
<h2>Hello World!</h2>
Invoke the Servlet by clicking <a href="SimpleServlet">here</a>.
</body>
</html>

This is just a placeholder for invoking the servlet.

index.xhtml

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtm
l1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html">
<h:head>
<title>Enter Name &amp; Age</title>
</h:head>
<h:body>
<h1>Enter Name &amp; Age</h1>
<h:form>
<h:panelGrid columns="2">
<h:outputText value="Name:"/>
<h:inputText value="#{simplebean.name}" title="name" id="name" required="true"/>
<h:outputText value="Age:"/>
<h:inputText value="#{simplebean.age}" title="age" id="age" required="true"/>
</h:panelGrid>
<h:commandButton action="show" value="submit"/>
</h:form>
</h:body>
</html>

JSF 2 uses Facelets as viewing technology and so an ".xhtml" file is used for all the JSF tags. This page is intentionally kept simple and not using any templating, composition, or any other features of Facelets. This page renders an HTML form with two text boxes and a command button, binds the value of text box to the managed bean, and displays the page "show.xhtml" when the command button is clicked. The default JSF 2 navigation handler try to match a view on the disk ("show.xhtml" in this case) based upon the "action" attribute.

show.xhtml

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtm
l1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html">
<h:head>
<title>Show Name &amp; Age</title>
</h:head>
<h:body>
<h1>Show Name &amp; Age</h1>
<h:form action="show">
<h:panelGrid columns="2">
<h:outputText value="Name:"/>
<h:outputText value="#{simplebean.name}" />
<h:outputText value="Age:"/>
<h:outputText value="#{simplebean.age}" />
</h:panelGrid>
</h:form>
</h:body>
</html>

This page reads the bean properties (stored from previous page) and displays them on the page.

How do you build this entire application ?

mvn clean package

Lets deploy the application on a Java EE 6 compliant application server, GlassFish v3 (download here):

./bin/asadmin deploy --force=true ~/samples/javaee6/simplewebapp/target/simplewebapp-1.0-SNAPSHOT.war

And now your application is accessible at "http://localhost:8080/simplewebapp-1.0-SNAPSHOT/index.jsp" and looks like:

Clicking on "here" looks like:

The JSF page is accessible at "http://localhost:8080/simplewebapp-1.0-SNAPSHOT/index.jsf" and looks like (after entering the values):

Notice that even though the page is named "index.xhtml", it’s accessed as "index.jsf". This is because the JSF specification provides recommended mapping for FacesServlet to "*.faces" and "/faces/*". In addition, Mojarra (Reference Implementation of JSF2 in GlassFish) also adds a mapping to "*.jsf". Any views using these URL pattersn are routed through FacesServlet. So alternative URLs for our page are "http://localhost:8080/simplewebapp-1.0-SNAPSHOT/index.faces" and "http://localhost:8080/simplewebapp-1.0-SNAPSHOT/faces/index.xhtml".

Clicking on "Submit" shows the following page:

That’s it!

Here are several other useful entries:

  • TOTD #109 : How to convert a JSF managed bean to JSR 299 bean (Web Beans) ?
  • TOTD #108 : Java EE 6 web application (JSF 2.0 + JPA 2.0 + EJB 3.1) using Oracle, NetBeans, and GlassFish
  • TOTD #102 : Java EE 6 (Servlet 3.0 and EJB 3.1) wizards in Eclipse
  • TOTD #99 : Creating a Java EE 6 application using MySQL, JPA 2.0 and Servlet 3.0 with GlassFish Tools Bundle for Eclipse
  • TOTD #98 : Create a Metro JAX-WS Web service using GlassFish Tools Bundle for Eclipse
  • TOTD #95 : EJB 3.1 + Java Server Faces 2.0 + JPA 2.0 web application – Getting Started with Java EE 6 using NetBeans 6.8 M1 & GlassFish v3
  • TOTD #94 : A simple Java Server Faces 2.0 + JPA 2.0 application – Getting Started with Java EE 6 using NetBeans 6.8 M1 & GlassFish v3
  • TOTD #93 : Getting Started with Java EE 6 using NetBeans 6.8 M1 & GlassFish v3 – A simple Servlet 3.0 + JPA 2.0 app

The next follow up blog will show "Hello World"s of Context & Dependency Injection, Bean Validation, Java API for Restful Web services, Java Persistence API, Interceptors, and other Java EE 6 specifications in this application.

Technorati: totd javaee glassfish v3 javaserverfaces servlet3 ejb maven

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