DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2...

75
DB2® Web services for DB2 Practitioners Author: Tim J Brown HS&T IBM Software Group Services Hursley UK [email protected] Last updated: 05/2004

Transcript of DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2...

Page 1: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2® Web services for DB2 Practitioners

Author: Tim J Brown

HS&T IBM Software Group Services Hursley UK [email protected]

Last updated: 05/2004

Page 2: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

2

1. Overview.................................................................................................... 3 2. Introduction ................................................................................................ 4 2.1. An Introduction to Web services ............................................................ 4 2.2. Web Services Fundamentals................................................................. 6 3. Walk Through Demo.................................................................................. 9 3.1. DB2 as a Web service provider ............................................................. 9 3.1.1. Installing WORF on IBM WebSphere Application Server ................ 10 3.1.2. Basic SQL as a Web service............................................................ 11 3.1.2.1. Creating the DADX document ...................................................... 11 3.1.2.2. Creating the web application ........................................................ 12 3.1.3. Stored Procedure as a Web service ................................................ 36 3.1.4. XML Web services ........................................................................... 52 3.2. DB2 as a Web service consumer ........................................................ 55 3.2.1. Enabling DB2 Web service consumer UDFs ................................... 55 3.2.2. Web services consumer UDFs......................................................... 56 3.2.3. From WSDL to Web service consumer function.............................. 57 3.2.4. Testing the Web service consumer functions .................................. 61 3.2.5. Creating a wrapper UDF to a Web services consumer function...... 61 4. Tooling ..................................................................................................... 65 5. DB2 Web services, why bother? ............................................................. 66 6. Security.................................................................................................... 69 7. Troubleshooting....................................................................................... 70 8. Appendix.................................................................................................. 72 8.1. How to apply a fix pack to WAS........................................................... 72 8.2. Installing Microsoft’s free .NET compiler ............................................. 73 9. References .............................................................................................. 74 10. Relevant Resources............................................................................. 75

Page 3: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

3

1. Overview The purpose of this document is to look at the fundamentals of Web services, how DB2 Universal Database™ implements the ability to provide Web services and how to consume them. This document attempts to give the reader a good grounding in how to build an environment for providing and consuming Web services using the functionality provided in DB2. It will take the reader through the process of creating a basic Web application using nothing but a text editor. The reason for this is to give the reader a good understanding of what is needed in order to build, provide and consume Web services from the ground up.

It will provide the information necessary to create Web services which use basic SQL and stored procedures; it will explain how the DB2 XML extender can be used in Web services; it will also discuss some scenarios in which Web services may be appropriate and give further information on Tooling and Security.

This document is aimed at those people who already have a working understanding of DB2 Universal Database, for example DB2 consultants, DB2 DBAs, DB2 Application Developers, and so on… or anyone else who has an interest in what DB2 has to offer in this space.

As my background is in DB2 for the distributed platforms, I have approached this document bringing that experience with me, and I may have made assumptions about the reader’s knowledge of DB2 and the tools provided with DB2. It is worth noting that although this document used Windows as the main operating system, most of this functionality is available across all of the supported DB2 platforms.

I hope you find this document useful and please remember all questions and comments are welcome.

Page 4: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

4

2. Introduction

2.1. An introduction to Web services The Internet infrastructure is ready to support a new generation of e-business applications, called Web services. Web services represent the next level of function and efficiency in e-business. Specifically, Web services are enhanced e-business applications that are easier to advertise and easier to discover -- by other businesses -- because they are described in a more uniform way on the Internet. These new enhancements allow e-business applications to be connected more easily both inside and outside the enterprise.

The Web services infrastructure is based on the eXtensible Markup Language (XML). Messages and data flow between a service requester and a service provider using XML.

Web services are generally considered as “The Next Generation of Application Integration”. The Web’s audience is expanding to include programs as well as humans. It’s a bold goal: Create an architecture that makes it possible for software to do what humans do with the Web -- access documents and run applications in a general way without requiring application-specific knowledge and client software. An architecture that supports Web services provides the groundwork to realise that goal.

Before describing the architecture, let’s first understand what is meant by “Web service”. A Web service is a set of application functions that perform some useful service on behalf of a requester such as informational or transactional functions. A Web service can be described and published to the network for use by other programs across the network. Examples of publicly available Web services today include a stock quote service, a service to retrieve news from Web news sources, a service to return maps of historic weather events by post code, and currency conversion services. Because Web services are modular, related Web services can be aggregated into a larger Web service. For example, it is possible for an application to be composed of separate Web services that do such things as obtaining stock quotes, subscribing to news services, converting currency and managing calendars.

One particularly nice aspect of Web services is that the level of abstraction they provide makes it relatively simple to wrap an existing enterprise application and turn it into a Web service. Web services are based on the XML standard data format and data exchange mechanisms, which provide both flexibility and platform independence. Requesters typically do not know or care about the underlying implementation of Web services, making it easy to integrate heterogeneous business processes. Web services provide you with a way to make your key business processes accessible to your customers, partners and suppliers. For example, an airline could provide its airline reservation systems as a Web service to make it easier for its large corporate customers to integrate the service into their travel planning applications. A supplier can make its inventory levels and pricing accessible to its key buyers.

Page 5: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

5

In one possible example, a buyer matches up incoming purchase orders with transportation services. 1) The buyer accesses the local database to select a list of purchase orders. 2) While viewing the detail for a particular purchase order, the buyer selects a transportation service provider from an approved list, a list that is kept in a private registry. 3) For each provider, the buyer receives quotes dynamically using Web services capabilities. Each request is bound and sent to the location specified in the registry and processed by the supplier’s Web service. The supplier’s Web service takes input about the request, accesses its database and returns the quote to the requester. 4) The buyer then chooses one service provider based on the prices quoted and the selection is then added back to the purchase order page to reflect the selection of a shipping service provider.

Figure 2.1

Note: Please refer back to this figure through out this document to help put things in perspective.

Web services leverage XML for data representation and exchange and do not require complex language-dependent mappings and compile time bindings. Web services offer both ease of development and ease of modification. Furthermore, Web services do not mandate tight synchronous relationships between requesters and service providers. This further simplifies the implementation of Web services in an Internet environment where it is impossible to tightly control network behaviour. The reliance

Page 6: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

6

on XML for data exchange, and the abundance of existing and emerging tools for Web service technology, make it relatively easy to get up and running with your first Web service.

2.2. Web services fundamentals The nature of Web services makes them natural components in a service-oriented architecture. In a typical service-oriented architecture, service providers host a network accessible software module (for the purposes of this document, a Web service). A service provider defines a service description for a Web service and publishes it to a service registry. A service requester uses a find operation to retrieve the service description from the registry and uses the service description to bind with the service provider and invoke or interact with the Web service implementation. Let’s see how this model is realized using Web services. (See Figure 2.2)

Figure 2.2

In simple terms, a Web service is created by wrapping an application in such a way that it can be accessed using standard XML messages which are themselves wrapped in such a way that masks the underlying transport protocol. The service can be publicized by being registered in a standard-format registry. This registry makes it possible for other people or applications to find and use the service. The pieces of the Web services architecture include:

1. A Web service (a general term used to describe software that can be invoked over the Web)

2. Application-specific messages that are sent in standard XML document formats conforming to the corresponding service description.

3. The XML messages are contained in Simple Object Access Protocol (SOAP) envelopes. SOAP is an application invocation protocol developed by IBM®, Microsoft®, and others that define a simple protocol for exchanging information encoded as XML messages.

The beauty of SOAP is that it makes no assumptions on the implementation of the endpoints. This means that a service requester needs only to create an XML request,

Page 7: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

7

send it to a service provider, and understand the XML response that comes back. (See Figure 2.3)

Figure 2.3

A SOAP request consists of the envelope itself, which contains the namespaces used by the rest of the SOAP message, an optional header, and the body, which may be a remote procedure call (RPC) or an XML document. SOAP builds on existing Internet standards such as HTTP and XML, but can be used with any network protocol, programming language, or data encoding model. For example, it is possible to send SOAP messages over IBM WebSphere® MQSeries®, FTP or even as mail messages. The logical interface and the service implementation are described by the Web Services Description Language (WSDL). WSDL is an XML vocabulary used to automate the details involved in communicating between Web services applications. There are three pieces to WSDL: a data type description (XML Schema), an interface description, and binding information. The interface description is typically used at development time and the binding information may be used at either development or execution time to actually invoke a particular service at the specified location. The service description is key to making the Web services architecture loosely coupled and reducing the amount of required shared understanding and custom programming between service providers and service requesters. To enable service requesters to find your Web service, you can publish descriptive information, ownership, business name, and business type and so on, via a registry that adheres to the Uniform Description, Discovery and Integration (UDDI) specification or into some other XML registry. The UDDI information can include a pointer to WSDL interfaces, the binding information, as well as the actual business name (the name that makes the purpose of the Web service understandable to humans). A UDDI registry is searchable by programs, enabling a service requester to bind to a UDDI provider to find out more information about a service before actually using it.

Page 8: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

8

The ability to compose Web services together is provided by Web services Flow Language (WSFL), another specification for which IBM is taking the lead. WSFL can be used to describe a business process (that is, an execution flow from beginning to end), or a description of overall interactions between varying Web services with no specified sequence.

If we look at how all of these specifications work together, a Web service can be defined as a modular application that can be:

Described using WSDL Published using UDDI Found using UDDI Bound using SOAP (or HTTP GET /POST) Invoked using SOAP (or HTTP GET/POST) Composed with other services into new services using WSFL

Page 9: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

9

3. Walk Through Demo

3.1. DB2 as a Web service provider Web services Object Runtime Framework (WORF) that ships with DB2 V8.1 provides an environment to easily create simple Web services that access DB2. WORF uses Apache Simple Object Access Protocol (SOAP) 2.2 or later and the Document Access Definition Extension (DADX). A DADX document specifies how to create a Web service using a set of operations that are defined by SQL statements (including stored procedure calls) and, optionally, XML Extender DAD files. The Web services that are created from a DADX file are called DADX Web services or DB2 Web services. Figure 3.1 represents the architecture of WORF. Figure 3.1

WORF provides the following features: Resource-based deployment and invocation Automatic service redeployment at development time when defining resource

changes HTTP GET and POST bindings in addition to SOAP Automatic WSDL and XSD generation, including support for UDDI Best

Practices Automatic documentation and test page generation

Page 10: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

10

In the following sections I will explain to you how to: Install WORF on IBM WebSphere Application Server (hereafter referred to as

Application Server) Create a simple Web service that exposes the results of SQL statements, and

generate a web application that hosts a Web service Deploy the Web application in WebSphere Test the Web service

Please Note: If at any time you get errors and the results are not as I suggest, please read the instructions again and refer to the troubleshooting section where I have highlighted some of the problems I came across and suggested solutions to those problems.

3.1.1. Installing WORF on IBM WebSphere Application Server In this section I assume that you have installed WebSphere Application Server 5.0.2 and that the Application Server root is C:\WebSphere\AppServer. SOAP V2.2 ships by default with Application Server 4.01 onwards. Ensure that you have soap.jar in C:\WebSphere\AppServer\lib. If you need to apply a fix pack to Application Server, please refer to: ‘How to apply a fix pack to WebSphere Application Server’ in Appendix A for details.

I also assume that you have installed DB2 Version 8.1 Fix pack 2 in C:\IBM\SQLLIB. WORF requires JDBC 2.0, which is the default in DB2 UDB Version 8. For DB2 UDB versions earlier than Version 8, select JDBC 2.0 by running the C:\IBM\SQLLIB\java12\usejdbc2.bat file. I also assume that you have created the SAMPLE database already. If you have not done it yet you can create it using the First Steps wizard that can be launched from the Windows Start -> Programs -> IBM DB2 -> Set-up Tools -> First Steps.

To install WORF on WAS, complete the following steps:

1. Locate dxxworf.zip in your C:\IBM\SQLLIB\samples\java\Websphere directory. If you cannot find it there you can download it from http://www7b.software.ibm.com/dmdd/zones/webservices/worf/

2. Unzip the dxxworf.zip to a directory, such as C:\worf. The directory has the following contents:

• readme.html • lib\worf.jar - WORF library which must be installed on the CLASSPATH of the servlet engine • lib\worf-servlets.jar - Servlets used for DB2 Web services that have to be included in your web applications using WORF • lib\services.war - sample Web application containing Web services that use WORF • schemas\ - XML schemas for the DADX and NST XML files • tools\

3. Copy worf.jar to C:\WebSphere\AppServer\lib 4. Start the WebSphere Administration Server.

Page 11: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

11

3.1.2. Basic SQL as a Web service In this section I’ll show you how to create a simple DB2 Web service based on the SAMPLE database. I will be doing this in such a way as to give you the understanding of the underlying files and their function. There are various tools available which would hide this from you. For example, WebSphere Application Developer (WSAD). In this way I hope to make problem determination easier and increase your understanding of what is happening under the covers. Please see figure 3.1.2 for a graphical representation of what we will achieve in this section. Figure 3.1.2

3.1.2.1. Creating the DADX document A DADX file defines a Web service by specifying a set of operations. Operations are similar to methods that you can invoke. The definition of an operation consists of a list of parameters and an action to be performed. The action to perform is defined using SQL statements or DAD file references. DADX follows XML syntax to define the Web service.

The operations in a DADX Web service can be defined by the following operation types:

SQL Operations <query> - queries the database <update> - performs an update, insert or delete operation <call> - calls stored procedures

XML collection operations (requires DB2 XML Extender) <retrieveXML> - generates XML documents <storeXML> - stores XML documents

Page 12: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

12

Let us look at a sample DADX file. Example 3.1 is a sample DADX file that exposes two operations namely listSales and listEmployees as Web service operations. For simplicity we use only the SQL operations in this DADX example.

Example 3.1

3.1.2.2. Creating the Web application In order to invoke the Web service defined in the DADX document discussed in “Creating the DADX document” above we need to deploy it in Application Server. Since it is just a resource it has to be packaged as part of a Web application and this wrapper Web application has to be deployed on Application Server. In this section we create a Web application that can host our DB2 Web service. Here I’ll show you how to create a Web application manually without using any of the tools.

Starting from a Web application skeleton A skeleton of a simple Web application consists of a WEB-INF folder and a welcome page in HTML. The WEB-INF folder contains a file named web.xml also called the deployment descriptor that contains the details about deployment of various resources of the web application. WEB_INF contains two more folders named classes and lib. Both these folders are in the CLASSPATH of the class loader. Generally we keep all the JAR files in the lib folder and other invokable resources under classes.

Before building our sample Web application let’s create a skeleton Web application by creating the directory structure as shown in Example 3.2. Keep the index.html and web.xml blank for the time being. WORFTest is going to be the base directory for our Web application for the rest of this section.

Create the WORFTest directory. Create WEB-INF directory under \WORFTest. Create the directory classes under WORFTest\WEB-INF. Create the directory lib under WORFTest\WEB-INF. Create index.html as a blank file under \WORFTest. Create web.xml as a blank file under \WORFTest\WEB-INF.

<?xml version="1.0" encoding="UTF-8"?> <DADX xmlns=”http://schemas.ibm.com/db2/dxx/dadx” xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xmlns:xsd=”http://www.w3.org/2001/XMLSchema” >

<operation name="listSales"> <documentation> Lists all the sales in the SALES table of the SAMPLE database </documentation>

<query> <SQL_query>SELECT * FROM sales</SQL_query> </query>

</operation> <operation name="listDepartments"> <documentation> Lists all the departments in the DEPARTMENT table of the SAMPLE database </documentation>

<query> <SQL_query>SELECT * FROM department</SQL_query> </query>

</operation> </DADX>

Page 13: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

13

Example 3.2

Defining the group for Web services We need to create a group for each set of related Web services. When I say related, in this context, I mean Web services that access the same database. As part of the group definition we also create connection configuration for the database the Web services of this group access. Each such group forms a directory in the file system. These groups are created under \WEB-INF\classes\groups directory. The DADX files are stored in the directories defined for these groups.

Let us create a group for our Web service and configure it for the SAMPLE database. Let us call our group the TestGroup.

Create the directory groups under WORFTest\WEB-INF\classes Create the directory TestGroup under WORFTest\WEB-INF\classes\groups Create the file group.properties in TestGroup and add the lines listed in

Example 3.3 (Please edit userID and password and set them as required. The userID should be the same as the user Id which created the SAMPLE database. If not the SQL statements later will require the full schema and table name )

Store the List.dadx file under WORFTest\WEB-INF\classes\groups\TestGroup Example 3.3

For further details about the group.properties file please refer to the “IBM DB2 Information Integrator Developer’s Guide”.

Now we have to inform the Web server about the existence of this group so that during runtime the proper group is looked up for DADX documents. We do this by creating a servlet for each group. This servlet is an instance of the DxxInvoker servlet that is part of worf-servlets.jar. The name of this servlet instance should be the same as the name of the Web service group, which is TestGroup in our case. When a request is issued to serve a DADX document, defined under a particular group, the

# /dadx TestGroup group properties dbDriver=COM.ibm.db2.jdbc.app.DB2Driver dbURL=jdbc:db2:sample userID= database-user-id password= password-for-the-above-user-id autoReload=true reloadIntervalSeconds=5

WORFTest | |-- index.html | |-- WEB-INF |

|-- web.xml | |-- classes | |-- lib

Page 14: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

14

servlet instance associated with this group gets invoked. The DxxInvoker servlet determines where to find DADX files by looking for a directory that matches its servlet name.

Place the worf-servlets.jar in the WORFTest\WEB-INF\lib directory. The worf-servlets.jar is part of dxxworf.zip we unzipped in “Creating the web application”.

Our next step is to create an instance of DxxInvoker servlet named TestGroup. We do this by adding the lines listed in Example 3.4 to our web.xml file.

Example 3.4

Please Note: For every group you want to create you need to follow the steps mentioned above.

<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" "http://java.sun.com/j2ee/dtds/web-app_2.2.dtd"> <web-app> <servlet> <servlet-name>TestGroup</servlet-name> <servlet-class>

com.ibm.etools.webservice.rt.dxx.servlet.DxxInvoker </servlet-class> <init-param >

<param-name>faultListener</param-name> <param-value>org.apache.soap.server.DOMFaultListener </param-value>

</init-param> <load-on-startup>-1</load-on-startup>

</servlet> <servlet-mapping> <servlet-name>TestGroup</servlet-name> <url-pattern>/testing/*</url-pattern> </servlet-mapping> </web-app>

Page 15: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

15

Packaging the Web application Now is the time to create our welcome page and associate it with the web application. Enter the text shown in Example 3.5 into WORFTest\index.html file and save it.

Example 3.5

Now to associate this index.html file as the welcome file for the web application insert the following lines into your web.xml file between <webapp> and </webapp>.

<welcome-file-list>

<welcome-file>index.html</welcome-file> </welcome-file-list>

<html> <head> <title> DB2 Web Services </title> </head> <body> <h1> DB2 Web Services </h1> <hr>

<p> <br>Test the “List Departments” Web Service >

<a href="testing/List.dadx/listDepartments"> list_Departments</a> <br> <br>Test the “List Sales” Web Service >

<a href="testing/List.dadx/listSales"> list_Sales</a> <br> <br>Generate<a href="testing/List.dadx/WSDL"> WSDL</a> <br>Generate<a href="testing/List.dadx/XSD"> XSD</a>

</body> </html>

Page 16: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

16

Now the completed web.xml file should look as shown in Example 3.6

Example 3.6

With this step we have finished our Web application. By now you should have the directory structure as shown in Example 3.7 ready with each file containing the contents discussed in the previous sections.

<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" "http://java.sun.com/j2ee/dtds/web-app_2.2.dtd"> <web-app> <servlet> <servlet-name>TestGroup</servlet-name> <servlet-class> com.ibm.etools.webservice.rt.dxx.servlet.DxxInvoker </servlet-class> <init-param > <param-name>faultListener</param-name> <param-value>org.apache.soap.server.DOMFaultListener

</param-value> </init-param> <load-on-startup>-1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>TestGroup</servlet-name> <url-pattern>/testing/*</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list>

Page 17: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

17

Example 3.7

We can now proceed to package the Web application as a web archive or war file by entering the following command. You will need to be in the WORFTest directory.

c:\WORFTest>c:\websphere\appserver\java\bin\jar -cvf SimpleWorfTest.war *

Now you have created the Web application that can be deployed on Application Server.

WORFTest | |-- index.html | |-- WEB-INF

| |-- web.xml | |-- --- -lib | | | |-- worf-servlets.jar | |-- --- -classes

| |-- groups |

|--TestGroup | |-- group.properties |-- List.dadx

Page 18: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

18

Deploying the Web application In this section I’ll show you how to deploy the web application on WebSphere Application Server 5.0.2S Just a reminder, that I assume that you have installed WebSphere Application Server 5.0.2 and that the server root is C:\WebSphere\AppServer.

Start the WebSphere Administrative web client by typing the following URL in the Web browser’s address bar: http://localhost:9090/admin (assuming you have accepted default option of port 9090 for WebSphere Application Server admin server while installing Application Server and that the admin server is currently started)

Enter the system user id and login to administer your Application Server. You should see a very similar screen to the one shown in Figure 3.2 below.

Figure 3.2

Click on the Install New Applications link listed under Applications. It should open up the screen shown in Figure 3.3. Provide the path of the Web application we created and also provide a context name in the appropriate input field as shown.

Page 19: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

19

Figure 3.3

Type in the context root as shown (if it is not entered for you) and then click Next and keep accepting the default values or making the selections as shown in the next few screens listed below in succession.

o Figure 3.4 o Figure 3.5 o Figure 3.6 o Figure 3.7 o Figure 3.8 o Figure 3.9 o Figure 3.10

Page 20: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

20

Figure 3.4

Click Next.

Page 21: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

21

Figure 3.5

Click Next.

Page 22: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

22

Figure 3.6

Put a tick in the box as shown and then click Next.

Page 23: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

23

Figure 3.7

Put a tick in the box as shown and then click Next.

Page 24: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

24

Figure 3.8

You will need to scroll down the screen and press Finish for Step 4 of this process.

Page 25: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

25

Figure 3.9

Click on the link Save to Master Configuration.

Page 26: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

26

Figure 3.10

Click on the Save button. This saves the details about the web application into the WebSphere repository. Once the save action is completed, the screen shown in Figure 3.2 above is displayed again.

Before we can start the application we need to ensure that the db2 JDBC drivers are included as part of the CLASSPATH. To do this, please follow the screens below.

Page 27: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

27

Figure 3.11

First click on the Application Servers link under Servers and then click on Server1 as can be seen in Figure 3.11 above.

Page 28: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

28

Figure 3.12

On the next screen you will need to scroll down the page and click on the Process definition link as shown above in Figure 3.12.

Page 29: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

29

Figure 3.13

You will need to scroll down the next page as well and click on the Java Virtual Machine link as seen in Figure 3.13.

Page 30: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

30

Figure 3.14

The correct class path, which in our case is C:\IBM\SQLLIB\java\db2java.zip, should then be entered into the CLASSPATH field as you can see in Figure 3.14. Once you have done this you will need to scroll down the screen and click OK. This will return you to a screen that should look the same as the one in Figure 3.15 below.

Page 31: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

31

Figure 3.15

Here you will need to click on Save to apply the changes to the master configuration.

Page 32: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

32

Figure 3.16

Finally you will need to save the changes to the master configuration, do this by click on the Save button at the bottom left of the screen, as seen in Figure 3.16.

Once the save action is completed, the screen shown in Figure 3.2 above is displayed again. Now you can start the Web application in order to test our Web services.

Starting the Web application In this section I assume that you completed all the instructions detailed in the previous sections, your Web application is successfully deployed and your WebSphere Administrative client is showing the main page as shown in Figure 3.2 above.

Click on Enterprise Applications link listed under Applications. You should get the screen shown in Figure 3.17 below.

Page 33: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

33

Figure 3.17

Select the SimpleWORFTest_war (the one you deployed in the previous section).

Click on the start button.

You should be able to see that the red cross has changed to a green arrow indicating that the web application has started.

Testing the DB2 Web services

Now it’s time for us to see our DB2 Web services in action. In this section we test the DB2 Web services that we developed and deployed in the last few sections.

Open a new Web browser window and type the following URL in the address bar. http://localhost/SimpleWorfTest/. You should see the screen as shown in Figure 3.18

Page 34: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

34

Figure 3.18

Click on the list_Departments link to test the Web service that lists all the departments in the SAMPLE database. Your result should look the same as Figure 3.19

Figure 3.19

Congratulations, you have a working Web service. If you have any problems with getting this result please refer to the Troubleshooting section of this document.

Page 35: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

35

Similarly you can also click on the list_Sales link to invoke the listSales operation of our sample Web service. You can also achieve the same result by directly typing the following URL in the address bar of your web browser http://localhost:9080/simpleWORFTest/testing/List.dadx/listSales If you analyze the definition of our servlet ‘TestGroup’ you will realize that the url-pattern for this servlet is /testing/*. Hence when Application Server gets the request for /testing/List.dadx, it invokes the TestGroup servlet. This servlet instance looks for a directory called TestGroup (its own name) under /WEB-INF/classes/groups directory. In this directory it searches for List.dadx and invokes the Web service operation.

As mentioned in the introduction WORF automatically generates the WSDL and XSD for the Web service hosted. You can view WSDL for the Web service defined by List.dadx by clicking on Generate WSDL link on the web application’s welcome page shown in Figure 2.18. You can also directly invoke this by entering the URL: http://localhost:9080/simpleWORFTest/testing/List.dadx/WSDL You can see the WSDL as shown in Figure 3.20 below.

Figure 3.20

In the same way you can view the XSD for the Web service by clicking on Generate XSD link on the web application’s welcome page. You can also directly invoke this by entering the URL: http://localhost:9080/simpleWORFTest/testing/List.dadx/XSD

Page 36: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

36

DADX and auto-deploy feature of WORF If you want to add another operation to the same Web service all you need to do is add another operation element into the List.dadx file and save the file. WORF will automatically pick up the new operation when you invoke it. Also if you want to create another related Web service with one or more operations in it, you can create a new DADX file similar to the one listed in Example 2.1 and place it under the directory in which the deployed List.dadx is placed.

For example, if your WAS root is C:\WebSphere\ApplicationServer, then this directory would be:

C:\WebSphere\AppServer\installedApps\<YOUR-NODE-NAME> \SimpleWORFTest_war.ear\SimpleWORFTest.war\ WEB-INF\classes\groups\TestGroup.

You need not redeploy your Web application. WORF will pick up the new DADX automatically when the DADX is invoked. In the preceding few sections I showed you how to expose the SQL query statement as a Web service. In fact WORF is capable of exposing any SQL statement and features provided by DB2 XML Extender.

3.1.3. Stored Procedure as a Web service Everything we have worked through so far has given us all we need to move on to the other features and functionality of DB2 Web services. In this section I will show you how to expose a DB2 stored procedure as a Web service. This will include a simple stored procedure as well as a stored procedure which will require input variables and join a few tables together. Please see figure 3.1.3 for a graphical representation of what we will achieve in this section. Figure 3.1.3

Page 37: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

37

In this section I assume you know how to use DB2’s Development Centre to build and deploy DB2 stored procedures. However I will attempt to give some guidance on this where I think it may be needed. I also assume you have installed a suitable compiler for SQL and Java Stored Procedures, for example, the free Microsoft .NET compiler as well as a Java SDK. For instructions on how in install the Microsoft .NET compiler please refer to Appendix B ‘Installing Microsoft’s free .NET compiler’.

Editing the DADX document

As it is stated in the section above about the auto-deploy feature of DADX, we can edit this document without having to redeploy the application. To start with we need to add our new operation to the DADX document.

But before we do that, we need to look at the requirements DADX has to allow us to call a stored procedure. As we saw before the basic SQL operation is very straight forward, however with a stored procedure we need to consider the following:

Stored procedures can return one or more result sets. You can include them in the output message. Metadata for a stored procedure result set must be defined explicitly in the DADX using the <result_set_metadata> element. At run-time, you obtain the metadata of the result set. The metadata must match the definition contained in the DADX file. Therefore, you can only invoke stored procedures that have result sets with fixed metadata. This restriction is necessary in order to have a well-defined WSDL file for the Web service. A single result set metadata definition can be referenced by several <call> operations, using the <result_set> element. The result set metadata definitions are global to the DADX and must precede all of the operation definition elements.

Let’s look at a sample of a DADX document in Example 3.8 which is making a call to a stored procedure.

Example 3.8

First look at the <result_set_metadata> element. Attributes: o name Identifies the root element for the result set.

<result_set_metadata name="listOrg" rowName="Org"> <column name="DEPTNUMB" type="SMALLINT" nullable="false"/> <column name="DEPTNAME" type="VARCHAR" nullable="true"/> <column name="MANAGER" type="SMALLINT" nullable="true"/> <column name="DIVISION" type="VARCHAR" nullable="true"/> <column name="LOCATION" type="VARCHAR" nullable="true"/> </result_set_metadata> <operation name="listOrg">

<documentation> Lists all the Organisations in the Org table of the SAMPLE database </documentation> <call>

<SQL_call>CALL <username>.org()</SQL_call> <result_set name="Orgs" metadata="listOrg"/> </call> </operation>

Page 38: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

38

o Rowname Used as the element name for each row of the result set. Children: o <column> Defines the column. The order of the columns must match that

of the result set returned by the stored procedure. Each column has a name, type, and nullability, which must match the result set. Attributes: name - Required. This specifies the name of the column. type - Required if you do not specify element. It specifies the type of

column. element - Required if you do not specify type. It specifies the element

of column. as - Optional. This provides a name for a column. nullable - Optional. Nullable is either true or false. It indicates whether

column values can be null. Next we can look at the <operation> element

Specifies a Web service operation. The operation element and its children specify the name of an operation, and the type of operation the Web service performs.

Attribute: o name A unique string that identifies the operation. The string must be

unique within the DADX file. Children: o Document the operation with the following element: <documentation>

Specifies a comment or statement about the purpose and content of the operation.

o <call> Specifies a call to a stored procedure. o <SQL_call> Specifies a stored procedure call. o <parameter> Required when referencing a parameter in an <SQL_call>

element. This specifies a parameter for an operation. Use a separate parameter element for each parameter referenced in the operation. Each parameter name must be unique within the operation. Attributes:

name The unique name of the parameter. type Use the type attribute to specify a simple type. kind Specifies whether a parameter passes input data, returns output

data, or does both. The valid values for this attribute are: – in – out – in/out

o <result_set> This defines a result set and must follow any <parameter> elements. The result set element has a name which must be unique among all the parameters and result sets of the operation. It must refer to a <result_set_metadata> element. One <result_set> element must be defined for each result set returned from the stored procedure. Attributes:

name A unique identifier for the result sets in the SOAP response. Metadata A result set meta data definition in the DADX file. The

identifier must refer to the name of an element. To Test this we need to do the following three things:

Page 39: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

39

Edit the DADX document and add the lines shown in Example 2.8 to the list.dadx file we used in our first example.

Create the stored procedure we are going to be calling as part of the new operation in the DADX document.

Edit the index.html welcome page so that we can execute the new stored procedure.

To edit the DADX document with out having to redeploy the application go to the following directory:

C:\WebSphere\AppServer\installedApps\<username> \SimpleWorfTest_war.ear\SimpleWorfTest.war\WEB-INF \classes\groups\TestGroup

There you will find the list.dadx and the group.properties files as we discussed

in the previous section. Edit the list.dadx file and add the lines from Example 3.8. You should end up with a list.dadx file which looks the same as Example 3.9.

Page 40: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

40

Example 3.9

Next we need to create the Stored Procedure for this operation. The procedure will do a select all from the ORG table.

The sample code for this stored procedure can be seen in Example 3.10 below.

<?xml version="1.0" encoding="UTF-8"?> < DADX xmlns=”http://schemas.ibm.com/db2/dxx/dadx” xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xmlns:xsd=”http://www.w3.org/2001/XMLSchema”> <result_set_metadata name="listOrg" rowName="Org"> <column name="DEPTNUMB" type="SMALLINT" nullable="false"/> <column name="DEPTNAME" type="VARCHAR" nullable="true"/> <column name="MANAGER" type="SMALLINT" nullable="true"/> <column name="DIVISION" type="VARCHAR" nullable="true"/> <column name="LOCATION" type="VARCHAR" nullable="true"/> </result_set_metadata>

<operation name="listOrg"> <documentation> Lists all the Organisations in the Org table of the SAMPLE database </documentation>

<call> <SQL_call>CALL <username>.org()</SQL_call> <result_set name="Orgs" metadata="listOrg"/> </call> </operation> <operation name="listSales">

<documentation> Lists all the sales in the SALES table of the SAMPLE database </documentation>

<query> <SQL_query>SELECT * FROM sales</SQL_query> </query> </operation> <operation name="listDepartments">

<documentation> Lists all the departments in the DEPARTMENT table of the SAMPLE database </documentation>

<query> <SQL_query>SELECT * FROM department</SQL_query> </query> </operation> </DADX>

Page 41: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

41

Example 3.10

You can create this stored procedure using the DB2 Development Center, the details of which I will not cover in this document.

You can also create this stored procedure by coping the sample code into a txt file called org.sql, editing the required sections (<username>) and then using the following command to execute it:

db2 -td@ -vf org.sql

To test that the stored procedure is working you can call it from a db2 command line by executing the following command:

db2 call <username>.org ()

The result of this should be the contents of the Org table.

Now we need to edit the index.html welcome page so that we can call this Web service from our application. You will find this file here: C:\WebSphere\AppServer\installedApps\<username>\SimpleWorfTest_war.ear\SimpleWorfTest.war

To do this, please add the text which is in blue in Example 3.11 to the index.html file and save it.

CREATE PROCEDURE <username>.ORG ( ) SPECIFIC <username>.listORG DYNAMIC RESULT SETS 1 ------------------------------------------------------------------------ -- SQL Stored Procedure ------------------------------------------------------------------------ P1: BEGIN -- Declare cursor DECLARE cursor1 CURSOR WITH RETURN FOR SELECT * FROM ORG AS ORG; -- Cursor left open for client application OPEN cursor1; END P1 @

Page 42: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

42

Example 3.11

To test the new Web service, Open a new web browser window and type the following URL in the address bar. http://localhost/SimpleWorfTest/. You should then see the new line which we just added. Click on the list_Organisations link and you should see the following screen to show a positive result.

Figure 3.21

Congratulations! You now have a stored procedure exposed as a Web service.

<html> <head> <title> DB2 Web Services </title> </head> <body> <h1> DB2 Web Services </h1> <hr> <p> <br>Test the "List Departments" Web Service > <a href="testing/List.dadx/listDepartments">list_Departments</a> <br>

<br>Test the "List Sales" Web Service > <a href="testing/List.dadx/listSales">list_Sales</a> <br>

<br>Test the "List Organisations" Web Service > <a href="testing/List.dadx/listOrg"> list_Organisations</a> <br> <br>Generate<a href="testing/List.dadx/WSDL"> WSDL</a> <br>Generate<a href="testing/List.dadx/XSD"> XSD</a> </body> </html>

Page 43: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

43

Now that we have a basic stored procedure working and exposed as a Web service, we can look at how we might use an input variable and join tables.

To do this, we need to go through the same steps as before

Edit the DADX file. Create the stored procedure. Edit the index.html welcome page.

First let’s edit the DADX file and add the new lines shown in Example 3.12 to your list.dadx file.

Page 44: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

44

Example 3.12

<?xml version="1.0" encoding="UTF-8"?> <DADX xmlns="http://schemas.ibm.com/db2/dxx/dadx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <result_set_metadata name="StaffOrg" rowName="Staff"> <column name="NAME" type="VARCHAR" nullable="true"/> <column name="JOB" type="CHAR" nullable="true"/> <column name="DEPARTMENT" type="VARCHAR" nullable="true"/> <column name="DIVISION" type="VARCHAR" nullable="true"/> <column name="LOCATION" type="VARCHAR" nullable="true"/> </result_set_metadata> <result_set_metadata name="listOrg" rowName="Org"> <column name="DEPTNUMB" type="SMALLINT" nullable="false"/> <column name="DEPTNAME" type="VARCHAR" nullable="true"/> <column name="MANAGER" type="SMALLINT" nullable="true"/> <column name="DIVISION" type="VARCHAR" nullable="true"/> <column name="LOCATION" type="VARCHAR" nullable="true"/> </result_set_metadata> <operation name="StaffOrg">

<documentation> Lists the managers and their departments in the SAMPLE database </documentation>

<call> <SQL_call>CALL timjbrown.stafforg(:salary)</SQL_call> <parameter name="salary" type="xsd:int" kind="in"/> <result_set name="OrgMgrs" metadata="StaffOrg"/> </call> </operation> <operation name="listOrg">

<documentation> Lists all the Organisations in the Org table of the SAMPLE database </documentation>

<call> <SQL_call>CALL timjbrown.org()</SQL_call> <result_set name="Orgs" metadata="listOrg"/> </call> </operation> <operation name="listSales">

<documentation> Lists all the sales in the SALES table of the SAMPLE database </documentation>

<query> <SQL_query>SELECT * FROM sales</SQL_query> </query> </operation> <operation name="listDepartments">

<documentation> Lists all the departments in the DEPARTMENT table of the SAMPLE database </documentation>

<query> <SQL_query>SELECT * FROM department</SQL_query> </query> </operation> </DADX>

Page 45: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

45

The new lines are shown in blue. First the result_set_metadata is defined. This must be the same as the expected

result from the stored procedure in the same way as it was done for the previous example except here the result set will include the results of doing a join between the two tables. The details can be seen in the create procedure code in Example 3.13.

The operation is defined as a stored procedure call. In this case though, we are using a parameter and must therefore define a name, a type and a kind. This is then followed by the result set name in the same way as with the previous example.

Now, it’s time to create the new stored procedure. The sample code for this can be seen in Example 3.13 below. This procedure will do a join between the STAFF and ORG tables. It will list the name and job title of the managers for each of the departments in the ORG table who earn more than the salary figure entered by us, as well as the division they fall into and their location.

Example 3.13

You can create this stored procedure using the Development Center. You can also create this stored procedure by copying the sample code into a

txt file called org.sql, editing the required sections (<username>) and then using the following command to execute it:

db2 -td@ -vf stafforg.sql

To test that the stored procedure is working you can call it from a db2 command line by executing the following command:

db2 call <username>.stafforg (20000)

CREATE PROCEDURE <username>.STAFFORG ( IN SALARY DECIMAL(7,2) ) SPECIFIC <username>.STAFFORG DYNAMIC RESULT SETS 1 ------------------------------------------------------------------------ -- SQL Stored Procedure ------------------------------------------------------------------------ P1: BEGIN -- Declare cursor DECLARE cursor1 CURSOR WITH RETURN FOR

SELECT STAFF.NAME, STAFF.JOB, ORG.DEPTNAME as DEPARTMENT, ORG.DIVISION, ORG.LOCATION

FROM DB2DAS.STAFF AS STAFF, DB2DAS.ORG AS ORG WHERE STAFF.ID = ORG.MANAGER AND STAFF.SALARY > STAFFORG.SALARY

ORDER BY STAFF.NAME ASC; -- Cursor left open for client application OPEN cursor1; END P1 @

Page 46: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

46

The result of this should be the name of the managers and the departments for which they are responsible, that earn more than 20000.

Now we need to edit the index.html welcome page so that we can call this Web service from our application. You will find this file here: C:\WebSphere\AppServer\installedApps\<username>\SimpleWorfTest_war.ear\SimpleWorfTest.war

To do this, please add the text which is in blue in Example 3.14 below to the index.html file and save it.

Page 47: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

47

Example 3.14

All we need to do now is demonstrate it. Once you have saved all the changes we can test the new Web service, Open a new Web browser window and type the following

<html> <head> <title> DB2 Web Services </title> </head> <body> <h1> DB2 Web Services </h1> <hr> <p> <br>Test the "List Departments" Web Service > <a href="testing/List.dadx/listDepartments">list_Departments</a> <br>

<br>Test the "List Sales" Web Service > <a href="testing/List.dadx/listSales">list_Sales</a> <br>

<br>Test the "List Organisations" Web Service > <a href="testing/List.dadx/listOrg"> list_Organisations</a>

<br> <br> <br>Test the "Department Managers" Web Service > <FORM method="post" action="testing/List.dadx/StaffOrg"> <TABLE border="0"> <TBODY> <TR> <TD>Enter a salary and click the <B>Execute</B> button. </TR> <TR>

<TD height="25"><INPUT TYPE="TEXT" NAME="salary" SIZE="20" maxlength="20">

</TD> </TR> <TR>

<TD height="35"><INPUT type="submit" name="Submit" value="Execute"><INPUT type="reset" value="Reset"></TD>

</TR> </TBODY> </TABLE> </FORM> <br> <br>Generate<a href="testing/List.dadx/WSDL"> WSDL</a> <br>Generate<a href="testing/List.dadx/XSD"> XSD</a> </body> </html>

Page 48: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

48

URL in the address bar http://localhost/SimpleWorfTest/ . The Welcome page as seen in Figure 3.22 should appear.

Figure 3.22

Enter a salary value and click on Execute button. If we enter a value of 20000, the result should be all those managers which earn more than 20000 and should show us the name of the departments which they are responsible. The page shown in Figure 3.23 is what should be returned.

Page 49: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

49

Figure 3.23

Congratulations! You now have a stored procedure, which accepts an input variable and joins tables, exposed as a Web service.

Let us take a minute to look back at what we have just done. We have exposed two simple SQL select statements as Web services, list_Departments and list_Sales. We have also exposed two stored procedures, one of which does a simple select statement list_Organisations and one which joins the staff and org tables together and uses an input variable of salary to define the where clause.

This has only scraped the surface of what we can do. For example, as was mentioned during the description of the DADX file, it is also possible to do update, insert and delete statements as part of the update SQL operation. Below in Example 3.15 are a few examples of how these might look in the DADX file. The changes to the index.html page follow in Example 3.16.

Page 50: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

50

Example 3.15

<operation name="deleteDepartment"> <documentation> Deletes a department the Department table of the SAMPLE database </documentation>

<update> <SQL_update>delete from department where deptno = :deptmnt </SQL_update>

<parameter name="deptmnt" type="xsd:string" kind="in"/> </update> </operation> <operation name="insertDepartment">

<documentation> Inserts a new department into the Department table of the SAMPLE database </documentation>

<update> <SQL_update>insert into department values(:deptmnt,:deptnme,:mgrno,:admrdpt,:location) </SQL_update>

<parameter name="deptmnt" type="xsd:string" kind="in"/> <parameter name="deptnme" type="xsd:string" kind="in"/> <parameter name="mgrno" type="xsd:string" kind="in"/> <parameter name="admrdpt" type="xsd:string" kind="in"/> <parameter name="location" type="xsd:string" kind="in"/> </update> </operation> <operation name="updateDepartment">

<documentation> Updates a department in the Department table of the SAMPLE database </documentation>

<update> <SQL_update>update department set location = :location where deptno = :deptmnt </SQL_update>

<parameter name="location" type="xsd:string" kind="in"/> <parameter name="deptmnt" type="xsd:string" kind="in"/> </update> </operation>

Page 51: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

51

Example 3.16

<br>Test the "Update Department" Web Service > <FORM method="post" action="testing/List.dadx/updateDepartment"> <TABLE border="0"><TBODY><TR>

<TD>Enter a Location and a Department and click the <B>Execute</B> button.

</TR></TBODY></TABLE> <TABLE border="0"><TR> <TD>Location</TD><TD>Department</TD> </TR><TR>

<TD height="25"><INPUT TYPE="TEXT" NAME="location" SIZE="20" maxlength="20"></TD> <TD height="25"><INPUT TYPE="TEXT" NAME="deptmnt" SIZE="20" maxlength="20"></TD>

</TR><TR> <TD height="35"><INPUT type="submit" name="Submit" value="Execute"><INPUT type="reset" value="Reset"></TD>

</TR></TBODY></TABLE> </FORM> <br>Test the "Insert Department" Web Service > <FORM method="post" action="testing/List.dadx/insertDepartment"> <TABLE border="0"><TBODY><TR>

<TD>Enter a Dept. No., Dept. Name, Manager No., Admin. Dept., and a location and click the <B>Execute</B> button.

</TR></TBODY></TABLE> <TABLE border="0"><TBODY><TR>

<TD>Department No.</TD><TD>Department Name</TD><TD>Manager No.</TD><TD>Admin. Department</TD><TD>Location</TD>

</TR><TR> <TD height="25"><INPUT TYPE="TEXT" NAME="deptmnt" SIZE="20" maxlength="10"> </TD> <TD height="25"><INPUT TYPE="TEXT" NAME="deptnme" SIZE="20" maxlength="20"> </TD> <TD height="25"><INPUT TYPE="TEXT" NAME="mgrno" SIZE="20" maxlength="10"> </TD> <TD height="25"><INPUT TYPE="TEXT" NAME="admrdpt" SIZE="20" maxlength="10"> </TD> <TD height="25"><INPUT TYPE="TEXT" NAME="location" SIZE="20" maxlength="10"> </TD>

</TR><TR> <TD height="35"><INPUT type="submit" name="Submit" value="Execute"><INPUT type="reset" value="Reset"></TD>

</TR></TBODY></TABLE> </FORM>

Page 52: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

52

These examples use the query and update SQL operations. The call operation, as we have already seen, allows us to call stored procedures. This opens up the possibility of allowing Web services to access procedures which are very complex and do a vast amount of data processing and execute other functions such as user defined functions. This also means that other external Web services can be consumed. Therefore Web services can open up a large selection of DB2 functionality to a wide audience very easily.

3.1.4. XML Web services We have now covered all of the SQL operations provided by DB2 Web services. In this section we will look at the XML operations. This will not be covered at the same level of detail as has been done with the previous topics. This is because this subject area is very large and requires a more detailed understanding of XML and XML Extender, which is out of scope of what this document is trying to achieve.

Extensible Markup Language (XML) collection operations require DB2 XML Extender. DB2 XML Extender should be installed and your database should be enabled before you begin. DB2 XML Extender is packaged with DB2 UDB Version 8.1. If you are running DB2 UDB Version 7.2 you will need to download DB2 XML Extender from one of the following sources:

FTP:

ftp://service.boulder.ibm.com/ps/products/db2extenders/fixes/

HTTP: www.ibm.com/software/data/db2/extenders/xmlext/support/fixpak.html

or www.ibm.com/software/data/db2/extenders/xmlext/downloads.html

DB2 XML Extender allows XML documents to be stored intact, and optionally indexed in side tables, using the XML column access method, or as a collection of relational tables using the XML collection access method. DB2 XML Extender uses an XML document format called the Document Access Definition (DAD) to define

<br>Test the "Delete Department" Web Service > <FORM method="post" action="testing/List.dadx/deleteDepartment"> <TABLE border="0"><TBODY><TR>

<TD>Enter a Department Number and click the <B>Execute</B> button. </TR> </TBODY></TABLE> <TABLE border="0"><TR> <TD>Department</TD> </TR><TR>

<TD height="25"><INPUT TYPE="TEXT" NAME="deptmnt" SIZE="20" maxlength="20"> </TD>

</TR><TR> <TD height="35"><INPUT type="submit" name="Submit" value="Execute"><INPUT type="reset" value="Reset"></TD>

</TR></TBODY></TABLE> </FORM>

Page 53: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

53

the mapping between XML and relational data. You can use DB2 XML Extender to implement Web services using WORF tools with DB2 UDB. DB2 XML Extender consists of a set of stored procedures, user-defined types (UDTs) and user-defined functions (UDFs) that you can use to store and retrieve XML data using DB2 UDB.

Here is a bit more information about DAD’s. With DAD’s you specify how structured XML documents are to be processed by the XML Extender using a document access definition (DAD) file. The DAD file is an XML document that maps the XML document structure to a DB2 table. You use a DAD file both when storing XML documents in a column, and when composing or decomposing XML data. The DAD file specifies whether you are storing documents using the XML column method, or defining an XML collection for composition or decomposition.

Relational data is either decomposed from incoming XML documents or used to compose outgoing XML documents. Decomposed data is the untagged content of an XML document stored in one or more database tables. XML documents are composed from existing data in one or more database tables. If your data is to be shared with other applications, you might want to be able to compose and decompose incoming and outgoing XML documents and manage the data as necessary to take advantage of the relational capabilities of DB2. This type of XML document storage is called XML collection.

There are basically two XML operations that the DADX can expose as a Web service and these storeXML and retrieveXML. These storage and retrieval operations help you to map XML document structures to DB2 tables. You can either compose XML documents from existing DB2 data, or decompose (storing untagged elements or attribute content) XML documents into DB2 data. This method is useful for data interchange applications, particularly when the application frequently updates the contents of XML documents.

As mentioned above there are two elements that make up the XML collection operation type:

<retrieveXML> Generates XML documents

<storeXML> Stores XML documents

Let’s look at this in a bit more detail: <retrieveXML> This element specifies to generate zero or one XML documents from a set of relational tables when using the XML collection access method. Depending on whether you specify a DAD file or an XML collection name, the operation calls the appropriate XML Extender composition stored procedure.

Children: Specify which of these stored procedures you want to use. You do this by passing either the name of a DAD file or the name of the collection by using one of the following elements:

Page 54: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

54

<DAD_ref> The content of this element is the name and path of a DAD file. If you specify a relative path for the DAD file, then the application assumes that the current working directory is the group directory.

<collection_name>

The content of this element is the name of the XML collection. You define collections by using the XML Extender administration interfaces, as described in DB2 XML Extender Administration and Programming.

<storeXML>

This element specifies to store (decompose) an XML document in a set of relational tables using the XML collection access method. Depending on whether you specify a DAD file or an XML collection name, the operation calls the appropriate XML Extender decomposition stored procedure.

Children: Specify which of these stored procedures you want to use. You do this by passing either the name of a DAD file, or the name of the collection by using one of the following elements:

<DAD_ref> same as above.

<collection_name>

same as above. For further information on XML Extender and XML Web services please refer to the following documents:

DB2 XML Extender Administration and Programming. IBM DB2 Information Integrator Developer’s Guide

Page 55: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

55

3.2. DB2 as a Web service consumer IBM DB2 Web service consumer user-defined functions (UDFs) are now available for this task. This is provided as part of fix pack 2 for DB2 v8. These new Web service consumer UDFs enable databases to directly invoke Web services using SQL. This eliminates the need to transfer data between Web services and the database. The result is increased productivity and better performance.

The Web services consumer converts existing WSDL interfaces into DB2 table or scalar functions. In the following sections I will show you how to enable DB2 as a Web service consumer and write a sample UDF that acts as a consumer to a standard Web service that fetches delayed stock quotes given the stock symbol.

If you are running DB2 UDB version 8.1 Fix pack 2, the Web services consumer package is already packaged. Otherwise you need to download it from http://www7b.software.ibm.com/dmdd/zones/webservices/wsconsumer/.

DB2 XML Extender is required for this functionality to be enabled. Please see the section titled XML Web services for further information about DB2 XML Extender.

3.2.1. Enabling DB2 Web service consumer UDFs The database you want to enable for DB2 Web services consumer must first be enabled for DB2 XML Extender. This can be done by executing the following commands from a DB2 command line:

Connect to the database you want to enable. db2 connect to sample

Now enable the sample database. dxxadm enable_db sample

You should see the following output

DXXA002I Connecting to database "SAMPLE". DXXA005I Enabling database "SAMPLE". Please wait. DXXA006I The database "SAMPLE" was enabled successfully.

Issue the following command from the DB2 command line to register five user-defined functions:

db2enable_soap_udf -n dbName -u uID -p password [-force]

The parameters have the following definitions:

dbName - The database name to be enabled uID user - ID for accessing the database password - The password associated with the user ID -force - Attempts to drop any existing functions.

The enable command copies the shared library with the implementation of the functions to your sqllib/function directory, and then it enables your database to use the

Page 56: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

56

functions. To make sure that you enabled the database correctly ensure that you have the following UDFs defined.

db2xml.soaphttpv (VARCHAR(256), VARCHAR(256), VARCHAR(3072)) db2xml.soaphttpv (VARCHAR(256), VARCHAR(256), CLOB(1M)) db2xml.soaphttpc (VARCHAR(256), VARCHAR(256), varchar(3072)) db2xml.soaphttpc (VARCHAR(256), VARCHAR(256), CLOB(1M)) db2xml.soaphttpcl ( VARCHAR(256), VARCHAR(256), varchar(3072))

Also ensure that db2soapudf.dll is copied to sqllib/function directory of your DB2 installation. You can disable the SOAP UDF’s in the database by executing the following command from a DB2 command line:

db2disable_soap_udf -n dbName -u uID -p password

The meanings of the parameters are the same as above.

Refer to DB2 Web services consumer documentation available at http://www-3.ibm.com/cgi-bin/db2www/data/db2/udb/winos2unix/support/v8document.d2w/report?fn=c0010854.htm if you find any trouble installing or enabling it.

Please Note: If you are running this on XP, there may be a problem when running the db2enable and db2disable soap functions. If this is the case please just execute the commands less the –u and –p options.

3.2.2. Web services consumer UDFs In this section I’ll show you how to use the Web services consumer UDFs you installed/enabled in “Enabling DB2 Web service consumer UDFs” above. I’ll first introduce you to the Web services consumer UDFs and explain their parameters. I’ll then present you with the WSDL for the ‘delayed Stock Quote’ Web service, a Web service provided by xmethods. We will then look at how to find out the values of different parameters for the consumer UDFs.

The db2xml.soaphttp() is a DB2 UDF that composes a SOAP request, posts the request to the service endpoint, receives the SOAP response, and returns the content of the SOAP body. The function is overloaded depending on the soap body to be a VARCHAR() or CLOB().

db2xml.soaphttpv returns VARCHAR():

db2xml.soaphttpv ( endpoint_url VARCHAR(256), soap_action VARCHAR(256), soap_body VARCHAR(3072)) | CLOB(1M))

RETURNS VARCHAR(3072)

Page 57: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

57

db2xml.soaphttpc returns CLOB():

db2xml.soaphttpc ( endpoint_url VARCHAR(256), soapaction VARCHAR(256), soap_body VARCHAR(3072) | CLOB(1M))

RETURNS CLOB(1M)

db2xml.soaphttpcl returns CLOB() as locator: db2xml.soaphttpcl( endpoint_url VARCHAR(256),

soapaction VARCHAR(256), soap_body varchar(3072))

RETURNS CLOB(1M) as locator

DB2 requires the following information to build a SOAP request and receive a SOAP response:

Service endpoint, e.g. 'http://services.xmethods.net/soap/servlet/rpcrouter' SOAP action URI reference (it is optional and may be null string i.e., ‘’ ) XML content of SOAP body, which are: name of operation with request

namespace URI, encoding style, and input arguments.

3.2.3. From WSDL to Web service consumer function The WSDL for ‘Delayed Stock Quote Request’ Web service is shown in Example 3.17 below. It describes the details of the Web service interface. It provides the description such as how to connect to the Web service and invoke the operation. This WSDL is also available at http://services.xmethods.net/soap/urn:xmethods-delayed-quotes.wsdl.

Page 58: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

58

Example 3.17

<?xml version='1.0' encoding='UTF-8'?> <definitions name='net.xmethods.services.stockquote.StockQuote'

targetNamespace='http://www.themindelectric.com/wsdl/ net.xmethods.services.stockquote.StockQuote/'

xmlns:tns='http://www.themindelectric.com/wsdl/ net.xmethods.services.stockquote. StockQuote/'

xmlns:electric='http://www.themindelectric.com/' xmlns:soap='http://schemas.xmlsoap.org/wsdl/soap/' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soapenc='http://schemas.xmlsoap.org/soap/encoding/' xmlns:wsdl='http://schemas.xmlsoap.org/wsdl/' xmlns='http://schemas.xmlsoap.org/wsdl/'>

<message name='getQuoteResponse1'>

<part name='Result' type='xsd:float'/> </message> <message name='getQuoteRequest1'>

<part name='symbol' type='xsd:string'/> </message> <portType name='net.xmethods.services.stockquote.StockQuotePortType'>

<operation name='getQuote' parameterOrder='symbol'> <input message='tns:getQuoteRequest1'/> <output message='tns:getQuoteResponse1'/>

</operation> </portType> <binding name='net.xmethods.services.stockquote.StockQuoteBinding'

type='tns:net.xmethods.services.stockquote.StockQuotePortType'> <soap:binding style='rpc'

transport='http://schemas.xmlsoap.org/soap/http'/> <operation name='getQuote'>

<soap:operation soapAction='urn:xmethods-delayed-quotes#getQuote'/><input> <soap:body use='encoded' namespace='urn:xmethods-delayed-quotes'

encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'/> </input> <output> <soap:body use='encoded' namespace='urn:xmethods-delayed-quotes'

encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'/> </output>

</operation> </binding> <service name='net.xmethods.services.stockquote.StockQuoteService'>

<documentation>net.xmethods.services.stockquote.StockQuote web service</documentation>

<port name='net.xmethods.services.stockquote.StockQuotePort' binding='tns:net.xmethods.services.stockquote.StockQuoteBinding'> <soap:address location='http://66.28.98.121:9090/soap'/>

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

Page 59: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

59

Now let us analyze the WSDL and find out how to map the elements of this WSDL to parameters of Web service consumer functions.

The service section of the WSDL contains the port definition for the SOAP interface:

<port name='net.xmethods.services.stockquote.StockQuotePort' binding='tns:net.xmethods.services.stockquote.StockQuoteBinding'>

<soap:address location='http://66.28.98.121:9090/soap'/> </port>

The location of soap:address shows the service endpoint of the Web service. This is the first parameter of the Web service consumer functions . If there are multiple ports for different bindings, you have to find the port with a SOAP binding.

<soap:binding transport=http://schemas.xmlsoap.org/soap/http .../>. The binding section of the WSDL lists all the operations of the service.

<binding name='net.xmethods.services.stockquote.StockQuoteBinding' type='tns:net.xmethods.services.stockquote.StockQuotePortType'> <soap:binding

style='rpc'transport='http://schemas.xmlsoap.org/soap/http'/> <operation name='getQuote'>

<soap:operation soapAction='urn:xmethods-delayed-quotes#getQuote'/> ... ...

</operation> </binding>

The soapAction of the desired Web service operation is the value of the second parameter of the Web service consumer functions. In our case we are interested in invoking the getQuote operation and hence the relevant soapAction as described in the WSDL is 'urn:xmethods-delayed-quotes#getQuote'. Now we are left with finding the structure of the soap body, the third argument of the Web service consumer functions. The portType definition provides you with this information. The portType may define many operations. Each operation typically contains an input and an output message element. Occasionally it may contain fault elements too. For simplicity we consider only input and output elements in our discussion.

<portType name='net.xmethods.services.stockquote.StockQuotePortType'>

<operation name='getQuote' parameterOrder='symbol'> <input message='tns:getQuoteRequest1'/> <output message='tns:getQuoteResponse1'/>

</operation> </portType>

Page 60: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

60

You can construct the structure of the soap body using the operation element of the portType. The name of the operation becomes the top level node. You then need to flatten out the input or output message element to get the rest of the structure. Thus in our case the getQuote forms the top level element and the flattening of input message getQuoteRequest1 yields the second level element symbol. In many cases this flattening of input or output message may yield quite a complex structure. Thus in our case the structure of the soap body becomes:

<stock:getQuote xmlns:stock="urn:xmethods-delayed-quotes" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"> <symbol xsi:type="xsd:string"> SYMBOL name to be supplied</symbol> </stock:getQuote>

This is the third parameter of the Web service consumer functions for our example. Similarly you can find out the structure of the result by flattening out the output message element. In our case it looks as follows:

<n:getQuoteResponse xmlns:n="urn:xmethods-delayed-quotes"> <Result xsi:type="xsd:float">QUOTE VALUE RETURNED</Result> </n:getQuoteResponse>

Table 3.1 summarises our discussion in this section and provides hints for finding the different parameter values for the Web service consumer functions. Table 3.1

No. Parameter Xpath to look for 1 Service endpoint URL /definition/port/soap:address/@location 2 SOAP action /definitions/binding/soap:binding/operation/

soap:operation/@soapAction 3 SOAP body /definitions/portType/operation

Page 61: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

61

3.2.4. Testing the Web service consumer functions Let’s test the Web service consumer functions by accessing the stock quote of IBM:

Open a DB2 command window. Connect to the database that you enabled for SOAP functions (SAMPLE in

our case). Create a file called getquote.sql and copy the following command into the file

and save it.

Please Note: Use the colour coding in the text below to help determine where the text is extracted from in the WSDL to build the Web service consumer below.

DB2 VALUES db2xml.soaphttpv ( 'http://66.28.98.121:9090/soap', 'urn:xmethods-delayed-quotes#getQuote', varchar ('<stock:getQuote xmlns:stock="urn:xmethods-delayed-quotes" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"> <symbol xsi:type="xsd:string">IBM</symbol> </stock:getQuote>' ) );

Enter the following command to execute it: db2 –tvf getquote.sql

You should be able to see the results similar to the one given below. Note that the actual value of the Result may vary depending on the stock price on any given day.

<n:getQuoteResponse xmlns:n="urn:xmethods-delayed-quotes">

<Result xsi:type="xsd:float">87.33</Result> </n:getQuoteResponse>

If you are running DB2 UDB Version 8.1 you may as well use SQL/XML query to construct the soap body. The following example is the same as the previous one except that it is written in SQL/XML and uses the overloaded soaphttpv function that takes soap body as a CLOB.

VALUES db2xml.soaphttpv('http://66.28.98.121:9090/soap', 'urn:xmethods-delayed-quotes#getQuote', xml2clob(XMLElement(name "getQuote", XMLAttributes('urn:xmethods-delayed-quotes' AS "xmlns:stock"), XMLElement(name "symbol",'IBM'))));

3.2.5. Creating a wrapper UDF to a Web services consumer function In order for the applications to work with DB2 and Web services seamlessly we make Web services calls using the DB2 UDFs that we just installed / enabled in “Enabling DB2 Web service consumer UDFs” above. However calling or invoking these UDFs clutter the application code and reduces the readability of the code. Also every time we make a call to the Web service we need to pass the URL of the Web service and the operation name.

Page 62: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

62

Therefore we wrap the call to a Web service in another UDF and invoke this UDF every time we want to invoke a Web service operation. In our case, instead of calling the db2xml.sopahttpv(...) every time we make a stock quote request, we create a wrapper UDF that takes only the stock symbol as parameter and internally calls the db2xml.soaphttpv(...).

Let us define our wrapper UDF getStockQuote which takes only one parameter, namely symbol as a VARCHAR(256) and returns Result as FLOAT. Example 3.18 shows the code for our getStockQuote UDF. (Please replace <schemaname> as appropriate) The result of the call to db2xml.soaphttpv is a CLOB. Hence we extract the value contained in the Result element pointed to by the XPath ’/*/Result’.

Example 3.18

This UDF can be invoked in the DB2 command line as follows: DB2 VALUES <username>.getStockQuote(‘IBM’)

In Example 3.18 we saw how to invoke a consumer UDF for Web services returning one value. DB2 also allows the writing of UDF’s that invoke Web services returning multiple results. In such cases we return a table with each row containing one result element. For example take the Web service Xignite News provided by http://www.xignite.com/xnews.asmx. The WSDL for this is available at http://www.xignite.com/xnews.asmx?WSDL. One of the operations provided by this Web service is GetStockHeadlines. We write the following UDF as shown in Example 3.19 to access this Web service operation.

CREATE FUNCTION <username>.getStockQuote (symbol VARCHAR(100)) RETURNS DECIMAL(5,2) SPECIFIC xmethods_getQuote LANGUAGE SQL CONTAINS SQL EXTERNAL ACTION NOT DETERMINISTIC RETURN db2xml.extractREAL( db2xml.xmlclob( db2xml.soaphttpv( 'http://66.28.98.121:9090/soap', 'urn:xmethods-delayed-quotes#getQuote', varchar('<m:getQuote xmlns:m="urn:xmethods-delayed-quotes"

SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"> <symbol xsi:type="xsd:string">' || symbol || '</symbol> </m:getQuote>' )

) ), '/*/Result' )

Page 63: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

63

Example 3.19

In this wrapper UDF we are extracting only the Headline elements from the result of the Web service and constructing a table from these elements and returning the table. You can invoke this UDF as follows:

select * from table (<username>.GetStockHeadlines('IBM', 10)) as x

By issuing the above query we should expect to see 10 or less news headlines related to IBM stock as can be seen in Example 3.20 below.

Example 3.20

Congratulations you have now successfully written 2 UDF’s to act as Web service consumers.

CREATE FUNCTION <username>.GetStockHeadlines ( Symbols VARCHAR(100), HeadlineCount INTEGER )

RETURNS TABLE (StockNews VARCHAR(3000)) LANGUAGE SQL CONTAINS SQL EXTERNAL ACTION NOT DETERMINISTIC RETURN

Select * from Table (db2xml.extractVarchars( DB2XML.XMLCLOB(

db2xml.soaphttpc( 'http://www.xignite.com/xnews.asmx', 'http://www.xignite.com/services/GetStockHeadlines',

'<m:GetStockHeadlines xmlns:m="http://www.xignite.com/services/" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">'

|| '<m:Symbols>' || Symbols || '</m:Symbols>' || '<m:HeadlineCount>' || rtrim(char(HeadlineCount) ) || '</m:HeadlineCount>'

|| '</m:GetStockHeadlines>' )

), '//StockNews/Headline') ) as X ;

STOCKNEWS -------------------------------------------------------------------------------------------------------------------------------IBM and ATB Financial Sign Largest IT Services Agreement of Its Kind in Western Canada [external] IBM Seen Struggling With Growth Problems SCO Escalates Legal Battle on Three Fronts Hewlett-Packard Unveils High-End Copy Machines [external] Oracle Needs to See Beyond PeopleSoft [external] NEWS: Online Extra: What It "Boils Down To" For Kodak Coverage initiated on IBM by Banc of America Sec [external] ONLINE ASIA: An Irresistable Offshore Tide for Jobs [external] Hewlett-Packard Set to Make Amends Sun gives key certification to two small software cos 10 record(s) selected.

Page 64: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

64

If you would like to try one more based on what I have just shown you should have a look at the following Web service.

The WSDL can be found here:

http://www.xmethods.net/sd/2001/CurrencyExchangeService.wsdl

and for more information go here: http://www.xmethods.com/ve2/ViewListing.po;jsessionid=G2jNPJOG59fikyDjLGdgjCa4(QhxieSRM)?key=uuid:D784C184-99B2-DA25-ED45-3665D11A12E5 VALUES db2xml.soaphttpv ( 'http://66.28.98.121:9090/soap', 'urn:xmethods-CurrencyExchange#getRate', xml2clob( XMLElement(name "getRate",

XMLAttributes('urn:xmethods-CurrencyExchange' AS "xmlns:currate"),

XMLElement(name "country1",'UK'), XMLElement(name "country2",'US') ) ) ); or CREATE FUNCTION <username>.getRate (country1 VARCHAR(100), country2 VARCHAR(100)) RETURNS DECIMAL(10,5) SPECIFIC xmethods_getRate LANGUAGE SQL CONTAINS SQL EXTERNAL ACTION NOT DETERMINISTIC RETURN db2xml.extractREAL( db2xml.xmlclob( db2xml.soaphttpv( 'http://66.28.98.121:9090/soap', 'urn:xmethods-CurrencyExchange#getRate', varchar( '<m:getRate xmlns:m="urn:xmethods-CurrencyExchange" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"> <country1 xsi:type="xsd:string">' || country1 || '</country1> <country2 xsi:type="xsd:string">' || country2 || '</country2> </m:getRate>' ) ) ), '/*/Result' );

and call this function by executing the following command:

db2 values <username>.getrate('UK','US') The expected results you might see are as follows:

1.69770 1 record(s) selected.

Page 65: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

65

4. Tooling In all the examples above we have used a text editor to create the DADX, XML, HTML and properties files. There are however tools which can be used to make these tasks a little easier, namely WebSphere Studio Application Developer (WSAD). WSAD can create the DADX files for you as well as check the WSDL to verify the external Web services. It can also be used to create the wrapper UDF. There are quite a few other things which this tool can help you with, but I will not go into that in this document. I would however recommend that you install a copy of this development tool and familiarise yourself with its possibilities.

Also it is worth noting that currently DB2 Web services are only supported with WebSphere Application Server and the Apache Tomcat Application Server.

Page 66: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

66

5. DB2 Web services, why bother? Why choose DB2 Web services? There are a number of situations in which DB2 Web services would be useful. A major reason why I might choose to implement DB2 Web services is for the ability to integrate data between two organisations with out having to develop complex applications or glue code. Other reasons why I would choose DB2 Web services are as follows:

If you can write SQL you can expose and access a Web service. If DB2 Information Integrator is used you can access heterogeneous data through

SQL and expose this as a Web service. You can easily consolidate Web services output in a DB2 database. You can access Web services from any programming language which supports

SQL, for example C and COBOL.

Let’s look at the following examples. Two organisations like a hotel and a car rental company may choose to share their information for the benefit of the customer. The hotel may choose to provide room availability and nightly rate information through their Web service. The car rental company may choose to provide their car availability as well as their daily rate information through their Web service. Each organisation would then only have to provide the WSDL for their Web services to each other. They could then in turn provide this information to their customers as easily as writing an SQL statement.

Through the use of XML the transfer of this data is straight forward. Each organisation now has access to information their customers find useful without having to go through a costly exercise of application development to allow this sharing of information.

Another reason why an organisation might choose to develop their DB2 Web services is to allow their users access to powerful stored procedures without having to develop a complex application and without having to do any kind of software roll out. These stored procedures can be accessed over the intranet through http or https and give a simple XML response which can be formatted with the use of style sheets and HTML.

Another reason why I may choose to implement DB2 Web services is if I required up to the minute information without having to worry about potential network problems. This could be achieved by getting DB2 to act as a Web service consumer automatically. What I mean by this is that the wrapped UDF could be executed automatically every other minute, and obtains the most recent currency exchange rates, stock quotes, supplier prices or weather information and inserts this information into my database. My application could then use this information without the concern for accuracy or network performance problems.

An easy way to explain all of these examples is through the use of a drawing which can be seen in Figure 5.1 below.

Page 67: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

67

Figure 5.1

1 - The SOAP UDF’s could consume external Web services every other minute triggered by a script. The data collected from these Web services is then inserted into the Web services data tables and could then be aggregated or consolidated. The database acts as a cached intermediary and allows the organisation to control the access to these external services.

2 - Internal users can access the Web services provided to them by the organisation as easily as using their intranet. This can in turn give them access to the data which has been collected from the external Web services. This also opens up the possibility of allowing their users to access stored procedures, do their data processing and execute other functions, such as user defined functions, which leads to a whole host of other DB2 functionality.

3 - External users (customers, suppliers etc.) could be provided with the required WSDL to access a set of controlled Web services provided by the organisation, without the requirement for complex application development. This allows organisations to share information and data very easily.

4 & 5- Business applications can also have access to these Web services or just the data which has been collected by the Web service consumer functions, without the user even being aware of it.

It is worth pointing out that these examples represent a hub-spoke solution pattern, with all the same business benefits. The access to external services could be done asynchronously in either a push or pull scenario. Any data which is obtained from the external services could be cleansed, aggregated or consolidated before being made available.

Page 68: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

68

However, an important point to consider is that Web services are not designed for moving large amounts of data between systems or organisations.

Following are a list of points I intend to investigate in the next few months. I intend to update this document or create a follow on document which could further influence the way in which DB2 Web services could be implemented:

WS-Security as well as the security provided by WebSphere application server. The use of a Web Services Gate Way (WSGW) with the DB2 Web service

consumer UDF’s. A possible implementation of this may look similar to Figure 5.2

Figure 5.2

Implementing all of the steps and examples I have discussed through out this document on z/OS.

Page 69: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

69

6. Security You can restrict access to Web services much as you would restrict access to Web sites that are not available to everyone. The transfer of the data can also be encrypted through the use of HTTPS. WebSphere provides many options for controlling access and for authentication. The standards for this are still emerging. Microsoft and IBM had proposed a SOAP security extension to the W3C as the mechanism for XML digital signatures. The SOAP security extension included with WebSphere Application Server 5.0.1 was intended to be a security architecture based on the SOAP Security specification, and on widely-accepted security technologies such as secure socket layer (SSL). However, as from WebSphere Application Server V5.0.2 onwards WebSphere will support the WS-Security specification (see http://www-106.ibm.com/developerworks/library/ws-secure/) for message level integrity, confidentiality and security token propagation. For further details refer to the WebSphere V5.0.2 Infocenter documentation.

Page 70: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

70

7. Troubleshooting Troubleshooting DB2 provider Web services is made simple because all errors are logged in the SystemErr.log file found in the application server error logs directory, which can be found in the following directory:

C:\WebSphere\AppServer\logs\server1

All database type errors which relate directly to the Web service will be logged here as well as any DADX errors such as syntax errors. Other error logs which should still be investigated during any troubleshooting exercise are the db2diag.log and the SystemOut.log.

Examples of some of error messages which could be found in the SystemErr.log file can be seen in Example 7.1.

Example 7.1

PROVIDER ERRORS 1. [29/09/03 11:17:33:595 BST] 5928ab7a SystemErr R DADX Database error: 29/09/03 11:17[IBM][CLI Driver][DB2/NT] SQL0104N An unexpected token "as" was found following "ESTAMP) as TIMESTAMP". Expected tokens may include: "INTO". SQLSTATE=42601 2. [02/11/03 05:15:14:499 GMT] 155a39e2 SystemErr R [Fatal Error] :90:14: The element type "query" must be terminated by the matching end-tag "</query>". org.xml.sax.SAXParseException: The element type "query" must be terminated by the matching end-tag "</query>". 3. [02/11/03 05:16:53:852 GMT] 3a7f39e0 SystemErr R com.ibm.etools.webservice.rt.framework.WORFRuntimeException: unknown operation: listSales 4. [02/11/03 05:18:25:193 GMT] 155a39e2 SystemErr R DADX Database error: 02/11/03 05:18[IBM][CLI Driver][DB2/NT] SQL0104N An unexpected token "." was found following "SELECT FROM db2das". Expected tokens may include: "FROM". SQLSTATE=42601 CONSUMER ERRORS 5. SQL0443N Routine "DB2XML.SOAPHTTPC" (specific name "SOAPHTTPVICO") has returned an error SQLSTATE with diagnostic text "Error during socket connect". SQLSTATE=38310 6. SQL0443N Routine "DB2XML.SOAPHTTPV" (specific name "SOAPHTTPVIVO") has returned an error SQLSTATE with diagnostic text "". SQLSTATE=38328

Page 71: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

71

Example 1: This was caused because of an error in the SQL statement syntax.

Example 2: This was caused because a <query> element in the DADX was not correctly closed with a </query>.

Example 3: This was caused because an operation name (listsales) was incorrectly referenced in the Index.html.

Example 4: This was caused because of an error in the SQL statement syntax.

Example 5: I received this error on many occasions and some of them I could never quite figure out, but as the error message suggests there was error during the socket connection. One of the main reasons I found for this error was because I was testing the consumer functionality on a network which used an HTTP Proxy for all outbound HTTP requests.

Currently the DB2 Web service consumer functionality and the SOAP UDF’s do not support HTTP Proxies. This has been raised as a development line item and is expected to be made available in one of the future releases. I would like to point out, that if my investigation into the use of Web Service Gateways proves to be positive this method may be a way to get around this problem, although I feel that HTTP proxies should be supported.

Example 6: This error was caused when the incorrect parameter was passed to the external Web service.

More information can be found in the IBM DB2 Information Integrator Developer’s Guide.

Page 72: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

72

8. Appendix

8.1. How to apply a fix pack to WebSphere Application Server Fix packs provides a number of important fixes for WebSphere. Obtain the fix you would like to apply to WAS and unzip it to c:\temp\was

Make sure that server1 Application Server is not running before applying the Fix Pack.

Start a Windows command prompt and navigate to the Application Server install directory, C:\WebSphere\AppServer\bin.

Prepare the WebSphere environment by running the batch program setupCmdLine.bat. This will set some environment variables required by the Fix Pack install process.

Still within the command prompt, change to the directory C:\temp\was and run the command updateWizard.bat. This batch program will copy some files and launch the update installer wizard.

Wait a few seconds for the Update Installation Wizard to start. On the Welcome panel, select Next.

The only product found on the machine should be IBM WebSphere Application Server V5.0.*, make sure it is selected and select Next.

Make sure the option Install fix packs is selected and select Next. Make sure the fix pack directory is set to c:\temp\was\fixpacks and select

Next. Make sure the install button is selected, the fix pack name is was50_fp*_win

and the Status is Not Installed. Select Next. Make sure both IBM HTTP Server and Embedded Messaging options are

selected and the directories are set to {install_directory}\IBMHttpServer and {install_directory}\IBM\WebSphere MQ. Select Next.

On the Confirmation panel select Next, to start the Fix Pack install. Once the install completes, select Finish to exit the wizard.

Verify the fix pack has been applied correctly.

Start a Windows command prompt and navigate to the Network Deployment install directory, C:\WebSphere\ApplicationServer\bin

Run the command VersionInfo.bat and ensure the reported Installed Product Version number is 5.0.*.

Page 73: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

73

8.2. Installing Microsoft’s free .NET compiler Microsoft is offering a free .NET compiler (and other .NET development tools) on their website. This is particularly useful if you want to compile DB2 Stored Procedures in a Windows environment, but don't want to pay for a copy of Visual Studio or a different IDE/compiler. There are two products you need to obtain in order for this to work. [They also MUST be installed in the order presented here.]

The first is the ".Net Framework Version 1.1 Redistributable Package" , which can be found here: http://www.microsoft.com/downloads/details.aspx?FamilyId=262D25E3-F589-4842-8157-034D1E7CF3A3&displaylang=en

The second is the ".NET Framework SDK Version 1.1" , which can be found here: http://www.microsoft.com/downloads/details.aspx?FamilyID=9b3a2ca6-3647-4070-9f41-a333c6b9181d&displaylang=en

Once these two products have been installed, you must modify the DB2_SQLROUTINE_COMPILER_PATH environment variable.

If you installed using the default directory suggestions use the following command: • db2set DB2_SQLROUTINE_COMPILER_PATH="C:\Program

Files\Microsoft.NET\SDK\v1.1\Bin\sdkvars.bat" Once you stop and restart the instance, you can test whether the installation was successful by connecting to a database and creating a dummy Stored Procedure such as: db2 create procedure p1 begin end If you received no error messages after executing this statement, then everything should be set up accordingly.

Page 74: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

74

9. References a. IBM DB2 Information Integrator Developer’s Guide Version 8 at http://www-

1.ibm.com/support/docview.wss?rs=845&context=SS4NVZ&context=SSSGP4&context=SSPMTE&q=&uid=swg27004163&loc=en_US&cs=utf-8&lang=en+en

b. Bart Steegmans from ITSO provided a chapter on “Web Services in DB2” from a draft redbook

c. Web Services Wizardry with WebSphere Studio Application Developer at http://devworks.krcinfo.com/WebForms/ProductDetails.aspx?ProductID=0738423351 - Ueli Wahli, Mark Tomlinson, Olaf Zimmermann, Wouter Deruyck, Denise Hendriks

d. Tutorial "Building Web Services with WORF and DB2 XML Extender" at http://www-106.ibm.com/developerworks/edu/dm-dw-dm-0304balani-i.html

Page 75: DB2® Web services for DB2 Practitioners - IBM · PDF fileDB2® Web services for DB2 Practitioners Author: ... DB2 as a Web service provider ... it will explain how the DB2 XML extender

DB2 Web services for DB2 Practitioners

75

10. Relevant Resources a. Web Services Description Language (WSDL) 1.1 -

http://www.w3.org/TR/wsdl b. Web services specifications -

http://www.ibm.com/developerworks/webservices/library/ws-spec.html

c. Start building Web services today - http://www.ibm.com/developerworks/offers/ws-speed-start/

d. Developer roadmap - http://www.ibm.com/developerworks/offers/ws-speed-start/

e. Web services with DB2 UDB V8.1 - http://www.ibm.com/developerworks/offers/ws-speed-start/db2.html

f. UDDI.org - http://www.uddi.org/ g. XML in 10 points - http://www.w3.org/XML/1999/XML-in-10-

points.html