ONJava.com    
 Published on ONJava.com (http://www.onjava.com/)
 See this if you're having trouble printing code examples


Constructing Services with J2EE

by Debu Panda
05/25/2005

Web services are now a popular technology for implementing service-oriented applications. J2EE has become a popular platform to deploy web services applications. And J2EE 1.4 standardized building and deploying web services applications for the Java platform.

In my last article, I provided an introduction to service-oriented architecture (SOA) from a Java developer's perspective. In this article, I will explain how you can use J2EE 1.4 to build services that are interoperable and portable across J2EE 1.4-compliant application servers such as Oracle Application Server 10g.

Web Services Architecture

Let's briefly examine the architecture of a web service before drilling down into the details of web services development and deployment on the J2EE platform.

There are many definitions for web services, but in simple terms, web services are self-contained and self-describing components that can be published, discovered, and invoked across the network. A web service, as shown in Figure 1, may perform a simple function, such as checking a credit history, or a complicated task that can span several business processes.

Figure 1
Figure 1. How a web service works

There are two methods of interaction with web services: RPC style and document style. RPC-style web services were initially popular in the industry, but in recent years have been eclipsed by document-style as the preferred means of message exchange with web services.

Related Reading

Java Web Services in a Nutshell
By Kim Topley

RPC-style web services represent exchanges that can be modeled as remote procedure calls (RPC). These are quite common in business applications, with the exchanged messages conforming to a well-defined signature for the remote call and its return. In contrast, document-style web services model XML document exchange, where the exchange patterns are defined by the sending and the receiving applications. Document-style services are more relevant for applications that need to exchange business or other types of documents and, unlike RPC-style web services, the sender may not expect or wait for an immediate response.

Most developers would agree that web services is an effective technology for implementing SOA because it provides interoperability between heterogeneous platforms and technologies relying upon portable technologies such as XML, SOAP, and HTTP.

This independence of platform and implementation technology is the primary reason for web services' popularity. The clients do not have to know the implementation technology involved and can simply invoke the service over the network. For example, even if you build a service using Java/J2EE technologies and deploy it on a J2EE server such as Oracle Application Server Containers for J2EE (OC4J), the clients can be built using Microsoft's .NET framework.

Now that we have a basic understanding of web services, let's take a look at the elements that make up a web service.

What Are Web Services Made of?

A Web Services Definition Language (WSDL; pronounced "wizdle") document is at the heart of a web service. The WSDL describes the service, and is the "contract" to which the web service guarantees it will conform. The WSDL provides a complete description of the web service, including the port, operations, and message types involved.

Here is a simple example of a WSDL document that describes a HelloWorld web service:


<definitions 
 name="HelloService" 
 targetNamespace="http://oracle.j2ee.ws/ejb/Hello"
 xmlns="http://schemas.xmlsoap.org/wsdl/" 
 xmlns:tns="http://oracle.j2ee.ws/ejb/Hello" 
 xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/" 
 xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/" 
 xmlns:ns1="http://oracle.j2ee.ws/ejb/Hello/types" 
 xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
 xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"> 
 <types> 
  <schema elementFormDefault="qualified" 
  targetNamespace="http://oracle.j2ee.ws/ejb/Hello/types" 
   xmlns="http://www.w3.org/2001/XMLSchema" 
   xmlns:soap11-enc="http://schemas.xmlsoap.org/soap/encoding/"
   xmlns:tns="http://oracle.j2ee.ws/ejb/Hello/types" 
   xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" 
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
  <complexType name="sayHello"> 
    <message name="HelloServiceInf_sayHello"> 
      <part name="parameters"
        element="ns1:sayHelloElement"/> 
    </message> 
    <message name="HelloServiceInf_sayHelloResponse"> 
      <part name="parameters" 
        element="ns1:sayHelloResponseElement"/> 
    </message> 
    <portType name="HelloServiceInf">
      <operation name="sayHello"> 
        <input message="tns:HelloServiceInf_sayHello"/> 
        <output message="tns:HelloServiceInf_sayHelloResponse"/>
      </operation> 
    </portType> 
    <sequence> 
      <element name="String_1" nillable="true" type="string"/> 
    </sequence> 
  </complexType> 
  <complexType name="sayHelloResponse"> 
    <sequence> 
    <element name="result" nillable="true" type="string"/> 
    </sequence> 
  </complexType> 
  <element name="sayHelloElement" type="tns:sayHello"/> 
  <element name="sayHelloResponseElement" 
    type="tns:sayHelloResponse"/> 
  </schema>
 </types> 
 <binding name="HttpSoap11Binding" type="tns:HelloServiceInf"> 
 <soap:binding style="document" 
      transport="http://schemas.xmlsoap.org/soap/http"/> 
 <operation name="sayHello">
   <soap:operation 
      soapAction="http://oracle.j2ee.ws/ejb/Hello:sayHello"/> 
   <input> 
     <soap:body use="literal" parts="parameters"/> 
   </input>
   <output> 
     <soap:body use="literal" parts="parameters"/> 
   </output> 
 </operation> 
 </binding> 
 <service name="HelloService"> 
   <port name="HttpSoap11" binding="tns:HttpSoap11Binding"> 
     <soap:address location="REPLACE_WITH_ACTUAL_URL"/> 
   </port>
</service>
</definitions> 

If you look at the WSDL, you'll note that it has a complete description of the HelloService web service, including the port, operations, and message types. The WSDL is the contract between the web service and its clients and it help automate the generation of client proxies.

The other two key technologies of the web services platform are SOAP, the protocol used to invoke a web service, and UDDI, which provides the registry where web services can be located.

Support for these technologies is fully integrated into the J2EE platform. Let's take a look at J2EE's web services support.

Using J2EE as a Web Services Platform

J2EE 1.4 provides a comprehensive platform for building and deploying web services applications using regular Java classes or Enterprise Java Beans. The following table provides the details of the web service APIs included in J2EE 1.4.

Java APIs Description

JAX-RPC /JSR 101

Java API for XML Remote Procedure Call: API for building web services and clients with remote procedure calls (RPC) and XML

Enterprise Web Services/ JSR 109

J2EE Deployment Model for Java Web Services

SAAJ

SOAP with Attachments API for Java: Enables developers to produce and consume messages conforming to the SOAP 1.1 specification and SOAP with Attachments

JAXP

Java API for XML Parsing: The reading, manipulating, and generating of XML documents through Java APIs in a standard way

JAXB

Java API for XML Binding: Automates the mapping between XML documents and Java objects

JAXR

Java API for XML Registries: Provides a standard way to access business registries, such as UDDI, and share information

EJB 2.1

Provides ability to expose Stateless Session EJB with web service end-point

JAX-RPC

JAX-RPC, defined under JSR 101 in the Java Community Process, provides the Java API for building and accessing web services and is thus the "heart and soul" of building and deploying web services with the J2EE platform. It provides a simple, robust platform for building web services applications by hiding from the application developer the complexity of mapping between XML types and Java types and the lower-level details of handling XML and SOAP messages. It introduces a method call paradigm by providing two programming models: a server-side model for developing web service endpoints using Java classes or stateless EJBs, and a client-side model for building Java clients that access web services as local objects. JAX-RPC 1.1 mandates the use of SOAP 1.1 and interoperability with web services built with other technologies such as Microsoft .NET. J2EE-1.4-compliant application servers, such as OC4J 10.1.3 and the Sun Java System Application Sever, provide support for JAX-RPC.

JAX-RPC is somewhat of a misnomer, since it supports both RPC-style and document-style web services.

Web Services Deployment Model

Prior to J2EE 1.4, all J2EE vendors supported web services using their proprietary deployment models. J2EE 1.4 defined the deployment model for Java web services. It standardized development, deployment, and service publication and consumption for web services for the J2EE platform.

I will discuss the deployment and consumption aspects of Java-based web services later in this article.

Given the J2EE 1.4 support for web services, let's examine the way in which a web service is constructed using the J2EE platform.

Building a Web Service with J2EE

Creating a web service as a distributed component that is portable and interoperable is not a trivial task. As discussed earlier, you can deploy either regular Java classes or stateless EJBs as web services. Regular Java classes are packaged in a web module and EJB web services are packaged in normal ejb-jar modules.

Given these two deployment options, which one do you use?

Java Class versus Stateless EJB: The Endless Debate

It is a matter of prolonged debate whether you should choose a regular Java class or EJBs as your technology for building a web service. Java classes are easier to develop than EJBs, are pure Java objects, and do not have the "extra baggage" that EJBs do. However, EJBs provide several nice features, such as declarative transaction and security, and let the developer concentrate on building business logic without having to worry about the infrastructure services. EJB 3.0 is greatly simplifying the programming model and in that spec EJBs will look like regular Java classes.

Packaging Requirement

Whether you decide to use a regular Java class or EJBs, you need to package several artifacts into your WAR or ejb-jar to expose your component as a Java web service. Following are the packaging structures for web services based either on EJB or regular Java classes.

ejb-jar for an EJB-based web service:

/META-INF/
    ejb-jar.xml    
    webservices.xml    
          oracle-webservices.xml    
    mapping-file.xml   
          wsdl/ the wsdl file 
    ejb classes (includes endpoint and bean classes)

Web app (.war) for a regular Java web service:

/WEB-INF/
    web.xml 
    webservices.xml    
    oracle-webservices.xml    
    mapping-file.xml    
    wsdl/        the wsdl file     
    /classes/(includes endpoint and bean classes)
/lib/

Let us discuss each of the deployment-time artifacts and descriptors:

You must package all these artifacts in the WAR or ejb-jar module before you can deploy your component as a web service. Many development tools, such as Oracle JDeveloper, simplify development of web services by doing mundane tasks such as generating deployment descriptors, mapping files, etc. Furthermore, most application servers provide web services assembly tools that take care of the J2EE web service packaging requirements.

Beyond an understanding of the components that make up a web service and the associated packaging requirements, there are architectural issues you must deal with when developing a web service.

Approaches to Constructing Services

The main challenge in building a web service is to identify the service with the right granularity. You can either build a new service, or expose an existing component that is built as a Java class or EJB and expose that as a service. When building a service, you can take either the top-down or bottom-up approach:

Interoperability Matters

Obviously, it is imperative that your web services be interoperable in nature. J2EE 1.4 mandates conformance to the Basic Profile 1.0 specified by the Web Services: Interoperability (WS-I) organization. When building web services, you must test for interoperability before you deploy them into production.

In addition to the design approaches and a need to field interoperable services, there are a few best practices that you can follow to maximize the utility of your web service.

Best Practices

Here are a few best practices for developing web services:

The J2EE Blueprint Application Java Adventure Builder provides a nice blueprint application for building Java-based web services application.

Once a web service has been designed, developed, and deployed, associated client components are generally created to interact with the given service.

Invoking Web Services

The client for a web service can be any of the following types: static stub, dynamic proxy, or Dynamic Invocation Interface (DII).

Building a web service client may be as complex as building a simple web service. Fortunately, J2EE 1.4 makes it simpler for J2EE developers to use web services from any type of J2EE component--namely web clients or EJB components.

You can invoke a web service as you would any other resources using JNDI via the following:

The Future of Java Web Services

Uptake of Emerging Web Services Standards

The web services platform has grown to include reliability, security, transactions, manageability, policy and so on. There are several standards that has emerged or emerging in the web services space. There are several JSRs being worked on in the Java Community Process to design a new Java API to uptake these emerging standards and the following table lists some of these JSRs.

Java Specification Request Goal
181 Web Services Metadata
208 Java Business Integration
261 Java API for XML Web Services Addressing
262 Web Services Connector for JMX
265 API for using Web Services Policy

In addition to these evolving standards, we are now getting a glimpse into the web services support afforded by the next major release of the J2EE platform.

Simplifying SOA Development with J2EE 5.0

Service-oriented applications are fairly difficult to build with J2EE, so J2EE 5.0 is designed to make development simpler by making use of Web Services Metadata annotations defined by JSR 181. EJB 3.0 and Web Services Metadata have the similar goals of providing developer friendliness.

For developing a simple Java web service in J2EE 1.4, you need several web service artifacts: WSDL, mapping files, and several verbose standard and proprietary web services deployment descriptors. The Web Services Metadata specification is taking a configuration-by-default approach similar to EJB 3.0 to make development easier. The Web Services Metadata annotation processor (or web services assembly tool) will generate these files for you so you only have to worry about the implementation class.

Here is how a simple Java web service looks when it's developed using Web Services Metadata:

package oracle.jr181.demo; 
import javax.jws.WebMethod; 
import javax.jws.WebService; 
@WebService(name = "HelloWorldService", 
      targetNamespace = "http://hello/targetNamespace" ) 
public class HelloWorldService {        
@WebMethod public String sayhello(String name ) { 
     return "Hello” +name+ “ from jws";
    }   
}
  
As I mentioned previously, EJB 3.0 is simplifying the development of EJBs by using regular Java classes. By making use of EJB 3.0 and Web Services Metadata, developing EJB-based web services is going to be much simpler. Here is how a simple HelloWorld EJB web service looks when using EJB 3.0 and web services metadata. You do not have to worry about creating WSDL, deployment descriptors, etc., and the application server will take care of generating these artifacts during deployment.
package oracle.ejb30.ws;
import javax.ejb.Remote;
import javax.jws.WebService;
@WebService  
public interface HelloServiceInf extends java.rmi.Remote{
@WebMethod java.lang.String sayHello(java.lang.String name) 
                              throws java.rmi.RemoteException;
}

The following is the implementation class for the HelloWorld EJB in EJB 3.0:

package oracle.ejb30.ws;
import java.rmi.RemoteException;
import javax.ejb.Stateless;
@Stateless(name="HelloServiceEJB")
public class HelloServiceBean implements HelloServiceInf {
public String sayHello(String name) {
 return("Hello "+name +" from first EJB3.0 Web Service");
 }
}

The above example clearly demonstrates that service development is going to be much simpler with web services metadata and EJB 3.0.

Conclusion

In this article, you learned the basics of building web services using the J2EE platform. You can start building and deploying your web services in your favorite J2EE-compliant application servers such as Oracle Application Server 10g, Sun Java System Application Sever, etc. today.

Resources

Debu Panda is a Senior Principal Product Manager of the Oracle Application Server development team.


Return to ONJava.com.

Copyright © 2009 O'Reilly Media, Inc.