+ All Categories
Home > Documents > Using SOAP and Web Services with Cach©

Using SOAP and Web Services with Cach©

Date post: 12-Sep-2021
Category:
Upload: others
View: 2 times
Download: 0 times
Share this document with a friend
126
Using SOAP and Web Services with Caché Version 2009.1 14 September 2017 InterSystems Corporation 1 Memorial Drive Cambridge MA 02142 www.intersystems.com
Transcript
Page 1: Using SOAP and Web Services with Cach©

Using SOAP and Web Serviceswith Caché

Version 2009.114 September 2017

InterSystems Corporation 1 Memorial Drive Cambridge MA 02142 www.intersystems.com

Page 2: Using SOAP and Web Services with Cach©

Using SOAP and Web Services with CachéCaché Version 2009.1 14 September 2017 Copyright © 2017 InterSystems CorporationAll rights reserved.

InterSystems, InterSystems Caché, InterSystems Ensemble, InterSystems HealthShare, HealthShare, InterSystems TrakCare, TrakCare,InterSystems DeepSee, and DeepSee are registered trademarks of InterSystems Corporation.

InterSystems iKnow, Zen, and Caché Server Pages are trademarks of InterSystems Corporation.

All other brand or product names used herein are trademarks or registered trademarks of their respective companies or 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 operation and maintenance of the products of InterSystemsCorporation. No part of this publication is to be used for any other purpose, and this publication is not to be reproduced, copied, disclosed,transmitted, stored in a retrieval system or translated into any human or computer language, in any form, by any means, in whole or in part,without the express prior written consent of InterSystems Corporation.

The copying, use and disposition of this document and the software programs described herein is prohibited except to the limited extentset forth in the standard software license agreement(s) of InterSystems Corporation covering such programs and related documentation.InterSystems Corporation makes no representations and warranties concerning such software programs other than those set forth in suchstandard software license agreement(s). In addition, the liability of InterSystems Corporation for any losses or damages relating to or arisingout of the use of such 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 BY INTERSYSTEMSCORPORATION ON THE USE OF, AND LIABILITY ARISING FROM, ITS COMPUTER SOFTWARE. FOR COMPLETE INFORMATIONREFERENCE SHOULD BE MADE TO THE STANDARD SOFTWARE LICENSE AGREEMENT(S) OF INTERSYSTEMS CORPORATION,COPIES OF WHICH WILL BE MADE AVAILABLE UPON REQUEST.

InterSystems Corporation disclaims responsibility for errors which may appear in this document, and it reserves the right, in its sole discretionand without notice, to make substitutions and modifications in the products and practices described in this document.

For Support questions about any InterSystems products, contact:

InterSystems Worldwide Response Center (WRC)+1-617-621-0700Tel:+44 (0) 844 854 2917Tel:[email protected]:

Page 3: Using SOAP and Web Services with Cach©

Table of Contents

About This Book .................................................................................................................................... 1

1 Introduction to Caché Web Services and Web Clients .................................................................... 31.1 Caché Support for Web Services ................................................................................................ 3

1.1.1 Generated Tools for Your Web Service ............................................................................ 41.1.2 HTTP Interfaces ............................................................................................................... 41.1.3 Caché Web Service Architecture ...................................................................................... 4

1.2 Caché Support for Web Clients .................................................................................................. 51.2.1 Caché Web Client Architecture ........................................................................................ 6

1.3 Additional Features .................................................................................................................... 71.4 Standards Supported in Caché .................................................................................................... 7

1.4.1 WSDL Support in Caché .................................................................................................. 8

2 Basics of Creating Web Services ..................................................................................................... 112.1 Overview of Caché Web Services ............................................................................................ 112.2 Basic Requirements .................................................................................................................. 12

2.2.1 Creating a New Web Service Using Studio .................................................................... 122.2.2 Example ......................................................................................................................... 13

2.3 About the Catalog and Test Pages ............................................................................................ 132.4 Specifying the Service Name and Namespaces of the Web Service ........................................ 14

2.4.1 Service Name ................................................................................................................. 152.4.2 Message Namespaces ..................................................................................................... 152.4.3 Type Namespaces ........................................................................................................... 15

2.5 Specifying the SOAP Versions Supported by the Web Service ................................................ 162.6 Viewing the WSDL ................................................................................................................... 16

2.6.1 Viewing the WSDL ........................................................................................................ 162.6.2 Generating the WSDL .................................................................................................... 17

2.7 Testing the Web Service ........................................................................................................... 172.8 Logging the SOAP Calls .......................................................................................................... 17

3 Creating Web Methods ..................................................................................................................... 193.1 Basic Requirements .................................................................................................................. 19

3.1.1 Example ......................................................................................................................... 203.2 Returning Values by Reference or as Output ........................................................................... 203.3 Using an Object as Input or Output .......................................................................................... 213.4 Using a Collection as Input or Output ...................................................................................... 223.5 Using a Data Set as Input or Output ......................................................................................... 22

3.5.1 About %XML.DataSet ................................................................................................... 233.5.2 Defining a Typed Data Set ............................................................................................. 233.5.3 Returning a Data Set ...................................................................................................... 233.5.4 Using a Data Set as an Input Argument ......................................................................... 253.5.5 Working with a Data Set ................................................................................................ 253.5.6 Controlling the Format of the Data Set .......................................................................... 263.5.7 Viewing the Data Set and Schema as XML ................................................................... 27

3.6 Using Nonprinting Characters in Input or Output .................................................................... 273.7 Using a Class Query as a Web Method .................................................................................... 283.8 Specifying the Binding Style for the SOAP Messages ............................................................ 29

3.8.1 Document-style Binding ................................................................................................ 293.8.2 RPC-style Binding ......................................................................................................... 29

Using SOAP and Web Services with Caché                                                                                                                          iii

Page 4: Using SOAP and Web Services with Cach©

3.9 Specifying the Encoding for the SOAP Messages ................................................................... 293.9.1 Literal Data .................................................................................................................... 303.9.2 SOAP-encoded Data ...................................................................................................... 30

4 Creating Web Clients ....................................................................................................................... 334.1 Overview of the Caché SOAP Client Wizard ........................................................................... 334.2 Using the SOAP Client Wizard ................................................................................................ 344.3 Using the Process() Method ..................................................................................................... 37

4.3.1 Example 1: Using an Ordinary WSDL .......................................................................... 384.3.2 Example 2: Using a Password-protected WSDL ........................................................... 38

4.4 Adjusting the Generated Classes for Long Strings ................................................................... 394.5 Basic Settings of a Caché Web Client ...................................................................................... 40

4.5.1 Endpoint for the Web Client ........................................................................................... 404.5.2 SOAP Version of the SOAP Requests ............................................................................ 404.5.3 Encoding and Binding Style .......................................................................................... 404.5.4 Namespaces for the Messages from the Client .............................................................. 414.5.5 Namespaces for Types Used by the Client ..................................................................... 41

4.6 About the Generated Caché Web Client Classes ...................................................................... 424.7 Using Caché Web Client Classes ............................................................................................. 444.8 Configuring the Client to Use SSL .......................................................................................... 444.9 Using the HTTP Response ....................................................................................................... 45

5 SOAP Fault Handling ....................................................................................................................... 475.1 Default Fault Handling in a Web Service ................................................................................. 475.2 Creating Custom SOAP Faults in a Caché Web Service .......................................................... 485.3 Details for SOAP 1.1 Faults ..................................................................................................... 48

5.3.1 Example SOAP Fault ..................................................................................................... 485.3.2 Details for %SOAP.Fault ................................................................................................ 495.3.3 Example Error Method ................................................................................................... 49

5.4 Details for SOAP 1.2 Faults ..................................................................................................... 505.4.1 Example SOAP Fault ..................................................................................................... 505.4.2 Details for %SOAP.Fault12 ............................................................................................ 505.4.3 Details for %SOAP.Fault12.Code .................................................................................. 515.4.4 Details for %SOAP.Fault12.Text .................................................................................... 525.4.5 Example Error Method ................................................................................................... 52

5.5 Macros for SOAP Fault Codes ................................................................................................. 535.6 Handling SOAP Faults and Other Errors in a Caché Web Client ............................................. 53

5.6.1 Example 1: Try-Catch .................................................................................................... 545.6.2 Example 2: $ZTRAP ...................................................................................................... 545.6.3 SSL Handshake Errors ................................................................................................... 55

6 Using MTOM for Attachments ........................................................................................................ 576.1 Attachments and SOAP Message Packaging ........................................................................... 57

6.1.1 SOAP Messages with All-inline Parts ............................................................................ 586.1.2 SOAP Messages with MTOM Packaging ...................................................................... 586.1.3 SOAP With Attachments ................................................................................................ 59

6.2 Forcing Responses as MTOM Packages .................................................................................. 596.3 Forcing Requests as MTOM Packages ..................................................................................... 606.4 Controlling the MTOM Packaging ........................................................................................... 606.5 Example .................................................................................................................................... 60

6.5.1 Web Method Argument .................................................................................................. 606.5.2 Web Service .................................................................................................................... 61

iv                                                                                                                          Using SOAP and Web Services with Caché

Page 5: Using SOAP and Web Services with Cach©

6.5.3 Web Client ...................................................................................................................... 61

7 Using SOAP With Attachments ....................................................................................................... 637.1 Sending Attachments ................................................................................................................ 637.2 Using Attachments ................................................................................................................... 647.3 Example .................................................................................................................................... 64

7.3.1 Web Service .................................................................................................................... 647.3.2 Web Client ...................................................................................................................... 65

8 Adding and Using SOAP Headers ................................................................................................... 678.1 How Caché Represents SOAP Headers ................................................................................... 67

8.1.1 Special Header Elements ............................................................................................... 688.2 Creating Custom Header Elements .......................................................................................... 698.3 Adding a Header Element to a SOAP Message ....................................................................... 698.4 Processing Specific Header Elements ...................................................................................... 708.5 Adding WS-Addressing Header Elements ............................................................................... 71

8.5.1 Adding WS-Addressing Headers to Request Messages ................................................. 718.5.2 Adding WS-Addressing Headers to Response Messages .............................................. 718.5.3 Creating WS-Addressing Header Elements Manually ................................................... 718.5.4 Handling WS-Addressing Header Elements .................................................................. 71

9 Using WS-Security Features ............................................................................................................ 739.1 Caché Support for WS-Security Features ................................................................................ 73

9.1.1 Caché Support for the WS-Security Header .................................................................. 739.1.2 Digital Signatures ........................................................................................................... 759.1.3 Encryption ...................................................................................................................... 759.1.4 Options for Creating Credentials ................................................................................... 769.1.5 Validation and Decryption .............................................................................................. 77

9.2 Creating a Collection of Root Authority Certificates ............................................................... 779.3 Creating, Editing, and Using X.509 Credentials ...................................................................... 77

9.3.1 Creating X.509 Credentials ............................................................................................ 779.3.2 Editing X.509 Credentials .............................................................................................. 789.3.3 Retrieving a Set of Caché X.509 Credentials ................................................................. 79

9.4 Adding a Time Stamp to the WS-Security Header ................................................................... 799.5 Adding a Username Token to the WS-Security Header ........................................................... 809.6 Adding a Digital Signature to the WS-Security Header ........................................................... 809.7 Signature Variations .................................................................................................................. 81

9.7.1 Adding a Digital Signature without a Binary Security Token ........................................ 819.7.2 Applying a Digital Signature to Specific Message Parts ............................................... 82

9.8 Encrypting the SOAP Body with an X.509 Certificate ............................................................ 839.9 Creating a SAML Token .......................................................................................................... 859.10 Adding a SAML Token to the WS-Security Header .............................................................. 879.11 Encrypting the Response Messages ....................................................................................... 879.12 Validating WS-Security Headers and Decrypting the Messages ............................................ 87

9.12.1 Validating WS-Security Headers and Decrypting the Messages .................................. 889.12.2 Validating the SAML Assertion ................................................................................... 889.12.3 CSP Authentication and WS-Security .......................................................................... 88

10 SOAP Session Management ........................................................................................................... 9110.1 Overview of SOAP Sessions .................................................................................................. 9110.2 Enabling Sessions ................................................................................................................... 9210.3 Using Session Information ..................................................................................................... 92

Using SOAP and Web Services with Caché                                                                                                                           v

Page 6: Using SOAP and Web Services with Cach©

11 Using the Caché Binary SOAP Format ........................................................................................ 9311.1 Introduction ............................................................................................................................ 9311.2 Extending the WSDL for a Caché Web Service ..................................................................... 94

11.2.1 WSDL Differences ....................................................................................................... 9411.2.2 Differences in Generated Web Client Classes .............................................................. 95

11.3 Redefining a Caché Web Client to Use Binary SOAP ........................................................... 9511.4 Specifying the Character Set .................................................................................................. 9511.5 Details on the Caché Binary SOAP Format ........................................................................... 95

12 Fine-tuning a Caché Web Service ................................................................................................. 9712.1 Controlling the XML Types ................................................................................................... 9712.2 Controlling the Namespaces of the Schema and Types .......................................................... 98

12.2.1 Controlling the Namespace of the Schema .................................................................. 9812.2.2 Controlling the Namespace of the Types ..................................................................... 98

12.3 Including Documentation for the Types ................................................................................. 9912.4 Controlling the Message Name of the SOAP Response ........................................................ 9912.5 Overriding the Default SOAPAction Header ......................................................................... 9912.6 Specifying Whether Elements Are Qualified ....................................................................... 10012.7 Controlling the Form of Message Parts ................................................................................ 10012.8 Controlling the Form of Null Arguments ............................................................................. 10112.9 Controlling Use of the xsi:type Attribute ............................................................................. 10112.10 Specifying the SOAP Envelope Prefix ............................................................................... 10112.11 Sending Responses Compressed by gzip ........................................................................... 10212.12 Defining a One-way Web Method ...................................................................................... 10212.13 Adding a Byte-order Mark to the SOAP Messages ............................................................ 10212.14 Customizing Callbacks of the Web Service ....................................................................... 10312.15 Specifying Custom Transport for a Web Service ............................................................... 103

12.15.1 Background .............................................................................................................. 10312.15.2 Defining Custom Transport for a Web Service ........................................................ 104

13 Fine-tuning a Caché Web Client ................................................................................................. 10513.1 Controlling the Timeout Period ............................................................................................ 10513.2 Using a Proxy Server ............................................................................................................ 10613.3 Setting HTTP Headers ......................................................................................................... 10713.4 Specifying the HTTP Version to Use ................................................................................... 10713.5 Controlling Use of the xsi:type Attribute ............................................................................. 10713.6 Specifying the Envelope Prefix ............................................................................................ 10813.7 Sending Responses Compressed by gzip ............................................................................. 10813.8 Defining a One-way Web Method ........................................................................................ 10813.9 Adding a Byte-order Mark to the SOAP Messages .............................................................. 10813.10 Creating Custom SOAP Messages ..................................................................................... 10913.11 Specifying Custom HTTP Requests ................................................................................... 11013.12 Specifying Custom Transport from the Web Client ........................................................... 110

13.12.1 Background .............................................................................................................. 11013.12.2 Defining Custom Transport for a Caché Web Client ............................................... 111

13.13 Specifying Flags for the SAX Parser ................................................................................. 11113.14 Using the WS-Security Login Feature ............................................................................... 11113.15 Using HTTP User Authentication ...................................................................................... 112

Appendix A: Summary of Web Service URLs ................................................................................ 113

Appendix B: Brief Introduction to SOAP and Web Services ........................................................ 115B.1 Web Services .......................................................................................................................... 115

vi                                                                                                                          Using SOAP and Web Services with Caché

Page 7: Using SOAP and Web Services with Cach©

B.2 SOAP Messages ..................................................................................................................... 115B.3 Using SOAP via HTTP .......................................................................................................... 116B.4 WSDL Documents ................................................................................................................. 116B.5 Web Client ............................................................................................................................. 117B.6 Tracing Web Service Calls ..................................................................................................... 117

Using SOAP and Web Services with Caché                                                                                                                         vii

Page 8: Using SOAP and Web Services with Cach©

List of Tables

Table 4–1: Encoding and Binding Style for Web Client Messages ....................................................... 40Table 4–2: Namespaces for SOAP Messages Sent by Web Clients ...................................................... 41Table 4–3: Namespaces for Types in Web Clients ................................................................................. 41Table 5–1: Caché ObjectScript Macros for SOAP Fault Codes ............................................................ 53Table 12–1: Effect of SoapBodyUse Keyword on ELEMENTQUALIFIED Parameter ..................... 100Table 12–2: Effect of SoapBodyUse Keyword on XMLELEMENT Parameter ................................. 100Table I–1: URLs for Your Web Service ............................................................................................... 113

viii                                                                                                                         Using SOAP and Web Services with Caché

Page 9: Using SOAP and Web Services with Cach©

About This Book

This book describes, to programmers, how to use the Caché support for SOAP and Web services. It includes the followingsections:

• Introduction to Caché Web Services and Web Clients

• Basics of Creating Web Services

• Creating Web Methods

• Creating Web Clients

• SOAP Fault Handling

• Using MTOM for Attachments

• Using SOAP With Attachments

• Adding and Using SOAP Headers

• Using WS-Security Features

• SOAP Session Management

• Using the Caché Binary SOAP Format

• Fine-tuning a Caché Web Service

• Fine-tuning a Caché Web Client

• Summary of Web Service URLs

• Brief Introduction to SOAP and Web Services

For a detailed outline, see the table of contents.

For more information, try the following sources:

• Using XML with Caché describes how to project Caché objects to XML and how to control that projection.

• Using Caché Server Pages (CSP) describes how to create CSP applications.

• Using Caché Internet Utilities includes information on using HTTP responses.

For general information, see the InterSystems Documentation Guide.

Using SOAP and Web Services with Caché                                                                                                                           1

Page 10: Using SOAP and Web Services with Cach©
Page 11: Using SOAP and Web Services with Cach©

1Introduction to Caché Web Services andWeb Clients

Caché supports SOAP 1.1 and 1.2 (Simple Object Access Protocol). This support is easy to use, efficient, and fully com-patible with the SOAP specification. This support is built into Caché and does not require any complex middleware oroperating system extensions. It is available on every platform supported by Caché.

Using Caché SOAP support, you can do the following:

• Define and publish Web services — a collection of related methods that client applications invoke using the SOAPprotocol. Such methods can be discovered and invoked by other SOAP-aware applications. Caché runs SOAP methodsdirectly within the database; the execution is highly efficient.

• Use an existing WSDL document to generate a Caché Web client that invokes the Web service described in the WSDL.

This chapter introduces the following:

• A summary of Caché support for Web services

• A summary of Caché support for Web clients

• Additional features provided by Caché support for Web services and SOAP

• Standards supported by Caché, including details on its support for WSDL documents

1.1 Caché Support for Web ServicesCaché provides powerful, built-in support for Web services. You can convert existing classes to Web services with a fewsmall changes, or you can create new Web services from scratch. In either case:

• A Web service class inherits from the %SOAP.WebService class.

• If a method or a class query is flagged with the WebMethod keyword, it can be invoked as a Web method.

• It must be possible to project all input and output of the Web methods to XML so that it can be packaged into SOAPmessages. For constant literal data, no work is needed. Any object used as input or output must be XML-enabled; thatis, it must inherit from %XML.Adaptor. Data sets must inherit from %XML.DataSet.

A Caché Web service does the following for you:

• Validates incoming SOAP messages.

Using SOAP and Web Services with Caché                                                                                                                           3

Page 12: Using SOAP and Web Services with Cach©

• Unpacks SOAP messages, converts data to Caché representation, and invokes the corresponding method.

• Runs the method directly within the Caché database; the execution is highly efficient.

• Returns a response message (a SOAP message) to the caller.

Also, because the %SOAP.WebService class inherits from %CSP.Page, a Caché Web service takes advantage of the CSP(Caché Server Pages) infrastructure and resides within a CSP application. A CSP application is a set of CSP pages linkedwith a logical application name and administered as a unit from the CSP Gateway.

1.1.1 Generated Tools for Your Web Service

The Caché class compiler generates a WSDL for the Web service and publishes it via a Web server (using CSP). ThisWSDL complies with the Basic Profile 1.0 established by the WS-I (Web Services Interoperability Organization). TheWSDL document is served dynamically and automatically reflects any changes you make to the interface of your Webservice class. It is not necessary to maintain this document manually.

When you compile a Web service, Caché also generates a catalog page for the Web service, for use while testing. The cat-alog page lists the methods defined in the service and provides a link to the WSDL document.

1.1.2 HTTP Interfaces

A Caché Web service supports two different interfaces over HTTP:

• SOAP, using the SOAPAction HTTP header, SOAP <Envelope. and <Body> elements and so on.

• A CSP page (for limited testing purposes only). This takes the method name and arguments as query parameters. Thistest page does not test the full SOAP pathway. The test pages are available from the catalog page that is mentioned inthe previous section. An example is shown in the next chapter, but otherwise these pages are not discussed.

The response message in XML is the same for both interfaces.

1.1.3 Caché Web Service Architecture

A Caché Web service is part of a CSP application. Caché must be running in order for the Web service to work.

To understand how a Caché Web service works by default, it is useful to follow the events that occur when the Web servicereceives a message it can understand: an HTTP request that includes a SOAP message.

First consider the contents of this HTTP request, which is directed to a specific URL:

• HTTP headers that indicate the HTTP version, character set, and other such information.

The HTTP headers include the SOAPAction HTTP request header field, which is required when you invoke a Webmethod via HTTP. This is a URI that indicates the intent of the SOAP HTTP request. SOAP places no restrictions onthe format or specificity of the URI or that it is resolvable.

• A request line, which includes a HTTP method such as GET, POST, or HEAD. This line indicates the action to take.

• The message body, which in this case is a SOAP message that contains a method call. More specifically, this SOAPmessage indicates the name of the method to invoke and values to use for its arguments. The message can also includea SOAP header.

Now let us examine what occurs when this request is sent:

1. The request is received by a third-party Web server.

2. Because the request is directed to a URL that ends with .cls, the Web server forwards the request to the CSP Gateway.

4                                                                                                                           Using SOAP and Web Services with Caché

Introduction to Caché Web Services and Web Clients

Page 13: Using SOAP and Web Services with Cach©

3. The CSP Gateway examines the URL. It interprets part of this URL as the logical name of a CSP application. TheGateway forwards the request to the appropriate physical location (the page for the Web service), within that CSPapplication.

4. When the Web service page receives the request, it invokes its OnPage method.

5. The Web service checks whether the request includes a Caché SOAP session header and if so, resumes the appropriateSOAP session or starts a new one.

Note: This step refers to SOAP sessions as supported by Caché SOAP support. The SOAP specification itself doesnot define a standard for sessions. However, Caché SOAP support provides a proprietary Caché SOAP sessionheader that you can use to maintain a session between a Web client and a Web service, as described here.

6. The Web service unpacks the message, validates it, and converts all input parameters to their appropriate Caché repre-sentation. For each complex type, the conversion creates an object instance that represents the complex type and usesthat object as input for the Web method.

The SOAPAction header is used here to determine the method and hence the request object.

When the Web service unpacks the message, it creates a new request object and imports the SOAP message into thatobject. In this process, the Web service uses a generated class (a Web method handler class) that was created whenyou compiled the Web service.

7. The Web service executes the requested Caché method, packages up the reply, and constructs a SOAP response,including a SOAP header if appropriate.

8. The Web service writes the SOAP response (an XML document) to the current output device.

The following figure shows the external parts of this flow:

1.2 Caché Support for Web ClientsWith Caché, you can easily create Web clients for nearly any Web service. To do so, you use the Caché SOAP client wizard,which reads a WSDL document and generates a set of Caché classes to use as a Web client. This tool is available as awizard within Studio or, equivalently, as a method that you can invoke programmatically.

Using SOAP and Web Services with Caché                                                                                                                           5

Caché Support for Web Clients

Page 14: Using SOAP and Web Services with Cach©

The generated Web client interface includes a client class that contains a proxy method for each method defined by theWeb service. Each proxy uses the same signature used by the corresponding Web service method. The interface also includesclasses to define any XML types needed as input or output for the methods.

Typically you do not customize the generated classes. You instead create additional classes that control the behavior ofyour Web client and invoke its proxy methods.

1.2.1 Caché Web Client Architecture

To understand how a Caché Web client works, we follow the events that occur when a user or other agent invokes a methodwithin the Web client.

1. First the Web client creates a SOAP message that represents the method call and its argument values.

2. Next it creates an HTTP request that includes the SOAP message. The HTTP request includes a request line and HTTPheaders, as described earlier.

3. It issues the HTTP request, sending it to the appropriate URL.

4. It waits for the HTTP response and determines the status.

5. It receives the SOAP response from the Web service.

6. It unpacks the SOAP response.

The following figure shows this flow:

6                                                                                                                           Using SOAP and Web Services with Caché

Introduction to Caché Web Services and Web Clients

Page 15: Using SOAP and Web Services with Cach©

1.3 Additional FeaturesCaché support for Web services and SOAP includes the following additional features:

• Session support. As noted earlier, although the SOAP specification itself does not define a standard for sessions, youcan create client-server SOAP sessions by using the CSP infrastructure and the session support provided by the %SOAP

package.

• Ability to create custom SOAP headers, SOAP message bodies, and SOAP faults.

• Ability to add attachments.

• Ability to provide authentication (user login) between a Web client and a Web service, as well as several key parts ofthe WS-Security standard. See the next heading.

• Ability to fine-tune the generated WSDL document to meet most format requirements.

• Option for transport other than HTTP between the Web client and Web service.

1.4 Standards Supported in CachéThe Caché support for SOAP and Web services supports the following standards:

• SOAP 1.1 (see http://www.w3.org/TR/2000/NOTE-SOAP-20000508/), including encoded format.

• SOAP 1.2, including encoded format as specified in section 3 SOAP Version 1.2 Part 2: Adjuncts(http://www.w3.org/TR/soap12-part2/).

• The following parts of WS-Security 1.1 created by OASIS (http://docs.oasis-open.org/wss/v1.1/wss-v1.1-spec-pr-SOAPMessageSecurity-01.pdf):

– WS-Security headers (http://www.oasis-open.org/committees/download.php/16790/wss-v1.1-spec-os-SOAPMessageSecurity.pdf)

– X.509 Token Profile 1.1 (http://www.oasis-open.org/committees/download.php/16785/wss-v1.1-spec-os-x509TokenProfile.pdf)

– XML Signature using Exclusive XML Canonicalization and RSA SHA-1 (http://www.w3.org/TR/xmldsig-core/)

Using SOAP and Web Services with Caché                                                                                                                           7

Additional Features

Page 16: Using SOAP and Web Services with Cach©

– UsernameToken Profile 1.1 (http://docs.oasis-open.org/wss/v1.1/wss-v1.1-spec-pr-UsernameTokenProfile-01.pdf)

– Most of WS-Security SAML Token Profile 1.1 (http://docs.oasis-open.org/wss/oasis-wss-SAMLTokenProfile-1.1) based on SAML version 2.0. The exceptions are as follows:

• Support does not include coverage for SAML 1.0 or 1.1. That is, Caché SOAP support does not providecoverage for features of the SAML Token Profile 1.1 specification that refer to SAML 1.0 or 1.1.

• Support does not include coverage of STR Dereference Transform (#STR-Transform), which allows indirectreference to a SAML Assertion by means of a <SecurityTokenReference> element which is a direct child ofthe <Security> header.

The Caché %SAML.Assertion class represents the SAML token child of the WS-Security header. For outboundSOAP messages, Caché Web services and Web clients can sign the SAML assertion token. However, it is theresponsibility of your application to define the SAML assertion itself.

For inbound SOAP messages, Caché Web services and Web clients can process the SAML assertion token andvalidate its signature. Your application must validate the details of the SAML assertion itself.

Full SAML support is not implemented. “SAML support in Caché” refers only to the specification listed here.

Also see “Caché Support for WS-Security Features,” later in this book.

• MTOM (Message Transmission Optimization Mechanism) 1.0 (http://www.w3.org/TR/soap12-mtom/).

• WSDL 1.1. Caché Web services produce WSDL documents that comply with the Basic Profile 1.0 established by theWS-I (Web Services Interoperability Organization). However, Caché Web clients do work for more general WSDLdocuments.

But also see the next heading.

• UDDI version 1.0 with client access only (no repository provided). See http://uddi.xml.org/

• Attachments handled as a multipart/related MIME message according to the SOAP with Attachments specification(http://www.w3.org/TR/SOAP-attachments).

• Transport via HTTP 1.1 or HTTP 1.0.

For information on XML standards supported in Caché, see the book Using XML with Caché.

1.4.1 WSDL Support in Caché

Caché support for Web services, SOAP, and Web clients does not support all possible WSDL documents. More flexibilityis provided on the client side, because it is frequently necessary to create Web clients that work with specific WSDL docu-ments that cannot be changed. This section discusses the details of the support.

1.4.1.1 Generating WSDL Documents

The WSDL documents generated by Caché Web services do not include headers. Also, the Web services that you can createin Caché do not reflect all possible variations.

1.4.1.2 Using WSDL Documents

On the client side, the Caché SOAP client wizard cannot process all possible WSDL documents. In particular:

• It does not support the <fault> element. That is, if you include a <fault> element within the <operation> element ofthe binding, the <fault> element is ignored.

• For the response messages, one of the following must be true:

8                                                                                                                           Using SOAP and Web Services with Caché

Introduction to Caché Web Services and Web Clients

Page 17: Using SOAP and Web Services with Cach©

– Each response message must be in the same namespace as the corresponding request message.

– The response messages must all be in the same namespace as each other (which can be different from the namespacesused by request messages).

• For the types used by the response messages, all types must be in the same namespace. This does not have to be thesame as the namespace of the types used by the request messages.

For the request messages, the types can be in different namespaces.

• the Caché SOAP client wizard does not process headers of the WSDL.

The SOAP client wizard does allow the use of the MIME binding in a WSDL (http://www.w3.org/TR/wsdl#_Toc492291084).The MIME parts are ignored and the remainder of the WSDL is processed. When you can create a Web client based on aWSDL that contains MIME binding, you must add explicit Caché ObjectScript code to support the MIME attachments;this task is beyond the scope of this book

Using SOAP and Web Services with Caché                                                                                                                           9

Standards Supported in Caché

Page 18: Using SOAP and Web Services with Cach©
Page 19: Using SOAP and Web Services with Cach©

2Basics of Creating Web Services

This chapter describes how to create a Web service in Caché. It includes the following topics:

• Overview of Caché Web services

• A description of the basic requirements for creating a Web service and Web methods

• An introduction to the Caché catalog and test pages for the Web service

• How to specify the service name of and namespaces used by the Web service

• How to specify the SOAP version given in the WSDL

• How to view the WSDL that Caché generates for your Web service

• Tools you can use to test a Web service

• How to log the SOAP messages

Note: To configure a Caché Web service to use SSL, you create an SSL/TLS configuration within the System ManagementPortal. For information, see the chapter “Using SSL/TLS with Caché” in the Caché Security AdministrationGuide.

See the first appendix for a table that summarizes the URLs related to your Web service.

2.1 Overview of Caché Web ServicesTo create a Web service in Caché, you create a class that extends %SOAP.WebService, which provides all the functionalityrequired to make one or more methods callable via the SOAP protocol. In addition, this class automates the managementof SOAP-related bookkeeping, such as maintaining a WSDL document that describes a service.

This class is derived from the %CSP.Page class. Because of this, every Web service class can respond to HTTP requests(via CSP). Thus, the %SOAP.WebService class implements methods that respond to HTTP events to do the following:

• Publish a human-readable catalog page (using HTML) describing the Web service and its methods. The descriptionson this page show the comments included in the class definition.

• Publish the WSDL document for the Web service as an XML document.

Using SOAP and Web Services with Caché                                                                                                                         11

Page 20: Using SOAP and Web Services with Cach©

2.2 Basic RequirementsTo create and publish a Web service in Caché, create and compile a Caché class that meets the following basic requirements:

• The class must extend %SOAP.WebService.

• The class must define the SERVICENAME parameter. Caché does not compile the class unless it defines this parameter.

• Optionally define methods or class methods to use as Web methods. For these methods:

– The method must be marked with the WebMethod keyword.

– To use an object as an argument or a return value, you must ensure that the object is XML-enabled. That is, theclass definitions for the types must extend %XML.Adaptor. The default settings for this class are normally suitable;if not, see the book Using XML with Caché.

– To use a data set as an argument or return value, you must ensure the data set is of type %XML.DataSet (or a sub-class). %XML.DataSet 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 thatthe ELEMENTTYPE parameter of the collection is set and refers to an XML-enabled class.

• Optionally define class queries to use as Web methods. These queries must be marked with the WebMethod keyword.

Important: In most cases, Web methods should be instance methods. Within a Web method, it is often necessary toset properties of and invoke methods of the Web service instance (as described in later chapters) to fine-tune the behavior of the method. Because a class method cannot do these tasks, a class method is usuallyless suitable as a Web method.

For further details on creating Web methods, see the chapter “Creating Web Methods,” later in this book.

2.2.1 Creating a New Web Service Using Studio

To create a new Web service class with Caché Studio, you can use a convenient wizard provided for this purpose:

1. In Studio, make sure that you are in the appropriate Caché namespace.

2. Click File > New.

This displays the New dialog box.

3. Click the Custom tab.

4. Click New Web Service and then click OK.

This displays a wizard.

5. Enter values for the package name, class name, and Web service name. These are required.

6. Optionally edit the namespace URI (or change this initial value later). This is the XML namespace, not the Cachénamespace.

7. Optionally type a list of method names, on separate lines.

8. Click OK.

Now, you have a new Web service class that contains stubs for the Web methods. For example:

/// MyApp.StockServiceClass MyApp.StockService Extends %SOAP.WebService [ ProcedureBlock ]{

12                                                                                                                         Using SOAP and Web Services with Caché

Basics of Creating Web Services

Page 21: Using SOAP and Web Services with Cach©

/// Name of the WebService.Parameter SERVICENAME = "StockService";

/// TODO: change this to actual SOAP namespace./// SOAP Namespace for the WebServiceParameter NAMESPACE = "http://tempuri.org";

/// Namespaces of referenced classes will be used in the WSDL.Parameter USECLASSNAMESPACES = 1;

/// TODO: add arguments and implementation./// ForecastMethod Forecast() As %String [ WebMethod ]{ ;Quit "Forecast"}

}

2.2.2 Example

When you add more details to the Web methods, you might have a result like this:

/// MyApp.StockServiceClass MyApp.StockService Extends %SOAP.WebService [ ProcedureBlock ]{

/// Name of the WebService.Parameter SERVICENAME = "StockService";

/// TODO: change this to actual SOAP namespace./// SOAP Namespace for the WebServiceParameter NAMESPACE = "http://tempuri.org";

/// Namespaces of referenced classes will be used in the WSDL.Parameter USECLASSNAMESPACES = 1;

/// This method returns tomorrow's price for the requested stockMethod Forecast(StockName As %String) As %Integer [WebMethod]{ // apply patented, nonlinear, heuristic to find new price Set price = $Random(1000) Quit price}}

2.3 About the Catalog and Test PagesWhen you compile a Web service class, the class compiler creates a convenient catalog page that you can use to examinethe Web service and view its WSDL. To see this CSP page:

1. In Studio, make sure you are viewing the Web service class.

2. Click View > Web Page.

The catalog page is immediately displayed. Its URL is constructed as follows:

base/csp/app/web_serv.cls

Here base is the base URL for your Web server (including port if necessary), /csp/app is the name of the CSP applicationin which the Web service resides, and web_serv is the class name of the Web service. (Typically, /csp/app is/csp/namespace.) For example:

http://localhost:57772/csp/samples/MyApp.StockService.cls

This page might look as follows:

Using SOAP and Web Services with Caché                                                                                                                         13

About the Catalog and Test Pages

Page 22: Using SOAP and Web Services with Cach©

The catalog page displays the class name, namespace, and service name, as well as the comments for the class and Webmethods. The Service Description link displays the WSDL; for information, see the section “Viewing the WSDL,” laterin this chapter. The Forecast link displays another page where you can test the associated method in a limited fashion; anexample is shown below:

Notes about this test page:

• It does not enable you to see the SOAP request.

• It does not test the full SOAP pathway. This means, for example, it does not write to the SOAP log that is discussedlater in this chapter.

• It accepts only simple, literal inputs, so you cannot use it to call methods whose arguments are objects or data sets.

This book does not discuss this page further. To test your Web service more fully, generate and use a Web client as describedlater in this book.

2.4 Specifying the Service Name and Namespaces of theWeb ServiceYour Web service class defines parameters that specify the service name of and namespaces used by the Web service.These are as follows:

14                                                                                                                         Using SOAP and Web Services with Caché

Basics of Creating Web Services

Page 23: Using SOAP and Web Services with Cach©

2.4.1 Service Name

The following required parameter of your Web service specifies its service name. Caché does not compile the class unlessit defines this parameter.

SERVICENAME

Name of the Web service. This name must start with a letter and must contain only alphanumeric characters.

2.4.2 Message Namespaces

The following optional parameters of your Web service specify the namespaces of the messages used by the Web service.These are listed in order of precedence.

NAMESPACE

URI that defines the target namespace for your Web service, so that your service, and its contents, do not conflictwith another service. This is initially set to "http://tempuri.org" which is a temporary URI used by SOAPdevelopers during development.

If you do not specify this parameter, the target namespace is "http://tempuri.org".

RESPONSENAMESPACE

URI that defines the namespace for the response messages. By default, this is equal to the namespace given bythe NAMESPACE parameter.

Note: As you can see, for a Caché Web service, all request messages must be in the same namespace. Similarly, allresponse messages must be in the same namespace. For a Caché Web client, however, these limitations do notapply. See the section “Namespaces for the Messages from the Client,” later in this book.

2.4.3 Type Namespaces

The following optional parameters of your Web service specify the namespaces of the types used by the Web service. Theseare listed in order of precedence.

TYPENAMESPACE

Namespace for the schema for the types defined by the Web service. If you do not specify this parameter, theschema is in the target namespace of the Web service (that is, either NAMESPACE or the default, which is"http://tempuri.org").

RESPONSETYPENAMESPACE

URI that defines the namespace for types used by the response messages. By default, this is equal to the namespacegiven by the TYPENAMESPACE parameter.

This parameter is used only if SoapBindingStyle equals "document" (the default).

Note: As you can see, for a Caché Web service, the types used by request messages must all be in the same namespace.For a Caché Web client, however, this limitation does not apply. See the section “Namespaces for Types Usedby the Client,” later in this book.

For either a Caché Web service or a Caché Web client, the types for the response messages must all be in thesame namespace.

Using SOAP and Web Services with Caché                                                                                                                         15

Specifying the Service Name and Namespaces of the Web Service

Page 24: Using SOAP and Web Services with Cach©

2.5 Specifying the SOAP Versions Supported by the WebServiceAs of this release, Caché Web services support both SOAP 1.1 and 1.2.

To specify the SOAP version that is advertised in the WSDL of your Web service, specify the following parameter:

SOAPVERSION

Specifies the SOAP version or versions required in any SOAP requests that this Web service receives. Use oneof the following values:

• "" — Use this value for SOAP 1.1 or 1.2.

• "1.1" — Use this value for SOAP 1.1. This is the default.

• "1.2" — Use this value for SOAP 1.2.

When the Web service receives a SOAP request, the SoapVersion property of the Web service is updated to equal the SOAPversion of that request. If the request does not use the required SOAP version, the Web service returns a Misunderstoodfault.

2.6 Viewing the WSDLWhen you use %SOAP.WebService to define a Web service, Caché creates and publishes a WSDL document that describesthis Web service. Whenever you modify and recompile the Web service, Caché automatically updates the WSDL corre-spondingly. This section discusses the following:

• Viewing the WSDL and the URL at which the WSDL is published

• Methods you can use to generate the WSDL as a static document

Also see “WSDL Support in Caché” in the first chapter.

2.6.1 Viewing the WSDL

To view the WSDL for the Web service, use the following URL:

base/csp/app/web_serv.cls?WSDL

Here base is the base URL for your Web server (including port if necessary), /csp/app is the name of the CSP applicationin which the Web service resides, and web_serv is the class name of the Web service. (Typically, /csp/app is/csp/namespace.)

Note: Any percent characters (%) in your class name are replaced by underscore characters (_) in this URL.

For example:

http://localhost:57772/csp/samples/MyApp.StockService.cls?WSDL

Or equivalently, click the Service Description link on the catalog page, as described in the chapter “Basics of Creating WebServices.”

16                                                                                                                         Using SOAP and Web Services with Caché

Basics of Creating Web Services

Page 25: Using SOAP and Web Services with Cach©

Either way, the browser displays the WSDL document as an XML document, for example:

2.6.2 Generating the WSDL

You can also generate the WSDL as a static document. The %SOAP.WebService class provides two methods you can usefor this:

FileWSDL()

Writes the WSDL to the specified filename. This method takes one argument, the filename.

Note: Before you use this method, be sure to specify the LOCATION parameter of the Web service. Otherwisethe WSDL does not include an address for the service.

GenerateWSDL()

Writes the WSDL to the current device. This method takes no arguments.

Neither method returns a value.

2.7 Testing the Web ServiceTo test your Web service, you can use tracing tools such as Wireshark, ProxyTrace, tcpTrace, or other commercial toolssuch as XMLSpy. Tracing tools enable you to see the actual method call, as well as the response. The method calls shownin this book were obtained via such a tool.

2.8 Logging the SOAP CallsTo log the SOAP calls made to or from a Caché namespace, set the following nodes of the ^ISCSOAP global:

Using SOAP and Web Services with Caché                                                                                                                         17

Testing the Web Service

Page 26: Using SOAP and Web Services with Cach©

PurposeNode

Specifies kind of logging. Use one of the following values:^ISCSOAP("Log")

• "i" — General input information

• "o" — General input information

• "s" — Security information

You can also use a string that contains any combination of thesevalues, for example: "ios"

Specifies the complete path and filename of the log file to create.^ISCSOAP("LogFile")

Note: You can use these to log both calls to any Caché Web service in the current namespace as well as any calls fromCaché Web clients in the current namespace. Caché Web clients are discussed later in this book.

18                                                                                                                         Using SOAP and Web Services with Caché

Basics of Creating Web Services

Page 27: Using SOAP and Web Services with Cach©

3Creating Web Methods

This chapter describes how to create different kinds of Web methods within a Web service class. It discusses:

• Basic requirements for a Web method

• How to return values by reference or as output

• How to use objects as arguments or return values

• How to use collections as arguments or return values

• How to use data sets as arguments or return values

• How to use nonprinting values as arguments or return values

• How to use a class query as a Web method

• How to specify the binding style (document or rpc) of the SOAP messages sent and received by the Web service

• How to specify the encoding (literal or SOAP-encoded) of these SOAP messages

3.1 Basic RequirementsThis section lists the basic requirements for defining a Web method within a Web service class.

• To use an instance method or class method as a Web method:

– Mark the method with the WebMethod keyword.

– If the method uses an object as an argument or a return value, you must ensure that the object is XML-enabled.That is, the class definitions for the types must extend %XML.Adaptor. The default settings for this class are normallysuitable; if not, see the book Using XML with Caché.

– If the method uses a data set as an argument or return value, you must ensure the data set is of 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 thatthe ELEMENTTYPE parameter of the collection is set and refers to an XML-enabled class.

• To use a class query as a Web method, mark the query with the WebMethod keyword.

Using SOAP and Web Services with Caché                                                                                                                         19

Page 28: Using SOAP and Web Services with Cach©

Important: In most cases, Web methods should be instance methods. Within a Web method, it is often necessary toset properties of and invoke methods of the Web service instance (as described in later chapters) to fine-tune the behavior of the method. Because a class method cannot do these tasks, a class method is usuallyless suitable as a Web method.

Note that a Web service contains only the Web methods defined in the Web service class. By design, any inherited methodsare ignored, even if they are marked as Web methods.

3.1.1 Example

If a method or class method does not have any inputs or outputs that are objects or data sets, only one step is needed tomake it into a Web method. Simply add the WebMethod keyword to its definition:

/// This method returns tomorrow's price for the requested stock./// This method is provided free from any warranty or promises.Method Forecast(StockName As %String) As %Integer [WebMethod]{ // apply patented, nonlinear, heuristic to find new price Set price = $Random(1000) Quit price}

When you invoke this method from a Web service, it sends a SOAP message to the Web service. This SOAP messagemight look like the following (with line breaks and spaces added here for readability):

<?xml version="1.0" encoding="UTF-8" ?><SOAP-ENV:Envelope xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:s='http://www.w3.org/2001/XMLSchema'> <SOAP-ENV:Body> <Forecast xmlns="http://tempuri.org"> <StockName xsi:type="s:string">GZP</StockName> </Forecast> </SOAP-ENV:Body></SOAP-ENV:Envelope>

The Web service performs the requested action and then sends a SOAP message in reply. The response message mightlook like the following:

<?xml version="1.0" encoding="UTF-8" ?><SOAP-ENV:Envelope xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:s='http://www.w3.org/2001/XMLSchema'> <SOAP-ENV:Body> <ForecastResponse xmlns="http://www.myapp.org"> <ForecastResult>799</ForecastResult> </ForecastResponse> </SOAP-ENV:Body></SOAP-ENV:Envelope>

3.2 Returning Values by Reference or as OutputTo return values by reference or as output, use the ByRef or Output keyword, as appropriate, within the signature of theWeb method. This change affects the SOAP response message.

For example, consider the following Web method which has a return value:

Method DoIt() As %String [ WebMethod ]{ set ans="Answer" Quit ans}

20                                                                                                                         Using SOAP and Web Services with Caché

Creating Web Methods

Page 29: Using SOAP and Web Services with Cach©

The body of the response message for this Web method is as follows:

<SOAP-ENV:Body> <DoItResponse xmlns="http://www.myapp.org"> <DoItResult>Answer</DoItResult> </DoItResponse></SOAP-ENV:Body>

In contrast, consider the following variation of the previously shown Web method. This method does not have a directreturn value but returns a value by reference:

Method DoIt2(Output ans as %String) [ WebMethod ]{ set ans="Answer" Quit}

The body of the response message for this variation is as follows:

<SOAP-ENV:Body> <DoIt2Response xmlns="http://www.myapp.org"> <ans>Answer</ans> </DoIt2Response></SOAP-ENV:Body>

Notice that the child of the <methodnameResponse> element is <ans>, which is the name of the output variable within themessage signature. In the previous case, the child of the <methodnameResponse> element was <methodnameResult>.

If you use the ByRef keyword instead of Output, that has the same effect on the response message.

You can include multiple output parameters within a single Web method, and you can also include input arguments asneeded.

3.3 Using an Object as Input or OutputIf you need to use an object as an argument or as a return value for a Web method, that object must be XML-enabled. Thatis, its class definition must extend %XML.Adaptor; then any instance of the class can be projected as XML.

For example, suppose you wrote a Web method that accepts two complex numbers (that is, numbers that have real andimaginary components) as input values and returns their sum. This method might look like this:

Method Add(a As ComplexNumber,b As ComplexNumber) As ComplexNumber [WebMethod]{ Set sum = ##class(ComplexNumber).%New() Set sum.Real = a.Real + b.Real Set sum.Imaginary = a.Imaginary + b.Imaginary

Quit sum}

You can use this method as a Web method only if the ComplexNumber class extends %XML.Adaptor. The ComplexNumberclass is defined as follows:

/// A complex numberClass MyApp.ComplexNumber Extends (%RegisteredObject,%XML.Adaptor) {Property Real As %Float;Property Imaginary As %Float;}

The default settings for %XML.Adaptor are normally suitable. For details, see the book Using XML with Caché.

Using SOAP and Web Services with Caché                                                                                                                         21

Using an Object as Input or Output

Page 30: Using SOAP and Web Services with Cach©

3.4 Using a Collection as Input or OutputIf you need to use a collection (%ListOfObjects or %ArrayOfObjects) as an argument or as a return value for a Web method,you must ensure that the ELEMENTTYPE parameter of the collection is set and refers to an XML-enabled class. Otherwise,the WSDL does not define all the needed types, and the Web service is not usable.

For %ListOfObjects, you can do this in two different ways:

• You can specify a value for the ELEMENTTYPE parameter within the method signature, for example:

Method MyMethod() As %ListOfObjects(ELEMENTTYPE="MyApp.MyXMLType") [ WebMethod ]{ //method implementation}

• You can create a subclass of %ListOfObjects and specify a value for the parameter in the subclass, for example:

Class MyApp.MyListOfObjects Extends %ListOfObjects{

Parameter ELEMENTTYPE = "MyApp.MyXMLType";

}

Then use this subclass as the type in your method signature.

Method MyMethod() As MyApp.MyListOfObjects [WebMethod]{ //method implementation}

For %ArrayOfObjects, you must create and use a subclass.

3.5 Using a Data Set as Input or OutputThis section describes how to use a data set as an argument or return value to a Web method. It provides the details on thefollowing:

• General introduction to %XML.DataSet

• How to define a typed data set, a subclass of %XML.DataSet

• How to create methods that return data sets

• How to create methods that use data sets as input

• How to work with data sets

• How to control the format of data sets

• Utility methods that let you see data sets as XML

Also see “Using a Class Query as a Web Method.”

22                                                                                                                         Using SOAP and Web Services with Caché

Creating Web Methods

Page 31: Using SOAP and Web Services with Cach©

3.5.1 About %XML.DataSet

In general, to create a data set that you can use as an argument or return value to a Web method, you use %XML.DataSet

or a custom subclass. This class is an XML-enabled subclass of the standard %ResultSet, and you use it in approximatelythe same way you use %ResultSet.

Note: The WSDL schema and XML format of %XML.DataSet are in proprietary Microsoft data set format. Only Cachéor .NET web clients can understand this format. To output results of a query so that a Java-based Web client canwork with it, use a %ListOfObjects subclass; there is an example in SOAP.Demo in the SAMPLES namespace.

3.5.2 Defining a Typed Data Set

Any data set uses a query that specifies the data to retrieve. If the query is known at compile time, the data set is typed;otherwise it is untyped. Typed data sets are convenient in many cases; for example, in .NET, a typed data set allows codecompletion in Microsoft Visual Studio.

To define a typed data set, create a subclass of %XML.DataSet and specify the QUERYNAME and CLASSNAME parameters.Together, these parameters refer to a specific SQL query. Then use this subclass as described in the next section.

Note: If you use %XML.DataSet as the return value for a method, the XML type for that value is DataSet. On the otherhand, if you use a subclass of %XML.DataSet as the return value, the XML type for the value is the name of thatsubclass. This behavior is the same as that of other XML-enabled classes, and it affects the XML types that aredescribed in the WSDL. For more information on controlling the XML types of your XML-enabled objects, seethe book Using XML with Caché.

3.5.3 Returning a Data Set

To return a data set, the Web method must do the following:

1. The return type must be %XML.DataSet or a custom subclass.

2. The Web method must create an instance of %XML.DataSet or your custom subclass and initialize it with the informationneeded to perform the query. The options here are the same as for the %ResultSet class:

• If you have defined a class query within the class of interest, use that class query as follows: Create a data set viathe %New() method and then set its ClassName and QueryName properties (if needed). Here the query namerefers to a class query that you have defined in the class of interest. For example:

/// Get all saved people; technique 1 for the docMethod GetPeople1() As %XML.DataSet [ WebMethod ]{ set dataset=##class(%XML.DataSet).%New() set dataset.ClassName="Sample.Person" set dataset.QueryName="GetPeople" Quit dataset}

See “Example 2: A Typed Data Set” for a variation of this method.

• As a variation on the preceding, create a data set via %New() method, providing a string argument that consistsof the class name, followed by a colon, followed by the class query name. For example:

/// Get all saved people; technique 2 for the docMethod GetPeople2() As %XML.DataSet [ WebMethod ]{ set dataset=##class(%XML.DataSet).%New("Sample.Person:GetPeople") Quit dataset

}

Using SOAP and Web Services with Caché                                                                                                                         23

Using a Data Set as Input or Output

Page 32: Using SOAP and Web Services with Cach©

• Create a data set via %New() method, providing the string argument "%DynamicQuery:SQL". Next invoke thePrepare() method of the data set, providing a string argument that consists of a SQL query. For example:

/// Get all saved people; technique 3 for the docMethod GetPeople3() As %XML.DataSet [ WebMethod ]{ set dataset=##class(%XML.DataSet).%New("%DynamicQuery:SQL") set mysql = "SELECT Name,DOB FROM Sample.Person" set status=dataset.Prepare(mysql) if $$$ISERR(status) do ..StatusError(status) Quit dataset}

Note that the Prepare() method returns a status, which your code should check. In this example, StatusErroris another method defined within this Web service; it extracts the error string from the status object and returnsthat string within a SOAP fault (and does not return control to the method shown here). Fault handling is discussedin the chapter “SOAP Fault Handling.”

3. Call the Execute() method of the data set, optionally providing any arguments in the order expected by the query. Thismethod returns a status, which your code should check.

4. Return the data set when you quit the method.

3.5.3.1 Example 1: An Untyped Data Set

The following shows an example; this returns an untyped data set:

/// Get all people who have a given home ZIP codeMethod GetPeopleByZip(zip As %String) As %XML.DataSet [ WebMethod ]{ Set dataset=##class(%XML.DataSet).%New("%DynamicQuery:SQL") Set sql1 = "SELECT Name FROM Sample.PersonWithAddress" Set sql2 = " where Sample.PersonWithAddress.Home_Zip = "_zip Set status=dataset.Prepare(sql1_sql2) If $$$ISERR(status) do ..StatusError(status) Set status=dataset.Execute() If $$$ISERR(status) do ..StatusError(status) Quit dataset}

As noted earlier, StatusError is an example method that extracts the error string and returns it within a SOAP fault (anddoes not return control to the method shown here). Fault handling is discussed in the chapter “SOAP Fault Handling.”

3.5.3.2 Example 2: A Typed Data Set

First we define a subclass of %XML.DataSet and specify the query:

Class Sample.PeopleDataSet Extends %XML.DataSet{

Parameter QUERYNAME = "GetPeople";

Parameter CLASSNAME = "Sample.Person";

}

Here we assume that the Sample.Person class contains a class query named GetPeople (not shown here).

The following Web method uses the preceding subclass and returns a typed data set:

/// Get all saved people; technique 4 for the docMethod GetPeople4() As Sample.PeopleDataSet [ WebMethod ]{ set dataset=##class(Sample.PeopleDataSet).%New() Quit dataset}

24                                                                                                                         Using SOAP and Web Services with Caché

Creating Web Methods

Page 33: Using SOAP and Web Services with Cach©

3.5.4 Using a Data Set as an Input Argument

To use a data set as an input argument for a Web method, make sure that the data set extends %XML.DataSet. For example,the signature of the Web method might look like the following:

Method ProcessDataSet(dataset as %XML.DataSet) As %String [ WebMethod ]{}

The following section provides information on how such a method can use the data set.

3.5.5 Working with a Data Set

The %XML.DataSet class provides the same general interface for examining a data set as does the %ResultSet class.Specifically, you examine the data set, one row at a time; you use methods to retrieve information such as the value in agiven column. To advance to the next row, you use the Next() method; typically you iterate through all the rows until youreach the end, when Next() returns 0.

The Next() method also returns 0 if an error occurs.

The data set instance is destroyed when your method completes, but if you want to close the data set within your methodbody, use the Close() method.

3.5.5.1 Typical Structure

The following example shows the outline of a method that uses a data set:

Method ProcessDataSet(dataset as %XML.DataSet) As %String [ WebMethod ]{ Set returnvalue="" While (dataset.Next(.status)) { //do stuff and set returnvalue } Quit returnvalue}

3.5.5.2 Example

A simple example follows; this counts all rows in the given data set:

/// count rows in datasetMethod CountRows(dataset as %XML.DataSet) As %Numeric [ WebMethod ]{ Set count=0 While (dataset.Next(.status)) { Set count=count+1 } Quit count}

Note that you cannot use the generated test Web page to test this method because the input is an object.

3.5.5.3 Available Methods for Examining the Data Set

Data sets inherit a common set of methods that you can use to examine the data set. The most common methods are asfollows:

• GetColumnCount() returns the number of columns in the data set.

• Get() returns data from the column with the given name, for the current row.

• GetData() returns data from the column with the given number, for the current row. The first column is 1.

Using SOAP and Web Services with Caché                                                                                                                         25

Using a Data Set as Input or Output

Page 34: Using SOAP and Web Services with Cach©

• GetColumnHeader()) returns the header of the column with the given number.

• GetColumnName() returns the name of the column with the given number.

• GetColumnType() returns the data type of the column with the given number. This method returns an integer corre-sponding to a specific data type; for information on what the integer values represent, see the class documentation for%Library.ResultSet.

3.5.6 Controlling the Format of the Data Set

By default, a data set is written in Microsoft DiffGram format and is preceded by its XML schema. The following showsan example:

<SOAP-ENV:Body> <Get0Response xmlns="http://www.myapp.org"> <Get0Result> <s:schema id="DefaultDataSet" xmlns="" attributeFormDefault="qualified" elementFormDefault="qualified" xmlns:s="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> <s:element name="DefaultDataSet" msdata:IsDataSet="true"> <s:complexType> <s:choice maxOccurs="unbounded"> <s:element name="GetPeople"> <s:complexType> <s:sequence> <s:element name="Name" type="s:string" minOccurs="0" /> <s:element name="DOB" type="s:date" minOccurs="0" /> </s:sequence> </s:complexType> </s:element> </s:choice> </s:complexType> </s:element> </s:schema>

<diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1"> <DefaultDataSet xmlns=""> <GetPeople diffgr:id="GetPeople1" msdata:rowOrder="0"> <Name>Quine,Howard Z.</Name> <DOB>1965-11-29</DOB> </GetPeople>... </DefaultDataSet> </diffgr:diffgram> </Get0Result> </Get0Response> </SOAP-ENV:Body>

The %XML.DataSet class provides the following options for controlling this format:

• The DATAONLY parameter and the DiffGram property control whether the output is in DiffGram format. By default,the output is in DiffGram format, which is shown above. If you subclass %XML.DataSet and set DATAONLY equal to1, or if you set the DiffGram equal to 0, the output is not in DiffGram format. The body of the XML data set is as followsinstead:

<SOAP-ENV:Body> <Get0Response xmlns="http://www.myapp.org"> <Get0Result> <GetPeople xmlns=""> <Name>Quine,Howard Z.</Name> <DOB>1965-11-29</DOB> </GetPeople> <GetPeople xmlns="">... </Get0Result> </Get0Response> </SOAP-ENV:Body>

26                                                                                                                         Using SOAP and Web Services with Caché

Creating Web Methods

Page 35: Using SOAP and Web Services with Cach©

In contrast to DiffGram format, notice that the schema is not output by default and that the output does not include the<diffgram> element.

• The NeedSchema property controls whether the output includes the XML schema. If you are using DiffGram format,the default is to output the schema; if you are not using DiffGram format, the default is not to output the schema. Toforce output of the schema, set NeedSchema equal to 1, or to suppress output of the schema, set it equal to 0.

• If you use DiffGram format, the WriteEmptyDiffgram property controls the contents of the <diffgram> element in thecase when the data set has no rows. By default (or if WriteEmptyDiffgram equals 0), the <diffgram> element containsan empty element as follows:

...<diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1"> <DefaultDataSet xmlns=""> </DefaultDataSet></diffgr:diffgram>...

In contrast, if WriteEmptyDiffgram equals 1, the <diffgram> element contains nothing:

...<diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" </diffgr:diffgram>...

This property has no effect if you are not using DiffGram format.

• If you use DiffGram format, the DataSetName property controls the name of the element within the <diffgram> element.By default, this element is named <DefaultDataSet>, as you can see in the example above. This property has no effectif you are not using DiffGram format.

3.5.7 Viewing the Data Set and Schema as XML

A data set that extends %XML.DataSet has utility methods that you can use to generate XML. All of these methods writeto the current device:

• WriteXML() writes the data set as XML, optionally preceded by the XML schema. This method has optional argumentsto control the name of the top-level tag, the use of namespaces, treatment of nulls, and so on. By default, this methodconsiders the format of the data set, as specified by the settings in the previous section. You can override that resultby providing values for optional arguments that control whether the output is in DiffGram format and so on. For details,see the class documentation for %XML.DataSet.

• XMLExport() writes the XML schema for the data set, followed by the data set as XML.

• WriteSchema() writes just the XML schema for the data set.

• XMLSchema() writes the Microsoft proprietary XML representation of its data set class.

For information on generating XML schemas from XML-enabled objects, see the book Using XML with Caché..

3.6 Using Nonprinting Characters in Input or OutputXML does not permit nonprinting characters, specifically characters below ASCII 32 (except for carriage return, line feed,and tab, which are permitted in XML).

Using SOAP and Web Services with Caché                                                                                                                         27

Using Nonprinting Characters in Input or Output

Page 36: Using SOAP and Web Services with Cach©

If you need to include a property in a SOAP message and that property contains any of these nonprinting characters, thatproperty must be of type %Binary or %xsd.base64Binary (which is equivalent). This value is automatically converted tobase–64 encoding on export to XML (or automatically converted from base–64 encoding on import).

3.7 Using a Class Query as a Web MethodYou can use a class query as a Web method; a class query returns a typed data set. Simply add the WebMethod keywordto the definition of the query.

For example:

Query QueryByName(name As %String = "") As %SQLQuery(CONTAINID = 1, SELECTMODE = "RUNTIME") [WebMethod]{ SELECT ID, Name, DOB, SSN FROM Sample.Person WHERE (Name %STARTSWITH :name) ORDER BY Name}

When this Web method is executed, it returns a data set in SOAP format, as follows:

<SOAP-ENV:Envelope xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:s='http://www.w3.org/2001/XMLSchema'>

<SOAP-ENV:Body><QueryByNameResponse xmlns="http://www.myapp.org"><QueryByNameResult><s:schema id="QueryByName_DataSet" targetNamespace="http://www.myapp.org/QueryByName_DataSet" xmlns="http://www.myapp.org/QueryByName_DataSet" xmlns:mstns="http://www.myapp.org/QueryByName_DataSet" attributeFormDefault="qualified" elementFormDefault="qualified" xmlns:s="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> <s:element name="QueryByName_DataSet" msdata:IsDataSet="true"> <s:complexType> <s:choice maxOccurs="unbounded"> <s:element name="QueryByName"> <s:complexType> <s:sequence> <s:element name="ID" type="s:long" minOccurs="0" /> <s:element name="Name" type="s:string" minOccurs="0" /> <s:element name="DOB" type="s:date" minOccurs="0" /> <s:element name="SSN" type="s:string" minOccurs="0" /> </s:sequence> </s:complexType> </s:element> </s:choice> </s:complexType> <s:unique name="Constraint1" msdata:PrimaryKey="true"> <s:selector xpath=".//mstns:QueryByName" /> <s:field xpath="mstns:ID" /> </s:unique> </s:element></s:schema> <diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1"> <QueryByName_DataSet xmlns="http://www.myapp.org/QueryByName_DataSet"> <QueryByName diffgr:id="QueryByName1" msdata:rowOrder="0"> <ID>1</ID> <Name>Xerxes,Dave L.</Name> <DOB>1941-12-09</DOB> <SSN>499-23-9251</SSN> </QueryByName> </QueryByName_DataSet> </diffgr:diffgram> </QueryByNameResult></QueryByNameResponse> </SOAP-ENV:Body></SOAP-ENV:Envelope>

Also see “Using a Data Set as Input or Output.”

28                                                                                                                         Using SOAP and Web Services with Caché

Creating Web Methods

Page 37: Using SOAP and Web Services with Cach©

3.8 Specifying the Binding Style for the SOAP MessagesThe SoapBindingStyle keyword controls the binding style for the input and outputs for the Web method. This specifieshow to translate a WSDL binding to a SOAP message and it controls the format of the body of the SOAP messages. Youcan specify either document (the default) or rpc for this keyword, which is available at the class level and the methodlevel.

Note: By default, the header elements are in literal format (rather than SOAP-encoded), independent of SoapBindingStyle.See the section “Creating Custom Header Elements,” later in this book.

3.8.1 Document-style Binding

The following SOAP message was generated in response to a Web method with SoapBindingStyle equal to document,the default setting. Line breaks and spaces have been added for readability.

<?xml version="1.0" encoding="UTF-8" ?> <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:s="http://www.w3.org/2001/XMLSchema"> <SOAP-ENV:Body> <DivideResponse xmlns="http://www.myapp.org"> <DivideResult>.5</DivideResult> </DivideResponse> </SOAP-ENV:Body></SOAP-ENV:Envelope>

3.8.2 RPC-style Binding

In contrast, the following SOAP message was generated in response to a Web method with SoapBindingStyle equal torpc:

<?xml version="1.0" encoding="UTF-8" ?><SOAP-ENV:Envelope xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:s='http://www.w3.org/2001/XMLSchema' xmlns:tns='http://www.myapp.org'> <SOAP-ENV:Body> <tns:DivideResponse> <tns:DivideResult>.5</tns:DivideResult> </tns:DivideResponse> </SOAP-ENV:Body></SOAP-ENV:Envelope>

3.9 Specifying the Encoding for the SOAP MessagesThe SoapBodyUse keyword controls the encoding for the input and outputs for the Web method. You can specify eitherliteral (the default) or encoded for this keyword, which is available at the class level and the method level. Most SOAPclients, including .NET, default to literal format; encoded format is generally considered outdated.

Note: The SoapBodyUse keyword affects the default values for the ELEMENTQUALIFIED and XMLELEMENTparameters, which affect the WSDL; see the chapter “Fine-tuning a Caché Web Service.”

The following subsections contain examples of output from Web methods with different settings of SoapBodyUse. Linebreaks have been added for readability. Both examples show the same object, PersonWithAddress, which has theproperties Name, DOB, FavoriteColors (a list of strings), and Home (an Address object) and Office, another Address.

Using SOAP and Web Services with Caché                                                                                                                         29

Specifying the Binding Style for the SOAP Messages

Page 38: Using SOAP and Web Services with Cach©

3.9.1 Literal Data

The following SOAP message was generated in response to a Web method with SoapBodyUse equal to literal, thedefault setting. Line breaks and spaces have been added for readability.

<?xml version="1.0" encoding="UTF-8" ?><SOAP-ENV:Envelope xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:s='http://www.w3.org/2001/XMLSchema'> <SOAP-ENV:Body> <GetPerson2Response xmlns="http://www.myapp.org"> <GetPerson2Result> <Name>Wijnschenk,Bob F.</Name> <DOB>1963-05-01</DOB> <FavoriteColors> <FavoriteColorsItem>Orange</FavoriteColorsItem> </FavoriteColors> <Home> <Street>455 Main Blvd</Street> <City>Xavier</City> <State>MD</State> <Zip>21692</Zip> </Home> <Office> <Street>8074 Madison Place</Street> <City>Reston</City> <State>IA</State> <Zip>29289</Zip> </Office> </GetPerson2Result> </GetPerson2Response> </SOAP-ENV:Body>

</SOAP-ENV:Envelope>

3.9.2 SOAP-encoded Data

In contrast, the following SOAP message was generated in response to a Web method with SoapBodyUse equal to encoded.

Note: For SOAP 1.2, the encoded version is slightly different.

<?xml version="1.0" encoding="UTF-8" ?><SOAP-ENV:Envelope xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:s='http://www.w3.org/2001/XMLSchema' xmlns:SOAP-ENC='http://schemas.xmlsoap.org/soap/encoding/' xmlns:types='http://www.myapp.org/encodedTypes'> <SOAP-ENV:Body SOAP-ENV:encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'> <types:GetPerson2EncResponse> <GetPerson2EncResult href="#id1" /> </types:GetPerson2EncResponse> <types:PersonWithAddress id="id1" xsi:type="types:PersonWithAddress"> <Name>Wijnschenk,Bob F.</Name> <DOB>1963-05-01</DOB> <FavoriteColors SOAP-ENC:arrayType="s:string[1]"> <FavoriteColorsItem>Orange</FavoriteColorsItem> </FavoriteColors> <Home xsi:type="types:Address"> <Street>455 Main Blvd</Street> <City>Xavier</City> <State>MD</State> <Zip>21692</Zip> </Home> <Office xsi:type="types:Address"> <Street>8074 Madison Place</Street> <City>Reston</City> <State>IA</State> <Zip>29289</Zip> </Office> </types:PersonWithAddress> </SOAP-ENV:Body>

</SOAP-ENV:Envelope>

30                                                                                                                         Using SOAP and Web Services with Caché

Creating Web Methods

Page 39: Using SOAP and Web Services with Cach©

For more information on the differences between literal format and SOAP-encoded format, see the book Using XML withCaché.

Using SOAP and Web Services with Caché                                                                                                                         31

Specifying the Encoding for the SOAP Messages

Page 40: Using SOAP and Web Services with Cach©
Page 41: Using SOAP and Web Services with Cach©

4Creating Web Clients

A Web client is software that accesses a Web service. A Web client provides a set of proxy methods, each of which corre-sponds to a method of the Web service. A proxy method uses the same signature as the Web service method to which itcorresponds, and it invokes the Web service method when asked to do so. This chapter describes how to create and useWeb clients in Caché:

• An overview of the Caché SOAP client wizard

• How to use the SOAP client wizard

• How to invoke the Caché client wizard programmatically

• How to adjust the generated classes to accommodate long strings

• Basic settings of the Caché Web client class set by the client wizard

• An example of the generated classes

• How to use the generated Web client class in general

• Configuring the client to use SSL to communicate with the Web service

• How to access the HTTP response that the Caché Web client receives

For information on logging SOAP calls to your Caché Web clients, see “Logging the SOAP Calls,” earlier in this book.

Also see the chapter “Fine-tuning a Caché Web Client.”

4.1 Overview of the Caché SOAP Client WizardTo create a Caché Web client, you can use the SOAP client wizard in Caché Studio or the corresponding class methodprovided by Caché. In either case, the tool uses a given WSDL document to create a Web client that corresponds to thatWeb service. Specifically, it creates a Web client class and all needed supporting classes.

You can use the tool with nearly any WSDL document; see “WSDL Support in Caché” in the first chapter. You mightfind it interesting to experiment with publicly available WSDL documents from the internet.

You can provide the URL or the file path for the WSDL.

Using SOAP and Web Services with Caché                                                                                                                         33

Page 42: Using SOAP and Web Services with Cach©

4.2 Using the SOAP Client WizardTo use the SOAP client wizard to create a client for a given Web service:

1. In Studio, make sure that you are in the appropriate Caché 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 want to work with.

If the WSDL is protected by a username and password, you can sometimes append a string to the URL that providesa suitable username and password.

For example, if the Web service is located in a Caché installation that has security enabled, you would append a stringlike the following (using the username _SYSTEM and password SYS as an example):

&CacheUserName=_SYSTEM&CachePassword=SYS

Alternatively, you could disable password protection for the CSP application.

Another option, available in all cases, is to save the WSDL as a file and use that file as input. In this case, you woulduse the Process() class method of %SOAP.WSDL.Reader. See the next section.

4. Click Next.

If the WSDL is at a location that uses SSL (that is, if the URL starts with https), then the dialog box displays thefield SSL Configuration.

5. Type the configuration name of an existing Secure Socket Layer (SSL) or Transport Layer Security (TLS) configurationto use to authenticate this connection.

For information on creating and managing SSL/TLS configurations, see the chapter “Using SSL/TLS with Caché”in the Caché Security Administration Guide.

6. Click Next.

The wizard then displays a screen like the following:

34                                                                                                                         Using SOAP and Web Services with Caché

Creating Web Clients

Page 43: Using SOAP and Web Services with Cach©

If you have an Ensemble installation, the screen has additional options.

7. For Class Type, choose a general type for the Web client class: registered object (the default), persistent, or serial.

8. For Proxy Class Package, type a package name for the Web client. This is also used as the base package for any generatedtype classes. The default package name is the service name.

If this package is the same as an existing package, by default the tool overwrites any existing classes that have thesame name.

9. If you have an Ensemble installation, optionally provide values for the following additional fields:

• Create Business Operation — Select this to generate an Ensemble business operation and related request andresponse message classes.

• Business Operation Package — Specify the package for the business operation class.

• Request Package — Specify the package for the request message class.

• Response Package — Specify the package for the response message class.

For information on Ensemble, see the Ensemble documentation.

10. Click Next. The wizard then displays a screen like the following:

Using SOAP and Web Services with Caché                                                                                                                         35

Using the SOAP Client Wizard

Page 44: Using SOAP and Web Services with Cach©

On this screen, you specify the packages for any generated type classes. The wizard detects all the namespaces usedin the WSDL, including any that are implied, and shows the default package names it will use for any type classes thatit will generate, if the types belong in those namespaces.

For example, the WSDL used here includes a type (ComplexNumber), which is in the namespacehttp://www.complexnumbers.org. The wizard will generate a type class to represent ComplexNumber, andwill generate that class within the package GSOPClient.ns2.

Note that not all namespaces shown here necessarily contain have types. In the example here, the WSDL uses thenamespaces http://schemas.xmlsoap.org/wsdl, http://schemas.xmlsoap.org/wsdl/mime,http://schemas.xmlsoap.org/wsdl/soap, and http://tempuri.org. No types are in these namespacesin this case.

11. Optionally edit the package names.

12. If possible, optionally select or clear Add NAMESPACE Class Parameter, which affects how generated type classes areassigned to namespaces:

• If the WSDL explicitly indicates the namespace to which a given type belongs, Add NAMESPACE Class Parameter

is selected and grayed out. In this case, the generated type class will include the NAMESPACE class parameterset equal to that namespace.

• If the WSDL does not indicate the namespace for a given type, you can select or clear Add NAMESPACE Class

Parameter.

If you select this option, the generated type class will include the NAMESPACE class parameter set equal to thenamespace of the Web service.

If you clear this option, the generated type class will not include the NAMESPACE class parameter

13. Click Next. The wizard generates and compiles the classes and displays a list of these classes.

14. Click Finish.

36                                                                                                                         Using SOAP and Web Services with Caché

Creating Web Clients

Page 45: Using SOAP and Web Services with Cach©

Note: If the Web service is located in a Caché installation that has security enabled, and if you do not include a usernameand password in the URL, the wizard generates a message like the following:

ERROR #6301: SAX XML Parser Error: Expected entity name for reference while processing Anonymous Stream at line 10 offset 27

4.3 Using the Process() MethodThe SOAP client wizard is also available as the Process() method of the %SOAP.WSDL.Reader class. To use this method:

1. Create an instance of %SOAP.WSDL.Reader.

2. Optionally set properties to control the behavior of your instance:

• CompileFlags — Specifies the flags to use when compiling the Web client classes. The initial expression is "dk";see the note after the list.

• MakePersistent — If this property is 1, the Web client is a persistent object; otherwise, it is a registered object.The initial expression is 0.

• MakeSerial — If this property is 1 and if MakePersistent is 1, the Web client is a serial class. The initial expressionis 0.

• MakeNamespace — Controls how generated type classes are assigned to namespaces. See the previous sectionfor details.

• OutputTypeAttribute — Controls how the SOAP client wizard sets the OUTPUTTYPEATTRIBUTE parameter inthe Web client that it generates. See the section “Controlling Use of the xsi:type Attribute” in the chapter “Fine-tuning the Web Client.”

• MakeBusinessOperation — Specifies whether to generate an Ensemble Web client (which is a business operation)and related request and response classes. This option works only if you are working within an Ensemble-enablednamespace.

• SSLConfiguration — Specifies the configuration name of an existing Secure Socket Layer (SSL) or TransportLayer Security (TLS) configuration to use to authenticate this connection.

For information on creating and managing SSL/TLS configurations, see the chapter “Using SSL/TLS with Caché”in the Caché Security Administration Guide.

For other properties, see the class documentation for %SOAP.WSDL.Reader.

3. Invoke the Process() method:

method Process(pLocationURL As %String, pPackage As %String = "") as %Status

• pLocationURL must be the URL of the WSDL of the Web service or the name of the WSDL file (including itscomplete path). Depending on the configuration of the Web service, it may be necessary to append a string thatprovides a suitable username and password; see the examples.

• pPackage is the name of the package in which to place the generated classes. If you do not specify a package,Caché uses the service name as the package name.

Note: If this package is the same as an existing package, by default the tool overwrites any existing classesthat have the same name. To prevent the tool from overwriting a class definition, add the XMLKEEPCLASSparameter to that class and set this parameter equal to 1.

Using SOAP and Web Services with Caché                                                                                                                         37

Using the Process() Method

Page 46: Using SOAP and Web Services with Cach©

Tip: If you use the CompileFlags property, you need information about the available compiler flags. To get this information,execute the following command:

Do $System.OBJ.ShowFlags()

4.3.1 Example 1: Using an Ordinary WSDL

The following shows an example Terminal session:

GSOP>set r=##class(%SOAP.WSDL.Reader).%New()

GSOP>set url="http://localhost:57772/csp/gsop/GSOP.AddComplexWS.CLS?WSDL=1"

Compilation started on 11/14/2008 13:21:26 with qualifiers 'dk'Compiling class MyClient2.ns2.ComplexNumberCompiling routine MyClient2.ns2.ComplexNumber.1Compilation finished successfully in 0.104s.

Compilation started on 11/14/2008 13:21:26 with qualifiers 'dk'Compiling class MyClient2.AddComplexSoapCompiling routine MyClient2.AddComplexSoap.1Compiling class MyClient2.AddComplexSoap.AddCompiling routine MyClient2.AddComplexSoap.Add.1Compilation finished successfully in 0.452s.

4.3.2 Example 2: Using a Password-protected WSDL

In some cases, the WSDL may be protected by a username and password. In such cases, you can sometimes append a stringto the URL that provides a suitable username and password.

For example, if the Web service is located in a Caché installation that has security enabled, you would append a string likethe following (using the username _SYSTEM and password SYS as an example):

&CacheUserName=_SYSTEM&CachePassword=SYS

The following shows an example Terminal session:

GSOP>set r=##class(%SOAP.WSDL.Reader).%New()

GSOP>set url1="http://localhost:57772/csp/gsop/GSOP.AddComplexWS.CLS?WSDL=1"

GSOP>set url=url1_"&CacheUserName=_SYSTEM&CachePassword=SYS"

GSOP>set status=r.Process(url,"MyClient3")

Compilation started on 11/14/2008 13:20:00 with qualifiers 'dk'Compiling class MyClient3.ns2.ComplexNumberCompiling routine MyClient3.ns2.ComplexNumber.1Compilation finished successfully in 0.171s.

Compilation started on 11/14/2008 13:20:00 with qualifiers 'dk'Compiling class MyClient3.AddComplexSoapCompiling routine MyClient3.AddComplexSoap.1Compiling class MyClient3.AddComplexSoap.AddCompiling routine MyClient3.AddComplexSoap.Add.1Compilation finished successfully in 0.486s.

The preceding approach may not work, depending on your security. If it does not work, retrieve the WSDL from a browserafter supplying the required username and password, save it as a file, and use the file instead.

38                                                                                                                         Using SOAP and Web Services with Caché

Creating Web Clients

Page 47: Using SOAP and Web Services with Cach©

4.4 Adjusting the Generated Classes for Long StringsWhen the Caché SOAP client wizard reads a WSDL, it assumes that any string-type input or output can be represented inCaché as %String, which is not always true. Some strings might exceed the Caché 32 kB limit for strings, and there is noinformation in the WSDL to inform the Caché SOAP client wizard of this.

If you have enabled long strings in Caché, your Web client works.

If you have not enabled long strings in Caché, however, your Web client throws an error when it encounters a string thatis too long.

The problem, however, is easy to correct. Adjust the method signature in your generated Web client class (specifically theclass that inherits from %SOAP.WebClient) so that it uses %GlobalCharacterStream instead of %String.

For example, consider a Web service (MyGiantStringService) that has one method (WriteIt), which takes noarguments and returns a very long string, greater than 32 kB. If you use the Caché SOAP client wizard to generate the Webclient class, the Web client class originally looks something like this:

Class GetGiantString.MyServiceSoap Extends %SOAP.WebClient{

/// This is the URL used to access the web service.Parameter LOCATION="http://localhost:57772/csp/gsop/MyApp.MyGiantStringService.cls";

/// This is the namespace used by the ServiceParameter NAMESPACE = "http://tempuri.org";

/// Use xsi:type attribute for literal types.Parameter OUTPUTTYPEATTRIBUTE = 1;

/// This is the name of the ServiceParameter SERVICENAME = "MyService";

Method WriteIt() As %String [ Final, ProcedureBlock = 1, SoapBindingStyle = document, SoapBodyUse = literal, WebMethod ]{ Quit ..WebMethod("WriteIt"). Invoke(##this,"http://tempuri.org/MyApp.MyGiantStringService.WriteIt")}

}

Note: Because of line-length limitations of the PDF book files, this example includes a line break that is not permittedsyntactically. This line break occurs within the definition of the method.

In this case, there is only one adjustment to make. Edit WriteIt as follows:

Method WriteIt() As %GlobalCharacterStream [ Final, ProcedureBlock = 1, SoapBindingStyle = document, SoapBodyUse = literal, WebMethod ]{ Quit ..WebMethod("WriteIt"). Invoke(##this,"http://tempuri.org/MyApp.MyGiantStringService.WriteIt")}

When you compile this class, Caché automatically regenerates the associated classes as needed.

You may also need to adjust property types within any generated type classes. For example, suppose the Web service usesan element called <Container>, which includes an element <ContainerPart> of type string. When you generate the CachéWeb client classes, Caché creates a Container class with a ContainerPart property of type %String. If the Web servicesends a string longer than 32 kB in the <ContainerPart> element, and if you have not enabled long strings, your Web clientthrows an error. To avoid this error, change the type of the ContainerPart property to %GlobalCharacterStream.

Using SOAP and Web Services with Caché                                                                                                                         39

Adjusting the Generated Classes for Long Strings

Page 48: Using SOAP and Web Services with Cach©

4.5 Basic Settings of a Caché Web ClientWhen the Caché SOAP client wizard generates Web client classes, it automatically sets certain keywords and parameters,described in this section.

Note: Because it is often necessary to create a Web client for a Web service over which you have no control, Cachésupports a greater range of options for the client side than for the Web service. Specifically, although some of thekeywords shown here can be used both within Web services and in Web clients, others are available only on theclient side. The reference documentation for these keywords describes where they can be used.

4.5.1 Endpoint for the Web Client

The SOAP client wizard automatically sets the endpoint for the Web client by setting the LOCATION parameter of theWeb client. By default, it sets this parameter equal to the URL of the Web service with which it communicates.

You can override this by setting the Location property of your Web client instance. If Location is null, then the LOCATIONparameter is used.

4.5.2 SOAP Version of the SOAP Requests

The SOAP client wizard automatically specifies the SOAP version to use in request messages, based on the SOAP versionin the WSDL of the Web service.

In the Web client, the SOAP version is controlled by the SOAPVERSION parameter:

SOAPVERSION

Specifies the SOAP version to use in any SOAP requests sent by this Web client. This equals one of the followingvalues:

• "" — The client sends SOAP 1.1 messages.

• "1.1" — The client sends SOAP 1.1 messages.

• "1.2" — The client sends SOAP 1.2 messages.

You can override this by setting the SoapVersion property of your Web client instance. If SoapVersion is null, then theSOAPVERSION parameter is used.

4.5.3 Encoding and Binding Style

The SOAP client wizard automatically specifies the encoding and binding style for the SOAP messages of the Web clientas follows:

Table 4–1: Encoding and Binding Style for Web Client Messages

Value Given by the SOAP Client WizardItem

Value of the use attribute of <soap:body>.You can specify this forthe class or for specific methods. The method keyword takesprecedence.

SoapBodyUse (keyword)

40                                                                                                                         Using SOAP and Web Services with Caché

Creating Web Clients

Page 49: Using SOAP and Web Services with Cach©

Value Given by the SOAP Client WizardItem

Binding style for the methods.The class keyword controls the value of the style attribute of<soap:binding>.

The method keyword, which takes precedence, controls the styleattribute of <soap:operation>

SoapBindingStyle (keyword)

4.5.4 Namespaces for the Messages from the Client

The SOAP client wizard automatically assigns the SOAP messages (of the Web client) to namespaces as follows.

Table 4–2: Namespaces for SOAP Messages Sent by Web Clients

Value Given by SOAP Client WizardItem

Namespace of the request messages, if all request messages usethe same namespace.

NAMESPACE (Web client parameter)

Namespace of a given request message, if request messages usedifferent namespaces.

SoapNameSpace (method keyword)

Namespace of the response messages. If this is not specified, theresponse messages are in the namespace given by theNAMESPACE parameter. Note that the SoapNameSpace keywordhas no effect on the namespaces of the response messages.

RESPONSENAMESPACE (Web clientparameter)

4.5.5 Namespaces for Types Used by the Client

The types used in the SOAP messages belong to namespaces. The SOAP client wizard automatically assigns these typesto namespaces as follows:

Table 4–3: Namespaces for Types in Web Clients

Value Given by SOAP Client WizardItem

The SOAP client wizard sets this parameter if all methodsrefer to types in the same namespace.

TYPENAMESPACE (Web client parameter)

The SOAP client wizard sets this parameter if the Webservice uses document-style binding and the responsemessages use types in a different namespace than therequest messages. This parameter applies to all methodsin the class and is not overridden by theSoapTypeNameSpace method keyword. Note that allresponse types are assumed to be in the same namespaceas each other.

RESPONSETYPENAMESPACE (Web clientparameter)

Value of the targetNamespace attribute of the <s:schema>element. The SOAP client wizard sets this keyword permethod if methods use types from different namespaces.

SoapTypeNameSpace (method keyword)

Using SOAP and Web Services with Caché                                                                                                                         41

Basic Settings of a Caché Web Client

Page 50: Using SOAP and Web Services with Cach©

4.6 About the Generated Caché Web Client ClassesThis section shows an example of the Web client classes generated by the SOAP client wizard tool.

Consider the following WSDL document:

<?xml version="1.0" encoding="UTF-8"?><definitions xmlns="http://schemas.xmlsoap.org/wsdl/" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/" xmlns:ns2="http://www.complexnumbers.org" xmlns:s="http://www.w3.org/2001/XMLSchema" xmlns:s0="http://www.myaddservice.org" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" targetNamespace="http://www.myaddservice.org"><types> <s:schema elementFormDefault="qualified" targetNamespace="http://www.myaddservice.org"> <s:import namespace="http://www.complexnumbers.org"/> <s:element name="Add"> <s:complexType> <s:sequence> <s:element minOccurs="0" name="a" type="ns2:ComplexNumber"/> <s:element minOccurs="0" name="b" type="ns2:ComplexNumber"/> </s:sequence> </s:complexType> </s:element> <s:element name="AddResponse"> <s:complexType> <s:sequence> <s:element minOccurs="0" name="AddResult" type="ns2:ComplexNumber"/> </s:sequence> </s:complexType> </s:element> </s:schema> <s:schema elementFormDefault="qualified" targetNamespace="http://www.complexnumbers.org"> <s:complexType name="ComplexNumber"> <s:sequence> <s:element minOccurs="0" name="Real" type="s:double"/> <s:element minOccurs="0" name="Imaginary" type="s:double"/> </s:sequence> </s:complexType> </s:schema></types><message name="AddSoapIn"> <part name="parameters" element="s0:Add"/></message><message name="AddSoapOut"> <part name="parameters" element="s0:AddResponse"/></message><portType name="AddComplexSoap"> <operation name="Add"> <input message="s0:AddSoapIn"/> <output message="s0:AddSoapOut"/> </operation></portType><binding name="AddComplexSoap" type="s0:AddComplexSoap"> <soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="document"/> <operation name="Add"> <soap:operation soapAction="http://www.myaddservice.org/GSOP.AddComplexWS.Add" style="document"/> <input> <soap:body use="literal"/> </input> <output> <soap:body use="literal"/> </output> </operation></binding><service name="AddComplex"> <port name="AddComplexSoap" binding="s0:AddComplexSoap"> <soap:address location="http://localhost:57772/csp/gsop/GSOP.AddComplexWS.cls"/>

42                                                                                                                         Using SOAP and Web Services with Caché

Creating Web Clients

Page 51: Using SOAP and Web Services with Cach©

</port></service></definitions>

This WSDL document describes a Web service that provides one method, Add, which adds two complex numbers.

Suppose that you use the SOAP client wizard to generate a Web client for this Web service. If you specify the package forthe client classes as MyClient, the SOAP client wizard generates the following classes:

• It generates the MyClient.ns2.ComplexNumber class, which is shown below. The wizard automatically adds thisclass to your current project. This class defines a type that is needed by the Web services. If the Web service neededmore types, those would be defined as well.

/// Created from: c:/sample-wsdl.txtClass MyClient.ns2.ComplexNumber Extends (%RegisteredObject, %XML.Adaptor){

Parameter ELEMENTQUALIFIED = 1;

Parameter NAMESPACE = "http://www.complexnumbers.org";

Parameter XMLNAME = "ComplexNumber";

Parameter XMLSEQUENCE = 1;

Property Real As %xsd.double(XMLNAME = "Real") [ SqlFieldName = _Real ];

Property Imaginary As %xsd.double(XMLNAME = "Imaginary");

}

• It generates the MyClient.AddComplexSoap class, which is shown below. The wizard automatically adds this classto your current project. This class contains methods that you can use to invoke each of the Web service methods.

Class MyClient.AddComplexSoap Extends %SOAP.WebClient{

/// This is the URL used to access the web service.Parameter LOCATION = "http://localhost:57772/csp/gsop/GSOP.AddComplexWS.cls";

/// This is the namespace used by the ServiceParameter NAMESPACE = "http://www.myaddservice.org";

/// Use xsi:type attribute for literal types.Parameter OUTPUTTYPEATTRIBUTE = 1;

/// This is the name of the ServiceParameter SERVICENAME = "AddComplex";

/// This is the SOAP version supported by the service.Parameter SOAPVERSION = 1.1;

Method Add(a As MyClient.ns2.ComplexNumber, b As MyClient.ns2.ComplexNumber) As MyClient.ns2.ComplexNumber [ Final, ProcedureBlock = 1, SoapBindingStyle = document, SoapBodyUse = literal, WebMethod ]{ Quit ..WebMethod("Add"). Invoke(##this,"http://www.myaddservice.org/GSOP.AddComplexWS.Add",.a,.b)}

}

Note: Because of line-length limitations of the PDF book files, this example includes a line break that is not permittedsyntactically. This line break occurs within the definition of the method.

• When you compile a Caché Web client class, the Caché compiler generates a class for each method defined in the Webservice. These classes are not automatically added to your project and their internal details are subject to change. Theseclasses extend %SOAP.ProxyDescriptor, which you should never subclass yourself.

Using SOAP and Web Services with Caché                                                                                                                         43

About the Generated Caché Web Client Classes

Page 52: Using SOAP and Web Services with Cach©

4.7 Using Caché Web Client ClassesAfter you generate a Caché Web client class, you do not generally edit the class. Instead you create other classes that actas a wrapper for that class and provide client-side error handling.

Important: One exception is that you might need to adjust the types of the inputs and outputs of the methods. In par-ticular, if any of the methods of the Web service have inputs or outputs that could exceed 32 kB in length,and if you have not enabled support for long strings in Caché, you must change the types of those inputsor outputs to an appropriate stream class.

In general, to use a Caché Web client class, you create another class that contains methods that do the following:

1. Create an instance of the Web client class.

2. Set its properties. Here you can control items such as the following:

• Endpoint of the Web client (the URL of the Web service it uses). To control this, set the Location property.

• Settings that designate a proxy server.

• Settings that control basic HTTP user authentication.

See the chapter “Fine-tuning a Caché Web Client.”

3. Invoke the methods of the Web client as needed.

4. Optionally examine the HTTP response received by the Web client, as described later in this chapter.

This class would also define custom error trapping as needed on the client; see the chapter “SOAP Fault Handling.”

The following shows a simple example, from a session in the Caché Terminal:

GSOP>set client=##class(Proxies.CustomerLookupServiceSoap).%New()

GSOP>set resp=client.GetCustomerInfo("137")

GSOP>w resp

[email protected]

GSOP>w resp.NameSmith,Maria

4.8 Configuring the Client to Use SSLThe endpoint for a Web client is controlled by its LOCATION parameter or its Location property. If this endpoint has HTTPSprotocol, the Web client must be configured to use SSL. Specifically:

• If you have not already done so, use the System Management Portal to create an SSL/TLS configuration that containsthe details of the needed SSL connection. For information, see the chapter “Using SSL/TLS with Caché” in the CachéSecurity Administration Guide.

• Set the SSLConfiguration property of the Web client equal to that SSL/TLS configuration name.

Note that if the client is connecting via a proxy server, you must also set the HttpProxySSLConnect property equal to 1 inthe Web client. For information on configuring a Caché Web client to use a proxy server, see the chapter “Fine-tuning theWeb Client.”

44                                                                                                                         Using SOAP and Web Services with Caché

Creating Web Clients

Page 53: Using SOAP and Web Services with Cach©

4.9 Using the HTTP ResponseBy default, when you invoke a Web client method, you do so via HTTP. The HTTP response is then available as theHttpResponse property of the Web client instance. This property is an instance of %Net.HttpResponse, which in turn hasproperties like the following:

• Headers contains the headers of the HTTP response.

• Data is a Caché multidimensional array that contains any data in the HTTP response.

• StatusCode, StatusLine, and ReasonPhrase provide status information.

For details, see the book Using Caché Internet Utilities. Or see the class documentation for %Net.HttpResponse.

Using SOAP and Web Services with Caché                                                                                                                         45

Using the HTTP Response

Page 54: Using SOAP and Web Services with Cach©
Page 55: Using SOAP and Web Services with Cach©

5SOAP Fault Handling

This chapter describes how to handle faults within a Web service and within a Web client.

• How Caché Web services handle errors by default

• How to create custom SOAP faults in a Caché Web service in general

• The details for SOAP 1.1 faults

• The details for SOAP 1.2 faults

• Caché macros that represent standard SOAP fault codes

• How to handle errors and SOAP faults in a Web client

For a detailed discussion of error processing, see the chapter on errors in the book Using Caché ObjectScript.

Note that the SOAPPREFIX parameter affects the prefix used in any SOAP faults; see “Specifying the SOAP EnvelopePrefix” in the chapter “Fine-tuning a Caché Web Service.”

5.1 Default Fault Handling in a Web ServiceBy default, when your Caché Web service encounters an error, it returns a standard SOAP message containing a fault. Thefollowing shows an example (for SOAP 1.1). The SOAP envelope is omitted in this example:

<SOAP-ENV:Body> <SOAP-ENV:Fault> <faultcode>SOAP-ENV:Server</faultcode> <faultstring>Server Application Error</faultstring> <detail> <error xmlns='http://www.myapp.org' > <text>ERROR #5002: Cache error: <DIVIDE>zDivide^FaultEx.Service.1</text> </error> </detail></SOAP-ENV:Fault></SOAP-ENV:Body>

Notice that the fault includes a Caché error message. If you normally trap Caché errors and use your own messages, youwould want to do that in this case as well. The following sections give the details.

Using SOAP and Web Services with Caché                                                                                                                         47

Page 56: Using SOAP and Web Services with Cach©

5.2 Creating Custom SOAP Faults in a Caché Web ServiceIn general, to trap errors in a Caché Web service and create custom SOAP faults, you do the following:

• Create custom error methods that create instances of %SOAP.Fault (for SOAP 1.1) or %SOAP.Fault12 (for SOAP 1.2)and then call the ReturnFault() method of the Web service.

Note: You can use %SOAP.Fault in all cases. If a Web service receives a SOAP 1.2 request and needs to return afault, the Web service automatically converts the fault to SOAP 1.2 format.

• Wherever your Web service traps errors, invoke the appropriate custom error method.

Within a Web service, a custom error method must do the following:

1. Create an instance of %SOAP.Fault (for SOAP 1.1) or %SOAP.Fault12 (for SOAP 1.2).

Return the type of SOAP fault that the clients expect, based on the SOAP version given in the WSDL.

2. Set properties of that instance, as described in the following sections.

• “Details for SOAP 1.1 Faults”

• “Details for SOAP 1.2 Faults”

In general, these properties include information such as a SOAP fault code, reason string, and context information.For SOAP 1.2, you can create a more complex SOAP fault that lists reasons in multiple languages; you can alsospecify namespaces and null handling.

3. Call the ReturnFault() method of the Web service, passing the fault object as an argument. Note that ReturnFault())does not return to its caller; it just sends the fault and terminates processing of the Web method.

Or call the ReturnStatusFault() method of the Web service.

5.3 Details for SOAP 1.1 FaultsThis section provides the details for %SOAP.Fault, which represents SOAP 1.1 faults. This section includes the following:

• An example SOAP 1.1 fault, for reference

• Details for %SOAP.Fault, which represents SOAP 1.1 faults

• An example error method that creates a SOAP 1.1 fault

5.3.1 Example SOAP Fault

First, for reference, here is an example of a SOAP 1.1 fault, including the SOAP envelope:

48                                                                                                                         Using SOAP and Web Services with Caché

SOAP Fault Handling

Page 57: Using SOAP and Web Services with Cach©

<SOAP-ENV:Envelope xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:s='http://www.w3.org/2001/XMLSchema' xmlns:flt="http://myfault.org" > <SOAP-ENV:Body> <SOAP-ENV:Fault> <faultcode>SOAP-ENV:Server</faultcode> <faultstring>Division error</faultstring> <detail>Division error detail</detail> </SOAP-ENV:Fault> </SOAP-ENV:Body></SOAP-ENV:Envelope>

5.3.2 Details for %SOAP.Fault

Caché represents a SOAP 1.1 fault as an instance of %SOAP.Fault, which has the following properties:

detail

Used as the <detail> element of the SOAP fault. Use this to specify information about the cause of the fault.

faultcode

Used as the <faultcode> element of the SOAP fault. Set this property equal to one of the SOAP 1.1 macros listedin “Macros for SOAP Fault Codes,” later in this chapter.

faultstring

Used as the <faultstring> element of the SOAP fault. Specify a string that indicates the reason for the fault, asintended for users to see.

faultactor

Specifies the URI of the SOAP node on the SOAP message path that caused the fault to happen.

This is useful if the SOAP message travels through several nodes in the SOAP message path, and the client needsto know which node caused the error. It is beyond the scope of this book to discuss this advanced use of SOAP.

faultPrefixDefinition

Specifies a namespace prefix declaration that is added to the envelope of the SOAP fault. Use a value of the fol-lowing form:

xmlns:prefix="namespace"

Where prefix is the prefix and namespace is the namespace URI.

For example:

set fault.faultPrefixDefinition = "xmlns:FLT=""http://myfault.com"""

The %SOAP.Fault class also provides the AsString() method, which returns the fault object as a string.

5.3.3 Example Error Method

The following shows the simple method that was used to generate the example shown previously:

Using SOAP and Web Services with Caché                                                                                                                         49

Details for SOAP 1.1 Faults

Page 58: Using SOAP and Web Services with Cach©

/// Create our own method to produce application specific SOAP faults.Method DivisionError(){ set fault=##class(%SOAP.Fault).%New() set fault.faultcode=$$$FAULTServer set fault.detail="Division error detail" set fault.faultstring="Division error" set fault.faultPrefixDefinition="xmlns:flt=""http://myfault.org""" // ReturnFault must be called to send the fault to the client. // ReturnFault will not return here. do ..ReturnFault(fault)}

The following Web method uses this example error method:

/// Divide arg1 by arg2 and return the resultMethod Divide(arg1 As %Numeric, arg2 As %Numeric) As %Numeric [ WebMethod ]{ Try { set ans=arg1 / arg2 }Catch{ do ..DivisionError() } Quit ans}

5.4 Details for SOAP 1.2 FaultsThis section provides the details for %SOAP.Fault12 and related classes, which represent SOAP 1.2 faults. This sectionincludes the following:

• An example SOAP 1.2 fault, for reference

• Details for %SOAP.Fault12, the main class that represents SOAP 1.2 faults

• Details for %SOAP.Fault12.Code, a helper class

• Details for %SOAP.Fault12.Text, another helper class

• An example error method that creates a SOAP 1.2 fault

5.4.1 Example SOAP Fault

First, for reference, here is an example of a SOAP 1.2 fault, including the SOAP envelope:

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://www.w3.org/2003/05/soap-envelope" xmlns:flt="http://myfault.org"> <SOAP-ENV:Body> <SOAP-ENV:Fault> <SOAP-ENV:Code> <SOAP-ENV:Value>SOAP-ENV:Receiver</SOAP-ENV:Value> </SOAP-ENV:Code> <SOAP-ENV:Reason> <SOAP-ENV:Text xml:lang="en">Division error</SOAP-ENV:Text> <SOAP-ENV:Text xml:lang="it">Errore di applicazione</SOAP-ENV:Text> <SOAP-ENV:Text xml:lang="es">Error del uso</SOAP-ENV:Text> </SOAP-ENV:Reason> <SOAP-ENV:Detail>Division error detail</SOAP-ENV:Detail> </SOAP-ENV:Fault> </SOAP-ENV:Body></SOAP-ENV:Envelope>

5.4.2 Details for %SOAP.Fault12

The class %SOAP.Fault12 represents a SOAP 1.2 fault. This class has the following properties:

50                                                                                                                         Using SOAP and Web Services with Caché

SOAP Fault Handling

Page 59: Using SOAP and Web Services with Cach©

Code

An instance of %SOAP.Fault12.Code, discussed in the following section.

Detail

Used as the <detail> element of the SOAP fault. Use this to specify information about the cause of the fault.

Node

Specifies the URI of the SOAP node on the SOAP message path that caused the fault to happen; optional for thedestination node.

This is useful if the SOAP message travels through several nodes in the SOAP message path, and the client needsto know which node caused the error. It is beyond the scope of this book to discuss this advanced use of SOAP.

Reason

A list of instances of %SOAP.Fault12.Text, discussed in a following section. Each instance contains a reason stringand a language code that indicates the language or locality of the reason string. These are used within the <Reason>element.

Role

Role that the node was operating in. See the preceding remarks for Node.

faultPrefixDefinition

Specifies a namespace prefix declaration that is added to the envelope of the SOAP fault. Use a value of the fol-lowing form:

xmlns:prefix="namespace"

Where prefix is the prefix and namespace is the namespace URI.

For example:

set fault.faultPrefixDefinition = "xmlns:FLT=""http://myfault.com"""

The %SOAP.Fault12 class also provides the AsString() method, which returns the fault object as a string.

5.4.3 Details for %SOAP.Fault12.Code

You use %SOAP.Fault12.Code as a value for the Code property of an instance of %SOAP.Fault12. The %SOAP.Fault12.Code

class has the following properties:

Subcode

An optional subcode.

Value

The value you provide depends on whether you have provided a subcode:

• If you used a subcode, specify Value as a qname.

• If you did not use a subcode, specify Value as one of the SOAP 1.2 macros listed in “Macros for SOAP FaultCodes,” later in this chapter.

Using SOAP and Web Services with Caché                                                                                                                         51

Details for SOAP 1.2 Faults

Page 60: Using SOAP and Web Services with Cach©

5.4.4 Details for %SOAP.Fault12.Text

You use %SOAP.Fault12.Text as a list element in the Reason property of an instance of %SOAP.Fault12. The%SOAP.Fault12.Text class has the following properties:

Text

A string indicating the reason for the fault, as intended for users to see.

lang

A code that corresponds to the language or locality in which the fault text is phrased. For information, see the W3Web site (http://www.w3.org/).

5.4.5 Example Error Method

The following shows the simple method that was used to generate the example shown previously:

/// Create our own method to produce application specific SOAP faults.Method DivisionError(){ set fault=##class(%SOAP.Fault12).%New() set fault.Detail="Division error detail" set fault.faultPrefixDefinition="xmlns:flt=""http://myfault.org"""

set code=##class(%SOAP.Fault12.Code).%New() set code.Value=$$$FAULTReceiver set fault.Code=code

set text=##class(%SOAP.Fault12.Text).%New() set text.Text="Division error" set text.lang="en" do fault.Reason.Insert(text)

set text=##class(%SOAP.Fault12.Text).%New() set text.Text="Errore di applicazione" set text.lang="it" do fault.Reason.Insert(text)

set text=##class(%SOAP.Fault12.Text).%New() set text.Text="Error del uso" set text.lang="es" do fault.Reason.Insert(text)

// ReturnFault must be called to send the fault to the client. // ReturnFault will not return here. do ..ReturnFault(fault)}

The following Web method uses this example error method:

/// Divide arg1 by arg2 and return the resultMethod Divide(arg1 As %Numeric, arg2 As %Numeric) As %Numeric [ WebMethod ]{ Try { set ans=arg1 / arg2 }Catch{ do ..DivisionError() } Quit ans}

52                                                                                                                         Using SOAP and Web Services with Caché

SOAP Fault Handling

Page 61: Using SOAP and Web Services with Cach©

5.5 Macros for SOAP Fault CodesThe SOAP include file (%soap.inc) defines macros, listed in the following table, for some of the standard SOAP fault codes.You can use these macros in your custom error methods. The table notes the version or versions of SOAP to which eachmacro applies.

Table 5–1: Caché ObjectScript Macros for SOAP Fault Codes

When to Use This MacroSOAPVersion(s)

Macro

When the Web service receives a SOAPmessage that contained an invalid elementinformation item instead of the expectedenvelope element information item.

A mismatch occurs if either the namespaceor the local name do not match.

1.1 and 1.2$$$FAULTVersionMismatch

When the Web service receives a SOAPmessage that contained an unexpectedelement that was marked withmustUnderstand="true"

1.1 and 1.2$$$FAULTMustUnderstand

When other server-side errors occur.1.1$$$FAULTServer

When the client made an incomplete orincorrect request.

1.1$$$FAULTClient

When the arguments are encoded in a dataencoding unknown to the receiver.

1.2$$$FAULTDataEncodingUnknown

When the sender made an incomplete,incorrect, or unsupported request.

1.2$$$FAULTSender

When the receiver cannot handle themessage because of some temporarycondition, for example, when it is out ofmemory.

1.2$$$FAULTReceiver

5.6 Handling SOAP Faults and Other Errors in a CachéWeb ClientIn a Caché Web client, you can use the TRY-CATCH mechanism or the older $ZTRAP mechanism.

In either case, when a Caché Web client receives an error, Caché sets the special variables $ZERROR and %objlasterror:

• If the error is a SOAP fault, the value of $ZERROR starts with <ZSOAP>, and %objlasterror contains the statuserror that is formed from the received SOAP fault.

In addition, the client instance has a property named SoapFault, which is an instance of %SOAP.Fault or %SOAP.Fault12

(depending on the SOAP version used in the Web service). You can use the information in this property. For moreinformation on %SOAP.Fault and %SOAP.Fault12, see the previous sections.

Using SOAP and Web Services with Caché                                                                                                                         53

Macros for SOAP Fault Codes

Page 62: Using SOAP and Web Services with Cach©

• If the error is not a SOAP fault, use your normal error handling (typically using $ZERROR). It is your responsibilityto specify how to proceed.

5.6.1 Example 1:Try-Catch

The following example uses TRY-CATCH:

Include %systemIncludeClass GSOPClient.Divide.UseClientTryCatch{

ClassMethod Divide(arg1 As %Numeric, arg2 As %Numeric) As %Numeric{ Set $ZERROR="" Set client=##class(GSOPClient.Divide.DivideSoap).%New()

//reset location to port 8080 to enable tracing set client.Location="http://localhost:8080/csp/gsop/GSOP.DivideWS.cls" Try { Set ans=client.Divide(arg1,arg2) } Catch { If $ZERROR["<ZSOAP>" { Set ans=%objlasterror } Else { Set ans=$$$ERROR($$$CacheError,$ZERROR) } }

Quit ans}

}

5.6.2 Example 2: $ZTRAP

The following example uses the older $ZTRAP mechanism. In this case, when a Caché Web client receives an error, controlis transferred to the label indicated by the $ZTRAP special variable (if that label is defined).

Include %systemIncludeClass GSOPClient.Divide.UseClientZTRAP{

ClassMethod Divide(arg1 As %Numeric, arg2 As %Numeric) As %Numeric{ Set $ZERROR="" Set $ZTRAP="ERRORTRAP" Set client=##class(GSOPClient.Divide.DivideSoap).%New()

//reset location to port 8080 to enable tracing set client.Location="http://localhost:8080/csp/gsop/GSOP.DivideWS.cls" Set ans=client.Divide(arg1,arg2) Quit ans

//control goes here in case of errorERRORTRAP If $ZERROR["<ZSOAP>" { Quit %objlasterror } Else { Quit $$$ERROR($$$CacheError,$ZERROR) }

}

}

54                                                                                                                         Using SOAP and Web Services with Caché

SOAP Fault Handling

Page 63: Using SOAP and Web Services with Cach©

5.6.3 SSL Handshake Errors

If a Caché Web client uses an SSL connection and a SSL handshake error has occurred, then the SSLError property of theclient contains text that describes the SSL error.

Using SOAP and Web Services with Caché                                                                                                                         55

Handling SOAP Faults and Other Errors in a Caché Web Client

Page 64: Using SOAP and Web Services with Cach©
Page 65: Using SOAP and Web Services with Cach©

6Using MTOM for Attachments

You can include attachments in SOAP request and response messages. The preferred way to do this is to use Caché supportfor MTOM (Message Transmission Optimization Mechanism).

This chapter discusses the details:

• An overview of attachments and SOAP message packaging

• How to force a Caché Web service to send responses as MTOM packages

• How to force a Caché Web client to send requests as MTOM packages

• How to control the details of the MTOM package

• An example that sends MTOM messages between a Web service and a Web client

For links to the specifications for MTOM, see “Standards Supported in Caché,” in the first chapter of this book.

For information on using Caché support for SOAP With Attachments, see the next chapter.

6.1 Attachments and SOAP Message PackagingAttachments are generally used to carry binary data. Caché SOAP support provides three general ways to package yourSOAP messages. Before discussing detailed options, it is worthwhile to review these kinds of packaging.

• Package the message with all parts inline (without attachments). Use base64 encoding for any binary data.

This is the default behavior of Caché Web services and Web clients, except when a Web service receives an MTOMrequest (in which case, the service responds with an MTOM response).

• Package the message according to the MTOM (Message Transmission Optimization Mechanism) specification, whichresults in a slightly more compact message than an all-inline message. This is now the preferred approach for SOAPmessages.

When you use this technique, Caché automatically packages the SOAP messages appropriately. That is, the MIMEparts are created as needed and are added to the message without your intervention.

Also by default, when Caché creates an MTOM package, it outputs binary streams using an attachment, and it outputsbinary strings (%Binary or %xsd.base64Binary) inline; you can control this behavior.

• Package the message according to the SOAP With Attachments specification, which results in a slightly more compactmessage than an all-inline message.

Using SOAP and Web Services with Caché                                                                                                                         57

Page 66: Using SOAP and Web Services with Cach©

When you use this technique, you must manually create MIME parts, populate them with data, specify the MIMEheaders appropriate, and attach the parts to the SOAP message. This is generally more work than the MTOM technique.See the next chapter “Using SOAP With Attachments.”

6.1.1 SOAP Messages with All-inline Parts

One way to package a SOAP message is to include all its elements as inline parts (that is, without attachments). Any binarydata is included inline as base64–encoded data. For example (with line breaks and spaces added for readability):

HTTP/1.1 200 OKDate: Wed, 19 Nov 2008 21:57:50 GMTServer: ApacheSET-COOKIE: CSPSESSIONID-SP-8080-UP-csp-gsop-=003000010000248guobl000000K7opwlDlY$XbvrGR1eYZsA--; path=/csp/gsop/;CACHE-CONTROL: no-cacheEXPIRES: Thu, 29 Oct 1998 17:04:19 GMTPRAGMA: no-cacheTRANSFER-ENCODING: chunkedConnection: closeContent-Type: text/xml; charset=UTF-8

1d7b<?xml version="1.0" encoding="UTF-8" ?><SOAP-ENV:Envelope xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:s='http://www.w3.org/2001/XMLSchema'><SOAP-ENV:Body> <DownloadResponse xmlns="http://www.filetransfer.org"> <DownloadResult><Filename>sample.pdf</Filename> <IsBinary>true</IsBinary> <BinaryContents> [very long binary content not shown here] </BinaryContents></attachment></Upload> </SOAP-ENV:Body></SOAP-ENV:Envelope>

Notice that this packaging does not use MIME, and there are no message boundaries.

6.1.2 SOAP Messages with MTOM Packaging

Another way to package a SOAP message is to use MIME parts as described in the MTOM (Message Transmission Opti-mization Mechanism) specification. Binary data can be placed into separate MIME parts without base64 encoding. TheSOAP message includes references to the separate parts as needed. For example (with line breaks and spaces added forreadability):

HTTP/1.1 200 OKDate: Wed, 19 Nov 2008 21:54:57 GMTServer: ApacheSET-COOKIE: CSPSESSIONID-SP-8080-UP-csp-gsop-=003000010000247guhlx000000NW1KN5UtWg$CWY38$bbTOQ--; path=/csp/gsop/;CACHE-CONTROL: no-cacheEXPIRES: Thu, 29 Oct 1998 17:04:19 GMTMIME-VERSION: 1.0PRAGMA: no-cacheTRANSFER-ENCODING: chunkedConnection: closeContent-Type: multipart/related; type="application/xop+xml"; boundary=--boundary388.5294117647058824932.470588235294118--; start="<0.B1150656.EC8A.4B5A.8835.A932E318190B>"; start-info="text/xml"

1ddb----boundary388.5294117647058824932.470588235294118--Content-Type: application/xop+xml; type="text/xml"; charset="UTF-8"Content-Transfer-Encoding: 8bitContent-Id: <0.B1150656.EC8A.4B5A.8835.A932E318190B>

<?xml version="1.0" encoding="UTF-8" ?><SOAP-ENV:Envelope xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:s='http://www.w3.org/2001/XMLSchema'><SOAP-ENV:Body><DownloadResponse xmlns="http://www.filetransfer.org"><DownloadResult>

58                                                                                                                         Using SOAP and Web Services with Caché

Using MTOM for Attachments

Page 67: Using SOAP and Web Services with Cach©

<Filename>sample.pdf</Filename> <IsBinary>true</IsBinary> <BinaryContents> <xop:Include href="cid:1.B1150656.EC8A.4B5A.8835.A932E318190B" xmlns:xop="http://www.w3.org/2004/08/xop/include"/> </BinaryContents></DownloadResult></DownloadResponse> </SOAP-ENV:Body></SOAP-ENV:Envelope>----boundary388.5294117647058824932.470588235294118--Content-Id: <1.B1150656.EC8A.4B5A.8835.A932E318190B>Content-Transfer-Encoding: binaryCONTENT-TYPE: application/octet-stream

[very long binary content not shown here]

Notice that in this message, the element BinaryContents consists of a reference to a MIME part.

6.1.3 SOAP With Attachments

A third way to package SOAP messages is to use the SOAP With Attachments specification, which also uses MIME parts,but packages the message somewhat differently from MTOM. An example follows (with line breaks and spaces added forreadability):

CACHE-CONTROL: no-cacheEXPIRES: Thu, 29 Oct 1998 17:04:19 GMTMIME-VERSION: 1.0PRAGMA: no-cacheTRANSFER-ENCODING: chunkedConnection: closeContent-Type: multipart/related; type="text/xml"; boundary=--boundary5469.5294117647058822436.411764705882353--

1e12----boundary5469.5294117647058822436.411764705882353--Content-Type: text/xml; charset="UTF-8"Content-Transfer-Encoding: 8bit

<?xml version="1.0" encoding="UTF-8" ?><SOAP-ENV:Envelope xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:s='http://www.w3.org/2001/XMLSchema'><SOAP-ENV:Body> <DownloadBinaryResponse xmlns="http://www.filetransfer.org"> <DownloadBinaryResult> MQ==</DownloadBinaryResult></DownloadBinaryResponse> </SOAP-ENV:Body></SOAP-ENV:Envelope>----boundary5469.5294117647058822436.411764705882353--Content-Transfer-Encoding: base64Content-Type: application/octet-stream

[very long binary content not shown here]----boundary5469.5294117647058822436.411764705882353----

0

6.2 Forcing Responses as MTOM PackagesBy default, a Caché Web service behaves as follows:

• If it receives a request in an MTOM package, the Web service sends the response as an MTOM package. Also, theIsMTOM property of the Web service is set to 1, rather than 0, the default.

• If it receives a request not in an MTOM package, the Web service, by default, sends the response not in an MTOMpackage.

You can force a Caché Web service to send every response as an MTOM package. To do, do either of the following:

• In your Caché Web service class, set the MTOMREQUIRED parameter to 1.

Using SOAP and Web Services with Caché                                                                                                                         59

Forcing Responses as MTOM Packages

Page 68: Using SOAP and Web Services with Cach©

• In your Caché Web service instance, set the MTOMRequired property to 1. You can do this within the Web methodor within the OnPreWebMethod() callback. For an introduction to this callback, see “Customizing Callbacks of theWeb Service” , later in this chapter.

MTOMREQUIRED and MTOMRequired have no effect on the WSDL of the Web service.

6.3 Forcing Requests as MTOM PackagesBy default, a Caché Web client behaves as follows:

• It does not send requests as MTOM packages.

• If it receives a response in an MTOM package, the Web client processes the response. Also, the IsMTOM property ofthe Web client is set to 1.

• If it receives a request not in an MTOM package, the Web client processes the response. The IsMTOM property of theWeb service client is not changed (as 0).

You can force a Caché Web client to send every request as an MTOM package. To do, do either of the following:

• In your Caché Web client class, set the MTOMREQUIRED parameter to 1.

• In your Caché Web client instance, set the MTOMRequired property to 1.

6.4 Controlling the MTOM PackagingBy default, when Caché creates an MTOM package, it uses the following rules:

• It outputs binary streams using an attachment.

• It outputs binary strings (%Binary or %xsd.base64Binary) inline.

You can use the MTOM property parameter to change this default:

• 1 means output this property as an attachment.

• 0 means output this property inline.

The MTOM property parameter has no effect when a Web service or Web client is not using MTOM.

6.5 ExampleThis example shows a Caché Web client that sends an attachment and the corresponding Web service that receives andsaves it. The Web service and Web client use MTOM.

6.5.1 Web Method Argument

The Web method used in this interaction accepts one argument, which is of type GSOP.FileAttachment. This class isas follows:

60                                                                                                                         Using SOAP and Web Services with Caché

Using MTOM for Attachments

Page 69: Using SOAP and Web Services with Cach©

Class GSOP.FileAttachment Extends (%RegisteredObject, %XML.Adaptor){

Property Filename as %String;

Property IsBinary as %Boolean;

Property AsciiContents as %GlobalCharacterStream;

Property BinaryContents as %GlobalBinaryStream;

}

To send an ASCII file, we put ASCII contents into the AsciiContents property and set IsBinary to 0. Similarly, tosend a binary file, we put binary contents into the BinaryContents property and set IsBinary to 1. In either case, weput the filename into the Filename property.

6.5.2 Web Service

The Web service is as follows:

/// Receive an attachment and save it to a file.Class GSOP.MTOMUploadWS Extends %SOAP.WebService [ ProcedureBlock ]{

/// Name of the Web service.Parameter SERVICENAME = "MTOMUpload";

/// SOAP namespace for the Web serviceParameter NAMESPACE = "http://www.mtomupload.org";

/// Namespaces of referenced classes will be used in the WSDL.Parameter USECLASSNAMESPACES = 1;

/// Receive an attachment and save itMethod Upload(attachment as GSOP.FileAttachment) As %String [ WebMethod ]{ If attachment.IsBinary { Set file=##class(%FileBinaryStream).%New() Set file.Filename="c:\from-client\"_$H_attachment.Filename Set status=file.CopyFrom(attachment.BinaryContents) } else { Set file=##class(%FileCharacterStream).%New() Set file.Filename="c:\from-client\"_$H_attachment.Filename Set status=file.CopyFrom(attachment.AsciiContents) }

If $$$ISERR(status) do $System.Status.DisplayError(status) Set status= file.%Save() If $$$ISERR(status) do $System.Status.DisplayError(status) Set return="Attachment saved to "_file.Filename

Quit return}

}

The Upload() method checks the IsBinary property of the argument and uses that to determine how to save theattachment. The file is saved into c:\from-client and $H is used in the filename to make sure it is unique.

6.5.3 Web Client

The generated Web client (GSOPClient.MTOMUploadToWS.MTOMUploadSoap) contains the method Upload(),which invokes the Web method of the same name. This class is not shown.

The Web client application also includes the following class, which uses the generated Web client class:

Include %systemInclude

Class GSOPClient.MTOMUploadToWS.UseClient{

Using SOAP and Web Services with Caché                                                                                                                         61

Example

Page 70: Using SOAP and Web Services with Cach©

ClassMethod UploadFile(IsBinary as %Boolean=0) As %String{ Set client=##class(GSOPClient.MTOMUploadToWS.MTOMUploadSoap).%New() Set client.MTOMRequired=1 Set attachment=##class(GSOP.FileAttachment).%New()

//for this example, hardcode what we are uploading If 'IsBinary { Set attachment.Filename="sample.txt" Set attachment.IsBinary=0 Set file=##class(%Library.FileCharacterStream).%New() Set file.Filename="c:\"_attachment.Filename Do attachment.AsciiContents.CopyFrom(file) } else { Set attachment.Filename="sample.pdf" Set attachment.IsBinary=1 Set file=##class(%Library.FileBinaryStream).%New() Set file.Filename="c:\"_attachment.Filename Do attachment.BinaryContents.CopyFrom(file) }

Set ans=client.Upload(attachment) Quit ans}

}

62                                                                                                                         Using SOAP and Web Services with Caché

Using MTOM for Attachments

Page 71: Using SOAP and Web Services with Cach©

7Using SOAP With Attachments

In your Caché Web clients and Web services, you can add and use attachments to SOAP messages by using the Cachésupport for SOAP With Attachments, instead of using the Caché MTOM support, as described in the previous chapter.

This method requires more work than using MTOM because your code must directly manage the MIME parts used asattachments.

• How to send attachments from a Web service or Web client via SOAP With Attachments

• How to access sent attachments within a Web service or Web client

• An example that shows attachments sent in both directions

For a link to the specifications for SOAP With Attachments standard, see “Standards Supported in Caché,” in the firstchapter of this book.

7.1 Sending AttachmentsWhen you use the Caché support for the SOAP with Attachments standard, you use the following process to send attachments:

1. Create the attachments. In general, to create an attachment:

a. Use a stream object to represent the attachment data. The class you use depends on the exact interface you needto obtain the stream data. For example, you might use %Library.FileCharacterStream to read the contents of a fileinto a stream.

b. Create a MIME part, which is an instance of %Net.MIMEPart.

c. For the MIME part:

• Set the Body property equal to your stream object. Or set the Parts property, which must be a list of instancesof %Net.MIMEPart.

• Call the SetHeader() method to set the Content-Transfer-Encoding header of the MIME part. Be sureto set this appropriately for the type of data you are sending.

2. Add the attachments to the Web service or Web client. To add a given attachment, you insert the MIME part into theappropriate property as follows:

• If you are sending an attachment from a Web client, update the Attachments property of your Web client.

• If you are sending an attachment from a Web service, update the ResponseAttachments property of the Web service.

Using SOAP and Web Services with Caché                                                                                                                         63

Page 72: Using SOAP and Web Services with Cach©

Each of these properties is a list with the usual list interface (for example, SetAt(), Count(), and GetAt() methods).

3. Update the appropriate properties of the Web client or the Web service to describe the attachment contents:

• ContentID

• ContentLocation

7.2 Using AttachmentsWhen a Caché Web service or Web client receives a SOAP message that has attachments (as specified by the SOAP WithAttachments specification), the following happens:

• The attachments are inserted into the appropriate property:

– For a Web service, the inbound attachments are placed in the Attachments property.

– For a Web client, the inbound attachments are placed in the ResponseAttachments property.

Each of these properties is a list with the usual list interface (for example, SetAt(), Count(), and GetAt() methods).Each list element is an instance of %Net.MIMEPart. Note that a MIME part can in turn contain other MIME parts. Yourcode is responsible for determining the structure and contents of the attachments.

• The ContentID and ContentLocation properties are updated to reflect the Content-ID and Content-Locationheaders of the inbound SOAP message.

The Web service or Web client can access these properties and thus access the attachments.

7.3 ExampleThis section provides an example Web service and Web client that send attachments to each other.

7.3.1 Web Service

The Web service provides two methods:

• UploadAscii() receives an ASCII attachment and saves it.

• DownloadBinary() sends a binary attachment to the requestor.

The class definition is as follows:

Class GSOP.FileTransferWS Extends %SOAP.WebService [ProcedureBlock]{

/// Name of the Web service.Parameter SERVICENAME = "FileTransfer";

/// SOAP namespace for the Web serviceParameter NAMESPACE = "http://www.filetransfer.org";

/// Namespaces of referenced classes will be used in the WSDL.Parameter USECLASSNAMESPACES = 1;

/// Receive an attachment and save itMethod UploadAscii(filename As %String = "sample.txt") As %Status [WebMethod]{ //assume 1 attachment; ignore any others

64                                                                                                                         Using SOAP and Web Services with Caché

Using SOAP With Attachments

Page 73: Using SOAP and Web Services with Cach©

Set attach=..Attachments.GetAt(1)

Set file=##class(%FileCharacterStream).%New() Set file.Filename="c:\from-client"_$H_filename

//copy attachment into file Set status=file.CopyFrom(attach.Body) If $$$ISERR(status) do $System.Status.DisplayError(status) Set status= file.%Save() Quit status}

/// Create an attachment and send it in response to the Web client callMethod DownloadBinary(filename As %String = "sample.pdf") As %Status [WebMethod]{ //use a file-type stream to read file contents Set file=##class(%Library.FileBinaryStream).%New() Set file.Filename="c:\"_filename

//create MIMEpart and add file to it Set mimepart=##class(%Net.MIMEPart).%New() Set mimepart.Body=file

//set header appropriately for binary file Do mimepart.SetHeader("Content-Type","application/octet-stream") Do mimepart.SetHeader("Content-Transfer-Encoding","base64")

//attach Set status=..ResponseAttachments.Insert(mimepart) Quit status}

}

7.3.2 Web Client

The Web client application provides two methods:

• UploadAscii() sends an ASCII file to the Web service.

• DownloadBinary() calls the Web service and receives an binary file in response.

The generated Web client class (GSOPClient.FileTransfer.FileTransferSoap) includes the methodsUploadAscii() and DownloadBinary(), which invoke the corresponding methods of the preceding Web service.This class is not shown.

The Web client application also includes the following class, which uses this generated Web client class:

Include %systemInclude

Class GSOPClient.FileTransfer.UseClient{

ClassMethod DownloadBinary(filename As %String = "sample.pdf") As %Status{ Set client=##class(GSOPClient.FileTransfer.FileTransferSoap).%New()

//call Web method Set ans=client.DownloadBinary(filename)

//get the attachment (assume only 1) Set attach=client.ResponseAttachments.GetAt(1)

//create a file and copy stream contents into it Set file=##class(%FileBinaryStream).%New() //include $H in the filename to make filename unique Set file.Filename="c:\from-service"_$H_filename Set status=file.CopyFrom(attach.Body) If $$$ISERR(status) do $System.Status.DisplayError(status) Set status= file.%Save() Quit status}

ClassMethod UploadAscii(filename As %String = "sample.txt") As %Status{ Set client=##class(GSOPClient.FileTransfer.FileTransferSoap).%New()

//use a file-type stream to read file contents

Using SOAP and Web Services with Caché                                                                                                                         65

Example

Page 74: Using SOAP and Web Services with Cach©

Set file=##class(%Library.FileCharacterStream).%New() Set file.Filename="c:\"_filename

//create MIME part, add file as Body, and set the header Set mimepart=##class(%Net.MIMEPart).%New() Set mimepart.Body=file Do mimepart.SetHeader("Content-Transfer-Encoding","7bit")

//attach to client and call Web method Do client.Attachments.Insert(mimepart) Set status=client.UploadAscii(filename) Quit status}

}

66                                                                                                                         Using SOAP and Web Services with Caché

Using SOAP With Attachments

Page 75: Using SOAP and Web Services with Cach©

8Adding and Using SOAP Headers

This chapter describes how to add headers to SOAP messages sent by a Web service or client, and how to configure a Webservice or client to process specific header elements on the messages it receives.

This chapter discusses the following:

• How Caché represents SOAP headers

• How to create a custom header element

• How to add a header element to a SOAP message

• How to use a header element received in a SOAP message

• How to add and use WS-Addressing header elements

Also see the Cinema example in the SAMPLES namespace.

8.1 How Caché Represents SOAP HeadersCaché represents a SOAP header as an array of instances of %SOAP.Header (or its subclasses). When a Caché Web serviceor client receives a SOAP message, it imports and processes the message. During this step, it updates its own HeadersIn

property, which then consists of an array of the elements that were found in the inbound SOAP message:

Using SOAP and Web Services with Caché                                                                                                                         67

Page 76: Using SOAP and Web Services with Cach©

The Caché Web service or client can then use these header elements by accessing the HeadersIn property. If the SOAPmessage did not include a <Header> element, the Count() of the HeadersIn property is 0.

Similarly, before your Caché Web service or client sends a SOAP message, update the HeadersOut property so that itcontains any custom elements you want to include in the outbound message. If the HeadersOut Count() is 0, the outboundSOAP message does not include a <Header> element.

In both cases, each member of the headers array property is an instance of %SOAP.Header or one of its subclasses.

8.1.1 Special Header Elements

Caché SOAP support also provides tools to help you add or validate special header elements:

• WS-Addressing (see the section “Adding WS-Addressing Header Elements” later in this book). The tools for WS-Addressing do not use HeadersIn and HeadersOut properties.

68                                                                                                                         Using SOAP and Web Services with Caché

Adding and Using SOAP Headers

Page 77: Using SOAP and Web Services with Cach©

• WS-Security (see the chapter “Using WS-Security Features,” later in this book). The WS-Security header element isavailable in HeadersIn.

• Caché SOAP session token (See the chapter “SOAP Session Management,” later in this book). This does use theHeadersIn and HeadersOut properties.

8.2 Creating Custom Header ElementsTo create a custom header element:

1. Create a subclass of %SOAP.Header.

2. In the subclass, define properties to contain the header information you need. By default, your properties are projectedto elements within the SOAP <Header> element.

3. Optionally specify the actor and mustUnderstand properties, which correspond to SOAP attributes for this header element.

4. Optionally set the XMLFORMAT parameter, which controls the format of this header element. By default, the headerelements are always in literal format (rather than SOAP-encoded).

5. Optionally set the NAMESPACE parameter.

For details on handling the XML projection, see the book Using XML with Caché.

8.3 Adding a Header Element to a SOAP MessageTo add header elements to a SOAP message (from either the Web service or the Web client), do the following beforesending the SOAP message.

1. Create an instance of your header object.

2. Set the properties of that object as appropriate, optionally including the actor and mustUnderstand properties.

3. Add the new header to the outbound header array, the HeadersOut property. This property is an array with the usualarray interface (for example, the SetAt(), Count(), and GetAt() methods).

Note: In order for a method to add a SOAP header element, the method must be an instance method and must be amember of an instantiable class (not an abstract class, for example).

For example, you might have a header class like the following:

Class Headers.TimeStamp Extends %SOAP.Header{

Property TimeSent As %TimeStamp;

}

Then within your Web service or client class, you could have a utility method that adds an instance of this header:

Method AddTimeStampHeader(){ set h=##class(Headers.TimeStamp).%New() set h.TimeSent=$ZTIMESTAMP do ..HeadersOut.SetAt(h,"Timestamp")}

Using SOAP and Web Services with Caché                                                                                                                         69

Creating Custom Header Elements

Page 78: Using SOAP and Web Services with Cach©

Finally, you could call this utility method from each Web method where you wanted to use it. For example:

/// Divide arg1 by arg2 and return the resultMethod Divide(arg1 As %Numeric, arg2 As %Numeric) As %Numeric [ WebMethod ]{ do ..AddTimeStampHeader()

//main method code here ...

Quit ans}

When you invoke this Web method, the header is added to the SOAP response. The response might look like the following(with line breaks and spaces added here for readability):

<SOAP-ENV:Envelope xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:s='http://www.w3.org/2001/XMLSchema'> <SOAP-ENV:Header> <TimeStamp xmlns:hdr="http://www.myapp.org"> <TimeSent>60712,70996.027Z</TimeSent> </TimeStamp> </SOAP-ENV:Header> <SOAP-ENV:Body> <DivideResponse xmlns="http://www.myapp.org"> <DivideResult>.5</DivideResult> </DivideResponse> </SOAP-ENV:Body></SOAP-ENV:Envelope>

8.4 Processing Specific Header ElementsTo configure a Web service or a Web client to recognize and process specific SOAP header elements, do the following:

• Understand the structure of the expected SOAP header element and create a header class that maps that structure. Forexample, if you are expecting a SOAP header element with elements <CallerID> and <CallDate>, then create a subclassof %SOAP.Header that has properties named CallerID and CallDate.

• In your Web service or Web client class, update the SOAPHEADERS parameter so that it includes the element nameof the expected header and the class to which it maps. This parameter must equal a comma-separated list of headerspecifications. Each header specification has the form "headerName:headerClass" where headerName is the elementname of the supported header and headerClass is the class that you have created. This list defines all headers supportedin the SOAP requests to this Web service.

When the Web service or Web client receives a request, it searches for each SOAP header in the SOAPHEADERS list. Ifany header in the SOAP request has mustUnderstand="1" and the header element name is not in the SOAPHEADERS list,then the service or client returns a SOAP fault without processing the message.

For each header that is found in the SOAPHEADERS list, the service or client creates an instance of the appropriate headerclass and adds the header to the inbound header array, which is the HeadersIn property. This property is an array with theusual array interface (for example, SetAt(), Count(), and GetAt() methods). The Web service or Web client can then acton these headers as appropriate.

Note: The header namespace is not used for matching the header in the list. However, the header namespace in theSOAP message must be the same as specified by the NAMESPACE parameter in your header subclass; otherwise,an error occurs when the message is imported.

70                                                                                                                         Using SOAP and Web Services with Caché

Adding and Using SOAP Headers

Page 79: Using SOAP and Web Services with Cach©

8.5 Adding WS-Addressing Header ElementsYou can also add WS-Addressing header elements to your SOAP messages, as specified by the WS-Addressing standardsfor SOAP 1.1 and SOAP 1.2. To do so, you use the WSADDRESSING parameter, which can equal "OFF" (the default) or"AUTO".

For a link to details about this standard, see the section “Standards Supported by Caché” in the first chapter.

8.5.1 Adding WS-Addressing Headers to Request Messages

For a Web client, if you specify the WSADDRESSING parameter as "AUTO", the client includes the fllowing WS-Addressing header elements in the request message:

• To:destination address

• Action: SoapAction

• MessageID: unique uuid

• ReplyTo: anonymous

8.5.2 Adding WS-Addressing Headers to Response Messages

For a Web service, if the WSADDRESSING parameter as "AUTO" and if the request message includes WS-Addressingheader elements, the service includes the following WS-Addressing header elements in the response message:

• To: anonymous

• Action: SoapAction_"Response"

• MessageID: unique uuid

• RelatesTo: MessageID of request

8.5.3 Creating WS-Addressing Header Elements Manually

For either a Web client or a Web service, if the WSADDRESSING parameter as "OFF" (the default), you can create theWS-Addressing header elements manually. To do so, create an instance of %SOAP.Addressing.Properties and use it as thevalue of the AddressingOut property.

8.5.4 Handling WS-Addressing Header Elements

When a Caché Web service or Web client receives a message that includes WS-Addressing header elements, the AddressingIn

property of the client or service is updated to equal an instance of %SOAP.Addressing.Properties.

Using SOAP and Web Services with Caché                                                                                                                         71

Adding WS-Addressing Header Elements

Page 80: Using SOAP and Web Services with Cach©
Page 81: Using SOAP and Web Services with Cach©

9Using WS-Security Features

This chapter describes how to use the WS-Security features provided in Caché. It discusses the following:

• An overview of Caché support for WS-Security features

• How to create the collection of root authority certificates that Caché uses

• How to create and use X.509 credentials, which provide an alias for a certificate and its private key

• How to add a time stamp to the WS-Security header

• How to add a username token to the WS-Security header

• How to add a digital signature to the WS-Security header

• Other ways to add digital signatures to the WS-Security header

• How to encrypt the body of SOAP messages

• How to encrypt response messages

• How to create a SAML token for use in outbound SOAP messages

• How to add a SAML token to outbound SOAP messages

• How to validate WS-Security headers of inbound SOAP messages and decrypt the messages

For other security options such as Kerberos, use a third-party SOAP gateway.

Note: If your Caché Web client uses a Web service that requires authentication, and if you do not want to use the featuresdescribed in this chapter, you can use the older WS-Security login feature. See “Using the WS-Security LoginFeature,” later in this book.

9.1 Caché Support for WS-Security FeaturesThis section describes the Caché support for WS-Security features.

9.1.1 Caché Support for the WS-Security Header

You can add the WS-Security header to the SOAP messages sent by Caché Web services and Web clients. The followingfigure shows the elements that you can include in this WS-Security header:

Using SOAP and Web Services with Caché                                                                                                                         73

Page 82: Using SOAP and Web Services with Cach©

These elements are as follows:

• The time stamp token (<wsu:Timestamp>) includes the <wsu:Created> and <wsu:Expires> elements, which specifythe range of time during which this message is valid. A time stamp is not, strictly speaking, a security element. Youcan use it, however, to avoid replay attacks.

• The username token (<wsse:UsernameToken>) enables a Web client to log into the Web service. It contains the usernameand password required by the Web service; these are included in clear text. If you include this header, use SSL so thatthe password cannot be intercepted and read by a third party.

• The signature element (<dsig:Signature>) signs parts of the message.

• The encrypted key element (<EncryptedKey>) specifies how the message is encrypted.

• The assertion element (<saml:Assertion>) includes the SAML assertion that you create. The assertion can be signedor unsigned and can include an X.509 SubjectConfirmation element.

74                                                                                                                         Using SOAP and Web Services with Caché

Using WS-Security Features

Page 83: Using SOAP and Web Services with Cach©

• The binary security tokens (<wsse:BinarySecurityToken>) are binary-encoded tokens that generally contain keymaterial. You can use these with the signature element, encryption element, and assertion element.

You can add these elements in any combination. Add them before sending the SOAP messages; the specified WS-Securityheader is included in all outbound SOAP messages.

9.1.2 Digital Signatures

In general, a digital signature has one of the following overall structures:

• It can consist of two pieces, as shown in the figure. These pieces are as follows:

– A <wsse:BinarySecurityToken> element that contains an X.509 certificate or a SAML assertion.

– A <dsig:Signature> element that uses the exclusive XML canonicalization method and the RSA SHA-1 crypto-graphic hash. The signature element and each signed element includes a direct reference (<SecurityTokenRefer-ence>) that points to the binary security token.

• It can consist of one piece, a <dsig:Signature> element that directly includes the key material, in some form. See“Options for Creating Credentials,” later in this section.

Also, by default, a digital signature is applied to specific parts of the SOAP message. You can instead choose the parts towhich it applies.

If the key material uses a SAML assertion, Caché follows the WS-Security SAML Token Profile specification. The keymaterial comes from the <SubjectConfirmation> element of the SAML assertion with Method = holder-of-key and <Sub-jectConfirmationData> or <KeyInfoConfirmationData> with a <KeyInfo> sub-element.

9.1.3 Encryption

You can also encrypt the body of SOAP messages sent by Caché Web services and Web clients. Caché support forencryption of SOAP messages is based on WS-Security 1.1. The encryption is based on an EncryptedKey element in theWS-Security header. In general, this element has one of the following overall structures:

• It can consist of two pieces, as shown in the figure. These pieces are as follows:

– A <wsse:BinarySecurityToken> element that contains an X.509 certificate or a SAML assertion.

If the binary security token contains an X.509 certificate, this technique follows the X.509 Certificate TokenProfile with X509v3 Token Type.

– An <EncryptedKey> element that contains a direct reference to the binary security token.

• It can consist of one piece, an <EncryptedKey> element that directly includes the key material, in some form. See“Options for Creating Credentials,” later in this section.

The algorithms used are as follows:

• Key encryption: RSA-OAEP

• Data encryption: AES-128, AES-192 and AES-256

• Signature Algorithm: #rsa-sha1

If the key material uses a SAML assertion, Caché follows the WS-Security SAML Token Profile specification, as describedin the previous section.

Using SOAP and Web Services with Caché                                                                                                                         75

Caché Support for WS-Security Features

Page 84: Using SOAP and Web Services with Cach©

9.1.4 Options for Creating Credentials

Within Caché SOAP support, there are three places where you create credentials:

• When you create a <Signature> element, you call the CreateX509() class method of %XML.Security.Signature.

• When you create an <EncryptedKey> element, you call the CreateX509() class method of %XML.Security.EncryptedKey.

• When you create a signed <Assertion> element, you call the CreateX509() class method of %SAML.Assertion.

All three of these methods include the following arguments:

• credentials, which can be either an instance of %SOAP.Security.BinaryToken or an instance of %SYS.X509Credentials.

• referenceOption, which controls how the element that you are adding refers to the credentials.

If credentials is a %SOAP.Security.BinaryToken, then you must use the default value for referenceOptions, which createsa direct reference from the added element to the binary security token. In this case, you must also be sure to insert the actualtoken into the WS-Security header.

If credentials is a %SYS.X509Credentials, then referenceOptions can have any of the following values, depending uponthe type of element that you are adding:

• $$$SOAPWSReferenceDirect — The element includes a direct reference to the binary security token. Specifically,a <KeyInfo> element is created with a <SecurityTokenReference> sub-element with a <Reference> sub-element whoseURI attribute is a local reference to the BinarySecurityToken. In order to use this option, you must be sure to add thesecurity token itself to the WS-Security header. This is the default.

• $$SOAPWSReferenceThumbprint — The element includes the SHA-1 thumbprint of the X.509 certificate.

• $$SOAPWSReferenceKeyIdentifier — The element includes the SubjectKeyIdentifier of the X.509 certificate.

• $$$SOAPWSReferenceIssuerSerial — The element includes a <KeyInfo> element with a <SecurityTokenRef-erence> child with a <X509Data> child that contains a <X509IssuerSerial> element.

• $$$KeyInfoX509Certificate — The element includes a <KeyInfo> element with a <X509Data> child thatcontains a <X509Certificate> element. This usage is not recommended by the WS-Security specification for the<Signature> and <EncryptedKey> elements, but may be used for the <Assertion> element.

• $$$KeyInfoX509IssuerSerial — The element includes a <KeyInfo> element with a <X509Data> child thatcontains a <X509IssuerSerial> element. This usage is not recommended by the WS-Security specification for the<Signature> and <EncryptedKey> elements, but may be used for the <Assertion> element.

• $$$KeyInfoX509SKI — The element includes a <KeyInfo> element with a X509Data child that contains a <X509SKI>element. This usage is not recommended by the WS-Security specification for the <Signature> and <EncryptedKey>elements, but may be used for the <Assertion> element.

• $$$KeyInfoX509SubjectName — The element includes a <KeyInfo> element with a <X509Data> child thatcontains a <X509SubjectName> element. This usage is not recommended by the WS-Security specification for the<Signature> and <EncryptedKey> elements, but may be used for the <Assertion> element.

• $$$KeyInfoRSAKey — The element includes a <KeyInfo> element with a <KeyValue> child that contains a<RSAKeyValue> element. This usage is not recommended by the WS-Security specification for the <Signature> and<EncryptedKey> elements, but may be used for the <Assertion> element.

Note that Caché SOAP support does not include support for STR Dereference Transform (#STR-Transform), which allowsindirect reference to a SAML Assertion by means of a <SecurityTokenReference> that is a direct child of the <Security>header.

76                                                                                                                         Using SOAP and Web Services with Caché

Using WS-Security Features

Page 85: Using SOAP and Web Services with Cach©

9.1.5 Validation and Decryption

Caché Web services and Web clients can validate the WS-Security header for inbound SOAP messages, as well as automat-ically decrypt the inbound messages.

They can also process the SAML assertion token and validate its signature. However, it is the responsibility of your appli-cation to validate the details of the SAML assertion itself.

9.2 Creating a Collection of Root Authority CertificatesCaché uses its own collection of root authority certificates to verify user certificates, verify signatures in incoming SOAPmessages, and encrypt content in outgoing SOAP messages. This collection is available to all namespaces of this Cachéinstallation.

This collection consists of two files that you create in the system manager’s directory:

• cache.cer contains trusted root CA X.509 certificates in PEM-encoded format.

• cache.crl contains X.509 certificate revocation lists in PEM-encoded format.

Note: Information on creating these files is beyond the scope of this book. For information on X.509, which specifiesthe content of certificates and certificate revocation lists. See RFC5280 (http://www.rfc-archive.org/getrfc.php?rfc=5280). For information on PEM-encoding, which is a file format, see RFC1421(http://www.ietf.org/rfc/rfc1421.txt).

CAUTION: Be careful to obtain root certificates from a trusted source for any production use, because these certificatesare the basis for trusting all other certificates.

This collection is not used for SSL. To configure a Caché Web service to use SSL, you create an SSL/TLS configurationwithin the System Management Portal. For information, see the chapter “Using SSL/TLS with Caché” in the CachéSecurity Administration Guide.

9.3 Creating, Editing, and Using X.509 CredentialsWith Caché SOAP support, you can use an X.509 certificate in outbound SOAP messages in two places: when digitallysigning the message, when encrypting the body, or both.

In Caché, you use a set of X.509 credentials to refer to an X.509 certificate and its private key, which are stored in theCaché database. This section describes how to create and retrieve these credentials, in general.

9.3.1 Creating X.509 Credentials

This is a one-time setup process, as follows:

1. Create or obtain the following:

• A personal X.509 certificate, in PEM-encoded X.509 format.

• An associated private key, in PEM-encoded PKCS#1 format.

Using SOAP and Web Services with Caché                                                                                                                         77

Creating a Collection of Root Authority Certificates

Page 86: Using SOAP and Web Services with Cach©

Note: Information on creating these files is beyond the scope of this documentation.

2. In the System Management Portal, click [Home] > [Security] > [X.509 Credentials].

3. Click Create New Credentials.

4. Specify the following values:

• Alias — Specify a unique, case-sensitive string that identifies these credentials. This property is required.

• File containing X.509 certificate — Click Browse ... and navigate to the certificate file. This property is required.

• File containing associated private key — Click Browse ... and navigate to the file that contains the password forthe private key. If you do not specify this property, you will have to provide the password instead when you retrievethe credentials.

• Authorized user(s) — Specify a comma-separated list of Caché users who can use these credentials. If this propertyis null, any user can use these credentials.

• Intended peer(s) — Specify a comma-separated list of the DNS names of systems where the credentials can beused. It is the responsibility of the user code to use the CheckPeerName() method of the credentials object tocheck that a peer is valid for these credentials.

5. Click Save.

When you do so, both the certificate file and the private key file (if any) are copied into the database.

Note that after you create the certificate file and private key file, you can also create the credentials programmatically. Forexample:

Set cred=##class(%SYS.X509Credentials).%New() Set cred.Alias="MyCred" Do cred.LoadCertificate("c:\mycertbase64.cer") Do cred.LoadPrivateKey("c:\mycertbase64.key") Set sc=cred.Save() If sc Do $system.Status.DisplayError(sc)

Note: Do not use the normal Cache object and SQL methods for accessing this data. The %Admin_Secure resourceis needed to use the Save() or Delete() methods.

For more details, see the class reference for %SYS.X509Credentials.

9.3.2 Editing X.509 Credentials

Once you have created a set of X.509 credentials, you can edit them as follows:

1. In the System Management Portal, click [Home] > [Security] > [X.509 Credentials].

2. In the table of sets of credentials, the value of the alias column serves as an identifier. For the set of credentials thatyou wish to edit, click Edit.

3. The following fields are read-only:

• Alias — Displays a unique, case-sensitive string that identifies these credentials. This property is required.

• X.509 Certificate Data — Lists important information from a certificate: its serial number, the distinguished nameof its issuer, and the distinguished name of its subject.

• Private key present — Checked if there is an existing private key associated with the certificate.

For the following fields, you can specify values:

78                                                                                                                         Using SOAP and Web Services with Caché

Using WS-Security Features

Page 87: Using SOAP and Web Services with Cach©

• Authorized user(s) — A comma-separated list of Caché users who can use these credentials. If this property isnull, any user can use these credentials.

• Intended peer(s) — A comma-separated list of the DNS names of systems where the credentials can be used. It isthe responsibility of the user code to use the CheckPeerName() method of the credentials object to check that apeer is valid for these credentials.

4. Click Save to save the specified lists of authorized users and intended peers.

It is not possible to change the alias or certificate of a set of credentials; it is also not possible to add, alter, or remove anassociated private key. To make any changes of this kind, create a new set of credentials.

9.3.3 Retrieving a Set of Caché X.509 Credentials

To retrieve a set of Caché credentials that can use an X.509 certificate, call the GetByAlias() class method of%SYS.X509Credentials.

classmethod GetByAlias(alias As %String, pwd As %String) as %SYS.X509Credentials

• alias is the alias for the certificate.

• pwd is the private key password. The private key password is needed only if the associated private key is encryptedand if the password was not loaded when the private key file was loaded.

To run this method, you must be logged in as a user included in the OwnerList for those credentials, or the OwnerList mustbe null.

You can retrieve Caché credentials in other ways such as the FindByField() , GetBySubjectKeyIdentifier(), andGetByThumbprint() methods. See the class documentation for %SYS.X509Credentials.

9.4 Adding a Time Stamp to the WS-Security HeaderTo add a time stamp to the WS-Security header, do the following in your Web client or Web service:

1. Call the Create() class method of %SOAP.Security.Timestamp. This method takes one optional argument (the expirationinterval in seconds) and returns an instance of %SOAP.Security.Timestamp. The default interval is 300 seconds.

2. Call the AddToken() method of the SecurityOut property of your Web client or Web service. For the method argument,use the %SOAP.Security.Timestamp instance you created.

3. Send the SOAP message as needed. The WS-Security header is included in the message.

4. For subsequent outbound messages:

• For a Web client, the SecurityOut property is left unchanged, so that subsequent outbound messages include thesecurity header you added. If this is undesirable, set the SecurityOut property to null.

• For a Web service, the SecurityOut property is automatically set to null after the first outbound SOAP message.

For example, in a Web service:

do ..SecurityOut.AddToken(##class(%SOAP.Security.Timestamp).Create())

Using SOAP and Web Services with Caché                                                                                                                         79

Adding a Time Stamp to the WS-Security Header

Page 88: Using SOAP and Web Services with Cach©

9.5 Adding a Username Token to the WS-Security HeaderTo add a WS-Security username token, do the following in your Web client or Web service:

1. Call the Create() class method of %SOAP.Security.UsernameToken. This method takes two arguments (the usernameand password) and returns an instance of %SOAP.Security.UsernameToken.

2. Call the AddToken() method of the SecurityOut property of your Web client or Web service. For the method argument,use the %SOAP.Security.UsernameToken instance you created.

3. Send the SOAP message as needed. The WS-Security header is included in the message.

4. For subsequent outbound messages:

• For a Web client, the SecurityOut property is left unchanged, so that subsequent outbound messages include thesecurity header you added. If this is undesirable, set the SecurityOut property to null.

• For a Web service, the SecurityOut property is automatically set to null after the first outbound SOAP message.

For example, in the Web client:

//set client=instance of client proxy class //set client.Location set user="_SYSTEM" set pwd="SYS" set usertoken=##class(%SOAP.Security.UsernameToken).Create(user,pwd) do client.SecurityOut.AddToken(usertoken)

CAUTION: Ensure that you are using SSL between the Web client and the Web service. The WS-Security header issent in clear text, so this technique is not secure unless SSL is used. See the section “Configuring theClient to Use SSL,” earlier in this book.

9.6 Adding a Digital Signature to the WS-Security HeaderCommonly, a digital signature consists of two parts: a binary security token that uses an X.509 certificate (or SAMLassertion), and a signature element that has a direct reference to that binary security token.

To add this kind of digital signature, do the following in your Web client or Web service:

1. Create the credentials. For information on creating credentials that use an X.509 certificate, see “Retrieving a Set ofCaché X.509 Credentials.” Or create credentials that use a signed SAML assertion as described in “Creating a SAMLToken,” later in this chapter.

2. Create a binary security token that contains the credentials. To do so, call the CreateX509Token() class method of%SOAP.Security.BinarySecurityToken.

classmethod CreateX509Token(credentials As %SYS.X509Credentials) as %SOAP.Security.BinarySecurityToken

Where credentials is the credentials you created in the previous step.

3. Add the binary security token to the WS-Security headers. To do so, call the AddToken() method of the SecurityOut

property of your Web client or Web service. For the method argument, use the binary security token you created pre-viously.

4. Create a digital signature. To do so, call the CreateX509() class method of %XML.Security.Signature.

80                                                                                                                         Using SOAP and Web Services with Caché

Using WS-Security Features

Page 89: Using SOAP and Web Services with Cach©

classmethod CreateX509(credentials As %SYS.X509Credentials, signatureOption As %Integer, referenceOption As %Integer) as %XML.Security.Signature

Where:

• credentials is the binary security token you created previously. (In general, this argument can be either an instanceof %SOAP.Security.BinaryToken or %SYS.X509Credentials. The next section discusses the latter option.)

• signatureOption is optional. See “Applying a Digital Signature to Specific Message Parts.”

• Ignore referenceOption; only one value (the default) is permitted when credentials is a binary security token.

This method returns a signature element that uses a direct reference to the binary security token.

5. Add the digital signature to the WS-Security headers. To do so, call the AddElement() method of the SecurityOut

property of your Web client or Web service.

6. Send the SOAP message as needed. The WS-Security header is included in the message.

7. For subsequent outbound messages:

• For a Web client, the SecurityOut property is left unchanged, so that subsequent outbound messages include thesecurity header you added. If this is undesirable, set the SecurityOut property to null.

• For a Web service, the SecurityOut property is automatically set to null after the first outbound SOAP message.

For example:

//get credentialsset x509alias = "something"set pwd = "password"set cred = ##class(%SYS.X509Credentials).GetByAlias(x509alias,pwd)

//get certificate and add it as binary security tokenset cert = ##class(%SOAP.Security.BinarySecurityToken).CreateX509Token(cred)do ..SecurityOut.AddToken(cert)

//create and add signature with direct reference to the binary security tokenset sig=##class(%XML.Security.Signature).CreateX509(cert)do ..SecurityOut.AddElement(sig)

9.7 Signature VariationsThis section discusses other ways to add digital signatures to your outbound SOAP messages.

9.7.1 Adding a Digital Signature without a Binary Security Token

The previous section describes how to add a digital signature with a direct reference to a binary security token that includesan X.509 certificate or a SAML assertion. Both the binary security token and the signature are included as elements withinthe WS-Security header.

This section describes how to add digital signatures that do not use a binary security token. Instead, the key material isincluded directly, in some form, within the signature itself.

The technique is as follows:

1. Create the credentials. For information on creating credentials that use an X.509 certificate, see “Retrieving a Set ofCaché X.509 Credentials.” Or create credentials that use a signed SAML assertion as described in “Creating a SAMLToken,” later in this chapter.

2. Create a digital signature. To do so, call the CreateX509() class method of %XML.Security.Signature.

Using SOAP and Web Services with Caché                                                                                                                         81

Signature Variations

Page 90: Using SOAP and Web Services with Cach©

classmethod CreateX509(credentials As %SYS.X509Credentials, signatureOptions As %Integer, referenceOptions As %Integer) as %XML.Security.Signature

• credentials — Use the credentials you created in the previous step.

• referenceOptions — Specify a value as described in “Options for Creating Credentials.”

• signatureOptions — Optionally specify a value as described in “Applying a Digital Signature to Specific MessageParts.”

3. Add the digital signature to the WS-Security headers. To do so, call the AddElement() method of the SecurityOut

property of your Web client or Web service.

4. Send the SOAP message as needed. The WS-Security header is included in the message.

5. For subsequent outbound messages:

• For a Web client, the SecurityOut property is left unchanged, so that subsequent outbound messages include thesecurity header you added. If this is undesirable, set the SecurityOut property to null.

• For a Web service, the SecurityOut property is automatically set to null after the first outbound SOAP message.

For example:

//get credentials set x509alias = "something" set pwd = "password" set cred = ##class(%SYS.X509Credentials).GetByAlias(x509alias,pwd)

//create signature that uses thumbprint of credentials set sig=##class(%XML.Security.Signature). CreateX509(cred,,$$SOAPWSReferenceThumbprint)

//add signature do ..SecurityOut.AddElement(sig)

Note: Because of line-length limitations for the PDF book files, this example includes a line break that is not permittedsyntactically. This line break occurs where the example sets the sig variable.

9.7.2 Applying a Digital Signature to Specific Message Parts

By default, when you create and add a digital signature to the WS-Security header, the signature is applied to specificmessage parts, as described in “Caché Support for the WS-Security Header.”

To instead apply the digital signature to message parts you choose, follow the basic steps described earlier with one variation:

• When you create the signature, use the signatureOptions argument to specify the message parts to sign:

classmethod CreateX509(credentials As %SYS.X509Credentials, signatureOptions As %Integer, referenceOptions As %Integer) as %XML.Security.Signature

signatureOptions controls which parts of the SOAP message are signed. Specify this as a binary combination of anyof the following macros (which are contained in the %soap.inc file):

– $$$SOAPWSIncludeNone

– $$$SOAPWSIncludeDefault (which equals$$$SOAPWSIncludeSoapBody+$$$SOAPWSIncludeTimestamp+$$$SOAPWSIncludeAddressing)

– $$$SOAPWSIncludeSoapBody

– $$$SOAPWSIncludeTimestamp

82                                                                                                                         Using SOAP and Web Services with Caché

Using WS-Security Features

Page 91: Using SOAP and Web Services with Cach©

– $$$SOAPWSIncludeAddressing

– $$$SOAPWSIncludeAction

– $$$SOAPWSIncludeFaultTo

– $$$SOAPWSIncludeFrom

– $$$SOAPWSIncludeMessageId

– $$$SOAPWSIncludeRelatesTo

– $$$SOAPWSIncludeReplyTo

– $$$SOAPWSIncludeTo

To combine macros, use plus (+) and minus (-) signs. For example:

$$$SOAPWSIncludeSoapBody+$$$SOAPWSIncludeTimestamp

For example:

//get credentials set x509alias = "something" set pwd="password" set cred = ##class(%SYS.X509Credentials).GetByAlias(x509alias,pwd)

//get certificate and add as binary security token to specific parts set parts = $$$SOAPWSIncludeSoapBody + $$$SOAPWSIncludeTimestamp set cert = ##class(%SOAP.Security.BinarySecurityToken). CreateX509Token(cred,parts) do ..SecurityOut.AddToken(cert)

//create and add signature set sig=##class(%XML.Security.Signature).CreateX509(cert) do ..SecurityOut.AddElement(sig)

Note: Because of line-length limitations of the PDF book files, this example includes a line break that is not permittedsyntactically. This line break occurs where the example sets the cert variable.

When you add the digital signature to the WS-Security header, Caché signs each of the selected message parts, accordingto your referenceOptions, as discussed in the previous sections.

9.8 Encrypting the SOAP Body with an X.509 CertificateTo send encrypted SOAP messages, you add the <EncryptedKey> element to the WS-Security headers, and Caché automat-ically encrypts the SOAP body correspondingly. The <EncryptedKey> element uses an X.509 certificate or a SAMLassertion as the key material.

To encrypt the body of your SOAP messages , do the following in your Web client or Web service:

1. Create the credentials. For information on creating credentials that use an X.509 certificate, see “Retrieving a Set ofCaché X.509 Credentials.” Or create credentials that use a signed SAML assertion as described in “Creating a SAMLToken,” later in this chapter.

2. If your <EncryptedKey> element is going to use a direct reference to the credentials, create and add the credentials tothe WS-Security headers.

To create a binary security token that contains the credentials, call the CreateX509Token() class method of%SOAP.Security.BinarySecurityToken.

classmethod CreateX509Token(credentials As %SYS.X509Credentials) as %SOAP.Security.BinarySecurityToken

Using SOAP and Web Services with Caché                                                                                                                         83

Encrypting the SOAP Body with an X.509 Certificate

Page 92: Using SOAP and Web Services with Cach©

Where credentials is the Caché credentials you created in the previous step.

To add this token to the WS-Security headers, call the AddToken() method of the SecurityOut property of your Webclient or Web service. For the method argument, use the token you just created.

3. Create the <EncryptedKey> element. To do so, call the CreateX509() class method of %XML.Security.EncryptedKey.

classmethod CreateX509(credentials As %SYS.X509Credentials = "", encryptionOptions As %Integer, referenceOption As %Integer) as %XML.Security.EncryptedKey

• credentials — Specify the binary security token you created previously.

• encryptionOptions — Ignore this argument, which is for future use.

• signatureOptions — Optionally specify a value as described in “Applying a Digital Signature to Specific MessageParts.”

4. Add the <EncryptedKey> element to the WS-Security headers. To do so, call the AddElement() method of theSecurityOut property of your Web client or Web service.

5. Send the SOAP message as needed. The body of the message is encrypted and the <EncryptedKey> element is includedin the WS-Security header of the message.

6. For subsequent outbound messages:

• For a Web client, the SecurityOut property is left unchanged, so that subsequent outbound messages are encryptedand include the security header you added. If this is undesirable, set the SecurityOut property to null.

• For a Web service, the SecurityOut property is automatically set to null after the first outbound SOAP message.

For example, to encrypt the SOAP body and add the <EncryptedKey> element with the thumbprint of the certificate:

//get credentials set x509alias = "something" set pwd="password" set cred = ##class(%SYS.X509Credentials).GetByAlias(x509alias,pwd) set x509=##class(%SYS.X509Credentials).GetByAlias(x509Alias[,password])

//get EncryptedKey element and add it set enc=##class(%XML.Security.EncryptedKey). CreateX509(cred,,$$$SOAPWSReferenceThumbprint) do ..SecurityOut.AddElement(enc)

Note: Because of line-length limitations of the PDF book files, this example includes a line break that is not permittedsyntactically. This line break occurs where the example sets the enc variable.

For example, to encrypt the SOAP body and add the EncryptedKey element with a direct reference to the certificate:

//get credentials set x509alias = "something" set pwd="password" set cred = ##class(%SYS.X509Credentials).GetByAlias(x509alias,pwd)

//get certificate as binary security token and add it set cert=##class(%SOAP.Security.BinarySecurityToken).CreateX509Token(cred) do ..SecurityOut.AddToken(cert)

//get EncryptedKey element and add it set enc=##class(%XML.Security.EncryptedKey). CreateX509(cred,,$$$SOAPWSReferenceDirect) do ..SecurityOut.AddElement(enc)

Note: Because of line-length limitations of the PDF book files, this example includes a line break that is not permittedsyntactically. This line break occurs where the example sets the enc variable.

84                                                                                                                         Using SOAP and Web Services with Caché

Using WS-Security Features

Page 93: Using SOAP and Web Services with Cach©

9.9 Creating a SAML TokenWith Caché SOAP support, you can use a SAML token in outbound SOAP messages as part of the WS-Security header.Optionally, you can use this SAML token as key material for the digital signature or as key material for encrypting thebody.

To create a SAML token for use in outbound SOAP messages, use the following procedure. Note that is beyond the scopeof this book to explain the SAML Token Profile specification itself; also see the class reference for %SAML.Assertion andrelated classes.

1. If you are going to create a digitally signed SAML token:

a. Create the credentials. For information on creating credentials that use an X.509 certificate, see “Retrieving a Setof Caché X.509 Credentials.” Or create credentials that use a signed SAML assertion as described in the currentprocedure.

b. Optionally create and then add a binary security token that contains the credentials.

To create the token, call the CreateX509Token() class method of %SOAP.Security.BinarySecurityToken.

classmethod CreateX509Token(credentials As %SYS.X509Credentials) as %SOAP.Security.BinarySecurityToken

Where credentials is the credentials you created in the previous step.

To add this token to the WS-Security header, call the AddToken() method of the SecurityOut property of yourWeb client or Web service. For the method argument, use the token you just created.

2. Call one of the following methods of %SAML.Assertion:

• To create an unsigned SAML token, call Create(). This method takes no arguments.

• To create a signed SAML token, call CreateX509(). This method takes the following arguments:

classmethod CreateX509(credentials As %SYS.X509Credentials, referenceOption As %Integer) as %SAML.Assertion

For credentials, use the binary security token or the credentials themselves. In the former case, do not specifyreferenceOption. In the latter case, see “Options for Creating Credentials.”

Either method returns an instance of %SAML.Assertion. If you used CreateX509(), the Signature property of thisinstance is specified automatically; otherwise it is null. In either case, the SAMLID and Version properties are alsospecified automatically.

3. Specify the following basic properties of your instance of %SAML.Assertion as follows:

• For IssueInstant, specify the date and time when this assertion is issued.

• For Issuer, create an instance of %SAML.NameID. Specify properties of this instance as needed and set the Issuer

property of your assertion equal to this instance.

4. Add SAML statements, as follows:

a. Create one or more instances of the appropriate statement classes: %SAML.AttributeStatement,%SAML.AuthnStatement, or %SAML.AuthzDecisionStatement. (These are all subclasses of %SAML.Statement.

Specify properties of these instances as needed.

For %SAML.AttributeStatement, the Attribute property is an instance of either %SAML.Attribute or%SAML.EncryptedAttribute.

Using SOAP and Web Services with Caché                                                                                                                         85

Creating a SAML Token

Page 94: Using SOAP and Web Services with Cach©

%SAML.Attribute carries attribute values in its AttributeValue property, which is a list of %SAML.AttributeValue

instances. To set a value in %SAML.AttributeValue, use the methods of that class, which enable you to specify theattribute either as XML, as a string, or as a single child element. Similarly, the %SAML.AttributeValue class providesmethods to retrieve the attribute values.

b. Create a list that contains these statement instances and set the Statement property of your assertion equal to thislist.

5. Add a <Subject> element to the SAML assertion. To do so:

a. Create a new instance of %SAML.Subject.

b. Set properties of the subject as needed.

c. Set the Subject property of your SAML assertion equal to this instance.

6. Optionally add a <SubjectConfirmation> element to the <Subject>. To do so:

a. Create the credentials. For information on creating credentials that use an X.509 certificate, see “Retrieving a Setof Caché X.509 Credentials.” Or create credentials that use a signed SAML assertion as described in the currentprocedure.

Or use the same credentials that you use to sign the assertion itself.

b. Optionally create and then add a binary security token that contains the credentials.

To create the token, call the CreateX509Token() class method of %SOAP.Security.BinarySecurityToken.

classmethod CreateX509Token(credentials As %SYS.X509Credentials) as %SOAP.Security.BinarySecurityToken

Where credentials is the credentials you created in the previous step.

To add this token to the WS-Security header, call the AddToken() method of the SecurityOut property of yourWeb client or Web service. For the method argument, use the token you just created.

c. Call the AddX509Confirmation() method of the Subject property of your SAML assertion.

method AddX509Confirmation(credentials As %SYS.X509Credentials, referenceOption As %Integer) as %Status

For credentials, use the binary security token or the credentials themselves. In the former case, do not specifyreferenceOption. In the latter case, see “Options for Creating Credentials.”

The <SubjectConfirmation> element is based on an X.509 KeyInfo element.

7. Specify the SAML <Conditions> element, as follows:

a. Create an instance of %SAML.Conditions.

b. Specify properties of this instance as needed and set the Conditions property of your assertion equal to this instance.

8. Optionally add an <Advice> element as follows:

a. Create an instance of one of the following classes: %SAML.AssertionIDRef, %SAML.AssertionURIRef, or%SAML.EncryptedAssertion. (These are all subclasses of %SAML.AssertionReference.)

b. Specify properties of this instance as needed and set the Advice property of your assertion equal to this instance.

86                                                                                                                         Using SOAP and Web Services with Caché

Using WS-Security Features

Page 95: Using SOAP and Web Services with Cach©

9.10 Adding a SAML Token to the WS-Security HeaderTo add a SAML token to the WS-Security header element:

1. Create the SAML token as described in the previous section.

2. Call the AddToken() method of the SecurityOut property of your Web client or Web service. For the method argument,use the SAML token you created.

3. Send the SOAP message as needed. The WS-Security header is included in the message.

4. For subsequent outbound messages:

• For a Web client, the SecurityOut property is left unchanged, so that subsequent outbound messages include thesecurity header you added. If this is undesirable, set the SecurityOut property to null.

• For a Web service, the SecurityOut property is automatically set to null after the first outbound SOAP message.

9.11 Encrypting the Response MessagesWhen a Web service has received an encrypted message and needs to send an encrypted response, sometimes it is convenientto encrypt the response with the SHA-1 hash of the <CipherValue> contained in the original request. To do so:

1. Call the Create() method of %XML.Security.EncryptedData. For the third argument, use$$$SOAPWSReferenceEncryptedKeySHA1, which returns the SHA-1 hash of the encrypted key that was containedin the last request to this Web service.

This method returns an EncryptedData element.

2. Call the AddElement() method of the SecurityOut property of your Web service.

3. Send the SOAP response. It contains the EncryptedData element with #EncryptedKeySHA1 to reference the requestkey for encryption.

For example:

set enc=##class(%XML.Security.EncryptedData).Create(,, $$$SOAPWSReferenceEncryptedKeySHA1)do ..SecurityOut.AddElement(enc)

Note: Because of line-length limitations of the PDF book files, this example includes a line break that is not permittedsyntactically. This line break occurs where the example sets the enc variable.

9.12 Validating WS-Security Headers and Decrypting theMessagesThis section discusses how to validate the WS-Security headers of any inbound SOAP messages and how to decrypt themessages. It discusses the following:

• How to validate WS-Security headers of inbound SOAP messages and how to decrypt those messages

Using SOAP and Web Services with Caché                                                                                                                         87

Adding a SAML Token to the WS-Security Header

Page 96: Using SOAP and Web Services with Cach©

• The relationship between CSP authentication and WS-Security

When your Caché Web service or Web client validates the WS-Security header of an inbound SOAP message, it alsodecrypts the message body, if appropriate.

9.12.1 Validating WS-Security Headers and Decrypting the Messages

To validate the WS-Security headers contained in any inbound SOAP messages, do the following:

1. If you have not already done so, create the collection of root authority certificates, as described in the previous section.

2. In the Web service or the Web client, set the SECURITYIN parameter to one of the following values:

• REQUIRE — The Web service or the Web client verifies the WS-Security header and issues an error if there is amismatch or if this element is missing.

• ALLOW — The Web service or the Web client verifies the WS-Security header element.

In both cases, the Web service or the Web client validates the <Timestamp>, <UsernameToken>, <BinarySecurityTo-ken>, <Signature>, and <EncryptedKey> header elements. It also validates the WS-Security signature in the SAMLassertion in the header, if any.

If validation fails, an error is returned.

The message is also decrypted, if appropriate.

For backward compatibility, the default is IGNORE. For this value, the Web service or client ignores the WS-Securityheader element except for the UsernameToken element, as described in the next section.

9.12.2 Validating the SAML Assertion

If the WS-Security header includes an <Assertion> element, a Caché Web service or Web client automatically validatesany WS-Security signature in that SAML assertion.

It does not, however, validate the assertion itself. To validate the SAML assertion, find the <Assertion> element of thesecurity header, as follows:

Set assertion=..SecurityIn.FindByElement("Assertion")

Then examine the assertion as needed.

9.12.3 CSP Authentication and WS-Security

It is useful to understand that with a Caché Web service, two separate mechanisms are in effect: the CSP engine and theWeb service itself.

• In the System Management Portal ([Home] > [Security Management] > [CSP Applications]), you specify allowedauthentication modes for a CSP application. The Password option, if selected, enables the CSP application to accepta Caché username/password pair.

• Independently of this, the Web service can require a Caché username/password pair.

These mechanisms work together as follows:

1. Upon receiving a message, a Caché Web service checks for the presence of a header element called <Security>, withoutexamining the contents of that element.

88                                                                                                                         Using SOAP and Web Services with Caché

Using WS-Security Features

Page 97: Using SOAP and Web Services with Cach©

2. If no <Security> header element is present and if the SECURITYIN parameter equals REQUIRE, the Web service issuesa fault and quits.

3. If the <Security> header element contains a UsernameToken element:

• If the Password option is selected, the Web service instructs the CSP engine to log into Cache.

The Web service does this regardless of the setting of the SECURITYIN parameter (that is, even if SECURITYINequals IGNORE).

The username is available in the $username variable and in the Username property of the Web service. The passwordis not available.

• If the Password option is not selected, no login occurs.

Using SOAP and Web Services with Caché                                                                                                                         89

Validating WS-Security Headers and Decrypting the Messages

Page 98: Using SOAP and Web Services with Cach©
Page 99: Using SOAP and Web Services with Cach©

10SOAP Session Management

SOAP Web services are inherently stateless and thus do not maintain sessions. However, it is often useful to maintain asession between a Web client and the Web service that it uses. The Caché SOAP support provides a way for you to do this.This chapter includes the following topics:

• Overview of the tools used for Caché SOAP session support

• How to enable session support

• How to use session support

Also see the section “Specifying Custom HTTP Requests” in the chapter “Fine-tuning a Caché Web Client.”

10.1 Overview of SOAP SessionsYou can maintain a session between a Web client and a Caché Web service. This support consists of the following generaltools:

• CSP session management, which is described in the book Using Caché Server Pages (CSP).

• The Caché SOAP session header, which is a simple proprietary header.

The overall flow is as follows:

1. The Web client sends an initial message to the Web service. This message does not include the Caché SOAP sessionheader.

2. The Web service receives the message and starts a new CSP session.

3. When the Web service sends its reply, it adds the Caché SOAP session header to the message.

4. The Web client receives the reply and detects the SOAP session header. The session cookie is saved in the SessionCookie

property of Web client. When the Web client sends another message, it uses the cookie to create a SOAP session headerin that message.

Note: This step happens automatically if the same client class is used for all SOAP messages in the session forCache and .NET Web clients. You may need further code for other client platforms.

5. The Web service receives the next reply, continues the CSP session, and includes the SOAP session header again whenit responds.

Using SOAP and Web Services with Caché                                                                                                                         91

Page 100: Using SOAP and Web Services with Cach©

10.2 Enabling SessionsIn order to use Caché support for SOAP sessions, you must be using a Caché Web service.

• If the Web client is based on Caché, only one step is needed to enable SOAP session support. In your Web serviceclass, set the SOAPSESSION parameter equal to 1.

• If you are using a third-party tool to create the Web client, you are responsible for detecting the Caché SOAP sessionheader element in the initial response and ensuring that the Web client includes this header element in all requestsduring the life of the session. This header element has the following format:

<csp:CSPCHD xmlns:csp="http://www.intersystems.com/SOAPheaders">value ofCPSCHD token</csp:CSPCHD>

10.3 Using Session InformationThe process of using session information is the same as it is with other CSP pages. Namely, the Web service can use avariable named %session, which is an instance of %CSP.Session. Properties of this object contain system information andany information you choose to add. Some of the commonly used properties are as follows:

• SessionID — Unique identifier of this session.

• EndSession — Normally this equals 0. Set this property to 1 in order to end the session.

• Data — Caché multidimensional array intended to hold any custom data.

• NewSession — Equals 1 if this is new session.

• AppTimeout — Specifies the timeout value for the session, in seconds.

The %session object provides many other properties, as well as some methods for tasks related to sessions. For furtherdetails, see the class documentation for %CSP.Session and see the book Using Caché Server Pages (CSP).

92                                                                                                                         Using SOAP and Web Services with Caché

SOAP Session Management

Page 101: Using SOAP and Web Services with Cach©

11Using the Caché Binary SOAP Format

Caché SOAP support provides an optional proprietary binary SOAP format, which is useful when you send and receivelarge SOAP messages and want to minimize message size.

As of this release, any Caché Web service can receive SOAP requests either in Caché binary SOAP format or in the usualSOAP format. No parameter is needed to enable this behavior. A Caché Web client uses binary SOAP format only if it isconfigured to do so.

This chapter discusses the following:

• An introduction to Caché binary SOAP

• How to extend the WSDL for a Caché Web service to indicate that it supports this format

• How to redefine an existing Caché Web client so that it uses Caché binary SOAP format

• How to specify the character set used

• Additional details on the API for this format

11.1 IntroductionCaché binary SOAP is carried over HTTP messages as follows:

• The message uses the POST method.

• Content-Type is always "application/octet-stream".

• The body is a binary representation of objects using a proprietary protocol.

• A binary SOAP request includes an ISCSoap header, which has the same contents as the SOAPAction header does forXML SOAP.

• SOAP sessions are supported. The session information is maintained by using the normal CSP session cookie. However,the SessionCookie property for SOAP Web clients and Web services is not supported, because binary SOAP does notuse the CSPCHD proprietary SOAP header.

The following example shows a binary SOAP request:

Using SOAP and Web Services with Caché                                                                                                                         93

Page 102: Using SOAP and Web Services with Cach©

POST /csp/gsop/GSOP.WebServiceBinary.cls HTTP/1.1User-Agent: Mozilla/4.0 (compatible; Cache;)Host: localhost:8080Connection: CloseISCSoap: http://www.myapp.org/GSOP.WebServiceBinary.DivideContent-Type: application/octet-streamContent-Length: 90

00085hdBinaryClient.MyAppSoap.Dividearg1arg2t

11.2 Extending the WSDL for a Caché Web ServiceAs of this release, any Caché Web service can receive SOAP requests either in Caché binary SOAP format or in the usualSOAP format. If a Caché Web service receives a binary request, it sends a binary response. Otherwise, it sends the usualresponse. No parameter is needed to enable this behavior.

You can extend the WSDL of a Web service so that:

1. The WSDL publicly states that the Web service supports the Caché binary SOAP format in addition to the usual SOAPformat.

2. The WSDL includes information on using the Caché binary SOAP format.

This allows any Caché Web client to correctly send messages in this format if wanted.

To extend the WSDL of a Caché Web service in this way, set the SOAPBINARY parameter to 1 for the Web service.

11.2.1 WSDL Differences

For a Caché Web service that has the SOAPBINARY parameter specified as 1, the WSDL is enhanced to carry the necessaryinformation for the Cache Web client. These WSDL extensions are valid according to the XML Schema, WSDL and WS-I Basic Profile specifications and are expected to be ignored by all conforming web client toolkits.

The Cache WSDL extensions are all in the http://www.intersystems.com/soap/ XML namespace which is indicatedin the WSDL with the isc: prefix. The changes are as follows:

• An extension child element of the wsdl:binding is introduced to indicate SOAP binary support:

<isc:binding charset="Cache_charset">

Where Cache_charset is the Caché character set (for example: Unicode, Latin1) of the Caché namespace for the Webservice.

• An extension attribute is added to all complexType elements in the XML schema in the wsdl:types element:

<complexType isc:classname="serviceClassname" ....>

Where serviceClassname is the class name corresponding to this complex type in the Caché namespace for the Webservice.

• An extension attribute is added to element and simpleContent elements for which the element name attribute is not thesame property name because of use of XMLNAME property parameter:

<element isc:property="property name" ....> <simpleContent isc:property="property name" ....>

Where property_name is the name of a property. This applies in the case of XMLPROJECTION equal to "content".

The isc:property attribute allows the property names to be the same in the generated client classes as in the serviceclasses. Current exceptions are any choice or substitutionGroup usage or for wrapped element where the type classhas an XMLNAME parameter.

94                                                                                                                         Using SOAP and Web Services with Caché

Using the Caché Binary SOAP Format

Page 103: Using SOAP and Web Services with Cach©

11.2.2 Differences in Generated Web Client Classes

If you use the SOAP client wizard to generate Web client classes for a Web service that has SOAPBINARY equal to 1, thegenerated classes contain the following additional parameter settings:

• SOAPBINARY equal to 0. This is added to the Web client class. It indicates that SOAP binary protocol is available,but is not used as default. You can edit this parameter.

• SOAPBINARYCHARSET equal to "Cache_charset" where Cache_charset is a Caché character set class based onthe isc:binding element. This is added to the Web client class.

• SOAPCLASSNAME equal to "serviceClassname" where serviceClassname is the name of the type class as usedby the Web service. This is added to each supporting type class that is created. Do not edit this parameter.

11.3 Redefining a Caché Web Client to Use Binary SOAPYou can redefine an existing Caché Web client so that it uses Caché binary SOAP format. To do so, set the SOAPBINARYparameter or the SoapBinary property to 1 for the Web client. You may need to make additional changes; see the previoussection.

11.4 Specifying the Character SetThe SoapBinaryCharset property of the Web client specifies the Caché character set (for example: Unicode, Latin1) of theWeb service. If the character set of the client machine and service machine are the same, strings are sent RAW; otherwisethey are set encoded as UTF8.

The SoapBinaryCharset property defaults to the SOAPBINARYCHARSET parameter, which defaults to null, which alwaysconverts strings to UTF8.

11.5 Details on the Caché Binary SOAP FormatThe API for binary SOAP is different from XML SOAP as follows:

• For CSP server:

– Binary SOAP is denoted by the presence of the ISCSoap HTTP header.

– The Initialize() method of the Web service is not called.

– A normal %request.Content stream is used in the initial implementation.

– Login is via CacheUserName and CachePassword query parameters attached to the URL. No login page is everreturned for binary SOAP.

– If an invalid login occurs, then an instance of %SOAP.Fault is be returned.

• For %Net.HttpRequest responses:

– A binary SOAP request is indicated by setting the SoapBinary property of the Web client class for the methodbeing called.

Using SOAP and Web Services with Caché                                                                                                                         95

Redefining a Caché Web Client to Use Binary SOAP

Page 104: Using SOAP and Web Services with Cach©

– The request is sent using a normal EntityBody stream.

– The response is returned in the Data property of HttpResponse.

96                                                                                                                         Using SOAP and Web Services with Caché

Using the Caché Binary SOAP Format

Page 105: Using SOAP and Web Services with Cach©

12Fine-tuning a Caché Web Service

This chapter discusses various ways to fine-tune a Caché Web service. It discusses the following:

• How to control the types used by the Web service

• How to control the namespace of the schema and types used by the Web service

• How to include the class documentation for the types as annotations within the WSDL

• How to control the message name of the SOAP response

• How to override the default SOAPAction header in HTTP requests

• How to specify whether elements are qualified

• How to control the form of the SOAP message parts

• How to control the form of null arguments

• How to control the use of the xsi:type attribute in the SOAP messages

• How to control the prefix used for the SOAP message envelope

• How to send responses compressed by gzip

• How to define a one-way Web method

• How to add a UTF-8 BOM to the start of each message sent by the Web service

• How to customize callbacks of the Web service

• How to use custom transport to communicate with a Web service

Also see the section “Basic Settings of the Web Service” in the chapter “Basics of Creating Web Services.”

12.1 Controlling the XML TypesThe WSDL defines the XML types for the arguments and return values of all methods of the Web service. For a CachéWeb service, the types are determined as follows:

• If the Caché type corresponds to a simple type (such as %String), an appropriate corresponding XML type is used.

• If the Caché type corresponds to an XML-enabled class, the XMLTYPE parameter of that class specifies the name ofthe XML type. If that parameter is not specified, the class name (without the package) is used as the XML type name.

Also, the WSDL defines this type, by using the information in the corresponding class definition.

Using SOAP and Web Services with Caché                                                                                                                         97

Page 106: Using SOAP and Web Services with Cach©

• If the Caché type corresponds to some other class, the class name (without the package) is used as the XML type name.Also, the WSDL does not define this type.

For further details, see the book Using XML with Caché.

Also see the section “WSDL Support in Caché” in the first chapter.

12.2 Controlling the Namespaces of the Schema andTypesThis section describes how to control the namespace for the schema of the WSDL, as well as the namespaces for any typesdefined within it.

12.2.1 Controlling the Namespace of the Schema

The TYPENAMESPACE parameter (of your Web service) controls the target namespace for the schema of your Web service.

If TYPENAMESPACE is null, the schema is in the namespace given by the NAMESPACE parameter of the Web service.The WSDL might look as follows:

<?xml version='1.0' encoding='UTF-8' ?>...<types><s:schema elementFormDefault='qualified' targetNamespace = 'http://www.myapp.org'>...

If you set TYPENAMESPACE to a URI, that URI is used as the namespace for the types. In this case, the WSDL mightlook as follows:

<?xml version='1.0' encoding='UTF-8' ?>...<types><s:schema elementFormDefault='qualified' targetNamespace = 'http://www.mytypes.org'>...

12.2.2 Controlling the Namespace of the Types

For any types referenced within the schema, the following rules govern how they are assigned to namespaces:

• If the USECLASSNAMESPACES parameter of the Web service is 0 (the default), then the types are in the samenamespace as the schema; see the previous section.

• If the USECLASSNAMESPACES parameter of the Web service is 1 (and if the Web service uses the document bindingstyle), then each type is in the namespace given by the NAMESPACE parameter of the corresponding type class.

For a given type, if the NAMESPACE parameter is null for the type class, then the type is in the same namespace asthe schema; see the previous section.

For information on binding styles, see “Specifying the Binding Style for the SOAP Messages,” earlier in this book.

98                                                                                                                         Using SOAP and Web Services with Caché

Fine-tuning a Caché Web Service

Page 107: Using SOAP and Web Services with Cach©

12.3 Including Documentation for the TypesBy default, the WSDL for a Web service does not include documentation for the types used by the Web service.

If you want to include the class documentation for the types within <annotation> elements in the schema, specify theINCLUDEDOCUMENTATION parameter of the Web service as 1.

12.4 Controlling the Message Name of the SOAPResponseYou can control the message name used in the response received from a Web method. By default, this message name isthe name of the Web method with Response appended to the end. The following example shows a response from a Webmethod called Divide; the response message name is DivideResponse.

<SOAP-ENV:Body> <DivideResponse xmlns="http://www.myapp.org"> <DivideResult>.5</DivideResult> </DivideResponse> </SOAP-ENV:Body>

To specify a different response message name, set the SoapMessageName keyword within the Web method definition.

Note that you cannot change the name of the SOAP message that invokes a given Web method; this name of this messageis the name of the method itself. You can, however, override the SOAPAction header of the HTTP request; see the latersection “Overriding the Default SOAPAction Header.”

12.5 Overriding the Default SOAPAction HeaderWhen you invoke a Web method via HTTP, the SOAP messages are required to have a SOAPAction HTTP header.

The WSDL for a Web service indicates the expected SOAP action for each method (operation). This SOAP action correspondsto a SOAPAction HTTP header, which can be used to indicate the intent of the SOAP HTTP request. The value is a URIidentifying the intent; it is generally used to route the incoming SOAP message. For example, a firewall could use thisheader to appropriately filter SOAP request messages in HTTP.

For a Web method created in Caché, the SOAPAction HTTP header has the following form by default:

SOAPAction: NAMESPACE/Package.Class.Method

where NAMESPACE is the value of the NAMESPACE parameter for the Web service, and Package.Class.Method is thename of the method that you are using as a Web method. For example:

SOAPAction: http://www.myapp.org/GSOP.WebService.GetPerson

To override this, specify a value for the SoapAction method keyword, within the definition of the Web method. This mustbe an empty string or unique for each method within the Web service.

Using SOAP and Web Services with Caché                                                                                                                         99

Including Documentation for the Types

Page 108: Using SOAP and Web Services with Cach©

12.6 Specifying Whether Elements Are QualifiedThe ELEMENTQUALIFIED parameter (of your Web service) controls the value of the elementFormDefault attribute inthe schema of the WSDL. Specifically:

• If ELEMENTQUALIFIED is 1, then elementFormDefault is "qualified".

• If ELEMENTQUALIFIED is 0, then elementFormDefault is "unqualified".

The default for this parameter depends on the value of the SoapBodyUse keyword as follows:

Table 12–1: Effect of SoapBodyUse Keyword on ELEMENTQUALIFIED Parameter

Default value for ELEMENTQUALIFIED

1 (elementFormDefault="qualified")If SoapBodyUse is literal

0 (elementFormDefault="unqualified")If SoapBodyUse is encoded

For information on the differences between qualified and unqualified elements, as well as examples, see the book UsingXML with Caché.

12.7 Controlling the Form of Message PartsYour Web service has another parameter (XMLELEMENT) that controls the precise form of the message parts of the SOAPmessages. Specifically:

• If XMLELEMENT is 1, then the part element has attributes called name and element. In this case, the WSDL containsa sample <message> element as follows:

<message name="GetPersonSoapOut"> <part name="GetPersonResult" element="s0:Person" /></message>

• If XMLELEMENT is 0, then the part element has attributes called name and type. In this case, the WSDL contains asample <message> element as follows:

<message name="GetPersonSoapOut"> <part name="GetPersonResult" type="s0:Person" /></message>

The default for this parameter depends on the value of the SoapBodyUse keyword, as follows:

Table 12–2: Effect of SoapBodyUse Keyword on XMLELEMENT Parameter

Default value for XMLELEMENT

1 (message parts are element attributes)If SoapBodyUse is literal

0 (message parts are type attributes)If SoapBodyUse is encoded

100                                                                                                                       Using SOAP and Web Services with Caché

Fine-tuning a Caché Web Service

Page 109: Using SOAP and Web Services with Cach©

12.8 Controlling the Form of Null ArgumentsNormally, if an argument is omitted, the SOAP message does not include the corresponding element. To change this, setthe XMLIGNORENULL parameter to 1; in this case, the SOAP message includes an empty element.

12.9 Controlling Use of the xsi:type AttributeBy default, Caché SOAP messages include the xsi:type attribute only for the top-level types. For example:

<?xml version="1.0" encoding="UTF-8" ?>...<types:GetPersonResponse><GetPersonResult href="#id1" /></types:GetPersonResponse><types:Person id="id1" xsi:type="types:Person"><Name>Yeats,Clint C.</Name><DOB>1944-12-04</DOB></types:Person> ...

In these examples, line breaks have been added for readability. To use this attribute for all types in the SOAP messages,set the OUTPUTTYPEATTRIBUTE parameter or the OutputTypeAttribute property to 1. The same output would look likethis:

<?xml version="1.0" encoding="UTF-8" ?>...<types:GetPersonResponse><GetPersonResult href="#id1" /></types:GetPersonResponse><types:Person id="id1" xsi:type="types:Person"><Name xsi:type="s:string">Yeats,Clint C.</Name><DOB xsi:type="s:date">1944-12-04</DOB></types:Person> ...

12.10 Specifying the SOAP Envelope PrefixBy default, a Caché Web service uses the prefix SOAP-ENV in the envelope of the SOAP messages it sends. You canspecify a different prefix. To do so, set the SOAPPREFIX parameter of the Web service. For example, if you set thisparameter equal to MYENV, the Web service includes this prefix in its messages, as follows:

<?xml version="1.0" encoding="UTF-8" ?><MYENV:Envelope xmlns:MYENV='http://schemas.xmlsoap.org/soap/envelope/' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:s='http://www.w3.org/2001/XMLSchema'> <MYENV:Body> <DivideResponse xmlns="http://www.myapp.org"> <DivideResult>.5</DivideResult> </DivideResponse> </MYENV:Body></MYENV:Envelope>

The SOAPPREFIX parameter also affects the prefix used in any SOAP faults generated by the Web service.

Using SOAP and Web Services with Caché                                                                                                                       101

Controlling the Form of Null Arguments

Page 110: Using SOAP and Web Services with Cach©

12.11 Sending Responses Compressed by gzipA Caché Web service can compress its response messages with gzip, a free compression program that is widely availableon the internet. To cause a Web service to do so, set the GZIPOUTPUT parameter equal to 1. This change has no effect onthe WSDL of the Web service.

If you do so, be sure that the Web client can automatically decompress the message with gunzip, the correspondingdecompression program.

If the Web client is a Caché Web client, note that the CSP Gateway automatically decompresses inbound messages beforesending them to the Web client.

12.12 Defining a One-way Web MethodNormally, when you execute a Web method, a SOAP message is returned, even if the method itself has no return type andreturns nothing when executed in Caché. This SOAP response message has the following general form:

<?xml version="1.0" encoding="UTF-8" ?><SOAP-ENV:Envelope xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:s='http://www.w3.org/2001/XMLSchema'> <SOAP-ENV:Body> <MethodNameResponse xmlns="http://www.myapp.org"></MethodNameResponse> </SOAP-ENV:Body></SOAP-ENV:Envelope>

In rare cases, you might need to define a Web method as being “one-way.” Such a method must return no value, and noSOAP response is expected to the request message. To define a one-way Web method, define the return type of the methodas %SOAP.OneWay. The WSDL does not define output defined for this Web method, and the Web service does not returna SOAP message.

Note: One-way methods should normally not be used. A request-response pair is much more common, supported, andexpected — even for a method that has no return type.

12.13 Adding a Byte-order Mark to the SOAP MessagesBy default, a message sent by a Caché Web service does not start with a BOM (byte-order mark).

The BOM is generally not needed because the message is encoded as UTF-8, which does not have byte order issues.However, in some cases, it is necessary or desirable to include a BOM in a SOAP message; this BOM merely indicatesthat the message is UTF-8.

To add a BOM to the messages sent by a Caché Web service, set the RequestMessageStart property of the service. Thisproperty must equal a comma-separated list of the parts to include at the start of a message. These parts are as follows:

• DCL is the XML declaration:

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

• BOM is the UTF-8 BOM.

The default is "DCL".

102                                                                                                                       Using SOAP and Web Services with Caché

Fine-tuning a Caché Web Service

Page 111: Using SOAP and Web Services with Cach©

In practice, RequestMessageStart can equal any of the following values:

• "DCL"

• "BOM"

• "BOM,DCL"

12.14 Customizing Callbacks of the Web ServiceYou can customize the behavior of a Caché Web service by overriding its OnPreWebMethod() and OnPostWebMethod()methods:

OnPreWebMethod()

Called just before a Web method is executed; does nothing by default. This method takes no arguments and cannotreturn a value. This method therefore cannot change the execution of the Web service except by returning a SOAPfault in the same way that a Web method would do.

This method can use %request, %session, and the Web service properties. Note that the MsgClass property of theWeb service is the message descriptor class that contains the Web method arguments.

OnPostWebMethod()

Called just after a Web method is executed; does nothing by default. This method takes no arguments and cannotreturn a value. This method therefore cannot change the execution or return value of the Web method. You customizethis method primarily to clean up required structures created by OnPreWebMethod().

12.15 Specifying Custom Transport for a Web ServiceBy default, a Caché Web service responds to transport in a specific way, described here. You can customize this behavior.

12.15.1 Background

When a Caché Web service receives a SOAP message, it executes its OnSOAPRequest() class method. By default, thismethod does the following:

1. Initializes the Web service instance by calling its Initialize() method. This method parses the inbound SOAP message,returns several pieces of information by reference, and processes the security header. See the documentation for the%SOAP.WebService class.

2. Sets properties of the Web service instance, such as SoapFault and others.

3. Initializes the response stream.

4. Invokes the Process() method of the Web service, passing to it the SOAP action and the method to invoke.

5. Resets the Web service instance by calling its Reset() method.

6. Copies the result into the response stream.

Using SOAP and Web Services with Caché                                                                                                                       103

Customizing Callbacks of the Web Service

Page 112: Using SOAP and Web Services with Cach©

12.15.2 Defining Custom Transport for a Web Service

To implement a Web service using your own transport, get the SOAP message as a stream using your transport, instantiatethe Web service class and call its OnSOAPRequest() class method.

The OnSOAPRequest() method must transport the request to the Web service and obtain the response. To indicate anerror, it must return a SOAP fault in the response stream. The signature of this method must be as follows:

Method OnSOAPRequest(action,requestStream, responseStream)

Here:

1. action is a %String that specifies the SOAP action. The piece of the action string after the last "." is used as the methodname for using the correct descriptor class. If action is null, then the element name from the first element (the wrappingelement) in the SOAP body is used as the method name.

2. requestStream is a stream that contains the SOAP request message encoded according to the encoding attribute of theXML directive.

3. responseStream is a character stream produced as the SOAP response that contains the response SOAP messageencoded in UTF-8. You can create this argument before calling OnSOAPRequest() and passed it in with the methodcall. Or this argument can be a variable passed by reference. In this case, OnSOAPRequest() must set it equal to aninstance of %FileCharacterStream that contains the response.

104                                                                                                                       Using SOAP and Web Services with Caché

Fine-tuning a Caché Web Service

Page 113: Using SOAP and Web Services with Cach©

13Fine-tuning a Caché Web Client

This chapter discusses various ways to fine-tune a Caché Web client. It discusses the following:

• How to control the timeout period for a Caché Web client

• How to enable your Caché Web client to communicate via a proxy server

• How to set HTTP headers

• How to specify the HTTP version to use

• How to control the use of the xsi:type attribute in the SOAP messages

• How to control the prefix used for the SOAP message envelope

• How to send responses compressed by gzip

• How to define one-way Web methods

• How to add a UTF-8 BOM to the start of each message sent by the Web client

• How to create custom SOAP messages

• How to specify custom HTTP requests to carry SOAP messages from a Caché Web client

• How to use transport other than HTTP to carry the SOAP message from a Caché Web client

• How to specify flags for the SAX parser to use when a Caché Web client invokes a Web service

• How to use the WS-Security login feature

• How to use basic HTTP authentication, as an alternative to WS-Security

Also see the section “Basic Settings of a Caché Web Client” in the chapter “Creating Web Clients.” This section discussesparameters that control the namespace, the type namespace, and other basics of the Web client.

13.1 Controlling the Timeout PeriodYou can control how long a Caché Web client waits for a response. To do so, set the Timeout property of the Web client.This specifies how long, in seconds, the Web client waits for a response.

If you are using a proxy server, this setting controls how long the client waits for a response from the proxy.

Using SOAP and Web Services with Caché                                                                                                                       105

Page 114: Using SOAP and Web Services with Cach©

13.2 Using a Proxy ServerYour Caché Web client can communicate with a Web service via a proxy server. In order to set this up, specify propertiesof your Web client instance to indicate the proxy server to use. These properties are as follows:

HttpProxyServer

Specifies the host name of the proxy server to use. If this property is not null, the HTTP request is directed to thismachine.

To specify the default proxy server for this Caché namespace or for this Caché installation, assign a value to oneof the following global nodes:

• ^%SYS("HttpRequest","ProxyServer")

• ^SYS("HttpRequest","ProxyServer")

The ^%SYS global affects the Caché installation, and the ^SYS global affects the current Caché namespace.

HttpProxyPort

Specifies the port to connect to, on the proxy server.

To specify the default proxy port for this namespace or for this Caché installation, assign a value to one of thefollowing global nodes:

• ^%SYS("HttpRequest","ProxyPort")

• ^SYS("HttpRequest","ProxyPort")

The ^%SYS global affects the Caché installation, and the ^SYS global affects the current Caché namespace.

HttpProxyHTTPS

Specify this as true if you are using a proxy server and if that proxy server supports HTTPS.

Note that if you are using HTTPS, you must also set the SSLConfiguration property of the client equal to the nameof the TLS/SSL configuration; for more details on security, see the section “Configuring the Client to Use SSL”earlier in this book.

HttpProxyAuthorization

Specify this as true if the Web client should authenticate itself with the proxy server. If this property is true, theWeb request includes a Proxy-Authorization header field.

HttpProxyTunnel

Specify this as true if the Web client should establish a tunnel through the proxy to the target HTTP server. If true,the request uses the HTTP CONNECT command to establish a tunnel. The address of the proxy server is takenfrom the HttpProxyServer and HttpProxyPort properties. If the endpoint URL has the https: protocol, then once thetunnel is established, Caché negotiates the SSL connection. In this case, the HttpProxyHTTPS property is ignoredbecause the tunnel establishes a direct connection with the target system.

106                                                                                                                       Using SOAP and Web Services with Caché

Fine-tuning a Caché Web Client

Page 115: Using SOAP and Web Services with Cach©

13.3 Setting HTTP HeadersIf you need further control over the HTTP headers sent by a Web client, you can use the following methods of%SOAP.WebClient:

SetHttpHeader()

Adds a header to the HTTP request. Note that the Content-Type, Content-Encoding, and Content-Lengthheaders are part of the entity body rather than the HTTP main headers. You cannot set the Content-Lengthheader, which is read-only. Nor can you set the Connection header, because this class does not support persistentconnections.

ResetHttpHeaders()

Clear all HTTP headers.

Also see the section “Using HTTP User Authentication,” earlier in this chapter.

13.4 Specifying the HTTP Version to UseBy default, a Caché Web client uses HTTP/1.1. You can instead use HTTP/1.0. To do so, set the HttpVersion property ofthe client to "1.0".

13.5 Controlling Use of the xsi:type AttributeBy default, Caché SOAP messages include the xsi:type attribute only for the top-level types. For example:

<?xml version="1.0" encoding="UTF-8" ?>...<types:GetPersonResponse><GetPersonResult href="#id1" /></types:GetPersonResponse><types:Person id="id1" xsi:type="types:Person"><Name>Yeats,Clint C.</Name><DOB>1944-12-04</DOB></types:Person> ...

In these examples, line breaks have been added for readability. To use this attribute for all types in the SOAP messages,set the OUTPUTTYPEATTRIBUTE parameter or the OutputTypeAttribute property to 1. The same output would look likethis:

<?xml version="1.0" encoding="UTF-8" ?>...<types:GetPersonResponse><GetPersonResult href="#id1" /></types:GetPersonResponse><types:Person id="id1" xsi:type="types:Person"><Name xsi:type="s:string">Yeats,Clint C.</Name><DOB xsi:type="s:date">1944-12-04</DOB></types:Person> ...

Using SOAP and Web Services with Caché                                                                                                                       107

Setting HTTP Headers

Page 116: Using SOAP and Web Services with Cach©

13.6 Specifying the Envelope PrefixBy default, a Caché Web service uses the prefix SOAP-ENV in the envelope of the SOAP messages it sends. You canspecify a different prefix. To do so, set the SOAPPREFIX parameter of the Web service. For example, if you set thisparameter equal to MYENV, the Web service includes this prefix in its messages instead of SOAP-ENV.

13.7 Sending Responses Compressed by gzipA Caché Web client can compress its response messages with gzip, a free compression program that is widely availableon the internet. To cause a Web client to do so, set its GZIPOUTPUT parameter equal to 1 or set its GzipOutput propertyequal to 1.

If you do so, be sure that the Web service can automatically decompress the message with gunzip, the correspondingdecompression program.

If the Web service is a Caché Web service, note that the CSP Gateway automatically decompresses inbound messagesbefore sending them to the Web service.

13.8 Defining a One-way Web MethodNormally, when a Web client calls a Web service, a SOAP message is returned, even if the method itself has no return typeand returns nothing when executed in Caché.

In rare cases, you might need to define a Web method as being “one-way.” Such a method must return no value, and noSOAP response is expected to the message.

Note: One-way methods should normally not be used. A request-response pair is much more common, supported, andexpected — even for a method that has no return type.

To define a one-way Web method, define the return type of the method as %SOAP.OneWay. The WSDL does not defineoutput defined for this Web method, and the Web service does not return a SOAP message.

13.9 Adding a Byte-order Mark to the SOAP MessagesBy default, a message sent by a Caché Web client does not start with a BOM (byte-order mark).

The BOM is generally not needed because the message is encoded as UTF-8, which does not have byte order issues.However, in some cases, it is necessary or desirable to include a BOM in a SOAP message; this BOM merely indicatesthat the message is UTF-8.

To add a BOM to the messages sent by a Caché Web client, set the RequestMessageStart property of the client. Thisproperty must equal a comma-separated list of the parts to include at the start of a message. These parts are as follows:

• DCL is the XML declaration:

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

108                                                                                                                       Using SOAP and Web Services with Caché

Fine-tuning a Caché Web Client

Page 117: Using SOAP and Web Services with Cach©

• BOM is the UTF-8 BOM.

The default is "DCL".

In practice, RequestMessageStart can equal any of the following values:

• "DCL"

• "BOM"

• "BOM,DCL"

13.10 Creating Custom SOAP MessagesIn special cases, you may want a Web client to send a custom SOAP message. The essential requirements are as follows:

1. Create a subclass of %SOAP.WebRequest and set its LOCATION parameter or Location property.

2. In this subclass, create a method to send a SOAP message. This method must create an instance of%Library.CharacterStream and place into it the SOAP message you want to send. It is your responsibility to ensure thatthe message is correctly formed.

3. The method must next invoke the SendSOAPBody() method:

method SendSOAPBody(Action As %String, OneWay As %Boolean = 0, Request As %CharacterStream, ByRef Response) as %Status

• Action is a string that gives the name of SOAP action to perform.

• OneWay is a true/false flag that controls whether the message is one way.

• Request is an instance of %Library.CharacterStream that contains the body of the SOAP request in the characterset of the current locale.

• Response is the response, returned by reference either as a character stream or an instance of %XML.Node.

If Response is null when you invoke SendSOAPBody(), then the method sets Response equal to an instance of%Library.CharacterStream. This stream contains the body of the SOAP response in the character set of the currentlocale.

If Response is an instance of %Library.CharacterStream when you invoke SendSOAPBody(), then the methodupdates Response to contain the body of the SOAP response in the character set of the current locale.

If Response is an instance of %XML.Node when you invoke SendSOAPBody(), then the method updates Responseto point to the body DOM.

%SOAP.WebRequest is a subclass of %SOAP.WebClient, so you may want to set other parameters and properties. You canalso add SOAP headers as described earlier in this book. See the class documentation for %SOAP.WebRequest for furthernotes.

Using SOAP and Web Services with Caché                                                                                                                       109

Creating Custom SOAP Messages

Page 118: Using SOAP and Web Services with Cach©

13.11 Specifying Custom HTTP RequestsBy default, if you use a Caché Web client, the Web client uses HTTP to transport the SOAP message to the Web serviceand to receive the response. The Web client automatically creates and sends an HTTP request, but you can create a customHTTP request. To do, you use the following general procedure:

1. Create an instance of %Net.HttpRequest and set properties as needed. For information on this class, see the chapter“Sending HTTP Requests and Reading HTTP Responses” in the book Using Caché Internet Utilities or see the classdocumentation for %Net.HttpRequest.

2. Set the HttpRequest property of your Web client equal to this instance.

This is useful in particular if you want to support multiple calls to a SOAP service within the same session. By default, theCaché Web client does not support multiple calls to a SOAP service using the same session. To work around this, create anew instance of %Net.HttpRequest and use it as the HttpRequest property of your Web client. This change forces the sameHTTP request to be reused for all calls, which returns all cookies in a response to the next request.

13.12 Specifying Custom Transport from the Web ClientBy default, if you use a Caché Web client, the Web client uses HTTP to transport the SOAP message to the Web serviceand to receive the response. You can define and use your own transport class.

13.12.1 Background

To communicate with the Web service that it uses, a Caché Web client requires a transport class. In general, the transportclass contains parameters, properties, and methods related to communication. The overall communication works as follows:

1. When a Web client proxy method is run, the Web client instance checks the value of its Transport property. If thisproperty is null, the Web client uses itself (via ##this) as the transport class instance. You can instead set Transport

property equal to an instance of some other suitable class, if you have defined such a class.

2. The Web client instance executes the DoSOAPRequest() of the transport class, passing the following arguments:

a. The oref of the Web client class.

b. A string that specifies the SOAP action.

c. A stream containing the request encoded in UTF-8.

d. (By reference) A stream containing the response.

3. The Web client instance checks the status of the result and acts accordingly.

For HTTP transport, the DoSOAPRequest() method includes the following general logic:

1. Create a request object (an instance of %Net.HttpRequest) and set its properties. Here, the method uses values of theproperties of the Web client instance, in particular HttpRequestHeaderCharset and other HTTP-related properties.

2. Go through the headers in the SOAP request and initialize the headers in the request object.

3. Execute the Post() method of the request object, which is a suitable action for HTTP transport.

4. Get the response and return that.

110                                                                                                                       Using SOAP and Web Services with Caché

Fine-tuning a Caché Web Client

Page 119: Using SOAP and Web Services with Cach©

Important: Do not directly use the DoSOAPRequest() method of %SOAP.WebClient. No guarantee is made about itsbehavior or future operation. The preceding summary is provided only as a general tip.

13.12.2 Defining Custom Transport for a Caché Web Client

To enable a Caché Web client to use custom transport, define a custom transport class. Then after you create an instanceof the Web client, set its Transport property equal to an instance of the transport class.

The requirements for the transport class are as follows:

• The class must be instantiable (that is, non-abstract).

• The class must implement the DoSOAPRequest() method as described below.

The DoSOAPRequest() method should transport the request to the Web service and obtain the response. The signature ofthis method must be as follows:

Method DoSOAPRequest(webClient,action,requestStream, responseStream) As %Status

• webClient is the oref of the Web client class.

• action is a %String that specifies the SOAP action.

• requestStream is a stream containing the request encoded in UTF-8.

• responseStream is a %FileBinaryStream argument that DoSOAPRequest() uses to write the response. This stream mustcontain data in the character set specified by the encoding attribute of the ?xml directive. UTF-8 is recommended.

13.13 Specifying Flags for the SAX ParserWhen a Caché Web client invokes a Web service, it internally uses the SAX parser, a third-party product that is shippedwith Caché. You can set the SAXFlags property of the Web client in order to set the flags for the parser to use.

For information on the parser flags themselves, see the book Using XML with Caché.

13.14 Using the WS-Security Login FeatureIf your Caché Web client is using a Web service that requires authentication, and if do not want to use the newer WS-Security features, you can use the older and simpler WS-Security login feature.

To use the WS-Security login feature:

1. Ensure that you are using SSL between the Web client and the Web service. The WS-Security header is sent in cleartext, so this technique is not secure unless SSL is used. See the section “Configuring the Client to Use SSL,” earlierin this book.

2. Invoke the WSSecurityLogin() method of the Web client. This method accepts the username and password, generatesa WS-Security username token with clear text password, and adds a WS-Security header to the Web request.

3. Invoke the Web method.

This technique adds the security token only to the next SOAP message.

Using SOAP and Web Services with Caché                                                                                                                       111

Specifying Flags for the SAX Parser

Page 120: Using SOAP and Web Services with Cach©

For information on the newer WS-Security features, see the chapter “Using WS-Security Features.”

13.15 Using HTTP User AuthenticationInstead of using WS-Security as described earlier in this book, you can use basic HTTP authentication. To do so:

• Set the HttpUsername and HttpPassword properties of the Web client before invoking the Web method.

• Ensure that you are using SSL between the Web client and the Web service. The username and password are sent inclear text, so this technique is not secure unless SSL is used. See the section “Configuring the Client to Use SSL,”earlier in this book.

This method is less secure than WS-Security but is required by some Web services.

112                                                                                                                       Using SOAP and Web Services with Caché

Fine-tuning a Caché Web Client

Page 121: Using SOAP and Web Services with Cach©

ASummary of Web Service URLs

The following table summarizes the URLs related to your Caché Web service.

Here:

• base is the base URL for your Web server (including port if necessary).

• /csp/app is the name of the CSP application in which the Web service resides. (Typically, /csp/app is /csp/namespacewhere namespace is the Caché namespace that contains the CSP application.)

• web_serv is the class name of the Web service.

Table I–1: URLs for Your Web Service

URL and ExampleItem

base/csp/app/web_serv.clsFor example:

http://localhost:57772/csp/samples/ MyApp.StockService.cls

end point forthe Webservice

base/csp/app/web_serv.cls?WSDLFor example:

http://localhost:57772/csp/samples/ MyApp.StockService.cls?WSDL

WSDL

Using SOAP and Web Services with Caché                                                                                                                       113

Page 122: Using SOAP and Web Services with Cach©
Page 123: Using SOAP and Web Services with Cach©

BBrief Introduction to SOAP and WebServices

This appendix provides a quick overview of Web services, SOAP, Web clients, and related concepts, for the benefit ofusers working with the Caché %SOAP classes or the Ensemble SOAP adapters (classes in the package EnsLib.SOAP).It is intended only as a summary, not as a tutorial. It includes information on the following:

• Web services and Web methods

• SOAP messages used to invoke and respond to Web services

• Sending SOAP messages via HTTP

• WSDL documents that describe Web services and their methods

• Web clients that consume Web services

• How to trace messages between a Web client and a Web service

B.1 Web ServicesA Web service is a set of Web methods that are hosted on an application server. Web methods are methods that can beinvoked remotely over a network or the internet. To invoke a Web method, you create a SOAP message (described ahead)and send it to the Web service via HTTP or other transport mechanism. Most commonly, a Web service sends a responsemessage back for every method call; the response message contains returned information or fault information in case of anerror.

The Web service can be written in any suitable language. The internal details are irrelevant to callers, who view only theSOAP interface of the Web service.

A Web service is required to have a service name and an endpoint (the location or URL to which you send SOAP messagesin order to invoke the Web methods).

B.2 SOAP MessagesA SOAP message is an XML document that follows a specific standard. The SOAP standard provides a way to package acall to a Web method, and to package the response. A SOAP message consists of the following components:

Using SOAP and Web Services with Caché                                                                                                                       115

Page 124: Using SOAP and Web Services with Cach©

• The SOAP envelope, which includes the following:

1. An optional <Header> element that contains one or more headers.

2. A required <Body> element.

• The purpose of the SOAP header, if included, is to give information about how the message is to be processed. Forexample, you use the mustUnderstand attribute to flag any message parts that you require the recipient to understand.

The SOAP header is not the same as any HTTP headers that you might add to the SOAP message; see “Using SOAPvia HTTP,” next.

• The SOAP body contains the actual data of the method call (or of the response from the Web service). If an error occurs,the body contains a SOAP fault.

A sample SOAP message follows; this one does not have a header. This message calls a Web method called Divide whichdivides one number by another and returns the answer:

<?xml version="1.0" encoding="UTF-8" ?><SOAP-ENV:Envelope xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:s='http://www.w3.org/2001/XMLSchema'> <SOAP-ENV:Body> <Divide xmlns="http://www.myapp.org"> <arg1 xsi:type="s:decimal">100</arg1> <arg2 xsi:type="s:decimal">25</arg2> </Divide> </SOAP-ENV:Body></SOAP-ENV:Envelope>

In this case, the response message is as follows:

<?xml version="1.0" encoding="UTF-8" ?><SOAP-ENV:Envelope xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:s='http://www.w3.org/2001/XMLSchema'> <SOAP-ENV:Body> <DivideResponse xmlns="http://www.mynamespace.org"> <DivideResult>4</DivideResult> </DivideResponse> </SOAP-ENV:Body></SOAP-ENV:Envelope>

B.3 Using SOAP via HTTPWeb services can be invoked in multiple ways but are typically invoked via HTTP.

If you invoke a Web service via HTTP, you must include the SOAPAction HTTP request header field. This is a URI thatindicates the intent of the SOAP HTTP request. SOAP places no restrictions on the format or specificity of the URI or thatit is resolvable.

B.4 WSDL DocumentsA Web service has a WSDL document, a machine-readable document that describes the methods of that Web service andhow to invoke them. A WSDL document is written in XML, following the standard for the Web Services DescriptionLanguage. In general, a WSDL has a root <definitions> element that contains additional elements that define the following:

116                                                                                                                       Using SOAP and Web Services with Caché

Brief Introduction to SOAP and Web Services

Page 125: Using SOAP and Web Services with Cach©

• Definition of any XML types needed for inputs or outputs of the Web service, defined in terms of base XML types.The <types> element includes one or more <schema> elements, which define the types themselves.

• Definition of messages used by the Web service. Each Web method requires one or two messages: a request messageto call the Web method, and a response message to use in reply. Each message is defined in terms of XML types.

• Definition of port types used by the Web service. Each port defines one or more operations. An operation correspondsto a Web method and uses the corresponding message or messages.

• The bindings of the Web service, which describes what protocol is being used, how the data is being transported, andwhere the Web service is located.

• Formal definition of the Web service itself, in terms of the preceding components. Typically this includes a URL forinvoking the Web service.

The service itself, any schemas, and the messages are all associated with XML namespaces; these can all be in a singlenamespace or can be in different namespaces. Note that Caché support for SOAP does not support all possible variations.See the section “Standards Supported by Caché,” earlier in this book.

B.5 Web ClientA Web client is software that accesses a Web service. A Web client provides a set of proxy methods, each of which corre-sponds to a method of the Web service. A proxy method uses the same signature as the Web service method to which itcorresponds, and it invokes the Web service method when asked to do so.

Web clients can be written in many different languages. The basic requirement is that they must be able to send and receiveSOAP messages, and they must know the location (URI) of their corresponding Web service.

B.6 Tracing Web Service CallsTracing tools such as Wireshark, ProxyTrace, tcpTrace, and so on give you a way to see the actual method calls, as wellas the responses.

A tracing session listens on a certain port, shows you the messages it receives there, forwards those messages to a destinationport, shows the responses, and forwards the responses to the listening port.

For example, suppose you have a Cache Web service at http://localhost:57772/csp/gsop/GSOP.Divide.CLS

And suppose you have a Cache Web client that you created to talk to that service. The Web client has a LOCATIONparameter equal to "http://localhost:57772/csp/gsop/GSOP.Divide.CLS"

To trace messages between the client and service, you need to do two things:

• In the tracing tool, start a tracing session that listens on port 8080 (for example) and that uses the destination port57772.

• In the Web client, edit LOCATION to use port 8080 instead of 57772. Then recompile.

Now when you use the Web client, the tracing tool intercepts and displays messages between the client and the Web service,as shown in the following example:

Using SOAP and Web Services with Caché                                                                                                                       117

Web Client

Page 126: Using SOAP and Web Services with Cach©

The top area shows the request sent by the client. The bottom area shows the response.

118                                                                                                                       Using SOAP and Web Services with Caché

Brief Introduction to SOAP and Web Services


Recommended