Using SOAP and Web Services with Ensemble - InterSystems ...

intersystems.com

Using SOAP and Web Services with Ensemble - InterSystems ...

Using SOAP and WebServices with EnsembleVersion 2008.207 October 2008InterSystems Corporation 1 Memorial Drive Cambridge MA 02142 www.intersystems.com


Using SOAP and Web Services with EnsembleInterSystems Version 2008.2 07 October 2008Copyright © 2008 InterSystems CorporationAll rights reserved.This book was assembled and formatted in Adobe Page Description Format (PDF) using tools and information fromthe following sources: Sun Microsystems, RenderX, Inc., Adobe Systems, and the World Wide Web Consortium atwww.w3c.org. The primary document development tools were special-purpose XML-processing applications builtby InterSystems using Caché and Java.andCaché WEBLINK, Distributed Cache Protocol, M/SQL, N/NET, and M/PACT are registered trademarks of InterSystemsCorporation.andInterSystems TrakCare, InterSystems Jalapeño Technology, Enterprise Cache Protocol, ECP, and InterSystemsZen are trademarks of InterSystems Corporation.All other brand or product names used herein are trademarks or registered trademarks of their respective companiesor organizations.This document contains trade secret and confidential information which is the property of InterSystems Corporation,One Memorial Drive, Cambridge, MA 02142, or its affiliates, and is furnished for the sole purpose of the operationand maintenance of the products of InterSystems Corporation. No part of this publication is to be used for any otherpurpose, and this publication is not to be reproduced, copied, disclosed, transmitted, stored in a retrieval system ortranslated into any human or computer language, in any form, by any means, in whole or in part, without the expressprior written consent of InterSystems Corporation.The copying, use and disposition of this document and the software programs described herein is prohibited exceptto the limited extent set forth in the standard software license agreement(s) of InterSystems Corporation coveringsuch programs and related documentation. InterSystems Corporation makes no representations and warrantiesconcerning such software programs other than those set forth in such standard software license agreement(s). Inaddition, the liability of InterSystems Corporation for any losses or damages relating to or arising out of the use ofsuch software programs is limited in the manner set forth in such standard software license agreement(s).THE FOREGOING IS A GENERAL SUMMARY OF THE RESTRICTIONS AND LIMITATIONS IMPOSED BYINTERSYSTEMS CORPORATION ON THE USE OF, AND LIABILITY ARISING FROM, ITS COMPUTERSOFTWARE. FOR COMPLETE INFORMATION REFERENCE SHOULD BE MADE TO THE STANDARD SOFTWARELICENSE AGREEMENT(S) OF INTERSYSTEMS CORPORATION, COPIES OF WHICH WILL BE MADE AVAILABLEUPON REQUEST.InterSystems Corporation disclaims responsibility for errors which may appear in this document, and it reserves theright, in its sole discretion and without notice, to make substitutions and modifications in the products and practicesdescribed in this document.For Support questions about any InterSystems products, contact:InterSystems Worldwide Customer SupportTel: +1 617 621-0700Fax: +1 617 374-9391Email: support@InterSystems.com


Table of ContentsAbout This Book ................................................................................................................................ 11 About SOAP and Web Services ..................................................................................................... 31.1 Ensemble Support for Web Services ...................................................................................... 31.2 Ensemble Support for Web Clients ........................................................................................ 51.2.1 The SOAP Client Wizard ............................................................................................. 51.2.2 The Proxy Client .......................................................................................................... 61.2.3 The Business Operation of an Ensemble Web Client .................................................. 71.3 Specific Standards Supported in Ensemble ........................................................................... 82 Creating an Ensemble Web Service .............................................................................................. 92.1 Overall Behavior .................................................................................................................... 92.2 Basic Requirements ............................................................................................................. 112.2.1 Development Tasks .................................................................................................... 112.2.2 Configuration Tasks ................................................................................................... 132.3 Defining Web Methods for Use in Ensemble ...................................................................... 142.3.1 Basic Steps of a Web Method .................................................................................... 142.3.2 Returning Faults to the Caller .................................................................................... 152.3.3 Example ..................................................................................................................... 162.3.4 Note About Class Queries .......................................................................................... 162.4 Implementing the OnProcessInput Method ......................................................................... 172.4.1 Creating Request and Response Classes .................................................................... 182.4.2 Using the SendRequestSync Method ......................................................................... 182.4.3 Using the SendRequestAsync Method ...................................................................... 192.4.4 Example ..................................................................................................................... 192.5 Viewing the WSDL .............................................................................................................. 202.6 Example ............................................................................................................................... 212.7 Creating a Switch in OnProcessInput .................................................................................. 232.8 Enabling SOAP Sessions ..................................................................................................... 242.9 Additional Options ............................................................................................................... 243 Creating an Ensemble Web Client .............................................................................................. 273.1 Overview .............................................................................................................................. 273.2 Basic Steps ........................................................................................................................... 293.2.1 Development Tasks .................................................................................................... 293.2.2 Configuration Tasks ................................................................................................... 293.3 Using the SOAP Client Wizard ............................................................................................ 303.3.1 Generated Classes and XMLKEEPCLASS ............................................................... 303.3.2 Using the Process Method ......................................................................................... 30Using SOAP and Web Services with Ensembleiii


3.4 Available Runtime Settings .................................................................................................. 323.4.1 Specifying Basics ....................................................................................................... 323.4.2 Specifying Credentials ............................................................................................... 323.4.3 Specifying an SSL Configuration .............................................................................. 333.4.4 Specifying a Proxy Server ......................................................................................... 343.5 Generated Classes for an Ensemble Web Client .................................................................. 343.6 Creating a Business Operation Class Manually ................................................................... 373.6.1 Basic Requirements of the Class ............................................................................... 373.6.2 Basic Requirements of the Methods .......................................................................... 383.6.3 Ways to Execute the Proxy Methods ......................................................................... 383.6.4 Reference Information ............................................................................................... 40Appendix A: Common Tasks in the Ensemble Management Portal ........................................... 43A.1 Adding a Business Host to a Production ............................................................................. 43A.2 Enabling a Business Host .................................................................................................... 44A.3 Editing Other Runtime Settings .......................................................................................... 44A.4 Creating Ensemble Credentials ........................................................................................... 45Appendix B: Customizing Startup and Teardown ....................................................................... 47B.1 Callback Methods ................................................................................................................ 47B.2 The Startup Sequence .......................................................................................................... 48B.3 The Teardown Sequence ...................................................................................................... 48Appendix C: Using the SOAP Inbound Adapter .......................................................................... 51C.1 Notes .................................................................................................................................... 51C.2 Development Tasks .............................................................................................................. 52C.3 Configuration Tasks ............................................................................................................. 52C.4 Settings of the Inbound Adapter .......................................................................................... 53Index ................................................................................................................................................. 55ivUsing SOAP and Web Services with Ensemble


List of TablesBasic Web Service Parameters .......................................................................................................... 12Common Properties of %SOAP.WSDL.Reader ................................................................................ 31Using SOAP and Web Services with Ensemblev


About This BookThis book describes how an Ensemble programmer can create Ensemble Web services and EnsembleWeb clients. You should be reasonably familiar with SOAP and Web services.This book contains the following chapters:• About SOAP and Web Services• Creating an Ensemble Web Service• Creating an Ensemble Web ClientThis book also contains the following appendixes:• Common Tasks in the Ensemble Management Portal• Customizing Startup and Teardown• Using the SOAP Inbound AdapterThere is also a detailed Table of Contents.For more information, try the following sources:• Developing Ensemble Productions describes how to create Ensemble productions in general.• Managing Ensemble Productions includes information on monitoring and correcting the statusof Ensemble adapters. It also includes information on common settings used in all business hosts.Using SOAP and Web Services with Ensemble 1


1About SOAP and Web ServicesEnsemble provides support for SOAP 1.1 (Simple Object Access Protocol). This support is easy touse, efficient, and fully compatible with the SOAP specification. This support is built into Ensembleand does not require any complex middleware or operating system extensions. It is available on everyplatform supported by Ensemble.Using Ensemble SOAP support, you can do the following:• Add a Web service to an Ensemble production in order to provide a SOAP-enabled front end tothe production. Client applications can invoke this Ensemble Web service by using the SOAPprotocol. Such methods can be discovered and invoked by other SOAP-aware applications.Ensemble runs SOAP methods directly within the database; the execution is highly efficient.• Add a Web client to an Ensemble production. You can use a tool to generate a business operationand the proxy client classes, given the existing WSDL document of the Web service you want touse. The Ensemble Web client invokes the external Web service via the Ensemble SOAP outboundadapter and a generated proxy client class.This chapter discusses the following topics:• An overview of Ensemble support for Web service• An overview of Ensemble support for Web clients• Where to find information on specific standards supported by Ensemble1.1 Ensemble Support for Web ServicesYou can provide a SOAP-enabled front end for your Ensemble production. To do so, you create anEnsemble Web service, which is both a Web service and an Ensemble business service. Internally,Using SOAP and Web Services with Ensemble 3


About SOAP and Web Servicesyour Web methods generally receive SOAP request messages, use them to construct and sendEnsemble request messages as needed within the production, receive the Ensemble response messages,and use them to construct SOAP response messages.To enable you to create an Ensemble Web service, Ensemble provides the base Ensemble Web serviceclass (EnsLib.SOAP.Service), as well as supporting classes in the %SOAP and %XML packages.Ensemble provides powerful, built-in support for Web services. The base Ensemble Web service classdoes the following for you:• Validates incoming SOAP messages.• Unpacks SOAP messages, converts data to Ensemble representation, and invokes the correspondingmethod, which sends an Ensemble request message to a destination inside the production.• Runs the method.• Receives an Ensemble response message and then constructs and returns a response message (aSOAP message) to the caller.The SOAP specification does not include session support. However, it is often useful to maintain asession between a Web client and the Web service that it uses. You can do this with an Ensemble Webservice. If a Web service uses sessions, it establishes a session ID and allows repeated calls on theservice after one successfully authenticated call from a client.The Ensemble Web service class also provides the full functionality of any Ensemble business service.Note:To create an Ensemble Web service, you do not use an Ensemble adapter.4 Using SOAP and Web Services with Ensemble


1.2 Ensemble Support for Web ClientsEnsemble Support for Web ClientsYou can invoke an external Web service from within an Ensemble production. To do so, you createan Ensemble Web client.At a high level, your Ensemble Web client receives Ensemble requests, converts them to SOAP requestsand sends them to the appropriate Web service. Similarly, it receives SOAP responses and convertsthem into Ensemble responses.The Ensemble Web client consists of the following parts, all of which you can generate in Studio byusing the SOAP client wizard:• A proxy client class that defines a proxy method for each method defined by the Web service. Thepurpose of the proxy client is to specify the location of the Web service and to contain the proxymethods. Each proxy method uses the same signature used by the corresponding Web servicemethod and invokes that method when requested.• A business operation that uses the Ensemble SOAP outbound adapter to invoke the proxy methods.• Supporting classes as needed to define XML types and Ensemble messages.1.2.1 The SOAP Client WizardIn order to understand these parts, it is useful to consider how they are generated. First, when you usethe SOAP client wizard, you provide the URL for the WSDL of the Web service of interest. The wizardreads the WSDL and then generates a set of classes.Using SOAP and Web Services with Ensemble 5


About SOAP and Web Services1.2.2 The Proxy ClientThe generated classes include the proxy client class that defines a proxy method for each method ofthe Web service. Each proxy method sends a SOAP request to the Web service (as shown below) andreceives the corresponding SOAP response.6 Using SOAP and Web Services with Ensemble


Ensemble Support for Web ClientsAs shown in the figure, the generated classes also include classes that define any XML types neededas input or output for the methods.1.2.3 The Business Operation of an Ensemble Web ClientThe wizard also gives you the option of generating a business operation class that invokes the proxyclient, as well as classes that define message types as needed. The following figure shows how theseclasses work:Using SOAP and Web Services with Ensemble 7


About SOAP and Web ServicesThe classes and methods shown within dashed lines are all generated by the SOAP client wizard.The business operation uses the SOAP outbound adapter, which provides useful runtime settings andthe generic method InvokeMethod. To invoke a proxy method in the proxy client class, the businessoperation class calls InvokeMethod, passing to it the name of the method to run, as well as anyarguments. In turn, InvokeMethod calls the method of the proxy client class.1.3 Specific Standards Supported in EnsembleFor information on the specific standards followed by the Caché/Ensemble support for SOAP andWeb services, see the book Using SOAP and Web Services with Caché in the Caché documentationset.Also see Using SOAP and Web Services with Caché for WSDL limitations in the Caché/Ensemblesupport for Web services.8 Using SOAP and Web Services with Ensemble


2Creating an Ensemble Web ServiceThis chapter describes how to create an Ensemble Web service, which is a Web service in an Ensembleproduction. When you do this, you are providing a SOAP-enabled interface to the production. Thischapter discusses the following:• Overall behavior of an Ensemble Web service• Basic requirements for creating one• How to define Web methods within an Ensemble Web service• How to implement the OnProcessInput method of an Ensemble Web service• How to view the WSDL for your Web service that Ensemble automatically generates and publishesfor• A simple example• How to create a switch inside OnProcessInput method if you want to address different destinations,depending on the Web method called• How to enable SOAP sessions• A summary of ways you can fine-tune the Web methods in your Ensemble Web service2.1 Overall BehaviorAn Ensemble Web service is based on EnsLib.SOAP.Service or a subclass. This class extends bothEns.BusinessService (so that it is an Ensemble business service) and %SOAP.WebService (so that itcan act as a Web service as well). An Ensemble Web service behaves as follows:Using SOAP and Web Services with Ensemble 9


Creating an Ensemble Web Service• Because it is a Web service, it has a WSDL document (generated automatically) that describesthe Web methods available in it. The service can receive any SOAP message that conforms to theWSDL and sends SOAP responses in return.• Because it is an Ensemble business service, it is an integral part of the Ensemble production towhich you add it. Monitoring, error logging, runtime parameters, and all the rest of the Ensemblemachinery are available as usual.Note:An Ensemble Web service is not available unless the production is running (and thebusiness service is enabled).In contrast to most other Ensemble inbound interfaces, the ProcessInput method of the business serviceis not invoked automatically. This means that your Web methods must invoke this method as appropriate,passing to it the appropriate request Ensemble message and receiving an Ensemble responsemessage. You can define any message that you need.The ProcessInput method of the Web service performs required internal activities and then invokesthe OnProcessInput method of the business service, passing to in whatever Ensemble request messageit received. The OnProcessInput method is an empty callback method; you customize it to send therequest message to some destination within Ensemble.The following figure shows the overall flow of request messages:10 Using SOAP and Web Services with Ensemble


Basic RequirementsCommunication with the outside world is done via SOAP request and response messages. Ensemblerequest and response messages are used within the production. For the Ensemble messages, the precedingfigure shows only the requests; the responses are returned by the same path, in reverse.2.2 Basic RequirementsTo create a Web service in an Ensemble production, you create a new business service class, add it toyour production, and configure it.2.2.1 Development TasksImportant:InterSystems recommends that you do not place custom code or data in the systemprovidednamespaces ENSLIB or ENSDEMO where it will be deleted the next timeyou upgrade Ensemble. The ENSEMBLE namespace and any new namespace thatyou create to hold your work is preserved across Ensemble upgrades.Using SOAP and Web Services with Ensemble 11


Creating an Ensemble Web ServiceIn the Ensemble Studio, write and compile a new business service class. The following list describesthe basic requirements:• Your class should extend EnsLib.SOAP.Service. This class extends both Ens.BusinessService (sothat it is an Ensemble business service) and %SOAP.WebService (so that it can act as a Web serviceas well).• The class should define the ADAPTER parameter as null ("").• The class should specify values for other parameters:Basic Web Service ParametersItemSERVICENAME parameterLOCATION parameterNAMESPACE parameterTYPENAMESPACEparameterRESPONSENAMESPACEparameterDescriptionName of the Web service. This name must start witha letter and must contain only alphanumericcharacters.The default service name is"MyEnsembleRequestWebService"URI for invoking the Web service. This can beabsolute or can be relative to the WSDL request URL.For example:"http://localhost/csp/MyEnsemble/MyProduction/MyWebService.cls"The default is null.URI that defines the target XML namespace for yourWeb service, so that your service, and its contents,do not conflict with another service. This is initiallyset to http://tempuri.org which is a temporaryURI used by SOAP developers during development.XML namespace for the schema in the types definedby the Web service. If you do not specify thisparameter, the schema is in the namespace givenby NAMESPACE instead.URI that defines the XML namespace for theresponse messages. By default, this is equal to thenamespace given by the NAMESPACE parameter.• The class should define Web methods, as described in the next section.• The class should implement the OnProcessInput method, as described in “Implementing theOnProcessInput Method.”12 Using SOAP and Web Services with Ensemble


• The class can optionally implement any or all of the startup and teardown methods: OnInit,OnTearDown, OnProductionStart, and OnProductionStop.The following example shows in general what the class might look like:Class ESOP.Shell Extends EnsLib.SOAP.Service{Parameter ADAPTER="";Parameter NAMESPACE = "http://www.myapp.org";Parameter SERVICENAME = "MyServiceName";///This is the Web method exposed to the outside world;///It receives a SOAP request message and sends an Ensemble///request message to ProcessInputMethod MyWebMethod() As ResponseType [WebMethod]{///implement your method here;///call ..ProcessInput}///This method is called by ProcessInput and forwards///an Ensemble request message to a business host in the production///(and receives and returns an Ensemble response reply)Method OnProcessInput(pInput As %RegisteredObject,ByRef pOutput As %RegisteredObject) As %Status{//call basic web service method to send message received from Web method//for exampleQuit ..SendRequestSync("ConfigName",pInput,.pOutput)}}Basic Requirements2.2.2 Configuration TasksTo add your Ensemble Web service (a business service) to an Ensemble production, use the EnsembleManagement Portal to do the following:1. Add an instance of your custom class to the Ensemble production.Important:Ensure that the configuration name is the same as the full class name, includingpackage. This is a requirement for running an Ensemble Web service.2. Enable the business service.3. Set the PoolSize setting to 0.For other settings, see the book Managing Ensemble Productions.4. Run the production.If you are not familiar with the Ensemble Management Portal, see the appendix “Common Tasks inthe Ensemble Management Portal.”Using SOAP and Web Services with Ensemble 13


Creating an Ensemble Web Service2.3 Defining Web Methods for Use in EnsembleYou can use an instance method or a class method as a Web method for use in Ensemble. This sectiondescribes the basic requirements, as well as the steps generally included in an Ensemble Web method.• Define the method within a subclass of EnsLib.SOAP.Service, as described in “Basic Requirements.”• Mark the method with the WebMethod keyword.• Ensure that all arguments and return values are XML-enabled:- If the method uses an object as an argument or a return value, you must ensure that the objectis XML-enabled. That is, the class definitions for the types must extend %XML.Adaptor. Thedefault settings for this class are normally suitable; if not, see Using XML with Caché.- If the method uses a data set as an argument or return value, you must ensure the data set isof type %XML.DataSet, which is an XML-enabled subclass of the standard %ResultSet.- To use a collection (%ListOfObjects or %ArrayOfObjects) as an argument or a return value,you must ensure that the ELEMENTTYPE parameter of the collection is set and refers to anXML-enabled class.2.3.1 Basic Steps of a Web MethodWithin an Ensemble Web service, a Web method should generally do the following:1. Construct an Ensemble request message and set its properties with received in the inbound SOAPmessage.2. Invoke the ProcessInput method of the Web service, passing the request message to it.3. Check the status returned by the ProcessInput method and react appropriately.4. Then:• In the case of success, look at the Ensemble response message that is returned by referenceand use it to construct the return value of the Web method. As noted previously, the returnvalue must be XML-enabled so that it can be packaged as a SOAP response.• In the case of failure, call the ReturnMethodStatusFault or ReturnStatusFault method ofthe Web service; see the next section for details.The ProcessInput method has the following signature:14 Using SOAP and Web Services with Ensemble


Method OnProcessInput(pInput As %RegisteredObject,ByRef pOutput As %RegisteredObject,ByRef pHint As %String) As %StatusHere:1. pInput is the Ensemble request message that you are sending.2. pOutput is the Ensemble response message that is sent in return.Defining Web Methods for Use in Ensemble3. pHint is an optional string that you can use to identify the Ensemble request; see the section“Creating a Switch in OnProcessInput,” later in this chapter.2.3.2 Returning Faults to the CallerBy default, if an error occurs when ProcessInput runs, the Web service returns a SOAP message tothe caller, but the SOAP message does not indicate where precisely the fault occurred. An examplefollows:SOAP-ENV:ServerServer Application ErrorERROR #5002: Cache error: zGetCustomerInfo+10^ESOP.WebService.1Your Web methods should check for an error and use ReturnMethodStatusFault orReturnStatusFault. In case of error, the message will be more informative, as follows:SOAP-ENV:MethodServer Application ErrorESOP.WebServiceERROR ErrException:zGetCustomerRequest+8^ESOP.MyOperation.1 -logged as '13 Jul 2007' number 4 @'set x=100/0'The ReturnMethodStatusFault and ReturnStatusFault methods return a SOAP fault to the callerand then trap the error. These methods have the following signatures:ClassMethod ReturnStatusFault(pCode As %String,pStatus As %Status)ClassMethod ReturnMethodStatusFault(pStatus As %Status)Using SOAP and Web Services with Ensemble 15


Creating an Ensemble Web ServiceHere:• pCode is a string that represents the error code to use in the element of the SOAPfault. The ReturnMethodStatusFault method uses the generic error code SOAP-ENV:Method• pStatus is the status to use in the returned SOAP fault. This is used to construct the details of theSOAP fault.Also notice that these methods set the element of the SOAP fault.2.3.3 ExampleThe following shows a simple example:Method GetCustomerInfo(ID As %Numeric)As ESOP.SOAPResponse [WebMethod]{//create Ensemble request message with given IDset request=##class(ESOP.CustomerRequest).%New()set request.CustomerID=ID//send Ensemble request message//ProcessInput calls OnProcessInput, which actually//sends the messageset sc=..ProcessInput(request,.response,"GetCustomerInfo")if $$$ISERR(sc) do ..ReturnMethodStatusFault(sc)//use info from Ensemble response to create SOAP responseset soapresponse=##class(ESOP.SOAPResponse).%New()set soapresponse.CustomerID=response.CustomerIDset soapresponse.Name=response.Nameset soapresponse.Street=response.Streetset soapresponse.City=response.Cityset soapresponse.State=response.Stateset soapresponse.Zip=response.Zip}quit soapresponse2.3.4 Note About Class QueriesYou can also use a class query as a Web method, if the class query is defined within a subclass ofEnsLib.SOAP.Service. To do so, mark the query with the WebMethod keyword. In practice, this maybe less useful within an Ensemble production, because the class query has no way to call theProcessInput method of the Web service, and thus no has no way to communicate with the rest of theproduction. Therefore, this book does not discuss this option.16 Using SOAP and Web Services with Ensemble


Implementing the OnProcessInput Method2.4 Implementing the OnProcessInput MethodYour custom business service class should implement the OnProcessInput method, which forwardsthe Ensemble request as appropriate within the production. The OnProcessInput method should havethe following signature:Method OnProcessInput(pInput As %RegisteredObject,ByRef pOutput As %RegisteredObject,ByRef pHint As %String) As %StatusHere:1. pInput is the Ensemble request message that you are sending.2. pOutput is the Ensemble response message that is sent in return.3. pHint is an optional string that you can use to decide how to handle the Ensemble request; see thesection “Creating a Switch in OnProcessInput,” later in this chapter.The OnProcessInput method should do some or all of the following:1. Create a request message (an instance of Ens.Request or a subclass), which will be the messagethat your business service sends. Or simply forward the input that the business service receives.For information on creating messages, see the subsection “Creating Request and ResponseClasses.”2. Call a suitable method of the business service to send the request to some destination within theproduction. Specifically, call one of the following inherited methods, as appropriate for yourneeds:• SendRequestSync sends a message synchronously (waits for a response). For details, seethe subsection “Using the SendRequestSync Method.”• SendRequestAsync sends a message asynchronously (does not wait for a response). Fordetails, see the subsection “Using the SendRequestAsync Method.”• SendDeferredResponse sends a response that was previously deferred. This method is lesscommonly used. For details, see the book Developing Ensemble Productions.Each of these methods returns a status (specifically, an instance of %Status).3. Make sure that you set the output argument (pOutput). Typically you set this equal to the responsemessage that you have received.4. Return an appropriate status. This step is required.The following shows an example:Using SOAP and Web Services with Ensemble 17


Creating an Ensemble Web ServiceMethod OnProcessInput(pInput As %RegisteredObject,ByRef pOutput As %RegisteredObject) As %Status{set sc= ..SendRequestSync("Lookup",pInput,.pOutput)Quit sc}This Web method does not construct a request message; it just forwards the input that the businessservice receives (pInput). Although it is compact, the Web method does perform the other three tasksdescribed in the previous list.2.4.1 Creating Request and Response ClassesAs noted earlier, your custom OnProcessInput method typically constructs a request message andsends it.• A request message is an instance of a subclass of Ens.Request and has properties to contain thedata of your request.• A response message is an instance of a subclass of Ens.Response and has properties to containthe data of the response.You will need to define each of these subclasses, as appropriate for your needs.2.4.2 Using the SendRequestSync MethodTo send a synchronous request, use the SendRequestSync method as follows:Set tSC = ..SendRequestSync(pTargetDispatchName, tRequest, .tResponse)This method takes the following arguments:• pTargetDispatchName — The configuration name of the business process or business operationto which the request is sent.• pRequest — Any persistent object, but typically a subclass of Ens.Request. This object containsthe data to send with the request.• pResponse — (By reference) Any persistent object, but typically a subclass of Ens.Response.This object receives the data returned by the response.• pTimeout — (Optional) The number of seconds to wait for a response. The default is -1 (waitforever).This method returns a status (an instance of %Status).If no response is expected, you can use SendRequestAsync instead of SendRequestSync.18 Using SOAP and Web Services with Ensemble


2.4.3 Using the SendRequestAsync MethodTo send an asynchronous request, use the SendRequestAsync method as follows:Set tSC = ..SendRequestAsync(pTargetDispatchName, tRequest)This method takes the following arguments:• pTargetDispatchName — The configuration name of the business process or business operationto which the request is sent.• tRequest — Any persistent object, but typically a subclass of Ens.Request. This object containsthe data to send with the request.This method returns a status (an instance of %Status).2.4.4 ExampleSuppose that you created an Ensemble Web service that could be used to look up customer information,given a customer ID. To transport request messages, you might use a class like the following:Class ESOP.CustomerRequest Extends Ens.Request [ClassType=persistent]{Property CustomerID As %Numeric;}To transport the corresponding responses, you might use a class like the following:Class ESOP.CustomerResponse Extends Ens.Response [ClassType=persistent]{Property CustomerID As %Numeric;Property Name As %String;Property Street As %String;Property City As %String;Property State As %String;Property Zip As %Numeric;}Implementing the OnProcessInput MethodYour custom OnProcessInput method sends the request message to another destination within theproduction — a business host that performs the lookup.Using SOAP and Web Services with Ensemble 19


Creating an Ensemble Web ServiceMethod OnProcessInput(pInput As %RegisteredObject,ByRef pOutput As %RegisteredObject) As %Status{set sc= ..SendRequestSync("Lookup",pInput,.pOutput)Quit sc}2.5 Viewing the WSDLEnsemble automatically creates and publishes a WSDL document that describes your Ensemble Webservice. Whenever you modify and recompile the Web service, Ensemble automatically updates theWSDL correspondingly.To view the WSDL for the Web service, use the following URL:base/app-name/web_serv.cls?WSDLHere base is the base URL for your Web server (including port if necessary), /csp/app is the name ofthe CSP application in which the Web service resides, and web_serv is the class name of the Webservice. (Typically, /csp/app is /csp/namespace, where namespace is the Ensemble namespace thatcontains the CSP application. )For example:http://localhost:57772/csp/samples/MyApp.StockService.cls?WSDLThe browser displays the WSDL document as an XML document. The following shows an example:20 Using SOAP and Web Services with Ensemble


Example2.6 ExampleThe following simple example shows an Ensemble Web service that can be used to look up customerinformation, given a customer ID.Class ESOP.WebService Extends EnsLib.SOAP.Service{Parameter ADAPTER;Parameter NAMESPACE = "http://www.myapp.org";Parameter SERVICENAME = "CustomerLookupService";Method GetCustomerInfo(ID As %Numeric) As ESOP.SOAPResponse [WebMethod]{//create Ensemble request message with given IDset request=##class(ESOP.CustomerRequest).%New()set request.CustomerID=ID//send Ensemble request message//ProcessInput calls OnProcessInput, which actually//sends the messageset sc=..ProcessInput(request,.response,"GetCustomerInfo")if $$$ISERR(sc) do ..ReturnMethodStatusFault(sc)//use info from Ensemble response to create SOAP responseset soapresponse=##class(ESOP.SOAPResponse).%New()Using SOAP and Web Services with Ensemble 21


Creating an Ensemble Web Serviceset soapresponse.CustomerID=response.CustomerIDset soapresponse.Name=response.Nameset soapresponse.Street=response.Streetset soapresponse.City=response.Cityset soapresponse.State=response.Stateset soapresponse.Zip=response.Zip}quit soapresponseMethod OnProcessInput(pInput As %RegisteredObject,ByRef pOutput As %RegisteredObject) As %Status{set sc= ..SendRequestSync("Lookup",pInput,.pOutput)Quit sc}}The SOAP response class is as follows:///Class ESOP.SOAPResponse Extends (%RegisteredObject, %XML.Adaptor){Property CustomerID As %Numeric;Property Name As %String;Property Street As %String;Property City As %String;Property State As %String;Property Zip As %Numeric;}Note the following points:• The example Web method (GetCustomerInfo) receives an Ensemble response message anduses it to construct a SOAP response message.• The SOAP response class has the same properties as the corresponding Ensemble response class.Unlike the Ensemble response, however, the SOAP response class is XML-enabled and non-persistent.• The OnProcessInput method just sends the Ensemble request message and returns the responseand status, without adding any further logic.• OnProcessInput sends all requests to a business host named Lookup, which performs the actuallookup. Lookup is not important for this example and is not shown in this book.• This Web service can receive only one type of SOAP message (a lookup request that contains acustomer ID). A more complex Web service would receive multiple types of SOAP messages,and would probably route each type to a different business host within the production. The followingsection describes how to do this.22 Using SOAP and Web Services with Ensemble


Creating a Switch in OnProcessInput2.7 Creating a Switch in OnProcessInputUntil now this chapter has considered only a Web service that defines a single Web method. If yourWeb service defines multiple methods, you may want to send them to different destinations within theproduction. To do so, you can use the optional hint argument of the ProcessInput and OnProcessInputmethods. The procedure is as follows:1. In each Web method, when you invoke ProcessInput, provide a hint argument that indicateswhich Web method is making this call. For example, provide the name of the method itself.2. Include the hint argument in the signature of OnProcessInput and use this argument to determinethe flow.For example, suppose that the previous example Web service defined two methods:• GetCustomerInfo, which should be sent to the GetCustomerInfoBO business operation.• GetStoreInfo, which should be sent to the GetStoreInfoBO business operation.To set up this logic, the methods would provide a hint when they called OnProcessInput. For example:Method GetCustomerInfo(ID As %Numeric) As ESOP.SOAPResponse [ WebMethod ]{//create Ensemble request message with given IDset request=##class(ESOP.CustomerRequest).%New()set request.CustomerID=ID//send Ensemble request message//ProcessInput calls OnProcessInput, which actually//sends the messageset sc=..ProcessInput(request,.response,"GetCustomerInfo")if $$$ISERR(sc) do ..ReturnMethodStatusFault(sc)//use info from Ensemble response to create SOAP responseset soapresponse=##class(ESOP.SOAPResponse).%New()set soapresponse.CustomerID=response.CustomerIDset soapresponse.Name=response.Nameset soapresponse.Street=response.Streetset soapresponse.City=response.Cityset soapresponse.State=response.Stateset soapresponse.Zip=response.Zip}quit soapresponseAnd the OnProcessInput method could use the hint as follows:Using SOAP and Web Services with Ensemble 23


Creating an Ensemble Web ServiceMethod OnProcessInputAlt(pInput As %RegisteredObject,ByRef pOutput As %RegisteredObject, pHint As %String) As %Status{if pHint="GetCustomerInfo"{set sc= ..SendRequestSync("GetCustomerInfoBO",pInput,.pOutput)}elseif pHint="GetStoreInfo" {set sc= ..SendRequestSync("GetStoreInfoBO",pInput,.pOutput)}Quit sc}Or, because the business operation has the same name as the corresponding Web method, with BOappended to it, you could use this instead:Method OnProcessInput(pInput As %RegisteredObject,ByRef pOutput As %RegisteredObject, pHint As %String) As %Status{set sc= ..SendRequestSync($Get(pHint)_"BO",pInput,.pOutput)Quit sc}2.8 Enabling SOAP SessionsThe SOAP specification does not include session support. However, it is often useful to maintain asession between a Web client and the Web service that it uses. You can do this with an Ensemble Webservice. If a Web service uses sessions, it establishes a session ID and allows repeated calls on theservice after one successfully authenticated call from a client.Support for SOAP sessions is controlled by the SOAPSESSION class parameter. The default is 0, whichmean that the Web service does not use sessions.To enable SOAP sessions, create a subclass of EnsLib.SOAP.Service and set SOAPSESSION to 1 inthe subclass. Base your Ensemble Web service on this subclass.For more information on SOAP sessions, see the book Using SOAP and Web Services with Caché inthe Caché documentation.2.9 Additional OptionsBecause your Ensemble Web service extends %SOAP.WebService, you can use all the SOAP supportprovided by that class. This support includes options for the following customizations, among others:• Customizing the SOAP headers• Passing attachments in the SOAP messages• Changing the binding style of the SOAP messages from document-style (the default) to rpc-style24 Using SOAP and Web Services with Ensemble


• Changing the encoding style of the messages from literal (the default) to SOAP-encoded• Customizing the XML types used in the SOAP messages• Customizing the SOAPAction header used to invoke a Web method• Controlling whether elements are qualified (controlling the elementFormDefault attribute of theWeb service)• Controlling the form of null arguments (to be an empty element rather than omitted)• Writing the Web method to have output parameters instead of return valuesAdditional OptionsFor these options and others, see Using SOAP and Web Services with Caché in the Caché documentationset.Using SOAP and Web Services with Ensemble 25


3Creating an Ensemble Web ClientThis chapter describes how to create an Ensemble Web client. At a high level, your Ensemble Webclient receives Ensemble requests from elsewhere within the production, converts them to SOAPrequests, and sends them to the appropriate Web service. Similarly, it receives SOAP responses, convertsthem into Ensemble responses, and sends them back within the production. This chapter discusses thefollowing topics:• An overview of the parts of an Ensemble Web client• The basic steps to create an Ensemble Web client• Details on how to use the SOAP client wizard to generate the classes needed for an EnsembleWeb client• Available runtime settings for the Ensemble Web client• Information on the classes generated by the SOAP client wizard• Details on how to create your own business operation class manually, rather than using the classgenerated by the SOAP client wizard3.1 OverviewAn Ensemble Web client consists of the following parts:• A proxy client class that defines a proxy method for each method defined by the Web service.Each proxy method uses the same signature used by the corresponding Web service method andinvokes that method when requested.• A business operation that uses the Ensemble SOAP outbound adapter to invoke the proxy client.Using SOAP and Web Services with Ensemble 27


Creating an Ensemble Web Client• Supporting classes as needed to define XML types and Ensemble messages.The following figure shows how the business operation, adapter, and proxy client class work together.Supporting classes are not shown here.In the preceding figure, all items within dashed lines can be generated by the SOAP client wizard inStudio. You can then edit this code as needed.For a more detailed look at these parts, see “Ensemble Support for Web Clients,” earlier in this book.28 Using SOAP and Web Services with Ensemble


Basic Steps3.2 Basic StepsThis section outlines the basic steps to create an Ensemble Web client. The steps include developmenttasks and then configuration tasks.3.2.1 Development TasksImportant:InterSystems recommends that you do not place custom code or data in the systemprovidednamespaces ENSLIB or ENSDEMO where it will be deleted the next timeyou upgrade Ensemble. The ENSEMBLE namespace and any new namespace thatyou create to hold your work is preserved across Ensemble upgrades.To create an Ensemble Web client, do the following within Studio:1. Use the SOAP client wizard to generate the business operation class, proxy client class, and supportingclasses. This tool is described in the next section of this chapter.2. Check whether you need to adjust the types of the inputs and outputs of the methods. In particular,if any of the methods of the Web service have inputs or outputs that could exceed 32K in length,and if you have not enabled support for long strings in Ensemble, you should change the types ofthose inputs or outputs to an appropriate stream class.3.2.2 Configuration TasksTo add your Ensemble Web client to an Ensemble production, use the Ensemble Management Portalto do the following:1. Add an instance of your custom business operation class to the Ensemble production, specificallythe business operation class generated by the SOAP client wizard.2. Enable the business operation.3. Specify appropriate values for the runtime settings of the associated adapter(EnsLib.SQL.OutboundAdapter), as discussed later in this chapter.4. Run the production.If you are not familiar with the Ensemble Management Portal, see the appendix “Common Tasks inthe Ensemble Management Portal” for information on these tasks.Using SOAP and Web Services with Ensemble 29


Creating an Ensemble Web Client3.3 Using the SOAP Client WizardTo use the SOAP client wizard to generate an Ensemble Web client, do the following:1. In Studio, make sure that you are in the appropriate Ensemble namespace.2. Click Tools —> Add-ins —> SOAP Client Wizard.3. On the first screen, enter the entire URL of the WSDL document for the Web service you wantto work with.4. Click Next.5. Click the check box to the left of Create Business Operation in Package. This option instructs thewizard to define a business operation class that invokes the proxy client, as well as message classesfor use with that business operation.6. For Create Business Operation in Package, optionally change the subpackage name from BusOpto another name.7. For Optional Package Name, type a package name for the proxy client and related classes. Thedefault package name is the service name. Also see the section “Generated Classes and XML-KEEPCLASS.”8. For Class Type, choose a general type for the proxy client class: persistent or serial (the default).9. Click Next. The wizard generates and compiles the classes and displays a list of these classes.10. Click Finish.3.3.1 Generated Classes and XMLKEEPCLASSThe SOAP client wizard generates a set of classes; the details of these classes are discussed later inthis chapter.You specify the package in which the tool should create the proxy client class and the supportingclasses. If this package is the same as an existing package, by default the tool will overwrite anyexisting classes that have the same name. To prevent the wizard from overwriting a class definition,add the XMLKEEPCLASS parameter to that class and set this parameter equal to 1.3.3.2 Using the Process MethodInstead of using the wizard, you can use the Process method of the %SOAP.WSDL.Reader class. Touse this method:1. Create an instance of %SOAP.WSDL.Reader.30 Using SOAP and Web Services with Ensemble


2. Optionally set properties to control the behavior of your instance.Common Properties of %SOAP.WSDL.ReaderUsing the SOAP Client WizardPropertyCompileFlagsMakePersistentMakeSerialOutputTypeAttributeMakeBusinessOperationPurposeSpecifies the flags to use when compiling thegenerated classes.The initial expression is "dk"; use$System.OBJ.ShowFlags() to get information on theavailable flags.If this property is 1, the proxy client is a persistentobject; otherwise, it is a registered object. The initialexpression is 0.If this property is 1 and if MakePersistent is 1, the proxyclient is a serial class. The initial expression is 0.Controls how the WSDL reader will set theOUTPUTTYPEATTRIBUTE parameter in the proxyclient that it generates; which controls the use of thexsi:type attribute in the SOAP messages. See UsingSOAP and Web Services with Caché in the Cachédocumentation set.Specifies whether to generate an Ensemble businessoperation and related request and response objects.The ADAPTER setting for this business operation isEnsLib.SOAP.OutboundAdapter. This option works onlyif you are working within an Ensemble-enablednamespace.For other properties, see the class documentation for %SOAP.WSDL.Reader.3. Invoke the Process method, providing the following arguments:• The first argument must be the URL of the WSDL of the Web service or the name of theWSDL file (including its complete path). Depending on the configuration of the Web service,it may be necessary to append a string that provides a suitable username and password; seethe examples.• The optional second argument is the name of the package in which the reader should placethe generated classes. If you do not specify a package, Caché uses the service name as thepackage name.Using SOAP and Web Services with Ensemble 31


Creating an Ensemble Web Client3.4 Available Runtime SettingsThis topic describes the runtime settings for your Ensemble Web client, which fall into several generalgroups:• Basic settings• Settings related to credentials• The setting that controls use of SSL• Settings that control the use of a proxy serverFor any settings not listed here, see the book Managing Ensemble Productions.3.4.1 Specifying BasicsThe following settings specify the basic information for the Ensemble Web client.WebServiceURL%StringSpecifies the URL where the Web service is located. If this setting is not given, the adapteruses the default location (the LOCATION parameter) declared in the proxy client class; seethe WebServiceClientClass setting. Note that SSL will only work if this URL uses https://WebServiceClientClass%StringSpecifies the full name (including package) of the proxy client class, specifically the classthat actually sends and receives SOAP messages to the Web service.Response Timeout%NumericSpecifies the timeout for getting a response from the remote Web server (the timeout foropening the connection to the server is always 5 seconds). The default value is 30.3.4.2 Specifying CredentialsThe Web service that you are accessing might require a username and password. In general, theEnsemble SOAP client can log into a Web service in either of the following ways:32 Using SOAP and Web Services with Ensemble


Available Runtime Settings• You can use WS-Security user authentication. In this case, you include a WS-Security header inthe SOAP request; this header includes the username and password. The proxy client automaticallydoes this if you specify a value for the SOAPCredentials setting.CAUTION:Ensure that you are using SSL between the Web client and the Web service. TheWS-Security header is sent in clear text, so this technique is not secure unlessSSL is used.• You can use basic HTTP user authentication, which is less secure than WS-Security but is sometimesrequired. In this case, you include the username and password in the HTTP header of theSOAP request. The proxy client automatically does this if you specify a value for the Credentialssetting.Use the technique that is appropriate for the Web service you are using.SOAPCredentials%StringCredentialsSpecify the ID of the Ensemble credentials that contain the username and password to beused in the WS-Security header of the SOAP request. For more information on WS-Securitysupport, see the book Using SOAP and Web Services with Caché in the Caché documentationset.%StringSpecify the ID of the Ensemble credentials that contain the username and password to beused in the HTTP header.For information on creating Ensemble credentials, see the appendix “Common Tasks in the EnsembleManagement Portal.”3.4.3 Specifying an SSL ConfigurationIf the Web server supports it, you can connect with SSL. To do so, specify a value for the followingruntime setting:SSLConfig%StringSpecifies the name of an existing SSL/TLS system configuration set to use, configured viathe System Management Portal.Using SOAP and Web Services with Ensemble 33


Creating an Ensemble Web ClientFor information on creating and managing SSL/TLS configurations, see the chapter “UsingSSL/TLS with Caché” in the Caché Security Administration Guide. The SSL/TLS configurationincludes an option called Configuration Name; this is the string to use in this setting.At the end of the SSLConfig string, you can add a vertical bar (|) followed by the private keypassword.Note:You must also ensure the Web service is at a URL that uses https://. The Webservice location is determined by the WebServiceURL setting; if this is not specified,the Ensemble Web client assumes the Web service is at the URL specified by theLOCATION parameter in proxy client class.3.4.4 Specifying a Proxy ServerYou can communicate with the Web service via a proxy server. To set this up, use the following runtimesettings:ProxyServerProxyPort%StringSpecifies the proxy server through which to send HTTP requests, if any.%IntegerProxyHTTPSSpecifies the proxy server port on which to send HTTP requests, if using a proxy server. Thedefault value is 80.%BooleanSpecifies whether the proxy (if any) uses HTTPS to communicate with the real HTTP/HTTPSserver.3.5 Generated Classes for an Ensemble WebClientThis section provides information about the classes that the SOAP client wizard generates.Consider a Web service named MyService that has the following details:34 Using SOAP and Web Services with Ensemble


• It is hosted at http://localhost:57772/csp/gsop/MyApp.AddService.CLS• The target XML namespace for the Web service is http://www.myapp.org• It defines a Web method named AddService, which accepts two complex numbers as argumentsand returns the result.Suppose that you use the SOAP client wizard to generate a Ensemble Web client for this Web service.If you specify the package for the client classes as MyClient, the SOAP client wizard will generatethe following classes and add them all to your current project:• It generates the MyClient.BusOp.MyServiceSoap class, which defines the business operation.Class MyClient.BusOp.MyServiceSoap Extends Ens.BusinessOperation{Parameter ADAPTER = "EnsLib.SOAP.OutboundAdapter";Generated Classes for an Ensemble Web ClientMethod Add(pRequest As MyClient.BusOp.AddRequest,Output pResponse As MyClient.BusOp.AddResponse) As %Library.Status{Set ..Adapter.WebServiceClientClass = "MyClient.MyServiceSoap"Set tSC = ..Adapter.InvokeMethod("Add",.AddResult,pRequest.a,pRequest.b) Quit:$$$ISERR(tSC) tSC}Set tSC = pRequest.NewResponse(.pResponse) Quit:$$$ISERR(tSC) tSCSet pResponse.AddResult=AddResultQuit $$$OKXData MessageMap{Add}}• It generates the MyClient.AddServiceSOAP class, the proxy client class:Class MyClient.AddServiceSoap Extends %SOAP.WebClient{/// This is the URL used to access the web service.Parameter LOCATION = "http://localhost:57772/csp/gsop/MyApp.AddService.cls";/// This is the namespace used by the ServiceParameter NAMESPACE = "http://www.myapp.org";/// Use xsi:type attribute for literal types.Parameter OUTPUTTYPEATTRIBUTE = 1;/// This is the name of the ServiceParameter SERVICENAME = "AddService";Method Add(a As MyClient.ComplexNumber, b As MyClient.ComplexNumber)As MyClient.ComplexNumber [ Final, ProcedureBlock = 1,SoapBindingStyle = document, SoapBodyUse = literal, WebMethod ]{Quit ..WebMethod("Add").Invoke(##this,"http://www.myapp.org/MyApp.AddService.Add",.a,.b)Using SOAP and Web Services with Ensemble 35


Creating an Ensemble Web Client}}• It generates the request and response message classes needed by the business operation. Therequest class is as follows:Class MyClient.BusOp.AddRequest Extends Ens.Request [ ClassType = persistent ]{Parameter RESPONSECLASSNAME = "MyClient.BusOp.AddResponse";Property a As MyClient.ComplexNumber;Property b As MyClient.ComplexNumber;}The response class is as follows:Class MyClient.BusOp.AddResponse Extends Ens.Response [ ClassType = persistent ]{Property AddResult As MyClient.ComplexNumber;}• Finally, it generates the MyClient.ComplexNumber class, which defines a complex numberand which is used by the other classes./// Created from: http://localhost:57772/csp/gsop/MyApp.AddService.CLS?WSDL=1Class MyClient.ComplexNumber Extends (%RegisteredObject, %XML.Adaptor){Parameter XMLNAME = "ComplexNumber";Parameter XMLSEQUENCE = 1;Property Real As %xsd.double(XMLNAME = "Real") [ SqlFieldName = _Real ];Property Imaginary As %xsd.double(XMLNAME = "Imaginary");}When you compile these classes, the compiler also generates a class for each method defined in theWeb service. These classes are not automatically added to your project and their internal details aresubject to change. These classes extend %SOAP.ProxyDescriptor, which you should never subclassyourself.36 Using SOAP and Web Services with Ensemble


Creating a Business Operation Class Manually3.6 Creating a Business Operation ClassManuallyRather than using the business operation class that the SOAP client wizard generates, you can createyour own class. This section describes how to do so. It discusses the following:• Basic requirements of the business operation class• Basic requirements of the methods in the business operation class• Specific techniques, with examples, for calling the proxy methods• Reference information for the adapter property and methods used hereImportant:InterSystems recommends that you do not place custom code or data in the systemprovidednamespaces ENSLIB or ENSDEMO where it will be deleted the next timeyou upgrade Ensemble. The ENSEMBLE namespace and any new namespace thatyou create to hold your work is preserved across Ensemble upgrades.3.6.1 Basic Requirements of the ClassThe following list describes the basic requirements of the business operation class• Your business operation class should extend Ens.BusinessOperation.• In your class, the ADAPTER parameter should equal EnsLib.SOAP.OutboundAdapter.• In your class, the INVOCATION parameter should specify the invocation style you want to use,which must be one of the following.- Queue means the message is created within one background job and placed on a queue, atwhich time the original job is released. Later, when the message is processed, a differentbackground job will be allocated for the task. This is the most common setting.- InProc means the message will be formulated, sent, and delivered in the same job in whichit was created. The job will not be released to the sender’s pool until the message is deliveredto the target. This is only suitable for special cases.• Your class should define one method for each method of the proxy client, as described in the followingsection.• Your class should define a message map that includes one entry for each method. A message mapis an XData block entry that has the following structure:Using SOAP and Web Services with Ensemble 37


Creating an Ensemble Web ClientXData MessageMap{methodname...}You will also need to define the Ensemble message classes that the business operation uses.3.6.2 Basic Requirements of the MethodsWithin your business operation class, your methods should invoke the proxy methods. Here the generalrequirements are as follows:1. The method should have the same signature as the proxy method that it is invoking.2. The method should be marked with the WebMethod keyword.3. The method should set the SoapBindingStyle and SoapBodyUse keywords as expected by theproxy client. (That is, use the same values as in the signature of the corresponding proxy method.)4. The method should set the WebServiceClientClass property of the adapter. When this property isset, a proxy client instance is created and placed in the %Client property of the adapter.5. The method should call the corresponding proxy method, using one of the techniques in the nextsection.6. The method should check the status.7. Then:• In the case of success, create a new response message (via the NewResponse method of therequest) and set its properties as appropriate.• In the case of failure, quit with the error.3.6.3 Ways to Execute the Proxy MethodsWithin your business operation, your methods should execute the proxy methods of the proxy clientclass. You can do this in multiple ways, which are best shown via an example. This section uses anexample Web service that has a Web method named GetStock that accepts a stock symbol (a string)and returns a number. Suppose that you have used the SOAP client wizard to generate a proxy client(GetStock.StockServiceSoap), which contains a method called GetStock.Also suppose that you have created message classes as follows:38 Using SOAP and Web Services with Ensemble


Class GetStock.BusOp.GetQuoteRequest Extends Ens.Request [ClassType=persistent]{Parameter RESPONSECLASSNAME = "GetStock.BusOp.GetQuoteResponse";Property StockName As %String;}AndClass GetStock.BusOp.GetQuoteRequest Extends Ens.Request [ClassType=persistent]{Parameter RESPONSECLASSNAME = "GetStock.BusOp.GetQuoteResponse";Property StockName As %String;}Creating a Business Operation Class ManuallyTo execute the proxy method GetStock, your business operation class can do any of the following:• Call the InvokeMethod method of the adapter and specify the name of the proxy method to run,as well as up to twelve arguments. In this case, there is only one argument (which we specify aspRequest.StockName). For example:Method GetQuote1(pRequest As GetStock.BusOp.GetQuoteRequest,Output pResponse As GetStock.BusOp.GetQuoteResponse) As %Status{set ..Adapter.WebServiceClientClass = "GetStock.StockServiceSoap"set status = ..Adapter.InvokeMethod("GetQuote",.answer,pRequest.StockName)if $$$ISERR(status) quit statusset pResponse=##class(GetStock.BusOp.GetQuoteResponse).%New()set pResponse.GetQuoteResult=answerquit $$$OK}When you use the SOAP client wizard to generate the business operation, it uses this method.• Access the %Client property of the adapter, which gives you an instance of the proxy client class,and execute the proxy method of that property. The %Client property is set when you set theWebServiceClientClass property. In this case, %Client has a method named GetQuote, whichaccepts a string stock symbol. For example:Method GetQuote2(pRequest As GetStock.BusOp.GetQuoteRequest,Output pResponse As GetStock.BusOp.GetQuoteResponse) As %Status{set ..Adapter.WebServiceClientClass = "GetStock.StockServiceSoap"set client=..Adapter.%Clientset answer=client.GetQuote("GRPQ")set pResponse=##class(GetStock.BusOp.GetQuoteResponse).%New()set pResponse.GetQuoteResult=answerquit $$$OK}Note that with this technique, you do not have access to the retry logic of Ensemble.Using SOAP and Web Services with Ensemble 39


Creating an Ensemble Web Client• Create a proxy method object by calling the WebMethod method of the adapter. Set propertiesof this object as appropriate (one property per named argument). In this case, WebMethod returnsan object with one property: StockName. After setting properties as needed, call the Invokemethod of that object. For example:Method GetQuote3(pRequest As GetStock.BusOp.GetQuoteRequest,Output pResponse As GetStock.BusOp.GetQuoteResponse) As %Status{set ..Adapter.WebServiceClientClass = "GetStock.StockServiceSoap"set proxymethod=..Adapter.WebMethod("GetQuote")set proxymethod.StockName=pRequest.StockNameset status=..Adapter.Invoke(proxymethod)if $$$ISERR(status) quit statusset pResponse=##class(GetStock.BusOp.GetQuoteResponse).%New()set pResponse.GetQuoteResult=proxymethod.%Resultquit $$$OK}In this case, you can provide any number of arguments.3.6.4 Reference InformationThis section provides reference information for the adapter property and methods mentioned in theprevious section.%ClientInvokeMethod%SOAP.WebClientThe associated instance of the proxy client (an instance of %SOAP.WebClient). This propertyis set when you set the WebServiceClientClass property of the adapter.Method InvokeMethod(pMethodName As %String,Output pResult As %RegisteredObject,ByRef pArg1,ByRef pArg2,ByRef pArg3,ByRef pArg4,ByRef pArg5,ByRef pArg6,ByRef pArg7,ByRef pArg8,ByRef pArg9,ByRef pArg10,ByRef pArg11,ByRef pArg12) As %Status40 Using SOAP and Web Services with Ensemble


WebMethodInvokeCalls the specified method of the proxy client class, passing as many as twelve argumentsand returns the status. The output is returned by reference as the second argument.Method WebMethod(pMethodName As %String) As %SOAP.ProxyDescriptorReturns an object that corresponds to the specified method. This object has one propertycorresponding to each method argument; you should set this properties before using theInvoke method. For details on %SOAP.ProxyDescriptor, see the class reference.Method Invoke(pWebMethod As %SOAP.ProxyDescriptor) As %StatusCalls the given method and returns the status.Creating a Business Operation Class ManuallyUsing SOAP and Web Services with Ensemble 41


ACommon Tasks in the EnsembleManagement PortalThis appendix describes common tasks that you perform in the Ensemble Management Portal. Thesetasks are needed to configure adapters as described in this book:• Adding a business service or operation to a production• Enabling a business service or business operation• Editing other runtime settings• Creating Ensemble credentialsA.1 Adding a Business Host to a ProductionTo add a business service or business operation to a production, do the following:1. Go to the [Ensemble] > [Productions] page.2. Find your production. Click the Configure button to the right of its name.3. Add the business host using these steps:• Click Add Service or Add Operation, as appropriate. A wizard is displayed.• Choose Other.• In the first drop-down list, choose the class name of the business host.Using SOAP and Web Services with Ensemble 43


Common Tasks in the Ensemble Management Portal• Enter appropriate data in the remaining fields as described in Developing Ensemble Productions,and click OK.4. Find the new business host in the production. Select it by clicking on it.5. Edit the settings as needed.6. Click Apply to save changes or click Cancel to discard them.When you click Apply, all changes immediately take effect, even if the production is currentlyrunning.Note:This procedure implicitly adds the associated adapter as well.A.2 Enabling a Business HostTo enable a business service or business operation, do the following:1. Go to the [Ensemble] > [Productions] page.2. Find your production. Click the Configure button to the right of its name.3. Click the business host to select it.4. Edit General Settings. Enable the business service or operation by checking the Enabled box.5. Click Apply to save changes or click Cancel to discard them.When you click Apply, all changes immediately take effect, even if the production is currentlyrunning.A.3 Editing Other Runtime SettingsTo edit the settings of a business service, business operation, or associated adapter, do the followingin the Ensemble Management Portal:1. Go to the [Ensemble] > [Productions] page.2. Find your production. Click the Configure button to the right of its name.3. Click the business host to select it.4. Edit General Settings for the business service. Hover the cursor over any setting name to displaythe help text for that setting.44 Using SOAP and Web Services with Ensemble


For detailed descriptions, see the book Managing Ensemble Productions.5. Edit Specific Settings for the business service. Hover the cursor over any setting name to displaythe help text for that setting. For detailed information on these settings, see other chapters in thisbook.6. Click Apply to save changes or click Cancel to discard them.Creating Ensemble CredentialsWhen you click Apply, all changes immediately take effect, even if the production is currentlyrunning.A.4 Creating Ensemble CredentialsSome remote systems require a username and password to log into that system. Ensemble permits youto store username-password pairs in a centralized, secure table that can be viewed and edited only byusers with access to the Ensemble Management Portal.You define Ensemble credentials, which consist of an ID and the username-password pair. Then youuse the ID as the value of the Credentials setting or the SOAPCredentials setting of your adapter.To create Ensemble credentials, log into the Ensemble Management Portal and do the following:1. Go to the [Ensemble] > [Maintenance] page.2. Click Credentials.3. Click Create New Credentials.4. For ID, enter a unique string that identifies this username-password pair. This is the identifier thatyou will use elsewhere within your production.5. For Username, enter the username that you will use to log on to the remote system.6. For Password, enter the corresponding password.7. Click Save.In some cases, it is not practical or possible to store the login data within Ensemble. You can writecode to get this data and pass it to Ensemble automatically. For details, see the book DevelopingEnsemble Productions.Using SOAP and Web Services with Ensemble 45


BCustomizing Startup and TeardownAll Ensemble business hosts inherit a set of callback methods that you can use to customize startupand teardown. You can customize any of these methods.B.1 Callback MethodsAll Ensemble business hosts inherit a set of callback methods that you can use to customize startupand teardown. You can customize any of these methods.OnInitOnTearDownMethod OnInit() As %StatusExecuted during startup of the business host. By default, this method does nothing.Method OnTearDown() As %StatusExecuted during teardown of the business host. By default, this method does nothing.OnProductionStartClassMethod OnProductionStart(pConfigName As %String) As %StatusExecuted when the production is started. By default, this method does nothing. Note that youcan use the adapter property %ConfigName to access the configured name of current businessservice.Using SOAP and Web Services with Ensemble 47


Customizing Startup and TeardownOnProductionStopClassMethod OnProductionStop(pConfigName As %String) As %StatusExecuted when the production is stopped. By default, this method does nothing.For reference, the following sections describes the exact startup and teardown sequences.B.2 The Startup SequenceThe startup sequence is the same for business services and business operations:1. At production startup, Ensemble calls the OnProductionStart method of each business serviceand business operation class listed in the production configuration.2. Ensemble creates a background process for each of the business services and business operationsin the production configuration. Ensemble can allocate more than one background process perbusiness host; the PoolSize of the business host specifies the number of background processes tocreate.3. Within each background process, Ensemble creates an instance of the business host class and aninstance of its associated adapter class (if any). Ensemble then sets the configurable propertyvalues of those instances.4. Ensemble calls the OnInit methods of the business host objects and the associated adapter objects,respectively.B.3 The Teardown SequenceThe startup sequence is slightly different for business services and business operations:1. During production shutdown:• Ensemble disables each business service; no more incoming requests are accepted for thisproduction.• Ensemble waits for each business operation to reach a quiescent state. That is, it waits untileach business operation has completed all of its synchronous requests.2. The OnTearDown method in each adapter is called.3. All adapter and business host objects are destroyed and their background processes are killed.48 Using SOAP and Web Services with Ensemble


The Teardown Sequence4. The OnProductionStop class method for each business host is called, once for each configureditem of that class in the production.Similarly, while a production is running, a given business service or business operation can be disabledor become inactive according to its configured schedule. When this occurs, the associated adapter (ifany) is shut down, and its OnTearDown method is executed.Using SOAP and Web Services with Ensemble 49


CUsing the SOAP Inbound AdapterThe EnsLib.SOAP.InboundAdapter class is not meant for production use but can be helpful for debuggingand demos. This appendix discusses it briefly.C.1 NotesThe SOAP inbound adapter (EnsLib.SOAP.InboundAdapter) does not require Web server software.Instead it spawns a TCP listener job using the Ensemble super server. This lets you run your servicein a foreground window, which is useful for debugging. (To do this, you must be running the servicelocally. Also make sure the PoolSize setting is 1 and the JobPerConnection setting is false.) It alsosupports SSL.The EnsLib.SOAP.InboundAdapter listens for HTTP input on a given port. When the adapter receivesinput, the following occurs:1. It extracts the HTTP SOAPaction header.2. It constructs a stream (%Library.GlobalBinaryStream) that contains the body of the input.3. It calls the Web method that corresponds to the given SOAPaction.Using SOAP and Web Services with Ensemble 51


Using the SOAP Inbound AdapterC.2 Development TasksImportant:InterSystems recommends that you do not place custom code or data in the systemprovidednamespaces ENSLIB or ENSDEMO where it will be deleted the next timeyou upgrade Ensemble. The ENSEMBLE namespace and any new namespace thatyou create to hold your work is preserved across Ensemble upgrades.To use the Ensemble SOAP inbound adapter, write and compile a new business service class inEnsemble Studio. The following list describes the basic requirements:• Your class should extend EnsLib.SOAP.Service. This class extends both Ens.BusinessService (sothat it is an Ensemble business service) and %SOAP.WebService (so that it can act as a Web serviceas well).• Your class should provide values for SERVICENAME and other parameters, as described in“Basic Requirements” of the chapter “Creating an Ensemble Web Service.”• The class should define Web methods, as described in “Defining Web Methods for Use inEnsemble.”C.3 Configuration TasksUse the Ensemble Management Portal to do the following:1. Add an instance of your custom class to the Ensemble production.Important:Ensure that the configuration name is the same as the full class name, includingpackage. This is a requirement for running an Ensemble Web service.2. Enable the business service.3. Set the PoolSize setting to 1 so that the adapter can use its TCP listener.4. Set the StayConnected setting to 0. Otherwise, clients may hang for their timeout period whilewaiting for the server to drop the connection.5. Specify other settings as needed; see the following section.6. Run the production.If you are not familiar with the Ensemble Management Portal, see the appendix “Common Tasks inthe Ensemble Management Portal.”52 Using SOAP and Web Services with Ensemble


C.4 Settings of the Inbound AdapterSettings of the Inbound AdapterThe inbound adapter uses the following settings:AllowSessions%BooleanIf this setting is true, this Web service establishes a session ID and allows repeated calls onthe service after one successfully authenticated call from a client. The default for this settingis false.AllowedIPAddresses%StringCallIntervalSpecifies a comma-separated list of remote IP addresses from which to accept connections.The adapter accepts IP addresses in dotted decimal form. An optional :port designation issupported, so either of the following address formats is acceptable: 192.168.1.22 or192.168.1.22:3298.If a port number is specified, connections from other ports will be refused.If the string starts with a ! character, the adapter initiates a connection to the specified address.In this case, only one address may be given, and if a port is specified, it supersedes the valueof the Port setting; otherwise, the Port setting is used.%NumericSpecifies the number of seconds that the adapter will listen for incoming data from its configuredsource, before checking for a shutdown signal from the Ensemble framework.If the adapter finds input, it acquires the data and passes it to the business service. The businessservice processes the data, and then the adapter immediately begins waiting for new input.This cycle continues whenever the production is running and the business service is enabledand scheduled to be active.The default CallInterval is 5 seconds. The minimum is 0.1 seconds.EnableStandardRequests%BooleanIf this setting is true, the adapter can also receive SOAP requests in the usual way (bypassingthe TCP connection). The default is false.Using SOAP and Web Services with Ensemble 53


Using the SOAP Inbound AdapterJobPerConnectionPort%BooleanIf this setting is true, the adapter spawns a new job to handle each incoming TCP connectionand allows simultaneous handling of multiple connections. When false, it does not spawn anew job for each connection. The default is true.%StringReadTimeoutSSLConfigSpecifies the TCP port to connect to. TCP port numbers have a maximum value of 65535.%NumericSpecifies the number of seconds to wait for each successive incoming TCP read operation,following receipt of initial data from the remote TCP port. The default is 5 seconds. The rangeis 0–600 seconds (a maximum of 10 minutes).%StringSpecifies the name of an existing SSL/TLS system configuration set to use, configured viathe System Management Portal.For information on creating and managing SSL/TLS configurations, see the chapter “UsingSSL/TLS with Caché” in the Caché Security Administration Guide. The SSL/TLS configurationincludes an option called Configuration Name; this is the string to use in this setting.At the end of the SSLConfig string, you can add a vertical bar (|) followed by the private keypassword.StayConnected%NumericSpecifies whether to keep the connection open between requests.• If this setting is 0, the adapter will disconnect immediately after every event.• If this setting is -1, the adapter auto-connects on startup and then stays connected.• This setting can also be positive (which specifies the idle time, in seconds), but such avalue is not useful for this adapter, which works by polling. If the idle time is longer thanthe polling interval (that is, the CallInterval) the adapter stays connected all the time. Ifthe idle time is shorter than the polling interval, the adapter disconnects and reconnectsat every polling interval.54 Using SOAP and Web Services with Ensemble


EnsLib.SOAP.OutboundAdapterusing, 37EnsLib.SOAP.Servicebasic behavior, 9error trapping, 15examplesEnsemble Web client, generated classes, 34Ensemble Web service, 21hint argument and OnProcessInput, 23invoking proxy methods, 38OnProcessInput, 17request and response messages, 19response messages with and without faulttrapping, 15Web method, 16Web service shell, 11WSDL (fragment), 20Hhint argumentintroduction, 17using, 23HTTPincluding username and password inheader, 32, 45HTTPSfor proxy server, 34specifying configuration to use, 33Web service location, 32IInvoke method, 38, 40InvokeMethod method, 34, 38, 40JJobPerConnection setting, 53Lliteral encoding, 24LOCATION parameter, 11, 32MMakeBusinessOperation property, 30MakePersistent property, 30MakeSerial property, 30message handlers, 37message map, 37NNAMESPACE parameter, 11namespacesfor Web service, 11null values, 24OOnInit method, 47OnProcessInput methodimplementing, 17using hint argument, 23OnProductionStart method, 47OnProductionStop method, 47OnTearDown method, 47output parameters instead of return values, 24OUTPUTTYPEATTRIBUTE parameter, 30OutputTypeAttribute property, 30PPoolSize setting, 13PoolSize setting for inbound adapter, 52Port setting, 53ProcessInput methodin Ensemble Web service, 9invoking from Web method, 14proxy clientassociating with adapter, 32executing methods, 38generated classes, 34generating, 30introduction, 6invoking from a business operation, 7ProxyHTTPS setting, 34proxy methodsas generated by SOAP client wizard, 34calling, 38introduction, 6ProxyPort setting, 34proxy server, using, 34ProxyServer setting, 34Qqualified elements, 2456 Using SOAP and Web Services with Ensemble


RReadTimeout setting, 53RESPONSENAMESPACE parameter, 11ResponseTimeout setting, 32ReturnMethodStatusFault method, 15ReturnStatusFault method, 15rpc-style binding, 24runtime settings, editing, 44runtime settings, inboundenabling SOAP sessions, 24runtime settings, outboundbasics, 32credentials, 32specifying a proxy server, 34specifying SSL, 33Sschema, namespace for, 11securitycreating credentials, 45specifying credentials, 32SendRequestAsync, 19SendRequestSync, 18SERVICENAME parameter, 11sessionsand inbound adapter, 53enabling, 24SOAPAction header, customizing, 24SoapBindingStyle keyword, 38SoapBodyUse keyword, 38SOAP client wizardadjusting generated code, 29and XMLKEEPCLASS, 30generated classes, 34introduction, 5running programmatically, 30using, 30SOAPCredentials setting, 32, 45SOAP encoding, 24SOAP faults, 15SOAP headersoptions, 24SOAP messagesadditional options, 24example classes, 19namespaces for, 11received by Ensemble, 3sent by Ensemble, 5SOAPSESSION parameter, 24SOAP sessionsand inbound adapter, 53enabling, 24SSLand inbound adapter, 53connecting to Web service via, 33SSLConfig setting, 33, 53startupcustomizing, 47details, 48StayConnected setting, 53StayConnected setting for inbound adapter, 52Tteardowncustomizing, 47details, 48TLS, connecting to Web service via, 33TYPENAMESPACE parameter, 11Uunqualified elements, 24URL for Web service, 20WWeb clientsbasic settings, 32business operation class, 7configuring, 29connecting via a proxy server, 34connecting via SSL, 33creating, 29credentials, 32generated classes, 6, 34in Ensemble, 5parts of, 27WebMethod keyword, 14, 38WebMethod method, 34, 38, 40Web methodsbasic requirements, 14basic steps, 14example, 16other options, 24specifying destinations, 17, 23WebServiceClientClass property/setting, 38Using SOAP and Web Services with Ensemble 57


WebServiceClientClass setting, 32Web servicesadditional options, 24configuration tasks, 13connecting to, via SSL, 33creating, 11example, 21forwarding request within production, 17, 23invoking from Ensemble, 5parts of, 9providing in Ensemble, 3returning SOAP faults, 15specifying location for client, 32supporting sessions, 24WSDL, 20Web Services Securityadding header to SOAP request, 32, 45WebServiceURL setting, 32WSDLusing to generate client, 30viewing, 20WS-Securityadding header to SOAP request, 32, 45XXML, projecting objects and data sets, 14XMLKEEPCLASS parameter, 30XML typesadjusting generated classes, 29customizing, 24generated for Web client, 6namespace for, 11xsi:type attribute, 3058 Using SOAP and Web Services with Ensemble

More magazines by this user
Similar magazines