Tecnologías XML / XSLT / Recetario XSLT / Recetas para aplicaciones XSLT verticales / SOAP: documentación desde WSDL
(Extracto de «XSLT Kochbuch» de Sal Mangano)
Problema
Utiliza SOAP y WSDL para un sitio comercial orientado a servicios y desea dar a los desarrolladores información completa y pertinente.
Solución
Construya un servidor de documentación WSDL: un servicio que describe servicios, o metaservicio. El ejemplo utiliza un CGI en Perl que aplica XSLT a un archivo que describe todos los servicios de la empresa. Llama al procesador XSLT mediante una llamada system. Este método rudimentario sirve para prototipos, no para producción. Utilice mejor los módulos Perl XML::LibXML y XML::LibXSLT. Mejor aún, una arquitectura de servidor XSLT como Cocoon. La sencillez permite centrarse en XSLT y WSDL en lugar de CGI.
Un CGI genera el inicio con servicios y puertos, explicados abajo. Esta interfaz Perl CGI llama a Saxon:
#!/usr/bin/perl
print "Content-type: text/html\n\n" ;
system "saxon StockServices.wsdl wsdlServiceList.xslt" ;La transformación crea un formulario de servicios, puertos, enlaces y tipos de puerto:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/" exclude-result-prefixes="wsdl soap http mime">
<xsl:output method="html"/>
<xsl:template match="/">
<html>
<head>
<title>Verfügbare Dienste von ACME Webservices GmbH</title>
<xsl:comment>WSDL-Dokumentation: Erzeugt mit wsdlServiceList.xslt</xsl:comment>
</head>
<body>
<xsl:apply-templates/>
</body>
</html>
</xsl:template>
<xsl:template match="wsdl:definitions">
<h1>Verfügbare Dienste von ACME Webservices GmbH</h1>
<br/>
<form name="QueryServiceForm" method="post" action="QueryService.pl">
<table>
<tbody>
<tr>
<td>Dienste</td>
<td>
<select name="service">
<option value="ALL">ALLE</option>
<xsl:apply-templates select="wsdl:service"/>
</select>
</td>
</tr>
<tr>
<td>Ports</td>
<td>
<select name="port">
<option value="ALL">ALLE</option>
<xsl:apply-templates select="wsdl:service/wsdl:port"/>
</select>
</td>
</tr>
<tr>
<td>Bindings</td>
<td>
<select name="binding">
<option value="ALL">ALLE</option>
<xsl:apply-templates select="wsdl:binding"/>
</select>
</td>
</tr>
<tr>
<td>Port-Typen</td>
<td>
<select name="portType">
<option value="ALL">ALLE</option>
<xsl:apply-templates select="wsdl:portType"/>
</select>
</td>
</tr>
</tbody>
</table>
<br/>
<button type="submit" name="submit">Dienste abfragen</button>
</form>
</xsl:template>
<xsl:template match="wsdl:service | wsdl:port | wsdl:binding | wsdl:portType">
<option value="{@name}"><xsl:value-of select="@name"/></option>
</xsl:template>
</xsl:stylesheet>El usuario elige una combinación de servicio, puerto, enlace y tipo de puerto. Otro pequeño CGI extrae la entrada e inicia la segunda transformación:
#!/usr/bin/perl
use warnings;
use strict;
use CGI qw(:standard);
my $query = new CGI ;
my $service = $query->param('service');
my $port = $query->param('port');
my $binding = $query->param('binding');
my $portType = $query->param('portType');
print $query->header('text/html');
system "saxon StockServices.wsdl QueryService.xslt service=$service port=$port binding=$binding portType=$portType"Selecciona los servicios coincidentes y muestra detalles. Primero normaliza parámetros, pues una referencia de atributo puede contener un espacio de nombres en forma de prefijo mientras el atributo @name del elemento referenciado no lo contiene. Lo mismo se aplica a las claves:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xslt [
<!ENTITY TNSPREFIX "'acme:'">
]>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xsd="http://www.w3.org/2000/10/XMLSchema" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/">
<!-- Abfrageparameter -->
<xsl:param name="service" select="'ALL'"/>
<xsl:param name="port" select="'ALL'"/>
<xsl:param name="binding" select="'ALL'"/>
<xsl:param name="portType" select="'ALL'"/>
<!-- Eine Technik (bzw. ein Hack), um Variablen zu leeren, wenn der entsprechende Parameter bzw. die Verkettung von &TNSPREFIX mit dem Parameter gleich ALL ist. Beispiel: number($service = 'ALL') * 99999 + 1 ergibt 1, wenn $service ungleich 'ALL' ist, aber 100000, wenn doch, und geht dann über die Länge des Strings hinaus, wodurch substring einen leeren Wert ergibt. All das hier dient der Vereinfachung von Kreuzverweisen. -->
<xsl:variable name="serviceRef" select="substring(concat(&TNSPREFIX;,$service),number($service = 'ALL') * 99999 + 1)"/>
<xsl:variable name="portRef" select="substring(concat(&TNSPREFIX;,$port),number($port = 'ALL') * 99999 + 1)"/>
<xsl:variable name="bindingRef" select="substring(concat(&TNSPREFIX;,$binding),number($binding = 'ALL') * 99999 + 1)"/>
<xsl:variable name="portTypeRef" select="substring(concat(&TNSPREFIX;,$portType),number($portType = 'ALL') * 99999 + 1)"/>
<!-- Diese Schlüssel vereinfachen und beschleunigen die Abfragen -->
<xsl:key name="bindings_key" match="wsdl:binding" use="concat(&TNSPREFIX;,@name)"/>
<xsl:key name="portType_key" match="wsdl:portType" use="concat(&TNSPREFIX;,@name)"/>
<xsl:output method="html"/>
<xsl:template match="/">
<html>
<head>
<title>ACME Web Services, Inc. Query Result</title>
<xsl:comment>WSDL Documentation: Generated by wsdlServiceList.xslt</xsl:comment>
</head>
<body>
<xsl:apply-templates select="wsdl:definitions"/>
</body>
</html>
</xsl:template>Guarde los resultados en una variable y compruebe su valor normalizado. Si está vacío, no hay coincidencias y se muestra un mensaje. La consulta es compleja porque el portType del servicio exige dos saltos: al enlace y después a su tipo de puerto.
<xsl:template match="wsdl:definitions">
<xsl:variable name="result">
<!-- Abfrage von Diensten, die zu den Abfrageparametern passen. Die portType-Übereinstimmung ist der einzig komplizierte Teil. Wir müssen vom Dienst-Port zum Binding und dann zum Binding-Typ traversieren, um eine Übereinstimmung zu erzielen. Deswegen die verschachtelten Aufrufe von key( ).-->
<xsl:apply-templates select="wsdl:service[(not($serviceRef) or @name = $service) and (not($portRef) or wsdl:port/@name = $port) and (not($bindingRef) or wsdl:port/@binding = $bindingRef) and (not($portTypeRef) or key('portType_key',key('bindings_key',wsdl:port/@binding)/@type)/@name = $portType)]"/>
</xsl:variable>
<xsl:choose>
<xsl:when test="normalize-space($result)">
<xsl:copy-of select="$result"/>
</xsl:when>
<xsl:otherwise>
<p><b>No Matching Services Found</b></p>
</xsl:otherwise>
</xsl:choose>
</xsl:template>El resto muestra WSDL en tablas HTML. Un servicio puede tener varios puertos: compruebe su correspondencia con los parámetros:
<xsl:template match="wsdl:service" mode="display">
<h1><xsl:value-of select="@name"/></h1>
<p><xsl:value-of select="wsdl:documentation"/></p>
<table border="1" cellpadding="5" cellspacing="0" width="600">
<tbody>
<xsl:apply-templates select="wsdl:port[(not($portRef) or @name = $port) and (not($bindingRef) or @binding = $bindingRef)]" mode="display"/>
</tbody>
</table>
</xsl:template>Una mediante estas claves puertos con enlaces y enlaces con tipos de puerto:
<xsl:template match="wsdl:port" mode="display">
<tr>
<td style="font-weight:bold" colspan="2" align="center">Port</td>
</tr>
<tr>
<td colspan="2"><h3><xsl:value-of select="@name"/></h3></td>
</tr>
<tr>
<td style="font-weight:bold" width="50">Binding</td>
<td><xsl:value-of select="substring-after(@binding,':')"/></td>
</tr>
<tr>
<td style="font-weight:bold" width="50">Address</td>
<td><xsl:value-of select="soap:address/@location"/></td>
</tr>
<tr>
<th colspan="2" align="center">Operations</th>
</tr>
<xsl:apply-templates select="key('bindings_key',@binding)" mode="display"/>
</xsl:template>
<xsl:template match="wsdl:binding" mode="display">
<xsl:apply-templates select="key('portType_key',@type)" mode="display">
<xsl:with-param name="operation" select="wsdl:operation/@name"/>
</xsl:apply-templates>
</xsl:template>
<xsl:template match="wsdl:portType" mode="display">
<xsl:param name="operation"/>
<xsl:for-each select="wsdl:operation[@name = $operation]">
<tr>
<td colspan="2"><h3><xsl:value-of select="@name"/></h3></td>
</tr>
<xsl:if test="wsdl:input">
<tr>
<td style="font-weight:bold" width="50">Input</td>
<td><xsl:value-of select="substring-after(wsdl:input/@message,':')"/></td>
</tr>
<xsl:variable name="msgName" select="substring-after(wsdl:input/@message,':')"/>
<xsl:apply-templates select="/*/wsdl:message[@name = $msgName]" mode="display"/>
</xsl:if>
<xsl:if test="wsdl:output">
<tr>
<td style="font-weight:bold" width="50">Output</td>
<td><xsl:value-of select="substring-after(wsdl:output/@message,':')"/></td>
</tr>
<xsl:variable name="msgName" select="substring-after(wsdl:output/@message,':')"/>
<xsl:apply-templates select="/*/wsdl:message[@name = $msgName]" mode="display"/>
</xsl:if>
</xsl:for-each>
</xsl:template>
<xsl:template match="wsdl:message" mode="display">
<xsl:variable name="dataType" select="substring-after(wsdl:part[@name='body']/@element,':')"/>
<tr>
<td colspan="2">
<xsl:apply-templates select="/*/wsdl:types/*/*[@name=$dataType]" mode="display">
<xsl:with-param name="initial-newline" select="false( )"/>
</xsl:apply-templates>
</td>
</tr>
</xsl:template>Este código muestra el esquema XSD de mensajes como XML dentro de HTML. Probablemente es lo más útil para documentar los tipos de datos asociados con mensajes de entrada y salida:
<xsl:template match="*" mode="display">
<xsl:param name="initial-newline" select="true( )"/>
<xsl:if test="$initial-newline">
<xsl:call-template name="newline"/>
</xsl:if>
<!-- öffnendes Tag -->
<a><</a>
<a><xsl:value-of select="name(.)" /> </a>
<!-- Ausgabeattribute -->
<xsl:for-each select="@*">
<a><xsl:text> </xsl:text><xsl:value-of select="name(.)" /> </a>
<a>="</a>
<xsl:value-of select="." />
<a>"</a>
</xsl:for-each>
<xsl:choose>
<xsl:when test="child::node( )">
<!-- schließe Start-Tag -->
<a>></a>
<xsl:apply-templates mode="display"/>
<xsl:call-template name="newline"/>
<!-- schließendes Tag -->
<a><</a>
<a>/<xsl:value-of select="name(.)" /></a>
</xsl:when>
<xsl:otherwise>
<a>/</a>
</xsl:otherwise>
</xsl:choose>
<a>></a>
</xsl:template>
<!-- Füge Zeilenende hinzu und rücke dann je nach Tiefe im Schema ein -->
<xsl:template name="newline">
<br/>
<xsl:for-each select="ancestor::xsd:*[not(self::xsd:schema)]">
<xsl:text>    </xsl:text>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>Discusión
La sección Transformar XML a HTML presentó un repositorio de metadatos de mensajes entre cliente y servidor. WSDL proporciona esa sintaxis para servicios web. Puede generar código y documentación; el ejemplo se centra en esta última.
WSDL describe las relaciones servicio/puerto. Un puerto es un extremo que combina enlace y dirección de red. Un enlace define protocolo y formato de datos concretos para un tipo de puerto. El tipo define un conjunto abstracto de operaciones. Una operación es una acción definida por un mensaje con datos, normalmente descritos en XSD. Este fragmento describe servicios de Acme Corporation:
<definitions name="StockServices" targetNamespace="http://acme.com/services.wsdl" xmlns:acme="http://acme.com/services.wsdl" xmlns:xsd1="http://acme.com/stockquote.xsd" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns="http://schemas.xmlsoap.org/wsdl/">WSDL utiliza XSD por defecto para los tipos de mensajes intercambiados:
<types>
<schema targetNamespace="http://acme.com/services.xsd" xmlns="http://www.w3.org/2000/10/XMLSchema">
<element name="Ticker">
<complexType>
<all>
<element name="tickerSymbol" type="string"/>
</all>
</complexType>
</element>
<element name="TradePrice">
<complexType>
<all>
<element name="price" type="float"/>
</all>
</complexType>
</element>
<element name="CompanyName">
<complexType>
<all>
<element name="company" type="string"/>
</all>
</complexType>
</element>
<element name="ServicesInfo">
<complexType>
<sequence>
<element name="Services">
<complexType>
<sequence>
<element name="Service" type="string" minOccurs="0" maxOccurs="unbounded"/>
</sequence>
</complexType>
</element>
<element name="Ports">
<complexType>
<sequence>
<element name="Port" type="string" minOccurs="0" maxOccurs="unbounded"/>
</sequence>
</complexType>
</element>
<element name="Bindings">
<complexType>
<sequence>
<element name="Binding" type="string" minOccurs="0" maxOccurs="unbounded"/>
</sequence>
</complexType>
</element>
<element name="PortTypes">
<complexType>
<sequence>
<element name="Port" type="string" minOccurs="0" maxOccurs="unbounded"/>
</sequence>
</complexType>
</element>
</sequence>
</complexType>
</element>
<element name="ServicesQuery">
<complexType>
<all>
<element name="Service" type="string"/>
<element name="Port" type="string"/>
<element name="Binding" type="string"/>
<element name="PortType" type="string"/>
</all>
</complexType>
</element>
<element name="ServicesResponse">
<complexType>
<sequence>
<any/>
</sequence>
</complexType>
</element>
</schema>
</types>Los mensajes asocian nombres y tipos y describen lo comunicado:
<message name="GetLastTradePriceInput">
<part name="body" element="xsd1:Ticker"/>
</message>
<message name="GetLastTradePriceOutput">
<part name="body" element="xsd1:TradePrice"/>
</message>
<message name="GetCompanyInput">
<part name="body" element="xsd1:Ticker"/>
</message>
<message name="GetCompanyOutput">
<part name="body" element="xsd1:CompanyName"/>
</message>
<message name="GetTickerInput">
<part name="body" element="xsd1:CompanyName"/>
</message>
<message name="GetTickerOutput">
<part name="body" element="xsd1:Ticker"/>
</message>
<message name="GetServicesInput"/>
<message name="GetServicesOutput">
<part name="body" element="xsd1:ServicesInfo"/>
</message>
<message name="QueryServicesInput">
<part name="body" element="xsd1:ServicesQuery"/>
</message>
<message name="QueryServicesOutput">
<part name="body" element="xsd1:ServicesRespose"/>
</message>Los tipos precisan las operaciones disponibles. Aquí, dos tipos cubren cotizaciones y descubrimiento de servicios. El ejemplo implementa descubrimiento, normalmente utilizado por otro programa en lugar de un navegador:
<portType name="StockPortType">
<operation name="GetLastTradePrice">
<input message="acme:GetLastTradePriceInput"/>
<output message="acme:GetLastTradePriceOutput"/>
</operation>
<operation name="GetTickerFromCompany">
<input message="acme:GetTickerInput"/>
<output message="acme:GetCompanyOutput"/>
</operation>
<operation name="GetCompanyFromTicker">
<input message="acme:GetCompanyInput"/>
<output message="acme:GetTickerOutput"/>
</operation>
</portType>
<portType name="ServicePortType">
<operation name="GetServices">
<input message="acme:GetServicesInput"/>
<output message="acme:GetServicesOutput"/>
</operation>
<operation name="QueryServices">
<input message="acme:QueryServicesInput"/>
<output message="acme:QueryServicesOutput"/>
</operation>
</portType>Los enlaces asocian operaciones y protocolos, aquí SOAP:
<binding name="StockQuoteSoapBinding" type="acme:StockPortType">
<soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
<operation name="GetLastTradePrice">
<soap:operation soapAction="http://acme.com/GetLastTradePrice"/>
<input>
<soap:body use="literal"/>
</input>
<output>
<soap:body use="literal"/>
</output>
</operation>
</binding>
<binding name="StockTickerSoapBinding" type="acme:StockPortType">
<soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
<operation name="GetTickerFromCompany">
<soap:operation soapAction="http://acme.com/GetTickerSymbol"/>
<input>
<soap:body use="literal"/>
</input>
<output>
<soap:body use="literal"/>
</output>
</operation>
</binding>
<binding name="StockNameSoapBinding" type="acme:StockPortType">
<soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
<operation name="GetCompanyFromTicker">
<soap:operation soapAction="http://acme.com/GetCompanyName"/>
<input>
<soap:body use="literal"/>
</input>
<output>
<soap:body use="literal"/>
</output>
</operation>
</binding>
<binding name="ServiceListSoapBinding" type="acme:ServicePortType">
<soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
<operation name="GetServices">
<soap:operation soapAction="http://acme.com/GetServices"/>
<input>
<soap:body use="literal"/>
</input>
<output>
<soap:body use="literal"/>
</output>
</operation>
</binding>Dos servicios exponen cotizaciones y descubrimiento. Observe cómo organizan puertos para indicar funciones:
<service name="StockInfoService">
<documentation>Provides information about stocks.</documentation>
<port name="StockQuotePort" binding="acme:StockQuoteSoapBinding">
<soap:address location="http://acme.com/stockquote"/>
</port>
<port name="StockTickerToNamePort" binding="acme:StockTickerSoapBinding">
<soap:address location="http://acme.com/tickertoname"/>
</port>
<port name="StockNameToTickerPort" binding="acme:StockNameSoapBinding">
<soap:address location="http://acme.com/nametoticker"/>
</port>
</service>
<service name="ServiceInfoService">
<documentation>Provides information about avaialable services.</documentation>
<port name="ServiceListPort" binding="acme:ServiceListSoapBinding">
<soap:address location="http://acme.com/stockquote"/>
</port>
<port name="ServiceQueryPort" binding="acme:ServiceQuerySoapBinding">
<soap:address location="http://acme.com/tickertoname"/>
</port>
</service>
</definitions>El servidor CGI muestra una pantalla de consulta para definir parámetros, como abajo.
Figura: pantalla de consulta WSDL.
Enviar la consulta produce el resultado siguiente.
Figura: pantalla de resultado WSDL.
Véase también
La especificación WSDL figura en Web Services Description Language (WSDL) 1.1. WSDL aún no es recomendación W3C, pero gana apoyo industrial. (Nota de la redacción data2type: Web Services Description Language (WSDL) Version 2.0.) Un grupo oficial, Web Services Description Working Group, trabaja en una futura recomendación W3C.
La receta Utilizar XSLT en Perl ofrece otras integraciones XSLT en Perl sin crear un proceso separado.
Copyright © 2006 O'Reilly Verlag GmbH & Co. KG
Puede imprimir la versión en línea para uso privado.
Para cualquier otro uso, este capítulo de «XSLT Kochbuch» está sujeto a las mismas condiciones que la edición encuadernada. La obra y todas sus partes están protegidas por derechos de autor. Todos los derechos reservados, incluidos reproducción, traducción, microfilmación, almacenamiento y tratamiento en sistemas electrónicos.
O'Reilly Verlag GmbH & Co. KG, Balthasarstraße 81, 50670 Köln, kommentar(at)oreilly.de