Today, Dwight takes us on a tour of the web services made available to us via ASP.NET. We learn how to create a web service, about Service-Oriented Architecture, and SOAP. This piece comes from chapter seven of .NET & J2EE Interoperability, by Dwight Peltzer (McGraw-Hill/Osborne, ISBN 0-07-223-054-1, 2004).
Building an enterprise-distributed web application is becoming increasingly complex. Ever-pressing consumer and business demands necessitate discovering new, more efficient ways of developing improved methods for presenting information through browser-based web applications and personal hand-held devices, and for incorporating legacy systems.
Methodologies employed in the past for building applications for the Internet are no longer sufficient for staying competitive. Application aggregation and interoperability is now the norm. Web services have changed business processes forever. There is no doubt that urgent consumer and business demands stretch a company's ability to design, create, and deploy web service-oriented applications.
Fortunately, an increasing number of software vendors are assembling systems by defining innovative new business logic that modifies and leverages preexisting repositories of data. It is less common today to construct new applications from the ground up.
The new business model emerging can be thought of as component-based applications supporting reusable component functionality. IBM's WebSphere and Microsoft .NET are representative of component-assembled business solutions. A component-based system must support scalability, flexibility, and security. With the plethora of component collections available, what are the criteria for selecting and differentiating between these components?
Components must contain no interdependencies with other components.
A component's functionality must support the object-oriented concept of tight cohesion.
A collection of component-based functionalities must be assembled into a cohesive whole, thereby facilitating coarse-grained operations on services that encompass more functionality and operate on larger sets of data.
The integrated components must be designed for distribution across many machines in order to enhance performance and reliability.
A component exposes one or more services so they can be consumed by other services or clients.
Once the system is built, the component-based infrastructure must describe and expose its services to clients so they can obtain the requisite information necessary for consuming those identifiable web services.
Remember: This is part one of chapter 7 .NET & J2EE Interoperability, by Dwight Peltzer (McGraw-Hill/Osborne, ISBN 0-07-223054-1, 2004). If you like what you see, feel free to click on the following link to get your own copy! Buy this book now.
I'll start by defining a web service by describing what a service is not. For example, a web service is not a subscription service but rather represents some kind of business logic processing on a web server. The key word to understanding "process" is "functionality." It defines what process is. "Web," of course, indicates some kind of event that exposes functionality and occurs on a server residing somewhere on the Internet in response to a client's request. The event requires an event handler (a server-side process that manages client requests by forwarding those requests to the appropriate server where a specified web server exposes its services to interested parties). The event (a web service) is invoked at the behest of a client or some application-based invocation.
For example, International Foreign Currency Exchange (IFCE) submits requests to a service provider such as Reuters for the most recent stock quote. Reuters, herein now defined as a service provider, resides somewhere on the Web on a wide area network (WAN). Because service providers offer many kinds of services, they must reside on a network so they can expose their services to clients on a large scale. The term "service" obfuscates the true meaning of a web service because it contains several different meanings, depending on context.
Viewing a web service from a developer's perspective is one point of view and differs from a user's point of view, or that of a service provider. For example, in J2EE, the name "component" replaces the term service, whereas in Microsoft .NET, web services use "service."
Web services are accessed by calling a listener (a service provider) capable of providing a contract that describes the particular web service a client seeks. The contract specifies both parameters and data types that the listener anticipates receiving, as well as the return type (if any) it sends back to the client. In addition, the listener facilitates incoming requests, and returns responses to clients. Figure 1 is a visual representation of a service provider's functionality.
Figure 1A service provider's functionality
Remember: This is part one of chapter 7 .NET & J2EE Interoperability, by Dwight Peltzer (McGraw-Hill/Osborne, ISBN 0-07-223054-1, 2004). If you like what you see, feel free to click on the following link to get your own copy! Buy this book now.
Microsoft designates ASP.NET as the technology for building web services. Both business logic and presentation layer are bundled together within ASP.NET. The developer begins the web service process by applying attributes that inform the Common Language Runtime (CLR) back to treat a defined class and its methods as a web service. (Refer to Chapter 5 for a complete discussion about the CLR and its functionality.) Web service business logic is stored in an .asmx file. The code can dwell either within the .asmx file or in a precompiled class. The developer applies the following directive to the file containing the class name and namespace in which the class for the web service resides. It looks like this:
<%@ WebService Language = "VB" Class ="IFCE" %>
Then, the developer declares a method that includes the number of parameters and its data types, as shown here:
<WEBMETHOD()><WebMethod()>Public Function ConvertCurrency (ByVal x As Double, ByVal y as Double) As Double //write the code to implement the method End Function
The code is compiled to Microsoft Intermediate Language (MSIL) and to its own specific assembly. Typically, the assembly should be placed in a bin file so others can reference it. Creating a web service class looks like this:
Imports System
.Web.Services Public Class IFCE Inherits WebService 'declare the methods here exposed by the Web Service End Class
XML-based web services use the namespace mechanism for defining an end point for the web service, the namespace to whom a client forwards requests. Here is the syntax:
<WebService (Namespace="http://www.IFCE.com/Webservices/") _ Public Class IFCE: WebService {}
ASP.NET uses reflection inspect metadata attributes. Attributes facilitate applying WebMethod attribute to declare methods as previously demonstrated. By examining this process, it is clear that the client requests a server-side provider to expose its services. The provider is mandated to issue the client a contract (aWSDL file) that lists the services it exposes. This information informs the client how to communicate with the service provider and utilize its services.
Therefore, it is possible to add to our definition of a web service by describing it as a discrete piece of business logic written in Java, managed C++ .NET, C# .NET, or some other programming language. Depending on the language, a function or method is typically decorated with a web method attribute, thereby designating it as eligible to initiate a call to a web service provider. This process informs the CLR that this call is to be treated as a valid web service invocation.
Remember: This is part one of chapter 7 .NET & J2EE Interoperability, by Dwight Peltzer (McGraw-Hill/Osborne, ISBN 0-07-223054-1, 2004). If you like what you see, feel free to click on the following link to get your own copy! Buy this book now.
What is a service-oriented architecture? Web services reside somewhere on the Internet in a registry. Registries contain numerous web services, and each individual service exposes its own services to requestors (clients). The services represent publishable and discoverable interfaces.
Let's digress for a moment to define an interface (more about interfaces later in the chapter). An interface is an abstract class containing a function or method declaration, which includes a list of parameters, for example:
int max
( int, int);
Every operation declared by an object specifies the following items:
The operation's name
The objects it accepts as parameters
The operation's return values
This is known as the operation's signature. By assembling the set of all signatures, we can define them as an interface. However, an interface does not provide an implementation, but only provides the abstract class's method name and a set of signatures.
Perhaps the most important functionality a web service provides is supporting a well-defined business process. Here is a quote describing the benefits SOA offers:
Service-Oriented Solutions...Applications are constructed as groups of interacting services providing well-defined interfaces to users. (Java Web Services, O'Reilly & Associates, 2002.)
SOA is implemented as a discoverable software entity that exists as a single instance. The instance interacts with web applications and represents a loosely coupled message-based communication model. Conceptually, each individual web service has two parts:
Service This represents the implementation for a web service. The basic requirement is that it must be accessible on a network by a service provider.
Service description Typically, this exists as an XML file containing a complete description of data types, communication protocols, and a URI where the web service implementation resides. This file is called Web Services Description Language (WSDL).
The terminology used to describe SOA elements in web services is specific, as demonstrated in the following.
Service provider A software entity implements the service specification. Any chunk of logic is exposed as a web service residing within the SOA. It could be either a complete mainframe-based business process, such as processing a request to convert a specified currency quote to another type of currency quote, such as the euro equivalent of 100 American dollars, or servicing a mortgage loan request. Providers publish metadata about services they keep in a registry. Typically, these providers are standards-setting organizations like ebXML, W3C.org, WS-1, software vendors, and developers. Several different mechanisms are used to publish service descriptions. Among them:
HTTP Get request The public repository http://www.xmethods.com is where developers can test their own web services.
Dynamic discovery Perhaps the most used registry is Universal Description, Discovery, and Integration (UDDI).
Direct A service requestor retrieves the service description from the service provider directly via email, FTP, or other such direct methods.
Service requestor This entity calls a service provider.
Service locator This serves as a registry manager and allows a client to locate registries, service provider interfaces, and service locations.
Services broker This service provider maintains a list of registries and passes on client requests to other service providers.
Remember: This is part one of chapter 7 .NET & J2EE Interoperability, by Dwight Peltzer (McGraw-Hill/Osborne, ISBN 0-07-223054-1, 2004). If you like what you see, feel free to click on the following link to get your own copy! Buy this book now.
The following items constitute the building blocks for constructing service-oriented architecture web services:
Encoding XML-ized data transmitted between client and server requires encoding. Typically, the decoding is UTF-8. In J2EE it is ISO-8859-1.
Description Web services represent an end point. Once the point is located, the service provider describes metadata about the service and requirements needed by the client in order to leverage its services.
DISCO This is a proprietary Microsoft method for discovery. In order to use DISCO, a URL is required before the document can be located. Use the Disco.exe command-line utility to generate theWSDL contract. Syntax for this is as follows:
Disco
[options] URL
In contrast, UDDI does not require the URL to locate a web service or registry. A registry normally provides a tool for searching by name, location, URL, keyword, and other search criteria. It is possible to search for the keyword wsdl. These URLs will always point toward WSDL contracts available for web services.
Messaging format Both client and business partner must agree on a mutual protocol before they can encode, format, and transmit messages to each other via HTTP and SOAP.
Fortunately, Microsoft and Sun Microsystems are assisting developers by releasing software solutions that enable a company to face numerous Internet business challenges.
SOA Best Practices
Service providers not only set forth a description of services but also impose constraints dependent on context. The following list presents some of the primary characteristics for efficient utilization of these services:
Interface design SOA services implement defined interfaces. This is important because multiple web services can implement a commonly shared interface. Conversely, a single service can implement numerous interfaces.
Asynchronous calls Generally speaking, best practices suggest message passing via asynchronous remote calls. This is important because asynchronous calls allow developers to continue working with other development tasks while awaiting a return result from the server. Synchronous calls are less desirable because all other tasks are blocked until the request fulfillment is completed.
Coarse-grained services Object-oriented technologies such as Java expose their services through individual methods. Using an individual method, however, is too fine an operation for processing large quantities of data. It is better to assemble individual methods into a cohesive coarse-grained service and process large amounts of data.
Remote Procedure Calls Web services enable clients to invoke procedures, methods, and functions on remote objects employing an XML-based protocol. RPCs expose both input and output parameters.
Remember: This is part one of chapter 7 .NET & J2EE Interoperability, by Dwight Peltzer (McGraw-Hill/Osborne, ISBN 0-07-223054-1, 2004). If you like what you see, feel free to click on the following link to get your own copy! Buy this book now.
The preceding discussion has focused on describing a web service process. It is useful now to explain how the client accesses services by employing the core web technologies-namely, Simple Object Access Protocol (SOAP), HTTP,Web Services Description Language (WSDL), and Universal Description, Discovery, and Integration (UDDI)-to locate the service/services the client specifies. Developers can browse numerous web service repositories (registries) and select appropriate services for implementing their own applications. Figure 2 demonstrates how a registry serves as host to a collection of web services.
Simple Object Access Protocol
SOAP provides a standard structure for transmitting XML documents over the wire, which includes SMTP, HTTP, and FTP. SOAP also defines encoding and binding standards for encoding non-XML Remote Procedure Calls. SOAP enhances interoperability between client and server. Clients with .NET can call EJBs through SOAP and vice versa.
NOTEOther protocols have been developed, for example, Sun's RPC, Microsoft's DCE, Java's RMI, and CORBA's ORBC.
Figure 2 A web service registry
Why are so many corporations embracing SOAP? It has industry-wide support and is not bound to one programming language. Interestingly, SOAP does not use a specified set of APIs, but rather leaves the implementation up to the programming language (such as Java) and the platform (such as Microsoft .NET). The SOAP specification does not describe how SOAP messages should be bound to HTTP.SOAP is an XML document. Listing 1 is representative of a typical SOAP request and response XML file.
NOTE In a production environment, change the XML namespace to your own namespace as demonstrated here:
<int xmlns="http://www.dp.org/results/>
Remember: This is part one of chapter 7 .NET & J2EE Interoperability, by Dwight Peltzer (McGraw-Hill/Osborne, ISBN 0-07-223054-1, 2004). If you like what you see, feel free to click on the following link to get your own copy! Buy this book now.
Let's step through Listing 1. The header indicates this is an HTTP POST request, followed by the name of the method, MathWebService. The .asmx extension is used for files that implement XML web services.Web services can be accessed directly through .asmx files, or this file can redirect the request to a compiled assembly implementing the web service. The root element of the SelectMaxValue document is the Envelope element. The listing has two sub-elements, the body and header elements.
The next item of interest is the attribute bearing the name of the host machine. The Content-type specifies the file as text/xml, and the encoding is utf-8. The SOAPAction attribute identifies the URI namespace where the method is located and lists the web service name. The XML declaration indicates the SOAP message is XML-based. Next, all SOAP messages have an envelope, where the message body is embedded. Both client and recipient must strip the content from the envelope for further processing. Notice the default xmlns namespace declarations. These must precede the SOAP body. Finally, the method is processed where the web service determines whether int value x is greater or smaller than y. The response is virtually self-explanatory. Beginning with the traditional SOAP header, the SOAP body result syntax is similar to the request, with the exception that the Method syntax indicates it is a response and returns a result.Before the discussion focuses on other SOAP attributes, here are the key elements discussed so far:
The SOAP envelope This encodes header information about the message and body of the message.
SOAP encoding This allows for a standardized method of serializing data into the body of a SOAP message.
RPC-style messages This entails the type of protocol a developer can employ to facilitate procedure-oriented communications via a request-response message.
HTTP binding This is the industry-wide method of binding SOAP messages to the HTTP messaging protocol.
Remember: This is part one of chapter 7 .NET & J2EE Interoperability, by Dwight Peltzer (McGraw-Hill/Osborne, ISBN 0-07-223054-1, 2004). If you like what you see, feel free to click on the following link to get your own copy! Buy this book now.
A SOAP message defines a SOAP actor, which is divided in two parts:
A default actor is the intended final recipient of a SOAP message.
An intermediary actor can act on the content of a SOAP message by modifying the content in some way.
The intermediary actor may manipulate the message content in an unspecified way before forwarding the message to its final destination. Although the message is altered, it is still considered the same message as the one originally sent. An optional header element will transmit data that might not be appropriate to encode in the envelope body. For example, if a default actor receives an encoded, compressed message, it would need to know what type of algorithm is used to compress the code before it could decode the message. Other types of optional headers include the all-important authentication method, routing information, transactions, and security information. A default actor may require the sender to provide authentication information before the recipient can process the message. A message may require specific routing to more than one destination. In addition, the recipient may require security information to determine whether a message is modified before arriving at its destination. For example, it is important for a stock quote to remain in its original state before a brokerage firm can sell the stock to clients. The header element can be added to the SOAP envelope as a child element.Listing 2 demonstrates this.
Listing 2Defining a child node within the SOAP envelope
Use the mustUnderstand attribute when information embedded within the header should not be ignored. Therefore, mustUnderstand provides a method for differentiating between noncritical information and mission-critical data that requires attention. By specifying a value of 1 in the header's root element, the identified data cannot be ignored. Listing 3 demonstrates how to use this attribute.
This example shows how the recipient must update the specified stock quote within scope of the client's transaction. In the event the transaction is going awry in some way, the application must roll back any changes made to the client's account. The mechanism used for this is the mustUnderstand attribute, and is achieved by setting the attribute to 1.
Remember: This is part one of chapter 7 .NET & J2EE Interoperability, by Dwight Peltzer (McGraw-Hill/Osborne, ISBN 0-07-223054-1, 2004). If you like what you see, feel free to click on the following link to get your own copy! Buy this book now.
The Actor attribute provides a mechanism for annotating SOAP headers. For example, a document can be routed to an intermediary that will create a transaction, specifying the URI for the intermediary for which a portion of the message is intended. If the header is destined for processing by the next recipient of a SOAP message, set both the mustUnderstand attribute and the Actor attribute. Listing 4 demonstrates how to do this.
If the TransactionCoordinator does not know how to interpret this message, it raises an error. The directive does not belong in this message. This is evidenced by lack of a corresponding opening tag. Before the message is passed on, all foreign elements must be removed. However, the intermediary can add header elements before forwarding the message to the next intermediary or final recipient.
The Body Element
All SOAP messages must have exactly one element. The body element contains the payload. There are some constraints on how the body is encoded. The payload can consist of a string of ASCII characters, a byte array, or XML text. However, the contents may not contain any characters that would invalidate the embedded XML document. XML messages can be placed in two categories: document-oriented messages and procedure-oriented messages. For example, a document that provides a stock quote to a client can be encoded within the body of a SOAP message and specify a particular routing for an intended recipient. The procedure-oriented messages offer two-way communications and are frequently referred to as RPC messages.
The Fault Element
SOAP messages fail for a number of reasons. It is important to use the Fault attribute and generate an error message back to a client. SOAP specifies a format for handling errors. Listing 5 demonstrates this.
The Faultcode contains a value to determine the kind of error it encounters. Several fault codes are available for use:
Version Mismatch This specifies an invalid namespace declared for the SOAP envelope.
MustUnderstand A child element residing within the SOAP header contains a mustUnderstand attribute. If the attribute is set to 1, it indicates the attribute was not understood.
Client Content located within the message body was found to be faulty.
Server The server determines that the error lies with the inability to obtain resources or the inability to process the message.
The SOAP features presented here must be adhered to when processing SOAP messages. The next major web services technology, Web Services Description Language (WSDL), describes what a SOAP payload contains.
Remember: This is part one of chapter 7 .NET & J2EE Interoperability, by Dwight Peltzer (McGraw-Hill/Osborne, ISBN 0-07-223054-1, 2004). If you like what you see, feel free to click on the following link to get your own copy! Buy this book now.