Spicing Up Your Web Services with XSLT

Tuesday Feb 10th 2009 by Paul Zikopoulos
Share:

The first thirteen parts of this series introduced some of the many features available within the IBM Data Studio integrated development environment (IDE) that's available for use with the IBM data servers. This installment explains how to apply Extensible Stylesheet Language Transformations (XSLT) to your Web services.

In the first thirteen parts of this series, I’ve introduced you to some of the many features available within the IBM Data Studio integrated development environment (IDE) that’s available for use with the IBM data servers. Specifically, I’ve shown you how to set up and use database connection objects, how to generate an overview diagram of your database architecture, how to build OLE DB functions that can be used to easily integrate data from external data sources that have an OLE DB provider, how to create an SQL statement using either the SQL Builder or the SQL Editor in IBM Data Studio, and how to take an SQL statement and quickly turn it into a stored procedure. I’ve also shown you how to wrap both an SQL statement and a stored procedure as a Web service. Most recently, I showed you how to test your Web service using the Web Services Explorer that’s integrated into IBM Data Studio or through a Web browser using the Web Services Explorer.

In this article, I’m going to show you how to apply Extensible Stylesheet Language Transformations (XSLT) to your Web services. The output of the Web service you created earlier in this series was XML. For example, when executing the FEMALEPERSONNEL Web service from a representational state transfer (REST) interface in a Web browser, the output looked like this:

Click for larger image
The output of the Web service you created earlier in this series was XML

As you can see, business logic was executed through a URL-based invocation of a Web service, but the output is just plain XML. XML isn’t a presentation language; rather it’s a data semantic language. Using XSLT, you can transform XML into all sorts of different output formats. For example, perhaps you want the output format of this data to be a Really Simple Syndication (RSS) feed, hypertext markup language (HTML)Braille text, or practically anything. In this article, we’re going to create a new Web service and transform the output such that it displays as a nicely formatted HTML Web page using XSLT.

Getting ready for this article

I assume in this article that you completed all the steps in “Part 12: Testing your Web Service using the Web Services Explorer”. From there, all you need to do in order to follow the steps in this article is ensure that the application server you defined and deployed your Web services to in Part 11 is started and running such that the Servers tab looks like this:

the Servers tab

I also assume that your Data Project Explorer view looks similar to this:

Data Project Explorer view

Finally, I assume you have access to the Mozilla Firefox Internet browser.

What is Extensible Stylesheet Language Transformation?

Extensible Stylesheet Language Transformation (XSLT) is an XML-based technology used to transform the structure of XML documents. In fact, the term stylesheet is part of the XSLT name because of its ability to change the content of the XML document – think cascading stylesheets (CSS) with HTML and you get the point.

XSLT is designed for use as part of the Extensible Stylesheet Language (XSL). XML Path Language (XPath) is an XSL sub-language that is designed to be used with XSLT. It is used for identifying or addressing parts of a source XML document. Every node within an XML document can be uniquely identified and located using the syntax defined for XPath.

One of the coolest things about XSLT is the fact that you can shape your XML into almost any output you want. For example, perhaps an XML response envelope from your Web service returns some XML data. Using XSLT, you could transform this data for output on a Web page in HTML. Another example of the use of XSLT is to screen-scrape an XHTML page and distribute that content to an RSS or Atom Syndication Format (ASF) feed.

When you configure XSL transformations for your Web services using a REST GET invocation, the message flow for a Web service operation follows these steps:

1.  A client application sends an HTTP GET (TEXT/XML) message that accesses an operation in a Web service. The message is tagged according to a custom XML schema.

2.  The message is transformed so that it is tagged according to the default XML schema.

3.  The Web service receives the message and passes to the database the SQL statement or stored procedure call that is in the operation.

4.  The Web service receives the response from the database and packages the response in an XML message that is tagged according to the default XML schema for the operation.

5.  The message is transformed so that it is either in XML (and is tagged according to the custom XML schema), or in a non-XML format, such as HTML or plain text.

6.  The Web service sends the response to the client application.

This process is shown in the following figure:

configure XSL transformations for your Web services using a REST GET invocation

As you can see in the previous figure, IBM Data Web Services gives you options to apply XSLT to incoming XML messages and outgoing XML messages. (In this article, the example shows you how to apply an XSLT transformation to the outbound XML message.)

In this series, I’m illustrating how to build Web services using a bottom-up approach where the business logic (in this case, an SQL statement or a stored procedure) has been built and the intent is to expose this logic as a Web service. In a top-down approach, you start with a service specification (for example, a WSDL file) and then implement the underlying code to match that specification. By applying XSLT to input service messages, in many cases, you can map the service format of the bottom-up style messages to the top-down design. This alleviates some of the top-down service format requirements while allowing you to develop bottom-up Web services; of course, this is all done with XSLT, only in this case on an input message.

Depending on how you build your Web service (for example, a SOAP service), this process varies somewhat; refer to the IBM Data Studio Information Center or integrated help for more information.

Here are some excerpts of the XSLT document that you will be using in this example:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0"
    xmlns:xalan="http://xml.apache.org/xslt" 
    xmlns:tns="http://www.w3.org/1999/xhtml">
    
	<xsl:output method="html" version="1" encoding="UTF-8" omit-xml-declaration="yes" standalone="yes" indent="yes" />

As you can see, the excerpts of this XSLT document show you that XSLT documents are indeed written in XML. You can also see that this XSLT document will transform the XML into HTML, as indicated by the xsl:output element where the method attribute is set to "html". Perhaps you are transforming an XML document into an RSS feed for which you would define an output clause similar to this: <xsl:output method="xml" encoding="UTF-8" media-type="application/rss+xml"/>

<xsl:template match="/">
  	<html><body>
   	<h2>Employee Record</h2>
	<xsl:element name="form">
  	<xsl:attribute name="action">http://localhost:8080/DemoMyWebService/rest/Demo/updateEmp</xsl:attribute>
  	<xsl:attribute name="method">POST</xsl:attribute>
  	<table border="1">
  	<tr>
  	<th rowspan="12">  	  
  	   <img>
  	   	<xsl:attribute name="src">data:image/gif;base64,<xsl:value-of select="//row/PICTURE/text()"/></xsl:attribute>
  	   </img>
  	</th>

As you further inspect the sample XSLT document used in this article, you can see how the previous code shapes the input XML data from our Web service into an HTML output. The following code tells an XSLT processor how to take the <EMPNO> XML element and transform it into HTML.

 	<td>EMPNO:</td>
  	<td>
        <xsl:value-of select="//row/EMPNO/text()"/>
        <xsl:element name="input">
        	<xsl:attribute name="value">
        	<xsl:value-of select="//row/EMPNO/text()"/></xsl:attribute>
        	<xsl:attribute name="type">hidden</xsl:attribute>
           	<xsl:attribute name="name">empno</xsl:attribute>
       	</xsl:element>
    </td>    

You can see how XML technologies are used with XSLT by noticing the XPath notation of the textual value of the <EMPNO>: //row/EMPNO/text().

Of course, all of the transformed data will be displayed in table format because all of the transformation logic resides within the following tags:

<table border="1">...</table>

It’s outside the scope of this article to delve into the depths of transformations with XML data; however, the W3 Schools Web site has some terrific resources on this (and many other) XML-related technologies. Check out http://www.w3schools.com/xsl/ for more information.

Web services and XSLT: an IBM Data Studio example

To create a Web service and apply an XSLT transformation to the XML output, perform the following steps:

1.  Build a piece of business logic that you want to expose as a Web service. For this example, build an SQL statement, called GetEmp, which returns details for a specific employee by joining columns from the EMPLOYEE, EMP_PHOTO, and EMP_RESUME tables.

The following SQL statement takes EMPNO as an input parameter and returns details for a specific employee by joining data from the three aforementioned tables that are part of the SAMPLE database:

SELECT employee.*, 
  (SELECT resume FROM emp_resume 
    WHERE emp_resume.empno = :empno AND 
          emp_resume.resume_format = 'ascii') AS resume, 
  (SELECT picture FROM emp_photo 
    WHERE emp_photo.empno = :empno AND 
          emp_photo.photo_format = 'gif') AS picture 
  FROM employee 
    WHERE employee.empno = :empno

Note: If you followed along in this series, you’ve likely created the SAMPLE database that’s provided with a DB2 installation; however, not all parts in this series use this database. If you don’t have the SAMPLE database, you can create it by entering the db2sampl command in your operating system command prompt. The EMPLOYEE EMP_PHOTO, and EMP_RESUME tables schemas looks like this:

Click for larger image
The EMPLOYEE table's schema

I used the Overview Diagram feature in IBM Data Studio (introduced in “Part 3: Overview diagrams - The Basics” and “Part 4 Overview diagrams – The Rest of the Story”). You can see that IBM Data Studio automatically detected the business relationship between the EMPLOYEE and DEPARTMENT tables, and gives you details as to the underlying columns of these tables. You can see from the previous figure and SQL statement that this SQL statement returns relational data, as well as data from a character large object (CLOB) column, and a binary large object (BLOB) column. This varying data types will present a challenge (as you will see) for the XML output of our Web service, and XSLT can be used to solve this problem.

Save this SQL statement as GetEmp such that the Data Project Explorer looks like this:

Save this SQL statement as GetEmp such that the Data Project Explorer looks like this

If you need help with this step, refer to “Part 6: Building an SQL Statement” (if you want to use the SQL Editor) or “Part 7: The SQL Builder’s Development Accelerators” (if you want to use the SQL Builder).

2.   Create a new Web service project, called HRTOOL, and drag the GetEmp SQL statement to this folder, as shown below:

2.	Create a new Web service project, called HRTOOL, and drag the GetEmp SQL statement to this folder

In the middle of the previous figure, you can see that the project from which you launched the New Web Service window becomes the default project (as shown in the Project field) for the Web service. You can use the Project drop-down list to select a different project, or even create a new project for this Web service by clicking New.

If you need help with this step, or the next two steps, refer to “Part 11: Transforming Business Logic into Web services”.

3.  Ensure that the target application server is started and build the Web service such that it can be invoked using the REST protocol, as follows:

Ensure that the target application server is started and build the Web service such that it can be invoked using the REST protocol

4.  Locate the URL of the Web service by launching the Web Service Explorer and getting the URL of the Web Services Description Language (WSDL) document (the highlighted portion below):

4.	Locate the URL of the Web service by launching the Web Service Explorer and getting the URL of the Web Services Description Language (WSDL) document

5.  Locate the URL to invoke your Web service using the GET method of a RESTful invocation (and copy the highlighted text within the quotes in the following figure):

Locate the URL to invoke your Web service using the GET method of a RESTful invocation

6.  Paste the URL from the previous figure into your Web browser’s address field and append the name of the Web service (getEmp) and a value of 000130 for the EMPNO parameter such that the URL looks like this: http://localhost:8080/DatabaseJournalProjectSOA_FEMALEPERSONNEL/rest/HRTOOL/getEmp?empno=000130.

Leave this Web browser session open for the remainder of this article.

The output in your Web browser should look like:

The output in your Web browser

You can see that the Web service was properly executed. Note that it returns the data for employee 000130 from the EMPLOYEE table:

the Web service was properly executed

The output of the RESUME CLOB column in the EMP_RESUME table is properly displayed (since it is character data):

The output of the RESUME CLOB column in the EMP_RESUME table is properly displayed

However, notice that the output of the PICTURE BLOB column in the EMP_PHOTO table isn’t properly displayed:

notice that the output of the PICTURE BLOB column in the EMP_PHOTO table isn’t properly displayed

Obviously, this isn’t the way you want to display your data in a Human Resources application, but we know we have the data; it’s just a matter of formatting it, and that is where XSLT comes into play.

7.  Associate an XSLT transform for the XML-based output message of the Web service as follows:

a.  Select the Web service you created, right-click, and select Manage XSLT:

Select the Web service you created, right-click, and select Manage XSLT

b.  The Configure XSL Transformations window opens. Click the Browse button associated with the Transformation of Output Messages box and ensure the XSL file field displays the location of this getEmp_HTML_Response.xsl file, as shown below:

The Configure XSL Transformations window

You can see in the previous figure that you can transform any input XML message using the Transformation of Input Messages field.

If you want to clear a transformation for an input or output XML message, simply click the corresponding Reset the select file button ().

The Generate Default button is used to generate a default XML schema for the input messages and the output messages. For example, if you click this button, IBM Data Studio will generate the following XSD document:

<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema" 
	xmlns:xsd="http://www.w3.org/2001/XMLSchema" targetNamespace="urn:example" xmlns:tns="urn:example">
  <element name="getEmp">
    <complexType>
      <sequence>
        <element name="empno" type="xsd:string" nillable="true"/>
      </sequence>
    </complexType>
  </element>
  <element name="getEmpResponse">
    <complexType>
      <sequence>
        <element maxOccurs="unbounded" minOccurs="0" name="row">
          <complexType>
            <sequence>
              <element name="EMPNO" type="xsd:string"/>
              <element name="FIRSTNME" type="xsd:string"/>
              <element name="MIDINIT" type="xsd:string" nillable="true"/>
              <element name="LASTNAME" type="xsd:string"/>
              <element name="WORKDEPT" type="xsd:string" nillable="true"/>
              <element name="PHONENO" type="xsd:string" nillable="true"/>
              <element name="HIREDATE" type="xsd:date" nillable="true"/>
              <element name="JOB" type="xsd:string" nillable="true"/>
              <element name="EDLEVEL" type="xsd:short"/>
              <element name="SEX" type="xsd:string" nillable="true"/>
              <element name="BIRTHDATE" type="xsd:date" nillable="true"/>
              <element name="SALARY" type="xsd:decimal" nillable="true"/>
              <element name="BONUS" type="xsd:decimal" nillable="true"/>
              <element name="COMM" type="xsd:decimal" nillable="true"/>
              <element name="RESUME" type="xsd:string" nillable="true"/>
              <element name="PICTURE" type="xsd:base64Binary" nillable="true"/>
            </sequence>
          </complexType>
        </element>
      </sequence>
    </complexType>
  </element>
</schema>

c.  Click Finish.

8.  Rebuild the Web service using the same steps and options as you did in Step 3.

9.   Return to the Web browser session where you invoked your Web service in Step 6 and press Enter. This action will once again invoke the same Web service and pass it EMPNO=000130 as the input parameter.

Your Web browser window should now look like this:

invoke the same Web service and pass it to the EMPNO=000130 as the input parameter

You can see that your Web service now takes the XML and transforms it into HTML, which is shown in the previous figure: quite a transformation!

Note: When I tested the steps in this article with Microsoft Internet Explorer (IE) as the Web browser, I noticed that the picture (BLOB) column did not render correctly. I’m currently investigating this nuance.

Wrapping it all up

In this article, I showed you how to further extend the point-and-click framework for building Web services provided by IBM Data Studio by applying an XSLT transformation to the output XML message generated by the Web service. Specifically, I showed you how to take the output of a Web service and convert it to HTML for display in a Web browser.

(The author would like to acknowledge the help and teachings of Michael Pauser, and IBM developer in the Silicon Valley lab that is the true mastermind behind the simplicity of IBM Data Web Services.)

» See All Articles by Columnist Paul C. Zikopoulos

Trademarks

IBM and DB2 are trademarks or registered trademarks of International Business Machines Corporation in the United States, other countries, or both.

Microsoft is a trademark of Microsoft Corporation in the United States, other countries, or both.

Linux is a registered trademark of Linus Torvalds in the United States, other countries, or both.

Other company, product, or service names may be trademarks or service marks of others.

Copyright International Business Machines Corporation, 2009.

 

Disclaimers

The opinions, solutions, and advice in this article are from the author’s experiences and are not intended to represent official communication from IBM or an endorsement of any products listed within. In addition, the code sample is provided for illustrative purposes only and there is no express guarantee of quality of operation. Neither the author nor IBM is liable for any of the contents or downloads in this article. The accuracy of the information in this article is based on the author’s knowledge at the time of writing.

Any references in this information to non-IBM Web sites are provided for convenience only and do not in any manner serve as an endorsement of those Web sites. The materials at those Web sites are not part of the materials for this IBM product and use of those Web sites is at your own risk.

Share:
Home
Mobile Site | Full Site
Copyright 2017 © QuinStreet Inc. All Rights Reserved