Chapter 29. Web Services and the WebLogic Platform

Introduction

WebLogic Platform offers one of the most comprehensive suites of tools for building, deploying, and consuming Web services. The WebLogic Platform technology stack embraces the current Web services’ standards of Simple Object Access Protocol (SOAP), Web Services Description Language (WSDL), and Universal Description, Discovery, and Integration (UDDI). It also provides support for upcoming Web services’ standards such as JAX-RPC (Java APIs for XML-based RPC).

This chapter provides a high-level overview of the Web services features in WebLogic Platform 7.0. It assumes that you are already familiar with the concept of Web services and the unique problems they solve. Chapter 7, “An Introduction to Web Services,” provides an excellent introduction to these concepts and is highly recommended as prerequisite reading before you proceed.

First, the chapter reviews the basic architecture of Web services; then it examines how that framework is expressed in WebLogic Platform 7.0 by providing a roadmap of Web service components in Platform 7.0. The chapter then examines the two types of Web services, simple and message-style, as well as the different back-end application components that can actually fulfill the services. The next logical step is to examine a Web service under the hood and then finally delve into the various Web service client APIs available in WebLogic Server.

The Architectural Framework of Web Services

Figure 29.1 shows the players in a Web service framework, and Figure 29.2 illustrates one sample chronology of a Web service use case flow.

The Web service players.

Figure 29.1. The Web service players.

The roles of the Web service players.

Figure 29.2. The roles of the Web service players.

A service provider, for example, WebLogic Server, hosts a Web service that it advertises by publishing the service in a Service Registry (for example, a UDDI node may also be hosted by WebLogic Server). A client, which can be a browser or Java application, GUI, or another Web service, optionally looks up a service in the Service Registry to obtain the service’s WSDL file. The service description WSDL file specifies to the client what operations are available, how to invoke those operations, and where (URL) to invoke them. The lookup is optional because the client may obtain the WSDL file in many other ways; it could even be in a predetermined location. A WSDL file may not even be necessary if the client already knows what, how, and where to invoke the service. The prescribed communication protocol between these players is SOAP, even if looking up a service in a registry. Of course, to use a registry, you must obtain its URL first.

Some of these technologies still lack the maturity, features, and in some cases, the critical mass required for supporting all possible business transactions. For instance, it is not practical for businesses to adopt the Web Service Registry, UDDI, due to inadequate partner agreement standards. However, Web services have evolved and gained traction with unprecedented speed. Although they are merely based on the evolution of ubiquitous technologies such as XML and HTTP, the potential effect they will have on business in the future could be revolutionary.

Steps 1, 2, and 3 shown in Figure 29.1 will be covered in Chapter 31, “Discovering Web Services.” This chapter will focus on steps 4 and 5 of this process, as well as the inner workings of the Web service implementation.

Supported Standards

WebLogic Platform 7.0 supports the following Web service standards:

  • SOAP 1.1 with attachments

  • WSDL 1.1

  • JAX-RPC 1.0

  • UDDI 2.0

Again, this chapter assumes you are already familiar with these standards, their formats, and intended use. However, the format diagram shown in Figure 29.3 and Figure 29.4 serve to clarify the parts of a SOAP message and WSDL document, respectively, and also help define the vocabulary for these chapters. Embedded boxes represent XML subelements of the enclosing XML element. Listing 29.1 shows an actual SOAP message. You can also refer to Listing 29.2 later in this chapter for a fleshed-out WSDL file.

The parts of a SOAP message.

Figure 29.3. The parts of a SOAP message.

The parts of a WSDL document. Listing 29.2 later in this chapter shows a fleshed-out WSDL file.

Figure 29.4. The parts of a WSDL document. Listing 29.2 later in this chapter shows a fleshed-out WSDL file.

Note

The HTTP header is technically not part of the SOAP message but is shown here for illustrative purposes only.

Example 29.1. An Actual SOAP Message

<env:Envelope  xmlns:xsd="http://www.w3.org/2001/XMLSchema"
  xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
  xmlns:env="http://schemas.xmlsoap.org/soap/envelope/"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
 <env:Header>
 </env:Header>
 <env:Body>
  <m:calculateTax    xmlns:m="http://www.bea.com/statelessSession"
    env:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
   <productCategory xsi:type="xsd:int">1959</productCategory>
   <zipCode xsi:type="xsd:string">80516</zipCode>
  </m:calculateTax>
 </env:Body>
</env:Envelope>

For more information on these standards, see the following links:

  • SOAP and WSDL are World Wide Web Consortium (W3C) specifications that can be found on the W3C Web site at http://www.w3.org.

  • UDDI is an initiative sponsored by a private consortium of companies. For more information, visit their Web site at http://www.uddi.org.

  • JAX-RPC is a Sun Microsystems specification based on JSR–101, accessible at http://java.sun.com.

Why WebLogic Web Services?

Web services are no more than windows to applications, be it large or small, simple or complex. It is therefore still critical, and more critical in some ways, for such applications to be scalable, efficient, reliable, and maintainable. Web services are all about real-time, instant, and round-the-clock access to information and applications. WebLogic Server, being a time-tested application server and market leader, is well positioned for the challenge.

Just as important, however, is the fact that the WebLogic Web service technology stack is all based on industry standards, which means Web service clients and servers built on the WebLogic Platform can interoperate with other standard Web service implementations in any programming language or programming model. In addition, version 7.0 now implements JAX-RPC, a standard implementation and deployment model for Java Web services, making your Web service code portable to other JAX-RPC–compliant servers.

Lastly, WebLogic Web services build on industry-standard J2EE components and are packaged as standard J2EE enterprise applications. You can therefore leverage your existing J2EE experience and investment in building world-class Web service offerings. For the non-J2EE developer, WebLogic Workshop provides one of the most advanced, intuitive, and powerful graphical IDEs (Integrated Development Environments) for quickly developing Web services without any server-side programming.

Roadmap to WebLogic Web Services

The objective of this section is to highlight major Web service initiatives in this release as opposed to providing an exhaustive list of all Web services or Web services–related components in WebLogic Platform 7.0. Figure 29.5 provides a snapshot of Web service pieces and interrelationships in WebLogic Platform 7.0.

WebLogic Web service roadmap.

Figure 29.5. WebLogic Web service roadmap.

Figure 29.5 makes the following points:

  • There are two ways of creating, deploying, and running a local Web service.

  • A Web service requires a runtime environment or container to execute.

  • The WebLogic Server can be a provider as well as a consumer of Web services.

  • Clients can be internal, external, or programmatic, possessing either a GUI or Web interface. Even a Web service can be a client to another Web service.

Creating Local Web Services

WebLogic Platform 7.0 provides two ways of developing your own locally hosted Web service: through WebLogic Server and through the WebLogic Workshop.

Through WebLogic Server

The WebLogic Server (WLS) component of WebLogic Platform 7.0 provides tools for you to create your own Web service, hosted within WebLogic Server. Both client and server requisite files can be generated automatically and yet allow points of control via pluggable custom components. Using these tools requires that you know Java and J2EE, but the WLS provides the most flexible and unbounded environment for creating Web services. This chapter and Chapter 30, “Developing Web Services for WebLogic Server,” will illustrate these features in greater detail.

Through WebLogic Workshop

The WebLogic Workshop (WLW) component of WebLogic Platform 7.0 is a wizard for creating Web services. For the business programmer who would rather focus on developing enterprise business logic and business components, WebLogic Workshop is the answer. WLW is a sophisticated IDE for creating Web service clients and providers, in an easy-to-use and intuitive visual interface. WLW is discussed in more detail in Chapter 32, “Web Services Made Easy—WebLogic Workshop.”

Web Service Runtime Environments

When a Web service executes, it presumes the availability of certain services that it uniquely needs. A Web service runtime environment provides a library of services, both client and server side, such as support for a fixed set of data types, APIs for type mappings (to XML) and extensibility mechanisms, processing of standard service descriptions, and deployment APIs. This concept of a Web service runtime is akin to a standard J2EE container that provides a uniform environment for application components such as Enterprise JavaBeans (EJB) to run, thus enabling portability of EJBs across any J2EE-compliant application server. The JAX-RPC initiative claims to do just that. It aims to replace many proprietary Web service implementations that exist today with an industry standard Web service deployment and execution model, thereby protecting your development investment.

There are two distinct Web service runtime environments in WebLogic Platform: one is for the WebLogic Server (JAX-RPC–based Web service container), and the other is for WebLogic Workshop (KNEX runtime). A Workshop-created Web service can run only in a KNEX runtime, and a WLS-created Web service can run only in a JAX-RPC container. However, both types of Web services can interoperate with each other, as well as be published in the same UDDI registry. No special client code is necessary to invoke WLW Web services; that is, a client is oblivious to what runtime environment the service provider is using. In WebLogic Platform 7.0, the appropriate Web service runtimes will be invoked automatically for you when you start either the WebLogic Workshop or WebLogic Server.

Local Web Service Advertised with UDDI

WebLogic Server 7.0 provides new support for hosting your own Web Service Registry, based on the worldwide standard UDDI 2.0. It also features a UDDI browser for both looking up and publishing a service and an implementation of the UDDI API. Publishing your Web service, however, either internally within your enterprise or otherwise, is not required for you to be able to create, deploy, and invoke the Web service. This topic is fully discussed in Chapter 31.

The Portlet Wizard

WebLogic Platform 7.0 includes a portal framework called the WebLogic Portal. A portal is a feature-rich Web site. It provides a single point of access to enterprise data and applications, presenting a unified and personalized view of that information to employees, customers, and business partners.

A portal allows you to have multiple Web applications within a single Web interface. In addition to regular Web content that appears in a portal, a portal provides the ability to display portlets in a single Web interface. A portlet is a self-contained application or content that resides within the WebLogic portal framework. WebLogic Portal provides a wizard for configuring a portlet to invoke and consume Web services.

The Portlet Wizard is accessible from inside the E-Business Control Center (EBCC) application of the WebLogic Portal component in WebLogic Platform 7.0. Invoke the EBCC in Windows by choosing Start, Programs, BEA WebLogic Platform 7.0, WebLogic Portal 7.0, E-Business Control Center.

You then must open a project in the EBCC. An example project file is available at

<WL_HOME>weblogic700samplesportalwlcsDomaineaAppswlcsApp-project wlcsApp-project.eaprj

If you don’t already have one, you must first define a portal to which your portlet will be associated. While creating your portlet, specify Web service(s) for the content type, as shown in Figure 29.6.

Create a Web service portlet using the EBCC Portlet Wizard.

Figure 29.6. Create a Web service portlet using the EBCC Portlet Wizard.

A convenient wizard feature is the capability to specify the WSDL URL of the Web service to be presented in the portlet, as shown in Figure 29.7.

The Portlet Wizard allows you to select the Web service to be included in the portlet, via a WSDL URL.

Figure 29.7. The Portlet Wizard allows you to select the Web service to be included in the portlet, via a WSDL URL.

For more information on the Portlet Wizard, consult the WebLogic Portal EBCC documentation.

Web Services Included with WebLogic Commerce

The WebLogic Portal component of WebLogic Platform 7.0 includes a sample commerce application representing an online hardware store, complete with an online catalog and shopping cart. During checkout, the sales taxes must be calculated and displayed, and before checkout can be completed, the user’s credit card must be authorized for the purchase amount. These two services, tax and payment, are deployed as Web services. Their Web service home pages, shown in Figure 29.8 and 29.9, were generated automatically by WebLogic Server when its tools were used to generate the Web service.

First, you need to launch the WebLogic Commerce Server, which hosts these two Web services. To do this in Windows, choose Start, Programs, BEA WebLogic Platform 7.0, WebLogic Portal 7.0, Portal Examples, Commerce Templates, Launch Commerce Server.

When the Commerce Server is up and running, you can reach the tax and payment home pages at the following URLs (by default), respectively:

http://localhost:7501/taxws/TaxService

http://localhost:7501/payws/PaymentService

The sample tax Web service that comes deployed with the WebLogic Portal Commerce sample (see Figure 29.8) illustrates how a local or remote Web service can be integrated with an online store. However, because it is a sample, its business logic is inadequate for commercial use. You must customize or integrate with a tax service bureau for production use.

The Commerce sample tax Web service home page.

Figure 29.8. The Commerce sample tax Web service home page.

Similar customization and integration requirements also apply to the sample payment Web service shown in Figure 29.9. The WebLogic Server generated both of these Web services automatically.

The Commerce sample payment Web service home page.

Figure 29.9. The Commerce sample payment Web service home page.

For now, observe that the generated Web service home page tells you what the service is all about, its publicly available operations or methods, access to its WSDL, and some Web service testing mechanisms. We will discuss Web service home pages in greater detail in the next chapter.

Another sample application called End-to-End highlights how the portal framework can be used to build business-to-business and business-to-consumer portlets. It implements and uses the same sales tax Web service as in the Commerce application. In addition, it implements and uses a unique payment Web service that was built with WebLogic Workshop. The End-to-End sample application can be invoked via

<WL_HOME>/weblogic700/samples/platform/e2eDomain/starteE2E.bat

Web Service Examples in WebLogic

WebLogic Platform includes a wealth of working sample code that further illustrates the Web service concepts described in these chapters. All Web service samples can be found in

<WL_HOME>weblogic700samplesserversrcexampleswebservices

where <WL_HOME> is the base install directory for WebLogic Platform. Each sample comes equipped with a build.xml file, so invoking ant builds and deploys the sample for you into the examples server, and invoking ant run runs the sample. You can find detailed instructions on how to run the examples at

<WL_HOME>weblogic700samplesserversrcexampleswebservicespackage-summary.html

The following samples are provided (specific sample locations shown in parentheses are relative to the preceding samples home folder):

  • An RPC Web service based on a Java class back-end component (in ..asicjavaclass)

  • An RPC Web service based on a stateless session bean back-end component (in ..asicstatelessSession)

  • An RPC Web service that uses user-defined types (in ..complexstatelessSession)

  • Client Examples:

    • A static client (in ..clientstatic)

    • A dynamic client using a WSDL file (in ..clientdynamic_wsdl)

    • A dynamic client without a WSDL file (in ..clientdynamic_no_wsdl)

    • A static client invoking a Web service that employs output parameters (in ..clientstatic_out)

    • An RPC Web service that uses SOAP handlers (in ..Handlerlog)

    • An RPC Web service that uses SOAP handlers exclusively with no back-end component (in ..Handler ocomponent)

In addition, two new examples can be found on the Sams Web site, www.samspublishing.com.

  • A Web service (called ws-inout) that illustrates use of output parameters or Holder classes

  • An asynchronous client and Web service (called ws-async) that uses JMS (Java Messaging Service) and MDB (message-driven beans) as back-end components

Web Service Design Questions

This section describes the choices, and hence decisions, you have for building a Web service using WebLogic Platform.

Web Service Types

The types of Web services essentially differ in the mode of communication employed: synchronous or asynchronous.

Synchronous Web Services

Also known as simple Web services, synchronous Web services implement a call-and-response Remote Procedure Call (RPC) mode of interaction. In this mode, the caller invokes the Web service, and the business logic behind the Web service executes its behavior while the caller waits for the business logic to complete its operation and return a response or result before proceeding. Hence, this is a synchronous mode of communication. When the business logic is complete, the Web service will return the results to the calling program or the Web service’s consumer. During the time that the Web service’s business logic is executing, the Web service’s consumer thread is blocked and cannot do any other work.

For a simple coarse-grained business process, like the tax rate calculation, this type of service may be acceptable. However, for complex business processes like inventory management, EDI processes, or a long-running transaction that may access multiple back-end legacy systems, the blocking time for the Web service’s consumer could be unacceptable. Releasing threads is very important when the consumer is running within a concurrent system where processing threads must be freed quickly to enable high throughput. Figure 29.10 depicts a simple RPC service invocation.

A simple RPC Web service invocation.

Figure 29.10. A simple RPC Web service invocation.

Asynchronous Web Services

Complex processes require an asynchronous communications mechanism rather than the simple synchronous RPC mechanism currently implemented by most Web service producers. An asynchronous process hands the Web service request to the Web service producer, allowing the Web service client or consumer to continue processing while the Web service producer does its work. The client in this case does not need the result of the service call, not even an error response, to continue. After an appropriate amount of time has passed, the Web service consumer checks back with the Web service producer to see whether the Web service’s response has been completed. If the response is completed, the consumer can retrieve the response and go on with its work. Alternatively, the Web service client can configure itself as a listener or provide callbacks for the service producer to inform the client in real-time when results become available.

Asynchronous Web services, also known as “complex” Web services, are useful in cases where a service, by nature, will take an inordinate amount of time or resources to fulfill. Examples of such services are

  • Settling payments

  • Obtaining a credit score or rating

  • Performing intensive computing tasks

  • Responding to data mining requests

Figure 29.11 illustrates an asynchronous Web service using a message-driven bean for executing business logic and JMS (Java Messaging Service) to effect acceptance and delivery of client arguments or data.

Asynchronous Web service using a message-driven bean for business logic.

Figure 29.11. Asynchronous Web service using a message-driven bean for business logic.

Asynchronous communications provide key advantages that are essential for enterprise-class Web services, including providing higher scalability, utilizing threads more efficiently, and providing users with faster feedback response.

Tip

In WebLogic Platform 7.0, a Web service no longer needs to be exclusively RPC or message-style. For your convenience, a single Web service can now contain both RPC and message-style methods.

Synchronous or Asynchronous?

How do you decide if a Web service should be request-response or message-style? In general, it should be considered a candidate for an asynchronous Web service if the service

  • Can be considered a “batch” job that usually runs overnight.

  • Does not need to return any immediate information or acknowledgment to the client—for example, calling a service to update an online catalog database. In other words, the nature of the request is one-way.

  • Takes an inordinate amount of time to fulfill.

  • Involves multiple critical or scarce resources, such as distributed transactions.

All other situations can be implemented as request-response.

Back-End Provider Components

A Java class or an EJB can perform the business logic that needs to be executed to fulfill a Web service request. The only EJB types acceptable as Web service back-end components in WebLogic Server are stateless session beans and message-driven beans.

EJBs

Web service operations implemented with a method of a stateless session EJB are interface driven, which means that the business methods of the underlying stateless session EJB determine how the Web service operation works. That is, if you specify a Web service based on a stateless session EJB, the WebLogic tools will automatically define the Web service operations and their signatures exactly as the methods and their signatures will be defined on the EJB. The danger here is that you expose your application component model as your Web service, which is typically a mistake. The next chapter suggests best practices for Web service design.

Use a stateless session EJB back-end component if your application has the following characteristics:

  • The behavior of the Web service can be expressed as an interface.

  • The Web service is process oriented rather than data oriented.

  • The implementation of the Web service will take advantage of the facilities of EJBs.

Message-driven beans, the other type of EJB on which to base Web services, can be used in conjunction with JMS destinations and queues for implementing asynchronous Web services. You can find more details on this later in this chapter in “Inside an Asynchronous Web Service.”

Java Classes

Web service operations implemented with Java classes are similar to those implemented with an EJB method. Creating a Java class is often simpler and faster than creating an EJB. However, there are limitations and restrictions to using a Java class as a back-end component; they will be discussed in the next chapter.

Security

You can secure your Web service in WebLogic Server using the following methods:

  • Snoop prevention—Use the HTTPS transport, which encrypts all traffic between the client and Web service provider.

  • Authentication—When using HTTPS, two-way authentication can be configured so the server has to send credentials to the client, and vice versa. However, this technique authenticates only the client (such as the browser), and not necessarily the user. To accomplish the latter, you can use something similar to digital signatures (such as what the W3C-DSIG working group is developing; go to http://www.w3.org/TR/SOAP-dsig/ for more information).

  • Authorization—Institute username and password login to access a Web service. At a minimum, use the HTTPS protocol if username/password information is required by a Web service.

  • Securing the business logic—Configure permissions for the EJBs that fulfill the Web service request.

Refer to Chapter 30 to see exactly how these security measures are configured into a Web service.

Anatomy of a WebLogic Web Service

To better understand WebLogic Web services, you need to look at the basis of the 7.0 implementation: JAX-RPC 1.0.

The JAX-RPC Model

JAX-RPC (Java APIs for XML-based RPC) is a finalized Java specification from Sun Microsystems for standardized Web service invocation, processing, and deployment. JAX-RPC is actually generalized to handle Remote Procedure Call mechanisms employing any protocol or transport, but in the context of this WebLogic Server discussion, we are binding JAX-RPC to the SOAP protocol and the HTTP transport of Web services. The WebLogic Platform Web services implementation is faithfully based on the JAX-RPC 1.0 specification. Therefore, understanding JAX-RPC is essential for the comprehension and effective use of the WebLogic Server Web services features.

Tip

General knowledge of XML and XML namespaces will aid in understanding portions of the JAX-RPC specifications. Refer to the XML specifications available at http://www.w3.org for more information.

Some of the more important elements specified by JAX-RPC are

  • Client invocation styles—Specifies standard patterns and APIs for invoking a Web service.

  • Supported type system—Specifies a minimal set of Java types and XML types to be supported.

  • Standard type mappings and extensible type mappings—Provides consistent transformation rules between Java and XML, and vice versa, and the ability to extend such rules. In WebLogic parlance, these transformations are implemented via serializers and deserializers, respectively.

  • Service endpoint model—Specifies a standard programming model for the creation and deployment of the service provider.

  • JAX-RPC runtime system—Defines a library of services required to support the JAX-RPC execution model.

  • Standard service description—Adds some standard semantics and conventions to WSDL authoring and consumption.

  • Standard message handlers—A message handler gains access to a SOAP request or response, either to consume, pre-process, or post-process it. For instance, a handler may actually fulfill the SOAP request or merely condition it for the service provider.

The specification also imposes rules on XML encodings for SOAP messages, protocol bindings, and transport. Note that JAX-RPC does not alter nor enhance the definition and semantics of WSDL or UDDI.

Note

None of the use cases described in this chapter utilize UDDI, implicitly or otherwise. WebLogic Platform 7.0 does offer extensive support and tools for UDDI, and this issue will be discussed in Chapter 31.

WebLogic Server 7.0 offers all these JAX-RPC features and more, and has fully passed the JAX-RPC 1.0 Technology Compatibility Kit (TCK) test suite for both Servlet and J2EE Container requirements. Consequently, any client- or server-side Web services code you develop with WebLogic Server can be deployed and run on any JAX-RPC–compliant Web service container, thereby protecting your investment.

Serializers and Deserializers

When you invoke a Web service using a Java method call, its arguments, which are Java primitives or objects, must be translated into XML constructs for inclusion into a SOAP message. The process of converting a Java object to XML representation is called serialization. Conversely, before a Web service response can be returned to the caller, the SOAP return message containing results in XML format must be translated back to the appropriate Java primitives or objects. This conversion is known as deserialization. These conversions are implemented in the serializer and deserializer Java classes. Figure 29.12 shows where these conversions occur in a Web service use case.

The place where Java to XML conversions, and vice versa, occur.

Figure 29.12. The place where Java to XML conversions, and vice versa, occur.

Client proxies provide a higher level abstraction layer that shields the client from underlying tasks such as building the SOAP message, parsing a SOAP response, and performing HTTP protocol activities. We will discuss client proxies in more depth later. As you can see, both the client proxy and the SOAP servlet use serializers and deserializers. The following statements explain Figure 29.12 (the numbers in parentheses correspond to those in the figure):

  • The client makes a Java call to the proxy, with Java object parameters. The proxy must then convert this call to XML (SOAP) with the help of serializers (1.1).

  • The SOAP servlet receives the call and must first convert the XML parameters into Java objects before calling the back-end service (1.2.1), using deserializers.

  • The back-end service results come back in Java and must be converted to XML using serializers (1.2.3) before it can be transported via HTTP.

  • The client proxy receives the results in a SOAP response (XML) and must then convert the XML results to Java object results, using deserializers (1.3).

In essence, call data needs to be in XML (SOAP) format before transporting via HTTP (serialize), and call data needs to be in Java format before it can be used by a client or back-end service (deserialize).

As mentioned earlier, JAX-RPC prescribes rules on Java-to-XML mapping and vice versa, on a definite set of data types, listed in the following section. The WebLogic Server has coded these rules into default serializer and deserializer classes that are automatically and appropriately invoked when any built-in type is used in a Web service method call. However, if your Web service methods use user-defined Java types (UDT or non–built-in types) for parameters and return values, custom serializers and deserializers must be written or generated, and configured via type mappings into your Web service. This effectively extends the WebLogic/JAX-RPC built-in type mapping system. The next chapter explains how to define UDTs and mappings.

Supported or Built-in Types

Table 29.1 lists the Java types that are supported by WebLogic Server and their mappings to XML.

Table 29.1. Java Types Supported by WebLogic Server and Their Mappings to XML

Java Data Type (Lowercase Indicates a Primitive Data Type)

Equivalent XML Data Type

Int

int

short

short

long

long

float

float

double

double

byte

byte

boolean

boolean

char

string (with facet of length=1)

java.lang.Integer

int

java.lang.Short

short

java.lang.Long

long

java.lang.Float

float

java.lang.Double

double

java.lang.Byte

byte

java.lang.Boolean

boolean

java.lang.Character

string (with facet of length=1)

java.lang.String

string

java.math.BigInteger

integer

java.math.BigDecimal

decimal

java.lang.String

string

java.util.Calendar

dateTime

java.util.Date

dateTime

Byte[]

base64Binary

Weblogic.xml.schema.binding.util.Duration

duration

Array of any built-in Java data type

SOAP Array

JavaBean whose properties are any sequence of built-in Java data type

<xsd:sequence>

javax.xml.rpc.namespace.Qname

Qname

Use of any of these types in your Web service methods requires no additional consideration or programming to ensure proper translation, interpretation, and delivery via SOAP and WSDL. They are translated between Java and XML automatically.

SOAP Handlers

Because JAX-RPC and WebLogic Server provide such a convenient abstraction for performing all facets of Web services, you normally do not need to nor get to build the SOAP message yourself. Sometimes this feature could become a limitation. If you must influence the SOAP message in some way, JAX-RPC provides the concept of handlers for intercepting SOAP messages (both requests and responses) before they reach their destination. Handlers are Java classes that can be configured for invocation by the Web service container at appropriate junctures. You can do almost anything inside a handler, maybe even fulfill simple Web service requests without invoking a back-end component. Figure 29.13 clarifies where in a Web service call such handlers come into play.

How handlers intercept SOAP messages.

Figure 29.13. How handlers intercept SOAP messages.

Note

To better illustrate handlers, Figure 29.13 is simplified in that it does not show the client invoking serializers and deserializers.

Have you noticed that handlers always work with the SOAP message, that is, the XML representation of the request or response as opposed to the Java representation? You develop the Handler class code and then configure it as part of defining a Web service. Details are reserved for the next chapter. For now, you can scrutinize the make-up of a WebLogic Web service in the next section.

Inside a Synchronous (RPC) Web Service

Figure 29.14 shows the components that make up an End-to-End synchronous Web service call and fulfillment. Details on how to develop or generate these components will be discussed in the next chapter.

The components that make up an End-to-End synchronous Web service call and fulfillment.

Figure 29.14. The components that make up an End-to-End synchronous Web service call and fulfillment.

Each component plays the following role in the game:

  1. The client application makes calls to a smart proxy using a prescribed API, based on its chosen interaction style: static or dynamic. These proxies shield the client from details such as building the SOAP call, processing the SOAP response, converting Java types to XML and vice versa, and reading the WSDL file.

  2. The client proxy enlists the services of a JAX-RPC runtime to perform tasks such as fetching WSDL files; invoking SOAP message handlers; activating appropriate serializers/deserializers, both custom and default ones; and sending HTTP commands.

  3. The SOAP message is sent via an HTTP (or HTTPS) Post command to an endpoint, where a listener like a servlet would be running.

  4. WebLogic Server, which is hosting the servlet as well as the Web service business logic, invokes the appropriate back-end component and returns the result to the client over HTTP.

To see what transpires in the WebLogic Web service container, you can expand the server components as shown in Figure 29.15.

A look inside the Web service container.

Figure 29.15. A look inside the Web service container.

Each of the numbered steps in Figure 29.15 is explained here:

  1. The client makes a Web service call.

  2. The Web service reads the SOAP message request and identifies the operation that it needs to run. The operation in this case corresponds to an invocation of a SOAP message handler chain followed by an invocation of a method in a stateless session EJB or a Java class. In the absence of the optional Handler class, the flow would go from step 2 to step 4.

  3. The Web service invokes the appropriate handler chain. The handler chain accesses the contents of the SOAP message request, possibly changing it in some way.

  4. The Web service converts the operation’s parameters in the (possibly modified) SOAP message from their XML representation to their Java representation using the appropriate deserializer class. The deserializer class is either one provided by WebLogic Server for built-in data types or a user-created one for non–built-in data types.

  5. The Web service invokes the appropriate back-end component method, passing it the Java parameters. A Java result is returned.

  6. The Web service converts the method’s return value from Java to XML using the appropriate serializer class and packages it into a SOAP message response.

  7. The Web service invokes the appropriate SOAP message handler chain. The handler chain accesses the contents of the SOAP message response, possibly changing it in some way. In the absence of this optional return value handler chain, the flow would go from step 6 to step 8.

  8. The Web service sends the (possibly modified) SOAP message response back to the client application that invoked the Web service.

WebLogic Web services even support building a Web service provider that is solely composed of handlers and no back-end component (class or EJB). In this case, the handler alone fulfills the service request. A more realistic scenario is for a handler to cache results of certain popular service requests, with a TTL (Time to Live) on the cache. If the cache is up to date, the handler can just return its contents without invoking the back-end component. When the cache expires or is empty, the back-end component is invoked first, and the results are cached and then returned. This could significantly increase performance and scalability of a Web service.

The client internals are similar to what was described previously for the server. Handlers can be installed on outgoing SOAP requests as well as incoming SOAP results. Client-side handlers can also perform caching, which also will save network overhead.

Inside an Asynchronous Web Service

As you recall from Figure 29.11, an asynchronous service utilizes JMS destinations and message-driven beans to deliver complex business logic to service clients. Such a service provides at least two operations:

  • A submitData operation that the client calls to submit input or data for processing

  • A requestData operation that the client calls later to see whether results are available

Figure 29.16 depicts the component architecture for such a service.

The component architecture for an asynchronous Web service.

Figure 29.16. The component architecture for an asynchronous Web service.

Processing steps for an asynchronous Web service are as follows:

  1. The client invokes the one-way operation named submitData.

  2. The submitData operation puts the client data into JMS Destination 1. Because the back-end MDB is subscribed to JMS Destination 1, it is invoked with the client data.

  3. The MDB processes the data, taking an unspecified amount of time to do so.

  4. When processing is complete, the MDB places the result in JMS Destination 2.

  5. The client invokes the RPC (request-response) operation named requestData, whose sole task is to check with JMS Destination 2 to see whether the result is available.

  6. If available, the result is returned to the client. Otherwise, the client must try again later.

In practice, for reliability and for avoiding timing issues, another listener needs to be added, and JMS Destination 2 must subscribe to it. The new listener’s sole function is to cache or persist the result. The requestData service can then check this persistent store for results.

You might ask if the JMS destinations should be queues or topics. The rule of thumb is to use a JMS queue if there is only one kind of MDB that can process the request data because the WebLogic EJB container can instantiate as many MDB instances as necessary to handle the load. However, if there are multiple kinds of MDBs, a JMS topic would allow them all to subscribe to it and process data concurrently.

You also might observe that this implementation, as is, does not scale to multiple users. Because the Web service may serve many clients, how does the requestData operation ensure that one client’s result will not inadvertently be delivered to another client? One simple solution is to include with each submitData request some unique client ID, which is also to be included with each requestData call.

A more elegant design would allow this asynchronous Web service to alert the client immediately when his result becomes available, thereby obviating the need for any polling. The WebLogic Workshop Web service IDE can do just that, and is discussed in Chapter 32. For this discussion, it behooves you to contemplate how the client might implement a callback mechanism.

WebLogic Web Service Clients

This section focuses on a few types and styles of Web service clients that can consume WebLogic Web services. The treatment is certainly not exhaustive, but it does provide a few starting points.

Web Service Client Models

JAX-RPC defines three programmatic client interaction models, which WebLogic Server supports. They are described in the following sections.

Static

The most simple among the client modes, static invocation is best suited for use in situations in which the Web service is known and can be bound at development time. The implication is that there is no requirement to switch to another, albeit similar, Web service at runtime.

JAX-RPC prescribes a pattern for generating service-specific client stubs (which collectively act as the smart proxy shown in Figure 29.12) that are bound into the client at build time. These stubs are essentially abstractions to the service and port elements of the WSDL file:

  • ServiceNamePort—. Specifies a client stub representing the WSDL port element, where all operations advertised for that port can be invoked

  • ServiceName_Impl—. Represents the WSDL service but also acts as a cabinet for retrieving the above port object

In the static client model, the Smart Proxy box is specifically composed of these stubs, as shown in Figure 29.17. The stubs shown here are for a specific Web service named TaxService.

Service-specific stubs in a static client.

Figure 29.17. Service-specific stubs in a static client.

WebLogic Server follows this JAX-RPC prescription by providing tools that can take a known Web service description, either described by a provider EJB or an existing WSDL, and generate these stubs. These tools are discussed in detail in Chapter 30. Listing 29.2 shows the service description (WSDL) for an over-simplified sales tax Web service called TaxService. It supports one operation called calculateTax, which takes two string arguments, the Product Category of the item to be taxed and Postal/ZIP Code of the tax jurisdiction, and finally returns the sales tax percentage.

Example 29.2. Tax Web Service WSDL File

<?xml version="1.0" encoding="utf-8"?>

<definitions xmlns:s="http://www.w3.org/2001/XMLSchema"
   xmlns:http="http://schemas.xmlsoap.org/wsdl/http/"
   xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
   xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
   xmlns:tns="http://www.bea.com/servers/samples/examples/webservices/basic"
   xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/"
   targetNamespace="http://www.bea.com/servers/samples/examples/webservices/basic"
   xmlns="http://schemas.xmlsoap.org/wsdl/">

  <message name="calculateTax">
    <part name="category" xmlns:partns="http://www.w3.org/2001/XMLSchema"
                                type="partns:string" />
    <part name="zip" xmlns:partns="http://www.w3.org/2001/XMLSchema"
                           type="partns:string" />
  </message>

  <message name="calculateTaxResponse" >
    <part name="result" xmlns:partns="http://www.w3.org/2001/XMLSchema"
                              type="partns:string" />
  </message>

  <portType name="TaxServicePort" >
    <operation name="calculateTax"  >
      <input message="tns:calculateTax" />
      <output message="tns:calculateTaxResponse" />
    </operation>
  </portType>

  <binding name="TaxServicePortSoapBinding" type="tns:TaxServicePort" >
    <soap:binding style="rpc"
           transport="http://schemas.xmlsoap.org/soap/http" />
    <operation name="calculateTax" >
      <soap:operation soapAction="" style="rpc" />
      <input>
         <soap:body use="encoded" namespace="http://www.bea.com/servers/
samples/examples/webservices/basic"
            encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" />
      </input>
      <output>
         <soap:body use="encoded" namespace="http://www.bea.com/servers/
samples/examples/webservices/basic"
            encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" />
      </output>
    </operation>
  </binding>

  <service name="TaxService" >
    <documentation>todo: add your documentation here</documentation>
    <port name="TaxServicePort"
        binding="tns:TaxServicePortSoapBinding">
      <soap:address location="http://localhost:7001/taxws/TaxService?WSDL"/>
    </port>
  </service>

</definitions>

The client code snippet looks like this:

TaxService_Impl ws = new
    TaxService Impl("http://localhost:7001/taxws/TaxService");

TaxServicePort port = ws.get TaxServicePort();

port.calculateTax("4A", "80302");

Both the TaxService_Impl and TaxServicePort classes can be generated by WebLogic Server. These stubs cannot be used to represent any other Web service except the one whose service description was used to generate them. In other words, the service cannot be changed at execution time; hence, it is considered static.

Dynamic (with WSDL)

The Dynamic client model, also known as the Dynamic Invocation Interface (DII), allows you to invoke a service whose interface types may not be known until runtime. Examples of this situation might be

  • If you’re using UDDI to discover and integrate a Web service at runtime

  • If static stubs are not available at build time

Although this mode is much more flexible, it is also more complex and likely more difficult to develop, debug, and test. It is recommended that you use this invocation style with caution and only if absolutely necessary.

Figure 29.18 shows the client stack for dynamic service invocation. Here the smart proxy is composed of three more-generic client proxies.

Generic stubs in a dynamic client.

Figure 29.18. Generic stubs in a dynamic client.

In the DII mode, the client proxies are no longer service specific as they are in the static client scenario. Here, you use JAX-RPC–prescribed generic classes for invoking a Web service, which include (all in package javax.xml.rpc):

  • Service—. Acts as a generic stub for a Web service and declares the operations or methods that a client may invoke on the service

  • ServiceFactory—. Acts as a factory class for creating Service instances

  • Call—. Represents a specific operation advertised by a service and is used as a handle for invoking the operation

Again, these classes can be used to invoke any Web service, not just this tax service example.

The steps for dynamic invocation are as follows:

  1. Establish a service factory in the Web service runtime.

  2. Instantiate a service factory.

  3. Indicate which specific port, service, and operation you are trying to invoke. You do so by using references into the WSDL file via the XML qualified name construct, mapped to Java as the QName class.

  4. Given the service WSDL and port QName, obtain a Service instance from the service factory.

  5. Given the port and operation, obtain a Call instance for the operation to be invoked, from the Service instance.

  6. Invoke the operation. You pass in an array whose elements are of type Object. Each object instance represents an argument to the service operation, in the same order as defined in its WSDL. For Web service operations that take primitive Java types, you can still pass in its equivalent wrapper classes in the object array argument. The built-in serializers and deserializers are smart enough, by way of reflection, to divine the appropriate conversions.

The code snippet shown in Listing 29.3 realizes the preceding steps (where appropriate the step number is mentioned in commentary).

Example 29.3. Code Representing the Steps for Dynamic Invocation

// STEP 1: Setup the global JAX-RPC service factory
System.setProperty( "javax.xml.rpc.ServiceFactory",
  "weblogic.webservice.core.rpc.ServiceFactoryImpl");

// STEP 2: create service factory
ServiceFactory factory = ServiceFactory.newInstance();

// STEP 3: define qnames
String targetNamespace = "http://localhost:7001/...";
QName serviceName = new QName(targetNamespace, "TaxService");

QName portName = new QName(targetNamespace, "TaxServicePort");

QName operationName = new QName(targetNamespace,
                                "calculateTax");
URL wsdlLocation =
    new URL("http://localhost:7001/taxws/TaxService?WSDL");

// STEP 4: create service
Service service = factory.createService(wsdlLocation, serviceName);

// STEP 5: create call
Call call = service.createCall(portName, operationName);

// Build args or custom types, if any

// STEP 6: invoke the operation
result = call.invoke( new Object[] {"4A", "80302"} ) ;

More on QNames

A qualified name (QName) construct is an unambiguous reference to an XML data item—in this case, a WSDL item. A qualified name is made up of two parts: a namespace qualifier and a local name. The first argument to the QName constructor is the namespace of the WSDL item. In the case of the TaxService WSDL, all the service, port, and operation items use the default namespace for the XML file: the TargetNamespace attribute of the namespace definitions element. The second argument in this case is the WSDL data item, which is a local name in the WSDL file.

At the risk of “stating the obvious,” Table 29.2 shows how each Qname value is set.

Table 29.2. How Each QName Value Is Set

QName For

WSDL Data Item

Example

service

name attribute of the service element

<service name="TaxService">

port

name attribute of the port element (port is a sub-element of service)

port <port name="TaxServicePort"

operation

name attribute of the operation element ( operation is a subelement of portType)

<operation name="calculateTax">

The WSDL file for this sample tax service is shown in Listing 29.2.

Dynamic (Without WSDL)

You can also invoke a Web service dynamically without having access to a WSDL file at runtime. You still need to consult the WSDL file contents at development time, to glean the information needed for dynamic clients, and more. You need to explicitly set more WSDL information in the Call object, such as operation parameters and endpoint address. As shown in Listing 29.4, the steps for this task are similar to the dynamic client using known WSDL information, with just some additional code (steps 6 and onward) that builds up the Call object prior to invocation.

Example 29.4. Code Snippet for Dynamic Client That Does Not Use WSDL File

// STEP 1: Setup the global JAX-RPC service factory
System.setProperty( "javax.xml.rpc.ServiceFactory",
  "Weblogic.Webservice.core.rpc.ServiceFactoryImpl");

// STEP 2: create service factory
ServiceFactory factory = ServiceFactory.newInstance();

// STEP 3: define qnames
String targetNamespace = "http://localhost:7001/...";
QName serviceName = new QName(targetNamespace, "TaxService");

QName portName = new QName(targetNamespace, "TaxServicePort");

QName operationName = new QName(targetNamespace,
                                "calculateTax");

// STEP 4: create service
Service service = factory.createService(serviceName);

// STEP 5: create call
Call call = service.createCall();

// Build args or custom types, if any

// STEP 6: set port and operation name
call.setPortTypeName( portName );
call.setOperationName( operationName );

// STEP 7: add parameters
call.addParameter( "category", new QName(  "http://www.w3.org/2001/XMLSchema",
                  "string" ), ParameterMode.IN );
call.addParameter( "zip", new QName(  "http://www.w3.org/2001/XMLSchema",
                  "string" ), ParameterMode.IN );
call.setReturnType( new QName("http://www.w3.org/2001/XMLSchema", "string"),
                    String );

// STEP 8: set end point address
call.setTargetEndpointAddress("http://localhost:7501/taxws/TaxService" );

// STEP 9: call service
result = call.invoke( new Object[] {"4A", "80302"} ) ;

A caveat to keep in mind is that a dynamic client is not completely dynamic because, as you may have noticed, the client still needs to presume or hard-code the Web service method’s signature (order and type of arguments and return type). It does allow you to switch Web services at execution time, but for such Web services to be interchangeable, they must all have the same signatures. A more realistic scenario occurs when a Web service is being enhanced (like new methods being added) or versioned. An existing client accustomed to using the version 1 service can just point to a different URL to get the new improved version 2 service (assuming backward compatibility).

InOut Parameters

JAX-RPC also defines a mechanism for supporting output arguments in Web service methods, that is, passing result information back to the client via the argument list. This is a convenient feature, allowing you to define a Web service method that returns multiple values without needing to define and use a complex type. WSDL 1.1 adds support for out and inout arguments via the following rules:

  • If a part name appears in only the output message, it is an out parameter.

  • If a part name appears in both the input and output message, with the same type, it is an inout parameter.

The javax.xml.rpc.holders.Holder interface class was created solely for affecting out or inout arguments. JAX-RPC defines a holder implementation class for each of its supported data types, which are as follows. (This list is not exhaustive; refer to the JAX-RPC specifications for the complete list.)

  • BigDecimalHolder, BigIntegerHolder

  • BooleanHolder, BooleanWrapperHolder

  • ByteArrayHolder

  • StringHolder

  • ByteHolder, ByteWrapperHolder

  • IntegerHolder, IntegerWrapperHolder

  • FloatHolder, FloatWrapperHolder

Note the pattern for primitives and their corresponding wrapper classes: xxxHolder represents the primitive type xxx, and xxxWrapperHolder represents its wrapper class. For instance, the IntegerHolder class represents the primitive type int, and the IntegerWrapperHolder class represents the Integer class. Table 29.3 lists the Holder classes supported by WebLogic Server 7.0.

Table 29.3. List of Holder Classes Provided by WebLogic Server 7.0

Built-in Holder Class

Type That It Holds

Javax.xml.rpc.holders.BooleanHolder

boolean

Javax.xml.rpc.holders.ByteHolder

byte

Javax.xml.rpc.holders.ShortHolder

short

Javax.xml.rpc.holders.IntHolder

int

Javax.xml.rpc.holders.LongHolder

long

Javax.xml.rpc.holders.FloatHolder

float

Javax.xml.rpc.holders.DoubleHolder

double

Javax.xml.rpc.holders.BigDecimalHolder

java.math.BigDecimal

Javax.xml.rpc.holders.BigIntegerHolder

java.math.BigInteger

Javax.xml.rpc.holders.ByteArrayHolder

byte[]

Javax.xml.rpc.holders.CalendarHolder

java.util.Calendar

Javax.xml.rpc.holders.QnameHolder

javax.xml.namespace.QName

Javax.xml.rpc.holders.StringHolder

java.lang.String

In other words, a client wishing to invoke a Web service method that has output arguments must pass the appropriate Holder class for each output parameter in its signature. For example, say you have a StockTrader Web service with a buy method that takes three arguments:

Buy (in ticker, inout numOfShares, out sharePrice)

where

  • ticker is an input parameter representing the stock to purchase.

  • numOfShares is an input parameter indicating the number of shares to purchase, but on return it will be set to the actual number of shares bought; therefore, it is an inout parameter.

  • sharePrice is undefined during invocation but on return will be set to the actual price of each share purchased; therefore, it is an out parameter.

Listing 29.5 shows the client code for invoking this method (using static proxies).

Example 29.5. Client Code for Invoking the buy Method

import javax.xml.rpc.holders.*;

public class Main{
  public static void main( String[] args ) throws Exception {

    // Get the Web service
    StockTrader_Impl trader = new StockTrader_Impl(WSDLuri);
    StockTraderPort traderPort = trader.getStockTraderPort();

    // Define the Holder objects for inout and out parameters
    IntHolder numShares = new IntHolder(100);
    FloatHolder sharePrice = new FloatHolder();

    // Invoke the Web service
    traderPort.buy( "BEAS", numShares, sharePrice );

    // Print out values of inout & out parameters
    System.out.println( "I ordered to buy 100 shares of BEAS " +
          "and actually got " + numShares.value + " shares at " +
          sharePrice.value " dollars per share.");
  }
}

Each Holder class must have a constructor that takes an initial value argument of the type that the Holder class represents. It also must have a public field named value, again of the type that the Holder class represents.

WebLogic Platform 7.0 ships Holder implementation classes for the standard set of supported built-in Java types. The WebLogic Web service tool serviceGen also automatically generates Holder classes for your user-defined types, whether or not you use output parameters. In the latter case, the classes are extraneous and do not affect your Web service in any way.

Summary

You have just completed a whirlwind tour of Web services technologies and how they are implemented in WebLogic Platform 7.0. This chapter covered the types of Web services (RPC and asynchronous) and the different modes of client interaction (static, dynamic, inout parameters). We hope that this knowledge will aid you in the design of your local Web services and clients, or in selecting the most appropriate Web service to purchase and use. You should now understand the need to standardize Web service deployment and execution models to protect your investments, and welcome initiatives such as JAX-RPC and JSR 109 [1], which BEA is proactively involved in and totally committed to. (“Implementing Enterprise Web Services,” which complements and extends JAX-RPC [JSR 101], purports to define standards for leveraging J2EE technology in implementing Web services. See http://www.jcp.org for more information.)

Chapter 30 will show you how to make these Web service features work for you. You have seen the forest; now you’re ready to look at the trees.



[1] “Implementing Enterprise Web Services,” which complements and extends JAX-RPC (JSR 101), purports to define standards for leveraging J2EE technology in implementing Web services. See http://www.jcp.org for more information.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset