Saturday Dec 04, 2010

Rich Web Experience 2010 Trip Report

The Rich Web Experience 2010 concluded earlier this week in Fort Lauderdale. In a typical No Fluff Just Stuff fashion, it was truly a rich experience starting from the location (hotel, city, and weather), food, content, speakers, 90-minute sessions, schwag, and many other items. There were about 350 attendees with topics ranging from HTML5, CSS3, NodeJS, GWT, iPad / iPhone / Android development, Grails, Git, Hudson, and pretty much all over the landscape. I gave three sessions on:
  1. Java EE 6 = Less Code + More Power
  2. Java EE 6 Toolshow
  3. Using Contexts and Dependency Injection in the Java EE 6 Ecosystem
The first session explained the three themes of Java EE 6 (light-weight, extensibility, and ease-of-use), explained newly introduced and updated specifications in the platform, and finally the modular, hybrid OSGi/Java EE host, embeddable, extensible, and high-availability nature of GlassFish. The attendance was light but audience was interactive.

The second session was a no-slides session and used NetBeans and Eclipse to demonstrate the following Java EE 6 features:
  1. @WebServlet
  2. @Stateless, No-interface view, EJB 3.1 in a WAR
  3. Embeddable EJB (unit test)
  4. @Schedule
  5. @PersistenceUnit in @WebServlet, @PersistenceContext in @Stateless
  6. Facelets templating
  7. CDI stereotypes @Model, @Qualifier
  8. RESTful Web services from Entity classes
The code build during the talk can be downloaded here.

The third session on CDI was a revision of my JavaOne session with a lot more context and code samples added. The talk explained CDI key concepts like type-safe dependency injection, Qualifiers, Stereotypes, Producer/Disposer, Alternative, Interceptor, Decorators, Scopes, CDI tooling, and other topics.

The slides for both the sessions are now available:

On a personal front, I totally enjoyed coming from a 40 degrees weather in San Jose to 70 degrees in Ft Lauderdale and that too with hotel right on the beach. I had couple of great runs by the Atlantic Ocean and a good walk along the beach.

Thursday had 2 hours dedicated for beach activity but I had to leave to catch my flight to Washington DC :( The dinner, lunch, and breakfast as part of the conference was healthy with a good mix of salads + carbs + proteins. The lemon tea + honey allowed me to deliver three 90 minute sessions in one day. And lastly enjoyed catching up with Venkat, Matthew McCullough, Kohsuke, Ben Ellingson and many other friends.

Here are some pictures:

And the complete album:

Next stop as part of No Fluff Just Stuff will be UberConf, Jul 12-16, 2011, mark your dates!

Technorati: conf glassfish javaee6 netbeans eclipse cdi weld rwx2010 richwebexperience florida

Monday Aug 23, 2010

TOTD #144: CDI @Produces for container-managed @Resource

Contexts & Dependency Injection (CDI) in Java EE 6 provides type-safe dependency injection. The type-safety part comes from the fact that no String-based identifiers are used for dependency injection. Instead CDI runtime uses the typing information that is already available in the Java object model.

Java EE 5 already had resource injection available in terms of PersistenceContext, PersistenceUnit, Resource, and others. But they require String-based identifiers to identify the resource to be injected. For example:

  • @PersistenceUnit(unitName="SOME_NAME")
  • @Resource(name="JNDI_NAME")
  • @WebServiceRefs(lookup="JNDI_NAME_OF_WEB_SERVICE_REF")

The main proposition of CDI is type-safety. This Tip Of The Day explains how @Produces annotation provided by CDI can be used to centralize all these String-based resource injection and add a facade of type-safety on them. Specifically, it shows how type-safety can be achieved for @PersistenceUnit. A similar approach can be taken for other String-based resource injections as well.

  1. Create a Singleton-scoped bean or Application-scoped bean as:
    import javax.inject.Singleton;
    public class ApplicationResources {

    All the Java EE component environment references can be centralized in this bean.
  2. If the PersistenceUnit is currently initialized as:
    @PersistenceUnit(unitName="StatesPU") EntityManagerFactory statesEMF;

    in other Java EE components, such as Servlet, then it can be alternatively defined in the type-safe manner using the following steps:
    1. Define a new Qualifier as:
      import static java.lang.annotation.ElementType.TYPE;
      import static java.lang.annotation.ElementType.FIELD;
      import static java.lang.annotation.ElementType.PARAMETER;
      import static java.lang.annotation.ElementType.METHOD;
      import static java.lang.annotation.RetentionPolicy.RUNTIME;
      import java.lang.annotation.Retention;
      import java.lang.annotation.Target;
      import javax.inject.Qualifier;
      public @interface StatesDatabase {
    2. Add the type-safe definition of "EntityManagerFactory" in "ApplicationResources" bean (defined above) as:
      @Produces @PersistenceUnit(unitName="StatesPU") @StatesDatabase EntityManagerFactory statesEMF;

    3. The "EntityManagerFactory" can now be injected in the Servlet in a type-safe manner as:
      @Inject @StatesDatabase EntityManagerFactory emf;

This procedure can be repeated for other String-based resources as well and thus centralize all of them at one place. And now your application becomes more type-safe! With this TOTD, you can use @Inject for injecting your container- and application-managed resources easily.

Read the latest documentation on Weld (Reference Implementation for CDI and included in GlassFish) for more details.

Technorati: totd cdi javaee6 glassfish weld produces typesafety

Thursday Feb 18, 2010

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

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:

    The changes are:
    • "" is added for the RESTful representation of Actor table.
    • "" is added to invoke the SOAP-based Web service.
    • "" 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 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
          // WHERE clause
           criteria.where(cb.equal(actor.<Short>get("actorId"), id));
          Query q = em.createQuery(criteria);
          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.
      package org.glassfish.samples;
      import javax.inject.Inject;
      import javax.jws.WebService;
      import sakila.Actor;
      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.
      package org.glassfish.samples;
      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-name>Jersey Web Application</servlet-name>
           <servlet-name>Jersey Web Application</servlet-name>

      So only one of or changes in "web.xml" are required.
      package org.glassfish.samples;
      import javax.enterprise.context.RequestScoped;
      import javax.inject.Inject;
      import sakila.Actor;
      public class ActorResource {
          @Inject SakilaBean sakila;
          public Actor getActor(@PathParam("id") int id) {
              return sakila.findActorById(id);
      The key points in the code are:
      • Standard JAX-RS annotations from "" 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 "", 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

Friday Oct 02, 2009

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

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:

public class StateList {
  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:

      EntityManagerFactory emf;

      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


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

Java EE 7 Samples

Stay Connected


« July 2016