XML technologies / XSLT / XSLT Cookbook / Code generation

(Excerpt from “XSLT Kochbuch” by Sal Mangano)

“Good programmers write good code. Great programmers write programs to generate it.”
Author unknown

Introduction

Automation is software development’s holy grail. Much development already means generating code from higher-level specifications: that is what assemblers and compilers do. Another form targets high-level languages such as Java or C++ rather than machine code. Why generate such code, and what has XML to do with it?

Programming encodes knowledge in specialized syntax optimized for one development stage. Reusing that work is difficult: source languages are hard to parse and comments hide useful information. Encoding application knowledge in XML promises more reuse. XML specifications can generate application code, tests, documentation and perhaps test data. XML does not provide this automatically; substantial planning and infrastructure remain necessary.

Unlike most chapters, its examples are components of a solution in a specific application context. There are two reasons.

First, you probably will not encode information in XML just because it is fashionable. A larger problem makes XML useful, and these examples make sense in that context.

Second, the problem is typical of large-scale development and may interest readers in itself. Even otherwise, the concepts apply to other development tasks.

What is this larger problem?

Consider a complex client-server application. Complex means many different server and client processes communicating through messages ( messages) via point-to-point or publish-subscribe middleware, or both. Products include IBM MQSeries, Microsoft Message Queuing (MSMQ), BEA Systems Tuxedo and TIBCO Rendezvous. The specific product is irrelevant here. Important work starts when a message arrives and triggers one or more reply messages. User I/O matters too, but can also be viewed as messages, usually on channels different from interprocess messaging. Messages may contain XML (SOAP), non-XML text or binary data. Chapter Vertical XSLT application recipes covers SOAP and WSDL. Here we focus on server-to-server exchanges, where XML is less common.

Such systems cannot be understood merely by reading one process’s source. Begin with their conversations and protocols, the interprocess messaging protocols ( interprocess messaging protocols). As a first approximation, process details do not matter. Treat processes as black boxes and study the small message set they exchange instead of hundreds of thousands of source lines.

Where can you learn this language? Rarely in one complete, current specification. Pieces lie in headers and design documents accumulated throughout the system’s life. Often only reverse-engineering application source yields reliable information, precisely what should not be necessary.

What connects this to XML, XSLT and code generation? We need detailed exchange documentation. A maintained Word document, perhaps, or a searchable message website? Better, encode it in XML and generate the site. Then generate code for applications handling messages too. That is this chapter’s approach. I call the XML files an interprocess message repository ( interprocess message repository); many recipes generate code from it.

First, the repository’s schema introduces its design. We use W3C XSD but show an intuitive graphical view for readers unfamiliar with schemas.

The next figure was generated with XMLSpy 4.0 from Altova. Three dots (...) mean an ordered sequence; the branching-switch icon means a choice.

Graphical XSD schema for a repository

Figure: Graphical XSD schema for a repository.

This illustrates useful recipes but is probably insufficient for an industrial repository, which could also store:

  • Symbolic constants for array and string lengths and enumeration values

  • More complex representations, such as unions and type aliases (C-typedefs)

  • Protocol information: complex message sequences exchanged by processes to fulfill a function

  • History: authors, last modifier, modification dates and so on

  • Delivery and transport information: publishers, subscribers or queues ( queues)

Consider a simple stock-order client-server application. Its repository might be:

<MessageRepository xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="C:\MyProjects\XSLT Cookbook\code gen\MessageRepository.xsd">
  <DataTypes>
    <Primitive>
      <Name>Real</Name>
      <Size>8</Size>
      <Category>real</Category>
    </Primitive>
    <Primitive>
      <Name>Integer</Name>
      <Size>4</Size>
      <Category>signed integer</Category>
    </Primitive>
    <Primitive>
      <Name>StkSymbol</Name>
      <Size>10</Size>
      <Category>string</Category>
    </Primitive>
    <Primitive>
      <Name>Message</Name>
      <Size>100</Size>
      <Category>string</Category>
    </Primitive>
    <Primitive>
      <Name>Shares</Name>
      <Size>4</Size>
      <Category>signed integer</Category>
    </Primitive>
    <Enumeration>
      <Name>BuyOrSell</Name>
      <Enumerators>
        <Enumerator>
          <Name>BUY</Name>
          <Value>0</Value>
        </Enumerator>
        <Enumerator>
          <Name>SELL</Name>
          <Value>1</Value>
        </Enumerator>
      </Enumerators>
    </Enumeration>
    <Enumeration>
      <Name>OrderType</Name>
      <Enumerators>
        <Enumerator>
          <Name>MARKET</Name>
          <Value>0</Value>
        </Enumerator>
        <Enumerator>
          <Name>LIMIT</Name>
          <Value>1</Value>
        </Enumerator>
      </Enumerators>
    </Enumeration>
    <Structure>
      <Name>TestData</Name>
      <Members>
        <Member>
          <Name>order</Name>
          <DataTypeName>AddStockOrderData</DataTypeName>
        </Member>
        <Member>
          <Name>cancel</Name>
          <DataTypeName>CancelStockOrderData</DataTypeName>
        </Member>
      </Members>
    </Structure>
    <Structure>
      <Name>AddStockOrderData</Name>
      <Documentation>Anfrage zur Buchung einer neuen Order.</Documentation>
      <Members>
        <Member>
          <Name>symbol</Name>
          <DataTypeName>StkSymbol</DataTypeName>
        </Member>
        <Member>
          <Name>quantity</Name>
          <DataTypeName>Shares</DataTypeName>
        </Member>
        <Member>
          <Name>side</Name>
          <DataTypeName>BuyOrSell</DataTypeName>
        </Member>
        <Member>
          <Name>type</Name>
          <DataTypeName>OrderType</DataTypeName>
        </Member>
        <Member>
          <Name>price</Name>
          <DataTypeName>Real</DataTypeName>
        </Member>
      </Members>
    </Structure>
    <Structure>
      <Name>AddStockOrderAckData</Name>
      <Documentation>Eine positive Bestätigung einer erfolgreich aufgenommenen Order.</Documentation>
      <Members>
        <Member>
          <Name>orderId</Name>
          <DataTypeName>Integer</DataTypeName>
        </Member>
      </Members>
    </Structure>
    <Structure>
      <Name>AddStockOrderNackData</Name>
      <Documentation>Eine negative Bestätigung einer nicht aufgenommenen Order.</Documentation>
      <Members>
        <Member>
          <Name>reason</Name>
          <DataTypeName>Message</DataTypeName>
        </Member>
      </Members>
    </Structure>
    <Structure>
      <Name>CancelStockOrderData</Name>
      <Documentation>Eine Anfrage zum Abbruch einer ganzen oder eines Teils einer Order.</Documentation>
      <Members>
        <Member>
          <Name>orderId</Name>
          <DataTypeName>Integer</DataTypeName>
        </Member>
        <Member>
          <Name>quantity</Name>
          <DataTypeName>Shares</DataTypeName>
        </Member>
      </Members>
    </Structure>
    <Structure>
      <Name>CancelStockOrderAckData</Name>
      <Documentation>Eine positive Bestätigung eines erfolgreichen Order-Abbruchs.</Documentation>
      <Members>
        <Member>
          <Name>orderId</Name>
          <DataTypeName>Integer</DataTypeName>
        </Member>
        <Member>
          <Name>quantityRemaining</Name>
          <DataTypeName>Shares</DataTypeName>
        </Member>
      </Members>
    </Structure>
    <Structure>
      <Name>CancelStockOrderNackData</Name>
      <Documentation>Eine negative Bestätigung eines fehlgeschlagenen Order-Abbruchs.</Documentation>
      <Members>
        <Member>
          <Name>orderId</Name>
          <DataTypeName>Integer</DataTypeName>
        </Member>
        <Member>
          <Name>reason</Name>
          <DataTypeName>Message</DataTypeName>
        </Member>
      </Members>
    </Structure>
  </DataTypes>
  <Messages>
    <Message>
      <Name>ADD_STOCK_ORDER</Name>
      <MsgId>1</MsgId>
      <DataTypeName>AddStockOrderData</DataTypeName>
      <Senders>
        <ProcessRef>StockClient</ProcessRef>
      </Senders>
      <Receivers>
        <ProcessRef>StockServer</ProcessRef>
      </Receivers>
    </Message>
    <Message>
      <Name>ADD_STOCK_ORDER_ACK</Name>
      <MsgId>2</MsgId>
      <DataTypeName>AddStockOrderAckData</DataTypeName>
      <Senders>
        <ProcessRef>StockServer</ProcessRef>
      </Senders>
      <Receivers>
        <ProcessRef>StockClient</ProcessRef>
      </Receivers>
    </Message>
    <Message>
      <Name>ADD_STOCK_ORDER_NACK</Name>
      <MsgId>3</MsgId>
      <DataTypeName>AddStockOrderNackData</DataTypeName>
      <Senders>
        <ProcessRef>StockServer</ProcessRef>
      </Senders>
      <Receivers>
        <ProcessRef>StockClient</ProcessRef>
      </Receivers>
    </Message>
    <Message>
      <Name>CANCEL_STOCK_ORDER</Name>
      <MsgId>4</MsgId>
      <DataTypeName>CancelStockOrderData</DataTypeName>
      <Senders>
        <ProcessRef>StockClient</ProcessRef>
      </Senders>
      <Receivers>
        <ProcessRef>StockServer</ProcessRef>
      </Receivers>
    </Message>
    <Message>
      <Name>CANCEL_STOCK_ORDER_ACK</Name>
      <MsgId>5</MsgId>
      <DataTypeName>CancelStockOrderAckData</DataTypeName>
      <Senders>
        <ProcessRef>StockServer</ProcessRef>
      </Senders>
      <Receivers>
        <ProcessRef>StockClient</ProcessRef>
      </Receivers>
    </Message>
    <Message>
      <Name>CANCEL_STOCK_ORDER_NACK</Name>
      <MsgId>6</MsgId>
      <DataTypeName>CancelStockOrderNackData</DataTypeName>
      <Senders>
        <ProcessRef>StockServer</ProcessRef>
      </Senders>
      <Receivers>
        <ProcessRef>StockClient</ProcessRef>
      </Receivers>
    </Message>
    <Message>
      <Name>TEST</Name>
      <MsgId>7</MsgId>
      <DataTypeName>TestData</DataTypeName>
      <Senders>
        <ProcessRef>StockServer</ProcessRef>
      </Senders>
      <Receivers>
        <ProcessRef>StockClient</ProcessRef>
      </Receivers>
    </Message>
  </Messages>
  <Processes>
    <Process>
      <Name>StockClient</Name>
    </Process>
    <Process>
      <Name>StockServer</Name>
    </Process>
  </Processes>
</MessageRepository>

It describes messages between client StockClient and server StockServer while performing tasks. WSDL readers may see similarities, though WSDL targets web services and usually SOAP, even if the WSDL specification is technically protocol-independent.

The final two examples concern other topics: generating C++ from UML (Unified Modeling Language) exported by modeling tools through XMI (XML Metadata Interchange), and generating XSLT with XSLT.

I chose C++ for most examples because I know it best and have written generators for it. The conceptual framework transfers to other languages, though the exact XSLT does not. (Only half-joking: C++ is so terribly complex that its users may have the strongest incentive to generate rather than write it!)

XSLT 2.0

These specialized recipes do not provide both 1.0 and 2.0 solutions as earlier chapters did. For code generation using XSLT 2.0, read Exploiting the potential of XSLT 2.0. Many techniques there suit code generation. General ideas include:

  • Use the new attribute separator of xsl:value-of.

    Generated code often contains delimited sequences, such as comma-separated lists. The ability of xsl:value-of to insert separators automatically simplifies generators.

  • Use powerful sequence constructs in XPath 2.0.

    XSLT 1.0 generators are verbose, with many loops and conditions. Instructions xsl:for-each and xsl:choose are hardly concise. Move tasks to XPath 2.0, often using XSLT and XPath to convert XML to sequences and then map them to code:

<!-- Eine Funktion zur Generierung einer Funktionsdeklaration im C-Stil, die vorwiegend XPath 2.0 verwendet. -->
<xsl:function name="ckbk:function-decl" as="xs:string*">
  <xsl:param name="name" as="xs:string"/>
  <xsl:param name="returnType" as="xs:string"/>
  <xsl:param name="argNames" as="xs:string*"/>
  <xsl:param name="argTypesPre" as="xs:string*"/>
  <xsl:param name="argTypesPost" as="xs:string*"/>
  <xsl:variable name="c" select="count($argNames)"/>
  <xsl:sequence select="$returnType, $name, '(', for $i in 1 to $c return ($argTypesPre[$i], $argNames[$i], $argTypesPost[$i], if ($i ne $c) then ',' else ''),');'"/>
</xsl:function>

  • Modular reusable XSLT is easier in 2.0.

    For generators supporting multiple target languages, learn techniques from Modularization and modes and Emulating object-oriented reuse and design patterns.

  • Multiple output documents are standard in 2.0.

    C and C++ generators producing separate headers and source files benefit from standardized xsl:result-document for multi-document output.

  

  

 

 

 

back to top