Connect SOAP API Developer’s Guide Common Coding Tasks

This section describes how to perform the following common coding tasks when using Xactly Connect:

Table 178: Common Coding Tasks

Screen Shot 2016-07-29 at 1.10.26 PM

 

Getting an Instance of XService

You can get an instance of XService by doing the following:

  • Java applications
    Use the getDiscoveryService() method, as shown in the following:

              XService service = new XServiceServiceLocator().
                 getDiscoveryService(new java.net.URL(
                 "http://www.xactlycorp.com/icm/services/DiscoveryService"));
  • NET applications
     Use the XServiceService() method, as shown in the following:
              XService.XServiceService service =
                 new XService.XServiceService();

Maintaining the Session State Between API Calls

You can maintain session state between API calls by doing the following:

  • Java applicationsCall setMaintainSession(true) on the binding. For example,
              XService service = new XServiceServiceLocator().
                 getDiscoveryService(new java.net.URL(
                 "http://www.xactlycorp.com/icm/services/DiscoveryService"));
    
              ((DiscoveryServiceSoapBindingStub) service).
                 setMaintainSession(true);
    
  • .NET applications
    Set service.CookieContainer = cookies, as shown in the following:

              System.Net.CookieContainer cookies =
                 new System.Net.CookieContainer();
    
              XService.XServiceService service =
                 new XService.XServiceService();
              service.CookieContainer = cookies;

Logging into the Xactly Connect Server

You can log into the Xactly Connect Server by doing the following:

  • Java applications
       String username = "user@xactlycorp.com";
       String password = "password";
       LoginResponse lr = service.login(username, password, "Incent");
       ((DiscoveryServiceSoapBindingStub) service).clearHeaders();
       String sessionId = lr.getSessionId();
       String serverUrl = lr.getServerUrl();
       ((DiscoveryServiceSoapBindingStub) service).
          _setProperty(Stub.ENDPOINT_ADDRESS_PROPERTY, serverUrl);
       ((DiscoveryServiceSoapBindingStub) service).setHeader(new
          XServiceServiceLocator().getServiceName().getNamespaceURI(),
          "SessionId", sessionId);
       ((DiscoveryServiceSoapBindingStub) service).setHeader(new
          XServiceServiceLocator().getServiceName().getNamespaceURI(),
          "UserName", username);
          if (!lr.isAuthenticated()) {
             System.out.println("Login Failed.");
             System.exit(-1);
}

                   

  • .NET applications
          string username = "username";
          string password = "Xactly200";
          XService.LoginResponse loginResponse =
             service.login(username, password);
          toolkitClient.log(loginResponse);

 

Uploading Order Stage Objects

You can upload Order Stage objects using the Xactly Incent Order Stage Upload template. The upload method returns an UploadResponse object which contains an array of ErrorCode objects listing any errors that have occurred during the upload process.

The code segment calls the getBytesFromFile method (explained in the section “Uploading Order Stage Objects” on page 163) to convert the upload file into a byte array. After the data is converted, the code invokes the upload service method to upload the data to Order Staging.

The following shows an example of how to use the upload method in a Java application.

String filename = "C:\\temp\\orderupload.xls";
   File uploadFile = new File(filename);
   byte[] uploadBytes = getBytesFromFile(uploadFile);
   UploadResponse uploadResponse =
         service.upload(uploadBytes, "OrderStage", true);
      long endTime = System.currentTimeMillis();


Checking for Operation Success or Failure

Every response object has a property method called isResult() that you can use to check whether an operation has successfully completed or failed.
The isResult() method returns true then the operation is successful.
The following shows an example of how to use the isResult() method in a Java application:

UploadResponse uploadResponse =
       service.upload(uploadBytes, "OrderStage", true);
   long endTime = System.currentTimeMillis();
   if (!uploadResponse.isResult()) {
       System.out.println("Error Uploading Order Stage. Exiting...");
       System.exit(-2);

}

 

Persisting Order Stage Objects

You can use the save() and saveOrderStage() methods to persist Order Stage objects. The save() method expects an object with the identities of the reference entities resolved. The saveOrderStage() method, on the other hand, does not expect you to set the identity of reference entities.

For example, Order Stage objects reference entities such as Product, Customer, and Geography. When you attempt to persist an Order Stage object with product information, the save() method expects the identity of the object while the saveOrder- Stage() method requires only the name of the product.

It is recommended that you use the saveOrderStage() method to create new Order Stage objects, and the save() method to update existing Order Stage objects.

Validating a Batch

You can validate a batch using the validateBatch() method, which accepts the name of the batch as a parameter. You must validate a batch before you can per- form calculations against it.

The following shows an example of how to use the validateBatch() method in a Java application:

  AsynchResponse asyncResponse = service.validateBatch(batchName);
   if (!asyncResponse.isResult()) {
       System.out.println("Error Validating batch. Exiting.");
             System.exit(-2);
          }

When a batch validation is started, the response is an asynchronous response contain- ing the transaction ID of the process. See “Validating a Batch of Orders” on page 170 for an example of how to validate a batch using a Java application,

 

Determining if a Batch Validated Successfully

After a batch validation is started, the response object AsynchResponse contains the transaction ID of the process. You can use this transaction ID with the search() method to determine the status of the process.

The following shows an example of how to determine whether a batch validated successfully in a Java application:

   // Create the ValidationStatusWSO object
   ValidationStatusWSO valStatus = new ValidationStatusWSO();
   // Set the batch name for the validation
   valStatus.setBatchName(batchName);
   // Set the transaction ID from the response object
   valStatus.setTransactionId(launchResponse.getTxnId());
   // Search for the validation status
   SearchResponse valSearchResult = service.search(valStatus);
// Obtain the search records from the search response and check
   // the status of the currentState property on the validation
   // status object
 if(valSearchResult.getSearchRecords() != null &&
          valSearchResult.getSearchRecords().length > 0) {
       ValidationStatusWSO vs =
          (ValidationStatusWSO)valSearchResult.getSearchRecords()[0];
       if (vs != null &&
             !(vs.getCurrentState().equals(

“VALIDATE_PROCESSING_FINISHE”) { // Batch validated successfully

}

}

See “Validating a Batch of Orders” on page 170 for an example of how to validate a batch using a Java application, For more information about the validation status codes, see “ValidationStatusWSO” on page 93.

 

Performing Calculations on a Batch

You can perform calculations on a batch using the calculateBatch() method. You have the following options when performing calculations:

  • You can process a batch through credit calculations, using the
    CREDIT_PROCESSING_ENUM parameter
  • You can process a batch through incentives in a single operation, using the INCENT_PROCESSING_ENUM parameter

The following shows an example of how to use the calculateBatch() method to
process a batch through incentives in a Java application:

AsynchResponse asyncResponse = service.calculateBatch(batchName,
          “INCENT_PROCESSING_ENUM”);
if (!asyncResponse.isResult()) {
            System.out.println(“Error Calculating batch. Exiting.”);
            System.exit(-2);
 }

When a calculation is started, the response is an asynchronous response containing the transaction ID of the process.

See “Performing Calculations on a Batch of Orders” on page 175 for an example of how to calculate a batch using a Java application, For more information about the process status codes, see “ProcessStatusWSO” on page 84.

 

Searching for Failed Orders in a Batch

You can search for failed orders in a batch by doing the following:

  1. Create an OrderStageWSO object
  2. Set the batch name that you want to search for failed orders
  3. Set the itemStatus property on the object to Failed
  4. Call the search() method

For example, using Java, you can do the following:

OrderStageWSO failedOrders = new OrderStageWSO();
failedOrders.setBatchName(“TestBatch”);
failedOrders.setItemStatus(“Failed”);

SearchResponse sr = service.search(failedOrders);

For a general example of how to search for Xactly objects using a Java application, see “Searching Xactly Objects” on page 191.

Moving Failed Orders to a Different Batch

You can move reassign failed Order Stage objects from one batch to another batch by doing the following:

  1. Search for failed orders in a batch and build a list containing the unique identifier of each failed order.
    See “Searching for Failed Orders in a Batch” on page 161 for more information on searching for failed orders in a batch.
  2. Call the reassignOrderStageBatch() method with the list of failed orders and the name of the batch to which you want to move the orders. The batch to which you are moving the orders must already exists in the application.

Deleting a Batch

You can delete a batch using the delete() method. When using the method, you need to specify a batch object that is fully resolved with the ID field specified.
The following prerequisites must also be met before you can delete a batch:

  • All calculation results, processed order items, staged orders in that batch must be
    deleted
  • No other batches should be in the validating state when you call the delete() method. If you attempt to delete a batch while other batches are validating, you receive following error message: “Order Stage validate operation in progress.”

If you know only the batch name and need to perform a delete operation, search for the batch first and pass the search result object as the parameter to the delete() method.

Java Sample Applications
This section describes the Java samples applications available with Xactly Connect. The sample applications perform the following functions:

Uploading Order Stage Objects Downloading Order Stage Objects Validating a Batch of Orders
Performing Calculations on a Batch of Orders Creating a Product
Uploading a Hierarchy of Objects
Searching Xactly Objects
Determining Xactly Incent Object Information

Uploading Order Stage Objects
This sample shows how to upload Order Stage objects using the Xactly Incent Order Stage Upload template. The upload method returns an UploadResponse object which contains an array of ErrorCode objects listing any errors that have occurred during the upload process.

package com.xactly.icm.xtoolkit.client;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import com.xactly.icm.xtoolkit.service.XService;
import com.xactly.icm.xtoolkit.service.XServiceServiceLocator;
import com.xactly.icm.xtoolkit.service.DiscoveryServiceSoapBindingStub;
import com.xactly.icm.xtoolkit.wso.LoginResponse;
import com.xactly.icm.xtoolkit.wso.SearchResponse;
import com.xactly.icm.xtoolkit.wso.UploadResponse;
import com.xactly.icm.xtoolkit.wso.UserBatchWSO;
import com.xactly.icm.xtoolkit.wso.XObject;

public class OrderStageUpload {
       public static void main(String args[]) throws Exception{
               XService service = new XServiceServiceLocator().
                      getDiscoveryService(new java.net.URL(
                      “http://www.xactlycorp.com/icm/services/DiscoveryService”));
               ((DiscoveryServiceSoapBindingStub) service).
                      setMaintainSession(true);

               String username = “demouser@xactlycorp.com”;
               String password = “password”;

               LoginResponse lr = service.login(username, password, “Incent”);
               ((DiscoveryServiceSoapBindingStub) service).clearHeaders();

               String sessionId = lr.getSessionId();
               String serverUrl = lr.getServerUrl();

               ((DiscoveryServiceSoapBindingStub) service).
                   _setProperty(Stub.ENDPOINT_ADDRESS_PROPERTY, serverUrl);
               ((DiscoveryServiceSoapBindingStub) service).setHeader(new
                     XServiceServiceLocator().getServiceName().getNamespaceURI(),
                    “SessionId”, sessionId);
               ((DiscoveryServiceSoapBindingStub) service).setHeader(new
                     XServiceServiceLocator().getServiceName().getNamespaceURI(),
                     “UserName”, username);

               if (!lr.isAuthenticated()) {
                     System.out.println(“Login Failed.”);
                     System.exit(-1);
               }
          String filename = “C:\\temp\\orderupload.xls”;
          File uploadFile = new File(filename);
          byte[] uploadBytes = getBytesFromFile(uploadFile);
          UploadResponse uploadResponse =
                service.upload(uploadBytes, “OrderStage”, true);
          long endTime = System.currentTimeMillis();

          if (!uploadResponse.isResult()) {
                System.out.println(“Error Uploading Order Stage. Exiting…”);
                System.exit(-2);
           }

    }
   public static byte[] getBytesFromFile(File file) throws
               Exception, IOException {
         InputStream is = new FileInputStream(file);

         long length = file.length();

        if (length > Integer.MAX_VALUE) {
              throw new Exception(“File too large”);
       }

        byte[] bytes = new byte[(int)length];

        int offset = 0;
        int numRead = 0;
        while (offset < bytes.length && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
                offset += numRead;
}

      if (offset < bytes.length) {
              throw new IOException(“Could not completely read file” +
                     file.getName());
}
      is.close();
      return bytes;
}

}

Step 1: Getting an Instance of XService

The first step involves getting an the instance of XService and instructing the system to maintain the session.

   XService service = new XServiceServiceLocator().
       getDiscoveryService(new java.net.URL(
       "http://www.xactlycorp.com/icm/services/DiscoveryService"));
   ((DiscoveryServiceSoapBindingStub) service).
       setMaintainSession(true);

Step 2: Logging into the Xactly Connect Server

The next step involves logging into the Xactly Connect Server.

   String username = "demouser@xactlycorp.com";
   String password = "password";
   LoginResponse lr = service.login(username, password, "Incent");
   ((DiscoveryServiceSoapBindingStub) service).clearHeaders();
   String sessionId = lr.getSessionId();
   String serverUrl = lr.getServerUrl();
   ((DiscoveryServiceSoapBindingStub) service).
       _setProperty(Stub.ENDPOINT_ADDRESS_PROPERTY, serverUrl);
   ((DiscoveryServiceSoapBindingStub) service).setHeader(new
       XServiceServiceLocator().getServiceName().getNamespaceURI(),
       "SessionId", sessionId);
   ((DiscoveryServiceSoapBindingStub) service).setHeader(new
       XServiceServiceLocator().getServiceName().getNamespaceURI(),
       "UserName", username);
 if (!lr.isAuthenticated()) {
          System.out.println("Login Failed.");
          System.exit(-1);

}

Step 3: Converting and Uploading Order Stage Objects

This section of the code calls the getBytesFromFile method (defined later in the example) to convert the upload file into a byte array. After the data is converted, the code invokes the upload service method to upload the data to Order Staging.

   String filename = "C:\\temp\\orderupload.xls";
   File uploadFile = new File(filename);
   byte[] uploadBytes = getBytesFromFile(uploadFile);
   UploadResponse uploadResponse =
         service.upload(uploadBytes, "OrderStage", true);
     long endTime = System.currentTimeMillis();
 

Step 4: Verifying the Success of the Upload Operation

This section of the code checks the uploadResponse object to verify that the upload was successful.

   if (!uploadResponse.isResult()) {
       System.out.println("Error Uploading Order Stage. Exiting...");
       System.exit(-2);

}

 

Downloading Order Stage Objects

This sample shows how to download the Order Stage objects that were uploaded in the sample application described in “Uploading Order Stage Objects” on page 163. The sample then searches for a Period Object using a period name.

Since the download of Order Stage objects is an asynchronous process, the application performs the following operations:

  • Initiates the download using the initiateDownload method, which returns an AsynchResponse object containing a transaction ID for the new download.
  • Uses the transaction ID to download the file. The file is returned as a byte[] array which is then written to a file.

package com.xactly.icm.xtoolkit.client;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import com.xactly.icm.xtoolkit.service.XService;
import com.xactly.icm.xtoolkit.service.XServiceServiceLocator;
import com.xactly.icm.xtoolkit.service.DiscoveryServiceSoapBindingStub;
import com.xactly.icm.xtoolkit.wso.AsynchResponse;
import com.xactly.icm.xtoolkit.wso.LoginResponse;
import com.xactly.icm.xtoolkit.wso.PeriodWSO;
import com.xactly.icm.xtoolkit.wso.SearchResponse;
import com.xactly.icm.xtoolkit.wso.UploadResponse;
import com.xactly.icm.xtoolkit.wso.UserBatchWSO;
import com.xactly.icm.xtoolkit.wso.XObject;

public class OrderStageDownload {
   public static void main(String args[]) throws Exception{
XService service = new XServiceServiceLocator().
   getDiscoveryService(new java.net.URL(
   "http://www.xactlycorp.com/icm/services/DiscoveryService"));
((DiscoveryServiceSoapBindingStub) service).
   setMaintainSession(true);
String username = "demouser@xactlycorp.com";
String password = "password";
LoginResponse lr = service.login(username, password, "Incent");
((DiscoveryServiceSoapBindingStub) service).clearHeaders();
String sessionId = lr.getSessionId();
String serverUrl = lr.getServerUrl();
((DiscoveryServiceSoapBindingStub) service).
   _setProperty(Stub.ENDPOINT_ADDRESS_PROPERTY, serverUrl);
((DiscoveryServiceSoapBindingStub) service).setHeader(new
   XServiceServiceLocator().getServiceName().getNamespaceURI(),
   "SessionId", sessionId);
((DiscoveryServiceSoapBindingStub) service).setHeader(new
   XServiceServiceLocator().getServiceName().getNamespaceURI(),
   "UserName", username);
if (!lr.isAuthenticated()) {
   System.out.println("Login Failed.");
   System.exit(-1);

}

                      String periodName = “DEC-2006”;

PeriodWSO periodWSO = new PeriodWSO();

periodWSO.setName(periodName);
SearchResponse searchResponse = service.search(periodWSO);
XObject[] srXObjs = searchResponse.getSearchRecords();
if (srXObjs != null && srXObjs.length > 0)
   periodWSO = (PeriodWSO)srXObjs[0];
String filename = "C:\\temp\\orderstagedownload.txt";
AsynchResponse asyncResponse =
   service.initiateDownload(periodWSO.getId(),
   "OrderStage", 0, false);
if (!asyncResponse.isResult()) {
   System.out.println("Error downloading Order Stage objects.");
   System.exit(-2);
}
Long downloadId = asyncResponse.getTxnId();
DownloadInfoWSO di = new DownloadInfoWSO();
di.setId(downloadId);
SearchResponse dr = service.search(di);
if (dr.isResult()) {
       DownloadInfoWSO sdr =
          (DownloadInfoWSO)dr.getSearchRecords()[0];
       if(!sdr.getDownloadState().equals("FAILED")) {
          while(sdr.getDownloadState().equals("IN PROGRESS")) {
             Thread.sleep(5000);
             dr = service.search(di);
             sdr = (DownloadInfoWSO)dr.getSearchRecords()[0];
          }
          byte[] bytes = service.download(downloadId);
          OutputStream os = new FileOutputStream(new File(filename));
          os.write(bytes);
          os.close();

}

else {

          System.out.println("Download Failed");
       }
    } 
}

     }

Step 1: Getting an Instance of XService

The first step involves getting an the instance of XService and instructing the system to maintain the session.

     XService service = new XServiceServiceLocator().
         getDiscoveryService(new java.net.URL(
         "http://www.xactlycorp.com/icm/services/DiscoveryService"));
     ((DiscoveryServiceSoapBindingStub) service).setMaintainSession(true);

Step 2: Logging into the Xactly Connect Server

The next step involves logging into the Xactly Connect Server.

     String username = "demouser@xactlycorp.com";
     String password = "password";
     LoginResponse lr = service.login(username, password, "Incent");
     ((DiscoveryServiceSoapBindingStub) service).clearHeaders();
        String sessionId = lr.getSessionId();
        String serverUrl = lr.getServerUrl();


((DiscoveryServiceSoapBindingStub) service).
       _setProperty(Stub.ENDPOINT_ADDRESS_PROPERTY, serverUrl);
   ((DiscoveryServiceSoapBindingStub) service).setHeader(new
       XServiceServiceLocator().getServiceName().getNamespaceURI(),
       "SessionId", sessionId);
   ((DiscoveryServiceSoapBindingStub) service).setHeader(new
       XServiceServiceLocator().getServiceName().getNamespaceURI(),
       "UserName", username);
       if (!lr.isAuthenticated()) {
          System.out.println("Login Failed.");
          System.exit(-1);

}

Step 3: Preparing the Period Object

This section of the code prepares the Period object for use in a search operation.

   String periodName = "DEC-2006";
   PeriodWSO periodWSO = new PeriodWSO();
   periodWSO.setName(periodName);

 

Step 4: Performing a Search for the Uploaded Objects

This section of the code performs a search (using the Period Object as a parameter) for the Order Stage objects that were uploaded in the sample application described in “Uploading Order Stage Objects” on page 163.

   SearchResponse searchResponse = service.search(periodWSO);
   XObject[] srXObjs = searchResponse.getSearchRecords();
   if (srXObjs != null && srXObjs.length > 0)
       periodWSO = (PeriodWSO)srXObjs[0];

 

Step 5: Initiating the Download

This section of the code initiates the download process, which is an asynchronous operation. The initiateDownload operation provides a download identifier that is used later in the program to download the file.

   String filename = "C:\\temp\\orderstagedownload.txt";
   AsynchResponse asyncResponse =
       service.initiateDownload(periodWSO.getId(),
       "OrderStage", 0, false);
   if (!asyncResponse.isResult()) {
       System.out.println("Error downloading Order Stage objects.");
       System.exit(-2);
   }

Step 6: Downloading the Information

This section of the code checks the download status and, if COMPLETE, downloads the file from the Connect Server using the download ID determined in the previous step.

   Long downloadId = asyncResponse.getTxnId();
   DownloadInfoWSO di = new DownloadInfoWSO();
   di.setId(downloadId);
   SearchResponse dr = service.search(di);
   if (dr.isResult()) {
       DownloadInfoWSO sdr = (DownloadInfoWSO)dr.getSearchRecords()[0];
       if(!sdr.getDownloadState().equals("FAILED")) {
          while(sdr.getDownloadState().equals("IN PROGRESS")) {
             Thread.sleep(5000);
             dr = service.search(di);
             sdr = (DownloadInfoWSO)dr.getSearchRecords()[0];
          }
          byte[] bytes = service.download(downloadId);
          ...
 

Step 7: Writing the Information to a File

This section of the code writes the content returned by the download method to a file.

   OutputStream os = new FileOutputStream(new File(filename));
   os.write(bytes);
   os.close();

 

Validating a Batch of Orders

This sample shows how to validate a batch of Xactly Order Items within Order Staging.

   package com.xactly.icm.xtoolkit.client;
   import com.xactly.icm.xtoolkit.service.XService;
   import com.xactly.icm.xtoolkit.service.XServiceServiceLocator;
   import com.xactly.icm.xtoolkit.service.DiscoveryServiceSoapBindingStub;
   import com.xactly.icm.xtoolkit.wso.AsynchResponse;
   import com.xactly.icm.xtoolkit.wso.ErrorCode;
   import com.xactly.icm.xtoolkit.wso.LoginResponse;
   import com.xactly.icm.xtoolkit.wso.SearchResponse;
   import com.xactly.icm.xtoolkit.wso.ValidationError;
   import com.xactly.icm.xtoolkit.wso.ValidationResponse;
   import com.xactly.icm.xtoolkit.wso.ValidationStatusWSO;
   import com.xactly.icm.xtoolkit.wso.XObject;
public class ValidateOrders {
 private static XService service;

public static void main(String[] args) throws Exception {
 service = new XServiceServiceLocator().

 getDiscoveryService(new java.net.URL(

 "http://www.xactlycorp.com/icm/services/DiscoveryService"));
 ((DiscoveryServiceSoapBindingStub) service).

 setMaintainSession(true);

 String username = "username";
 String password = "password";
 String batchName = "DemoBatch";

 LoginResponse lr = service.login(username, password, "Incent");
 ((DiscoveryServiceSoapBindingStub) service).clearHeaders();

 String sessionId = lr.getSessionId();
 String serverUrl = lr.getServerUrl();

 ((DiscoveryServiceSoapBindingStub) service).
 _setProperty(Stub.ENDPOINT_ADDRESS_PROPERTY, serverUrl);

 ((DiscoveryServiceSoapBindingStub) service).setHeader(new
 XServiceServiceLocator().getServiceName().getNamespaceURI(),
 "SessionId", sessionId);

 ((DiscoveryServiceSoapBindingStub) service).setHeader(new
 XServiceServiceLocator().getServiceName().getNamespaceURI(),
 "UserName", username);

 if (!lr.isAuthenticated()) {
 System.out.println("Login failed!");
 System.exit(-1);

} 

 AsynchResponse asyncResponse =
 service.validateBatch(batchName);

 if (!asyncResponse.isResult()) {
 System.out.println("Error Validating batch. Exiting.");
 log(asyncResponse);
 System.exit(-2);

} 

 ValidationStatusWSO vsXObj = new ValidationStatusWSO();
 vsXObj.setBatchName(batchName);
 vsXObj.setTransactionId(asyncResponse.getTxnId());
 Thread.sleep(5000);

while (true) {
 SearchResponse searchResponse = service.search(vsXObj);
 XObject[] srXObjs = searchResponse.getSearchRecords();
 if (srXObjs != null && srXObjs.length > 0) {

 ValidationStatusWSO vs =
 (ValidationStatusWSO)srXObjs[0];

 if (vs != null && !vs.getCurrentState().equals(
 "VALIDATE_PROCESSING_ENUM"))

break; } 

 Thread.sleep(1000);
 }

 ValidationResponse validationResponse =
 service.getValidationErrorForTransaction(

 vsXObj.getTransactionId());
 log(validationResponse);
 if (!validationResponse.isResult() ||

 validationResponse.getValidationErrors() != null) {
 System.out.println("Validation Errors found. Exiting.");
 System.exit(-2);

} } 

public static void log(AsynchResponse response) {
 if (response == null)

return; 

 System.out.println("Result :" + response.isResult());
 System.out.println("Transaction ID :" +

 response.getTxnId());

 ErrorCode[] errorCodes = response.getErrorCodes();
 if (errorCodes == null || errorCodes.length == 0)

return; 

 for (int i = 0; i < errorCodes.length; i++) {
 log(errorCodes[i]);

} } 

public static void log(ValidationResponse validationResponse) {
 if(validationResponse == null)

return; 

 ErrorCode ec = validationResponse.getErrorCode();
 if (ec != null)

log(ec); 
ValidationError[] validErrors =
 validationResponse.getValidationErrors();

 if (validErrors == null)
 return;

 System.out.println("Validation Errors: ");
 for(int i=0; i<validErrors.length; i++) {

 ValidationError validError = validErrors[i];
 System.out.println("Error No:" + i);
 System.out.println("Order Code:" +

 validError.getOrderCode());
 System.out.println("Item Code:" +
 validError.getItemCode());

 System.out.println("Field Name:" +
 validError.getErrorFieldName());
 System.out.println("Field Value:" +

 validError.getErrorFieldValue());
 System.out.println("Error Message:" +

 validError.getErrorMessage());
 System.out.println("");

} } 

 public static void log(ErrorCode errorCode) {
 if (errorCode == null)

return; 

 if (errorCode.getCode() != null)
 System.out.println("Code :" + errorCode.getCode());

 if (errorCode.getReason() != null)
 System.out.println("Reason :" + errorCode.getReason());

 if (errorCode.getStackTrace() != null)
 System.out.println("Stack Trace : " +

 errorCode.getStackTrace());

 } 

} 


Step 1: Getting an Instance of XService

The first step involves getting an the instance of XService and instructing the system to maintain the session.

XService service = new XServiceServiceLocator().
getDiscoveryService(new java.net.URL(
“http://www.xactlycorp.com/icm/services/DiscoveryService”));

((DiscoveryServiceSoapBindingStub) service).setMaintainSession(true);

 

Step 2: Logging into the Xactly Connect Server

The next step involves logging into the Xactly Connect Server.

String username = “demouser@xactlycorp.com”;
String password = “password”;

LoginResponse lr = service.login(username, password, “Incent”);
((DiscoveryServiceSoapBindingStub) service).clearHeaders();

String sessionId = lr.getSessionId();
String serverUrl = lr.getServerUrl();

((DiscoveryServiceSoapBindingStub) service).
_setProperty(Stub.ENDPOINT_ADDRESS_PROPERTY, serverUrl);

((DiscoveryServiceSoapBindingStub) service).setHeader(new
XServiceServiceLocator().getServiceName().getNamespaceURI(),
“SessionId”, sessionId);

((DiscoveryServiceSoapBindingStub) service).setHeader(new
XServiceServiceLocator().getServiceName().getNamespaceURI(),
“UserName”, username);

if (!lr.isAuthenticated()) {
System.out.println(“Login Failed.”);
System.exit(-1);

}

Step 3: Validating the Batch

This section of the code validates the batch using the batch name, using the batch name from the previously uploaded file.

AsynchResponse asyncResponse = service.validateBatch(batchName);
if (!asyncResponse.isResult()) {

System.out.println(“Error Validating batch. Exiting.”);
log(asyncResponse);
System.exit(-2);

}

Step 4: Checking the Validation Status

Since validating a batch is an asynchronous operation, this section of the code sleeps for a period of time and then checks the validation status. A status of VALIDATE_PROCESSING_ENUM indicates that the validation is still in progress.

ValidationStatusWSO vsXObj = new ValidationStatusWSO();
vsXObj.setBatchName(batchName);
vsXObj.setTransactionId(asyncResponse.getTxnId());
Thread.sleep(5000);

while (true) {
     SearchResponse searchResponse = service.search(vsXObj);
     XObject[] srXObjs = searchResponse.getSearchRecords();
     if (srXObjs != null && srXObjs.length > 0) {

              ValidationStatusWSO vs =
                       (ValidationStatusWSO)srXObjs[0];

             if (vs != null && !vs.getCurrentState().equals(
                      “VALIDATE_PROCESSING_ENUM”))

                 break;

             }

          Thread.sleep(1000);
}

 

Step 5: Logging Validation Errors

This section of the code retrieves any validation errors and logs the errors.

ValidationResponse validationResponse =
service.getValidationErrorForTransaction(

           vsXObj.getTransactionId());
log(validationResponse);
if (!validationResponse.isResult() ||

          validationResponse.getValidationErrors() != null) {
System.out.println(“Validation Errors found. Exiting.”);
System.exit(-2);

}

Step 6: Defining Logging Utility Methods

This section of the code defines two utility methods to log the AsynchResponse and the ValidationResponse.

public static void log(AsynchResponse response) {

           . . .

}

public static void log(ValidationResponse validationResponse) { …

           . . .

}

 

Performing Calculations on a Batch of Orders

This sample shows how to start a calculation process on a batch of orders.

package com.xactly.icm.xtoolkit.client;

import com.xactly.icm.xtoolkit.service.XService;
import com.xactly.icm.xtoolkit.service.XServiceServiceLocator;
import com.xactly.icm.xtoolkit.service.DiscoveryServiceSoapBindingStub;
import com.xactly.icm.xtoolkit.wso.AsynchResponse;
import com.xactly.icm.xtoolkit.wso.CalculationDiagnostics;

import com.xactly.icm.xtoolkit.wso.CalculationResponse;
import com.xactly.icm.xtoolkit.wso.ErrorCode;
import com.xactly.icm.xtoolkit.wso.LoginResponse;
import com.xactly.icm.xtoolkit.wso.ProcessStatusWSO;
import com.xactly.icm.xtoolkit.wso.SearchResponse;
import com.xactly.icm.xtoolkit.wso.XObject;
public class CalculateOrders {
   private static XService service; 
  public static void main(String[] args) throws Exception {
       service = new XServiceServiceLocator().
getDiscoveryService(new java.net.URL(
   "http://www.xactlycorp.com/icm/services/DiscoveryService"));
((DiscoveryServiceSoapBindingStub) service).
   setMaintainSession(true);
String username = "username";
String password = "password";
String batchName = "DemoBatch";
LoginResponse lr = service.login(username, password, "Incent");
((DiscoveryServiceSoapBindingStub) service).clearHeaders();
String sessionId = lr.getSessionId();
String serverUrl = lr.getServerUrl();
((DiscoveryServiceSoapBindingStub) service).
   _setProperty(Stub.ENDPOINT_ADDRESS_PROPERTY, serverUrl);
((DiscoveryServiceSoapBindingStub) service).setHeader(new
   XServiceServiceLocator().getServiceName().getNamespaceURI(),
   "SessionId", sessionId);
((DiscoveryServiceSoapBindingStub) service).setHeader(new
   XServiceServiceLocator().getServiceName().getNamespaceURI(),
   "UserName", username);
if (!lr.isAuthenticated()) {
   System.out.println("Login failed!");
   System.exit(-1);
}

AsynchResponse asyncResponse =
 service.calculateBatch(batchName,
 "INCENT_PROCESSING_ENUM");

if (!asyncResponse.isResult()) {
   System.out.println("Error Calculating batch. Exiting.");
 log(asyncResponse);
 System.exit(-2);
}
ProcessStatusWSO psXObj = new ProcessStatusWSO();
psXObj.setBatchName(batchName);
psXObj.setTransactionId(asyncResponse.getTxnId());
Thread.sleep(5000);
while(true) {
   SearchResponse searchResponse = service.search(psXObj);
   XObject[] srXObjs = searchResponse.getSearchRecords();
   if (srXObjs != null && srXObjs.length > 0) {  
       ProcessStatusWSO ps = (ProcessStatusWSO)srXObjs[0];
       if (ps != null && ps.getCurrentState() != null &&
!(ps.getCurrentState().equals(
       "INCENT_PROCESSING_ENUM") ||
   ps.getCurrentState().equals(
       "CREDIT_PROCESSING_ENUM") ||
   ps.getCurrentState().equals(
       "CREDIT_PROCESSING_FINISHED") ||
         ps.getCurrentState().equals("NEW_ENUM")))
         break;

}
                   Thread.sleep(1000);
              }
System.out.println("Retrieve Calculation Diagnostics.");
   CalculationResponse calcResponse =
       service.getCalculationProcessDiagnostics(batchName);
   log(calcResponse);
   if (!calcResponse.isResult()) {
       System.out.println("Error Retrieving diagnostics. Exiting.");
       System.exit(-2);
   }

         }

public static void log(AsynchResponse response) {
   if (response == null)

return;

   System.out.println("Result :" + response.isResult());
   System.out.println("Transaction ID :" +
       response.getTxnId());
   ErrorCode[] errorCodes = response.getErrorCodes();
   if (errorCodes == null || errorCodes.length == 0)

return;

   for (int i = 0; i < errorCodes.length; i++) {
       log(errorCodes[i]);

                      }

             }

public static void log(CalculationResponse calcResponse) {
   if(calcResponse == null)

return;

   ErrorCode ec = calcResponse.getErrorCode();
   if (ec != null)

log(ec);

   CalculationDiagnostics calcDiag =
       calcResponse.getCalculationDiagnostics();
   System.out.println("Calculation Diagnostics: ");
   System.out.println("Batch Name:" + calcDiag.getBatchName());
   System.out.println("Total Items:" +
       calcDiag.getTotalItems());
   System.out.println("Direct Credits:" +
       calcDiag.getDirectCredits());
   System.out.println("Indirect Credits:" +
       calcDiag.getIndirectCredits());
   System.out.println("Commissions:" +
       calcDiag.getTotalCommissions());
   System.out.println("Bonus:" + calcDiag.getTotalBonus());
   System.out.println("No Credit Items:" +
       calcDiag.getNoCredits());
   System.out.println("No Incentive Items:" +
       calcDiag.getNoIncentives());
   System.out.println("");

}

public static void log(ErrorCode errorCode) {
   if (errorCode == null)
return;
   if (errorCode.getCode() != null)
       System.out.println("Code :" + errorCode.getCode());
   if (errorCode.getReason() != null)
       System.out.println("Reason :" + errorCode.getReason());
   if (errorCode.getStackTrace() != null)
       System.out.println("Stack Trace : " +
          errorCode.getStackTrace());

      }
   }

Step 1: Getting an Instance of XService

The first step involves getting an the instance of XService and instructing the system to maintain the session.

   XService service = new XServiceServiceLocator().
       getDiscoveryService(new java.net.URL(
       "http://www.xactlycorp.com/icm/services/DiscoveryService"));
((DiscoveryServiceSoapBindingStub) service).
       setMaintainSession(true);

Step 2: Logging into the Xactly Connect Server

The next step involves logging into the Xactly Connect Server.

   String username = "demouser@xactlycorp.com";
   String password = "password";
   LoginResponse lr = service.login(username, password, "Incent");
   ((DiscoveryServiceSoapBindingStub) service).clearHeaders();
   String sessionId = lr.getSessionId();
   String serverUrl = lr.getServerUrl();
   ((DiscoveryServiceSoapBindingStub) service).
       _setProperty(Stub.ENDPOINT_ADDRESS_PROPERTY, serverUrl);
   ((DiscoveryServiceSoapBindingStub) service).setHeader(new
       XServiceServiceLocator().getServiceName().getNamespaceURI(),
       "SessionId", sessionId);
   ((DiscoveryServiceSoapBindingStub) service).setHeader(new
       XServiceServiceLocator().getServiceName().getNamespaceURI(),
       "UserName", username);
   if (!lr.isAuthenticated()) {
       System.out.println("Login Failed.");
       System.exit(-1);

}

Step 3: Calculating the Batch

This section of the code calculates the batch using the name from the previously vali- dated batch.

   AsynchResponse asyncResponse = service.calculateBatch(batchName,
       "INCENT_PROCESSING_ENUM");
   if (!asyncResponse.isResult()) {
       System.out.println("Error Calculating batch. Exiting.");
       log(asyncResponse);
       System.exit(-2);

}

Step 4: Checking the Process Status

This section of the code creates a ProcessStatusWSO object, searches for the pro- cess status using the batch name, and then checks the status.

   ProcessStatusWSO psXObj = new ProcessStatusWSO();
   psXObj.setBatchName(batchName);
   psXObj.setTransactionId(asyncResponse.getTxnId());
   Thread.sleep(5000);
   while(true) {
       SearchResponse searchResponse = service.search(psXObj);
       XObject[] srXObjs = searchResponse.getSearchRecords();
       if (srXObjs != null && srXObjs.length > 0) {
          ProcessStatusWSO ps = (ProcessStatusWSO)srXObjs[0];
          if (ps != null && ps.getCurrentState() != null &&
   !(ps.getCurrentState().equals(
       "INCENT_PROCESSING_ENUM") ||
   ps.getCurrentState().equals(
       "CREDIT_PROCESSING_ENUM") ||
   ps.getCurrentState().equals(
       "CREDIT_PROCESSING_FINISHED") ||
   ps.getCurrentState().equals("NEW_ENUM")))
break;

}

   Thread.sleep(1000);
}

Step 5: Retrieving the Calculation Diagnostics

This section of the code retrieves the calculation diagnostics after the processing has completed.

   System.out.println("Retrieve Calculation Diagnostics.");
   CalculationResponse calcResponse =
       service.getCalculationProcessDiagnostics(batchName);
   log(calcResponse);
   if (!calcResponse.isResult()) {
       System.out.println("Error Retrieving diagnostics. Exiting.");
       System.exit(-2);
   }

Step 6: Defining Logging Utility Methods

This section of the code defines three utility methods to log the AsynchResponse, Cal- culationResponse, and the ErrorCode.

public static void log(AsynchResponse response) {

}

public static void log(CalculationResponse calcResponse) {

}

public static void log(ErrorCode errorCode) {

}

 

Creating a Product

This sample shows how to use the ProductWSO object to create a new Xactly product. package com.xactly.icm.xtoolkit.client;

   import com.xactly.icm.xtoolkit.service.XService;
   import com.xactly.icm.xtoolkit.wso.LoginResponse;
   import com.xactly.icm.xtoolkit.wso.ProductWSO;
   import com.xactly.icm.xtoolkit.wso.SaveResponse;
public class CreateProduct {
   public static void main(String args[]) throws Exception {
       XToolkitUtil util = new XToolkitUtil();
       String username = "username";
       String password = "password";
       XService service = util.getXService();
       LoginResponse lr = service.login(username, password, "Incent");
       ((DiscoveryServiceSoapBindingStub) service).clearHeaders();
       String sessionId = lr.getSessionId();
       String serverUrl = lr.getServerUrl();
       ((DiscoveryServiceSoapBindingStub) service).
          _setProperty(Stub.ENDPOINT_ADDRESS_PROPERTY, serverUrl);
       ((DiscoveryServiceSoapBindingStub) service).setHeader(new
          XServiceServiceLocator().getServiceName().getNamespaceURI(),
          "SessionId", sessionId);
       ((DiscoveryServiceSoapBindingStub) service).setHeader(new
          XServiceServiceLocator().getServiceName().getNamespaceURI(),
          "UserName", username);
       util.log(lr);
       if (!lr.isAuthenticated()) {
          System.out.println("Login Failed.");
          System.exit(-1);

}

       ProductWSO product = new ProductWSO();
       product.setName("Connect Product 1");
       product.setDescription(
          "Created from Xactly Connect Client");
       SaveResponse response = service.save(product);
       if (!response.isResult()) {
          System.out.println("Product save failed.");
          System.exit(-2);

}

       util.log(lr);
   }

}

Step 1: Getting an Instance of XService and Logging into the Xactly Connect Server

The first step involves getting an the instance of XService and logging into the Xactly Connect Server.

   XService service = util.getXService();
   LoginResponse lr = service.login(username, password, "Incent");
   ((DiscoveryServiceSoapBindingStub) service).clearHeaders();
   String sessionId = lr.getSessionId();
   String serverUrl = lr.getServerUrl();
   ((DiscoveryServiceSoapBindingStub) service).
       _setProperty(Stub.ENDPOINT_ADDRESS_PROPERTY, serverUrl);
   ((DiscoveryServiceSoapBindingStub) service).setHeader(new
       XServiceServiceLocator().getServiceName().getNamespaceURI(),
       "SessionId", sessionId);
   ((DiscoveryServiceSoapBindingStub) service).setHeader(new
       XServiceServiceLocator().getServiceName().getNamespaceURI(),
       "UserName", username);
   util.log(lr);
   if (!lr.isAuthenticated()) {
       System.out.println("Login Failed.");
       System.exit(-1);

}

Step 2: Creating the Product Object

This step creates a new ProductWSO object and sets the name and description of the object.

   ProductWSO product = new ProductWSO();
   product.setName("Connect Product 1");
   product.setDescription("Created from Xactly Connect Client");

 

 

Step 3: Saving the Product Object

The final step uses the save method to save the ProductWSO object and checks the response for success.

   SaveResponse response = service.save(product);
   if (!response.isResult()) {
       System.out.println("Product save failed.");
       System.exit(-2);

}

Uploading a Hierarchy of Objects

This sample shows how to import data from a Microsoft Excel spreadsheet file and create a hierarchy of positions in the Xactly system.

   package com.xactly.icm.xtoolkit.client;
   import java.io.File;
   import java.text.DateFormat;
   import java.text.SimpleDateFormat;
   import java.util.Map;
   import java.util.HashMap;
   import com.xactly.icm.xtoolkit.wso.XObject;
   import com.xactly.icm.xtoolkit.service.XService;
   import com.xactly.icm.xtoolkit.wso.LoginResponse;
   import com.xactly.icm.xtoolkit.wso.PersonWSO;
   import com.xactly.icm.xtoolkit.wso.PositionWSO;
   import com.xactly.icm.xtoolkit.wso.SaveResponse;
   import com.xactly.icm.xtoolkit.wso.SearchResponse;
   import com.xactly.icm.xtoolkit.wso.TitleWSO;
   import jxl.Cell;
   import jxl.Sheet;
   import jxl.Workbook;
public class UploadHierarchy {
       public static void main(String args[]) throws Exception {
          String inputFile = args[0];
          Workbook workbook =
             Workbook.getWorkbook(new File(inputFile));
          XToolkitUtil l_toolkitUtil = new XToolkitUtil();
          XService service = l_toolkitUtil.getXService();
String username = "username";
String password = "password";
LoginResponse lr = service.login(username, password, "Incent");
((DiscoveryServiceSoapBindingStub) service).clearHeaders();
String sessionId = lr.getSessionId();
String serverUrl = lr.getServerUrl();
((DiscoveryServiceSoapBindingStub) service).
   _setProperty(Stub.ENDPOINT_ADDRESS_PROPERTY, serverUrl);
((DiscoveryServiceSoapBindingStub) service).setHeader(new
   XServiceServiceLocator().getServiceName().getNamespaceURI(),
   "SessionId", sessionId);
((DiscoveryServiceSoapBindingStub) service).setHeader(new
   XServiceServiceLocator().getServiceName().getNamespaceURI(),
   "UserName", username);
if (!lr.isAuthenticated()) {
   System.out.println("Login Failed.");
   System.exit(-1);

}

l_toolkitUtil.log(lr);
Map<String, PositionWSO> positionMap =
   new HashMap<String, PositionWSO>();
Map<String, TitleWSO> titleMap =
   new HashMap<String, TitleWSO>();
Sheet sheet = workbook.getSheet(0);
int row = 1;
while (true) {
   Cell[] cellArray = sheet.getRow(row);
   if (cellArray.length > 0
       && cellArray[0].getContents().equals("<EOF>"))

break;

   String name = cellArray[0].getContents();
   String startDate = cellArray[1].getContents();
   String endDate = cellArray[2].getContents();
   String titleName = cellArray[3].getContents();
   String parentPos = cellArray[4].getContents();
   String personEmpId = cellArray[5].getContents();
   String description = cellArray[6].getContents();
PersonWSO person = new PersonWSO();
person.setEmployeeId(personEmpId);
SearchResponse searchResponse = service.search(person);
XObject[] results = searchResponse.getSearchRecords();
if (results != null && results.length > 0)
   person = (PersonWSO)results[0];
TitleWSO title = titleMap.get(titleName);
if (title == null) {
   title = new TitleWSO();
   title.setName(titleName);
   searchResponse = service.search(title);
   results = searchResponse.getSearchRecords();
   if (results != null && results.length > 0) {
       title = (TitleWSO)results[0];
       titleMap.put(titleName, title);
   }
}
PositionWSO position = null;
if (parentPos !=null && !parentPos.equals("")) {
   position = positionMap.get(parentPos);
   if (position == null) {
       position = new PositionWSO();
       position.setName(parentPos);
       searchResponse = service.search(position);
       results = searchResponse.getSearchRecords();
       if (results != null && results.length > 0) {
          position = (PositionWSO)results[0];
          positionMap.put(position.getName(), position);
       }

} }

if (parentPos != null && !parentPos.equals("") &&
       position == null) {
   l_toolkitUtil.log("Parent Position : " +
       parentPos + " not found. Skipping row");

row++;

continue; }

PositionWSO newPosition = new PositionWSO();
newPosition.setName(name);
DateFormat df =
   DateFormat.getDateInstance(DateFormat.FULL);
SimpleDateFormat formatter =
   new SimpleDateFormat("MM/dd/yyyy");
if (startDate != null) {
             java.util.Calendar cal =
                 java.util.Calendar.getInstance();
             cal.setTime(formatter.parse(startDate.toString()));
             newPosition.setIncentiveStartDate(cal);

}

          if (endDate != null) {
             java.util.Calendar cal =
                 java.util.Calendar.getInstance();
             cal.setTime(formatter.parse(endDate.toString()));
             newPosition.setIncentiveEndDate(cal);

}

          if (title != null)
             newPosition.setTitle(title.getId());
          else {
             l_toolkitUtil.log("Title : " + titleName +
                 " not found. Skipping row");
             row++;

continue; }

          if (parentPos != null && position != null)
             newPosition.setParentPosition(position.getId());
          if (personEmpId != null && person != null)
             newPosition.setParticipant(person.getId());
          if (description != null)
             newPosition.setDescription(description);
          newPosition.setIsActive(new Boolean(true));
          SaveResponse saveResponse = service.save(newPosition);
          l_toolkitUtil.log(saveResponse);
          if (!saveResponse.isResult()) {
             l_toolkitUtil.log("Save failed.");
          }
          else {
             newPosition.setId(saveResponse.getSavedIds()[0]);
             positionMap.put(newPosition.getName(), newPosition);

}

row++;

}

}

}

 

Step 1: Creating a New Workbook to Import Data in a Microsoft Excel Spreadsheet

The first step involves collecting the file name from the command line and importing the Microsoft Excel spreadsheet data into a workbook.

   String inputFile = args[0];
   Workbook workbook = Workbook.getWorkbook(new File(inputFile));

 

Step 2: Logging into the Xactly Connect Server

The next step involves logging into the Xactly Connect Server using XToolkitUtil, which is provided with the Xactly sample applications.

   XToolkitUtil l_toolkitUtil = new XToolkitUtil();
   XService service = l_toolkitUtil.getXService();
   String username = "username";
   String password = "password";
   LoginResponse lr = service.login(username, password, "Incent");
   ((DiscoveryServiceSoapBindingStub) service).clearHeaders();
   String sessionId = lr.getSessionId();
   String serverUrl = lr.getServerUrl();
   ((DiscoveryServiceSoapBindingStub) service).
       _setProperty(Stub.ENDPOINT_ADDRESS_PROPERTY, serverUrl);
   ((DiscoveryServiceSoapBindingStub) service).setHeader(new
       XServiceServiceLocator().getServiceName().getNamespaceURI(),
       "SessionId", sessionId);
   ((DiscoveryServiceSoapBindingStub) service).setHeader(new
       XServiceServiceLocator().getServiceName().getNamespaceURI(),
       "UserName", username);
   l_toolkitUtil.log(lr);

 

Step 3: Creating a New Hashmap for Positions and Titles

The next step involves creating a new hashmap for Xactly positions and titles. Later in the program, these maps are used to ensure that each position and title is processed only once.

   Map<String, PositionWSO> positionMap =
       new HashMap<String, PositionWSO>();
   Map<String, TitleWSO> titleMap =
       new HashMap<String, TitleWSO>();

 

Step 4: Accessing and Storing the Excel Data

The next step involves looping through the rows imported from the Microsoft Excel spreadsheet in Step 1 and storing the data in variables.

   Sheet sheet = workbook.getSheet(0);
   int row = 1;
   while (true) {
       Cell[] cellArray = sheet.getRow(row);
       if (cellArray.length > 0
          && cellArray[0].getContents().equals("<EOF>"))

break;

       String name = cellArray[0].getContents();
       String startDate = cellArray[1].getContents();
       String endDate = cellArray[2].getContents();
       String titleName = cellArray[3].getContents();
       String parentPos = cellArray[4].getContents();
       String personEmpId = cellArray[5].getContents();
       String description = cellArray[6].getContents();

        . . .

}

Step 5: Retrieving Information About the Person

The next step involves retrieving information about the person from the Xactly system using the person’s employee ID that appeared in the imported Excel spreadsheet.

   PersonWSO person = new PersonWSO();
   person.setEmployeeId(personEmpId);
   SearchResponse searchResponse = service.search(person);
   XObject[] results = searchResponse.getSearchRecords();
   if (results != null && results.length > 0)
          person = (PersonWSO)results[0];

Step 6: Retrieving the Title Information

The next step involves retrieving information about the person’s title from the Xactly system using the title that appeared in the imported Excel spreadsheet.

   TitleWSO title = titleMap.get(titleName);
   if (title == null) {
       title = new TitleWSO();
       title.setName(titleName);
       searchResponse = service.search(title);
       results = searchResponse.getSearchRecords();
       if (results != null && results.length > 0) {
          title = (TitleWSO)results[0];
          titleMap.put(titleName, title);
       }

}

Step 7: Retrieving the Position Information

The next step involves retrieving information about the parent position from the Xactly system using the parent position that appeared in the imported Excel spreadsheet.

   PositionWSO position = null;
   if (parentPos !=null && !parentPos.equals("")) {
       position = positionMap.get(parentPos);
       if (position == null) {
          position = new PositionWSO();
          position.setName(parentPos);
          searchResponse = service.search(position);
          results = searchResponse.getSearchRecords();
          if (results != null && results.length > 0) {
             position = (PositionWSO)results[0];
             positionMap.put(position.getName(), position);
          }

}

}

 

Step 8: Creating a New Position Object

The next step involves creating and populating a new Position object that will be part of the hierarchy in the Xactly system. The following code segment shows how to create the new Position object.

   PositionWSO newPosition = new PositionWSO();
   newPosition.setName(name);

 

Step 9: Setting the Parent Position and Other Data

The next step involves setting the parent position (to establish the hierarchy) along with the related information on the new Position object.

   if (parentPos != null && position != null)
       newPosition.setParentPosition(position.getId());
   if (personEmpId != null && person != null)
       newPosition.setParticipant(person.getId());
   if (description != null)
       newPosition.setDescription(description);

 

Step 10: Saving the Position and Checking for Success

The final step involves saving the new Position object in the Xactly system and check- ing the response for success using XToolkitUtil, which is provided with the Xactly sample applications.

   SaveResponse saveResponse = service.save(newPosition);
   l_toolkitUtil.log(saveResponse);
   if (!saveResponse.isResult()) {
       l_toolkitUtil.log("Save failed.");
   }
   else {
       newPosition.setId(saveResponse.getSavedIds()[0]);
       positionMap.put(newPosition.getName(), newPosition);

}

 

Searching Xactly Objects

This sample shows how to use the UserWSO object to set a search criteria, invoke the search method to find matching users, and then use the searchResponse object to iterate through the results to extract the required information.

   package com.xactly.icm.xtoolkit.client;
   import com.xactly.icm.xtoolkit.service.XService;
   import com.xactly.icm.xtoolkit.service.XServiceServiceLocator;
   import com.xactly.icm.xtoolkit.service.DiscoveryServiceSoapBindingStub;
   import com.xactly.icm.xtoolkit.wso.LoginResponse;
   import com.xactly.icm.xtoolkit.wso.SearchResponse;
   import com.xactly.icm.xtoolkit.wso.UserWSO;
   import com.xactly.icm.xtoolkit.wso.XObject;
      public class SearchObjects {
         private static XService service;
         public static void main(String[] args) throws Exception {

service = new XServiceServiceLocator().
   getDiscoveryService(new java.net.URL("
   http://www.xactlycorp.com/icm/services/DiscoveryService"));
((DiscoveryServiceSoapBindingStub) service).
   setMaintainSession(true);
String username = "username";
String password = "password";
/* Login to XConnect Server */
LoginResponse lr = service.login(username, password, "Incent");
(DiscoveryServiceSoapBindingStub) service).clearHeaders();
String sessionId = lr.getSessionId();
String serverUrl = lr.getServerUrl();
((DiscoveryServiceSoapBindingStub) service).
   _setProperty(Stub.ENDPOINT_ADDRESS_PROPERTY, serverUrl);
((DiscoveryServiceSoapBindingStub) service).setHeader(new
   XServiceServiceLocator().getServiceName().getNamespaceURI(),
   "SessionId", sessionId);
((DiscoveryServiceSoapBindingStub) service).setHeader(new
   XServiceServiceLocator().getServiceName().getNamespaceURI(),
   "UserName", username);
if (!lr.isAuthenticated()) {
   System.out.println("Login failed!");
   System.exit(-1);

}

UserWSO user = new UserWSO();
user.setName("xactly");
SearchResponse searchResponse = service.search(user);
if (!searchResponse.isResult()) {
             XObject[] searchObjects =
                 searchResponse.getSearchRecords();
             for(int i=0; i < searchObjects.length; i++) {
                 user = (UserWSO)searchObjects[i];
                 System.out.println("------ Search Result ------");
                 System.out.println("Name: " + user.getName());
                 System.out.println("Email: " + user.getEmail());

} }else {

             System.out.println("Search failed.");
             System.exit(-1);
          }

}

}

Step 1: Getting an Instance of XService

The first step involves getting an the instance of XService and instructing the system to maintain the session.

   XService service = new XServiceServiceLocator().
       getDiscoveryService(new java.net.URL(
       "http://www.xactlycorp.com/icm/services/DiscoveryService"));
   ((DiscoveryServiceSoapBindingStub) service).setMaintainSession(true);

Step 2: Logging into the Xactly Connect Server

The next step involves logging into the Xactly Connect Server.

   String username = "demouser@xactlycorp.com";
   String password = "password";
   LoginResponse lr = service.login(username, password, "Incent");
   DiscoveryServiceSoapBindingStub) service).clearHeaders();
   String sessionId = lr.getSessionId();
   String serverUrl = lr.getServerUrl();
   ((DiscoveryServiceSoapBindingStub) service).
       _setProperty(Stub.ENDPOINT_ADDRESS_PROPERTY, serverUrl);
   ((DiscoveryServiceSoapBindingStub) service).setHeader(new
       XServiceServiceLocator().getServiceName().getNamespaceURI(),
       "SessionId", sessionId);
         ((DiscoveryServiceSoapBindingStub) service).setHeader(new
             XServiceServiceLocator().getServiceName().getNamespaceURI(),
            "UserName", username);
if (!lr.isAuthenticated()) {
       System.out.println("Login Failed.");
       System.exit(-1);

}

Step 3: Setting the Search Criteria

This step creates a new UserWSO object and sets the search criteria to xactly. This instructs the search method to find all users that have xactly as part of their name.

   UserWSO user = new UserWSO();
   user.setName("xactly");

Step 4: Searching for Users

The final step uses the search method to locate all users that have xactly as part of their name, and then iterates through the searchResponse object to extract the name and email address for each matching user.

   SearchResponse searchResponse = service.search(user);
   if (!searchResponse.isResult()) {
       XObject[] searchObjects =
          searchResponse.getSearchRecords();
       for(int i=0; i < searchObjects.length; i++) {
          user = (UserWSO)searchObjects[i];
          System.out.println("------ Search Result ------");
          System.out.println("Name: " + user.getName());
          System.out.println("Email: " + user.getEmail());

} }else {

       System.out.println("Search failed.");
       System.exit(-1);
   }

 

Routing a Plan Document

This sample shows how to route a plan document (based on a plan). After routing the document, the sample code waits for 10 seconds and then performs a QueryDocu- mentStatus request on the document, printing all persons to which this document is routed along with the step information.

Note that the system returns all documents (in the response) matching the document name string. For example, the query “Doc” returns %Doc%, which includes the follow- ing, among others:

  • DocDoc-1
  • ADoc

Note also that the sample prints routing error details to the console.

import java.util.Calendar;
import org.apache.axis.client.Stub;
import com.xactly.icm.xtoolkit.service.DiscoveryServiceSoapBindingStub;
import com.xactly.icm.xtoolkit.service.XService;
import com.xactly.icm.xtoolkit.service.XServiceServiceLocator;
import com.xactly.icm.xtoolkit.wso.DocumentOwner;
import com.xactly.icm.xtoolkit.wso.DocumentOwnerFetchByType;
import com.xactly.icm.xtoolkit.wso.ErrorCode;
import com.xactly.icm.xtoolkit.wso.LoginResponse;
import com.xactly.icm.xtoolkit.wso.RouteDocumentRQ;
import com.xactly.icm.xtoolkit.wso.RouteDocumentRS;
import com.xactly.icm.xtoolkit.wso.RouteDocumentStatusRQ;
import com.xactly.icm.xtoolkit.wso.RouteDocumentStatusRS;
import com.xactly.icm.xtoolkit.wso.StepInfo;
import com.xactly.icm.xtoolkit.wso.XDocument;
public class RouteDocumentToolkitTestClient {
   private static XService service;
   public static void main(String[] args) {
       try {
          service = new XServiceServiceLocator().
             getDiscoveryService(new java.net.URL(
             "http://www.xactlycorp.com/icm/services/DiscoveryService"));
          ((DiscoveryServiceSoapBindingStub) service).
             setMaintainSession(true);
          LoginResponse loginResult = service.login(
             "demouser@xactlycorp.com", "password", "Incent");
          if (!loginResult.isAuthenticated()) {
             System.out.println("Login failed");
             return;
          else {
             System.out.println("Login successful ");
             ((DiscoveryServiceSoapBindingStub) service).clearHeaders();
             String sessionId = loginResult.getSessionId();
             String serverUrl = loginResult.getServerUrl();
((DiscoveryServiceSoapBindingStub) service)._setProperty(
             Stub.ENDPOINT_ADDRESS_PROPERTY, serverUrl);
          ((DiscoveryServiceSoapBindingStub) service).setHeader(
             new XServiceServiceLocator().getServiceName().
             getNamespaceURI(), "SessionId", sessionId);
          ((DiscoveryServiceSoapBindingStub) service).setHeader(
             new XServiceServiceLocator().getServiceName().
             getNamespaceURI(), "UserName",
             "demouser@xactlycorp.com");
          boolean routed = routeDocumentBasedOnPlan("MD_GOOD_PLAN_PN",
                 service);
          if (routed) {
             Thread.currentThread().sleep(10000);
             int pageNumber = 0;
             boolean hasMore = false;
             do {
                 hasMore = queryDocStatus("MD_GOOD_PLAN_PN",
                    pageNumber++, service);
             while (hasMore);
          }
       }
   catch (Exception exc) {
       exc.printStackTrace();
   }

}

public static boolean routeDocumentBasedOnPlan(String docName,
       XService service) throws Exception {
   boolean result = false;
   RouteDocumentRQ req = new RouteDocumentRQ();
   XDocument xdoc = new XDocument();
   // Set the name of the document
   xdoc.setName(docName);
   DocumentOwner downer = new DocumentOwner();
   downer.setFetchByType(DocumentOwnerFetchByType.OnPlan);
   downer.setRouteBy(null);
   xdoc.setOwner(downer);
   // Set the hierarchy date to the effective date for
   // fetching the document owners
   xdoc.setHierarchyDate(Calendar.getInstance());
   req.setXDocument(xdoc);
// Call the RouteDocument request
   RouteDocumentRS response = service.routeDocument(req);
   if (!response.isResult()) {
       ErrorCode[] ecArr = response.getErrorCodes();
       for (int i = 0; i < ecArr.length; i++) {
          System.out.print("Error Code = " + ecArr[i].getCode());
          System.out.println(" : Error Reason = "
             + ecArr[i].getReason());
       result = false;
   } else {
       System.out.println("Document routed successfully.");
       result = true;

}

   return result;
}
public static boolean queryDocStatus(String docName, int pageNumber,
       XService service) throws Exception {
   RouteDocumentStatusRQ statusReq = new RouteDocumentStatusRQ();
   statusReq.setDocName(docName);
   statusReq.setPageNumber(0);
   // statusReq.setRoutingStatus(
   //    RouteDocumentStatusRQRoutingStatus.Pending);
   RouteDocumentStatusRS statusRS =
       service.queryDocumentStatus(statusReq);
   if (statusRS != null && statusRS.isResult()) {
       XDocument[] xdocArr = statusRS.getXDocument();
       for (XDocument xdocOne : xdocArr) {
          System.out.println("Initiator = " + xdocOne.getInitiator());
          System.out.println("Name = " + xdocOne.getName());
          System.out.println("Reason = " + xdocOne.getReason());
          System.out.println("CompletionDate = "
             + xdocOne.getCompletionDate());
          System.out.println("HierarchyDate = "
             + xdocOne.getHierarchyDate());
          System.out.println("Owner Name = "
             + xdocOne.getOwner().getName());
          System.out.println("RouteDate = " + xdocOne.getRouteDate());
          System.out.println("RoutingStatus = "
             + xdocOne.getRoutingStatus());
          StepInfo[] sInfo = xdocOne.getStepInfo();
 for (StepInfo step : sInfo) {
                    System.out.println("Step No: " + step.getStepNo());
                    System.out.println("Step Status: "
                       + step.getStepStatus());
                    System.out.println("Step UserName: "
                       + step.getUserName());
                    System.out.println("Step Information: "
                       + step.getInformation());

} }

          } else {
             ErrorCode[] ecArr = statusRS.getErrorCodes();
             for (int i = 0; i < ecArr.length; i++) {
                 System.out.print("Error Code = " + ecArr[i].getCode());
                 System.out.println(" : Error Reason = "
                    + ecArr[i].getReason());

                                        }

             return false;
          }
          return statusRS.isHasMore();
       }

}

 

Step 1: Getting an Instance of XService

The first step involves getting an the instance of XService and instructing the system to maintain the session.

   XService service = new XServiceServiceLocator().
       getDiscoveryService(new java.net.URL(
       "http://www.xactlycorp.com/icm/services/DiscoveryService"));
   ((DiscoveryServiceSoapBindingStub) service).setMaintainSession(true);

 

Step 2: Logging into the Xactly Connect Server

The next step involves logging into the Xactly Connect Server.

   LoginResponse loginResult = service.login(
       "demouser@xactlycorp.com", "password", "Incent");
   if (!loginResult.isAuthenticated()) {
       System.out.println("Login failed");
       return;
   else {
       System.out.println("Login successful ");
       ((DiscoveryServiceSoapBindingStub) service).clearHeaders();
       String sessionId = loginResult.getSessionId();
       String serverUrl = loginResult.getServerUrl();
((DiscoveryServiceSoapBindingStub) service)._setProperty(
          Stub.ENDPOINT_ADDRESS_PROPERTY, serverUrl);
       ((DiscoveryServiceSoapBindingStub) service).setHeader(
          new XServiceServiceLocator().getServiceName().
          getNamespaceURI(), "SessionId", sessionId);
       ((DiscoveryServiceSoapBindingStub) service).setHeader(
          new XServiceServiceLocator().getServiceName().
          getNamespaceURI(), "UserName",
          "demouser@xactlycorp.com");

                      }

 

Step 3: Routing the Document and Iterating Through the Responses

This step routes the document based on the plan, and then queries the document sta- tus every ten seconds. Note that the code checks whether there are more records available, and increments the page number before invoking the queryDocStatus operation again (see Step 4 and Step 5 below for more details).

   boolean routed = routeDocumentBasedOnPlan("MD_GOOD_PLAN_PN", service);
   if (routed) {
       Thread.currentThread().sleep(10000);
       int pageNumber = 0;
       boolean hasMore = false;
       do {

hasMore = queryDocStatus(“MD_GOOD_PLAN_PN”, pageNumber++, service); while (hasMore);

}

 

Step 4: Routing the Document

This step uses the routeDocument operation to route the document by plan (DocumentOwnerFetchByType.OnPlan). Other routing options including the following:

• DocumentOwnerFetchByType.Person • DocumentOwnerFetchByType.Title
• DocumentOwnerFetchByType.User

Note that you need to set the RouteBy field when routing a document by person (DocumentOwnerFetchByType.Person).

   RouteDocumentRQ req = new RouteDocumentRQ();
          XDocument xdoc = new XDocument();
// Set the name of the document
xdoc.setName(docName);
DocumentOwner downer = new DocumentOwner();
downer.setFetchByType(DocumentOwnerFetchByType.OnPlan);

  downer.setRouteBy(null);

          xdoc.setOwner(downer);
          // Set the hierarchy date to the effective date for
          // fetching the document owners
          xdoc.setHierarchyDate(Calendar.getInstance());
          req.setXDocument(xdoc);
          // Call the RouteDocument request
          RouteDocumentRS response = service.routeDocument(req);

Step 5: Querying the Document Status

This step queries the document status and returns matching documents (in addition to printing the persons and step information to which the document is routed).

Note that setting the DocName and RoutingStatus fields is optional in the RouteDocu- mentStatusRQ object. When you set both DocName and RoutingStatus, the query- DocumentStatus operation returns all the documents matching both fields.

Similarly, the queryDocumentStatus operation returns the corresponding documents when either of the two fields are set (using a substring match, not a full string match). Note further that PageNumber is a required field.

The queryDocumentStatus operation returns 200 results in each request. You can use the hasMore and pageNumber fields in the response to iterate through additional results, as required.

Specifically, when the hasMore field is true in the response, you need to perform an additional query to retrieve the next 200 results, incrementing the pageNumber field by 1 for each successive query (set PageNumber to 0 for the first query request).

   RouteDocumentStatusRQ statusReq = new RouteDocumentStatusRQ();
   statusReq.setDocName(docName);
   statusReq.setPageNumber(0);
   RouteDocumentStatusRS statusRS = service.queryDocumentStatus(statusReq);
   if (statusRS != null && statusRS.isResult()) {
       XDocument[] xdocArr = statusRS.getXDocument();
       for (XDocument xdocOne : xdocArr) {
          System.out.println("Initiator = " + xdocOne.getInitiator());
          System.out.println("Name = " + xdocOne.getName());
          ...
for (StepInfo step : sInfo) {
   System.out.println("Step No: " + step.getStepNo());
   System.out.println("Step Status: " + step.getStepStatus());
   System.out.println("Step UserName: " + step.getUserName());
   System.out.println("Step Information: "     
        + step.getInformation());
  }
         }
     }

Determining Xactly Incent Object Information

This sample shows how to use the describeXObject method to retrieve the meta- data associated with the object. You can use the describeXObject method to retrieve the field list, object properties, and data types.

   package com.xactly.icm.xtoolkit.client;
   import com.xactly.icm.xtoolkit.service.XService;
   import com.xactly.icm.xtoolkit.service.XServiceServiceLocator;
   import com.xactly.icm.xtoolkit.service.DiscoveryServiceSoapBindingStub;
   import com.xactly.icm.xtoolkit.wso.LoginResponse;
   import com.xactly.icm.xtoolkit.wso.UserWSO;
   import com.xactly.icm.xtoolkit.wso.XField;
   public class DescribeXactlyObject {
       private static XService service;
       public static void main(String[] args) throws Exception {
service = new XServiceServiceLocator().
   getDiscoveryService(new java.net.URL(
   "http://www.xactlycorp.com/icm/services/DiscoveryService"));
((DiscoveryServiceSoapBindingStub) service).
   setMaintainSession(true);
String username = "username";
String password = "password";
LoginResponse lr = service.login(username, password, "Incent");
((DiscoveryServiceSoapBindingStub) service).clearHeaders();
String sessionId = lr.getSessionId();
String serverUrl = lr.getServerUrl();
((DiscoveryServiceSoapBindingStub) service).
   _setProperty(Stub.ENDPOINT_ADDRESS_PROPERTY, serverUrl);
((DiscoveryServiceSoapBindingStub) service).setHeader(new
   XServiceServiceLocator().getServiceName().getNamespaceURI(),
   "SessionId", sessionId);
((DiscoveryServiceSoapBindingStub) service).setHeader(new
   XServiceServiceLocator().getServiceName().getNamespaceURI(),
   "UserName", username);
if (!lr.isAuthenticated()) {
   System.out.println("Login failed!");
   System.exit(-1);
}
UserWSO user = new UserWSO();
XField [] userFields = service.describeXObject(user);
for(int i=0; i < userFields.length; i++) {
   XField field = userFields[i];
   System.out.println("------------- Field -------------");
   System.out.println("Name: " + field.getName());
   System.out.println("Data Type: " + field.getDataType());
   System.out.println("Display Label: " +
       field.getDisplayLabel());
   System.out.println("Field Length: " + field.getLength());
   System.out.println("Is Required: " +
       field.getRequired());
   System.out.println("Is Searchable: " +
           }
        }
     }

 

Step 1: Getting an Instance of XService

The first step involves getting an the instance of XService and instructing the system to maintain the session.

   XService service = new XServiceServiceLocator().
       getDiscoveryService(new java.net.URL(
       "http://www.xactlycorp.com/icm/services/DiscoveryService"));
   ((DiscoveryServiceSoapBindingStub) service).
       setMaintainSession(true);

 

Step 2: Logging into the Xactly Connect Server

The next step involves logging into the Xactly Connect Server.

   String username = "demouser@xactlycorp.com";
   String password = "password";
   LoginResponse lr = service.login(username, password, "Incent");
   ((DiscoveryServiceSoapBindingStub) service).clearHeaders();
   String sessionId = lr.getSessionId();
   String serverUrl = lr.getServerUrl();
  ((DiscoveryServiceSoapBindingStub) service).
       _setProperty(Stub.ENDPOINT_ADDRESS_PROPERTY, serverUrl);
   ((DiscoveryServiceSoapBindingStub) service).setHeader(new
       XServiceServiceLocator().getServiceName().getNamespaceURI(),
       "SessionId", sessionId);
   ((DiscoveryServiceSoapBindingStub) service).setHeader(new
       XServiceServiceLocator().getServiceName().getNamespaceURI(),
       "UserName", username);
   if (!lr.isAuthenticated()) {
       System.out.println("Login Failed.");
       System.exit(-1);

}

 

Step 3: Extracting the Metadata Information

This step uses the describeXObject method to retrieve the metadata associated with the object, including the data type, display label, length, and whether the object is required.

   UserWSO user = new UserWSO();
   XField [] userFields = service.describeXObject(user);
   for(int i=0; i < userFields.length; i++) {
       XField field = userFields[i];
       System.out.println("------------- Field -------------");
       System.out.println("Name: " + field.getName());
       System.out.println("Data Type: " + field.getDataType());
       System.out.println("Display Label: " +
          field.getDisplayLabel());
       System.out.println("Field Length: " + field.getLength());
       System.out.println("Is Required: " +
          field.getRequired());
       System.out.println("Is Searchable: " +
          field.getSearchable());

}