oriolrius.cat

Des del 2000 compartiendo sobre…

Tag: xml

gSOAP toolkit SOAP per C/C++

Reading time: 4 – 6 minutes

gSOAP, després de perdre-li la pista durant molt de temps aquesta llibreria de C i C++ crec que és la millor de codi obert i GPL que he trobat. Així doncs, ús la vull recomenar. El nom ve de “SOAP generator” i el va fer un professor, la versió 1.0 va sortir l’any 1999, per tant, podriem dir que l’eina esta més que provada si tenim en compte que va per la versió 2.7.1 que va sortir al gener del 2008.

Per entendre una mica que ofereix aquest toolkit esta molt bé fixar-se en aquest parell de gràfics que donen una visió de l’eina quan l’usem com a servidor SOAP:

gSOAP schema for server mode

i com a client SOAP:

gSOAP schema for client mode

Si haguessim de fer una llista de funcionalitats més detallada i tècnica em quedaria amb la que ofereix la pàgina de l’aplicació:

  • All-in-one package. Independence from third-party tools and libraries ensures successful builds and reliable runtime execution.
  • Open source with several license options.
  • gSOAP supports both pure ANSI C application development and mixed C/C++ application development.
  • gSOAP is the only toolkit that supports XML-to-C/C++ mapping for native C and C++ data types, which means that you can serialize your application data directly instead of having to use wrappers or SOAP/XML-specific data types. Any C or C++ data type can be serialized when it can be specified in a C/C++ header file (except unions). The toolkit automatically serializes pointer-based data structure graphs, including cyclic graphs and pointers to derived class instances to support polymorphism.
  • The toolkit follows the WS-I Basic Profile 1.0a compliance recommendations. It warns about potential interoperability issues before building a new Web service application, so you don’t have to go through another development cycle to make your services compliant. In addition, a report is available to check compliance.
  • Complete support for industry-standard Web services protocols SOAP 1.1/1.2 (RPC and doc/lit), WSDL 1.1, and UDDI v2. Supports XML schema with primitive XSD types, simpleTypes, complexTypes, extension, restriction, elements, attributes, groups, attributeGroups, and arrays (including polymorphic data types and SOAP 1.1 encoding of multi-dimensional sparse arrays). Extensive interoperability testing with other SOAP toolkits resulted in a toolkit release that has proven to be stable, robust, and reliable.
  • Supports SOAP-over-UDP, MIME (SwA), DIME (streaming), MTOM (streaming), HTTP1.0/1.1, IPv4, IPv6, RSS, XML-RPC, WS-Addressing, WS-Enumeration, and many other WS-* protocols.
  • Supports WS-Security: authentication, tokens, digital signatures (XML encryption will be added in the near future).
  • gSOAP is the only toolkit that implements streaming techniques for DIME and MTOM binary attachment transfers. It also supports SOAP with Attachements (SwA) Multipart/related MIME attachments.
  • Fast and efficient because gSOAP uses streaming XML parsing techniques. Typical round-trip SOAP service invocation latencies are below 1ms. Shown to be the fastest SOAP1.1/1.2 compliant C/C++ implementation available (wrt. most common uses we tested).
  • Very portable: Windows, Linux, Unix, Mac OS X, Solaris, HP-UX, AIX, FreeBSD, TRU64, Irix, QNX, VxWorks, MS-DOS. Also portable to handheld devices such as WinCE (Pocket PC), Palm OS, Symbian, and embedded Linux. Clients and server applications can be created that are under 100K with a total memory footprint under 150K.
  • The gSOAP WSDL parser automates server and client application development. gSOAP also generates WSDL documens to publish your services.
  • gSOAP Web Services and clients are just as easy to program as C# and JavaRMI, see How To section below.
  • Serialization of native C and C++ data types allows you also to store and retrieve application data from XML repositories.
  • Includes stand-alone HTTP/1.1 and HTTPS secure Web Server.
  • Offers Apache_mod, IIS, WinInet, CGI, and FastCGI interfaces.
  • Supports HTTP/1.1 POST/GET SOAP/XML messaging with compression, chunking, keep-alive, logging, and SSL encryption.
  • The gSOAP compiler can be conveniently integrated in an IDE. For example, MSVC++ 6.0 project examples with gSOAP integrated in MSVC++ are included in the gSOAP distribution for Windows.
  • Security: supports HTTPS and WS-Security. In addition, the source codes have been carefully written to avoid security holes such as buffer overruns. Also, gSOAP is open source which means that the gSOAP implementation can be verified.
  • gSOAP’s memory management uses garbage collection so (deserialized) data can be cleaned up without a hassle.
  • Company backup for support, licensing, and consulting.
  • Extensive documentation.

RSS 2.0 vs Atom 1.0

Reading time: 1 – 2 minutes

A IBM han escrit un article anomenat Implement news syndication using RSS and Atom (local en pdf). A part de l’interés propi del contingut de l’article pels programadors que vulguin un model UML de les classes que han de crear per exportar informació en aquests formats XML (RSS i Atom) a l’article hi ha un gràfic que m’ha ajudat molt a entendre les diferències entre RSS 2.0 i Atom. Perquè ambdós dona la sensació que són, fan i serveixen pel mateix. Doncs amb aquest gràfic podem acabar de confirmar-ho o desmentir-ho del tot.

Generant RSS de les revisions de Subversion

Reading time: 2 – 2 minutes

rss.jpg

Quan treballes en un projecte on hi ha més d’una persona treballant contra un repositori de codi és molt bona idea poder-se sindicar via RSS a les noves revisions que es van publicant del codi i als comentaris associats a aquestes revisions. De fet, aconseguir això amb subversion no és gens difícil. Jo fins ara ho he fet amb el WebSVN (port del ViewCVS. A més gràcies al trac també podem obtenir aquests RSS i moltes més funcionalitats. Però tot això ja us ho he explicat. En alguns casos però ens pot interessar publicar aquests RSS sense haver de tenir programes orientats a altres funcionalitats sinó únicament aprofitar les extencions WebDAV/DAV_SVN per publicar els RSS. Això és el que ens expliquen a l’article HOWTO: Adding an RSS feed to a Subversion Server (local).

De fet, el que planteja aquest article és força senzill. Simplement usa un generador d’RSS a partir de les revisions de l’SVN, l’script esta fet en python i després li diem al subversion que després de cada commit que es fassi al repositori es genir un nou fitxer RSS. Així doncs el tema no té cap misteri però va bé tenir-ho en un howto per si mai fa falta.

Client SOAP genèric

Reading time: < 1 minute

A SOAPClient.com tenen un munt d’aplicacions i eines via web per provar els serveis SOAP que programem o que hem d’usar. Concretament volia descatar el client genèric SOAP, al qual només cal passar-li la direcció URL del WSDL i ell ens mostra un formulari per llençar una petició SOAP contra el servidor i després podem veure la sortida en format XML o HTML. Realment útil per saber si el nostre SOAPService funciona correctament.

Trick: xml2yaml

Reading time: < 1 minute

Petit trick per convertir un fitxer XML a un fitxer YAML (yml) amb Perl, fan falta les llibreries pertinents de perl.

perl -MYAML -MXML::Simple -e 'print Dump XMLin "fixer.xml"'

php: SimpleXML i xml2array

Reading time: < 1 minute

Dues funcions potentissimes de PHP, sobretot ara que cada dos per tres hem de treballar amb fitxers XML.

$xml = simplexml_load_file('fitxer.xml');

Llegeix el fitxer.xml del disc dur i el converteix en un objecte de la classe SimpleXMLElement. Per veure en què es converteix es pot usar print_r.

Ara que ja tenim les dades en forma d’objecte si encara no ens agraden podem convertir-les en un array amb una sola funció:

$varArray = get_object_vars($objXml);

També amb un print_r podem veure un array dels de tota la vida.

Sovint la potència esta en la simplicitat… val la pena no perdre de vista aquestes funcions.

PHP5 – Generant WSDL amb Zend Studio 5.1

Reading time: 3 – 5 minutes

Al programar un webservice amb el PHP5 és més que trivial tal com podem llegir a la documentació sobre SOAP (local) del propi PHP. El problema ve quan volent aprofitar la simplicitat dels serveis SOAP toca programar a mà el WSDL. O sigui, agafa i posat a definir la interficie en XML de la/es classe/s que vols exportar a través del webservice, o sigui, una missión imposible.

La meva sorpresa ha estat veure que després d’adpotar el Zend Studio com a IDE de programació del meu codi PHP he vist que disposava d’un assistent ben senzill d’usar per tal de generar automàticament aquest fitxer WSDL. La cosa és ben senzilla imaginem que usem el codi de l’exemple de la web de Zend, com comentava abans.

El servidor SOAP:

<?php
class QuoteService {
  private $quotes = array("ibm" => 98.42);
	function getQuote($symbol) {
    if (isset($this->quotes[$symbol])) {
      return $this->quotes[$symbol];
    } else {
      throw new SoapFault("Server","Unknown Symbol '$symbol'.");
    }
  }
}
	$server = new SoapServer("server2.wsdl");
$server->setClass("QuoteService");
$server->handle();
?>

El client, encara més simple que el servidor:

<?php
  $client = new SoapClient("server2.wsdl");
  print($client->getQuote("ibm"));
?>

Ara que ja tenim el codi en el nostre Zend, només cal que anem a:

menu.png

Cal seguir l’assistent que no és massa difícil, aquí en teniu els passos capturats per l’exemple del que parlem:

wizard-wsdl-1.png
wizard-wsdl-2.png

Podeu veure com s’exporten automàticament les classes dels arxius que seleccioneu, cal que poseu al costat de cada classe exportada la URL a través de la qual s’accedeix al servei:

wizard-wsdl-3.png

Al final obtenim el fitxer WSDL, en el nostre cas aquest:

<?xml version='1.0' encoding='UTF-8'?>
	<!-- WSDL file generated by Zend Studio. -->
	<definitions name="server2" targetNamespace="urn:server2" xmlns:typens="urn:server2" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns="http://schemas.xmlsoap.org/wsdl/">
	<message name="getQuote">
		<part name="symbol"/>
	</message>
	<message name="getQuoteResponse">
		<part name="getQuoteReturn"/>
	</message>
	<portType name="QuoteServicePortType">
		<operation name="getQuote">
			<input message="typens:getQuote"/>
			<output message="typens:getQuoteResponse"/>
		</operation>
	</portType>
	<binding name="QuoteServiceBinding" type="typens:QuoteServicePortType">
		<soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>
		<operation name="getQuote">
			<soap:operation soapAction="urn:QuoteServiceAction"/>
			<input>
				<soap:body namespace="urn:server2" use="encoded" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
			</input>
			<output>
				<soap:body namespace="urn:server2" use="encoded" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
			</output>
		</operation>
	</binding>
	<service name="server2Service">
		<port name="QuoteServicePort" binding="typens:QuoteServiceBinding">
			<soap:address location="http://oriol.joor.net/soap/server2.php"/>
		</port>
	</service>
</definitions>

Si sou observadors notareu que aquest fitxer és lleugerament diferent al de la documentació que mostra Zend. Però jo l’he provat i funciona perfectament així doncs no m’hi trencaré el cap en saber a què es deuen aquests petits canvis al implmentar aquest format XML.

SOAP vs XML-RPC

Reading time: 4 – 6 minutes

Abans de començar un detall important sobre el món XML, compte a no acabar com el de la foto:

xml.jpg

Bé doncs ens trobem davant de dos protocols del tipus RPC (Remote Procedure Control), o sigui, que serveixen per intercomunicar dos processos que estan corrent en sistemes dispersos. Si mai ús han donat Sistemes Operatius, segur que us han fet fer la típica pràctica d’RPC d’Unix programada en C. El que acostuma a ser el mal son de tots els alumnes d’informàtica i telemàtica. Doncs bé, tranquils des d’aquella teoria inicial sobre RPC s’ha avançat molt.

De fet, jo fa molt de temps que uso els XML-RPC per implementar web-services senzillets entre les meves aplicacions. Hi ha un protocol que s’usa molt en el món del blogging, es diu ping (no el de tota la vida per mirar si un sistema és viu). Bàsicament el ping el que fa és aprofitar l’XML-RPC per notificar a un altre servei web un event de la nostre web, concretament que hem actualitzat el blog. També s’usa XML-RPC per fer trackback entre articles a diferents blogs. Així podem informar a un altre blog de que hem parlat sobre aquell article que ell ha escrit. Fixeu-vos que tot això és independent del sisteam operatiu, el servidor web, l’aplicació, etc.

Com podeu veure l’XML-RPC esta molt estès i és realment molt útil i senzill d’usar en totes aquestes aplicacions que us comento. Per tant, podriem dir que l’XML-RPC esta orientat a la simplicitat i la senzillesa d’ús, permet passar dades entre processos codificant-les en XML i usant l’HTTP com a protocol de transport. El model de dades que usa l’XML per implementar XML-RPC és molt senzill i si mireu un HTTP-POST que transporti una transacció XML-RPC veureu que és molt senzill entendre les estructures de dades que es monten a partir de les típiques etiquetes.

soap.gif

Llavors ús preguntareu; si l’XML-RPC va tan bé perquè carai vull el SOAP o fins hi tot; què carai és el SOAP. Doncs bé, el Simple Object Access Protocol (SOAP) és un protocol RPC com ja he dit i també es codifica en XML i es transporta sobre HTTP, i encara us diré més també serveix per transportar informació estructurada en el seu interior. La diferència escencial és que és capaç de transportar estructures de dades força complexes i a més permet definir contra quin mètode de quina classe han de ser usades aquestes estructures. Així doncs, el SOAP ens permet oferir infinitat de serveis en un sol biding (publicació) de servei.

Com podeu veure l’escència és la mateixa però la potència és ben diferent. SOAP al suportar models de dades tan complexos fa que quan intentem mirar un XML dels que usa per fer les transaccions ens costi força entendre el que hi ha dintre. Ja que a la mínima que ens compliquem una mica el model de dades a passar pel webservice es fa ben difícil entendre el munt d’etiquetes i d’atributs de les etiquetes que es creen.

A més SOAP disposa de diferents extencions que el fan encara més potent. Bàsicament les més conegudes són SOAP 1.1, SOAP 1.2 i WSDL. Aquest últim és el més usat per implementar WebServices, el seu propi nom ja ens indica aquest fet WSDL: Web Services Description Language. Concretament Microsoft amb .NET, IBM i Sun amb Java fan diverses implementacions del WSDL per tal d’implementar WebServices en les seves arquitectures. Això ens va de perles a la gent que ens agrada el PHP, perquè permet que ens entenguem amb els ASP, JSP, servlets i altres similars des del nostre PHP5 que ja implementa suport de SOAP/WSDL de serie.

Si voleu començar a jugar amb el SOAP i el PHP5, a la pròpia web de Zend podeu trobar aquest document: PHP SOAP Extension. Per una informació més tècnica del WSDL, la gent d’xml.com tenen un munt de documents sobre el tema, concretament us recomano: WSDL first i encara un altre sobre el mateix Examining WSDL. Si ja controleu l’UML és una bona idea que comenceu a veure com es modelen els WSDL des d’UML, un bon document per començar UML for Web Services.

Abans d’acabar l’article si voleu un document seriós que resolgui els vostres dubtes sobre les diferències que hi ha entre XML-RPC i SOAP, sobretot no us perdeu: XML-RPC vs SOAP (local)d’en kate rhodes.

XML & DocBook: Structured Technical Documentation Authoring

Reading time: 2 – 3 minutes

docbook.jpg

XML is short for Extended Markup Language and is a subset of SGML, the Standard Generalized Markup Language. XML is an HTML-like formatting language. Whereas most HTML-related formats developed in the past adopted the “be conservative in what you send and liberal in what you receive” attitude, XML takes the opposite approach–documents should be 100% compatible. This compatibility is known as “well-formedness” of an XML document. To this end, even when the goal is clear, a document is rejected if it does not follow XML specifications to the fullest extent. In terms of practicality, this approach guarantees interoperability in the long run. Unlike HTML, which is the standard groupname for a lot of sub-protocols that are slightly different and not fully interoperable with one another, the strictness of XML ensures compatibility. XML also improves security dramatically, because there is only one way to interpret expressions, a way on which everybody agrees.

DocBook is an XML Document Type Definition or DTD. It is a subset of XML particularly suited for but not limited to the creation of books and papers about computer hardware and software. DocBook is well-known in the Linux community and is used by many publishing companies and open-source development projects. Most tools are developed for the DocBook DTD and are included in most Linux distributions. This allows for sending raw data that can be processed at the receiver’s end–wherever applications able to interpret XML directly are available.

The important thing to keep in mind is XML and DocBook let authors focus on content. In that sense, the presence of the word “markup” in the definition of XML is misleading. With XML, authors specify what type of data they are including, such as text explanations, command names, tables or images. How the content is formatted, laid out and displayed should not be their concern. From a single source, the receiver might generate PDF, PS, plain text, HTML and many other representations of the content.

Another advantage is DocBook XML files are written in plain text. Although many editors are available, such as oXygen and XMLmind, advanced DocBook users easily can write the source texts using vim, Emacs or any other text editor.

Publicat al Linux Journal: XML & DocBook: Structured Technical Documentation Authoring