+ All Categories
Home > Documents > Introduction to Web Services - Implementing a Java Web Service

Introduction to Web Services - Implementing a Java Web Service

Date post: 05-Jan-2016
Category:
Upload: pepehillo
View: 5 times
Download: 2 times
Share this document with a friend
Description:
Introduction to Web Services - Implementing a Java Web Service
Popular Tags:
16
Copyright 2003, Systinet Corp. Page 1 of 16 Developers Corner Tutorial Your First Web Service In 10 Minutes
Transcript

Copyright 2003, Systinet Corp. Page 1 of 16

Developers Corner Tutorial Your First Web Service In 10 Minutes

> Developers Corner: Your First Web Service in 10 Minutes

Copyright 2003, Systinet Corp. Page 2 of 16

Contents ................................................................................ 2

Introduction........................................................................... 3 About this tutorial 3 Web service - a programmatic definition 3 Installing software 4

Implementing a Simple Web Service ................................... 5

Implementing a Java Web Service Client............................ 9

Implementing a Microsoft .NET Web service client..........12

1.6. SOAP messages at glance ..........................................13 Introduction 13 SOAP message structure 13

Cleanup and Review ...........................................................15 Review of What We Learned 15

Copyright and Disclaimer ...................................................16

Contents

Copyright 2003, Systinet Corp. Page 3 of 16

About this tutorial

You've heard the hype, and your head is probably dizzy from all the acronyms. So just what are Web services, and how can you use them? This series of articles is intended to demystify Web services and show, step-by-step, how to build, deploy, use, and find them.

Basic Web services aren't very difficult to create. To prove this point, we'll show you, in this article, how to construct a Web service in about 10 minutes. In subsequent articles we'll delve deeper into Web services and explain the following topics in detail:

• Advanced topics such as complex type mapping and exception handling

• Securing Web services

• Exposing legacy applications as Web services

• Publishing services in a UDDI registry

In this introduction, we begin with a programmatic definition of Web services, then quickly move on to show a simple Java class that calls and executes a Web service. All of our examples will be in Java. We've created our examples using Systinet WASP Server for Java, 4.5 (details on how to access and download this software is in the Installing software chapter). You don't have to use these products to understand the examples, but we strongly recommend it.

The concepts we introduce and the code we create are generally applicable and relatively independent of the tools used. We assume some knowledge of XML, but none of Web services.

Web service - a programmatic definition

A Web service is a software component with the following features:

• It is accessible through a SOAP (Simple Object Access Protocol) interface. (See http://www.w3c.org/TR/SOAP/ )

• Its interface is described in a WSDL (Web Service Description Language) document. (See http://www.w3c.og/TR/wsdl/ )

SOAP is an extensible XML messaging protocol that forms the foundation for Web Services. SOAP provides a simple and consistent mechanism that allows one application to send an XML message to another application. A SOAP message is a one-way transmission from a SOAP sender to a SOAP receiver, and any application can participate in an exchange as either sender or receiver. SOAP messages may be combined to support many communication behaviors, including request/response, solicit response, one-way asynchronous messaging, or event notification. SOAP is a high-level protocol that defines only the message protocol and a few rules for message processing. It is completely independent of the underlying transport protocol, so SOAP messages can be exchanged over HTTP, JMS, or mail transport protocols. Currently the HTTP protocol is the most frequently used transport for SOAP messages. We'll show some sample SOAP messages later in this article.

WSDL is an XML document that contains a set of definitions that describes a Web service. It provides all the information needed to access and use a Web service. A WSDL document describes what the Web service does, how it communicates, and where it resides. You use the WSDL document at

Introduction

> Developers Corner: Your First Web Service in 10 Minutes

Copyright 2003, Systinet Corp. Page 4 of 16

development-time to create your service interfaces. Some SOAP implementations, including Systinet WASP, also use WSDL at runtime to support dynamic communications.

Installing software

REQUIREMENTS: We assume that you have a Java 1.4 or later SDK and a standard HTTP browser installed on your system and the JAVA_HOME system variable points to the Java root directory.

If you want to follow along with the demo, you'll need to download WASP Server for Java, 4.5 ( http://www.systinet.com/products/wasp_jserver/overview ) from the Systinet Web site. Unpack the downloaded package to a local disk and run the install script from the bin subdirectory of the WASP Server installation. You'll need to agree to the product license and then please answer with default options to all installation questions (simply press Enter multiple times).

IMPORTANT: Please set the WASP_HOME environment variable to point to the WASP Server root directory.

You'll also need to download the tutorial sources (http://dev.systinet.com/get&dl=dHV0b3JpYWxzLnppcA) and unpack it on the local disk.

Copyright 2003, Systinet Corp. Page 5 of 16

We'll perform the following steps to create our simple Web service:

• Create the Web service business logic. First we need to write a Java class that implements the Web service business logic. In this case, our business logic will be a simple Java class that simulates a stock quote service.

• Deploy the Java class to a SOAP server. Next we need to turn the Java class into a Web service. We'll deploy the Java class to the WASP SOAP server using the WASP deployment tool.

• Generate the client access classes. A client application uses a proxy object to access a Web service. At request time, the proxy accepts a Java method call from the application and translates it into a SOAP request message. At response time, the proxy receives the SOAP response message, translates it into Java objects, and returns the results to the client application.

• Client application development. The client application treats the proxy as a standard Java object that transparently performs the communication with the Web service.

NOTE: We're using MS Windows notation for our command-line commands. If you have a Unix-based environment, please use the appropriate .sh script instead of the Windows .bat version.

So let's start with a simple Java class that implements a stock quote lookup function. Please look at the Java code on the next page.

NOTE: All Java sources mentioned in this example can be found in the src subdirectory of the unpacked tutorial sources archive. All of them reside in the com.systinet.demos.stock package.

Implementing a Simple Web Service

> Developers Corner: Your First Web Service in 10 Minutes

Copyright 2003, Systinet Corp. Page 6 of 16

Example 1: Web service code (StockQuoteService.java)

/* * StockQuoteService.java * * Created on Sat 13th Oct 2001, 15:25 */ package com.systinet.demos.stock; /** * Simple stock quote service * * @version 1.0 */ public class StockQuoteService { public double getQuote(String symbol) { if(symbol!=null && symbol.equalsIgnoreCase("SUNW")) return 10; if(symbol!=null && symbol.equalsIgnoreCase("MSFT")) return 50; if(symbol!=null && symbol.equalsIgnoreCase("BEAS")) return 11; return 0; } public java.util.LinkedList getAvailableStocks() { java.util.LinkedList list = new java.util.LinkedList(); list.add("SUNW"); list.add("MSFT"); list.add("BEAS"); return list; } }

Our example is yet another simple stock quote system (we've seen so many of these, developers should be registered traders by now), but it illustrates how easily Web services can be created and deployed. In our example, we're going to retrieve the price of three stocks (BEAS, MSFT, and SUNW).

The easiest way to turn our class into a Web service is to compile our Java classes and then use the deployment tool to deploy them to the SOAP server.

Copyright 2003, Systinet Corp. Page 7 of 16

NOTE: You'll find all scripts in the bin subdirectory of the unpacked tutorial sources archive.

NOTE: Before running this example you need to install the Systinet Web services framework, WASP Server for Java. Please see the Installation chapter of this document for step-by-step installation.

First we start WASP Server with the serverstart.bat script from the WASP bin directory. Then we compile StockQuoteService.java and deploy the compiled class to the server using the run.bat deploy_stock command in the tutorials bin directory from the command-line console.

Next we'll make sure that everything worked properly by opening the administration console (if you accepted the default install, http://localhost:6060/admin/console) in the HTTP browser. Go to the Web services tab in the admin console and click on the StockQuoteService_inst service from the List of service instances table. Then click on the URL link in the List of service instance's endpoints and you should see the Web service WSDL file in the browser pop-up window. Notice that WASP Server automatically generated the WSDL file and made it publicly available at http://localhost:6060/StockQuoteService/.

The WSDL file contains a full description of the deployed Web service. Basically there are three parts in a WSDL file:

• The WHAT part, consisting of the types, message, and portType elements, defines the messages and data types exchanged between client and server. First let's look at the contents of the WSDL <types> element. It contains all the XML Schema types that were generated to represent the corresponding Java classes. The message definitions follow. A message is the basic communication element of SOAP. A message can consist of one or more parts, each part representing a typed parameter. There are two messages (input and output) for each method of our stock quote Java class. All messages are grouped into operations in an entity called a portType. A portType represents a Web service interface -- the abstract set of operations supported by the service. A Web service can have multiple interfaces represented by different portTypes. Look at the StockQuoteService portType in the sample WSDL file. It includes two operations: getAvailableStocks and getQuote. To invoke the getQuote method, the client sends a StockQuoteService_getQuote_1_Request message. Notice that the StockQuoteService_getQuote_1_Request message consists of one part (the input parameter) called p0, which is defined as an XML Schema string type. The Web service is supposed to reply with the StockQuoteService_getQuote_Response message, which contains one part (the return value) called response, which is an XML Schema double type.

• The HOW part, consisting of the binding elements, binds an abstract interface (the portType) to a set of concrete protocols. In this case, we're using SOAP over HTTP. Since we're using SOAP, we use a number of WSDL extensibility elements for SOAP to define the specifics of our SOAP binding. (Notice that many of the elements in this section use the soap: namespace prefix. These elements are SOAP extensions to WSDL.) The soapAction attribute in the soap:operation element is an HTTP-specific attribute that can be used to provide a hint as to the

> Developers Corner: Your First Web Service in 10 Minutes

Copyright 2003, Systinet Corp. Page 8 of 16

intent of the SOAP message. It can contain a message routing parameter or value that helps the SOAP runtime determine which application or method should be executed. The value specified in this attribute must also be specified in the SOAPAction: attribute in the HTTP header of the SOAP request message. In our case this attribute contains no value. A SOAP binding requires that we specify the communication style used for each operation in the portType. SOAP supports two possible communication styles: RPC and Document. The RPC style simulates a remote procedure call. It formats the request message as a structure containing the input parameters. The name of the structure indicates the method to be invoked. The response message is a structure containing the return value and any response parameters. The Document style does not impose any particular structure on the SOAP messages. It assumes that the contents of the SOAP message are well-formed XML data. A SOAP binding also requires that we specify how our messages are expressed in XML. We can use either literal or encoded serialization rules. The use='literal' attribute indicates that the message should be serialized according to a specified XML Schema instance. The use='encoded' attribute indicates that the message should be serialized using a particular encoding style. An encoding style defines a set of data typing rules. In this case we use the encoding style defined by SOAP in section 5 of the SOAP specification. Other encoding styles can also be used.

• Finally the WHERE part, consisting of the service element, maps the service bindings to a specific service implementation. It specifies the actual location (a URI) of the Web service. Check out the service element at the very end of the WSDL document.

As you can see, a WSDL file completely describes a Web service. Given this WSDL file, we have all the information we need to create a client application that can access our stock quote Web service.

Copyright 2003, Systinet Corp. Page 9 of 16

A Java client binds to a remote Web service using a proxy component. This proxy component can be statically generated from the WSDL file at development time or dynamically generated at runtime. In this example we'll use a dynamically generated proxy. We need a Java interface that can keep a reference to this dynamically created object. We can either create the interface ourselves, or we can use WASP's WSDL2Java compiler to generate one for us. The interface creation is easy since the only requirement is that the interface methods must be a subset of methods of the Web service business logic Java class. The code below shows the Web service interface as generated by the WSDL2javab tool.

Example 2: Web service interface code (StockQuoteService.java)

package com.systinet.demos.stock.client; /** */ public interface StockQuoteService { /** */ double getQuote(java.lang.String p0); /** */ java.util.LinkedList getAvailableStocks(); } /* * Generated by WSDLCompiler, (c) 2001, Systinet, Inc. * http://www.systinet.com */

Now let's look at the client code in Figure 3. All the client needs to do is lookup the Web service and bind to its proxy. This is handled through the WASP Web service Registry by invoking its lookup method. The lookup method requires two parameters: a reference to a WSDL file and the class of the Java interface that will reference the proxy instance. The lookup method returns the proxy that is used to invoke the Web service. Each time the client invokes an operation on the proxy, the request is automatically translated into a SOAP request and sent to the Web service.

Implementing a Java Web Service Client

> Developers Corner: Your First Web Service in 10 Minutes

Copyright 2003, Systinet Corp. Page 10 of 16

/** * Stock Client * * @version 1.1 */ package com.systinet.demos.stock.client; import org.systinet.wasp.webservice.Registry; import java.net.InetAddress; public class StockQuoteClient { /** * Web service client main method. * Finds the web service and * @param args not used. */ public static void main( String[] args ) throws Exception { // obtain real localhost (required by Soap Spy) String localhost = InetAddress.getLocalHost().getHostName(); // lookup and bind to StockQuoteService StockQuoteService service = (StockQuoteService)Registry.lookup( "http://"+localhost+":6060/StockQuoteService/", StockQuoteService.class ); // use StockQuoteService System.out.println("Getting available stocks"); System.out.println("------------------------"); java.util.LinkedList list = service.getAvailableStocks(); java.util.Iterator iter = list.iterator(); while(iter.hasNext()) { System.out.println(iter.next()); } System.out.println(""); System.out.println("Getting SUNW quote"); System.out.println("------------------------"); System.out.println("SUNW "+service.getQuote("SUNW")); System.out.println(""); } }

Copyright 2003, Systinet Corp. Page 11 of 16

Run the run.bat make_stock command from the bin directory. This script will invoke the WSDL2Java tool and generate the Java interface, and then it will compile the client application. After that you can run the run.bat run_stock command. You should see the output from the getAvailableStocks and getQuote methods on the console.

WASP Server supports other APIs that you can use to invoke Web services including JAXM and JAX-RPC. Please see the jaxm or jaxrpc demos from the WASP Server distribution for comprehensive code examples.

> Developers Corner: Your First Web Service in 10 Minutes

Copyright 2003, Systinet Corp. Page 12 of 16

If you have the MS .NET Framework SDK (http://msdn.microsoft.com/downloads/default.asp?url=/downloads/sample.asp?url=/msdn-files/027/000/976/msdncompositedoc.xml) installed on your computer, you can run the build_ms.bat [NT] that will compile a C# client application. If you are running on Windows NT or 2000 be sure to add the NT argument on the command line. This batch file works with .NET 1.0, if you are using a different version you will need to add the paths to csc.exe and wsdl.exe to your system PATH variable. After build_ms.bat has successfully executed you can run the StockQuoteClient.exe application from the demo build directory. You can check the C# source code located in the src\ms.net directory.

You can also open the stockquote.xls Excel spreadsheet from the src\ms.net directory and change the stock symbols in it. You should see how the price is dynamically recalculated using the getQuote macro that invokes our stock Web service. You'll need have the MS SOAP Toolkit 3.0 installed: http://msdn.microsoft.com/downloads/default.asp?URL=/downloads/sample.asp?url=/msdn-files/027/001/948/msdncompositedoc.xml

Implementing a Microsoft .NET Web service client

Copyright 2003, Systinet Corp. Page 13 of 16

Introduction

Now we can use the WASP SOAP Spy tool to view the SOAP messages that are exchanged between client and service. First, we need to start SOAP Spy by invoking the SoapSpy.bat script from the bin subdirectory of the WASP Server installation. Start the SOAP Spy listener by clicking on the left-most icon in the toolbar. Then run the Java Web service client using the run.bat spy_stock command and SOAP Spy should display the exchanged SOAP messages. Modify one of the request messages and click the resend button. Check out the new response.

SOAP message structure

SOAP messages follow the following basic structure:

<ENVELOPE attrs> <HEADER attrs> <directives/> </HEADER> <BODY attrs> <payload/> or <FAULT attrs> <errors/> </FAULT> </BODY> </ENVELOPE>

The message content is enclosed in an ENVELOPE element. In this simple case, our SOAP messages contain only a BODY section. The Body carries the message payload (in our example, the stock value and related data). Generally, SOAP doesn't mandate any specific rules for the Body section. We've already mentioned two possible styles for the Body section: Document and RPC. The Document style has no rigid formatting

1.6. SOAP messages at glance

> Developers Corner: Your First Web Service in 10 Minutes

Copyright 2003, Systinet Corp. Page 14 of 16

requirements beyond standard XML rules, while the RPC style defines rules for marking up the method call with all its parameters. The SOAP specification recommends but doesn't mandate an encoding style, the basic framework for expressing typed values in a SOAP message. The SOAP encoding style is based on the data types defined in the XML Schema, Part 2 Recommendation which includes primitive programming language types such as int, float, double, or string. SOAP Encoding also defines rules for building complex types (e.g. arrays, structures, etc.) on top of these primitives. In our case (we are using the RPC style with SOAP encoding), the Body section of the input message contains the invoked method name with encoded parameters:

<n0:getQuote xmlns:n0="http://systinet.com/wsdl/com/systinet/demos/stock/ StockQuoteService"> <p0 i:type="d:string">SUNW</p0> </n0:getQuote>

The output message contains the result of the method call:

<n0:getQuoteResponse xmlns:n0="http://systinet.com/wsdl/com/systinet/demos/stock/ StockQuoteService"> <response i:type="d:double">10.0</response> </n0:getQuoteResponse> A SOAP message can also contain a HEADER section, which is usually used to propagate context information, such as payment details, transaction context, or security credentials. We'll show the use of Header sections in subsequent articles. If an error occurs during processing, the SOAP server should return a FAULT in the Body section. The Fault element should contain a fault code, a fault description, and any details available about the fault. We'll show SOAP error processing in the next article.

Copyright 2003, Systinet Corp. Page 15 of 16

Now that we're finished, we should undeploy our Web service from the server by running the run.bat clean script.

Review of What We Learned

In this first article we've hopefully demonstrated that creating a Web service isn't so difficult - in fact, one of the benefits of using Web services is that they're relatively easy to make and deploy. In the process of creating our stock trading system we've introduced some fundamental concepts, including SOAP and WSDL. We've shown how SOAP messages are constructed, and we've created and analyzed a WSDL file that provides the instructions on how to interact with a Web service. In the next article we'll build on these concepts and examine how SOAP handles complex types, error messaging, and remote references.

Cleanup and Review

> Developers Corner: Your First Web Service in 10 Minutes

Copyright 2003, Systinet Corp. Page 16 of 16

This document and the information contained herein are the property of

Systinet Corporation and shall not be reproduced or copied in whole or in

part without written permission of Systinet Corp.

Copyright © 2003 Systinet Corp. All Rights Reserved.

The information in this document is preliminary and is subject to change

without notice and should not be construed as a commitment by Systinet

Corporation.

SYSTINET CORPORATION SHALL HAVE NO LIABILITY FOR THIS

DOCUMENT, INCLUDING ANY LIABILITY FOR NEGLIGENCE. SYSTINET

CORPORATION MAKES NO WARRANTIES, EXPRESS, IMPLIED, STATUTORY,

OR IN ANY OTHER COMMUNICATION. SYSTINET CORPORATION

SPECIFICALLY DISCLAIMS ANY WARRANTY OF MERCHANTABILITY OR

SATISFACTORY QUALITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE

AND NON-INFRINGEMENT.

Systinet, WASP, "The Web Services Infrastructure Company" and "Web

Services That Work" are trademarks of Systinet Corp.

Java and all Java-based marks are trademarks or registered trademarks of

Sun Microsystems, Inc. in the U.S. and other countries.

Microsoft, Windows and Windows NT and the Windows logo are trademarks

or registered trademarks of Microsoft Corporation in the United States and

other countries.

UNIX is a registered trademark of The Open Group in the United States and

other countries.

Other company, product, and service names mentioned in these

documents may be trademarks or service marks of others.

Systinet Corp. Five Cambridge Center, 8th Floor Cambridge, MA 02142 Phone: 1.617.868.2224 www.systinet.com

Copyright and Disclaimer


Recommended