Docstoc

Web Services and SOAP

Document Sample
Web Services and SOAP Powered By Docstoc
					 Web Services and SOAP


Representation and Management
     of Data on the Web


                                1
               Example Scenario

                                             Harry Potter (5)
             Buy Harry Potter (5)
                                              Price: 20.95
                                                             4
                                            Copies in Stock: 5
                                 Buy it
                               How Much?

                                              Book Store
Buy Harry Potter (5)      Book Store
                                               20.95



                       Harry Potter (5)
                         Price: 25.95
                       Copies in Stock: 1
                       Copies in Stock: 0

                                                                 2
       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
                                              3
    Difficulties in Using a Web
      Site As a Web Service

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

    How do we
     find the
    price? Use
    Parsing 
                                         How do
                        17.99            we find
                                          this
                                          URL?

                                                      4
           More Difficulties
          (Filling out a Form)


 Forms
  span
multipl
e pages
                           How do
                           we find
                            this
                            URL?


                                     5
     What Would We Like to 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)


                                                   6
               Solution: 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
                                                        7
         SOAP: 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

                                                      8
         What Web Services are
           Available Already?
• Google search
• Weather reports
• Stock prices
• Currency exchanges
• Sending SMS messages, Faxes
• Prices of books in Barnes and Nobles
• Dictionaries
• etc.

                                         9
           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>              Name of the Interface
         <sayHelloTo>               Name of the Method
            <name>John</name>        Name of the Parameter
         </sayHelloTo>
       </Hello>
                                                         10
        SOAP Simplification (2)

• The Server could respond with:
    <?xml version="1.0"?>
     <Hello>                Name of the Interface
                                   Name of the Method +
        <sayHelloToResponse>
                                         Response
         <message>Hello John, How are you?</message>
        </sayHelloToResponse>
     </Hello>




                                                          11
SOAP Intuition




                 12
             Actual 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>


                                                           13
             Actual 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>
                                                           14
           SOAP 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                                            15
        SOAP 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


                                                      16
           Soap Error Response for
                Method 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>                                 17
            Soap Error Response for
                 Header 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.

                                                          18
            Sending 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)


                                           19
          SOAP 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)
                                                      20
         SOAP Response via HTTP

HTTP/1.0 200 OK
Content-Type: text/xml
Content-Length: 615


<SOAP-ENV:Envelope …




                                  21
         Example: 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…

                                                     22
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>
                                                                 23
       Here is Yesterday's Response
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>
                                                                  24
Programming SOAP




                   25
             The 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
                                                     26
    What do we have to 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


                                                    27
            Technical Details -
            Application 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...

                                                      28
               Technical Details -
                Client 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
                                                     29
             Technical Details -
              SOAP 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
                                                        30
       Creating the Application Server

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
                                                               31
     Deploying 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



                                                 32
          Deployment Descriptor
<isd:service
   xmlns:isd="http://xml.apache.org/xml-soap/deployment"
   id="urn:helloApp">
      <isd:provider type="java"
                     scope="application"
                 This is the URI of the application!
                     methods="sayHelloTo">
                 (Recall SOAPAction HTTP header)
         <isd:java class="hello.HelloServer"/>
      </isd:provider>
      <isd:faultListener>
        org.apache.soap.server.DOMFaultListener
      </isd:faultListener>
</isd:service>
                                                           33
          Deployment 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>
    The scope of the Object used to
      <isd:faultListener>
    fulfill the SOAP Request.
        org.apache.soap.server.DOMFaultListener
    Application means that all SOAP
      </isd:faultListener>
    requests will be sent to the same
    object.
</isd:service>
                                                           34
          Deployment 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>
    Space delimited list of available
        org.apache.soap.server.DOMFaultListener
    methods
      </isd:faultListener>
</isd:service>
                                                           35
          Deployment 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>
       Name of the java class that
        org.apache.soap.server.DOMFaultListener
       implements the service. Note that
      </isd:faultListener>
       is is of the form:
</isd:service>packageName.className
                                                           36
          Deployment Descriptor
<isd:service
   xmlns:isd="http://xml.apache.org/xml-soap/deployment"
   id="urn:helloApp">
      <isd:provider type="java"
                     scope="application"
                     methods="sayHelloTo">
       Name of listener to deal with
         <isd:java class="hello.HelloServer"/>
       errors
      </isd:provider>
      <isd:faultListener>
        org.apache.soap.server.DOMFaultListener
      </isd:faultListener>
</isd:service>
                                                           37
          Scope 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

                                                       38
    Scope of Web Service (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?




                                              39
         Completing the Deployment

• 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

                                                         40
   Checking for Deployed Services

• You can get a list of all deployed web
 services using the command
  java org.apache.soap.server.ServiceManagerClient
    http://<host>:<port>/soap/servlet/rpcrouter list

• In this case you should see: urn:helloApp




                                                       41
          Undeploying a Service

• You can undeploy a web service, so that it
 is no longer recognized by the SOAP
 Processor using the command
  java 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
                                                     42
       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
                                           43
     Creating the Client Application
import java.net.URL;             Use host and port of
import java.util.Vector;             your tomcat
import org.apache.soap.*;             application
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);
                                                             44
     Creating the Client Application
import java.net.URL;                  Use URI of the
import java.util.Vector;                Web Service
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);
                                                             45
     Creating the Client Application
                               Defines how the
import java.net.URL;           parameters are
import java.util.Vector;        serialized and
import org.apache.soap.*;        deserialized
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);
                                                             46
Vector params = new Vector();
params.addElement(new Parameter("name", String.class,
                   args[0], null));
call.setParams(params);

// Invoke the call.               Parameter Constructor
Response resp = null;                  Arguments:
try {
                                 (1) name of parameter
    resp = call.invoke(url, "");
                                 (2) type of parameter
                                 {
 } catch( SOAPException e ) (3) value of parameter
   System.err.println("Caught SOAPException (" +
                                 (4) type of encoding
                                 (leave as + "): " +
                        e.getFaultCode() null to use
                                 the same
                        e.getMessage()); as in Call)
    System.exit(-1);
 }

                                                          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);
 }

                                                        48
        // 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());
         }

    }
}
                                                            49
            Note 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)
                                                             50
            Another Example

• Web Service to compute addition and
 subtraction of numbers.
• Web Service will be implemented in
 Javascript
• Client Application will be a Servlet




                                         51
          Creating 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


                                             52
          Deployment Descriptor:
            CalcDescriptor.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>
                                                            53
          Deployment Descriptor:
            CalcDescriptor.xml
<isd:service
   xmlns:isd="http://xml.apache.org/xml-soap/deployment"
   id="urn:calcServer">
 Don't forget to deploy using:
     <isd:provider type="script"
     java org.apache.soap.server.ServiceManagerClient
                      scope="application"
                      methods="add subtract">
     http://<host>:<port>/soap/servlet/rpcrouter deploy
         <isd:script language="javascript">
     CalcDescriptor.xml
               function add(p1, p2) { return p1+p2; }
               function subtract(p1, p2) {return p1-p2; }
        </isd:script>
     </isd:provider>
</isd:service>
                                                            54
           Creating 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
                                                                  55
              Creating 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");        56
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();
}



                                                            57
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, "" );


                                                                    58
              // 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();
        }
    }
}



                                                                              59
Implementing a SOAP Processor




                                60
    How Could a SOAP Processor
         be 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
                                           61
     Simple SOAP Implementation

• 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
                                                    62
 Getting Invocation Details from 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>
                                                       63
 Getting Invocation Details from 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
                                                                64
          Our Simple SOAP Processor
import 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"));
                                                                     65
  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>");
} } }                                                      66
67
68
                 Scoping

• What did the scoping of the Web Service
 correspnd to: (page?, request?, session?,
 application?)
• How would the implementation differ if
 the scoping was different?




                                             69
UDDI - Universal Description,
  Discovery and Integration
           Service




                                70
           A 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


                                             71
              "Types" of Pages

• White Pages:
  – Basic contact information, business name, address,
    etc.
  – Allow others to find you based on your identification
• Yellow Pages:
  – Describe web services by category
  – Allow others to find you by category (e.g., car sales
    business
• Green Pages:
  – Technical information about supported methods of
    web service
                                                            72
   UDDI Business Registry (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


                                               73
       Interacting 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
                                                  74
WSDL - Web Services
 Description Language




                        75
       Describing 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
                                                   76
   Recall Currency Exchange Example
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>               77
      CurrencyExchange'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

                                      78
<?xml version="1.0"?>
<definitions name="CurrencyExchangeService"
targetNamespace="http://www.xmethods.net/sd/CurrencyExch
angeService.wsdl"
xmlns:tns="http://www.xmethods.net/sd/CurrencyExchangeSer
vice.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>
                                                            79
<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>                                                80
       <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>
                                                                 81
Web Services Pitfalls




                        82
     Using Web Services is not as
          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
                                                   83

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:4
posted:11/23/2011
language:English
pages:83