Difference between revisions of "Java API:Utility functions"
imported>Aeric |
imported>Aeric |
||
Line 2: | Line 2: | ||
These methods are defined in the [{{DOCHOST}}/javadocs/com/platform/api/Logger.html Logger] class. Going from the lowest level to the highest: | These methods are defined in the [{{DOCHOST}}/javadocs/com/platform/api/Logger.html Logger] class. Going from the lowest level to the highest: | ||
:* [{{DOCHOST}}/javadocs/com/platform/api/Logger.html#trace(java.lang.Object,%20java.lang.Object) trace(message, | :* [{{DOCHOST}}/javadocs/com/platform/api/Logger.html#trace(java.lang.Object,%20java.lang.Object) trace("message", "type")] - Detailed platform trace. Not recommended for application debugging. | ||
:* [{{DOCHOST}}/javadocs/com/platform/api/Logger.html#debug(java.lang.Object,%20java.lang.Object) debug(message, | :* [{{DOCHOST}}/javadocs/com/platform/api/Logger.html#debug(java.lang.Object,%20java.lang.Object) debug("message", "type")] - Platform debug messages. Not recommended for application debugging. | ||
:* [{{DOCHOST}}/javadocs/com/platform/api/Logger.html#info(java.lang.Object,%20java.lang.Object) '''info(message, | :* [{{DOCHOST}}/javadocs/com/platform/api/Logger.html#info(java.lang.Object,%20java.lang.Object) '''info("message", "type")'''] - Log an information message<br>This is the default display level in the [[Debug Log]]. This level is appropriate for most application debugging. | ||
:* [{{DOCHOST}}/javadocs/com/platform/api/Logger.html#warn(java.lang.Object,%20java.lang.Object) warn(message, | :* [{{DOCHOST}}/javadocs/com/platform/api/Logger.html#warn(java.lang.Object,%20java.lang.Object) warn("message", "type")] - Log a warning message. | ||
:* [{{DOCHOST}}/javadocs/com/platform/api/Logger.html#error(java.lang.Object,%20java.lang.Object) error(message, | :* [{{DOCHOST}}/javadocs/com/platform/api/Logger.html#error(java.lang.Object,%20java.lang.Object) error("message", "type")] - Log an error. | ||
:* [{{DOCHOST}}/javadocs/com/platform/api/Logger.html#fatal(java.lang.Object,%20java.lang.Object) fatal(message, | :* [{{DOCHOST}}/javadocs/com/platform/api/Logger.html#fatal(java.lang.Object,%20java.lang.Object) fatal("message", "type")] - Log a fatal error. | ||
where: | where: | ||
:* ''message'' is the message to put into the debug log | :* ''message'' is the message to put into the debug log | ||
:* '' | :* ''type'' is an arbitrary string that specifies a message type, or category<br>(Put anything there you like. For example: The class name. Use it for searching and filtering the debug log.) | ||
==Localization Functions== | ==Localization Functions== |
Revision as of 01:17, 19 September 2013
Logger Functions
These methods are defined in the Logger class. Going from the lowest level to the highest:
- trace("message", "type") - Detailed platform trace. Not recommended for application debugging.
- debug("message", "type") - Platform debug messages. Not recommended for application debugging.
- info("message", "type") - Log an information message
This is the default display level in the Debug Log. This level is appropriate for most application debugging.
- info("message", "type") - Log an information message
- warn("message", "type") - Log a warning message.
- error("message", "type") - Log an error.
- fatal("message", "type") - Log a fatal error.
where:
- message is the message to put into the debug log
- type 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.)
Localization Functions
These methods are defined in the Functions class.
- formatCurrency - format a value using company's locale for currencies
- formatNumber - format a numeric value using the user's locale
- formatPercent- format a percentage value using the user's locale
- parseCurrency - parse a String using company's locale for currencies
- parseNumber - parse a String using the user's locale
- parsePercent - parse a String using the user's locale
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
- <syntaxhighlight lang="java" enclose="div">
import static com.platform.api.CONSTANTS.*; ... String = Functions.getEnv(String variable) </syntaxhighlight>
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.
- <syntaxhighlight lang="java" enclose="div">
String userID = Functions.getEnv(ENV.USER.ID); </syntaxhighlight>
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
- <syntaxhighlight lang="java" enclose="div">
Map user = Functions.getLoggedInUserInfo(); Logger.info(user, "UserInfo"); Logger.info(user.get("last_name"), "UserInfo"); </syntaxhighlight>
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
- <syntaxhighlight lang="java" enclose="div">
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");
} </syntaxhighlight>
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
- <syntaxhighlight lang="java" enclose="div">
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");
</syntaxhighlight>
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.
<syntaxhighlight lang="java" enclose="div"> Parameters params = Functions.getParametersInstance(); params.add("name", "Acme Solutions"); params.add("number", "GRG2323339"); Result result = Functions.addRecord("ACCOUNT", params); </syntaxhighlight>
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
- <syntaxhighlight lang="java" enclose="div">
void Functions.showMessage(String message); void Functions.showMessage(String key, String[] args); </syntaxhighlight>
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:
- <syntaxhighlight lang="java" enclose="div">
Functions.showMessage("#custom.label", null) </syntaxhighlight>
To include linebreaks in the message, specify <br>:
- <syntaxhighlight lang="java" enclose="div">
Functions.showMessage("Include
for
newline");
</syntaxhighlight>
- 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
- <syntaxhighlight lang="java" enclose="div">
void Functions.sleep(long milliseconds); </syntaxhighlight>
- 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
- <syntaxhighlight lang="java" enclose="div">
Functions.setTargetPage("Service?t=923&targetpage=ChangeSecurityQuestion.jsp");
</syntaxhighlight>
- 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.
- <syntaxhighlight lang="java" enclose="div">
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"); } } } </syntaxhighlight>
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
- <syntaxhighlight lang="java" enclose="div">
void = Functions.throwError(String key [, String[] args])
</syntaxhighlight>
If no arguments are needed (for example, for a label in the #custom category), use:
- <syntaxhighlight lang="java" enclose="div">
Functions.throwError("#custom.label",null) </syntaxhighlight>
- 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".
<syntaxhighlight lang="java" enclose="div"> 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.
} </syntaxhighlight>
To include linebreaks in the message, specify <br>:
- <syntaxhighlight lang="java" enclose="div">
Functions.throwError("Include
for
newline"); </syntaxhighlight>
translateToken
The translateToken API accesses a Custom Label (a message) defined in the Translation Workbench.
- Syntax
- <syntaxhighlight lang="java" enclose="div">
String result = Functions.translateToken(String key) String result = Functions.translateToken(String key, String [] args) </syntaxhighlight>
- 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.
- <syntaxhighlight lang="java" enclose="div">
String [] args = {"nice", "walk"}; String msg = Functions.translateToken("#custom.go_msg", args));
// ==> "It's a nice day for a walk."
</syntaxhighlight>
Service Configuration Functions
These methods are defined in the ServiceConfiguration class.
- 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