Java API:Utility functions
Logger Functions
These methods are defined in the Logger class. Going from the lowest level to the highest:
- trace("message", "msgType") - Detailed platform trace. Not recommended for application debugging.
- debug("message", "msgType") - Platform debug messages. Not recommended for application debugging.
- info("message", "msgType") - Log an information message.
- This is the default display level in the Debug Log. This level is appropriate for most application debugging, as logged messages from here through fatal are displayed, by default.
- warn("message", "msgType") - Log a warning message.
- error("message", "msgType") - Log an error.
- fatal("message", "msgType") - Log a fatal error.
where:
- message is the message to put into the debug log
- msgType is an arbitrary string that specifies a message type, or category
(Put anything there you like. For example, the class name. Use it for searching and filtering the debug log.)
Considerations:
- Log messages are plain text. For a linebreak, use "\n".
Service Configuration Functions
- getServiceName - returns the Service Name configured in Service Provider Settings.
- For example: mydomain.com
- getServiceDomainURL - returns the domain URL configured in Service Provider Settings.
- For example: https://service.mydomain.com
General Purpose Functions
These methods are defined in the Functions class.
getEnv
- getEnv(String key)
- Description
- Gets the environment variable value for the key
- See also: getLoggedInUserInfo
Syntax
import static com.platform.api.CONSTANTS.*; ... String = Functions.getEnv(String variable)
Environment Variable Constants
- The following constants can be used as keys to access the environment variables:
Key Variable ENV.USER.ID Logged in user's ID ENV.USER.USER_NAME Logged in user's username ENV.USER.FULL_NAME Logged in user's full name ENV.USER.COMPANY_NAME Logged in user's company name ENV.USER.EMAIL Logged in user's email ENV.USER.TENANT_ID The ID of the tenant the user is logged in to ENV.USER.TIME_ZONE Logged in user's timezone ENV.COMMUNITY.TENANT.ID The community tenant ID ENV.SESSION.ID ID of the logged in user's session ENV.ISV.RECAPTCHA_PUBLIC_KEY Key used when verifying that the system is interacting with a person. Learn more: recaptcha.
Return
- The value of the environment variable as a String.
- Example
- This example calls getEnv to get the current user's identifier.
String userID = Functions.getEnv(ENV.USER.ID);
getLoggedInUserInfo
- Functions.getLoggedInUserInfo()
- Description
- Retrieves information about a Logged in User
- In addition to the fields are listed in REST API:user Resource, this API returns the following:
Name Type Attribute Description Additional Information locale Object Read Only Identifies the user's language and country code java.util.Locale
- Syntax
Map<String,Object> Functions.getLoggedInUserInfo()
- Return
- Map containing user information
- Example
Map user = Functions.getLoggedInUserInfo(); Logger.info(user, "UserInfo"); Logger.info(user.get("last_name"), "UserInfo");
getParametersInstance
- Functions.getParametersInstance()
- Description
- Gets an instance of the Parameters class
- Returns an instance of the Parameters class
- Syntax
Parameters = Functions.getParametersInstance()
- Return
- Parameters object
- Example
- This example creates an instance of Parameters, adds name-value pairs to it, and calls addRecord, passing the Parameters object as an argument.
Parameters params = Functions.getParametersInstance(); params.add("name", "Acme Solutions"); params.add("number", "GRG2323339"); Result result = Functions.addRecord("ACCOUNT", params);
getTimezonesUtility
- Functions.getTimezonesUtility()
- Description
- Retrieves the list of time zones
- Syntax
Map<String, TimeZoneBean> m = Functions.getTimezonesUtility();
- Return
- Map<String, TimeZoneBean>
- Example
- Retrieve a list of all timezones
- Learn more: Time Zone Codes
Logger.info("Retrieve time zone list", "TimeZones"); Map<String, TimeZoneBean> timezoneCollection = Functions.getTimezonesUtility(); for(Map.Entry e : timezoneCollection.entrySet()) { TimeZoneBean tz = e.getValue(); Logger.info("code: "+ tz.getId() + "; value: "+ tz.getJavaValue() + "; user friendly value: "+ tz.getUserFriendlyValue(), "TimeZones"); }
getTimezoneUtility
- Description
- Retrieves a time zone, based on a provided id
- Syntax
TimeZoneBean tz = Functions.getTimezoneUtility(String timezoneId);
- Where timezoneId is a Time Zone Code
- Return
- TimeZoneBean
- Example
- Retrieve the time zone for timezoneId = 80
Logger.info("Retrieve time zone 80", "TimeZones"); TimeZoneBean tz = Functions.getTimezoneUtility("80"); Logger.info("code: "+ tz.getId() + "; value: "+ tz.getJavaValue() + "; user friendly value: "+ tz.getUserFriendlyValue(), "TimeZones");
showMessage
- Description
This function displays a message to the user, either at the top of page or in a dialog, depending on the context.
- The basic version of the function displays a message string.
- With additional options, a localized version of a message can displayed.
- Considerations
-
- The function displays the message in the UI, irrespective of any database insertions or updates (in other words, without interrupting the program flow).
- If the function is called multiple times, the messages are concatenated, and displayed together when the code returns to the platform. (Only one dialog is ever displayed.)
- The text is displayed in HTML format, so linebreaks (<br>) and text formatting (<b>, <i>) can be included.
- In a JSP page, this function does nothing. Use a JavaScript alert(), instead.
- Syntax
void Functions.showMessage(String message); void Functions.showMessage(String key, String[] args);
To display a localized message:
Element Type Description key String A category name, followed by '.' and a message or label identifier (a "token").
Example: #categoryname.tokennameargs Array of String Optional. Causes the first parameter to be treated as a key. - If no additional arguments are passed, the original key (the message string) is displayed.
- If arguments are passed, the key is used to retrieve a Custom Label in the current language, with the supplied arguments injected into it.
To provide a key for a label that has no arguments (for example, for a label in the #custom category), use:
Functions.showMessage("#custom.label", null)
To include linebreaks in the message, specify <br>:
Functions.showMessage("Include <br> for <br> newline");
- Return
-
- Returns the localized message configured on the key in the Translation Workbench.
- If no key is configured in the translation workbench, then the passed key is returned.
sleep
- Functions.sleep(long milliseconds)
- Description
- Pauses the current process for the specified number of milliseconds.
- Syntax
void Functions.sleep(long milliseconds);
- Throws
-
- InterruptedException if the process was awakened by the JVM (or terminated) before the specified wake-up time.
setTargetPage
- setTargetPage(String URL)
- Description
- Performs the action of clicking a link in the UI
- Sets the target page, URL is the relative path
- Syntax
Functions.setTargetPage("Service?t=923&targetpage=ChangeSecurityQuestion.jsp");
- Return
- None
- Example
Perform the following steps to display the security page:
1. Go to Configuration > Customization > Developer Resources > Classes > New Class.
2. Create the class with the following code.
package com.platform.nmag3.nmjip; import com.platform.api.*; public class Redirect { public void setTargetAPIPageTest(Parameters params)throws Exception { try { Functions.setTargetPage("Service?t=923&targetpage=ChangeSecurityQuestion.jsp"); } catch(Exception exp) { throw new Exception("setTargetAPIPageTest() method failed in JAVAAPITestClass"); } } }
3. Go to Configuration > System Objects > User Business Rules.
4. Add a business rule for the Update event.
5. Ensure that you select the Unconditionally (Always) option in the Execution Criteria field.
6. Under actions to perform, select Invoke Method from the dropdown.
7. Select the class name as Redirect and choose method name as setTargetAPIPageTest() [class created in the step 2].
8. Save the Rule.
9. Go to Configuration > Access Management > Users.
10. Click the Edit button to update any user details.
11. Click Save.
12. Now, the security page appears as the target page.
throwError
- Functions.throwError(key [, String[] args])
- Description
-
- Ends execution and throws an error with the specified message
- Supports Language Translation via Translation Workbench
- Translates the token and displays the translated message in the selected language
Element Display Type Description key string A category name, followed by '.' and a message or label identifier (a "token").
Example: #categoryname.tokennameString [] args string Optional Declares an array of Strings in Java (or Arguments)
- If arguments are passed, the call expects a token
- If no arguments are passed, the message alone is displayed
- Syntax
void = Functions.throwError(String key [, String[] args])</pre>
If no arguments are needed (for example, for a label in the #custom category), use:
Functions.throwError("#custom.label",null)
- Return
-
- Returns the message configured on the key in the Translation Workbench
- If no key is configured in the translation workbench, then the passed key is returned
- Example
- This example checks a parameter passed to it to see if it is equal to "Acme". If it is, the code calls throwError to display an error message saying that the account cannot be "Acme".
if(requestParams.get("name").equals("Acme")) { // message "Account cannot be Acme" will be shown to the user in the UI. Functions.throwError("Account cannot be Acme"); } else { // Normal business logic. }
To include linebreaks in the message, specify <br>:
Functions.throwError("Include <br> for <br> newline");
translateToken
The translateToken API accesses a Custom Label (a message) defined in the Translation Workbench.
- Syntax
String result = Functions.translateToken(String key) String result = Functions.translateToken(String key, String [] args)
- Parameters
-
- key
- The category and token (index key) for the message to retrieve, in the form: "#category.token_name".
- args
- An array of string-arguments to be substituted into the message, in the locations defined by the message format.
- Returns
- A string containing the selected message in the user's currently active language, with specified arguments substituted.
- Example
- In this example, go_msg is a Custom Label in the Translation Workbench created in the "custom" category, where the translation in the user's current language is "It's a {1} day for a {2}." Supplying the arguments then allows for variations on the message.
String [] args = {"nice", "walk"}; String msg = Functions.translateToken("#custom.go_msg", args)); // ==> "It's a nice day for a walk."