29.3 VDX Example

The following code example shows how one might use the VDX service to access the attributes associated with entities defined in the directory abstraction layer. It demonstrates the use of ad hoc searches, as well as predefined searches called global queries. This code listing includes examples that use the getAttribute(), getAttributes(), query(), and globalQuery() methods on the service.

To get a reference to the SOAP endpoint for the VDX service, it calls a method called getVdxStub(). The implementation for this method is shown at the end of the listing:

NOTE:This example presumes that you have generated client stubs from the WSDL file IRemoteVdx.wsdl. Use the SOAP stack provider of your choice (such as AXIS or CFX) to generate client stubs.

With Apache CXF, for example, you should be able to generate the stubs to match the package names in the import statement by using the following command:

wsdl2java -p com.netiq.ws.client.vdx IRemoteVdx.wsdl
import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.xml.rpc.Stub;
import java.rmi.RemoteException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.rmi.RemoteException;
import java.util.Calendar;
import java.util.Date;
import java.util.Hashtable;
import java.util.Map;
//
// Vdx imports
import com.netiq.ws.client.vdx.IRemoteVdx;
import com.netiq.ws.client.vdx.VdxService;
import com.netiq.ws.client.vdx.VdxServiceException;
import com.netiq.ws.client.vdx.VersionVO;
import com.netiq.ws.client.vdx.Attribute;
import com.netiq.ws.client.vdx.AttributeArray;
import com.netiq.ws.client.vdx.AttributeType;
import com.netiq.ws.client.vdx.ByteArrayArray;
import com.netiq.ws.client.vdx.BooleanArray;
import com.netiq.ws.client.vdx.DateArray;
import com.netiq.ws.client.vdx.StringArray;
import com.netiq.ws.client.vdx.IntegerArray;
import com.netiq.ws.client.vdx.EntryArray;
import com.netiq.ws.client.vdx.Entry;
import com.netiq.ws.client.vdx.EntityAttributeMap;


public class ServiceTest
{
  public static final int VDX           = 0;
  public static final int NOTIFICATION      = 1;
  public static final int RESOURCE         = 2;
  public static final int ENDPOINT_SERVICE  = VDX;

  private static final int LOCALHOST    = 0;  // localhost
  private static final int TESTSERVER      = 1;  // testserver
  private static final int SELECTED_URL     = TESTSERVER;

      private String [] SERVER_URLS = {
    "http://localhost:8080/IDMProv/vdx/service",
    "http://testserver:8080/IDMProv/vdx/service"
  }; 

  private String url = SERVER_URLS[SELECTED_URL];
  private String username = "cn=admin,ou=idmsample,o=netiq";
  private String password = "test";

      private String [] userAttributes = {
                    //"passwordAllowChange", // boolean
                    "UserPhoto",             // binary
                    //"loginTime",             // time
                    "Department",            // string
                    "Title", 
                    "Email",
                    "manager",               // dn = string
                    "TelephoneNumber",
                    "directReports",  
                    "FirstName", 
                    //"surname",
                    "group", 
                    "srvprvHideAttributes", 
                    "NotificationPrefs", 
                    "srvprvQueryList", 
                    "Location",
                    };

  public ServiceTest() { };

  public static void main(String [] args)
  {
           ServiceTest serviceTest = new ServiceTest();  
       //
           // Set default if no params are given
       int wService = ENDPOINT_SERVICE;
       if(args.length == 1)
              wService = Integer.parseInt(args[0]);

       try
       {
           serviceTest.run(wService);
       }
       catch(Exception e)
       {
       System.exit(-1);
       }
  }


  private void waitHere(long _time) { try { Thread.sleep(_time *
1000); } catch(InterruptedException ie) {} }
  

  public void run(int _service)
  throws Exception
  {
     if(_service == VDX)
     {
    System.out.println("Calling VDX endpoint");
    //
    // Get the version number
    getVersionTestCase();
    waitHere(2);
    //
    // Get attribute data for entity user
    getAttributeTestCase();
    waitHere(2);
    //
    // Get attributes
    getAttributesTestCase();
    waitHere(2);
    //
    // Query attributes
    queryAttributesTestCase();
    waitHere(2);
    //
    // Global query
           // Global query MUST be associated with a defined and
deployed query.
    // This can be done via the Designer.
 
    globalQueryTestCase();
     }
     else if(_service == NOTIFICATION)
     {
    System.out.println("Calling Notification endpoint");
    NotificationTest notificationTest = new
NotificationTest();
    //
    // Email Notification
    notificationTest.emailNotificationTestCase();
         }
     else if(_service == RESOURCE)
     {
    System.out.println("Calling Resource endpoint");
         }
         else
     {
    System.out.println("Unrecognized service selection");
         }
  }


public void globalQueryTestCase()
    throws Exception
    {
  
System.out.println("\n<=========queryAttributesTestCase=========>");
        try
        {
            //
            // Get the vdx stub
    IRemoteVdx vdxStub = getVdxStub(url, username, password);
            //
            // Create entry items corresponding to param key in DAL
            StringEntry [] entry = {
                    new StringEntry("titleattribute", "Chief Operating
Officer"), 
                    new StringEntry("managerattribute",
"cn=jmiller,ou=users,ou=idmsample-pproto,o=netiq")
            }; 
            //
            // Create and set the array of entries (key,value pairs)
            StringEntryArray entryArr = new StringEntryArray();
            entryArr.setStringentry(entry);
            //
            // Create and set the map using the entries
            StringMap map = new StringMap();
            map.setEntries(entryArr);
            //
            // Define and execute the global query
            int QUERY_KEY_INDEX = 0;
            String [] queryKeyName = {"TestVdxGlobalQuery2",
"TestVdxGlobalQuery"};
            //
            // Results from global query TestVdxGlobalQuery2 ----->
cn=apalani,ou=users,OU=idmsample-pproto,O=netiq
            //
            // Make the vdx endpoint call
            StringArray array =
vdxStub.globalQuery(queryKeyName[QUERY_KEY_INDEX], map);
            String [] str = array.getString();
            if(str == null)
                throw new Exception("Global query returns null for key
name " + queryKeyName);
            else
            {
                System.out.println("Results for global query : " +
queryKeyName[QUERY_KEY_INDEX]);
               
System.out.println("=================================================
===");
                for(int index = 0; index < str.length; index++)
                {
                    System.out.println(str[index]);
                }
            }
        }
        catch(VdxServiceException error) 
        {
            System.out.println(error.getReason() );
            throw new Exception(error.getReason() );
        }
        catch(RemoteException error) 
        {
            System.out.println(error.getMessage() );
            throw new Exception(error.getMessage() );
        }
    }


    public void queryAttributesTestCase()
    throws Exception
    {
    System.out.println("\nCalling queryAttributesTestCase() test
case");
    try
        {
    IRemoteVdx vdxStub = getVdxStub(url, username, password);

            StringArray attributes = new StringArray();
            attributes.setString(new String[]{"FirstName", "Title",
"UserPhoto", "Department"});
            String expression1 = "FirstName STARTWITH 'J'";
            String expression2 = "Title = 'Controller'";
            String expression3 = "vdxInteger > 0";
            String expression4 = "TelephoneNumber != '(555) 555-1201'";
            // 
            // Test Cases
            // expression1 --> Should yield all users whose firstname
starts with J
            // expression1 AND expression2 --> Should yield jkelley who
is the Controller
            // expression1 AND expression3 --> Should yield only jmiller
            // expression1 AND expression4 --> Should yield all users
starting with J EXCEPT jmiller
            String finalExpression = expression1 + " AND " +
expression2;
            //
            // Make the vdx endpoint call
            EntityAttributeMap map = vdxStub.query("user", attributes,
finalExpression);
            EntryArray entryArray = map.getEntries();
            Entry [] entries = entryArray.getEntry();
            if(entries != null)
            {
                for(int index = 0; index < entries.length; index++)
                {
                    String dnKey = entries[index].getKey();
                    System.out.println("DN Key = " + dnKey);
                    AttributeArray attributeArray =
entries[index].getValues();
                    Attribute [] attributeData =
attributeArray.getAttribute();
                    for(int attrIndex = 0; attrIndex <
attributeData.length; attrIndex++)
                    {
                        //
                        // Determine how to handle the return data
                        examineAttributeData(attributeData[attrIndex],
" ");
                    }
                    
                }
            }
        }
        catch(VdxServiceException error) 
        {
            System.out.println(error.getReason() );
            throw new Exception(error.getReason() );
        }
        catch(RemoteException error) 
        {
            System.out.println(error.getMessage() );
            throw new Exception(error.getMessage() );
        }
    }


    public void getVersionTestCase()
    throws Exception
    {
    System.out.println("\nCalling getVersionTestCase() test
case");

  try
  {
    IRemoteVdx vdxStub = getVdxStub(url, username, password);
            VersionVO version = vdxStub.getVersion();
            System.out.println("Version : " + version.getValue() );
  }
          catch(RemoteException error) 
          {
                System.out.println(error.getMessage() );
                throw new Exception(error.getMessage() );
          }
    }


    public void getAttributeTestCase()
    throws Exception
    {
      System.out.println("\nCalling getAttributeTestCase() test
case");

          try
          {
     IRemoteVdx vdxStub = getVdxStub(url, username, password);

            String recipient =
"cn=jmiller,ou=users,ou=idmsample,o=netiq";
            String entity = "user";
            for(int attributeIndex = 0; attributeIndex <
userAttributes.length; attributeIndex++)
            {
                //
                // Now, get the values for each attribute from the VDX
layer
                Attribute attributeData =
vdxStub.getAttribute(recipient, 
                            entity, userAttributes[attributeIndex]);
                //
                // Determine how to handle the return data
                examineAttributeData(attributeData,
userAttributes[attributeIndex]);
            }
         }
        catch(VdxServiceException error) 
        {
            System.out.println(error.getReason() );
            throw new Exception(error.getReason() );
        }
        catch(RemoteException error) 
        {
            System.out.println(error.getMessage() );
            throw new Exception(error.getMessage() );
        }
   }

    public void getAttributesTestCase()
    throws Exception
    {
      System.out.println("\nCalling getAttributesTestCase() test
case");

          try
          {
     IRemoteVdx vdxStub = getVdxStub(url, username, password);

            String recipient =
"cn=jmiller,ou=users,ou=idmsample,o=netiq";
            String entity = "user";
    StringArray userAttributesArray = new
StringArray(userAttributes);
            AttributeArray attributeArray =
vdxStub.getAttributes(recipient, 
      entity, userAttributesArray);
            Attribute [] attributeData = attributeArray.getAttribute();
            for(int index = 0; index < attributeData.length; index++)
            {
                //
                // Determine how to handle the return data
                examineAttributeData(attributeData[index],
userAttributes[index]);
            }         
    }
        catch(VdxServiceException error) 
        {
            System.out.println(error.getReason() );
            throw new Exception(error.getReason() );
        }
        catch(RemoteException error) 
        {
            System.out.println(error.getMessage() );
            throw new Exception(error.getMessage() );
        }
   }


    private void examineAttributeData(Attribute _attribute, String _attributeName)
    throws Exception
    {
        AttributeType type = _attribute.getType();
       System.out.println("Attribute type : " + type);
        //
        // What type are we dealing with?
        if(type.getValue().compareTo(AttributeType._Integer) == 0)
        {
            IntegerArray intArray = _attribute.getIntegers();
            int [] intData = intArray.getInt();
            if(intData == null)
                System.out.println(_attributeName + " attribute : " +
"null because no attribute value exists.");
            else
            {
                for(int intIndex = 0; intIndex < intData.length;
intIndex++)
                {
                    System.out.println(_attributeName + " attribute : "
+ intData[intIndex]);
                }
            }
        }
        else if(type.getValue().compareTo(AttributeType._Boolean) == 0)
        {
            BooleanArray boolArray = _attribute.getBooleans();
            boolean [] booleanData = boolArray.getBoolean();
            if(booleanData == null)
                System.out.println(_attributeName + " attribute : " +
"null because no attribute value exists.");
            else
            {
                for(int boolIndex = 0; boolIndex < booleanData.length;
boolIndex++)
                {
                    System.out.println(_attributeName + " attribute : "
+ booleanData[boolIndex]);
                }
            }
        }
        else if( (type.getValue().compareTo(AttributeType._String) ==
0) ||
                 (type.getValue().compareTo(AttributeType._DN) == 0) )
        {
            StringArray dataArray = _attribute.getStrings();
            String [] stringData = dataArray.getString();
            if(stringData == null)
                System.out.println(_attributeName + " attribute : " +
"null because no attribute value exists.");
            else
            {
                for(int strIndex = 0; strIndex < stringData.length;
strIndex++)
                {
                    System.out.println(_attributeName + " attribute : "
+ stringData[strIndex]);
                }
            }
        }
        else if(type.getValue().compareTo(AttributeType._Binary) == 0)
        {
            ByteArrayArray byteArray = _attribute.getBinaries();
            byte [][] byteData = byteArray.getBase64Binary();
            if(byteData == null)
                System.out.println(_attributeName + " attribute : " +
"null because no attribute value exists.");
            else
            {
                for(int byteIndex = 0; byteIndex < byteData.length;
byteIndex++)
                {
                    byte [] data = byteData[byteIndex];
                    // 
                    // Save the data to a gif file and view it to
                    // make sure the binary return data is correct.
                    try
                    {
                        File fileObj = new File("C:\\temp\\photo.gif");
                        if(fileObj.exists())
                            fileObj.delete();
                        FileOutputStream fout = new
FileOutputStream(fileObj);
                        fout.write(data);
                        fout.flush();
                    }
                    catch(FileNotFoundException fne)
                    {
                        throw new Exception(fne.getMessage());
                    }
                    catch(IOException ioe)
                    {
                        throw new Exception(ioe.getMessage());
                    }
                }
            }
        }
        else if(type.getValue().compareTo(AttributeType._Time) == 0)
        {
            DateArray dateArray = _attribute.getDates();
            Calendar [] calendar = dateArray.getDatetime();
            if(calendar == null)
                System.out.println(_attributeName + " attribute : " +
"null because no attribute value exists.");
            else
            {
                for(int calIndex = 0; calIndex < calendar.length;
calIndex++)
                {
                    System.out.println(_attributeName + " attribute : "
+ calendar[calIndex].getTime().toString());
                }
            }
        }
        
    }


    /**
     * Method to obtain the remote interface to the Vdx endpoint
     * @param _url
     * @param _username
     * @param _password
     * @return IRemoteMetrics interface 
     * @throws Exception
     */
    private IRemoteVdx getVdxStub(String _url, String _username, String
_password)
    throws Exception
    {
        Properties properties = new Properties();
        properties.put(Context.INITIAL_CONTEXT_FACTORY,
"org.jnp.interfaces.NamingContextFactory");

        String lookup =
"xmlrpc:soap:com.netiq.ws.client.vdx.VdxService";

        InitialContext ctx = new InitialContext();
        VdxService svc = (VdxService) ctx.lookup(lookup);

        Stub stub = (Stub)svc.getIRemoteVdxPort();

        stub._setProperty(Stub.USERNAME_PROPERTY, _username);
        stub._setProperty(Stub.PASSWORD_PROPERTY, _password);
        stub._setProperty(Stub.SESSION_MAINTAIN_PROPERTY,
Boolean.TRUE);
        stub._setProperty(Stub.ENDPOINT_ADDRESS_PROPERTY, _url);

        return (IRemoteVdx) stub;
    }

}