Difference between revisions of "Java API:Support Classes and Objects"

From AgileApps Support Wiki
imported>Aeric
imported>Aeric
 
(13 intermediate revisions by the same user not shown)
Line 1: Line 1:
<noinclude>__NUMBEREDHEADINGS__</noinclude>Use these support classes and objects with the [[Java API]].
<noinclude>__NUMBEREDHEADINGS__</noinclude>
__NOTOC__
Support classes and objects used with the [[Java API]]:
:* [[#Parameters Class|Parameters Class]] - A set of key-value pairs that holds field names and their values.
:* [[#ParametersIterator Class|ParametersIterator Class]] - Iterate through the <tt>Parameters</tt> objects returned by a search.
:* [[#Result Class|Result Class]] - Returned by most Java APIs. Contains status and other information.
:* [[#HttpConnection Class|HttpConnection Class]] - Makes an HTTP connection to a specified URI.
:* [[#SearchContext Class|SearchContext Class]] - Formulate a search query, one part at a time.
:* [[#request Object in JSP Pages|request Object in JSP Pages]] - Contains information provided in the HTTP request.
:* [[#tenantContext Object|tenantContext Object]] - Access and manage data shared by another tenant.


==Parameters Class==
==Parameters Class==
Line 16: Line 25:
{{:SearchContext Class}}
{{:SearchContext Class}}


==getPriorParams Method in Data Policy Parameters==
== request Object in JSP Pages ==
{{:getPriorParams}}
 
== request Object==
{{:request Object}}
{{:request Object}}


== requestParams Object==
== tenantContext Object==
{{:requestParams Object}}
{{:tenantContext Object}}
 
<!--
== functionParams Object==
== requestParams Object (deprecated) ==
{{:functionParams Object}}
{{Deprecated|Functions have been deprecated, along with this object. Existing functions can be edited, but it is no longer possible to create them. Instead of writing functions, the recommended practice is to write methods in Java [[Classes]], in order to gain the benefits of an improved [[Development Experience]]. }}


==tenantContext Object==
For information on this deprecated functionality, see the version 8.0 platform docs:<br>
{{:tenantContext Object}}
{{SERVER}}/lj80/index.php?title={{PAGENAMEE}}#requestParams_Object
<noinclude>
--><noinclude>


[[Category:Java API|Support Classes and Objects]]
[[Category:Java API|Support Classes and Objects]]
</noinclude>
</noinclude>

Latest revision as of 01:36, 12 January 2013


Support classes and objects used with the Java API:

1 Parameters Class

The Parameters class is a set of key-value pairs that holds a list of fields and their values:

  • You add key-value pairs to a Parameters object to pass values to Java API calls as input parameters. Each Java API call knows how to extract the key-value pairs and use the field values.
  • You extract key-value pairs that the Java API calls return.

You can see the fields defined for an object by selecting GearIcon.png > Customization > Objects > {object} > Fields.

1.1 Instantiating

You cannot instantiate a Parameters object with the new operator. Instead, you make the getParametersInstance utility call in the Java API:

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

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

You can also get an instance of a Parameters object by calling getParameters in the Result object.

Example

As an example, in the account object, there is a field called name that holds the name of an organization. Follow these steps to set the name field and add a new account record:

  1. Create an instance of the Parameters object
  2. Add the name field to it, setting the value (such as "Acme Solutions")
  3. Pass the Parameters object to the addRecord call

The code for this example is:

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

Parameters account = Functions.getParametersInstance(); account.add("name", "Acme Solutions"); String accountName = account.get("name"); Result result = Functions.addRecord("ACCOUNT", account); </syntaxhighlight>

1.2 Methods

The Parameters object has following methods which you can use to manipulate the set of key-value pairs.

1.2.1 add

Adds a key-value pair to the object.

Signature of the Method

void add(String key, Object value)
Example
This example the creates an instance of Parameters and then adds a key-value pair to it. As is frequently the case, it uses a string for the value, as well as the key.

<syntaxhighlight lang="java" enclose="div">Parameters params = Functions.getParametersInstance(); params.add("name", "Acme Solutions"); </syntaxhighlight>

1.2.2 get

Gets the value of the given key.

You must make sure the string is valid. No error is returned if you try to get an invalid string.

Signature of the Method <syntaxhighlight lang="java" enclose="div">String get(String key)</syntaxhighlight>

Example
This example creates an instance of Parameters, adds a key-value pair to it, and then calls get to assign that value to a variable.

<syntaxhighlight lang="java" enclose="div"> Parameters params = Functions.getParametersInstance(); params.add("name", "Acme Solutions"); String accountName = params.get("name"); </syntaxhighlight>

1.2.3 getDate

Gets a date value for the given key.

The returned value maps to java.util.Date.

For the first signature, this method throws a Java Exception if a date cannot be formed from the given key's value. For the second signature, this call returns defaultValue if a date cannot be formed.

Method Signature

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

Date getDate(String key) Date getDate(String key, Date defaultValue) </syntaxhighlight>

Example #1 - Get a Date
Use the getDate() method to retrieve a value in 'Date' format from the Parameters object.

This example assigns the result of a getRecord call to an instance of Parameters and then calls getDate with one parameter to assign the value to a variable.

If the following code is run from a data policy on any object, you can use requestParams to retrieve the record ID of the record and object ID of the object
<syntaxhighlight lang="java" enclose="div">

String recordID = requestParams.get("record_id"); Result result = Functions.getRecord(requestParams.get("object_id"), "record_id,date_created", recordID); Logger.info("Record retrieved in function using getRecord:"

           + result.getMessage(), "Parameters");

Date d = (result.getParameters()).getDate("date_created"); </syntaxhighlight>

Example #2 - Get an Existing or Default Date
This example assigns the result of a getRecord call to an instance of Parameters. The code then calls getDate with two parameters to assign the value to a variable; if a date value cannot be formed, the current date is assigned. The following code can be used in scenarios when we want to retrieve date field even if it is not populated. Assigns a default value of current Date.
<syntaxhighlight lang="java" enclose="div">

String recordID = requestParams.get("record_id"); Result result = Functions.getRecord(requestParams.get("object_id"), "record_id,date_created", recordID); Logger.info("Record retrieved in function using getRecord: "

          + result.getMessage(), "Parameters");

Parameters params = result.getParameters(); Date accountCreationDate = params.getDate("date_created", new Date()); // If the date_created field is not null or blank, returns // the date value, otherwise returns the current date. </syntaxhighlight>

1.2.4 getBoolean

Gets a Boolean value for a given key. If the value is equal to "1" or "true" or Boolean True, this call returns "true", otherwise it returns "false".

Signature of the Method <syntaxhighlight lang="java" enclose="div">boolean getBoolean(String key)</syntaxhighlight>

Example
This example assigns the result of a getRecord call to an instance of Parameters. The code then calls getBoolean to assign a property called do_not_call to a variable called do_not_call which is then conditonally tested to determine the code to execute.

<syntaxhighlight lang="java" enclose="div"> // Some code to populate accountID String accountID = ""; //If the following code is being used on a data policy from Account object, //you can retrieve the ID of the account record using requestParams String accountID = requestParams.get("record_id"); Result recordRetrieved = Functions.getRecord(requestParams.get("object_id"),

   "record_id,date_created,do_not_call", accountID);

Logger.info("Record retrieved in function using getRecord:"

          + recordRetrieved.getMessage(), "Parameters");

boolean doNotCall = (recordRetrieved.getParameters()).getBoolean("do_not_call"); if(doNotCall) {

   // Code here will specify what to do when doNotCall is true

} else {

   // Code here will specify what to do when 
   // doNotCall is false (in other words, when it is OK to call)

} </syntaxhighlight>

1.2.5 getInteger

Gets an integer value for the given key.

For the first signature, this method throws a Java Exception if an integer cannot be formed from the given key's value. For the second signature, this call returns defaultValue if an integer cannot be formed.

Signature of the Method

int getInteger(String key)

int getInteger(String key, int defaultValue)
Example
This example assigns the result of a getRecord call to an instance of Parameters and then calls getInteger with one parameter to assign the value to a variable.
<syntaxhighlight lang="java" enclose="div">

String accountID = ""; // Assuming the following code is being called from a policy on Account object accountID = requestParams.get("record_id"); Result recordRetrieved = Functions.getRecord("ACCOUNT", "record_id,employees", accountID); Logger.info("Record retrieved in function using getRecord:"

          + recordRetrieved.getMessage(), "Parameters");

int employees = (recordRetrieved.getParameters()).getInteger("employees");

</syntaxhighlight>

Example
This example assigns the result of a getRecord call to an instance of Parameters. The code then calls getInteger with two parameters to assign the value to a variable; if an integer value cannot be formed, 10 is assigned.

<syntaxhighlight lang="java" enclose="div"> String accountID = ""; // Assuming the following code is being called from a policy on Account object accountID = requestParams.get("record_id"); Result recordRetrieved = Functions.getRecord("ACCOUNT", "record_id,employees", accountID); Logger.info("Record retrieved in function using getRecord:"

          + recordRetrieved.getMessage(), "Parameters");

int employees = (recordRetrieved.getParameters()).getInteger("employees", 10); // This will return 10 employees if value of employees // is null or blank. </syntaxhighlight>

1.2.6 getFloat

Gets a float value for the given key.

For the first signature, this method throws a Java exception if a float cannot be formed from the given key's value. For the second signature, this call returns defaultValue if a float cannot be formed.

Signature of the Method

float getFloat(String key)

float getFloat(String key, float defaultValue)
Example
This example assigns the result of a getRecord call to an instance of Parameters and then calls getFloat with one parameter to assign the value to a variable.

<syntaxhighlight lang="java" enclose="div"> String accountID = ""; String objectID = ""; // Let us assume the following code is being used in a data policy related to ACCOUNT //You can use requestParams object to retrieve the record ID and object ID accountID = requestParams.get("record_id"); objectID = requestParams.get("object_id"); Result recordRetrieved = Functions.getRecord("ACCOUNT","record_id,revenue,date_created", accountID); Logger.info("Result from getRecord!\nMessage:" + recordRetrieved.getMessage()

         + "\nCode:" + recordRetrieved.getCode(), "Parameters");

if(recordRetrieved.getCode() == 1) {

  // This will return the revenue as 0
  // if the value of employees is null or blank
  Float totalRevenue = (recordRetrieved.getParameters()).getFloat("revenue"); 

} </syntaxhighlight>

Example
The following example show how to assign default values when you try to retrieve a float value using getFloat()

This example assigns the result of a getRecord call to an instance of Parameters. The code then calls getFloat with two parameters to assign the value to a variable; if a float value cannot be formed, 0.0 is assigned.

<syntaxhighlight lang="java" enclose="div"> String accountID = ""; String objectID = ""; // Let us assume the following code is being used in a data policy related to ACCOUNT //You can use requestParams object to retrieve the record ID and object ID accountID = requestParams.get("record_id"); objectID = requestParams.get("object_id"); Result recordRetrieved = Functions.getRecord("ACCOUNT","record_id,revenue,date_created", accountID); Logger.info("Result from getRecord!\nMessage:" + recordRetrieved.getMessage()

         + "\nCode:" + recordRetrieved.getCode(), "Parameters");

if(recordRetrieved.getCode() == 1) {

  // This will return the revenue as 0
  // if the value of employees is null or blank
  Float totalRevenue = ((recordRetrieved.getParameters()).getFloat(("revenue"), 0.0f)); 

} </syntaxhighlight>

1.2.7 remove

Removes a key-value pair for the given key.

Signature of the Method <syntaxhighlight lang="java" enclose="div">void remove(String key)</syntaxhighlight>

Example
This example creates an instance of Parameters, adds a key-value pair to it, and then removes that key-value pair.

<syntaxhighlight lang="java" enclose="div"> Parameters myAccount = Functions.getParametersInstance(); myAccount.add("name", "Acme Solutions"); myAccount.remove("name"); </syntaxhighlight>

1.2.8 clear

Removes all key-value pairs.

Signature of the Method

void clear()
Example
This example creates an instance of Parameters, adds key-value pairs to it, and then removes all the key-value pairs.

<syntaxhighlight lang="java" enclose="div"> Parameters params = Functions.getParametersInstance(); params.add("name", "Acme Solutions"); params.add("number", "60000"); params.clear(); </syntaxhighlight>

1.2.9 size

Returns the size of the Parameters object.

Signature of the Method <syntaxhighlight lang="java" enclose="div">int size()</syntaxhighlight>

Example
This example creates an instance of Parameters and adds two key-value pairs to it. The code then assigns the result of calling size to a variable called sizeOfParameters; at this point sizeOfParameters contains 2. Next, the code calls remove to delete one of the name-value pairs and assigns the result of calling size to sizeOfParameters; at this point sizeOfParameters contains 1.

<syntaxhighlight lang="java" enclose="div"> Parameters myAccount = Functions.getParametersInstance(); myAccount.add("name", "Acme Solutions"); myAccount.add("number", "Acme Solutions"); int sizeOfParameters = myAccount.size(); // sizeOfParameters variable is now 2

myAccount.remove("name"); sizeOfParameters = myAccount.size(); // sizeOfParameters variable is now 1 </syntaxhighlight>

1.2.10 getObject

Returns an Object of the value for the given string. Used to retrieve the record being imported as a string array.

Signature of the Method <syntaxhighlight lang="java" enclose="div">Object getObject(String key)</syntaxhighlight>

Example

<syntaxhighlight lang="java" enclose="div"> //Retrieve the row that will be imported //The String array returned will contain all the values in the row as its various elements String[] accountArray = (String[])requestParams.getObject("record"); //Retrieve the element String name = accountArray[0]; //Check the value of the column //Add the check based on your criteria if (name.equals("Acme")) {

  //Use throwError API so as to report the error 
  //The record that did not meet the criteria
  //Will not be imported   
   String msg = "Ignoring record:" + name;
   Logger.info(msg, "Parameters");  // Log it
   Functions.throwError(msg);       // Report it to user

} else {

  //Add you custom code here to proceed further 
  Logger.info("Value of record in csv:" + name, "Parameters");

} </syntaxhighlight>


2 ParametersIterator Class

The ParametersIterator class holds a list of Parameters objects returned by the searchRecords call. You can iterate through an instance of ParametersIterator to process Parameters objects one-by-one.

You create an instance of a ParametersIterator by making a getIterator call in the Result object.

2.1 Methods

The ParametersInterator class has following methods which you can call to manipulate the Parameters object:

2.1.1 hasNext

Returns true if there are more objects in the list, otherwise returns false. This method is used to iterate through a ParametersIterator object to get Parameters objects one-by-one.

Signature of the Method

boolean hasNext()

2.1.2 next

Gets the next Parameters object.

Signature of the Method

Parameters next()

2.1.3 remove

Removes the current Parameters object from the ParametersIterator object. Normally you do not need to call this.

Signature of the Method

void remove()

ParametersIterator Class Example

This example performs a search and if the search was successful and returned records, the code creates an instance of ParametersIterator. In a while loop, the code calls the ParametersIterator.next method to get an instance of Parameters from which it then extracts the name and number keys.

<syntaxhighlight lang="java" enclose="div"> String accountID = ""; // Some logic to populate accountID variable Result result = Functions.searchRecords("ACCOUNT", "record_id,name,number",

   "name contains 'Acme'");

int resultCode = result.getCode(); if(resultCode < 0) {

   // Some error happened.
   String msg = "Account could not be retrieved";
   Logger.info(msg + ":\n" + result.getMessage(), "Iterator"); // Log details
   Functions.throwError(msg + ".");                            // Error message

} else if(resultCode == 0) {

 // No records found. Take action according to your business logic

} else {

  //Records retrieved successfully
  ParametersIterator iterator = result.getIterator();
  while(iterator.hasNext())
  {
    Parameters myAccount = iterator.next();
    String accountID = myAccount.get("record_id");
    String accountName = myAccount.get("name");
    String number = myAccount.get("number");
    // Take action according to your business logic
  }

}</syntaxhighlight>


3 Result Class

An instance of the Result class is returned by many of the Java APIs.

Considerations
  • If the return code is less than zero, it is an error code.
The Result object contains an error message that explains the error.
  • If the return code is zero, the call succeeded, but no records are present.
This value is returned by an add, update, or delete, or when no records match specified search criteria.
  • If the return code is greater than zero, the value is the number of records in the result set.
In that case, there are two options:
  • If the API expected to return a single record, as in a getRecord operation, the getParameters method (below) returns a Parameters object that contains the record fields.
  • If the API expected to return multiple records, as in an execSQL query or a searchRecords operation, then the getIterator method (below) is used to cycle through the list of Parameters objects contained in the Result set (one per record). (In that case, the getParameters method returns null.)

3.1 Methods

The Result class has following methods.

3.1.1 getCode

Gets the error code for record handling calls such as addRecord, updateRecord, deleteRecord, and so on.

For the searchRecords and getRecord calls, the code indicates the number of records returned.

These are the rules that the record handling calls follow for setting the error code:

  • All record handling calls set the error code to negative one (-1) if not successful.
  • Most record handling calls set the error code to zero (0) if successful. The exceptions to this rule are:
    • getRecord sets the error code to one (1) if successful
    • searchRecord sets the error code to the number of records retrieved if successful

Signature of the Method

<syntaxhighlight lang="java" enclose="div">int getCode()</syntaxhighlight>
Example
This example calls addRecord, assigning the returned value to an instance of Result and calling Result.getCode to assign the error code to a variable which is then conditionally checked to determine the code to execute.

<syntaxhighlight lang="java" enclose="div"> Parameters myAccount = Functions.getParametersInstance(); myAccount.add("name", "Acme Solutions"); Result result = Functions.addRecord("ACCOUNT", params); int returnCode = result.getCode(); if(returnCode < 0) {

   String msg = "Account could not be added";
   Logger.info(msg + ":\n" + result.getMessage(), "Accounts"); // Log details
   Functions.throwError(msg + ".");                            // Error message

} else {

 // take other actions according to 
 // your business logic.

} </syntaxhighlight>

3.1.2 getID

Gets the record identifier set by addRecord and generateDocument. When these calls fail, the record identifier is an empty string.

Signature of the Method <syntaxhighlight lang="java" enclose="div">String getID()</syntaxhighlight>

Example
This example calls addRecord, assigning the returned value to an instance of Result and calling Result.getCode to assign the error code to a variable which is then conditionally checked to determine the code to execute. If the call was successful, the code calls getID to extract the record identifier.

<syntaxhighlight lang="java" enclose="div"> Parameters myAccount = Functions.getParametersInstance(); myAccount.add("name", "Acme Solutions"); Result result = Functions.addRecord("ACCOUNT", myAccount); int returnCode = result.getCode(); if(returnCode < 0) {

   String msg = "Account could not be added";
   Logger.info(msg + ":\n" + result.getMessage(), "Accounts"); // Log details
   Functions.throwError(msg + ".");                            // Error message

} else {

 String id = result.getID();
 // use the ID when updating the record or adding a record to a related object

} </syntaxhighlight>

3.1.3 getMessage

Gets the message that indicates success or failure.

Signature of the Method <syntaxhighlight lang="java" enclose="div">String getMessage()</syntaxhighlight>

Example
This example calls addRecord, assigning the returned value to an instance of Result and calling Result.getCode to assign the error code to a variable which is then conditionally checked to determine the code to execute. If the call was not successful, the code calls getMessage to extract the message string.

<syntaxhighlight lang="java" enclose="div"> Parameters myAccount = Functions.getParametersInstance(); myAccount.add("name", "Acme Solutions"); Result result = Functions.addRecord("ACCOUNT", params); int returnCode = result.getCode(); if(returnCode < 0) {

   String msg = "Error adding Acme Solutions account";
   Logger.info(msg + ":\n" + result.getMessage(), "Accounts"); // Log details
   Functions.throwError(msg + ".");                            // Error message

} else {

 String id = result.getID();
 // use the ID to addTask, addActivity or 
 // add any other related object.

} </syntaxhighlight>

3.1.4 getIterator

Gets a ParametersIterator object after a searchRecords call.

Signature of the Method <syntaxhighlight lang="java" enclose="div">ParametersIterator getIterator()</syntaxhighlight>

Example
This example calls searchRecords, assigning the returned value to an instance of Result and calling Result.getCode to assign the error code to a variable which is then conditionally checked to determine the code to execute. If the call was successful and records were returned, the code creates an instance of ParametersIterator. In a while loop, the code calls the ParametersIterator.next method to get an instance of Parameters from which it then extracts the record identifier.

<syntaxhighlight lang="java" enclose="div"> Result result = Functions.searchRecords("ACCOUNT", "record_id,name, number,city", "name starts with 'Acme'"); int returnCode = result.getCode(); if(returnCode < 0) {

   String msg = "Error searching Account records";
   Logger.info(msg + ":\n" + result.getMessage(), "Accounts"); // Log details
   Functions.throwError(msg + ".");                            // Error message

} else if(returnCode == 0) {

 Functions.throwError("No records found");

} else {

 ParametersIterator iterator = result.getIterator();
 while(iterator.hasNext())
 {
   Parameters myAccount = iterator.next();
   String id = myAccount.get("record_id");
   // execute your other business logic
 }

} </syntaxhighlight>

3.1.5 getParameters

Creates a Parameters object.

Signature of the Method

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

Parameters getParameters() </syntaxhighlight>

Example
This example calls getRecord, assigning the returned value to an instance of Result and calling Result.getCode to assign the error code to a variable which is then conditionally checked to determine the code to execute. If the call was successful and records were returned, the code creates an instance of Parameters and extracts the name.
<syntaxhighlight lang="java" enclose="div">

String accountID = ""; // Some code to populate accountID variable Result result = Functions.getRecord("ACCOUNT", accountID); int returnCode = result.getCode(); if(returnCode < 0) {

   String msg = "Error retrieving Account record";
   Logger.info(msg + ":\n" + result.getMessage(), "Accounts"); // Log details
   Functions.throwError(msg + ".");                            // Error message

} else {

 Parameters params = result.getParameters();
 String accountName = params.get("name");
 // execute your other business logic based on name

} </syntaxhighlight>


4 HttpConnection Class

4.1 About the Java API:Support Classes and Objects

The HttpConnection class makes a HTTP connection to a given URI. You can use it to make GET and POST requests to other web services.

Considerations
  • HTTPS calls are supported only for URIs that have standard security certificates.
  • When you call the execute method in HttpConnection, it executes the request, gets the response, and closes the connection. This means that a single object cannot be used multiple times. For multiple HTTP requests, instantiate multiple instances.
  • Make sure that the URL is properly encoded when instantiating an HttpConnection object.

Learn more:

4.2 Constructor

You create an instance of HttpConnection using the new operator.

Method signature
HttpConnection con = new HttpConnection(int methodType, String encoded_URI)
methodType
Sets the HTTP method type:
  • CONSTANTS.HTTP.METHOD.GET for an HTTP GET request
  • CONSTANTS.HTTP.METHOD.POST for an HTTP POST request
String encoded_URI
Properly encoded URI to connect to
Learn more: URL Encoding

4.3 Methods

The methods are:

4.3.1 addHeader

Adds a key-value pair to the request header.

Method signature
void addHeader(String key, String value)
Parameters
  • key - The name of the key
  • value - The value of the key
Return
None

4.3.2 addParameter

Adds a parameter to an HTTP POST request. This methods throws an exception if it is called for an HTTP GET request.

Method signature
void addParameter(String key, String value)
Parameters
  • key - The name of the key
  • value - The value of the key
Return
None

4.3.3 execute

Executes the request and returns a standard HTTP response such as "200 - OK" or "404 - not found".

Method signature
int execute()
Parameters
None
Return
Standard HTTP response

4.3.4 getResponse

Returns the response as a String.

Method signature
String getResponse()
Parameters
None
Return
The response from the service

4.3.5 encode

Returns a String encoded from s.

Method signature
String encode(String s)
Parameters
  • s - The string to encode
Return
The encoded string

4.3.6 getResponseHeaders

Retrieve the headers from the HTTP Response from an external server. It is a map of String Header Name/Header Value pairs.

For example, if the Header Content-Length is equal to 10008, then "Content-Length" is the Header Name and "10008" is the Header Value.

This method is to be called after execute method of HttpConnection.

Method signature
HashMap<String name, String value> getResponseHeaders()
Parameters
None
Return
A HashMap of Header Name/Header Value string pairs

4.3.7 setRequestBody

Specify the body of the request, the content type, and character set.

Method signature
HashMap<String name, String value> getResponseHeaders()
Parameters
  • content-Type - String. One of the valid MIME types for the body of a request. For example: "application/xml".
  • charSet - String. The character set used in the request. For example: "utf-8".
Return
None
Learn more:

4.4 HttpConnection Example

This example gets the result of a Google search for "IT Leaders".

<syntaxhighlight lang="java" enclose="div"> HttpConnection con = new HttpConnection(CONSTANTS.HTTP.METHOD.GET,

   "http://www.google.com/search?hl=en&q=IT+Leaders&btnG=Google+Search");

int code= con.execute(); String response = con.getResponse(); </syntaxhighlight >

Notepad.png

Note: The typical response format is JSON. Those libraries are built into the platform. The APIs are documented at JSON.org.


5 SearchContext Class

This class is designed for large, complex queries. Using it, you can formulate a search query one part at a time, and have each part validated independently, rather than putting the entire query in one long string and having it validated all at once.

5.1 Creating a SearchContext Object

Use the setters and getters in the SearchContext class to set up the query. (The syntax for each part is identical to that used with the REST APIs to create a Dynamic Search. The only difference is that you don't have to concatenate them all into a single string.)

5.2 Using the SearchContext Object

These APIs take a SearchContext object:

  • Functions.searchRecords(SearchContext searchContext)
  • Functions.searchGlobalPicklists(SearchContext searchContext)
  • Functions.searchPackages(SearchContext searchContext)
  • Functions.searchSocialFeeds(SearchContext searchContext)
  • Functions.searchSocialGroups(SearchContext searchContext)

Learn more: Uses recorded in the Javadocs

5.2.1 Example

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

SearchContext searchContext = new SearchContext();

searchContext.setFieldList("*"); searchContext.setObjectId(""); // For a record search: objectName or ID searchContext.setPage(0); searchContext.setPageSize(5000); searchContext.setFilter("title contains 'Order' "); // Criteria searchContext.setSortBy("date_created"); searchContext.setSortBy2("title"); searchContext.setSortOrder("DESC"); searchContext.setSortOrder2("ASC");

List<GlobalPicklistBean> results; results = Functions.searchGlobalPicklists(searchContext); </syntaxhighlight>


6 request Object in JSP Pages

The request object is available in any JSP Page. It contains information provided when the HTTP request is made. The information it contains can be used with the REST record Resource or Java Record Handling APIs to get further information from the record.

When a JSP page is invoked by an active record, the request object contains record identifiers.

Record-identifying information is available when:

To get all of the parameters available in the request object, and their values:

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

<%

 String[] params = request.getParameterValues();
 for (int i=0; i<params.length; i++)
 {
   String paramName = params[i];
   String paramValue = request.getParameter( paramName );
 }

%> </syntaxhighlight>

To obtain a record identifier from a request object sent by the platform:

With the object ID and record ID, use the getRecord API to retrieve the record.
<syntaxhighlight lang="java" enclose="div">

<%

 String object_id = request.getParameter("object_id");
 String record_id = request.getParameter("record_id");

%> </syntaxhighlight>

Notepad.png

Note: Although the object_id is alphanumeric, it can be used in any API that requires an object name.

To obtain a record identifier from a request object sent by a Custom Action button:

This code gets the record IDs and uses the searchRecords API to retrieve the records:
<syntaxhighlight lang="java" enclose="div">

<%

 // Get the object ID and the comma separated list of record IDs
 String object_id = request.getParameter("object_id");
 String selectedRecords = request.getParameter("selectedRecords"); 
 // Break the comma-separated list into record IDs. 
 // Join them with "OR" operands for use when searching for the records
 String filterCriteria = "";
 if (selectedRecords != null)
 {
   StringTokenizer st = new StringTokenizer(selectedRecords,",");
   while (st.hasMoreTokens())
   {
     if ( !"".equals(filterCriteria.trim()))
     {
        // Criteria string isn't empty, and we're adding another expression
        // Prefix the new expression with a boolean OR operator
        filterCriteria += " OR "
     }
     filterCriteria += "record_id = "+ st.nextToken();
   }
 }
 // Use the filter criteria to fetch the selected records
 // Here, we ask for the record_id and name fields
 Result results;
 results = Functions.searchRecords(object_id , "record_id,name", filterCriteria);
 int resultCode = results.getCode();
 if (resultCode < 0)
 {
    // Error occurred
 }
 else if (resultCode == 0)
 {
   // No records found. (This situation should never occur.)
 }
 else
 {
   // Records retrieved successfully
   // Process them here
   ParametersIterator iterator = results.getIterator();
   while(iterator.hasNext())
   {
     Parameters params = iterator.next();
     String recordID = params.get("record_id");
     String recordName = params.get("name");
     // Take additional action according to your business logic
   }
 }

%> </syntaxhighlight>

7 tenantContext Object

The tenantContext object is used to access and manage data that has been shared by another tenant, using Tenant Data Sharing Policies.

Once a data sharing policy has been set up, you specify the sharing tenant's ID to get a tenantContext. You then use that object as a parameter in one of the Java APIs for Tenant Data Sharing.

Learn more: TenantContext javadocs

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

try {

   TenantContext tenantContext = new TenantContext(String tenantId);

} catch Exception(e) {

   // An exception is thrown if the specified tenant has not defined
   // a tenant data sharing policy that gives you access.

} </syntaxhighlight>