Java Code Samples

From AgileApps Support Wiki
Revision as of 02:01, 10 September 2013 by imported>Aeric

These samples assume basic familiarity with the use of the platform's Java APIs.
Learn more:

Class Template

Use this class as a template for your own. It provides a starting point for most things you'll want to do, as it accesses record data and uses it to perform some operation.

<syntaxhighlight lang="java" enclose="div">

package com.platform.site.util;

import com.platform.api.*; //import com.platform.beans.*; import java.util.*;

public class YourClass {

 public void doSomething(Parameters p) throws Exception
 {      
     debug("Started");
     String objectID = p.get("object_id");
     String recordID = p.get("id");  
     // Define the parameters for some operation
     Parameters params = Functions.getParametersInstance();
     params.add("key", "value");
     ...
     // Do it
     Result r = Functions.doSomething(params);
     if (r.getCode() < 0) {
        // Display error message at top of user's page.
        // (Transaction is rolled back. No changes are committed.)
        Functions.throwError("Failed:\n  " + r.getMessage() );       
     }  
     debug("Success");
  }
  public void debug(String msg) throws Exception {
     // Put the message in the log.
     // Use the class name as the message type.
     Logger.info(msg, "YourClass");
     // For interactive debugging. Displays at top of user's page.
     //showMessage(msg);
  }

} </syntaxhighlight>

Notes and additional code snippets:

  • Object names and IDs
  • Most APIs take either object name or object ID. (Only a few require object ID.)
  • For most operations you'll know which object you're operating on, so you'll specify the object name in a string.
  • But the object ID is also available in the incoming Parameters, when you need it.
  • List of Parameters
  • Add this line to the code above to put a complete list of incoming parameters into the debug log:
<syntaxhighlight lang="java" enclose="div">

// Generate a newline-separated list of parameters debug( p.toString().replace(",", ",\n") ); </syntaxhighlight>

Add a Task to a Record

This example uses the addRecord API to create a new Task associated with an existing case.

<syntaxhighlight lang="java" enclose="div">

import com.platform.api.Functions; import com.platform.api.Parameters; import java.util.*;

public class RecordAdditions {

  public void addTask(Parameters p) throws Exception
  {      
      String subject = "New Task Record";
      String description = "This task needs to be accomplished.";
      String relatedTo = "cases:99999999";
      // Create the Task parameters
      Parameters taskParams = Functions.getParametersInstance();
      taskParams.add("subject", subject);
      taskParams.add("description", description);
      taskParams.add("related_to", relatedTo);
      taskParams.add("due_date", new Date() );
         // Add other fields like owner_id, as required     
     
      // Add the Task
      Result r = Functions.addRecord("tasks", taskParams);
      // Check the result here. 
      // On success, Result.getCode() returns zero (0)
      // On failure, it returns -1
  }

} </syntaxhighlight>

Notepad.png

Note: Since a Task can be attached to a record in any object, related_to is a Multi Object Lookup field. It's data value therefore contains both an object identifier and the record identifier, separated by a colon.
Learn more: Field Type Reference

Add a Note

This example adds a note with special handling instructions to a claim record. To do that, it uses a method defined in a utility package. In this scenario, there is a Rule that is triggered by adding a record when certain conditions are met (for example, when the record pertains to a particular customer, or when a particular flag has been set). The Rule then invokes the method defined here.

The incoming parameters object identifies the record and contains its field values. A new one is constructed for the note, using the reference_type and reference_id fields to link the note to the appropriate record.

<syntaxhighlight lang="java" enclose="div">

package com.platform.site.util;

import com.platform.api.*;

public class ClaimAdditions {

 public void addNote(Parameters p) throws Exception
 {      
    Parameters noteParams = Functions.getParametersInstance();
    noteParams.add( "reference_type", p.get("object_id") ); // Object Name or ID
    noteParams.add( "reference_id", p.get("id")  );         // record Id
    noteParams.add("title", "OPTIONAL TITLE HERE");
    String descr = "Special handling instructions: ...";
    noteParams.add("description", descr);
    noteParams.add("visibility_filter",CONSTANTS.NOTES.VISIBLE_TO_EVERYONE);
    //noteParams.add("visible_to_specific_type_data", "ID#1,ID#2,..."); 
     // Add the Note
     Result r = Functions.addRecord("NOTE", noteParams);
     // Check the result here. 
     // On success, Result.getCode() returns zero (0)
     // On failure, it returns -1
  }

} </syntaxhighlight>

Where the possible values for the visibility filter are:

  • VISIBLE_TO_ME
  • VISIBLE_TO_EVERYONE
  • VISIBLE_TO_SPECIFIC_USERS
Requires visible_to_specific_type_data param with a comma-separated list of User IDs
  • VISIBLE_TO_SPECIFIC_ROLES
Requires visible_to_specific_type_data param with a comma-separated list of Role IDs
  • VISIBLE_TO_SPECIFIC_TEAMS
Requires visible_to_specific_type_data param with a comma-separated list of Team IDs

Send an Email Message

This section shows how to send an email message to a contact.

The following code sample will:

  • Get the record for the contactRecID (the contact named "John Smith")

Find more information about arguments in sendEmailUsingTemplate

<syntaxhighlight lang="java" enclose="div">

Result getContactRecordResult = Functions.getRecord("CONTACT",

   "first_name,last_name,email", contactRecID);

Logger.info("Sending Email to contact of Hello World Account..with email address:"

               +(getContactRecordResult.getParameters()).get("email"), "SendMail");

</syntaxhighlight>

The following code sample calls sendEmailUsingTemplate. In order, the parameters are:

  • Related object identifier
  • Identifier of the related record which is contactRecID that was retrieved previously
  • To list which is set by making a nested call to Parameters.get to get the email address of the contact that was just retrieved
  • Cc list which is set by making a nested call to Parameters.get to get the email address of the contact that was just retrieved
  • Description (a text string)
  • Identifier of a print template. This template is evaluated at run time, its template variables substituted, and then sent as the body of the message
  • List of print template identifiers to send as attachments (not used in this example)
  • List of document identifiers in your documents folder to send as attachments (not used in this example)
<syntaxhighlight lang="java" enclose="div">

Result sendEmailResult = Functions.sendEmailUsingTemplate("CONTACT", contactRecID,

         (getContactRecordResult.getParameters()).get("email"),
         (getContactRecordResult.getParameters()).get("email"),
         "Sending Email to Hello World's Primary Contact - John Smith",
         "1869974057twn1678149854", "", ""); 

Logger.info("Done sending mail from Hello World account's Contact John Smith",

           "SendMail");

if(sendEmailResult.getCode() != 0) {

   Logger.info("Error in sending email!" + sendEmailResult.getMessage(), 
               "SendMail"); 

} else {

   Logger.info("Success on sendEmail, check inbox : " + sendEmailResult.getMessage(), 
               "SendMail");

} </syntaxhighlight>

Like other Java API calls such as addRecord and searchRecords, sendEmailUsingTemplate returns a Result object whose methods you can call to check the result of the call. When sendEmailUsingTemplate succeeds, Result.getCode returns zero (0).

Search and Update

To update a record, this example follows these steps:

In this example, the Contact record that was created in the Add a Contact Recordexample is updated by associating it to the Account record created in the Add an Account Record example.

Search for the Account and Contact Records

Follow these general steps to search for records:

  1. Call searchRecords
  2. Check the result
  3. Process the returned records

First, create a variable to hold the record identifier.

<syntaxhighlight lang="java" enclose="div">

String contactRecID = null; </syntaxhighlight>

When a record is added database, the platform assigns it a unique record identifier. The value of a record identifier is opaque and is of no interest to the typical user. However, several Java API calls use the recordID parameter.

To get a record identifier, request the record_id field when making a searchRecords call. Find more information about arguments in searchRecords.

This example calls searchRecords for the CONTACT object. In order, the parameters to searchRecords in this example are:

  • name of the object
  • names of the fields to retrieve which includes record_id
  • filter string (in this case, the filter string specifies that last_name contains "Smith" (the same as for the contact record previously created)
<syntaxhighlight lang="java" enclose="div">

Result contactSearchResult = Functions.searchRecords("CONTACT", "record_id,first_name,last_name,email", "last_name contains 'Smith'"); </syntaxhighlight>

Check the Result

The result code for searchRecords works a little differently than for addRecord.

Debug Example for searchRecords

This example checks the return code by calling Result.getCode, and takes some action, based on the return code:

  • Return codes:
  • less then zero (<0); the call is not successful
  • equal to zero (=0); no records found
  • greater than zero (> 0); successful and the value of the return code is the number of records returned

This code sample assigns the result code to a variable, which then defines the following action:

  • If not successful, an error dialog is displayed
  • If the code is zero, then a message is written to the debug log
  • If successful, then the code is the number of records returned
<syntaxhighlight lang="java" enclose="div">

int contactSearchCode = contactSearchResult.getCode();

if(contactSearchCode < 0) {

   String msg = "Error searching CONTACT object";
   Logger.info(msg + ":\n" + contactSearchResult.getMessage(), "Search");
   Functions.throwError(msg + ".");                     

} else if(contactSearchCode == 0) {

   Logger.info("Contact:No records found using the search function in CONTACT.",
               "Search");

} else {

   // If the code "falls through" here, it means records were returned 
   // that need to be processed; use the value of the return code in 
   // the next section ...

} </syntaxhighlight>

Process the Returned Records

In earlier examples, the Parameters object was shown to hold name-value pairs for fields for when the addRecord call is made.

The searchRecords call uses the Parameters object, but in a different way - the searchRecords call returns the set of fields that were requested for each record that matches the search criteria as an array of Parameters objects.

To process each Parameters object in the search results, create an instance of ParametersIterator and then specify ParametersIterator.hasNext as the expression of a while loop.

The example resumes with the code "falling through" when checking the result code for searchRecords, meaning that the result code is greater than zero, which is the number of records returned.

The following code sample will:

  • Create an instance of ParametersIterator by calling Result.getIterator
  • Set up a while loop with ParametersIterator.hasNext as the expression to evaluate at each iteration; Within the while loop, the code will:
  • Create an instance of Parameters by calling ParametersIterator.next
  • Call Parameters.get, specifying record_id as the parameter to get the value of the record identifier field which is assigned to a variable named contactRecordId
  • Make a Java API getRecord call with these parameters:
  • Object identifier
  • List of fields to get
  • The record identifier which is contactRecordId in this case
  • Make a nested call to Result.getParameters to get the value of the first_name field; Checks if it is equal to "John". If so, the contactRecordId is assigned to the variable named contactRecID and the code breaks out of the loop; The contactRecID variable is used later when calling updateRecord, and sendEmailUsingTemplate
<syntaxhighlight lang="java" enclose="div">

{

  // "Falling through" here means records were returned
  Logger.info("Search for John Smith: Number of records found using 
      search function in Contact:" + contactSearchCode, "Search");
  ParametersIterator contactIterator = contactSearchResult.getIterator();
  while(contactIterator.hasNext())
  {
     Parameters contactParams = contactIterator.next();
     String contactRecordId = contactParams.get("record_id");  
     Result getContactRecordResult = Functions.getRecord("CONTACT", 
        first_name,last_name,flag_primary_contact,description", contactRecordId);
     String firstName = (getContactRecordResult.getParameters()).get("first_name");
     Logger.info("Result from getRecord:\n" + getContactRecordResult.getMessage(),
                     "Search");
     Logger.info("Return code from getRecord:" + getContactRecordResult.getCode(),
                     "Search");
     Logger.info("First name retrieved : " + firstName, "Search");
     if(firstName.equals("John")) {
        contactRecID = contactRecordId; 
        break;
     }
  }

} </syntaxhighlight>

Relate the Account Record to the Contact Record

As objects are manipulated in the platform (added, updated, deleted), associations between objects must be maintained.

For example, when a Contact is created, it must be related to an Account:

  • In the platform user interface, objects are related using the Lookup field as described in Relating Objects Using Lookups
  • In the Java API, objects are related in code by searching for an object and then using a field value that identifies the object to set a field in a related object

Define the Relationship between Objects In this example, the code searches for an Account and then uses the Account Number to set a field in the contact. When relating a record in the Account object to a record in the Contact object, these three key-value pairs are required to define the relationship:

  • reference_type
  • related_to_id
  • related_to_name

The following code searches for an account where the name field contains the text string "Hello". The Account record is created in Add an Account Record. The code follows the same model for a Update Records: call searchRecords, check the result code, and loop to process the returned records.

The following code sample:

  • Sets up a while loop with ParametersIterator.hasNext as the expression to evaluate at each iteration. Within the while loop, the code creates two instances of Parameters:
  • The first instance is created by calling getParametersInstance and is named updateContactParams; This instance is used to update the contact record later
  • The second instance is created by calling ParametersIterator.next and is called accountParams
  • Calls accountParams.get, specifying record_id as the parameter to get the value of the record identifier field, which is assigned to a variable named accountRecordId.
  • Makes a Java API getRecord call using accountRecordId as a parameter
  • Makes a nested call to Result.getParameters to get the value of the name field
  • Checks if the name is equal to "Hello World"; If it is, the code adds some name-value pairs to updateContactParams
  • Assigns the accountRecordId retrieved in the previous account search to related_to_id (This is how record identifiers are used to relate one object to another in the Java API)
  • Makes an updateRecord call, specifying contactRecID and updateContactParams as parameters, which updated the Contact record.
  • Checks the result in the final lines of code in the same way that previous examples did.
<syntaxhighlight lang="java" enclose="div">

Result accountSearchResult = searchRecords ("ACCOUNT", "record_id,name,number,primary_contact_id",

   "name contains 'Hello'");

int accountResultCode = accountSearchResult.getCode(); Logger.info(" Account:Result message for search ALL Account Records is "

           + accountSearchResult.getMessage(), "Search");

Logger.info(" Account:Result code for search ALL Record is " + accountResultCode,

           "Search");

if(accountResultCode < 0) {

   String msg = "Account could not be retrieved";
   Logger.info(msg + ":\n" + accountSearchResult.getMessage(), "Search");
   Functions.throwError(msg + ".");

} else if(accountResultCode == 0) {

   Logger.info("Account:No records found using the search function in ACCOUNT.", 
               "Search");

} else {

   Logger.info(
     "Search for Hello World: Number of records found using search function in Account:"
     + accountResultCode, "Search");
   ParametersIterator accountIterator = accountSearchResult.getIterator();
   while(accountIterator.hasNext())
   {
       Parameters updateContactParams = Functions.getParametersInstance();
       Parameters accountParams = accountIterator.next();
       String accountRecordId = accountParams.get("record_id");	      
       Result getAccountRecordResult = 
           Functions.getRecord("ACCOUNT", "name,description", accountRecordId);
       String accountName = (getAccountRecordResult.getParameters()).get("name");
       Logger.info("Result from getRecord on ACCOUNT:\n" 
                   + getAccountRecordResult.getMessage(), "Search");
       Logger.info("Return code from getRecord on ACCOUNT:" 
                  + getAccountRecordResult.getCode(), "Search");
       if(accountName.equals("Hello World")) 
       {
           Logger.info("Account record ID:" + accountRecordId, "Update");
           updateContactParams.add("description", "Updating Contact");
           updateContactParams.add("reference_type", "Account");
           updateContactParams.add("related_to_id", accountRecordId);
           updateContactParams.add("related_to_name", accountName);
           Logger.info("Updating contact record with id:" + contactRecID, "Update");
           Result contactUpdateResult = 
               Functions.updateRecord("CONTACT", contactRecID, updateContactParams);
           if(contactUpdateResult.getCode() == 0) 
           {
              Logger.info("Account:Contact of the Account record updated successfully\n"
                  + contactUpdateResult.getMessage(), "Update");
           }
           else
           {
               String msg = "Error updating contact";
               Logger.info(msg + ":\n" + contactUpdateResult.getMessage(), "Update");
               Functions.throwError(msg + ".");
           }  
       }           
   }

} </syntaxhighlight>