Content starts here Understanding the Advanced Static Mediator API Sample
This page last changed on Jun 23, 2008.

edocs Home > BEA AquaLogic Data Services Platform 3.0/3.2 Documentation > ALDSP 3.2 New Features Documentation

Understanding the Advanced Static Mediator API Sample

This topic describes how to use the static mediator API to call a data service operation with a complex argument.

You can find the source code for this sample project in the following file:

DSPClientSamplesStatic1/JavaResources/client.java_and_ws.static0/ClientComplexArg.java

Topic Map


Advanced API Samples - Mediator, Web Services, and DSP Controls

Importing Packages

The first segment of the sample project imports several required packages including the DASResult package which represents the result of invoking an operation on a data service.

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import com.bea.dsp.das.DASResult;

import weblogic.jndi.Environment;
import java.io.StringWriter;

Note that you could also choose to import the following classes that appear in the generated mediator client JAR file:

import das.ws.retailapplication.customermanagement.ProfileServiceDAS
import das.ejb.retailapplication.customermanagement.ProfileServiceDAS
import retailer.CASE_SERVICE

The ProfileServiceDAS classes (for web services and Java respectively) are the generated DataAccessService classes for the data service. These classes contains type-safe methods that map to the actual data service operations. The CASE_SERVICE class provides the SDO interface for manipulating DataObjects returned from the data service.

Obtaining a Data Access Service Handle

You use a DataAccessService object to call methods (operations) on a data service. For the static mediator API, the DataAccessService (DAS) classes have a factory method named getInstance() which return the handle. The getInstance() method requires two parameters to return the handle:

  • A WebLogic JNDI Context object. The context object allows the Java client to connect to the data service running through a instance of WebLogic server.
  • The name of the dataspace project in which the data service is deployed.
    For more information on the DataAccessService class see:

    For more information on WebLogic JNDI context objects, see Programming WebLogic JNDI:

The ALDSP web service client identifies the DataAccessService class using the URL of the WSDL file. The ALDSP Java client, on the other hand, identifies the DataAccessService class using the dataspace name.
The sample code parses the WSDL URL to determine the dataspace name for the Java client. Note that in a typical application, you would more likely use strings rather than obtaining this information from the WSDL URL.

das.ws.retailapplication.customermanagement.ProfileServiceDAS wsDas = null;
das.ejb.retailapplication.customermanagement.ProfileServiceDAS ejbDas = null;
DASResult<retailer.CASE_SERVICE> dasResult = null;

...

   if(isWebServiceClient()){
      contextCacheKey=locator;
      wsDas=das.ws.retailapplication.customermanagement.ProfileServiceDAS.getInstance(
         new java.util.Hashtable(), contextCacheKey);
   } else {
      splitLocator(locator);
      Context ctx = getInitialContext(uri, username, password);
      ejbDas=das.ejb.retailapplication.customermanagement.ProfileServiceDAS.getInstance(ctx, contextCacheKey);
   }

The sample uses a helper method, getInitialContext(), to get the initial context.

public static InitialContext getInitialContext(String url, String username, String password) throws NamingException {
   Environment env = new Environment();
   env.setProviderUrl(url);
   env.setInitialContextFactory("weblogic.jndi.WLInitialContextFactory");
   env.setSecurityPrincipal(username);
   env.setSecurityCredentials(password);
   return new InitialContext(env.getInitialContext().getEnvironment());
}

Creating the SDO DataFactory

The following code segment shows the use of the HelperContext to create a new DataFactory which you can later use to create new DataObjects.

commonj.sdo.helper.HelperContext hc=com.bea.dsp.das.HelperContextCache.get(contextCacheKey);
commonj.sdo.helper.XMLHelper xh = hc.getXMLHelper();
commonj.sdo.helper.DataFactory factory = hc.getDataFactory();

When using ALDSP 3.0, your clients may need to call the following before making other ALDSP calls:

com.bea.dsp.das.HelperContextCache.setClassLoader(contextCacheKey, Thread.currentThread().getContextClassLoader());

where contextCacheKey is the dataspace name if you are using the Java Mediator API, or the WSDL URL if you are using the Web Service Mediator API.

Retrieving Data from the Service

The generated DataAccessService method getServiceCase(profileService) retrieves the result set from the data service. This method returns all CASE objects corresponding to the specified profile from the data service.

retailer.PROFILE_SERVICE profileService =(retailer.PROFILE_SERVICE)factory.create(retailer.PROFILE_SERVICE.class );

   com.bea.dsp.sdo.SDOUtil.setElementName(profileService, "urn:retailer", "PROFILE");
   retailertype.PROFILE_TYPE profile = profileService.createPROFILE();
   profile.setCustomerID("CUSTOMER4");
   profile.setFirstName("dummyFirstName");
   profile.setLastName("dummyLastName");
   profile.setCustomerSince( "2001-01-01");
   profile.setEmailAddress( "dummyEmailAddress");
   profile.setTelephoneNumber("8885551212");

   if(isWebServiceClient()){
      dasResult = wsDas.getServiceCase(profileService);
   } else {
      dasResult = ejbDas.getServiceCase(profileService);
   }

Note that the argument for the setElementName() method must include the namespace URI along with the name of the type of the argument. You can determine the namespace URI by doing the following:

  1. Open RetailDataspace/RetailApplication/CustomerManagement/ProfileService.ds
  2. In the Design View, right-click the getServiceCase function and choose Edit Signature.
  3. Select the PROFILE argument, and click Edit. The Schema file field shows the schema file where the element is defined.
  4. Select and copy the contents of the schema file, choose File > OpenFile, paste the file name into the text box (manually changing the forward slashes to backward slashes), and click Open.
  5. Click Design View for the open schema file.
  6. Locate the PROFILE element and note its type (PROFILE_SERVICE). The namespace URI for the type appears at the top of the Schemas box (urn:retailer).

The method getServiceCase() is mapped directly from the original data service operation of the same name. The operation definition as specified in the data service file appears as follows:

(::pragma  function <f:function kind="navigate" roleName="ServiceCase" visibility="public" xmlns:f="urn:annotations.ld.bea.com"/>::)

declare function tns:getServiceCase($profile as element(ns5:PROFILE)) as element(ns7:CASE)*{
for $b in ns8:getServiceCaseByCustID($profile/ns2:PROFILE/CustomerID)
return $b
};

Obtaining a DataObject from the Result

The return type of the DataAccessService method is a dasResult object, which operates as an iterator. This means that you can use the DASResult.next() method similar to the way you would use the Java method Iterator.next(). The DASResult.next() method returns the next CASE, which is an SDO DataObject. SDO is a Java-based data programming model (API) and architecture for accessing and updating data.

The sample iterates through the dasResult object and outputs the data.

while( dasResult.hasNext()){
   out("DataObject : " + dataObjectToString(xh,(retailer.CASE_SERVICE)dasResult.next()));
}

Disposing the dasResult Object

You must call the DASResult.dispose() method whenever you are finished iterating through a result object. The sample project uses the following code segment to dispose the object:

try {
   if(dasResult!=null) dasResult.dispose();
} catch(Exception e){e.printStackTrace();}

Placing the dispose() call in a try/finally block is a recommended best practice.

ClientComplex.Arg.java Listing

The following lists the code for the ClientComplexArg.java sample project.

ClientComplex.Arg.java Sample Project Code 
package client.java_and_ws.static0;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import com.bea.dsp.das.DASResult;

import weblogic.jndi.Environment;
import java.io.StringWriter;

public class ClientComplexArg {

   String locator="http://localhost:7001/RetailDataspace/RetailApplication/CustomerManagement/ProfileService.ws?WSDL";
   String dsLocator=null;
   String uri=null;
   String username= "weblogic";
   String password="weblogic";

   java.io.Writer out=new java.io.PrintWriter(System.out);

   String className=this.getClass().getName().substring(this.getClass().getName().lastIndexOf('.')+1);
   String runningIn=this.getClass().getClassLoader().equals(com.bea.dsp.das.DASResult.class.getClassLoader()) ? "standalone" : "webapp";
   String contextCacheKey=null;

   enum ClientType {java, webservice, control};
   ClientType clientType=ClientType.java;
   enum ClassloaderType { noclassloader, currentthread, other};
   ClassloaderType classloaderType=ClassloaderType.noclassloader;

   public ClientComplexArg(){
      this((String)null,(String)null,(String)null, (String)null, null, null);
   }

   public ClientComplexArg(java.io.Writer out){
      this((String)null,(String)null,(String)null, (String)null, out, null);
   }

   public ClientComplexArg(String locator){
      this(locator,(String)null,(String)null, (String)null, null, null);
   }

   public ClientComplexArg(String locator, java.io.Writer out, String classloadertypeStr){
      this(locator,(String)null,(String)null, (String)null, out, classloadertypeStr);
   }

   public ClientComplexArg(String cType, String locator, String username, String password, java.io.Writer out, String classloadertypeStr){
      if(cType != null) this.clientType=ClientType.valueOf(cType);
      if(locator!=null) this.locator=locator;
      if(username!=null) this.username=username;
      if(password!=null)this.password=password;
      if(out!=null) this.out=out;
      if(classloadertypeStr != null) this.classloaderType=ClassloaderType.valueOf(classloadertypeStr);
   }

   public static void main(String[] args) {
      String locator=args.length > 0 ? args[0] : null;
      String uri=args.length > 1 ? args[1] : null;
      String username=args.length > 2 ? args[2] : null;
      String password=args.length > 3 ? args[3] : null;
      String classloadertypeStr=args.length > 4 ? args[4] : null;
      ClientComplexArg c=new ClientComplexArg(locator, uri, username, password, null, classloadertypeStr);
      c.run();
   }

   public void run(){

      if (! locator.startsWith("http://") ){
         out("locator must be http://... (wsdl URL)");
         return;
      }

      das.ws.retailapplication.customermanagement.ProfileServiceDAS wsDas = null;
      das.ejb.retailapplication.customermanagement.ProfileServiceDAS ejbDas = null;
      DASResult<retailer.CASE_SERVICE> dasResult = null;

      try {
         if (isWebServiceClient()){
            contextCacheKey=locator;
            wsDas=das.ws.retailapplication.customermanagement.ProfileServiceDAS.getInstance(new java.util.Hashtable(), contextCacheKey);
         } else {
            splitLocator(locator);
            Context ctx = getInitialContext(uri, username,password);
            ejbDas = das.ejb.retailapplication.customermanagement.ProfileServiceDAS.getInstance(ctx, contextCacheKey);
         }

         commonj.sdo.helper.HelperContext hc=com.bea.dsp.das.HelperContextCache.get(contextCacheKey);
         commonj.sdo.helper.XMLHelper xh = hc.getXMLHelper();
         commonj.sdo.helper.DataFactory factory = hc.getDataFactory();

         retailer.PROFILE_SERVICE profileService =(retailer.PROFILE_SERVICE)factory.create(retailer.PROFILE_SERVICE.class );

         com.bea.dsp.sdo.SDOUtil.setElementName(profileService, "urn:retailer", "PROFILE");
         retailertype.PROFILE_TYPE profile = profileService.createPROFILE();
         profile.setCustomerID("CUSTOMER4");
         profile.setFirstName("dummyFirstName");
         profile.setLastName("dummyLastName");
         profile.setCustomerSince( "2001-01-01");
         profile.setEmailAddress( "dummyEmailAddress");
         profile.setTelephoneNumber("8885551212");

         if (isWebServiceClient()){
            dasResult = wsDas.getServiceCase(profileService);
         } else {
            dasResult = ejbDas.getServiceCase(profileService);
         }

         while( dasResult.hasNext()){
            out("DataObject : " + dataObjectToString(xh,(retailer.CASE_SERVICE)dasResult.next()));
         }
      } catch (Exception e) {
         e.printStackTrace();
      } finally {
         try {
            if(dasResult!=null) dasResult.dispose();
         } catch(Exception e){e.printStackTrace();}
      }
   }

   public void out(String s){
      try{
         if(out instanceof javax.servlet.jsp.JspWriter)
            s = s.replace("&","&amp;").replace("<", "&lt;").replace(">", "&gt;");
            out.write(className+"/"+runningIn+"/"+clientType+"/"+classloaderType+" "+s+"\n");
            out.flush();
      }catch (Exception e){
         e.printStackTrace();
      }
   }

   public static InitialContext getInitialContext(String url, String username, String password) throws NamingException {
      Environment env = new Environment();
      env.setProviderUrl(url);
      env.setInitialContextFactory("weblogic.jndi.WLInitialContextFactory");
      env.setSecurityPrincipal(username);
      env.setSecurityCredentials(password);
      return new InitialContext(env.getInitialContext().getEnvironment());
   }

   static String dataObjectToString(commonj.sdo.helper.XMLHelper xh, commonj.sdo.DataObject dObj) {
      try {
         com.bea.sdo.PropertyXML element = ((com.bea.sdo.DataObjectXML) dObj).getContainmentPropertyXML();
         String elementName = element.getXMLName();
         String elementURI = element.getXMLNamespaceURI();

         commonj.sdo.helper.XMLDocument xmlDocument = xh.createDocument(dObj, elementURI, elementName);
         StringWriter outputWriter = new StringWriter();
         xh.save(xmlDocument, outputWriter, null);
         return outputWriter.toString();
      } catch (Exception e) {
         e.printStackTrace();
      }
         return null;
   }

   boolean isWebServiceClient(){
      return clientType==ClientType.webservice;
   }

   void splitLocator(String locator) throws Exception {
      uri=null;
      contextCacheKey=null;
      dsLocator=null;
      for(int i=0, j=0, last=0;i<locator.length(); i++) {
         if(locator.charAt(i) == '/') {
            j++;
            if(j==2)
               last=i;
            if(j==3) {
               uri="t3://"+locator.substring(last+1,i);
               last=i;
            }
            if(j==4) {
               contextCacheKey=locator.substring(last+1,i);
               dsLocator="ld:"+locator.substring(i+1).replace(".ws?WSDL", "");
               break;
            }
         }
      }
      if(uri==null || contextCacheKey== null || dsLocator==null)
         throw new Exception("locator not valid : "+locator);
      return;
   }
}

Related Topics

Concepts
How Tos
Reference
Document generated by Confluence on Jul 03, 2008 12:11