Web servicesoverview

  • 584 views
Uploaded on

about internet services

about internet services

More in: Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads

Views

Total Views
584
On Slideshare
0
From Embeds
0
Number of Embeds
0

Actions

Shares
Downloads
0
Comments
0
Likes
2

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. Web Services OverviewWeb Services OverviewMarlon PierceMarlon PierceCommunity Grids LabCommunity Grids LabIndiana UniversityIndiana University
  • 2. AssignmentsAssignments Download and install Tomcat (again).Download and install Tomcat (again).• http://jakarta.apache.org/tomcat/http://jakarta.apache.org/tomcat/• You will need two tomcat servers.You will need two tomcat servers. Install Apache Axis.Install Apache Axis.• Use “HappyAxis” to make sure you have done soUse “HappyAxis” to make sure you have done socorrectly.correctly.• http://ws.apache.org/axis/http://ws.apache.org/axis/ Design and deploy a sample web service.Design and deploy a sample web service. Write a client application to use the web service.Write a client application to use the web service. Use Google and Amazon WSDL to design yourUse Google and Amazon WSDL to design yourown client.own client.
  • 3. This Lecture…This Lecture… This lecture is intended toThis lecture is intended to introduceintroducethe main concepts of Web Services.the main concepts of Web Services. We will also look at some thingsWe will also look at some things((SOAP, WSDLSOAP, WSDL) in detail…) in detail… But the primary purpose is toBut the primary purpose is tointroduce topics that will all beintroduce topics that will all becovered incovered in greater detailgreater detail in futurein futurelectures.lectures.
  • 4. What Are Web Services?What Are Web Services? Web services framework is an XML-based distributedWeb services framework is an XML-based distributedobject/service/component system.object/service/component system.• SOAP, WSDLSOAP, WSDL, WSIL, UDDI, WSIL, UDDI• Intended to supportIntended to support machine-to-machinemachine-to-machine interactions over theinteractions over thenetwork.network. Basic ideas is to build anBasic ideas is to build an platform and programmingplatform and programminglanguage-independentlanguage-independent distributed invocation system out ofdistributed invocation system out ofexistingexisting Web standardsWeb standards..• Most standards defined by W3C, Oasis (IP considerations)Most standards defined by W3C, Oasis (IP considerations)• Interoperability really works, as long as you can map XMLInteroperability really works, as long as you can map XMLmessage to a programming language type, structure, class,message to a programming language type, structure, class,etc.etc. Very loosely defined, when compared toVery loosely defined, when compared to CORBACORBA, etc., etc. Inherit both good and bad of the webInherit both good and bad of the web• Scalable, simple, distributedScalable, simple, distributed• But no centralized management, system is inefficient, must beBut no centralized management, system is inefficient, must betolerant of failures.tolerant of failures.
  • 5. Basic Architectures:Basic Architectures:Servlets/CGI and Web ServicesServlets/CGI and Web ServicesBrowserWebServerHTTP GET/POSTDBJDBCWebServerDBJDBCBrowserWebServerSOAPGUIClientSOAPWSDLWSDLWSDLWSDL
  • 6. Explanation of Previous SlideExplanation of Previous Slide The diagram on the left represents a standardThe diagram on the left represents a standardweb application.web application.• Browsers converse with web servers using HTTPBrowsers converse with web servers using HTTPGET/POST methods.GET/POST methods.• Servlets or CGI scripts process the parameters and takeServlets or CGI scripts process the parameters and takeaction, like connect to a DB.action, like connect to a DB.• Examples:Examples: Google, AmazonGoogle, Amazon On the right, we have a Web services system.On the right, we have a Web services system.• Interactions may be either through the browser orInteractions may be either through the browser orthrough a desktop client (Java Swing, Python, Windows,through a desktop client (Java Swing, Python, Windows,etc.)etc.)• I will explain how to do this in several more lectures.I will explain how to do this in several more lectures.• Examples:Examples: Google, AmazonGoogle, Amazon
  • 7. Some TerminologySome Terminology The diagram on the left is called aThe diagram on the left is called a client/serverclient/serversystem.system. The diagram on the right is called aThe diagram on the right is called a multi-tieredmulti-tieredarchitecture.architecture. SOAPSOAP: Simple Object Access Protocol: Simple Object Access Protocol• XML Message format between client and service.XML Message format between client and service. WSDLWSDL: Web Service Description Language.: Web Service Description Language.• Describes how the service is to be usedDescribes how the service is to be used• Compare (for example) to Java Interface.Compare (for example) to Java Interface.• Guideline for constructing SOAP messages.Guideline for constructing SOAP messages.• WSDL is an XML language for writingWSDL is an XML language for writing ApplicationApplicationProgrammer InterfacesProgrammer Interfaces (APIs).(APIs).
  • 8. Amazon and Google ExperimentAmazon and Google Experimentwith Web Serviceswith Web Services Both Google and Amazon have conductedBoth Google and Amazon have conductedopen experiments with Web services.open experiments with Web services. Why? To allow partners to develop customWhy? To allow partners to develop customuser interfaces and applications that workuser interfaces and applications that workGoogle and Amazon data and services.Google and Amazon data and services. You can download their APIs and try them.You can download their APIs and try them.• http://www.google.com/apis/http://www.google.com/apis/• http://www.amazon.com/webserviceshttp://www.amazon.com/webservices
  • 9. Why Use Web Services?Why Use Web Services? Web services provide a cleanWeb services provide a clean separationseparationbetween a capability and its user interface.between a capability and its user interface. This allows a company (Google) with aThis allows a company (Google) with asophisticated capability and huge amountssophisticated capability and huge amountsof data to make that capability available toof data to make that capability available toits partners.its partners.• ““Don’t worry about howDon’t worry about how PageRankPageRank works orworks orweb robots or data storage. We will do that.web robots or data storage. We will do that.You just use this WSDL API to build your clientYou just use this WSDL API to build your clientapplication to use our search engine.”application to use our search engine.”
  • 10. A Google AsideA Google Aside Google’sGoogle’s PageRankPageRank system was developedsystem was developedby two Stanford grad students.by two Stanford grad students. OpenOpen algorithm published in scholarlyalgorithm published in scholarlyjournals, conferences.journals, conferences.• Previous (and lousy) search engines were allPrevious (and lousy) search engines were allproprietary.proprietary. See for exampleSee for examplehttp://www7.scu.edu.au/programme/fullphttp://www7.scu.edu.au/programme/fullpapers/1921/com1921.htmapers/1921/com1921.htm
  • 11. When To Use Web Services?When To Use Web Services? Applications do not have severe restrictions onApplications do not have severe restrictions onreliability and speedreliability and speed.. Two or more organizations need toTwo or more organizations need to cooperatecooperate• One needs to write an application that uses another’sOne needs to write an application that uses another’sservice.service. Services can beServices can be upgraded independentlyupgraded independently ofofclients.clients.• Google can improve PageRank implemenation withoutGoogle can improve PageRank implemenation withouttelling me.telling me.• Just don’t change the WSDL.Just don’t change the WSDL. Services can be easily expressed with simpleServices can be easily expressed with simplerequest/responserequest/response semantics and simplesemantics and simple statestate..• HTTP and Cookies, for example.HTTP and Cookies, for example.
  • 12. Relationship to PreviousRelationship to PreviousWorkWorkConnecting to Bryan’sConnecting to Bryan’sLectures on XML, Java, JavaLectures on XML, Java, JavaServlets and JSP.Servlets and JSP.
  • 13. XML OverviewXML Overview XML is a language for building languages.XML is a language for building languages. Basic rules: be well formed and be validBasic rules: be well formed and be valid Particular XML “dialects” are defined by anParticular XML “dialects” are defined by anXML Schema.XML Schema.• XML itself is defined by its own schema.XML itself is defined by its own schema. XML is extensible via namespacesXML is extensible via namespaces Many non-Web services dialectsMany non-Web services dialects• RDF, SVG,GML, XForms, XHTMLRDF, SVG,GML, XForms, XHTML Many basic tools available: parsers, XPathMany basic tools available: parsers, XPathand XQuery for searching/querying, etc.and XQuery for searching/querying, etc.
  • 14. XML and Web servicesXML and Web services XML provides a natural substrate for distributedXML provides a natural substrate for distributedcomputing:computing:• Its just a data description.Its just a data description.• Platform, programming language independent.Platform, programming language independent. So let’s describe the pieces.So let’s describe the pieces. Web Services Description Language (WSDL)Web Services Description Language (WSDL)• Describes how to invoke a service (compare with CORBADescribes how to invoke a service (compare with CORBAIDL).IDL).• Can bind to SOAP, other protocols for actual invocation.Can bind to SOAP, other protocols for actual invocation. Simple Object Access Protocol (SOAP)Simple Object Access Protocol (SOAP)• Wire protocol extension for conveying RPC calls.Wire protocol extension for conveying RPC calls.• Can be carried over HTTP, SMTP.Can be carried over HTTP, SMTP.
  • 15. Web Service ArchitecturesWeb Service Architectures The following examples illustrate how WebThe following examples illustrate how Webservices interact with clients.services interact with clients. For us, a client is typically a JSP, servlet,For us, a client is typically a JSP, servlet,or portlet that a user accesses throughor portlet that a user accesses throughbrowser.browser. You can also build other clientsYou can also build other clients• Web serviceWeb service interoperabilityinteroperability means that clientsmeans that clientsand services can be in different programmingand services can be in different programminglanguages (C/C++, python, java, etc).languages (C/C++, python, java, etc).
  • 16. Browser InterfaceUser InterfaceServer + ClientStubsServer plusServiceImplementationsBackendResourcesHTTP(S)SOAP/HTTP(S)Local invocation, JDBCconnection or Grid ProtocolUI Server has stubsfor all services (database access, jobsubmission, filetransfer, etc.)A particular serverhas severalservice implementations.Backend is a database,application code plusoperating system.
  • 17. User Interface ServerDB Service 1JDBCDBJob Sub/MonAnd FileServicesOperating andQueuingSystemsUser InterfaceDB Service 2JDBCDBHost 1 Host 2 Host 3
  • 18. Before Going On…Before Going On… In the next several slides we’ll go into theIn the next several slides we’ll go into thedetails of WSDL and SOAP.details of WSDL and SOAP. But in practice,But in practice, you don’t need to workyou don’t need to workdirectly with eitherdirectly with either..• Most tools that I’m familiar with generate theMost tools that I’m familiar with generate theWSDL for you from your class.WSDL for you from your class.• SOAP messages are constructed by classes.SOAP messages are constructed by classes.• GeneratedGenerated client stubsclient stubs will even hide SOAPwill even hide SOAPclasses behind a local “façade” that looks like aclasses behind a local “façade” that looks like alocal class but actually constructs SOAP calls tolocal class but actually constructs SOAP calls tothe remote server.the remote server.
  • 19. Web ServicesWeb ServicesDescription LanguageDescription LanguageDefines what your serviceDefines what your servicedoes and how it is invoked.does and how it is invoked.
  • 20. WSDL OverviewWSDL Overview WSDL is an XML-based Interface DefinitionWSDL is an XML-based Interface DefinitionLanguage.Language.• You can define the APIs for all of your services in WSDL.You can define the APIs for all of your services in WSDL. WSDL docs are broken into five major parts:WSDL docs are broken into five major parts:• Data definitionsData definitions (in XML) for custom types(in XML) for custom types• Abstract message definitionsAbstract message definitions (request, response)(request, response)• Organization of messages into “Organization of messages into “portsports” and “” and “operationsoperations””((classes and methods).classes and methods).• Protocol bindingsProtocol bindings (to SOAP, for example)(to SOAP, for example)• Service point locationsService point locations (URLs)(URLs) Some interesting featuresSome interesting features• A single WSDL document can describe several versionsA single WSDL document can describe several versionsof an interface.of an interface.• A single WSDL doc can describe several related services.A single WSDL doc can describe several related services.
  • 21. The Java CodeThe Java Codepublic String[] execLocalCommand(Stringpublic String[] execLocalCommand(Stringcommand) {command) {Runtime rt = Runtime.getRuntime();Runtime rt = Runtime.getRuntime();String stdout="",stderr="";String stdout="",stderr="";try {try {Process p = rt.exec(command);Process p = rt.exec(command);BufferedReader in=BufferedReader in=new BufferedReader(newnew BufferedReader(newInputStreamReader(p.getInputStream()));InputStreamReader(p.getInputStream()));BufferedReader err=BufferedReader err=new BufferedReader(newnew BufferedReader(newInputStreamReader(p.getErrorStream()));InputStreamReader(p.getErrorStream()));
  • 22. Java Code ContinuedJava Code ContinuedString line;String line;while((line=in.readLine())!= null)while((line=in.readLine())!= null){stdout+=line+"n";}{stdout+=line+"n";}in.close();in.close();while ((line=err.readLine())!=null)while ((line=err.readLine())!=null){stderr+=line+"n";}{stderr+=line+"n";}err.close();err.close();}//End of try{}}//End of try{}catch (Exception eio) {…}catch (Exception eio) {…}String[] retstring=new String[2];String[] retstring=new String[2];retstring[0]=stdout;retstring[0]=stdout;retstring[1]=stderr;retstring[1]=stderr;return retstring;return retstring;} //End of method} //End of method
  • 23. WSDL Example: JobWSDL Example: JobSubmissionSubmission Our example is a simple service that canOur example is a simple service that canexecutes local (to the server) commands.executes local (to the server) commands. Service implementation (in Java) has aService implementation (in Java) has asingle methodsingle method• ExecLocal takes a single string argument (theExecLocal takes a single string argument (thecommand to exec)command to exec)• Returns a 2D string array (standard out andReturns a 2D string array (standard out anderror).error). The WSDL maps to a Java interface in thisThe WSDL maps to a Java interface in thiscase.case.
  • 24. The Full WSDLThe Full WSDL The following slide contains the WSDLThe following slide contains the WSDLdefinition for the Job Submit service.definition for the Job Submit service.• I omitted some data definitions to get into oneI omitted some data definitions to get into onepage with a decent font.page with a decent font. As you can see, WSDL is veryAs you can see, WSDL is very verboseverbose• Typically, you don’t write WSDLTypically, you don’t write WSDL• This file was actually generated from my JavaThis file was actually generated from my Javaclass byclass by Apache AxisApache Axis.. We will go through the parts of the doc inWe will go through the parts of the doc insome detail.some detail.
  • 25. <?xml version="1.0" encoding="UTF-8"?><wsdl:definitions><wsdl:message name="execLocalCommandResponse"><wsdl:message name="execLocalCommandRequest"><wsdl:portType name="SJwsImp"><wsdl:operation name="execLocalCommand" parameterOrder="in0"><wsdl:input message="impl:execLocalCommandRequest"name="execLocalCommandRequest"/><wsdl:output message="impl:execLocalCommandResponse"name="execLocalCommandResponse"/></wsdl:operation></wsdl:portType><wsdl:binding name="SubmitjobSoapBinding" type="impl:SJwsImp"><wsdlsoap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/><wsdl:operation name="execLocalCommand"><wsdlsoap:operation soapAction=""/><wsdl:input name="execLocalCommandRequest"><wsdl:output name="execLocalCommandResponse"></wsdl:operation></wsdl:binding><wsdl:service name="SJwsImpService"><wsdl:port binding="impl:SubmitjobSoapBinding" name="Submitjob"></wsdl:service></wsdl:definitions>
  • 26. WSDL Elements IWSDL Elements I TypesTypes: describes custom XML data types: describes custom XML data types(optional) used in messages.(optional) used in messages.• For OO languages, types are a limited objectFor OO languages, types are a limited objectserialization.serialization.• We’ll see an example for defining arrays.We’ll see an example for defining arrays. MessageMessage: abstractly defines the messages that: abstractly defines the messages thatneed to be exchanged.need to be exchanged.• Conventionally messages are used to group requestsConventionally messages are used to group requestsand responses.and responses.• Each method/function in the interface contains 0-1Each method/function in the interface contains 0-1request and 0-1 response messages.request and 0-1 response messages.• Consists ofConsists of partpart elements. Usually you need one part forelements. Usually you need one part foreach variable sent or received. Parts can either be XMLeach variable sent or received. Parts can either be XMLprimitive types or custom complex types.primitive types or custom complex types.
  • 27. TypesTypes for Job Submissionfor Job Submission Recall that the job submissionRecall that the job submissionservice sends a string (theservice sends a string (thecommand) and returns a 2D array.command) and returns a 2D array. StringsStrings are XML Schemaare XML Schema primitiveprimitivetypestypes, so we don’t need a special, so we don’t need a specialdefinition in our WSDL.definition in our WSDL. ArraysArrays areare not primitive typesnot primitive types. They. Theyare defined in the SOAP schema, soare defined in the SOAP schema, sowe will import that definition.we will import that definition.• In other words, SOAP has rules for arrayIn other words, SOAP has rules for arrayencoding; vanilla XML does not.encoding; vanilla XML does not.
  • 28. Example: WSDLExample: WSDL typestypes for Customfor CustomData DefinitionData Definition<wsdl:types><schema targetNamespace="http://.../GCWS/services/Submitjob"xmlns:impl="http://.../GCWS/services/Submitjob"xmlns="http://www.w3.org/2001/XMLSchema"><import namespace="http://schemas.xmlsoap.org/soap/encoding/" /><complexType name="ArrayOf_xsd_string"><complexContent><restriction base="soapenc:Array"><attribute ref="soapenc:arrayType"wsdl:arrayType="xsd:string[]" /></restriction></complexContent></complexType><element name="ArrayOf_xsd_string" nillable="true"type="impl:ArrayOf_xsd_string" /></schema></wsdl:types>
  • 29. What Does It Mean?What Does It Mean? We start with some usefulWe start with some usefulnamespace definitions.namespace definitions. We next import the SOAP schemaWe next import the SOAP schema• It has the array definitions we need.It has the array definitions we need. Finally, we define our own local XMLFinally, we define our own local XMLcomplex type, ArrayOf_xsd_string.complex type, ArrayOf_xsd_string.• This extends the SOAP array typeThis extends the SOAP array type• We restrict this to String arrays.We restrict this to String arrays.
  • 30. MessageMessage Elements for JobElements for JobSubmission ServiceSubmission Service Our service implementation has one method ofOur service implementation has one method ofthe form (in Java)the form (in Java)public String[] execLocalCommand(String cmd)public String[] execLocalCommand(String cmd) This will require one “request” message and oneThis will require one “request” message and one“response” message.“response” message. Each message has oneEach message has one part:part:• Request message must send the String cmd.Request message must send the String cmd.• Response must get back the String[] array (definedResponse must get back the String[] array (definedpreviously as a custom type).previously as a custom type). If we had to pass two input variables, ourIf we had to pass two input variables, our“request” message would need two part“request” message would need two partelements.elements. Note the name attributes of messages areNote the name attributes of messages areimportant!important!
  • 31. Message Examples for JobMessage Examples for JobSubmission ServiceSubmission Service<wsdl:messagename="execLocalCommandResponse"><wsdl:partname="execLocalCommandReturn"type="impl:ArrayOf_xsd_string" /></wsdl:message><wsdl:messagename="execLocalCommandRequest"><wsdl:part name="in0" type="xsd:string" /></wsdl:message>
  • 32. portTypesportTypes portTypeportType elements map messages toelements map messages tooperationsoperations.. You can think of portType==class,You can think of portType==class,operation==class methods.operation==class methods. Operations can contain input, output,Operations can contain input, output,and/or fault bindings for messages.and/or fault bindings for messages. An operation may support of the followingAn operation may support of the followingmessage styles:message styles:• One-way: request onlyOne-way: request only• Two-way: request/responseTwo-way: request/response• Solicit-response: server “push” and client responseSolicit-response: server “push” and client response• Notification: one-way server pushNotification: one-way server push
  • 33. portType for JobSubmitportType for JobSubmit We previously defined the messagesWe previously defined the messagesand types needed. Now we bindand types needed. Now we bindthem into the portType structure.them into the portType structure. PortType names are importantPortType names are important• Will be referenced byWill be referenced by bindingbinding element.element. Note names of previously definedNote names of previously definedmessages are used as references inmessages are used as references inthe operations.the operations.
  • 34. <wsdl:portType name="SJwsImp"><wsdl:operation name="execLocalCommand"parameterOrder="in0"><wsdl:inputmessage="impl:execLocalCommandRequest"name="execLocalCommandRequest" /><wsdl:outputmessage="impl:execLocalCommandResponse"name="execLocalCommandResponse" /></wsdl:operation></wsdl:portType>Example WSDL NuggetExample WSDL Nugget
  • 35. Some Notes on the PortTypeSome Notes on the PortTypeDefinitionDefinition PortTypes refer to messages by namePortTypes refer to messages by name• The message attribute in <input> andThe message attribute in <input> and<output> elements of <operation> refer to<output> elements of <operation> refer tothe name attributes of the previously definedthe name attributes of the previously definedmessages.messages.• The operation and portType names willThe operation and portType names willsimilarly be used for reference in forthcomingsimilarly be used for reference in forthcomingtags.tags. Also note “parameterOrder” does what youAlso note “parameterOrder” does what youwould expect. For the current example,would expect. For the current example,there is only one input parameter.there is only one input parameter.
  • 36. PortType BindingsPortType Bindings portTypes are abstract interfaceportTypes are abstract interfacedefinitions.definitions.• Don’t say anything about how to invoke aDon’t say anything about how to invoke aremote method.remote method. Remote invocations are defined inRemote invocations are defined in bindingbindingelements.elements. Binding elements are really just placeBinding elements are really just placeholders that are extended for specificholders that are extended for specificprotocolsprotocols• WSDL spec provides SOAP, HTTP GET/POST,WSDL spec provides SOAP, HTTP GET/POST,and MIME extension schema examples.and MIME extension schema examples.
  • 37. SOAP Bindings for JobSubmitSOAP Bindings for JobSubmitServiceService Note that the binding element contains a mixtureNote that the binding element contains a mixtureof tags from different namespaces (wsdl andof tags from different namespaces (wsdl andwsdlsoap).wsdlsoap). WSDL child elements forWSDL child elements for bindingbinding element areelement areoperation, input,operation, input, andand output.output. WSDLSOAP elements are from a different XMLWSDLSOAP elements are from a different XMLschema (a new one, neither WSDL nor SOAP).schema (a new one, neither WSDL nor SOAP).• This is how you extend WSDL bindings: define a newThis is how you extend WSDL bindings: define a newschema that gives mapping instructions from WSDL toschema that gives mapping instructions from WSDL tothe protocol of choice.the protocol of choice. The binding element name is important, will beThe binding element name is important, will beused as a reference by the final port binding.used as a reference by the final port binding.
  • 38. <wsdl:bindingname="SubmitjobSoapBinding" type="impl:SJwsImp"><wsdlsoap:binding style="rpc"transport="http://schemas.xmlsoap.org/soap/http" /><wsdl:operation name="execLocalCommand"><wsdlsoap:operation soapAction="" /><wsdl:input name="execLocalCommandRequest"><wsdlsoap:bodyencodingStyle=http://schemas.xmlsoap.org/soap/encoding/namespace="http://.../GCWS/services/Submitjob"use="encoded" /></wsdl:input><wsdl:output name="execLocalCommandResponse"><wsdlsoap:bodyencodingStyle=http://schemas.xmlsoap.org/soap/encoding/namespace=http://.../GCWS/services/Submitjobuse="encoded" /></wsdl:output></wsdl:operation></wsdl:binding>
  • 39. A Closer Look at SOAP BindingA Closer Look at SOAP Binding<wsdlsoap:body<wsdlsoap:bodyencodingStyle=encodingStyle=http://schemas.xmlsoap.org/http://schemas.xmlsoap.org/soap/encoding/soap/encoding/namespace=namespace=http://.../GCWS/services/Submihttp://.../GCWS/services/Submitjobtjob use="use="encodedencoded" />" /> All this really means is “encode the message byAll this really means is “encode the message bythe rules in encodingStyle and put it in the SOAPthe rules in encodingStyle and put it in the SOAPbody.”body.” The bindings are just instructions that must beThe bindings are just instructions that must beimplemented by the SOAP message generator.implemented by the SOAP message generator.
  • 40. Service and Port DefinitionsService and Port Definitions So far, we have defined the classSo far, we have defined the classmethod interfaces (portTypes) andmethod interfaces (portTypes) andthe rules for binding to a particularthe rules for binding to a particularprotocol.protocol. PortPort elements define how theelements define how thebindings (and thus the portTypes)bindings (and thus the portTypes)are associated with a particularare associated with a particularserver.server. TheThe serviceservice element collectselement collects ports.ports.
  • 41. <wsdl:service name="SJwsImpService"><wsdl:portbinding="impl:SubmitjobSoapBinding"name="Submitjob"><wsdlsoap:addresslocation="http://.../GCWS/services/Submitjob" /></wsdl:port></wsdl:service>Service and Port Elements for theService and Port Elements for theJob Submission ServiceJob Submission Service
  • 42. ExplanationExplanation Note the port element’s binding attributeNote the port element’s binding attributepoints to the appropriatepoints to the appropriate bindingbinding elementelementby name.by name. The only purpose of the port element is toThe only purpose of the port element is topoint to a service location (a URL). This ispoint to a service location (a URL). This isdone by extension (SOAP in this case.)done by extension (SOAP in this case.) Ports are child elements of thePorts are child elements of the serviceserviceelement. A service can contain one orelement. A service can contain one ormore ports.more ports.• Note the value of multiple ports: a singleNote the value of multiple ports: a singleportType may correspond to several ports,portType may correspond to several ports,each with a different protocol binding andeach with a different protocol binding andservice point.service point.
  • 43. WSDL TriviaWSDL Trivia The schema rules allow all of the elements weThe schema rules allow all of the elements wehave discussed to appear zero or more times.have discussed to appear zero or more times. A single WSDL file may contain many portTypesA single WSDL file may contain many portTypes(although this is not usual).(although this is not usual).• You may want to do this to support multiple interfaceYou may want to do this to support multiple interfacedefinitions of a service for backward compatibility.definitions of a service for backward compatibility. Multiple ports may also be used to provideMultiple ports may also be used to providedifferent views of a servicedifferent views of a service• One portType defines the interface.One portType defines the interface.• Another provides access to metadata about the service.Another provides access to metadata about the service.• Yet another may define how the service interacts withYet another may define how the service interacts withother servicesother services via notification/event systemsvia notification/event systems..
  • 44. Simple Object AccessSimple Object AccessProtocolProtocolA message format forA message format forexchanging structured, typedexchanging structured, typedinformationinformation
  • 45. SOAP BasicsSOAP Basics SOAP is often thought of as a protocol extensionSOAP is often thought of as a protocol extensionfor doing RPC over HTTP.for doing RPC over HTTP. This is not completely accurate: SOAP is an XMLThis is not completely accurate: SOAP is an XMLmessage format for exchanging structured, typedmessage format for exchanging structured, typeddata.data. It may be used for RPC in client-serverIt may be used for RPC in client-serverapplications but is also suitable for messagingapplications but is also suitable for messagingsystems (like JMS) that follow one-to-many (orsystems (like JMS) that follow one-to-many (orpublish-subscribe) models.publish-subscribe) models. SOAP is not a transport protocol. You mustSOAP is not a transport protocol. You mustattach your message to a transport mechanismattach your message to a transport mechanismlike HTTP.like HTTP.
  • 46. SOAP StructureSOAP Structure A SOAP message is contained in anA SOAP message is contained in anenvelop.envelop. The envelop element in turn containThe envelop element in turn contain(in order)(in order)• An optionalAn optional headerheader with one or morewith one or morechild entrieschild entries..• AA bodybody element that can contain one orelement that can contain one ormore child entries. These child entriesmore child entries. These child entriesmay contain arbitrary XML data.may contain arbitrary XML data.
  • 47. SOAP HeadersSOAP Headers Headers are really just extension pointsHeaders are really just extension pointswhere you can include elements fromwhere you can include elements fromother namespaces.other namespaces.• i.e., headers can contain arbitrary XML.i.e., headers can contain arbitrary XML. Header entries may optionally have aHeader entries may optionally have a“mustUnderstand” attribute.“mustUnderstand” attribute.• mustUnderstand=1 means the messagemustUnderstand=1 means the messagerecipient must process the header element.recipient must process the header element.• If mustUnderstand=0 or is missing, the headerIf mustUnderstand=0 or is missing, the headerelement is optional.element is optional.
  • 48. SOAP BodySOAP Body Body entries are really just placeholdersBody entries are really just placeholdersfor arbitrary XML from some otherfor arbitrary XML from some othernamespace.namespace. The body contains the XML message thatThe body contains the XML message thatyou are transmitting.you are transmitting. The message format is not specified byThe message format is not specified bySOAP.SOAP.• The <Body></Body> tag pairs are just a wayThe <Body></Body> tag pairs are just a wayto notify the recipient that the actual XMLto notify the recipient that the actual XMLmessage is contained therein.message is contained therein.• The recipient decides what to do with theThe recipient decides what to do with themessage.message.
  • 49. Example MessagesExample Messages Recall the WSDL interface for “SubmitJob”Recall the WSDL interface for “SubmitJob”• Sends one string commandSends one string command• Returns array of strings for standard out and error.Returns array of strings for standard out and error. The envelop is decorated with a few usefulThe envelop is decorated with a few usefulnamespacesnamespaces::• soapenv defines the versionsoapenv defines the version• xsd is the Schema definition itselfxsd is the Schema definition itself• xsi defines some useful constants.xsi defines some useful constants. The body is just an arbitrary XMLThe body is just an arbitrary XMLfragment.fragment.• Assumes the recipient knows what this means.Assumes the recipient knows what this means.• Recipient must looks up the ExecLocalCommand operation inRecipient must looks up the ExecLocalCommand operation inthe JobSubmit service and passes it one string argument.the JobSubmit service and passes it one string argument.• The ns1 namespace tells the recipient the WSDL namespaceThe ns1 namespace tells the recipient the WSDL namespacethat defines the service.that defines the service.• xsi:type lets the recipient know that the arbitrary XML elementxsi:type lets the recipient know that the arbitrary XML elementin0 is in fact a string, as defined by the XML Schema.in0 is in fact a string, as defined by the XML Schema.
  • 50. <soapenv:Envelopexmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"xmlns:xsd=http://www.w3.org/2001/XMLSchemaxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><soapenv:Body><ns1:execLocalCommandsoapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"xmlns:ns1="http://.../GCWS/services/Submitjob/GCWS/services/Submitjob"><in0 xsi:type="xsd:string">/usr/bin/csh /tmp/job.script</in0></ns1:execLocalCommand></soapenv:Body></soapenv:Envelope>SOAP RequestSOAP Request
  • 51. Example ResponseExample Response The structure is the same as the request.The structure is the same as the request. The interesting thing here is that theThe interesting thing here is that therequest returns a 2-element array of tworequest returns a 2-element array of twostrings.strings.• Arrays not defined by XML schemaArrays not defined by XML schema• SOAP encoding does define arrays, so useSOAP encoding does define arrays, so usexsi:type to point to this definition.xsi:type to point to this definition.• <item></item> surrounds each array<item></item> surrounds each arrayelement.element. Note that arbitrary XML returns canNote that arbitrary XML returns canlikewise be encoded this way.likewise be encoded this way.• Use xsi:type to point to a schema.Use xsi:type to point to a schema.
  • 52. <soapenv:Envelopexmlns:soapenv=http://schemas.xmlsoap.org/soap/envelope/xmlns:xsd=http://www.w3.org/2001/XMLSchemaxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><soapenv:Body><ns1:execLocalCommandResponsesoapenv:encodingStyle=http://schemas.xmlsoap.org/soap/encoding/xmlns:ns1="http://../services/Submitjob"><execLocalCommandReturn xsi:type="soapenc:Array“soapenc:arrayType="xsd:string[2]"xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"><item></item> <item></item></execLocalCommandReturn></ns1:execLocalCommandResponse></soapenv:Body></soapenv:Envelope>SOAP ResponseSOAP Response
  • 53. Developing WebDeveloping WebServicesServicesUsing Apache Axis to developUsing Apache Axis to developJava implementations of WebJava implementations of Webservices.services.
  • 54. Web Service DevelopmentWeb Service DevelopmentToolsTools Web service toolkits exist for variousWeb service toolkits exist for variousprogramming languages:programming languages:• C++,Python, Perl, various MicrosoftC++,Python, Perl, various Microsoft.NET kits..NET kits. We’ll concentrate on building JavaWe’ll concentrate on building JavaWeb services with Apache Axis.Web services with Apache Axis. Language and implementationLanguage and implementationinteroperability is addressed throughinteroperability is addressed throughWS-I.WS-I.• http://www.ws-i.org/http://www.ws-i.org/
  • 55. Apache Axis OverviewApache Axis Overview Apache Axis is a toolkit for converting JavaApache Axis is a toolkit for converting Javaapplications into Web services.applications into Web services. Axis service deployment tools allow you toAxis service deployment tools allow you topublish your service in a particularpublish your service in a particularapplication server (Tomcat).application server (Tomcat). Axis client tools allow you to convertAxis client tools allow you to convertWSDL into client stubs.WSDL into client stubs. Axis runtime tools accept incoming SOAPAxis runtime tools accept incoming SOAPrequests and redirect them to therequests and redirect them to theappropriate service.appropriate service.
  • 56. Developing and Deploying aDeveloping and Deploying aServiceService Download and install Tomcat and Axis.Download and install Tomcat and Axis. Write a Java implementationWrite a Java implementation• Our SubmitJob is a simple example but services can getOur SubmitJob is a simple example but services can getquite complicated.quite complicated.• Compile it into Tomcat’s classpath.Compile it into Tomcat’s classpath. Write a deployment descriptor (WSDD) for yourWrite a deployment descriptor (WSDD) for yourservice.service.• Will be used by Axis runtime to direct SOAP calls.Will be used by Axis runtime to direct SOAP calls. Use Axis’s AdminClient tool to install your WSDDUse Axis’s AdminClient tool to install your WSDDfile.file.• The tells the axis servlet to load your class and directThe tells the axis servlet to load your class and directSOAP requests to it.SOAP requests to it. That’s it.That’s it.• Axis will automatically generate the WSDL for yourAxis will automatically generate the WSDL for yourservice.service.
  • 57. <deployment name="Submitjob"xmlns="http://xml.apache.org/axis/wsdd/"xmlns:java="http://xml.apache.org/axis/wsdd/providers/java"><service name="Submitjob" provider="java:RPC"><parameter name="scope" value="request"/><parameter name="className"value="WebFlowSoap.SJwsImp"/><parameter name="allowedMethods"value="execLocalCommand"/></service></deployment>Sample WSDDSample WSDD
  • 58. ExplanationExplanation Use Axis’s command-lineUse Axis’s command-lineAdminClient tool to deploy this to theAdminClient tool to deploy this to theserver.server. Axis will create a service calledAxis will create a service called• http://your.server/services/SubmitJobhttp://your.server/services/SubmitJob WSDL for service is available fromWSDL for service is available from• http://your.server/services/SubmitJob?http://your.server/services/SubmitJob?wsdlwsdl A list of all services is available fromA list of all services is available from• http://your.server/serviceshttp://your.server/services
  • 59. Check your Tomcat Serverfor a list of deployedservices.
  • 60. WSDL generated byinspecting the Javaimplementation. Can bedownload from theserver.(XML was shown inearlier slides)
  • 61. Building a Client with AxisBuilding a Client with Axis Obtain the WSDL file.Obtain the WSDL file. Generate client stubsGenerate client stubs• Stubs look like local objects but reallyStubs look like local objects but reallyconvert method invocations into SOAPconvert method invocations into SOAPcalls.calls. Write a client application with theWrite a client application with thestubsstubs• Can be a Java GUI, a JSP page, etc.Can be a Java GUI, a JSP page, etc. Compile everything and run.Compile everything and run.
  • 62. Sample Java Client CodeSample Java Client Code/**Create SubmitJob client object and point to the/**Create SubmitJob client object and point to theservice you want to use */service you want to use */SubmiJob sjws = newSubmiJob sjws = newSubmitJobServiceLocator().getSubmitjob(newSubmitJobServiceLocator().getSubmitjob(newURL(http://your.server/services/SubmitJob));URL(http://your.server/services/SubmitJob));/** Invoke the method as if local. *//** Invoke the method as if local. */String[] messages =String[] messages =sjws.execLocalCommand(command);sjws.execLocalCommand(command);
  • 63. Two Notes On Client StubsTwo Notes On Client Stubs Axis stubs convert method calls intoAxis stubs convert method calls intoSOAP requests but WSDL does notSOAP requests but WSDL does notrequire the use of SOAP.require the use of SOAP.• Web Service Invocation Framework (WSIF)Web Service Invocation Framework (WSIF)from IBM allows flexibility of protocols. (Alekfrom IBM allows flexibility of protocols. (AlekSlominski, IU)Slominski, IU) Client stubs introduce versioningClient stubs introduce versioningproblemsproblems..• We are developing dynamic (stubless) clientsWe are developing dynamic (stubless) clientsthat construct SOAP messages by inspectingthat construct SOAP messages by inspectingWSDL at runtime.WSDL at runtime.
  • 64. Web Service URLsWeb Service URLs JavaJava• http://xml.apache.org/axis/http://xml.apache.org/axis/ XSOAP: C++ and Java toolkits for WSXSOAP: C++ and Java toolkits for WS• http://www.extreme.indiana.edu/xgws/xsoap/http://www.extreme.indiana.edu/xgws/xsoap/ gSOAP: C++ SOAP toolkitgSOAP: C++ SOAP toolkit• http://www.cs.fsu.edu/~engelen/soap.htmlhttp://www.cs.fsu.edu/~engelen/soap.html Python Web Services:Python Web Services:• http://pywebsvcs.sourceforge.net/http://pywebsvcs.sourceforge.net/ Perl:Perl:• http://www.soaplite.com/http://www.soaplite.com/