Difference between revisions of "Getting Started with the Java API"

From AgileApps Support Wiki
imported>Aeric
m (Text replace - ' getEnv(' to ' Functions.getEnv(')
imported>Aeric
 
(47 intermediate revisions by the same user not shown)
Line 1: Line 1:
Get started with the Java API and learn how to use Support Classes, Objects and Calls in the example presented here.
===About the Java API===
:''Learn more: [[Java API]]''
The Java APIs are used when writing custom [[Classes]] that can be invoked from Rules.


Use these examples as a step-by-step tutorial to learn these basic skills:
The examples on the remainder of this page take you through the process of working with Java API, step by step.
#Create an [[#Add an Account Record|Account Record]] and a [[#Add a Contact Record|Contact Record]]
#Update Records with this process:
#:*[[#Search for the Account and Contact Records|Search for the Account and Contact Records]] in the database
#:*[[#Relate the Account Record to the Contact Record|Relate the Account Record to the Contact Record]]
#:*[[#Update the Contact Record|Update the Contact Record with New Data]]
#[[#Create a Task Record|Create a Task to Send an Email Message]] and assign it to a User (task owner)
#[[#Send an Email Message|Send an Email Message]] to the Contact, then [[#Mark the Task as Completed|Mark the Task as Completed]]


Be sure to use a [[Plain Text Editor]] to manipulate the code.
{{:Common:Java API Considerations}}


:''For detailed descriptions of classes, objects and calls, see [[Java API]]''
''Learn More:''
 
:* [[Java Code Samples]] - an initial class template and advanced, ready-to-copy code samples
For a cut-and-paste version of '''all''' the code described in these step-by-step examples, see: [[#Java API Sample|Java API Sample]]
:* [[Java Debugging Tips]] - for help debugging your application
:* [[Java API]] - for detailed descriptions of the classes, objects and API calls used in these examples
:* [[Localization#Java Programming]] - learn how to take into account localization of data for users


===Add an Account Record===
===Add an Account Record===
Line 26: Line 21:
====Set up a Parameters Object====
====Set up a Parameters Object====


Data is passed to the platform using a <tt>Parameters</tt> object. The <tt>Parameters</tt> object holds key-value pairs, where each key corresponds to a field name and each value corresponds to a field value in the database. Set the key-value pairs and then pass the <tt>Parameters</tt> object as an argument when the record is added.
Data is passed to the platform using a <tt>Parameters</tt> object. The <tt>Parameters</tt> object holds key-value pairs, where each key corresponds to a field name and each value corresponds to a field value in the database. Set the key-value pairs and then pass the <tt>Parameters</tt> object as an argument when the record is added. (To learn more about the parameters passed to a Java method, see the [[Standard Parameters]].)


To set up a Parameters Object, create an instance of <tt>Parameters</tt> to hold the key-value pairs for the record by calling [[Utility_Calls#getParametersInstance|<tt>getParametersInstance</tt>]]. This instance is named <tt>addAccountParams</tt>:
To set up a Parameters Object, create an instance of <tt>Parameters</tt> to hold the key-value pairs for the record by calling [[Java API:Utility functions#getParametersInstance|<tt>getParametersInstance</tt>]]. This instance is named <tt>addAccountParams</tt>:


<pre>Parameters addAccountParams = Functions.getParametersInstance();</pre>
:<syntaxhighlight lang="java" enclose="div">
Parameters addAccountParams = Functions.getParametersInstance();
</syntaxhighlight>


To see the fields that are defined in an object:
To see the fields that are defined in an object:
#Open a web browser and [[Login]] to the platform
#Open a web browser and [[Login]] to the platform
#Click '''Designer > Data > Objects > {object} > Fields'''
#Click '''[[File:GearIcon.png]] > Customization > Objects > {object} > Fields'''
#View the field list
#View the field list


Add the key-value pairs for the database fields to <tt>addAccountParams</tt> by calling <tt>Parameters.add</tt>:
Add the key-value pairs for the database fields to <tt>addAccountParams</tt> by calling <tt>Parameters.add</tt>:


<pre>
:<syntaxhighlight lang="java" enclose="div">
addAccountParams.add("name","Hello World Account");
addAccountParams.add("name","Hello World Account");
addAccountParams.add("number","0000001");
addAccountParams.add("number","0000001");
Line 47: Line 44:
addAccountParams.add("phone", "222-222-2222");
addAccountParams.add("phone", "222-222-2222");
addAccountParams.add("website", "www.helloworldaccount.com");
addAccountParams.add("website", "www.helloworldaccount.com");
</pre>
</syntaxhighlight>


====Call addRecord====
====Call addRecord====
To add a new record, call <tt>addRecord</tt> and pass it an object identifier and the <tt>addAccountParams</tt> object. The values you added to <tt>addAccountParams</tt> are written to the account record in the database.
To add a new record, call <tt>addRecord</tt> and pass it an object identifier and the <tt>addAccountParams</tt> object. The values you added to <tt>addAccountParams</tt> are written to the account record in the database.


<pre>Result accountAddResult = Functions.addRecord("ACCOUNT", addAccountParams);</pre>
:<syntaxhighlight lang="java" enclose="div">
Result accountAddResult = Functions.addRecord("ACCOUNT", addAccountParams);
</syntaxhighlight>


Like <tt>addRecord</tt>, many of the Java API record handling calls have an <tt>objectID</tt> parameter the object is specified ("ACCOUNT" in this example). In the <tt>objectID</tt> parameter, specify the [[Object Type Identifier]].
Like <tt>addRecord</tt>, many of the Java API record handling calls have an <tt>objectID</tt> parameter the object is specified ("ACCOUNT" in this example). In the <tt>objectID</tt> parameter, specify the [[Object Type Identifier]].
Line 60: Line 58:
The <tt>addRecord</tt> code (as well as several other Java API calls) returns an instance of the <tt>Result</tt> class. It is possible to check member variables in the <tt>Result</tt> object by calling its methods. For example, the code below makes a Java API <tt>debug</tt> utility call, making a nested call to <tt>Result.getMessage</tt> which returns a string indicating whether the call succeeded.
The <tt>addRecord</tt> code (as well as several other Java API calls) returns an instance of the <tt>Result</tt> class. It is possible to check member variables in the <tt>Result</tt> object by calling its methods. For example, the code below makes a Java API <tt>debug</tt> utility call, making a nested call to <tt>Result.getMessage</tt> which returns a string indicating whether the call succeeded.


<pre>Functions.debug("Result of addRecord for Account:" + accountAddResult.getMessage());</pre>
:<syntaxhighlight lang="java" enclose="div">
Logger.info("Result of addRecord for Account:" + accountAddResult.getMessage(), "Add");
</syntaxhighlight>


The string specified in the <tt>debug</tt> call is written to the debug log.  
The string specified in the <tt>debug</tt> call is written to the debug log.  


To view the Debug Log:
To view the Debug Log:
:Click '''Designer > Global Resources > Debug Log'''
:Click '''[[File:GearIcon.png]] > Customization > Developer Resources > Debug Log'''


:When the code runs, use the Debug Log to troubleshoot problems during development. Many other <tt>debug</tt> calls are included in these code samples.
:When the code runs, use the Debug Log to troubleshoot problems during development. Many other <tt>debug</tt> calls are included in these code samples.
Line 79: Line 79:
If the call is not successful, make a Java API <tt>throwError</tt> call, otherwise make a <tt>Result.getID</tt> call and continue  
If the call is not successful, make a Java API <tt>throwError</tt> call, otherwise make a <tt>Result.getID</tt> call and continue  


<pre>
:<syntaxhighlight lang="java" enclose="div">
if(accountAddResult.getCode() < 0)
if(accountAddResult.getCode() < 0)
     String msg = "Function: Add Account";
     String msg = "Function: Add Account";
     Functions.debug(msg + ":\n" + accountAddResult.getMessage()); // Log details
     Logger.info(msg + ":\n" + accountAddResult.getMessage(), "Add"); // Log details
     Functions.throwError(msg + ".");                     // Error dialog
     Functions.throwError(msg + ".");                                 // Error message
else
else
     return accountAddResult.getID();
     return accountAddResult.getID();
</pre>
</syntaxhighlight>


===Add a Contact Record===
===Add a Contact Record===
Following the same process (as adding an Account record), now add a Contact Record:
Here, you following the same process as adding an Account record to add a Contact Record:
*Set up a Parameters Object
:*Set up a Parameters Object
*Create an instance of <tt>Parameters</tt> by calling <tt>getParametersInstance</tt>
:*Create an instance of <tt>Parameters</tt> by calling <tt>getParametersInstance</tt>
*Check the Result
:*Check the Result


<pre>Parameters addContactParams = Functions.getParametersInstance();</pre>
:<syntaxhighlight lang="java" enclose="div">
Parameters addContactParams = Functions.getParametersInstance();
</syntaxhighlight>


Then set the key-value pairs in the <tt>Parameters</tt> instance:
Then set the key-value pairs in the <tt>Parameters</tt> instance:


<pre>
:<syntaxhighlight lang="java" enclose="div">
addContactParams.add("first_name", "John");
addContactParams.add("first_name", "John");
addContactParams.add("last_name", "Smith");
addContactParams.add("last_name", "Smith");
Line 105: Line 107:
addContactParams.add("flag_primary_contact", "true");
addContactParams.add("flag_primary_contact", "true");
addContactParams.add("street", "12345 Lake st");
addContactParams.add("street", "12345 Lake st");
</pre>
</syntaxhighlight>


Call <tt>addRecord</tt>, specifying "CONTACT" as the object identifier and passing the <tt>Parameters</tt> object you set up above.
Call <tt>addRecord</tt>, specifying "CONTACT" as the object identifier and passing the <tt>Parameters</tt> object you set up above.


<pre>Result contactAddResult = Functions.addRecord("CONTACT", addContactParams);</pre>
:<syntaxhighlight lang="java" enclose="div">
 
Result contactAddResult = Functions.addRecord("CONTACT", addContactParams);
</syntaxhighlight>


Make a nested call to <tt>Result.getMessage</tt> to write to the debug log:
Make a nested call to <tt>Result.getMessage</tt> to write to the debug log:


<pre>Functions.debug("Result of addRecord for Contact - John Smith:" + contactAddResult.getMessage());</pre>
:<syntaxhighlight lang="java" enclose="div">
 
Logger.info("Result of addRecord for Contact - John Smith:"
          + contactAddResult.getMessage(), "Add");
</syntaxhighlight>


Check the return code by calling <tt>Result.getCode</tt>:
Check the return code by calling <tt>Result.getCode</tt>:


<pre>
:<syntaxhighlight lang="java" enclose="div">
if(contactAddResult.getCode() < 0)
if(contactAddResult.getCode() < 0)
     String msg = "Getting Started: Add John Smith";
     String msg = "Getting Started: Add John Smith";
     Functions.debug(msg + ":\n" + contactAddResult.getMessage()); // Log details
     Logger.info(msg + ":\n" + contactAddResult.getMessage(), "Add"); // Log details
     Functions.throwError(msg + ".");                     // Error dialog
     Functions.throwError(msg + ".");                                 // Error message
else
else
     return contactAddResult.getID();
     return contactAddResult.getID();
</pre>
</syntaxhighlight>
 
===Update Records===
To update a record, complete these steps:
*[[#Search for the Account and Contact Records|Search for the Account and Contact Records]]
*[[#Check the Result|Check the Result]]
*[[#Process the Returned Records|Process the Returned Records]]
*[[#Relate the Account Record to the Contact Record|Relate the Account Record to the Contact Record]]
 
In this example, the Contact record that was created in the [[#Add a Contact Record|Add a Contact Record]]example is updated by associating it to the Account record created in the [[#Add an Account Record|Add an Account Record]] example.
 
====Search for the Account and Contact Records====
Follow these general steps to search for records:
# Call <tt>searchRecords</tt>
# Check the result
# Process the returned records
 
First, create a variable to hold the record identifier.
 
String contactRecID = null;
 
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 <tt>recordID</tt> parameter.
 
To get a record identifier, request the <tt>record_id</tt> field when making a [[#searchRecords|<tt>searchRecords</tt>]] call. Find more information about arguments in <tt>[[searchRecords]]</tt>.
 
This example calls <tt>searchRecords</tt> for the CONTACT object. In order, the parameters to <tt>searchRecords</tt> in this example are:
* name of the object
* names of the fields to retrieve which includes <tt>record_id</tt>
* filter string (in this case, the filter string specifies that <tt>last_name</tt> contains "Smith" (the same as for the contact record previously created)
 
<pre>Result contactSearchResult = Functions.searchRecords("CONTACT",
"record_id,first_name,last_name,email", "last_name contains 'Smith'");</pre>
 
 
=====Check the Result=====
 
The result code for <tt>searchRecords</tt> works a little differently than for <tt>addRecord</tt>.
 
'''Debug Example for <tt>searchRecords</tt>'''
 
This example checks the return code by calling <tt>Result.getCode</tt>, 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:
===Update a Record===
*If not successful, an error dialog is displayed
This code updates a record.
*If the code is zero, then a message is written to the debug log
:<syntaxhighlight lang="java" enclose="div">
*If successful, then the code is the number of records returned
public void changeRecordValue(Parameters p) throws Exception
 
<pre>
int contactSearchCode = contactSearchResult.getCode();
 
if(contactSearchCode < 0)
{
    String msg = "Error searching CONTACT object";
    Functions.debug(msg + ":\n" + contactSearchResult.getMessage());  // Log details
    Functions.throwError(msg + ".");                    // Error dialog
}
else if(contactSearchCode == 0)
{
{
    Functions.debug("Contact:No records found using the search function in CONTACT.");
  try {
}
      String objectID = p.get("object_id");
else
      String recordID = p.get("id"); 
{
     
    // If the code "falls through" here, it means records were returned
      // Specify the parameters to modify. (Only specified params are changed.)
    // that need to be processed; use the value of the return code in
      Parameters params = Functions.getParametersInstance();
    // the next section ...
      params.add("field_name", "new_value");
}
</pre>
 
=====Process the Returned Records=====
In earlier examples, the <tt>Parameters</tt> object was shown to hold name-value pairs for fields for when the <tt>addRecord</tt> call is made.  
 
The <tt>searchRecords</tt> call uses the <tt>Parameters</tt> object, but in a different way - the <tt>searchRecords</tt> call returns the set of fields that were requested for each record that matches the search criteria as an array of <tt>Parameters</tt> objects.


To process each <tt>Parameters</tt> object in the search results, create an instance of <tt>ParametersIterator</tt> and then specify <tt>ParametersIterator.hasNext</tt> as the expression of a <tt>while</tt> loop.
      // Result.getCode() >= 0 on success, -1 on failure
 
       Result r = Functions.updateRecord(objectID, recordID, params);
The example resumes with the code "falling through" when checking the result code for <tt>searchRecords</tt>, meaning that the result code is greater than zero, which is the number of records returned.
       if (r.getCode() < 0) {
 
        Functions.throwError("Update failed\n" + r.getMessage() );    
The following code sample will:
      
* Create an instance of <tt>ParametersIterator</tt> by calling <tt>Result.getIterator</tt>
  } catch (Exception e) {
* Set up a <tt>while</tt> loop with <tt>ParametersIterator.hasNext</tt> as the expression to evaluate at each iteration; Within the <tt>while</tt> loop, the code will:
       Functions.throwError( e.getMessage() );    
:* Create an instance of <tt>Parameters</tt> by calling <tt>ParametersIterator.next</tt>
  }
:* Call <tt>Parameters.get</tt>, specifying <tt>record_id</tt> as the parameter to get the value of the record identifier field which is assigned to a variable named <tt>contactRecordId</tt>
:* Make a Java API <tt>getRecord</tt> call with these parameters:
::* Object identifier
::* List of fields to get
::* The record identifier which is <tt>contactRecordId</tt> in this case
:* Make a nested call to <tt>Result.getParameters</tt> to get the value of the <tt>first_name</tt> field; Checks  if it is equal to "John". If so, the <tt>contactRecordId</tt> is assigned to the variable named <tt>contactRecID</tt> and the code breaks out of the loop; The <tt>contactRecID</tt> variable is used later when calling <tt>[[updateRecord]]</tt>, <tt>[[addTask]]</tt>, and <tt>[[sendEmailUsingTemplate]]</tt>
 
<pre>
{
  // "Falling through" here means records were returned
  Functions.debug("Search for John Smith: Number of records found using
      search function in Contact:" + contactSearchCode );
  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");
      Functions.debug("Result from getRecord:\n" + getContactRecordResult.getMessage());
       Functions.debug("Return code from getRecord:" + getContactRecordResult.getCode());
       Functions.debug("First name retrieved : " + firstName); 
      if(firstName.equals("John"))
        {
          contactRecID = contactRecordId;  
          break;
        }
    }
}
}
</pre>
</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:
===Change Record Ownership===
:*In the platform user interface, objects are related using the [[Lookup]] field as described in [[Relating Objects Using Lookups]]
This code changes a record's owner. Note that it does not reassign any tasks that may be attached to the record. (Additional code would be required to do that.)
:*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
:<syntaxhighlight lang="java" enclose="div">
 
public void changeOwner(Parameters p) throws Exception
'''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:
:*<tt>reference_type</tt>
:*<tt>related_to_id</tt>
:*<tt>related_to_name</tt>
 
The following code searches for an account where the <tt>name</tt> field contains the text string "Hello". The Account record is created in [[#Add an Account Record|Add an Account Record]]. The code follows the same model for a [[#Update Records|Update Records]]: call <tt>searchRecords</tt>, check the result code, and loop to process the returned records.
 
The following code sample:
:*Sets up a <tt>while</tt> loop with <tt>ParametersIterator.hasNext</tt> as the expression to evaluate at each iteration. Within the <tt>while</tt> loop, the code creates two instances of <tt>Parameters</tt>:
::* The first instance is created by calling <tt>getParametersInstance</tt> and is named <tt>updateContactParams</tt>; This instance is used to update the contact record later
::* The second instance is created by calling <tt>ParametersIterator.next</tt> and is called <tt>accountParams</tt>
:*Calls <tt>accountParams.get</tt>, specifying <tt>record_id</tt> as the parameter to get the value of the record identifier field, which is assigned to a variable named <tt>accountRecordId</tt>.
:*Makes a Java API <tt>getRecord</tt> call using <tt>accountRecordId</tt> as a parameter
:*Makes a nested call to <tt>Result.getParameters</tt> to get the value of the <tt>name</tt> field
:*Checks if the name is equal to "Hello World"; If it is, the code adds some name-value pairs to <tt>updateContactParams</tt>
:*Assigns the <tt>accountRecordId</tt> retrieved in the previous account search to <tt>related_to_id</tt> (This is how record identifiers are used to relate one object to another in the Java API)
:*Makes an <tt>updateRecord</tt> call, specifying <tt>contactRecID</tt> and <tt>updateContactParams</tt> as parameters, which updated the Contact record.
:*Checks the result in the final lines of code in the same way that previous examples did.
 
<pre>
Result accountSearchResult = searchRecords ("ACCOUNT", "record_id,name,number,primary_contact_id",
    "name contains 'Hello'");
int accountResultCode = accountSearchResult.getCode();
Functions.debug(" Account:Result message for search ALL Account Records is " + accountSearchResult.getMessage());
Functions.debug(" Account:Result code for search ALL Record is " + accountResultCode);
if(accountResultCode < 0)
{
{
    String msg = "Account could not be retrieved";
  try {
    Functions.debug(msg + ":\n" + accountSearchResult.getMessage());  // Log details
      String objectID = p.get("object_id");
    Functions.throwError(msg + ".");                    // Error dialog
       String recordID = p.get("id");
}
      String newOwner = "..ID of owner with desired team..";
else if(accountResultCode == 0)
      boolean notifyNewOwner = true;
{
    Functions.debug("Account:No records found using the search function in ACCOUNT.");
}
else
{
    Functions.debug("Search for Hello World: Number of records found using search function in Account:" +
        accountResultCode);
    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");
        Functions.debug("Result from getRecord on ACCOUNT:\n" + getAccountRecordResult.getMessage());
        Functions.debug("Return code from getRecord on ACCOUNT:" + getAccountRecordResult.getCode());
        if(accountName.equals("Hello World"))
        {
            Functions.debug("Account record ID:" + accountRecordId);
            updateContactParams.add("description", "Updating Contact");
            updateContactParams.add("reference_type", "Account");
            updateContactParams.add("related_to_id", accountRecordId);
            updateContactParams.add("related_to_name", accountName);
            Functions.debug("Updating contact record with id:" + contactRecID);
            Result contactUpdateResult = Functions.updateRecord("CONTACT", contactRecID, updateContactParams);
            if(contactUpdateResult.getCode() == 0)
            {
              Functions.debug("Account:Contact of the Account record updated successfully\n" +
                  contactUpdateResult.getMessage());
            }
            else
            {
                String msg = "Error updating contact";
                Functions.debug(msg + ":\n" + contactUpdateResult.getMessage());  // Log details
                Functions.throwError(msg + ".");                    // Error dialog
            } 
        }         
    }
}
</pre>
 
===Create a Task Record===
 
This section shows how to add a task and associate it to the previously created contact record.
 
====Set Up a Parameters Object====
 
As with the records created earlier, the code starts by creating an instance of <tt>Parameters</tt> and then assigning key-value pairs to it.
 
The following code sample will:
*Set up <tt>Parameters</tt>; Note that the <tt>contact_id</tt> and <tt>reference_id</tt> keys are set to the <tt>contactRecID</tt> that was retrieved in the [[#Search for the Account and Contact Records|Search for the Account and Contact Records]] section, which associates the task with that contact
 
<pre>
String taskRecordID = null;
Functions.debug("Testing addTask");
Parameters addTaskParams = Functions.getParametersInstance();
addTaskParams.add("action_type", "Email");
 
//Set the frequency for this task to be every day
addTaskParams.add("calendar_frequency", "1");
 
//Set the calendar type to be day
addTaskParams.add("calendar_type", "5");
addTaskParams.add("contact_id", contactRecID );
addTaskParams.add("date_created", new Date());
addTaskParams.add("description", "Send email to set up an appointment to discuss the invoice.");
addTaskParams.add("notify_complete", "In Progress");
addTaskParams.add("percentage_complete", "10");
addTaskParams.add("priority", "High");
 
//Associate this task to a record that already exists so it will be displayed in open activities
//Add this task to a contact (associate the task to the contact record
//by setting the reference ID and the reference type)
addTaskParams.add("reference_id", contactRecID );
addTaskParams.add("reference_type", "CONTACT");
addTaskParams.add("status", "In Progress");
addTaskParams.add("subject", "Hello World - Invoice discussion:" + new Date());
addTaskParams.add("repeat_flag", "true");
addTaskParams.add("reminder_duration", "24");
</pre>
 


The following code sample shows the call to <tt>addTask</tt>. In order, the parameters are:
      // Result.getCode() >= 0 on success, -1 on failure
* Subject of the task
      Result r = Functions.changeOwnerShipInfo(
* Date of the task
        objectID, recordID, newOwner, notifyNewOwner);
* Owner of the task which is set by making a nested call to <tt>getEnv</tt> which is a Java API utility call
      if (r.getCode() < 0) {
* <tt>Parameters</tt> object
        Functions.throwError("Update failed\n" + r.getMessage() );    
 
      } 
<pre>
  } catch (Exception e) {
Result addTaskResult = Functions.addTask("CONTACT : Task for - " + contactRecID,
      Functions.throwError( e.getMessage() );    
    new Date(), Functions.getEnv(ENV.USER.ID), addTaskParams);
  }
Functions.debug("Result of addTask" + addTaskResult.getMessage());
if(addTaskResult.getCode() != -1)
{  
    taskRecordID = addTaskResult.getID();
    Functions.debug("Added task using addTask - ID : " + taskRecordID);
}
}
else
</syntaxhighlight>
{
    String msg = "Error adding Task";
    Functions.debug(msg + ":\n" + addTaskResult.getMessage());  // Log details
    Functions.throwError(msg + ".");                    // Error dialog
}
</pre>
 
====Check the Result====
 
Like other Java API calls such as <tt>addRecord</tt> and <tt>searchRecords</tt>, <tt>addTask</tt> returns a <tt>Result</tt> object whose methods can be called to check the result of the call. If <tt>addTask</tt> does not succeed, <tt>Result.getCode</tt> returns -1.
 
===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 <tt>contactRecID</tt> (the contact named "John Smith")
Find more information about arguments in <tt>[[sendEmailUsingTemplate]]</tt>
 
<pre>
Result getContactRecordResult = Functions.getRecord("CONTACT", "first_name,last_name,email",
    contactRecID);
Functions.debug("Sending Email to contact of Hello World Account..with email address:" +
    (getContactRecordResult.getParameters()).get("email"));
</pre>
 
 
The following code sample calls <tt>sendEmailUsingTemplate</tt>. In order, the parameters are:
* Related object identifier
* Identifier of the related record which is <tt>contactRecID</tt> that was retrieved previously
* To list which is set by making a nested call to <tt>Parameters.get</tt> to get the email address of the contact that was just retrieved
* Cc list which is set by making a nested call to <tt>Parameters.get</tt> to get the email address of the contact that was just retrieved
* Description (a text string)
* Identifier of a [[Print Templates|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 Templates|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)
 
<pre>
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", "", "");
Functions.debug("Done with sending mail from Hello World account's Contact John Smith");
if(sendEmailResult.getCode() != 0)
    Functions.debug("Error in sending email!" + sendEmailResult.getMessage());
}
else
{
    Functions.debug("Success on sendEmail, check inbox : " + sendEmailResult.getMessage());
    //If email was sent successfully update the task to end the task
    Parameters updateTaskParams = Functions.getParametersInstance();
    updateTaskParams.add("subject", "Email sent");
    updateTaskParams.add("end_flag", 1);
    updateTaskParams.add("status", "Completed");
    updateTaskParams.add("due_date", new Date());
    Result updateTaskResult = Functions.updateTask(taskRecordID, addTaskParams);
    Functions.debug("Updated task using updateTaskResult - " + taskRecordID + " : " + updateTaskResult.getMessage());
}
</pre>
 
Like other Java API calls such as <tt>addRecord</tt> and <tt>searchRecords</tt>, <tt>sendEmailUsingTemplate</tt> returns a <tt>Result</tt> object whose methods you can call to check the result of the call. When <tt>sendEmailUsingTemplate</tt> succeeds, <tt>Result.getCode</tt> returns zero (0).
 
====Mark the Task as Completed====
 
In this example, when the call to <tt>sendEmailUsingTemplate</tt> succeeds, the code creates an instance of <tt>Parameters</tt> and adds field-value pairs to it. Then the code calls <tt>updateTask</tt> specifying <tt>taskRecordID</tt> and the <tt>Parameters</tt> object as parameters. This updates the task that was added earlier, setting its <tt>status</tt> field to "completed".
 
===Java API Sample===
{{:Complex Java Code Data Policy Sample}}
 
{{#if: {{ShowDevInfo}} |
<noinclude>
<noinclude>


[[Category:Java API|1]]
[[Category:Java API|1]]
[[Category:Learn More]]
</noinclude>
</noinclude>
}}

Latest revision as of 21:08, 2 February 2015

About the Java API

The Java APIs are used when writing custom Classes that can be invoked from Rules.

The examples on the remainder of this page take you through the process of working with Java API, step by step.

Considerations
  • The Java 6 syntax and feature set are supported in custom classes.
  • When pasting code into the online editor, make sure it comes from a plain text editor.

Learn More:

Add an Account Record

To add record using Java API, follow these steps:

  1. Set up a Parameters Object
  2. Call addRecord to add a new record
  3. Check the result by calling methods in an instance of a Result object

Set up a Parameters Object

Data is passed to the platform using a Parameters object. The Parameters object holds key-value pairs, where each key corresponds to a field name and each value corresponds to a field value in the database. Set the key-value pairs and then pass the Parameters object as an argument when the record is added. (To learn more about the parameters passed to a Java method, see the Standard Parameters.)

To set up a Parameters Object, create an instance of Parameters to hold the key-value pairs for the record by calling getParametersInstance. This instance is named addAccountParams:

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

Parameters addAccountParams = Functions.getParametersInstance(); </syntaxhighlight>

To see the fields that are defined in an object:

  1. Open a web browser and Login to the platform
  2. Click GearIcon.png > Customization > Objects > {object} > Fields
  3. View the field list

Add the key-value pairs for the database fields to addAccountParams by calling Parameters.add:

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

addAccountParams.add("name","Hello World Account"); addAccountParams.add("number","0000001"); addAccountParams.add("city", "Orlando"); addAccountParams.add("country", "United States"); addAccountParams.add("county", "Marine County"); addAccountParams.add("phone", "222-222-2222"); addAccountParams.add("website", "www.helloworldaccount.com"); </syntaxhighlight>

Call addRecord

To add a new record, call addRecord and pass it an object identifier and the addAccountParams object. The values you added to addAccountParams are written to the account record in the database.

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

Result accountAddResult = Functions.addRecord("ACCOUNT", addAccountParams); </syntaxhighlight>

Like addRecord, many of the Java API record handling calls have an objectID parameter the object is specified ("ACCOUNT" in this example). In the objectID parameter, specify the Object Type Identifier.

Check the Result

The addRecord code (as well as several other Java API calls) returns an instance of the Result class. It is possible to check member variables in the Result object by calling its methods. For example, the code below makes a Java API debug utility call, making a nested call to Result.getMessage which returns a string indicating whether the call succeeded.

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

Logger.info("Result of addRecord for Account:" + accountAddResult.getMessage(), "Add"); </syntaxhighlight>

The string specified in the debug call is written to the debug log.

To view the Debug Log:

Click GearIcon.png > Customization > Developer Resources > Debug Log
When the code runs, use the Debug Log to troubleshoot problems during development. Many other debug calls are included in these code samples.

Debug Example for addRecord

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

  • Return codes:
  • less then zero (<0); the call is not successful
  • greater than or equal to zero (>= 0); successful

If the call is not successful, make a Java API throwError call, otherwise make a Result.getID call and continue

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

if(accountAddResult.getCode() < 0)

   String msg = "Function: Add Account";
   Logger.info(msg + ":\n" + accountAddResult.getMessage(), "Add"); // Log details
   Functions.throwError(msg + ".");                                 // Error message

else

   return accountAddResult.getID();

</syntaxhighlight>

Add a Contact Record

Here, you following the same process as adding an Account record to add a Contact Record:

  • Set up a Parameters Object
  • Create an instance of Parameters by calling getParametersInstance
  • Check the Result
<syntaxhighlight lang="java" enclose="div">

Parameters addContactParams = Functions.getParametersInstance(); </syntaxhighlight>

Then set the key-value pairs in the Parameters instance:

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

addContactParams.add("first_name", "John"); addContactParams.add("last_name", "Smith"); addContactParams.add("description", "Contact for Hello World added."); addContactParams.add("email", "mia@financio.com"); addContactParams.add("flag_primary_contact", "true"); addContactParams.add("street", "12345 Lake st"); </syntaxhighlight>

Call addRecord, specifying "CONTACT" as the object identifier and passing the Parameters object you set up above.

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

Result contactAddResult = Functions.addRecord("CONTACT", addContactParams); </syntaxhighlight>

Make a nested call to Result.getMessage to write to the debug log:

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

Logger.info("Result of addRecord for Contact - John Smith:"

         + contactAddResult.getMessage(), "Add");

</syntaxhighlight>

Check the return code by calling Result.getCode:

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

if(contactAddResult.getCode() < 0)

   String msg = "Getting Started: Add John Smith";
   Logger.info(msg + ":\n" + contactAddResult.getMessage(), "Add"); // Log details
   Functions.throwError(msg + ".");                                 // Error message

else

   return contactAddResult.getID();

</syntaxhighlight>

Update a Record

This code updates a record.

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

public void changeRecordValue(Parameters p) throws Exception {

  try {
     String objectID = p.get("object_id");
     String recordID = p.get("id");  
     
     // Specify the parameters to modify. (Only specified params are changed.)
     Parameters params = Functions.getParametersInstance();
     params.add("field_name", "new_value");
     // Result.getCode() >= 0 on success, -1 on failure
     Result r = Functions.updateRecord(objectID, recordID, params);
     if (r.getCode() < 0) {
        Functions.throwError("Update failed\n" + r.getMessage() );      
     }  
  } catch (Exception e) {
     Functions.throwError( e.getMessage() );      
  }

} </syntaxhighlight>

Change Record Ownership

This code changes a record's owner. Note that it does not reassign any tasks that may be attached to the record. (Additional code would be required to do that.)

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

public void changeOwner(Parameters p) throws Exception {

  try {
     String objectID = p.get("object_id");
     String recordID = p.get("id");  
     String newOwner = "..ID of owner with desired team..";
     boolean notifyNewOwner = true;
     // Result.getCode() >= 0 on success, -1 on failure
     Result r = Functions.changeOwnerShipInfo(
        objectID, recordID, newOwner, notifyNewOwner);
     if (r.getCode() < 0) {
        Functions.throwError("Update failed\n" + r.getMessage() );      
     }  
  } catch (Exception e) {
     Functions.throwError( e.getMessage() );      
  }

} </syntaxhighlight>