You are on page 1of 9

Chapter 11: Web Services

Chapter 10. Web Services


Table of Contents
• Web Applications1
• Introduction to Web Services2
• Simple Object Access Protocol (SOAP)3
• Java API for XML Web Services (JAX-WS)4
• Building a Web Service using JAX-WS5
• Universal Description, Discovery and Integration (UDDI)6

Web Applications
At this point in the course, students should be familiar with the concept of web applications. Most should,
at this point, have written their own web application, integrating client, application and data storage tiers to
provide a variety of functionality.
However, there are two types of web applications:
• Presenation-oriented: A presentation-oriented web application generates interactive web pages
containing various types of markup language (HTML, XML etc.) and dynamic content in response
to requests. This is the form of web application we are familiar with and we have covered practical
implementations of such applications through the vast majority of this module.
• Service-oriented: A service-oriented web application implements the endpoint of a web service.
Presentation-oriented applications are often clients of service-oriented web applications. It is this form
of web application we are concerned with in this chapter.

Introduction to Web Services


Web Services, in the general meaning of the term, are services offered via the Web. In a typical Web
services scenario, a business application sends a request to a service at a given URL using the SOAP
protocol over HTTP. The service receives the request, processes it, and returns a response. As an example of
this consider a stock quote servie, in which the request asks for the current price of a specified stock, and the
response gives the stock price. This is one of the simplest forms of a Web service in that the request is filled
almost immediately, with the request and response being parts of the same method call.
Another example could be a service that maps out an efficient route for the delivery of goods. In this case, a
business sends a request containing the delivery destinations, which the service processes to determine the
most cost-effective delivery route. The time it takes to return the response depends on the complexity of the
routing, so the response will probably be sent as an operation that is seperate from the request.
Another definition of what a Web service is provided by IBM:
"A Web service is an interface that describes a collection of operations that are network accessible
through standardized XML messaging. Web services fulfill a specific task or set of tasks. A Web
service is described using a standard, formal XML notion calls it service description, that provides
all of the details necessary to interact with the service, including message formats (that detail the
operations), transport protocols and location. The nature of the interface hides the implementation
details of the service so that it can be used independently of the hardware or software platform on
which it is implemented and independently of the programming language in which it is written. This
allows and encourages Web services based applications to be loosely coupled, component-oriented,

Chapter 11: Web Services 1


ID: 740-EE | Version: 10 | Date: 4/28/10 3:13:34 PM
cross-technology implementations. Web services can be used alone or in conjunction with other Web
services to carry out a complex aggregation or a business transaction"
One key driver behind the rise of Web services is the continuing evolution of Business-to-Business
Computing (B2B). B2B computing is about integrating the business systems of two or more companies
to support cross-enterprise business processes. Online HTML-based applications are consumer-oriented
(B2C) To access most online functionality, a human being needs to use a Web browser to navigate the
company's site through multiple page transitions, input information using Web forms, submit them, and get
results back in human-readable form. This is entirely unsuitable for Business-to-Business (B2B) services,
since automating and simulating this human use is both non-ideal and error prone. The only true way to
integrate applications on the Web is to use a B2B-focused solution. Web services and consumers of Web
services are typically businesses, making Web services predominantly suitable for business-to-business
(B2B) transactions. B2B applications have no UI because their clients are other applications.
Web services depend on the ability of parties to communicate with each other even if they are using different
information systems. XML is a markup language that makes data portable and is a key technology in
addressing this need. Enterprises have discovered the benefits of using XML for the integration of data both
internally (for sharing data among departments) and externally (for sharing data with other enterprises).
Because of this data integration ability, XML has become the underpinning for Web-related computing.
Chapter 3 of this course covered XML in considerable detail, and this section assumes that you are familiar
with the concepts therein.
Figure 11.0 - Web Services Architecture (ref. Wikipedia)

The diagram above shows a generic architecture for Web Services. The core element of this relates to the
communication between the service requester and the service provider. This communication is handled via
the Simple Object Access Protocol (SOAP).

Chapter 11: Web Services 2


ID: 740-EE | Version: 10 | Date: 4/28/10 3:13:34 PM
Simple Object Access Protocol (SOAP)
SOAP is a simple protocol, based on the idea that at some point in a distributed architecture, you will need to
exchange information. Additionally, in a system that is probably overtaxed and process-heavy, this protocol
is lightweight, requiring a minimal amount of overhead. Finally, it allows all this to occur over HTTP, which
allows you to get around tricky issues such as firewalls and keep away from having all sorts of sockets
listening on oddly numbered ports.
SOAP relies on HTTP as a transport mechanism to send XML based messages. The messages are packed
in what is called a SOAP envelop and sent to the server to process in a Request/Response fashion. SOAP
unlike other protocols such as DCOM or RMI does not require strong connection between client and the
server. SOAP messages are string based messages passed from the client to the server and vice versa in the
form of SOAP envelopers. Unlike other protocols, which require that the applications of the same type are
running on both ends, SOAP allows access to services in an alternate language/platform. SOAP enables
"incompatible" systems to interoperate.
Figure 11.1. The SOAP Message Process

Some of the features of SOAP worth noting are:


• Uses standard internet HTTP
• Uses XML to send and receive messages
• Platform Independent
• Language Independent
• A protocol for exchanging information in a decentralized and distributed environment.
A SOAP message is based on XML and contains an Envelop, a Header and a Body.
• Envelope - The envelope represents the Message. It is used for describing the message and how to
process it.
• Header - The Header contains the features of the SOAP message
• Body - The Body contains mandatory information for the message receiver
Figure 11.2. SOAP Message

Chapter 11: Web Services 3


ID: 740-EE | Version: 10 | Date: 4/28/10 3:13:34 PM
The SOAP envelope is analogous to the envelope of an actual letter. It supplies information about the
message that is being encoded in a SOAP payload, including data relating to the recipient and sender, as well
as details about the message itself.
Example SOAP message for getting a Stock Quote:

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/1999/XMLSchema" >
<SOAP-ENV:Body>
<ns1:GetStockQuote xmlns:ns1="urn:xmethods-quotes">

<SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<symbol xsi:type="xsd:string">IBM</symbol>
</ns1:GetStockQuote>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>

The SOAP server, using the support of complex XML parsers, decodes the call and figures that you want to
get a stock quote. It then quickly fetches the stock quote and sends you back a packet like so:

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
<SOAP-ENV:Body>
<m:GetStockQuoteResponse xmlns:m="urn:xmethods-quotes">
<Price>34.5</Price>
</m:GetStockQuoteResponse>
</SOAP-ENV:Body>

</SOAP-ENV:Envelope>

This, after removing all the envelopes, simply tells you that the price of the IBM stock was 34.5. Most
commercial servers would return a LOT more information than just this, such as what currency, last traded
price etc. However, the example is displayed to show the basic structure of SOAP messages.

Chapter 11: Web Services 4


ID: 740-EE | Version: 10 | Date: 4/28/10 3:13:34 PM
While we now know, what form the messages take, we still need to know how to send and receive them. As
stated, we use HTTP for this purpose. We have already described HTTP earlier in this course. Essentially,
we would make a HTTP request such as:

POST /StockQuote HTTP/1.1


Host: www.stockquoteserver.com
Content-Type: text/xml; charset="utf-8"
Content-Length: nnnn
SOAPAction: "Some-URI"

...the soap request packet here...

The SOAPAction header indicates the 'intent' of a request, and it is mandatory. Each SOAP server could
have multiple functions, and it could decide to use the SoapAction header to figure out which function is
being called. Also, firewalls etc. can filter content using this header. The SOAP response from the HTTP
server will be as follows:

HTTP/1.1 200 OK
Content-Type: text/xml; charset="utf-8"
Content-Length: nnnn

...Soap Response packet here...

Java API for XML Web Services (JAX-WS)


JAX-WS (Java API for XML Web Services) is a Java API for building Web services and clients that
communicate using XML. It is part of the Java EE platform from Sun Microsystems and is implemented as
part of project Glassfish, an open source Java EE application server from Sun. Previous to JAX-WS was
JAX-RPC (Java API for XML-based RPC) but the naming (and some functionality) was changed in Java
Platform Enterprise Edition 5.
The JAX-WS enables Java technology developers to develop SOAP based interoperable and portable
web services. SOAP, as we have seen, defines the envelope structure, encoding rules and conventions for
representing web service invocations and responses. These calls and responses are transmitted as SOAP
messages over HTTP.
Despite the fact that these SOAP messages can be complex, the JAX-WS hides this complexity away from
the application developer. On the server side the developer specifies the web service operations by defining
methods in an interface written in the Java programming language. The developer also codes one or more
classes that implement these methods.

Building a Web Service using JAX-WS


To attempt to explain web services and JAX-WS in more detail, we will attempt to deploy our own web
service! Naturally, we will try to keep things simple by creating a relatively simple web service which does
some mathematical calculations and the corresponding client. To achieve this, we are going to use some
tools:
• Eclipse - is our development environment of choice for this module, and we will continue to use it here
• JEE - which we should have installed previously. JEE provides the JAX-WS API required for the
development of our web service.
• Glassfish Service Adaptor - Glassfish is an application server project by Sun Microsystems for the
Java EE platform. This application server is known as the Sun Java System Application Server
(SJSAS) and is a Java EE 5 certified application server. Since we already have Java EE installed
on our systems, it is appropriate that we use this application server for deployment of our web
service. We have already used the application server in previous sections, such as the Java Message

Chapter 11: Web Services 5


ID: 740-EE | Version: 10 | Date: 4/28/10 3:13:34 PM
System Chapter. The service adaptor allows us to deploy directly from Eclipse straight into the Sun
Application server (somewhat like we do with Tomcat using the Sysdeo plugin)

Setup
1. After starting Eclipse, select the Java EE perspective: Windows -> Open Perspective -> Others ->
Java EE
2. In the servers tab at the bottom of the page, right click in the window and select New -> Server
3. To download the Glasfish Server Adaptor, select Download additional server adaptors. Accept the
license and let Eclipse restart
4. After Eclipse has retstarted, you can create a new GlassFish V2 Java EE5 server
5. In the creation dialog select Installed Runtimes and select the directory where your Java EE has been
installed
6. We can then right click on the server instance to start up our Sun Application Server. Note: Ensure that
Tomcat had previous been shut down, as the Sun Application server and Tomcat server default ports are
both 8080.
Note: These five steps are a once off step. The setup stage can be skipped for future deployments.

Creating our Web Service Endpoint


1. Create a new dynamic web project. Give it a name (eg. calculator) and select as target runtime
'Glassfish'
2. In the src directory create a new package called 'sample' and then create a new Java class
'Calculator.java'
3. Deploy the service by selecting the project and select Run As -> Run on Server
4. Check in the server Window that the calculator project has a status of Synchronized. If it does not,
right-click in the server window and select publish.
5. You can also look for the web service in the Application Server Admin page by visiting http://
localhost:4848
Source: Calculator.java7

package sample;

import javax.jws.WebService;

@WebService
public class Calculator {
public int sum(int param1, int param2){
return param1 + param2;
}
public int multiply(int param1, int param2) {
return param1 * param2;
}
}

You have now written and deployed a web service! However, before you shut down your computer and
settle into happy dreams for the night, you're going to need to deploy a client. A web service doesn't provide
any functionality without clients.

Creating the Web Service Client


At this point, we know a few things about web services.
1. We know that we can have a variety of different client types: applications, servlets, JSPs, EJBs and so
on

7. http://wiki.eeng.dcu.ie:8888/ee557/g3/743-EE.html (Calculator.java)

Chapter 11: Web Services 6


ID: 740-EE | Version: 10 | Date: 4/28/10 3:13:34 PM
2. We know that in order to get these clients to talk to the web service we need to construct and
deconstruct SOAP messages containing XML, which in turn we need to parse.
3. We know that in order to manually handle 2) we would need to implement vast quantites of code
to handle the XML parsing, construction as well as the protocols for sending and receiving SOAP
messages
This is where the wsimport command for JAX-WS applications steps in. The wsimport command-line
tool processes an existing Web Services Description Language (WSDL) file and generates the required
portable support classes for developing JAX-WS web service applications. Essentially, it is going to
automatically generate all of the class files involved with the SOAP, XML and communication aspects of our
web service!
The WSDL is a document written in XML, describing the following:
• What a service does - the methods that the service provides
• How a service is accessed - details of the data formats and protocols necessary to access a service
operations
• Where a service is located - details of the protocol specific network address, such as a URL
There are plenty of examples of WSDL documents available on the web if you are interested in looking at
some. Here is a WSDL file8 which I previously used in this module to describe a fax web service providing
fax resources to clients. However, for our purposes, we are going to automatically generate a WSDL file
using the ?wsdl option in our wsimport statement. It is possible to generate clients and servers without
manually writing a WSDL file (most of the time). The option ?wsdl generates a dynamic WSDL file the first
time it is called and caches it in the server for further use.
So now, we have wsimport command generating not only our support classes for the client, but also
instructing the server to automatically generate (where possible) the WSDL file dynamically.
So let's get back to creating our web service client:
1. Create a New Project for the calculator client (an ordinary Java project)
2. Select Add Glassfish v2 as Server Runtime in the Build Path. Right click project -> BuildPath -> Add
Library -> ServerRuntime -> Glassfish v2
3. Open a command window and go to the source directory of your project in Eclipse. In my case it looks
like: D:\Java\Workspace\calculatorclient\src
4. In this directory execute: wsimport -keep http://localhost:8080/calculator/CalculatorService?wsdl
5. Now we can create the CalculatorClient application in Eclipse (you can also refresh in the project view
to see all of your generated files)
6. Execute the CalculatorClient from the command line using 'java CalculatorClient 34 23' - View the
results.
7. You have now written and deployed both a web service and client!
Source: CalculatorClient.java9

package sample;

public class CalculatorClient {

/**
* @param args
*/
public static void main(String[] args) {

if (args.length != 2)
{
System.out.println("Usage - CalculatorClient num1 num2");

8. http://wiki.eeng.dcu.ie:8888/ee557/g3/746-EE.html (interfax.wsdl)
9. http://wiki.eeng.dcu.ie:8888/ee557/g3/744-EE.html (CalculatorClient.java)

Chapter 11: Web Services 7


ID: 740-EE | Version: 10 | Date: 4/28/10 3:13:34 PM
System.exit(1);
}
//Create Service
CalculatorService service = new CalculatorService();

//create proxy
Calculator proxy = service.getCalculatorPort();

int a = new Integer(args[0]).intValue();


int b = new Integer(args[1]).intValue();

//invoke
System.out.println("Sum of the arguments = " + proxy.sum(a,b));
System.out.println("Multiple of the arguments = " + proxy.multiply(a,b));
}
}

Figure 11.3 CalculatorClient expected output

Deploying the Web Service - Video Tutorial


The following video describes the above steps in full detail, demonstrating each of the components involved.

Demonstrating Web Services Using JAXWS Video

Part "Multimedia data"


Mime-type: application/x-shockwave-flash, size: 35852024 bytes

Fields
Name Value
Height 480
Width 640
Start Flash false
Loop false
Start video false
Start audio false

Chapter 11: Web Services 8


ID: 740-EE | Version: 10 | Date: 4/28/10 3:13:34 PM
UDDI - Universal Description, Discovery and Integration
UDDI is an XML-based standard for describing, publishing and finding Web services. It is an online
directory that gives businesses and organisations a standard approach to describing their services, to discover
other company services and to understanding the methods required to conduct business with a specific
company. This is achieved via WSDL (Web Service Description Language) which is used to describe the
interfaces of the web services.
Before UDDI, there was no Internet standard for business to reach their customers and partners with
information about their products and services. Nor was there a reasonable approach to discovering methods
of how to integrate with each other's services and processes.
So how can we use it? Let us consider for an example, that we create a web service for checking flights
across multiple airlines and making reservations with these companies. We register our service into the
UDDI directory, providing the WSDL data describing our available services and how they are used. Travel
agencies could then search the UDDI directory to find out how to use our interface. Once the interface is
found, the travel agency can now communicate with our service because we have provided it a well-defined
reservation interface.
Equally, in the process, it should be noted that we are quite likely using the web service interfaces of a
number of airlines in order to provide this compiled data to the travel agencies directly.
As has been said in a number of sections throughout the module, web services are a huge topic of study for
which we could write much more content. However, for the purposes of this module, this is all the content
we will cover.

Navigation
Next: Chapter 11: Introduction to Ajax10
Previous: Chapter 9: Messaging with Java11

10. http://wiki.eeng.dcu.ie:8888/ee557/g2/551-EE.html (Chapter 11: Introduction to Ajax)


11. http://wiki.eeng.dcu.ie:8888/ee557/g2/664-EE.html (Chapter 9: Messaging with Java)

Chapter 11: Web Services 9


ID: 740-EE | Version: 10 | Date: 4/28/10 3:13:34 PM

You might also like