web services and soap

Post on 14-Jan-2016

27 Views

Category:

Documents

1 Downloads

Preview:

Click to see full reader

DESCRIPTION

Web Services and SOAP. Representation and Management of Data on the Web. Harry Potter (5) Price: 20.95 Copies in Stock: 5. Harry Potter (5) Price: 20.95 Copies in Stock: 4. Buy Harry Potter (5). How Much?. Buy it. Book Store. Buy Harry Potter (5). 20.95. Harry Potter (5) - PowerPoint PPT Presentation

TRANSCRIPT

1

Web Services and SOAPWeb Services and SOAP

Representation and

Management of Data on the

Web

2

Example ScenarioExample Scenario

Book Store

Harry Potter (5)Price: 25.95

Copies in Stock: 1

Harry Potter (5)Price: 25.95

Copies in Stock: 0

Book Store

Harry Potter (5)Price: 20.95

Copies in Stock: 5

Buy Harry Potter (5)

Buy Harry Potter (5)

How Much?

20.95

Buy it

Harry Potter (5)Price: 20.95

Copies in Stock: 4

Harry Potter (5)Price: 25.95

Copies in Stock: 1

Harry Potter (5)Price: 25.95

Copies in Stock: 0

3

What is a Web Service?What is a Web Service?

• A Web Service is simply a service

available via the Web

• Service can be implemented as Java

application, C++ application,

Javascript code, etc.

• Usually, web service means a service

that can be accessed programmatically

4

Difficulties in Using a Web Difficulties in Using a Web Site As a Web ServiceSite As a Web Service

http://www.amazon.com/exec/obidos/tg/stores/detail/-/books/043935806X/reviews/103-8286384-9129400#043935806x4000

How do we find this

URL?

17.99

How do we find the

price? Use Parsing

5

More Difficulties More Difficulties (Filling out a Form)(Filling out a Form)

How do we find this

URL?

Forms span

multiple

pages

6

What Would We Like to What Would We Like to Do?Do?

• Call functions such as:

– Amazon.getPrice("Harry Potter")

– Amazon.buyBook("Harry Potter", myId)

• The language that our program uses

shouldn't depend on the language that

Amazon uses

• Use a standard underlying protocol (HTTP,

FTP, SNMP)

7

Solution: SOAPSolution: SOAP

• SOAP stands for "Simple Object Access Protocol"

• Used for "Remote Procedure Calls", similar to:– IIOP (for Corba), ORPC (for DCOM), RMI (for Java)

• Difference: SOAP is text-based (actually XML), not binary. Firewall Friendly

• Difference: Language independent, can call a program in any language

• Difference: Uses standard port, since uses standard protocols

8

SOAP: RPC versus DOCSOAP: RPC versus DOC

• SOAP is simply a standard for sending messages (think of it as an envelope)

• You can send two types of messages using SOAP:– RPC: Remote Procedure Call, a request to call a

method

– DOC: A document (this is used for more complex client - server communication)

• We will only discuss RPC today

9

What Web Services are What Web Services are Available Already?Available Already?

• Google search

• Weather reports

• Stock prices

• Currency exchanges

• Sending SMS messages, Faxes

• Prices of books in Barnes and Nobles

• Dictionaries

• etc.

10

SOAP Simplification (1)SOAP Simplification (1)

• Consider the Java interface:public interface Hello {

public String sayHelloTo(String name);

}

• Suppose that a client wants to call the server's sayHelloTo method. Could send an XML message:

<?xml version="1.0"?><Hello>    <sayHelloTo>        <name>John</name>    </sayHelloTo></Hello>

Name of the InterfaceName of the Method

Name of the Parameter

11

SOAP Simplification (2)SOAP Simplification (2)

• The Server could respond with:<?xml version="1.0"?>

<Hello>

    <sayHelloToResponse>

       <message>Hello John, How are

you?</message>

    </sayHelloToResponse>

</Hello>

Name of the Interface

Name of the Method + Response

12

SOAP IntuitionSOAP Intuition

13

Actual Soap RequestActual Soap Request

<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:Header> </SOAP-ENV:Header>    <SOAP-ENV:Body>         <ns1:sayHelloTo  xmlns:ns1="Hello"

SOAP-ENV:encodingStyle=" http://schemas.xmlsoap.org/soap/encoding/">

           <name xsi:type="xsd:string">John</name>         </ns1:sayHelloTo>    </SOAP-ENV:Body>

</SOAP-ENV:Envelope>

14

Actual Soap ResponseActual Soap Response

<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:sayHelloToResponse xmlns:ns1="Hello"                SOAP-ENV:encodingStyle="

http://schemas.xmlsoap.org/soap/encoding/">                 <return xsi:type="xsd:string">

Hello John, How are you doing?</return>

          </ns1:sayHelloToResponse>    </SOAP-ENV:Body>

</SOAP-ENV:Envelope>

15

SOAP Header SectionSOAP Header Section

• The SOAP Header can contain information that describes the SOAP request. Example:

<SOAP-ENV:Header>     <t:Transaction xmlns:t="some-URI"

SOAP-ENV:mustUnderstand="1">5     </t:Transaction></SOAP-ENV:Header>

• 5 is the transaction ID of which this method is a part

• SOAP envelope's mustUnderstand attribute is set to 1, which means that the server must either understand and honor the transaction request or must fail to process the message

16

SOAP Response on ErrorSOAP Response on Error

• There can be many errors in processing a

SOAP request

• Error in Running Method: e.g., Suppose that

the "Hello Server" does not allow anyone to

say hello on Tuesday

• Error in Processing SOAP Headers: e.g.,

Problem running method as part of a

transaction

17

Soap Error Response for Soap Error Response for Method ErrorMethod Error

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">   <SOAP-ENV:Body>       <SOAP-ENV:Fault>           <faultcode>SOAP-ENV:Server</faultcode>           <faultstring>Server Error</faultstring>           <detail>               <e:myfaultdetails xmlns:e="Hello">                 <message>                   Sorry, I cannot say hello on Tuesday.                 </message>                 <errorcode>1001</errorcode>               </e:myfaultdetails>           </detail>       </SOAP-ENV:Fault>   </SOAP-ENV:Body></SOAP-ENV:Envelope>

18

Soap Error Response for Soap Error Response for Header ErrorHeader Error

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">   <SOAP-ENV:Body>       <SOAP-ENV:Fault>           <faultcode>SOAP-ENV:MustUnderstand</faultcode>           <faultstring>SOAP Must Understand Error</faultstring>       </SOAP-ENV:Fault>   </SOAP-ENV:Body></SOAP-ENV:Envelope>

No detail element may appear when there is an error in processing the Headers of a SOAP request.

19

Sending a RequestSending a Request

• The SOAP request did not contain the

address to which it should be sent

• Q: Where do we put the URL of the

Web Service?

• A: It depends on the Protocol used to

send the request (today, consider

HTTP)

20

SOAP Request via HTTPSOAP Request via HTTP

POST http://www.Hello.com/HelloApplication HTTP/1.0

Content-Type: text/xml

Content-Length: 587

SOAPAction: urn:helloApp

<SOAP-ENV:Envelope …

Note: There are 2 addresses(1) URL of SOAP Server (2) URI of application to run (this needn't

correspond to an actual address)

21

SOAP Response via HTTPSOAP Response via HTTP

HTTP/1.0 200 OK

Content-Type: text/xml

Content-Length: 615

<SOAP-ENV:Envelope …

22

Example: Currency RateExample: Currency Rate

• There are many web services available that

you can use

• See http://www.xmethods.com/ for a list

• Look at ones marked "RPC" (Remote

Procedure Call), especially

• To get Currency exchange, for example, you

can do "telnet wwwproxy.cs.huji.ac.il 8080"

and then send the following request…

23

POST http://services.xmethods.net:80/soap HTTP/1.0

Content-Type: text/xml

Content-Length: 485

SOAPAction: ""

<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:getRate xmlns:ns1="urn:xmethods-CurrencyExchange" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">

<country1 xsi:type="xsd:string">United States</country1>

<country2 xsi:type="xsd:string">Israel</country2>

</ns1:getRate>

</SOAP-ENV:Body></SOAP-ENV:Envelope>

24

HTTP/1.0 200 OK

Content-Type: text/xml

<?xml version='1.0' encoding='UTF-8'?>

<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/' xmlns:xsi='http://www.w3.org/1999/XMLSchema-instance' xmlns:xsd='http://www.w3.org/1999/XMLSchema' xmlns:soapenc='http://schemas.xmlsoap.org/soap/encoding/' soap:encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'>

<soap:Body><n:getRateResponse

xmlns:n='urn:xmethods-CurrencyExchange'>

<Result xsi:type='xsd:float'>4.521</Result>

</n:getRateResponse>

</soap:Body></soap:Envelope>

Here is Yesterday's Here is Yesterday's ResponseResponse

25

Programming SOAPProgramming SOAP

26

The Main PlayersThe Main Players

• There are 3 components that take part in a SOAP application:

• Client Application: A program/Servlet/etc. that sends a SOAP request. Wants to use a service.

• SOAP Processor: A program that can receive SOAP requests and act accordingly (e.g., call an method of the Application Server)

• Application Server: A program that supplies the Web service

27

What do we have to What do we have to Program?Program?

• We won't directly read or write SOAP

messages

• Instead, use Java methods that create

request and analyze result

• Use a SOAP processor that is actually a

Servlet (you will download it)

• Code the Client Application and the

Application server

28

Technical Details - Technical Details - Application ServerApplication Server

• Your application server does not need anything

special

• In fact, your application server does not have

to "know" that it is being used as a Web

Service!!

• However, you will need to put the application

server somewhere in the classpath of Tomcat

so that the SOAP Processor can find it and run

it. More details on this soon...

29

Technical Details - Technical Details - Client ApplicationClient Application

• Your SOAP client will use special packages to generate a SOAP request

• Need the following packages in your CLASSPATH to compile: – soap.jar

– mail.jar

– activation.jar

• Note: All files mentioned here that you need are linked to from Exercise 5

30

Technical Details - Technical Details - SOAP ProcessorSOAP Processor

• Your Tomcat web server needs a web application that is a SOAP Processor

• Put soap.war in your <tomcat_home>/webapps directory

• To actually run the SOAP Processor, it needs the soap.jar, mail.jar, activation.jar files in its classpath

• Easiest way to get the files in its classpath: Add them to the directory <tomcat_home>/lib

31

Creating the Application Creating the Application ServerServer

package hello;

public class HelloServer {

public String sayHelloTo(String name) {

            return "Hello " + name +

", How are you doing?";      

   }    

}

• Note: No SOAP specific code here!!• Note: Put application in a package. Create a jar file from the package and put the package in <tomcat_home>/lib, so that it will be in Tomcat's classpath

32

Deploying the Web ServiceDeploying the Web Service

• The SOAP Processor must be told

about your application. This is called

"deploying"

• Deploying is a two-step process:

– Create a deployment descriptor

– Call the java command that deploys the

web application

33

Deployment DescriptorDeployment Descriptor

<isd:service xmlns:isd="http://xml.apache.org/xml-soap/deployment" id="urn:helloApp"> <isd:provider type="java" scope="application" methods="sayHelloTo"> <isd:java class="hello.HelloServer"/> </isd:provider>

<isd:faultListener>org.apache.soap.server.DOMFaultListener

</isd:faultListener></isd:service>

This is the URI of the application!

(Recall SOAPAction HTTP header)

34

Deployment DescriptorDeployment Descriptor

<isd:service xmlns:isd="http://xml.apache.org/xml-soap/deployment" id="urn:helloApp"> <isd:provider type="java" scope="application" methods="sayHelloTo"> <isd:java class="hello.HelloServer"/> </isd:provider>

<isd:faultListener>org.apache.soap.server.DOMFaultListener

</isd:faultListener></isd:service>

The scope of the Object used to fulfill the SOAP Request. Application means that all SOAP requests will be sent to the same object.

35

Deployment DescriptorDeployment Descriptor

<isd:service xmlns:isd="http://xml.apache.org/xml-soap/deployment" id="urn:helloApp"> <isd:provider type="java" scope="application" methods="sayHelloTo"> <isd:java class="hello.HelloServer"/> </isd:provider>

<isd:faultListener>org.apache.soap.server.DOMFaultListener

</isd:faultListener></isd:service>

Space delimited list of available methods

36

Deployment DescriptorDeployment Descriptor

<isd:service xmlns:isd="http://xml.apache.org/xml-soap/deployment" id="urn:helloApp"> <isd:provider type="java" scope="application" methods="sayHelloTo"> <isd:java class="hello.HelloServer"/> </isd:provider>

<isd:faultListener>org.apache.soap.server.DOMFaultListener

</isd:faultListener></isd:service>

Name of the java class that implements the service. Note that is is of the form:

packageName.className

37

Deployment DescriptorDeployment Descriptor

<isd:service xmlns:isd="http://xml.apache.org/xml-soap/deployment" id="urn:helloApp"> <isd:provider type="java" scope="application" methods="sayHelloTo"> <isd:java class="hello.HelloServer"/> </isd:provider>

<isd:faultListener>org.apache.soap.server.DOMFaultListener

</isd:faultListener></isd:service>

Name of listener to deal with errors

38

Scope of Web ServiceScope of Web Service

• page: The service instance is available until

a response is sent back or the request is

forwarded to another page

• request: The service instance is available for

the duration of the request, regardless of

forwarding

• session: The service instance is available for

the entire session

39

Scope of Web Service Scope of Web Service (cont.)(cont.)

• application: The same service instance

is used to serve all invocations

• Which of these scope values require us

to think about synchronizing access to

data members and methods?

40

Completing the Completing the DeploymentDeployment

• Save the deployment descriptor in a file, e.g.,

HelloDescriptor.xml

• Run the command:

java org.apache.soap.server.ServiceManagerClient

http://<host>:<port>/soap/servlet/rpcrouter deploy

HelloDescriptor.xml

where <host> and <port> are those of Tomcat

• Note that Tomcat must be running for this to

work

41

Checking for Deployed Checking for Deployed ServicesServices

• You can get a list of all deployed web

services using the commandjava org.apache.soap.server.ServiceManagerClient

http://<host>:<port>/soap/servlet/rpcrouter list

• In this case you should see: urn:helloApp

42

Undeploying a ServiceUndeploying a Service

• You can undeploy a web service, so

that it is no longer recognized by the

SOAP Processor using the commandjava org.apache.soap.server.ServiceManagerClient

http://<host>:<port>/soap/servlet/rpcrouter

undeploy urn:helloApp

• Note that the last argument is the URI

of the web service to be removed

43

What must the client do?What must the client do?

• Create the SOAP-RPC call

• Set up any type mappings for custom parameters

• Set the URI of the SOAP service to use

• Specify the method to invoke

• Specify the encoding to use

• Add any parameters to the call

• Connect to the SOAP service

• Receive and interpret a response

44

Creating the Client Creating the Client ApplicationApplication

import java.net.URL;import java.util.Vector; import org.apache.soap.*;import org.apache.soap.rpc.*;                             public class Client { public static void main(String[] args) throws Exception {         URL url = new URL("http://localhost:8080" + "/soap/servlet/rpcrouter");

   // Build the call.   Call call = new Call();   call.setTargetObjectURI("urn:helloApp");   call.setMethodName("sayHelloTo");   call.setEncodingStyleURI(Constants.NS_URI_SOAP_ENC);

Use host and port of your tomcat

application

45

Creating the Client Creating the Client ApplicationApplication

import java.net.URL;import java.util.Vector; import org.apache.soap.*;import org.apache.soap.rpc.*;                             public class Client { public static void main(String[] args) throws Exception {         URL url = new URL("http://localhost:8080" + "/soap/servlet/rpcrouter");

   // Build the call.   Call call = new Call();   call.setTargetObjectURI("urn:helloApp");   call.setMethodName("sayHelloTo");   call.setEncodingStyleURI(Constants.NS_URI_SOAP_ENC);

Use URI of the Web Service

46

Creating the Client Creating the Client ApplicationApplication

import java.net.URL;import java.util.Vector; import org.apache.soap.*;import org.apache.soap.rpc.*;public class Client { public static void main(String[] args) throws Exception {         URL url = new URL("http://localhost:8080" + "/soap/servlet/rpcrouter");

   // Build the call.   Call call = new Call();   call.setTargetObjectURI("urn:helloApp");   call.setMethodName("sayHelloTo");   call.setEncodingStyleURI(Constants.NS_URI_SOAP_ENC);

Defines how the parameters are serialized and deserialized

47

       Vector params = new Vector();            params.addElement(new Parameter("name", String.class,

args[0], null));       call.setParams(params);

   // Invoke the call.   Response resp = null;            try {        resp = call.invoke(url, "");

    } catch( SOAPException e ) {System.err.println("Caught SOAPException (" +

e.getFaultCode() + "): " + e.getMessage());

       System.exit(-1);    }       

Parameter Constructor Arguments:

(1) name of parameter(2) type of parameter(3) value of parameter(4) type of encoding (leave as null to use the same as in Call)

48

       Vector params = new Vector();            params.addElement(new Parameter("name", String.class,

args[0], null));       call.setParams(params);

   // Invoke the call.   Response resp = null;            try {        resp = call.invoke(url, "");

    } catch( SOAPException e ) {System.err.println("Caught SOAPException (" +

e.getFaultCode() + "): " + e.getMessage());

       System.exit(-1);    }       

49

       // Check the response.   if( !resp.generatedFault() ) {

Parameter ret = resp.getReturnValue(); Object value = ret.getValue();           

System.out.println(value); } else {

Fault fault = resp.getFault();             System.err.println("Generated fault: "); System.out.println ("  Fault Code   = " +

fault.getFaultCode());              System.out.println ("  Fault String = " +

fault.getFaultString());    }    }  

}

50

Note on ParametersNote on Parameters

• It must be possible to "serialize" the parameters that the method invoked receives and returns. Why?

• The following have default serialization/deserialization:– primitive types: int, long, double, etc.

– primitive Objects: Integer, Long, Double, String, etc.

– complex Objects: Vector, Enumeration, Hashtable, arrays

– easy to use JavaBeans (not discussed here)

51

Another ExampleAnother Example

• Web Service to compute addition and

subtraction of numbers.

• Web Service will be implemented in

Javascript

• Client Application will be a Servlet

52

Creating the ServerCreating the Server

• When the application server is a script,

the script is actually put in the

deployment descriptor

• Need the jar files bsf.jar and js.jar

• Put them in your <tomcat_home>/lib

directory

53

Deployment Descriptor: Deployment Descriptor: CalcDescriptor.xmlCalcDescriptor.xml

<isd:service xmlns:isd="http://xml.apache.org/xml-soap/deployment" id="urn:calcServer"> <isd:provider type="script" scope="application" methods="add subtract">

<isd:script language="javascript"> function add(p1, p2) { return p1+p2; }

function subtract(p1, p2) {return p1-p2; } </isd:script> </isd:provider> </isd:service>

54

Deployment Descriptor: Deployment Descriptor: CalcDescriptor.xmlCalcDescriptor.xml

<isd:service xmlns:isd="http://xml.apache.org/xml-soap/deployment" id="urn:calcServer"> <isd:provider type="script" scope="application" methods="add subtract">

<isd:script language="javascript"> function add(p1, p2) { return p1+p2; }

function subtract(p1, p2) {return p1-p2; } </isd:script> </isd:provider> </isd:service>

Don't forget to deploy using:

java

org.apache.soap.server.ServiceManagerClient

http://<host>:<port>/soap/servlet/rpcrouter

deploy CalcDescriptor.xml

55

Creating the Client FormCreating the Client Form

• Start with an HTML form that gets two numbers

and an operation: (basic code below)

<form method="get" action="servlet/CalcServlet">

Number 1: <input type="text" name="p1"><br>

Number 2: <input type="text" name="p2"><br>

Operation:

<input type="radio" name="operation" value="add"> Add

<input type="radio" name="operation" value="subtract"> Subtract

<input type="submit">

</form>Here it is

56

Creating CalcServletCreating CalcServlet

import java.io.*; import java.net.*; import java.util.*;import org.apache.soap.*; import org.apache.soap.rpc.*;import javax.servlet.*; import javax.servlet.http.*;

public class CalcServlet extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

res.setContentType("text/html");PrintWriter out = res.getWriter();

int p1 = Integer.parseInt(req.getParameter("p1"));int p2 = Integer.parseInt(req.getParameter("p2"));String operation = req.getParameter("operation");

57

out.println("<HTML><BODY>Using javascript to Compute " +

p1 + " " + (operation.equals("add")? "+" : "-") + " " + p2 + "<br>");

try { out.println("Result is:" + compute(new Integer(p1),

new Integer(p2), operation));

} catch (Exception e) { e.printStackTrace(new java.io.PrintWriter(out));}out.println("</BODY></HTML>");out.close();

}

58

private String compute(Integer arg1, Integer arg2, String operation) throws Exception

{

URL url = new URL ("http://localhost:8080/soap/servlet/rpcrouter");

// Build the call. Call call = new Call(); call.setTargetObjectURI("urn:calcServer"); call.setMethodName(operation); call.setEncodingStyleURI(Constants.NS_URI_SOAP_ENC); Vector params = new Vector(); params.addElement(new Parameter("p1", Integer.class, p1,

null)); params.addElement(new Parameter("p2",Integer.class, p2,

null)); call.setParams (params);

Response resp = call.invoke(url, "" );

59

// Check the response. if ( resp.generatedFault() ) {

Fault fault = resp.getFault (); System.out.println("The call failed: "); System.out.println("Fault Code = " +

fault.getFaultCode()); System.out.println("Fault String = " +

fault.getFaultString()); return null; } else {

Parameter result = resp.getReturnValue(); return result.getValue().toString(); } }}

60

Implementing a SOAP Implementing a SOAP ProcessorProcessor

61

How Could a SOAP How Could a SOAP Processor be Processor be

Implemented?Implemented?• No, we won't be implementing a SOAP

Processor in this course

• However, it could be implemented

using reflection

• Reflection is a Java mechanism for

discovering the class/methods/fields of

an object

62

Simple SOAP Simple SOAP ImplementationImplementation

• In SOAP, the details about the RPC are in an XML message

• In our Simple SOAP Implementation example, details will be in parameters of HTTP request

• We will allow user to invoke any method of any class, provided that the method only has String arguments

• All this is to give us an idea of how a SOAP processor works

63

Getting Invocation Details from Getting Invocation Details from Client (HTML Form)Client (HTML Form)

<form name="info" method="get" action="servlet/SOAPImitation">

Class Name: <input type="text" name="class"><br>Method Name: <input type="text" name="method"><br><input type="button" value="Set Number of Arguments"

onClick="setArguments()"> <input type="hidden" name="paramNum" value="0">

<p id = "argumentP"></p><input type="submit"></form>

64

Getting Invocation Details from Getting Invocation Details from Client (HTML Form)Client (HTML Form)

function setArguments() { num = prompt("Enter the number of arguments to the

method", 0); p = document.getElementById("argumentP"); str = "" for (i = 0 ; i < num ; i++) { str += "Argument " + i + ": " + "<input type='text' name='param" + i + "'><br>"; } p.innerHTML=str; info.paramNum.value=num}

Here it is

65

Our Simple SOAP ProcessorOur Simple SOAP Processorimport java.io.*; import javax.servlet.*; import javax.servlet.http.*;import java.lang.reflect.*;

public class SoapImitation extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse res)

throws ServletException, IOException {res.setContentType("text/html");PrintWriter out = res.getWriter();

try{ Class objClass = Class.forName(req.getParameter("class")); int numParams=Integer.parseInt(req.getParameter("paramNum"));

66

Class[] paramClasses = new Class[numParams]; Object[] paramObjs = new Object[numParams]; for (int i = 0 ; i < numParams ; i++) {

paramClasses[i] = Class.forName("java.lang.String");paramObjs[i] = req.getParameter("param" + i);

} Method method =

objClass.getMethod(req.getParameter("method"), paramClasses);

Object result = method.invoke(objClass.newInstance(), paramObjs); out.println("<HTML><BODY><h1>Method Result</h1>" +

result + "</BODY></HTML>");} catch (Exception e) { out.println("<HTML><BODY>Error!</BODY></HTML>");} } }

67

68

69

ScopingScoping

• What did the scoping of the Web

Service correspnd to: (page?, request?,

session?, application?)

• How would the implementation differ if

the scoping was different?

70

UDDI - Universal Description, UDDI - Universal Description, Discovery and Integration Discovery and Integration

ServiceService

71

A Telephone BookA Telephone Book

• How can you find a web service?

• How can you register your web service

so others will find it?

• UDDI is a standard for describing and

finding web services

• Think of UDDI as a telephone book

72

"Types" of Pages"Types" of Pages

• White Pages: White Pages: – Basic contact information, business name, address, etc.

– Allow others to find you based on your identification

• Yellow Pages:Yellow Pages:– Describe web services by category

– Allow others to find you by category (e.g., car sales business

• Green Pages:Green Pages:– Technical information about supported methods of web

service

73

UDDI Business Registry UDDI Business Registry (UBR), Public Cloud(UBR), Public Cloud

• Nodes contain all UDDI information

• Nodes are synchronized, so they retain

the same data

• You can query any node

• You can add UDDI to a node, and it will

be replicated to all others

74

Interacting with the UDDIInteracting with the UDDI

• UDDI is itself a web service!!!

• Interaction is via SOAP messages

• The JAXR package defines a standard way to interact with registries (can work with other types of registries too, e.g., ebXML)

• Two types of interaction:– Inquiry: Does not need authentification

– Publish: Needs authentification

• Here is a web interface for a UBR node

75

WSDL - Web Services WSDL - Web Services Description LanguageDescription Language

76

Describing a Web ServiceDescribing a Web Service

• SOAP is just one standard to access a web service, there are many others (XML-RPC, WDDX)

• Need a standard way to describe a Web Service:– the methods available

– their parameters

– etc.

• WSDL is a standard for describing web services using XML, i.e., a language for green pages

77

Recall Currency Exchange Recall Currency Exchange ExampleExample

POST http://services.xmethods.net:80/soap HTTP/1.0

Content-Type: text/xml

Content-Length: 485

SOAPAction: ""

<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:getRate xmlns:ns1="urn:xmethods-CurrencyExchange" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">

<country1 xsi:type="xsd:string">United States</country1>

<country2 xsi:type="xsd:string">Israel</country2>

</ns1:getRate></SOAP-ENV:Body></SOAP-ENV:Envelope>

78

CurrencyExchange's WSDLCurrencyExchange's WSDL

• Here is the WSDL for this service

• Note that it has to describe:– URL

– URI

– Method Name

– Method Namespace

– Parameter Names

– Parameter Types

– Encoding of Parameters

79

<?xml version="1.0"?>

<definitions name="CurrencyExchangeService" targetNamespace="http://www.xmethods.net/sd/CurrencyExchangeService.wsdl" xmlns:tns="http://www.xmethods.net/sd/CurrencyExchangeService.wsdl"

xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns="http://schemas.xmlsoap.org/wsdl/">

<message name="getRateRequest">

<part name="country1" type="xsd:string"/>

<part name="country2" type="xsd:string"/>

</message>

<message name="getRateResponse">

<part name="Result" type="xsd:float"/>

</message>

80

<portType name="CurrencyExchangePortType">

<operation name="getRate">

<input message="tns:getRateRequest" />

<output message="tns:getRateResponse" />

</operation>

</portType>

<binding name="CurrencyExchangeBinding"

type="tns:CurrencyExchangePortType">

<soap:binding style="rpc"

transport="http://schemas.xmlsoap.org/soap/http"/>

<operation name="getRate">

<soap:operation soapAction=""/>

<input > <soap:body use="encoded"

namespace="urn:xmethods-CurrencyExchange"

encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>

</input>

81

<output >

<soap:body use="encoded"

namespace="urn:xmethods-CurrencyExchange"

encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>

</output>

</operation>

</binding>

<service name="CurrencyExchangeService">

<documentation>Returns the exchange rate </documentation>

<port name="CurrencyExchangePort"

binding="tns:CurrencyExchangeBinding">

<soap:address

location="http://services.xmethods.net:80/soap"/>

</port>

</service></definitions>

82

Web Services PitfallsWeb Services Pitfalls

83

Using Web Services is not Using Web Services is not as Simple as it Looksas Simple as it Looks

• It is not practical to automatically find web services for your needs (UBR contains a lot of junk)

• There is no built-in mechanism for payment for use of a web service

• There is no built-in security control

• When a web service changes (e.g., adds a parameter to its method), the program using it breaks

top related