Difference between revisions of "Java API:Utility functions"

From AgileApps Support Wiki
imported>Aeric
imported>Aeric
Β 
(10 intermediate revisions by the same user not shown)
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, category)] - Detailed platform trace. Not recommended for application debugging.
:* [{{DOCHOST}}/javadocs/com/platform/api/Logger.html#trace(java.lang.Object,%20java.lang.Object) trace("message", "msgType")] - Detailed platform trace. Not recommended for application debugging.


:* [{{DOCHOST}}/javadocs/com/platform/api/Logger.html#debug(java.lang.Object,%20java.lang.Object) debug(message, category)] - Platform debug messages. Not recommended for application debugging.
:* [{{DOCHOST}}/javadocs/com/platform/api/Logger.html#debug(java.lang.Object,%20java.lang.Object) debug("message", "msgType")] - Platform debug messages. Not recommended for application debugging.


:* [{{DOCHOST}}/javadocs/com/platform/api/Logger.html#info(java.lang.Object,%20java.lang.Object) '''info(message, category)'''] - 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#info(java.lang.Object,%20java.lang.Object) '''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 <tt>fatal</tt> are displayed, by default.


:* [{{DOCHOST}}/javadocs/com/platform/api/Logger.html#warn(java.lang.Object,%20java.lang.Object) warn(message, category)] - Log a warning message.
:* [{{DOCHOST}}/javadocs/com/platform/api/Logger.html#warn(java.lang.Object,%20java.lang.Object) warn("message", "msgType")] - Log a warning message.


:* [{{DOCHOST}}/javadocs/com/platform/api/Logger.html#error(java.lang.Object,%20java.lang.Object) error(message, category)] - Log an error.
:* [{{DOCHOST}}/javadocs/com/platform/api/Logger.html#error(java.lang.Object,%20java.lang.Object) error("message", "msgType")] - Log an error.


:* [{{DOCHOST}}/javadocs/com/platform/api/Logger.html#fatal(java.lang.Object,%20java.lang.Object) fatal(message, category)] - Log a fatal error.
:* [{{DOCHOST}}/javadocs/com/platform/api/Logger.html#fatal(java.lang.Object,%20java.lang.Object) fatal("message", "msgType")] - 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
:* ''category'' is an arbitrary string that specifies the message type<br>(Put anything there you like, and use it for searching and filtering the debug log.)
:* ''msgType'' 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==
Considerations:
These methods are defined in the [{{DOCHOST}}/javadocs/com/platform/api/Functions.html Functions] class.
:* Log messages are plain text. For a linebreak, use "\n".
:* [{{DOCHOST}}/javadocs/com/platform/api/Functions.html#formatCurrency(java.lang.String,%20int) formatCurrency] - format a value using company's locale for currencies
Β 
:* [{{DOCHOST}}/javadocs/com/platform/api/Functions.html#formatNumber(java.lang.String,%20int) formatNumber] - format a numeric value using the user's locale
Β 
:* [{{DOCHOST}}/javadocs/com/platform/api/Functions.html#formatPercent(java.lang.String,%20int) formatPercent]- format a percentage value using the user's locale
Β 
:* [{{DOCHOST}}/javadocs/com/platform/api/Functions.html#parseCurrency(java.lang.String) parseCurrency] - parse a String using company's locale for currencies
Β 
:* [{{DOCHOST}}/javadocs/com/platform/api/Functions.html#parseNumber(java.lang.String) parseNumber] - parse a String using the user's locale
Β 
:* [{{DOCHOST}}/javadocs/com/platform/api/Functions.html#parsePercent(java.lang.String) parsePercent] - parse a String using the user's locale


==Service Configuration Functions==
==Service Configuration Functions==
Line 47: Line 37:
===getLoggedInUserInfo===
===getLoggedInUserInfo===
{{:getLoggedInUserInfo}}
{{:getLoggedInUserInfo}}
=== getParametersInstance ===
{{:getParametersInstance}}


===getTimezonesUtility===
===getTimezonesUtility===
Line 53: Line 46:
===getTimezoneUtility===
===getTimezoneUtility===
{{:getTimezoneUtility}}
{{:getTimezoneUtility}}
=== getParametersInstance ===
{{:getParametersInstance}}


===showMessage===
===showMessage===
Line 71: Line 61:
=== translateToken ===
=== translateToken ===
{{:translateToken }}
{{:translateToken }}
==Service Configuration Functions==
These methods are defined in the [{{DOCHOST}}/javadocs/com/platform/api/ServiceConfiguration.html ServiceConfiguration] class.
:* [{{DOCHOST}}/javadocs/com/platform/api/utility/ServiceConfiguration.html#getServiceName() getServiceName] - returns the Service Name configured in [[Service Provider Settings]].
:: For example: <tt>mydomain.com</tt>
:* [{{DOCHOST}}/javadocs/com/platform/api/utility/ServiceConfiguration.html#getServiceDomainURL() getServiceDomainURL] - returns the domain URL configured in [[Service Provider Settings]].
:: For example: <tt><nowiki>https://service.mydomain.com</nowiki></tt>
<noinclude>
<noinclude>


[[Category:Java API|Utility APIs]]
[[Category:Java API|Utility APIs]]
</noinclude>
</noinclude>

Latest revision as of 01:56, 11 November 2014

Logger Functions

These methods are defined in the Logger class. Going from the lowest level to the highest:

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.

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

For example: mydomain.com
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>

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>


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>


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.tokenname

args 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
Element Display Type Description
key string

A category name, followed by '.' and a message or label identifier (a "token").
Example: #categoryname.tokenname

String [] 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>