Skip navigation.

Programming WebLogic XML

  Previous Next vertical dots separating previous/next from contents/index/pdf Contents Index View as PDF   Get Adobe Reader

Using Advanced XML APIs

The following sections provide information about using the following advanced XML APIs:

 


Using the WebLogic XPath API

The WebLogic XPath API contains all of the classes required to perform XPath matching against a document represented as a DOM, an XMLInputStream, or an XMLOutputStream. Use the API if you want to identify a subset of XML elements within an XML document that conform to a given pattern.

For additional API reference information about the WebLogic XPath API, see the weblogic.xml.xpath Javadoc.

Using the DOMXPath Class

This section describes how to use the DOMXPath class of the WebLogic XPath API to perform XPath matching against an XML document represented as a DOM. The section first provides an example and then a description of the main steps used in the example.

Example of Using the DOMXPath Class

The sample Java program at the end of this section uses the following XML document in its matching:

<?xml version='1.0' encoding='us-ascii'?>
<!-- "Purchaseorder". -->
<purchaseorder
department="Sales"
date="01-11-2001"
raisedby="Pikachu"
>
<item
ID="101">
<title>Laptop</title>
<quantity>5</quantity>
<make>Dell</make>
</item>
<item
ID="102">
<title>Desktop</title>
<quantity>15</quantity>
<make>Dell</make>
</item>
<item
ID="103">
<title>Office Software</title>
<quantity>10</quantity>
<make>Microsoft</make>
</item>
</purchaseorder>

The Java code example is as follows:

package examples.xml.xpath;
import java.io.IOException;
import java.util.Iterator;
import java.util.Set;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
import weblogic.xml.xpath.DOMXPath;
import weblogic.xml.xpath.XPathException;
/**
* This class provides a simple example of how to use the DOMXPath
* API.
*
* @author Copyright (c) 2002 by BEA Systems, Inc. All Rights Reserved.
*/
public abstract class DOMXPathExample {
  public static void main(String[] ignored)
    throws XPathException, ParserConfigurationException,
           SAXException, IOException
  {
    // create a dom representation of the document
    String file = "purchaseorder.xml";
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true); // doesn't matter for this example
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(file);
    // create some instances of DOMXPath to evaluate against the
    // document.
    DOMXPath totalItems = // count number of items
      new DOMXPath("count(purchaseorder/item)");
    DOMXPath atLeast10 =  // titles of items with quantity >= 10
      new DOMXPath("purchaseorder/item[quantity >= 10]/title");
    // evaluate them against the document
    double count = totalItems.evaluateAsNumber(doc);
    Set nodeset = atLeast10.evaluateAsNodeset(doc);
    // output results
    System.out.println(file+" contains "+count+" total items.");
    System.out.println("The following items have quantity >= 10:");
    if (nodeset != null) {
      Iterator i = nodeset.iterator();
      while(i.hasNext()) {
        Node node = (Node)i.next();
        System.out.println("  "+node.getNodeName()+
                           ": "+node.getFirstChild().getNodeValue());
      }
    }
    // note that at this point we are free to continue using evaluate
    // atLeast10 and totalItems against other documents
  }
}

Main Steps When Using the DOMXPath Class

The following procedure describes the main steps to use the DOMXPath class to perform XPath matching against an XML document represented as a DOM:

  1. Create an org.w3c.dom.Document object from an XML document, as shown in the following code excerpt:
  2. String file = "purchaseorder.xml";
    DocumentBuilderFactory factory =
    DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(file);
  3. Create a DOMXPath object to represent the XPath expression you want to evaluate against the DOM.
  4. The following example shows an XPath expression that counts the items in a purchase order:

     DOMXPath totalItems = 
    new DOMXPath("count(purchaseorder/item)");

    The following example shows an XPath expression that returns the titles of items whose quantity is greater or equal to 10:

     DOMXPath atLeast10 = 
    new DOMXPath("purchaseorder/item[quantity >= 10]/title");
  5. Evaluate the XPath expression using one of the DOMXPath.evaluateAsXXX() methods, where XXX refers to the data type of the returned data, such as Boolean, Nodeset, Number, or String.
  6. The following example shows how to use the evaluateAsNumber() method to evaluate the totalItems XPath expression:

     double count = totalItems.evaluateAsNumber(doc);
    System.out.println(file+" contains "+count+" total items.");

    The following example shows how to use the evaluateAsNodeset() method to return a Set of org.w3c.dom.Nodes which you can iterate through in the standard way:

     Set nodeset = atLeast10.evaluateAsNodeset(doc);
     System.out.println("The following items have quantity >= 10:");
    if (nodeset != null) {
    Iterator i = nodeset.iterator();
    while(i.hasNext()) {
    Node node = (Node)i.next();
    System.out.println(" "+node.getNodeName()+
    ": "+node.getFirstChild().getNodeValue());
    }
    }

For additional API reference information about the WebLogic XPath API, see the weblogic.xml.xpath Javadoc.

Using the StreamXPath Class

The example in this section shows how to use the StreamXPath class of the WebLogic XPath API to perform XPath matching against an XMLInputStream. The section first provides an example and then a description of the main steps used in the example. Although the example shows how to match only against an XMLInputStream, you can use similar code to match against an XMLOutputStream.

Example of Using the StreamXPath Class

The sample Java program at the end of this section uses the following XML document in its matching:

<?xml version='1.0' encoding='us-ascii'?>
<!-- "Stock Quotes". -->
<stock_quotes>
<stock_quote symbol='BEAS'>
<when>
<date>01/27/2001</date>
<time>3:40PM</time>
</when>
<price type="ask" value="65.1875"/>
<price type="open" value="64.00"/>
<price type="dayhigh" value="66.6875"/>
<price type="daylow" value="64.75"/>
<change>+2.1875</change>
<volume>7050200</volume>
</stock_quote>
<stock_quote symbol='MSFT'>
<when>
<date>01/27/2001</date>
<time>3:40PM</time>
</when>
<price type="ask" value="55.6875"/>
<price type="open" value="50.25"/>
<price type="dayhigh" value="56"/>
<price type="daylow" value="52.9375"/>
<change>+5.25</change>
<volume>64282200</volume>
</stock_quote>
</stock_quotes>

The Java code for the example is as follows:

package examples.xml.xpath;
import java.io.File;
import weblogic.xml.stream.Attribute;
import weblogic.xml.stream.StartElement;
import weblogic.xml.stream.XMLEvent;
import weblogic.xml.stream.XMLInputStream;
import weblogic.xml.stream.XMLInputStreamFactory;
import weblogic.xml.stream.XMLStreamException;
import weblogic.xml.xpath.StreamXPath;
import weblogic.xml.xpath.XPathException;
import weblogic.xml.xpath.XPathStreamFactory;
import weblogic.xml.xpath.XPathStreamObserver;
/**
* This class provides a simple example of how to use the StreamXPath
* API.
*
* @author Copyright (c) 2002 by BEA Systems, Inc. All Rights Reserved.
*/
public abstract class StreamXPathExample {
  public static void main(String[] ignored)
    throws XPathException, XMLStreamException
  {
    // Create instances of StreamXPath for two xpaths we want to match
    // against this tream.
    StreamXPath symbols =
      new StreamXPath("stock_quotes/stock_quote");
    StreamXPath openingPrices =
      new StreamXPath("stock_quotes/stock_quote/price[@type='open']");
    // Create an XPathStreamFactory.
    XPathStreamFactory factory = new XPathStreamFactory();
    // Create and install two XPathStreamObservers.  In this case, we
    // just use to anonymous classes to print a message when a
    // callback is received.  Note that a given observer can observe
    // more than one xpath, and a given xpath can be observed by
    // mutliple observers.
    factory.install(symbols, new XPathStreamObserver () {
      public void observe(XMLEvent event) {
        System.out.println("Matched a quote: "+event);
      }
      public void observeAttribute(StartElement e, Attribute a) {} //ignore
      public void observeNamespace(StartElement e, Attribute a) {} //ignore
    });
    // Note that we get matches for both a start and an end elements,
    // even in the case of <price/> which is an empty element - this
    // is the behavior of the underlying streaming parser.
    factory.install(openingPrices, new XPathStreamObserver () {
      public void observe(XMLEvent event) {
        System.out.println("Matched an opening price: "+event);
      }
      public void observeAttribute(StartElement e, Attribute a) {} //ignore
      public void observeNamespace(StartElement e, Attribute a) {} //ignore
    });
    // get an XMLInputStream on the document
    String file = "stocks.xml";
    XMLInputStream sourceStream = XMLInputStreamFactory.newInstance().
      newInputStream(new File(file));
    // use the factory to create an XMLInputStream that will do xpath
    // matching against the source stream
    XMLInputStream matchingStream = factory.createStream(sourceStream);
    // now iterate through the stream
    System.out.println("Matching against xml stream from "+file);
    while(matchingStream.hasNext()) {
      // we don't do anything with the events in our example - the
      // XPathStreamObserver instances that we installed in the
      // factory will get callbacks for appropriate events
      XMLEvent event = matchingStream.next();
    }
  }
}

Main Steps When Using the StreamXPath Class

The following procedure describes the main steps to use the StreamXPath class to perform XPath matching against an XML document represented as an XMLInputStream:

  1. Create a StreamXPath object to represent the XPath expression you want to evaluate against the XMLInputStream.
  2. The following example shows an XPath expression that searches for stock quotes in an XML document:

    StreamXPath symbols =
    new StreamXPath("stock_quotes/stock_quote");

    The following example shows an XPath expression that matches stock quotes using their opening price:

    StreamXPath openingPrices = new   StreamXPath("stock_quotes/stock_quote/price[@type='open']");
  3. Create an XPathStreamFactory. Use this factory class to specify the set of StreamXPath objects that you want to evaluate against an XMLInputStream and to create observers (using the XPathStreamObserver interface) used to register a callback whenever an XPath match occurs. The following example shows how to create the XPathStreamFactory:
  4. XPathStreamFactory factory = new XPathStreamFactory();
  5. Create and install the observers using the XPathStreamFactory.install() method, specifying the XPath expression with the first StreamXPath parameter, and an observer with the second XPathStreamObserver parameter. The following example shows how to use an anonymous class to implement the XPathStreamObserver interface. The implementation of the observe() method simply prints a message when a callback is received. In the example, the observeAttribute() and observeNamespace() methods do nothing.
  6. factory.install(symbols, new XPathStreamObserver () {
    public void observe(XMLEvent event) {
    System.out.println("Matched a quote: "+event);
    }
    public void observeAttribute(StartElement e, Attribute a) {}
    public void observeNamespace(StartElement e, Attribute a) {}
    }
    );
  7. Create an XMLInputStream from an XML document:
  8. String file = "stocks.xml";
    XMLInputStream sourceStream =
    XMLInputStreamFactory.newInstance().newInputStream(new File(file));
  9. Use the createStream() method of the XPathStreamFactory to create a new XMLInputStream that will perform XPath matching against the original XMLInputStream:
  10.  XMLInputStream matchingStream =
    factory.createStream(sourceStream);
  11. Iterate over the new XMLInputStream. During the iteration, if an XPath match occurs, the registered observer is notified:
  12. while(matchingStream.hasNext()) {
    XMLEvent event = matchingStream.next();
    }

For additional API reference information about the WebLogic XPath API, see the weblogic.xml.xpath Javadoc.

 


Using the WebLogic XML Digital Signature API

The WebLogic XML Digital Signature API contains classes to digitally sign and validate SOAP messages. The API is contained in the weblogic.webservice.core.soap package.

The following table lists the two main classes of the XML Digital Signature API.

Table 5-1 Classes of the WebLogic XML Didital Signature API

Class

Description

XMLSignature

Main class used to sign and validate a SOAP message represented as a java.io.InputStream. Use the sign() method to digitally sign the message using the client's digital certificate and private key. Use the validate() method to ensure that the SOAP message is valid.

ValidateResult

Class that represents the result of validating a signed SOAP message. Use the getCertificates() method to return a list of digital certificates found in the signed XML document.

When using the API, a thrown XMLSignatureInvalidException means that the signature is invalid and a thrown XMLSignatureMalformedException means that the SOAP message is unprocessable.

Warning: The WebLogic XML Digital Signature API works only with RSA encryption.

The following sample client application shows a simple way to use the WebLogic XML Digital Signature API. The Java code in bold shows how to use the XMLSignature.sign() method to read an unsigned SOAP message, represented as a java.io.InputStream, and then write the resulting signed SOAP message, represented as a java.io.OutputStream , using the client's private key and digital certificates. The program also shows how to validate the signed SOAP message and output the digital certificates found in the message.

import weblogic.webservice.core.soap.XMLSignature;
import weblogic.webservice.core.soap.ValidateResult;
import java.security.cert.X509Certificate;
import java.security.PrivateKey;
import java.security.Key;
import java.security.KeyStore;
import java.io.FileInputStream;
import java.io.FileOutputStream;
/**
* Sample client application that shows how to sign and validate a SOAP message.
*
* Copyright (c) 2003 by BEA Systems. All Rights Reserved.
*/
public class SignSOAPMessage {
  private static final String CLIENT_KEYSTORE = "clientkeystore";
private static final String KEYSTORE_PASS = "mypasswd";
private static final String KEYNAME = "clientkey";
private static final String KEYPASS = "clientpass";
  private static final String signedXML = "soap-signed.xml";
  private static Key getPrivateKey(String keyname, 
String password,
String keystore) throws Exception {
KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(new FileInputStream(keystore), KEYSTORE_PASS.toCharArray());
    Key result = ks.getKey(keyname, password.toCharArray());
    return result;
  }
  private static X509Certificate getCertificate(String keyname,
String keystore) throws Exception {
KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(new FileInputStream(keystore), KEYSTORE_PASS.toCharArray());
    X509Certificate result = (X509Certificate) ks.getCertificate(keyname);
    return result;
}
  public static void main(String[] args) throws Exception {
X509Certificate clientcert = getCertificate(KEYNAME, CLIENT_KEYSTORE);
PrivateKey clientprivate = (PrivateKey) getPrivateKey(KEYNAME,
KEYPASS, CLIENT_KEYSTORE);
ValidateResult result;
if (args[1].equals("sign")) {
XMLSignature.sign(new FileInputStream(args[0]), new FileOutputStream(signedXML), clientcert, clientprivate);
result = XMLSignature.validate(new FileInputStream(signedXML));
} else {
result = XMLSignature.validate(new FileInputStream(args[1]));
}
    System.out.println("Cert: " + result.getCertificates());
  }
}

 

Skip navigation bar  Back to Top Previous Next