ONJava.com -- The Independent Source for Enterprise Java
oreilly.comSafari Books Online.Conferences.

advertisement

AddThis Social Bookmark Button

Working with Complex Data Types, Part 1
Pages: 1, 2

Now we can modify the client application so that it passes an appropriate Object[]as the parameter to the executeTrade service method.



The multiParams variable is declared as an Object[], and is populated with the String MINDSTRM, an Integer with the value of 100, and a Boolean with the value of true. Since we're using an array of Java Object instances, we don't use Java primitives as elements of the array. Instead we wrap those primitive values in their Java object equivalents. The second parameter of the Parameter constructor is Object[].class, which is the class for an array of object instances.

package javasoap.book.ch5;
import java.net.*;
import java.util.*;
import org.apache.soap.*;
import org.apache.soap.rpc.*;
public class TradingClient {
   public static void main(String[] args) 
      throws Exception {
      
      URL url = 
        new URL(
          "http://georgetown:8080/soap/servlet/rpcrouter");
    
      Call call = new Call(  );
      call.setTargetObjectURI("urn:BasicTradingService");
      
      call.setEncodingStyleURI(Constants.NS_URI_SOAP_ENC);
      Object[] multiParams = { "MINDSTRM", new Integer(100), 
                                    new Boolean(true) };
      Vector params = new Vector(  );
      params.addElement(new Parameter("params", 
                           Object[].class, multiParams, null));
      call.setParams(params);
      
      try {
         call.setMethodName("executeTrade");
         Response resp = call.invoke(url, "");
         Parameter ret = resp.getReturnValue(  );
         Object value = ret.getValue(  );
         System.out.println("Trade Description: " + value);
      }
      catch (SOAPException e) {
         System.err.println("Caught SOAPException (" +
                         e.getFaultCode(  ) + "): " +
                         e.getMessage(  ));
      }
   }
}

If all goes well, the result of executing the executeTrade( ) service method is:

Trade Description: Buy 100 of MINDSTRM

We could force the service object down another path by changing the order of the parameters in the multiParams array. In this case, we would encounter a class cast exception, and the method would return an error string.

In this Series

Working with Complex Data Types, Part 4
This is the last in a series of book excerpts on working with complex data types from Java and SOAP. In this excerpt, learn about returning custom types, using a stock market example.

Working with Complex Data Types, Part 3
The third in a series of excerpts from Java and SOAP, this article excerpt covers passing custom types as parameters.

Working with Complex Data Types, Part 2
In part two in this series of book excerpts from Java and SOAP, learn about returning arrays.

Here is the SOAP envelope for the proper invocation of the executeTrade( ) service method:

<SOAP-ENV:Envelope 
  xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"   
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  
  <SOAP-ENV:Body>
    <ns1:executeTrade xmlns:ns1="urn:BasicTradingService" 
      SOAP-ENV:encodingStyle=
          "http://schemas.xmlsoap.org/soap/encoding/">
  
      <params  
          xmlns:ns2="http://schemas.xmlsoap.org/soap/encoding/" 
          xsi:type="ns2:Array" ns2:arrayType="xsd:anyType[3]">
        <item xsi:type="xsd:string">MINDSTRM</item>
        <item xsi:type="xsd:int">100</item>
        <item xsi:type="xsd:boolean">true</item>
      </params>
    </ns1:executeTrade>
  </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

In Chapter 3, we talked about using ur-type to represent any possible data type. Here we see the use of anyType for that purpose. The XML Schema Part 0 recommendation, dated May 2, 2001, explains this in section 2.5.4 as follows: "The anyType represents an abstraction called the ur-type which is the base type from which all simple and complex types are derived. An anyType type does not constrain its content in any way."

The params element is typed by assigning the xsi:type attribute the value of ns2:Array. The only difference from the homogeneous case is that every array element has a different value assigned to the ns2:arrayType attribute. The value xsd:anyType[3] indicates that the array contains 3 elements, each of which can be of any valid data type (see sidebar).

Now let's take a look at passing arrays as parameters using GLUE. The BasicTradingService class can be deployed in GLUE without modification. We'll use a simple Java application to get this service started:

package javasoap.book.ch5;
import electric.util.Context;
import electric.registry.Registry;
import electric.server.http.HTTP;
public class BasicTradingApp {
   public static void main( String[] args )
      throws Exception {
    
      HTTP.startup("http://georgetown:8004/glue");
      Context context = new Context(  );
      context.addProperty("activation", "application");
      context.addProperty("namespace", 
                               "urn:BasicTradingService");
      Registry.publish("urn:BasicTradingService",
         javasoap.book.ch5.BasicTradingService.class, context );
   }
}

Compile and execute the application, and the service is deployed. Now let's write a simple example to access the service using the GLUE API. First let's look at the interface to the service, IBasicTradingService:

package javasoap.book.ch5;
public interface IBasicTradingService {
  int getTotalVolume(String[] symbols);
  String executeTrade(Object[] params);
}

Now we can write an application that binds to the service and calls both its methods:

package javasoap.book.ch5;
import electric.registry.RegistryException;
import electric.registry.Registry;
public class BasicTradingClient {
   public static void main(String[] args) throws Exception 
   {
      try {
        IBasicTradingService srv = 
          (IBasicTradingService)Registry.bind(
            "http://georgetown:8004/glue/urn:BasicTradingService.wsdl",
            IBasicTradingService.class);
        String[] stocks = { "MINDSTRM", "MSFT", "SUN" };
        int total = srv.getTotalVolume(stocks);
        System.out.println("Total Volume is " + total);
        Object[] multiParams = { "MINDSTRM", new Integer(100), 
                                    new Boolean(true) };
        String desc = srv.executeTrade(multiParams);
        System.out.println("Trade Description: " + desc);
    }
    catch (RegistryException e)
    {
       System.out.println(e);
    }
  }
}

As we've seen before, GLUE allows us to use familiar Java programming syntax without having to think about the underlying SOAP constructs. This holds true for the passing of array parameters as well. Everything is pretty much handled for us after the interface is bound to the service.

There are some interesting things to see in the SOAP request envelopes generated by this example. Here is the SOAP envelope for the getTotalVolume( ) method invocation:

<soap:Envelope 
  xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' 
  xmlns:xsd='http://www.w3.org/2001/XMLSchema' 
  xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/' 
  xmlns:soapenc='http://schemas.xmlsoap.org/soap/encoding/' 
  soap:encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'>
    <soap:Body>
      <n:getTotalVolume xmlns:n='urn:BasicTradingService'>
        <arg0 href='#id0'/>
      </n:getTotalVolume>
      <id0 id='id0' soapenc:root='0' 
        xmlns:ns2='http://www.themindelectric.com/package/java.lang/'           
        xsi:type='soapenc:Array' soapenc:arrayType='xsd:string[3]'>
         <i xsi:type='xsd:string'>MINDSTRM</i>
         <i xsi:type='xsd:string'>MSFT</i>
         <i xsi:type='xsd:string'>SUN</i>
      </id0>
    </soap:Body>
</soap:Envelope>

The Body element starts off like we've seen before; the envelope is qualified by a namespace identifier, soap, which represents the namespace of the SOAP envelope. The first child element of the SOAP body is getTotalVolume, which of course is the name of the service method being invoked. getTotalVolume is namespace-qualified using the name of the service. The only child element of getTotalVolume is arg0, which represents the parameter passed to the method. But this isn't the array we passed; it's a reference to the array. This is a significant difference between the ways that GLUE and the Apache SOAP API generate this call. Apache SOAP puts the array in the envelope as a child element of getTotalVolume, and GLUE uses a reference and serializes the array after the getTotalVolume element terminates. So the parameter is serialized as arg0, and includes an href attribute with the value #id0. No data is included, as the array resides elsewhere.

The array that we passed as a parameter follows the getTotalVolume element. It's named id0, although the element name itself, which is generated by GLUE, is not important. The id attribute is assigned a value of id0, which coincides with the href value used in the getTotalVolume element. GLUE generates the soapenc:root attribute with a value of 0, meaning that this element is not considered the root of an object graph. (GLUE seems to include that attribute automatically.) Next we see a declaration of a namespace identifier called ns2 that seems to identify the internal GLUE package for java.lang; however, the ns2 namespace identifier is never used. The xsi:type and soapenc:arrayType attributes are set up in the same way as in the Apache SOAP examples. Finally, the elements of the array are serialized. The only difference between this example and the one generated by Apache SOAP is in the name of the array elements themselves. Apache SOAP named these elements item, and GLUE named them i. The names don't matter; the result is the same.

This example gives us a good opportunity to see two equally valid ways to serialize arrays. It's important that SOAP implementations understand these different styles if they are to interoperate. This is one of the reasons we keep showing the SOAP envelopes generated by the examples. Becoming familiar with the various styles of serialization will help you down the road if you run into problems getting applications based on different implementations to communicate correctly. (Did I say if?)

Let's take a look at the SOAP envelope for the call to the executeTrade service method. This method takes a heterogeneous array as a parameter. It too uses a reference to a separately serialized array, this time encoded as xsd:anyType:

<soap:Envelope 
  xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' 
  xmlns:xsd='http://www.w3.org/2001/XMLSchema' 
  xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/' 
  xmlns:soapenc='http://schemas.xmlsoap.org/soap/encoding/' 
  soap:encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'>
    <soap:Body>
      <n:executeTrade xmlns:n='urn:BasicTradingService'>
        <arg0 href='#id0'/>
      </n:executeTrade>
      <id0 id='id0' soapenc:root='0' 
        xmlns:ns2='http://www.themindelectric.com/package/java.lang/' 
        xsi:type='soapenc:Array' soapenc:arrayType='xsd:anyType[3]'>
        <i xsi:type='xsd:string'>MINDSTRM</i>
        <i xsi:type='xsd:int'>100</i>
        <i xsi:type='xsd:boolean'>true</i>
      </id0>
    </soap:Body>
</soap:Envelope>

In the next installment, learn about Returning Arrays.

Robert Englander is Principal Engineer and President of MindStream Software, Inc. (www.mindstrm.com). He provides consulting services in software architecture, design, and development, as well as developing frameworks for use on client projects.


View catalog information for Java and SOAP

Return to ONJava.com.