Wednesday Oct 27, 2010

TOTD #147: Java Server Faces 2.0 Composite Components using NetBeans - DRY your code

The Java Server Faces 2.0 uses Facelets instead of JSP as the view declaration language. This allows "view" part of MVC to be completely written using XHTML and CSS only and all the business logic resides in the backing bean. This enables a cleaner separation of views with model and controller and thus follows the MVC design pattern in a more intuitive way. JSF 2 also defines how resources can be packaged, located, and rendered by JSF runtime within a web application.

Using these two features of Facelets and Resource Handling, JSF2 defines a composite component as a component that consists of one or more JSF components defined in a Facelet markup file that resides inside of a resource library. The composite component is defined in the defining page and used in the using page. The "defining page" defines the metadata (or parameters) using <cc:interface> and implementation using <cc:implementation> where "cc" is the prefix for "http://java.sun.com/jsf/composite" namespace. Future versions of the JSF 2 specification may relax the requirement to specify metadata as it can be derived from the implementation itself.

A composite component can be defined using JSF 1.2 as well but it requires a much deeper understanding of JSF lifecycle and also authoring multiple files. JSF2 really simplifies the authoring of composite components using just an XHTML file.

Code is king! This Tip Of The Day (TOTD) will explain how to convert an existing code fragment into a JSF2 composite component using NetBeans IDE.

Lets say a Facelet (index.xhtml) has the following code fragment:

<h:form>
    <h:panelGrid columns="3">
    <h:outputText value="Name:" />
    <h:inputText value="#{user.name}" id="name"/>
    <h:message for="name" style="color: red" />
    <h:outputText value="Password:" />
    <h:inputText value="#{user.password}" id="password"/>
    <h:message for="password" style="color: red" />
  </h:panelGrid>

  <h:commandButton actionListener="#{userService.register}"
                   id="loginButton" action="status" value="submit"/>
</h:form>


This fragment displays an HTML form with two text input boxes and a "submit" button. The two input boxes are bound to "user" bean and clicking on the button invokes "register" method of the "userService" bean.

Instead of repeating this code in multiple pages, its beneficial to convert this into a composite component and use the resulting tag instead of the complete fragment again. Why ?

  • Follows the DRY principle and allows to keep the code, that can be potentially be repeated at multiple places, in a single file.
  • It allows developers to author new components without any Java code or XML configuration.

How do you convert an existing code fragment to a composite component ? NetBeans makes it really easy.

In NetBeans IDE select the code fragment, right-click, "Refactor", "Convert to Composite Component..." as shown below:

In the next screen, change the filename to "loginPanel" and take every thing else as default as shown below:

and click on "Finish".

This will generate "web/resources/ezcomp/loginPanel.xhtml" and move the component definition to this file, aka "defining page" and looks like:

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:cc="http://java.sun.com/jsf/composite"
      xmlns:h="http://java.sun.com/jsf/html">

 <!-- INTERFACE -->
 <cc:interface>
 </cc:interface>

 <!-- IMPLEMENTATION -->
 <cc:implementation>
   <h:form>
     <h:panelGrid columns="3">
       <h:outputText value="Name:" />
       <h:inputText value="#{user.name}" id="name"/>
       <h:message for="name" style="color: red" />
       <h:outputText value="Password:" />
       <h:inputText value="#{user.password}" id="password"/>
       <h:message for="password" style="color: red" />
     </h:panelGrid>

     <h:commandButton actionListener="#{userService.register}"
                      id="loginButton" action="status" value="submit"/>
   </h:form>
</cc:implementation>
</html>

<cc:interface> defines metadata that describe the characteristics of component, such as supported attributes, facets, and attach points for event listeners. <cc:implementation> contains the markup substituted for the composite component.

<cc:interface> is generated in the page but is empty and may be made optional in a subsequent release of the JSF specification.The "using page" will declare a new namespace as:

xmlns:ez="http://java.sun.com/jsf/composite/ezcomp"

and then replace the code fragment with:

<ez:loginPanel/>

The tag name for the new composite component is the same as the "defining page" file name. This enables "<ez:loginPanel/>" to be used instead of repeating that entire code fragment.

Now lets say that the code fragment need to pass different value expressions (instead of #{user.name}) and invoke a different method (instead of #{userService.register}) when submit button is clicked in different "using page"s. The "defining page" can then look like:

<!-- INTERFACE -->
<cc:interface>
  <cc:attribute name="name"/>
  <cc:attribute name="password"/>
  <cc:attribute name="actionListener"
      method-signature="void action(javax.faces.event.Event)"
      targets="ccForm:loginButton"/>
</cc:interface>

<!-- IMPLEMENTATION -->
<cc:implementation>
  <h:form id="ccForm">
  <h:panelGrid columns="3">
    <h:outputText value="Name:" />
    <h:inputText value="#{cc.attrs.name}" id="name"/>
    <h:message for="name" style="color: red" />
    <h:outputText value="Password:" />
    <h:inputText value="#{cc.attrs.password}" id="password"/>
    <h:message for="password" style="color: red" />
  </h:panelGrid>

  <h:commandButton id="loginButton"
                   action="status"
                   value="submit"/>
  </h:form>
</cc:implementation>

The changes are highlighted in bold and explained below:

  • All the parameters are explicitly specified in <cc:interface> for clarity. The third parameter has a "targets" attribute referrring to "ccForm:loginButton".
  • In <cc:implementation>
    • The <h:form> in has "id" attribute. This is required such that the button within the form can be explicitly referenced.
    • <h:inputText> is now using #{cc.attrs.xxx} instead of #{user.xxx}. #{cc.attrs} is a default EL expression that is available for composite component authors and provide access to attributes of the current composite component. In this case #{cc.attrs} has "name" and "password" defined as attributes.
    • "actionListener" is an attach point for event listener, defined as a "method-signature" and describes the signature of a method pointed to by the expression.
    • <h:commandButton> has "id" attribute so that it can be clearly identified within the <h:form>.

The "user", "password", and "actionListener" are then passed as required attributes in the "using page" as:

<ez:loginPanel
    name="#{user.name}"
    password="#{user.password}"
    actionListener="#{userService.register}"/>


Now the "using page" can pass different "backing beans" and business method to be invoked when "submit" button is invoked.

The complete source code for this TOTD can be downloaded here.

How are you using JSF 2 composite components ?

The entire source code used in this blog can be downloaded here.

JSF 2 implementation is bundled with GlassFish Server Open Source Edition, try it today!

I realized TOTD #135 already explains how to author composite components. Hey, but this TOTD provides new information on how to attach event listeners :-)

Technorati: totd javaee6 glassfish jsf2 composite component facelets

Sunday Mar 14, 2010

TOTD #124: OSGi Declarative Services in GlassFish - Accessed from a Java EE client

The OSGi R4 compendium specification enables declaration of "Declarative Services" in configuration files. The specification says:

The service component model uses a declarative model for publishing, finding and binding to OSGi services. This model simplifies the task of authoring OSGi services by performing the work of registering the service and handling service dependencies.

There are several advantages of OSGi declarative services and they are well defined in the specification.

Neil Bartlett provided history and introduction to Declarative Services. Jerome blogged about OSGi Declarative Services in GlassFish v3 a while back. As mentioned in his post, this "curious reader" decided to experiment with adding more than one service implementation.

This Tip Of The Day shows how to use Maven Bundle Plugin and Maven SCR Plugin to create an OSGi bundle with two declarative services. Then it shows how to create a Java EE client, inject the declared services, and invoke them.

Lets get started!

For those who want want to see the results first:

  • Download service project and build as "mvn clean install". Install the service as "cp target/helloservice-1.0-SNAPSHOT.jar" to "domains/domain1/autodeploy/bundles".
  • Download client project and build as "mvn clean package"
  • Deploy the client to GlassFish v3 as "asadmin deploy target/helloclient-1.0-SNAPSHOT.war"
  • Invoke the client as "curl http://localhost:8080/helloclient-1.0-SNAPSHOT/HelloClient"

Now lets try to understand and create the projects from scratch.

First, create the service project as:

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

Lets first look at the completed project structure:

pom.xml
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/osgi
src/main/java/org/glassfish/samples/osgi/helloservice
src/main/java/org/glassfish/samples/osgi/helloservice/api
src/main/java/org/glassfish/samples/osgi/helloservice/api/HelloService.java
src/main/java/org/glassfish/samples/osgi/helloservice/impl
src/main/java/org/glassfish/samples/osgi/helloservice/impl/HelloImpl.java
src/main/java/org/glassfish/samples/osgi/helloservice/impl/HowdyImpl.java

The three source files are one service API and two implementations.

HelloService.java

package org.glassfish.samples.osgi.helloservice.api;

/\*\*
 \* @author arungupta
 \*/
public interface HelloService {
  public String sayHello(String name);
}

A very simple interface with one method that takes a String parameter and returns a String response.

HelloImpl.java

package org.glassfish.samples.osgi.helloservice.impl;

import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Service;
import org.glassfish.samples.osgi.helloservice.api.HelloService;

/\*\*
 \* @author arungupta
 \*/
@Component(name="hello-service")
@Service
public class HelloImpl implements HelloService {

  public String sayHello(String name) {
    return "Hello " + name;
  }
}

This class is an implementation of the service interface. Notice this class is in "impl" package, different from the "api" package where interface was defined.

The business method implementation appends the greeting "Hello " to name parameter and generates the response message. The @Component and @Service annotations help in generation of the component descriptors as defined by the Maven SCR Plugin. This plugin provides many other annotations to customize the generation of metadata in "OSGI-INF/servicesComponent.xml". The "name" attribute will be used later by the Java EE client to access this service.

HowdyImpl.java

package org.glassfish.samples.osgi.helloservice.impl;

import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Service;
import org.glassfish.samples.osgi.helloservice.api.HelloService;

/\*\*
 \* @author arungupta
 \*/
@Component(name="howdy-service")
@Service
public class HowdyImpl implements HelloService {

  public String sayHello(String name) {
    return "Howdy " + name;
  }
}

Another implementation of HelloService interface and uses "Howdy " for the greeting. Notice the name attribute has a different value.

Here is the complete pom.xml:

<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.osgi.helloservice</groupId>
  <artifactId>helloservice</artifactId>
  <packaging>bundle</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>helloservice</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.felix</groupId>
      <artifactId>org.apache.felix.scr.annotations</artifactId>
      <version>1.2.0</version>
      <scope>provided</scope>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>1.5</source>
          <target>1.5</target>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.felix</groupId>
        <artifactId>maven-bundle-plugin</artifactId>
        <version>2.0.1</version>
        <extensions>true</extensions>
        <configuration>
          <instructions>
            <Export-Package>${pom.groupId}.api</Export-Package>
            <Bundle-SymbolicName>${pom.artifactId}</Bundle-SymbolicName>
          </instructions>
        </configuration>
      </plugin>
    <plugin>
      <groupId>org.apache.felix</groupId>
      <artifactId>maven-scr-plugin</artifactId>
      <executions>
        <execution>
          <id>generate-scr-scrdescriptor</id>
          <goals>
            <goal>scr</goal>
          </goals>
        </execution>
      </executions>
    </plugin>
  </plugins>
 </build>
</project>

Maven SCR Plugin generates the descriptor file using the metadata specified by the @Component and @Service annotation in service implementations. If this plugin is used with Maven Bundle Plugin then it also adds the generated descriptor (OSGI-INF/serviceComponents.xml) to the bundle and set the required "Service-Component" manifest header.

Giving "mvn clean install" generates "target/helloservice-1.0-SNAPSHOT.jar" and installs the bundle in the local repository. This JAR is used later in the client project for importing the service API definition. The generated JAR has the following manifest:

Manifest-Version: 1.0
Export-Package: org.glassfish.samples.osgi.helloservice.api
Service-Component: OSGI-INF/serviceComponents.xml
Built-By: arungupta
Tool: Bnd-0.0.357
Bundle-Name: helloservice
Created-By: Apache Maven Bundle Plugin
Build-Jdk: 1.6.0_17
Bundle-Version: 1.0.0.SNAPSHOT
Bnd-LastModified: 1268374529666
Bundle-ManifestVersion: 2
Import-Package: org.glassfish.samples.osgi.helloservice.api
Bundle-SymbolicName: helloservice

The key thing to notice is that only "api" package is exported. The generated component descriptor in "OSGI-INF/serviceComponents.xml" looks like:

<?xml version="1.0" encoding="UTF-8"?>
<components xmlns:scr="http://www.osgi.org/xmlns/scr/v1.0.0">
  <scr:component enabled="true" name="hello-service">
    <implementation class="org.glassfish.samples.osgi.helloservice.impl.HelloImpl"/>
    <service servicefactory="false">
      <provide interface="org.glassfish.samples.osgi.helloservice.api.HelloService"/>
    </service>
    <property name="service.pid" value="hello-service"/>
  </scr:component>
  <scr:component enabled="true" name="howdy-service">
    <implementation class="org.glassfish.samples.osgi.helloservice.impl.HowdyImpl"/>
    <service servicefactory="false">
     <provide interface="org.glassfish.samples.osgi.helloservice.api.HelloService"/>
    </service>
    <property name="service.pid" value="howdy-service"/>
  </scr:component>
</components>

Notice that the "Service-Component" manifest header is pointing to this generated descriptor. And so the two declared services "hello-service" and "howdy-service" are available for consumption by other clients.

There are several ways to manage OSGi runtime bundle in GlassFish as described in TOTD #118. Simply copying the bundle to "glassfish/domains/domain1/autodeploy/bundles" is sufficient in this case, so lets do that.

The remote telnet shell (accessible using "telnet localhst 6666") shows status of the deployed bundle and associated service as:

-> find hello
START LEVEL 1
 ID State Level Name
[ 221] [Active ] [ 1] helloservice (1.0.0.SNAPSHOT)
-> scr list 221
 Id State Name
[ 2] [active ] hello-service
[ 3] [active ] howdy-service
-> scr info 2
ID: 2
Name: hello-service
Bundle: helloservice (221)
State: active
Default State: enabled
Activation: delayed
Services: org.glassfish.samples.osgi.helloservice.api.HelloService
Service Type: service
Properties:
 component.id = 2
 component.name = hello-service
 service.pid = hello-service
-> scr info 3
ID: 3
Name: howdy-service
Bundle: helloservice (221)
State: active
Default State: enabled
Activation: delayed
Services: org.glassfish.samples.osgi.helloservice.api.HelloService
Service Type: service
Properties:
 component.id = 3
 component.name = howdy-service
 service.pid = howdy-service

Maven SCR Plugin provides several other annotations to change the default value for each service.

Now create a Java EE client project to invoke the service as:

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

Lets look at the completed project structure:

pom.xml
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/osgi
src/main/java/org/glassfish/samples/osgi/HelloClient.java

There is only one source file which is the Servlet client and looks like:

package org.glassfish.samples.osgi;

import java.io.IOException;
import java.io.PrintWriter;
import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.glassfish.samples.osgi.helloservice.api.HelloService;

/\*\*
 \* Hello world!
 \*/
@WebServlet(urlPatterns={"/HelloClient"})
public class HelloClient extends HttpServlet {

  @Resource(mappedName="hello-service")
  HelloService helloService;

  @Resource(mappedName="howdy-service")
  HelloService howdyService;

  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException {
    PrintWriter out = response.getWriter();
    out.println(helloService.sayHello("Duke"));
    out.println(howdyService.sayHello("Duke"));
  }
}

This is a Java EE 6-style Servlet, using @WebServlet annotation, and will be accessible at "/HelloClient". The two OSGi services are injected using @Resource annotation and using the name specified in the "OSGI-INF/serviceComponents.xml" descriptor earlier.

pom.xml

<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.osgi</groupId>
  <artifactId>helloclient</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>helloclient</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.glassfish.samples.osgi.helloservice</groupId>
      <artifactId>helloservice</artifactId>
      <version>1.0-SNAPSHOT</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>javax</groupId>
      <artifactId>javaee-api</artifactId>
      <version>6.0</version>
      <scope>provided</scope>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <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>
</project>

Note that the previously generated service bundle is added as a dependency in the "provided" scope as its already deployed to GlassFish.

"mvn clean package" generates "target/helloclient-1.0-SNAPSHOT.war" Deploy this WAR file to GlassFish as:

asadmin deploy target/helloclient-1.0-SNAPSHOT.war

And finally invoke the client as:

curl http://localhost:8080/helloclient-1.0-SNAPSHOT/HelloClient

to see the output as:

Hello Duke
Howdy Duke

This is the expected output after invoking the two services.

So there you go, this blog demonstrated how to access a OSGi declarative service from a Java EE client - both deployed on GlassFish v3.

Are you using OSGi Declarative Services ? How ?

Technorati: totd osgi glassfish javaee declarative service maven bundle bnd scr component dependencyinjection

About

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


Java EE 7 Samples

Stay Connected

Search

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