Difference between revisions of "Functions"

From PresenceWiki
Jump to: navigation, search
(&eval{EXPRESSION})
(&heVal{NUMBER})
Line 520: Line 520:
 
*sqrt
 
*sqrt
  
=====&heVal{NUMBER}=====
+
=====Hex Value=====
 +
Format: &hexVal{NUMBER}
 +
 
 
Returns the hexidecimal value of the number passed in parameter 1.  
 
Returns the hexidecimal value of the number passed in parameter 1.  
 
<pre>&hexVal(255)</pre> Returns FF
 
<pre>&hexVal(255)</pre> Returns FF

Revision as of 08:20, 14 August 2015

Contents

About Presence Functions

Functions can be used almost anywhere a Presence Text Area is Used, you know if you are in a Presence Text Area by Pressing CTRL+Space. Almost all Presence Functions will accept Presence Variables in the form of ${variable_name}, you can also embed other functions into functions e.g &round{"&random{"${maxval}"}"} would return a rounded integer rather than a double/float based on the value of the ${maxval} variable.

It is always a good idea to place quotes around any parameters within the function unless it is a numeric function that only accepts whole numbers, doing this helps to ensure the parser can recognise the start and end of the data.

Anybody can create their own Presence Functions, for more information see Function Call.

Index of Functions

This list aims to be a comprehensive list of default functions available with Presence. Please note that it is always a work in progress.

Boolean Functions

Equals String

Format: &equalsString{Paramter,Parameter}

This function compares String1 and String2. If they are equal it will return the value "true". Otherwise it will return "false".

&equalsString{"ABC","ABC"}
Returns true
&equalsString{"ABC","BC"}
Returns false
If Boolean Test

Format: &if{Boolean Param To Test, True Result, False Result}

This function performs a test on a string. If it equals "true" or "1" the value of Parameter 2 will be returned. Otherwise, value of Parameter 3 will be returned.

&if{"true", "I AM TRUE", "I AM FALSE"}
Returns "I AM TRUE"
&if{"0", "I AM TRUE", "I AM FALSE"}
Returns "I AM FALSE"

Data Functions

On Demand Task Call

Format: &onDemand{taskAlias, parameter+,parameter+,param...}

Calls an On Demand Task that is on the Live Task Queue.

taskAlias: The alias of the Task to be called, the task should be on the Live Tasks Queue #On Demand Processes

parameter+ : The Parameters to be passed (zero or more).

&onDemand{"myTask","id=5", "now=true"}

Calls the Task referenced by the alias "myTask" and sets the following variables in the target task:

${id} = 5 ${now} = true

If the task returns a magic ${response} variable that value will be populated in the variable or space you are calling the function from.

Does Column Exist On Data Table

Format: &doesColumnExist{"COL_NAME"}

Tests to see if the specified column name exists in the current Data table - returns "true" if it does or "false" if not.

Parameter 1: The column name to test

Date Functions

All date functions use format patterns defined below, these date/time format patterns are based on Java Simple Date Format, for more information see http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

Date and Time Patterns

G Era designator e.g. "AD"

y Year e.g. yyyy="2015"; yy="15"

M Month in year e.g. M="8" (August); MM="08"; MMM="Aug" MMMM="August"

w Week in year e.g. w="33" (13/August/2015)

W Week in month e.g. W="2" (13/August/2015)

D Day in year e.g. D="225" (13/August/2015)

d Day in month e.g d="13" (13/August/2015)

F Day of week in month

E Day in week e.g. E="Thu"

a Am/pm marker

H Hour in day (0-23)

h Hour in day (1-12)

m Minute in hour

s Second in minute

S Millisecond

z Time zone e.g. z="BST"; zzzz="British Summer Time"

Z Time zone (RFC 822 time zone) e.g Z="+0100"

X Time zone (ISO 8601 time zone) e.g X="+01"; XX="+0100"; XXX="+01:00"

Get Current Date

Format: &currentDate{format, offset}

Returns: the current date in the format specified by the first parameter.

format=The date format to use to format the current date (e.g. "dd/MM/yyyy"). See #Date and Time Patterns

offset=(Optional) The offset in days (e.g. -1, 1, 2, -5)

&currentDate{"MMM/yyyy"}
Returns Aug/2015
&currentDate{"dd/MM/yyyy"}
Returns 13/08/2015 or whatever the current date is.
&currentDate{"dd/MM/yyyy",-5}
Returns 08/08/2015 (minus 5 days from the current date)
&currentDate{"dd/MM/yyyy",-3M}
Returns 13/05/2015 (minus 3 months from the current date)
&currentDate{"dd/MM/YYYY",5}
Returns 18/08/2015 (plus 5 days from the current date)
Format Date

Format: &formatDate{DATE_VALUE, input_format, output_format}

Returns: a new format for a date passed into the function on parameter 1

&formatDate{"2015-08-13","yyyy-MM-dd","dd/MM/yyyy"}
Returns 13/08/2015
&formatDate{"2015-08-13","yyyy-MM-dd","E dd MMM YYYY"}
Returns Thu 13 Aug 2015
&formatDate{"2015-08-13","yyyy-MM-dd","dd/MM/yyyy",5}
Returns 13/08/2015 (adds 5 days to the date on parameter 1)
&formatDate{"2015-08-13","yyyy-MM-dd","EEEE dd MMM YYYY"}
Returns Thursday 13 Aug 2015
Adjust Time Zone

Format: &adjustTimeZone{Date_in_originating_timezone,Format_of_date_in_param_1, Originating_timezone, Resulting_timezone, Resulting_date_format (OPTIONAL)}

This function adjusts a given date from the source timezone to another timezone. For example, an event happens in San Fransisco at 03:00 AM but the time needs to be displayed in London, which would be 11:00 AM.

&adjustTimeZone{"2013-08-02 03:00", "yyyy-MM-dd HH:mm", "US/Pacific", "Europe/London"}
Returns 2013-08-02 11:00

There is an optional 5th parameter which is the format to be used when creating the string that is returned. If it is omitted then the format specified in the 2nd parameter is used.

Calculate Date Ignoring Weekends

Format :&calcDateIgnoreWeekends{DATE, FORMAT, TIMEADJUST, IGNOREWEEKENDS}

Using the start date DATE, formatted according to rules specified in FORMAT, add the number of days* specified in TIMEADJUST. IGNOREWEEKENDS should be set to "true" if weekends are ignored - in which case, if weekend days are encountered while adding minutes, skip to Monday.

Therefore if IGNOREWEEKENDS = true: Wednesday 22nd June 2011 @ 12:00 + 5 days = Wednesday 29th June 2011 @ 12:00

TIMEADJUST defaults to days, however other time periods can be specified by appending a letter, e.g.:

5000S = 5000 milliseconds

60s = 60 seconds

60m = 60 minutes

24H = 24 hours

1M = 1 month

1y = 1 year

Note that for months and years the IGNOREWEEKENDS attribute will be discarded - weekends will never be taken into account.

Calculate Runtime Basic

Format: &calcNextRuntimeFromBasic{Run_on_First_of_Month, Run_on_Last_of_Month, Run_On_Date, Run_Time(HH:mm)}

Gets Next Runtime From Date in milliseconds, only valid in a running task - can't be tested

The parameters for this are retrieved from the top info of the schedule info page. ie, Run on First of Month string (true/false) Run on Last of Month string (true/false) Run On Date string (1-31) Run Time (HH:MM) string

&calcNextRuntimeFromBasic{"true", "false", "0", "09:00"}
Returns 1441094400000
Calulate Runtime From Day

Format: &calcNextRuntimeFromDay{Run_on_First_of_Month, Run_on_Last_of_Month, Run_On_Date, Run_Time(HH:mm)}

Get Next Runtime From Day(s)

The parameters for this are retrieved from the bottom of the schedule info page.

This uses the context, so the data table should contain the following:-

Integer "DAYOFWEEK" 1-Sunday 2=Monday etc Integer "FREQUENCY" 0=Every, 1=First, 2=Last Integer "INTERVALMINUTES" eg 30 String "STARTTIME" eg 09:00 String "ENDTIME" eg 13:00

Calculate Timezone Difference Hours

Format: &calcTimezoneDifferenceHours{TIMEZONE}

Calculates the time difference between the system timezone and the specified timezone, returns difference in hours.

Example, if system running in GMT:

&calcTimezoneDifferenceHours{"EST"}

Will return -5 (ie GMT-5).

Current Time

Format: &currentTime{TIMEFORMAT}

Returns: the current time in the format specified by the first parameter, offset by the number of minutes in the second parameter (default is zero).

Parameter 1: The time format to use to format the current time (eg "HH:mm:ss" for 24 hour, "h:mm:ss a" for 12 hour + am/pm). Parameter 2: (Optional) The offset in minutes.

Examples assume current time is 15:30:00 PM

&currentTime{"HH:mm:ss"}
Returns (eg) "15:30:00"
&currentTime{"HH:mm", -60}
Returns "14:30" (60 minutes in the past)
&currentTime{"h.mm a", 30}
Returns "4.00 PM" (half an hour in the future)
Current Time Stamp

Format: &currentTimeStamp{"OPTIONAL"}

Returns: the current time in milliseconds, offset by the number of minutes in the parameter (default is zero).

Date In Milliseconds

Format: &dateInMillis{DATE,FORMAT}

Converts a given date into milliseconds from the 1970s epoch.

&dateInMillis{"01/01/2001", "dd/MM/yyyy"}
Returns 978307200000
Format Milliseconds

Format: &formatMilliseconds{MILLISECONDS,FORMAT}

Returns a millisecond date in a readable format specified.

&formatMilliseconds{"978307200000", "dd/MM/yyyy"}
Returns 01/01/2001
&formatMilliseconds{"0", "dd MMM yyyy"}
Returns the epoch date "01 Jan 1970"
Format TF400 Date

Format: &formatTF400Date{DATE, RETURN_FORMAT}

Formats a TF400 date numeric in the format specified.

TF400 dates are a LONG type in the following format:

HHmmssyyyyMMdd

They may be 13 or 14 digits depending on whether the hour part is before 12 PM.

This function prepends a trailing zero if necessary and returns the date as a String in the format specified.

&formatTF400Date{"9342220130325", "dd MMM yyyy 'at' HH:mm:ss"}
Returns 25 Mar 2013 at 09:34:22
Milliseconds To Date

Format: &millisToDate{MILLISECONDS,DATE FORMAT}

Coverts the milliseconds parameter to a formatted date string, same as #Format Milliseconds, retained for backwards compatibility

&millisToDate{"978307200000", "yyyy-MM-dd'T'HH:mm:ss.SSSZ"}
Returns 2001-01-01T00:00:00.000+0000
Parse Seven Digit Date

Format: &parseSevenDigitDate{DATE,NEW FORMAT}

Attempts to parse the seven digit date set in parameter 1. If this is successful, the function will then reformat the date in the date specified by parameter 2.

- Parameter 1: The seven-digit date to parse (eg "1032403") - Parameter 2: The Java date format to use for formatting. Eg "dd-MM-yyyy".

&parseSevenDigitDate{"1150101", "dd-MM-yyyy"}
Returns 01-01-2015
Seven Digit Date

Format: &sevenDigitFormat{DATE,FORMAT OF DATE}

Creates a seven digit string representation of the specified date, where the first character represents the century, ie 0 for years ending in 47-99 and 1 for years ending in 00-46.

Complete format is CYYMMDD.

Parameter 1: The date string to be parsed and reformatted Parameter 2: The date format to use in parsing the input date.

 &sevenDigitFormat{"23 Mar 2003", "dd MMM yyyy"}
Returns "1030323"
Validate Date

Format: &validatedate{DATE,FORMAT OF DATE, CHECK FUTURE} Pass it a date string and a date format.

Returns 1 if valid, else 0.

Can also pass it a true to check that the date is not in the future.

Excel Functions

Update Excel Cell

Format: &updateXLCell{PATH,SHEET INDEX,ROW,CELL,VALUE}

Updates a specified cell in an Excel worksheet.

Parameters:

1: Path of Excel file 2: Sheet index (zero based) 3: Row number (zero based) 4: Cell number (zero based) 5: New value

Returns the old value.

File Operations

Add files To Zip

Format: &addfilesToZip{DIR,ZIP FILE}

Creates a zip archive.

Argument #1: The directory containing files to be added to the archive Argument #2: The target zip file name.

Files are added recursively, ie subdirectory contents are also added. If the target zip file already exists it will be renamed to [old_file_name].yyyymmdd

Extract Text from PDF File

Format: &extractTextFromPdf{FILE}

Extracts text from a searchable PDF file. Some PDF files may not actually contain text even though it looks that way, instead you may get an embedded scanned image and this function will not be able to read a scanned image as text.

Useage: &extractTextFromPdf {"FILE_LOCATION"}

Does File Exist

Format: &fileExists{FILE LOCATION}

Tests whether the specified file exists. If the file exists the function returns "TRUE", otherwise returns "FALSE".

File Length

Format: &fileLength{"FILE_LOCATION"}

Returns the length of the specified file, or -1 if it doesn't exist or if the path specified is a folder.

Get File Value

Format: &getFileValue{FILE,KEY}

Gets a value from a INI or Properties type file.

Returns a String for the Key value specified in Parmeter2

Example: &getFileValue{"c:\myfile.ini","MYKEY"}

See also : #Set File Value

Lookup MIME Type By Extension

Format: &lookupMimeByExtention{"FILENAME_OR_EXTENSION"}

Attempts to retrieve the MIME type for the file name specifies. Uses the Java MimetypesFileTypeMap so is incomplete.

&lookupMimeByExtension{".pdf"}
Returns application/octet-stream
Measure Image

Format: &measureImage{IMAGE_FILE}

Measures the width and height of image file specified in arg 1.

Returns a string of the format:

width=n,height=n

Set File Value

Format: &setFileValue{FILE,KEY,VALUE}

Sets a value in a INI or Properties type file.

Returns success string

Example: &setFileValue{"c:\myfile.ini","MYKEY", "MYVALUE"}

See also : #Get File Value

Touch File

Format: &touchFile{FILE}

Sets the last modified date of the file in parameter 1 to be the current system time.

Unzip File

Format: &unzip{ZIP,TO FOLDER}

Unzips the archive specified in argument #1 into the directory specified in argument #2.

Example: unzip{"/archive.zip", "/extracted/"}

Extracts the archive "/archive.zip" into the directory "/extracted". If the directory does not already exist it will be created at runtime.

HTML Utitlity Functions

HTML Encode

Format: &htmlEncode{HTML STRING}

Encodes a string of HTML, replacing any non-alphanumerics with their entity reference equivalent.

&htmlEncode{"I was wondering & found a £1 coin!"}
Returns
I was wondering &-a-m-p-; found a &-p-o-u-n-d-;1 coin&-#-3-3-; *Dashes inserted to explain, actual function does not insert dashes
URL Decode

Format: &urlDecode{URLEncodedText}

Utility function for HTML form decoding. Decodes a String from the application/x-www-form-urlencoded MIME format.

To conversion process is the reverse of that used by the urlEncode{} function. It is assumed that all characters in the encoded string are one of the following: "a" through "z", "A" through "Z", "0" through "9", and "-", "_", ".", and "*". The character "%" is allowed but is interpreted as the start of a special escaped sequence.

URL Encode

Format: &urlEncode{STING_TO_ENCODE}

Utility function for HTML form encoding. Converts a String to the application/x-www-form-urlencoded MIME format.

When encoding a String, the following rules apply:

The alphanumeric characters "a" through "z", "A" through "Z" and "0" through "9" remain the same.

The special characters ".", "-", "*", and "_" remain the same.

The space character " " is converted into a plus sign "+".

All other characters are unsafe and are first converted into one or more bytes using some encoding scheme. Then each byte is represented by the 3-character string "%xy", where xy is the two-digit hexadecimal representation of the byte.

The recommended encoding scheme to use is UTF-8. However, for compatibility reasons, if an encoding is not specified, then the default encoding of the platform is used.

JSON Functions

The following functions do basic operations on JSON formats, to parse a JSON format into a data table use the JSON Node to create JSON formats then you would use the Custom Data Formatter Standard Option.

JSON To XML

Format: &JSONToXML{JSON_STRING}

Converts a JSON format document into XML. Place the JSON string into a variable first, this will place it into an effective CDATA section Create a Varible called ${jsondata} and populated the JSON data into it.

e.g. ${jsondata} would contain
{"menu": {
  "id": "file",
  "value": "File",
  "popup": {
    "menuitem": [
      {"value": "New", "onclick": "CreateNewDoc()"},
      {"value": "Open", "onclick": "OpenDoc()"},
      {"value": "Close", "onclick": "CloseDoc()"}
    ]
  }
}}

So you then call the function:

&JSONToXML{"${jsondata}"}
Returns
<menu><id>file</id><popup><menuitem><value>New</value><onclick>CreateNewDoc()</onclick></menuitem><menuitem><value>Open</value><onclick>OpenDoc()</onclick></menuitem>

<menuitem><value>Close</value><onclick>CloseDoc()</onclick></menuitem></popup><value>File</value></menu>

XML To JSON

Format: &XMLToJSON{XML_STRING}

Converts an XML document into JSON format.

Parameter 1: XML document

&xmlToJSON{"<menu><id>file</id><popup><menuitem><value>New</value><onclick>CreateNewDoc()</onclick></menuitem><menuitem><value>Open</value><onclick>OpenDoc()</onclick></menuitem>
<menuitem><value>Close</value><onclick>CloseDoc()</onclick></menuitem></popup><value>File</value></menu>"}
Returns
{"menu": {
"id": "file",
"popup": {"menuitem": [
 {
  "value": "New",
  "onclick": "CreateNewDoc()"
 },
 {
  "value": "Open",
  "onclick": "OpenDoc()"
 },
 {
  "value": "Close",
  "onclick": "CloseDoc()"
 }
]},
"value": "File"
}}

Miscellaneous Functions

Inspect Context

Format: &inspectContext{CONTEXT_VALUE}

Inspects the current Presence Context and returns the value of the property specified in the first parameter. The property can be a dot separated list of objects and properties, for example, some common usages may be:

data.empty - returns true if the data table is empty, or false otherwise

data.rowCount - returns the number of rows in the current data table

taskMode - returns the current mode of the task as a number (see Presence Context)

container.topLeveltask.taskName - the name of the currently running (top level) task

container.nestedTask.taskName - the name of the currently running (nested) task

If an asterisk is specified instead of a property name, all of the available properties will be returned as a comma-separated list. For example:

&inspectContext{"data.*"}
Returns all available properties for the context data table
empty,rows,rowCount,columnNames,firstRow,class,
&inspectContext{"*"}
Returns all available properties for the context (includes data and container).
userContext,timeZone,data,taskMode,container,executionPath,localVariables,currentRunner,universalVariables,replaceNullColumns,
replaceNonNullColumns,globalVariablePassword,currentTaskElement,threadNumber,variables,class,
Is Null

Format: &isNull{TEST_VALUE, RETURN_VAL_IF_TRUE}

Tests if first parameter is null (empty) and returns second parameter if it is. Otherwise returns first parameter.

&isNull{"", "it was null"}
Returns "it was null"
&isNull{"i'm here!", "it was null"}
Returns "i'm here!".

Numeric Functions

Byte String

Format: &byteString{BYTE}

This converts Presence's internal byte storage mechanism into the correct format for external applications. Specifically, 128 is subtracted from the value of each byte. Function cannot be tested, will only work during runtime

Divide

Format: &divide{VAL1,VAL2}

Divides 1st parameter by 2nd parameter and returns the result.

&divide{10,5}
Returns 2.
Eval

Format: &eval{EXPRESSION}

Evaluates the expression in argument 1 and returns the logical result.

&eval{"10*(2+5)"}
Returns 70
&eval{"5+(3*3)"}
Returns 45
&eval{"6/2"}
Returns 3

eval also supports the following constants and functions

  • cos
  • sin
  • ceil
  • floor
  • PI
  • E
  • sqrt
Hex Value

Format: &hexVal{NUMBER}

Returns the hexidecimal value of the number passed in parameter 1.

&hexVal(255)
Returns FF
&multiply{VAL+}

Multiplies all parameters and returns the result.

&multiply{1,5,8}
Returns 40
&percent{PERCENTAGE,VALUE}

Returns the first argument expressed as a percentage of the second.

&percent{10,20}
Returns 50
&random{MAX}

Returns a random number between zero and the argument specified

&random{50}
Could Return 49.21655577700601
&round{NUMBER}

Round the parameter to the nearest whole number. See java.lang.Math.round(double) for contract.

Returns an integer representing the rounded value.

&round{5.791}
Returns 6
&subtract{VAL1,VAL2}

Subtracts argument 2 from argument 1 and returns the result.

&subtract{30,5}
Returns 25
&sum{VAL+}

Adds all the parameters and returns the result.

&sum{1,5,8,9,1225,1551,998,1005}
Returns 4802

Presence Internal Functions

&currentTaskName{}

Returns the current task name. No parameters required.

Print Functions

&pdfprintfunction{PDF FILE, PRINTER UNC, COPIES, FROM PAGE, TO PAGE, THROW ERROR, DUPLEX, SHORT EDGE BINDING}

Returns either Printed,Failed to print or throws an error

Parameters:-

1:PDF File

2:Printer UNC

3:Copies

4:Page-From:- 1 = first page

5:Page-To:- -1 = all

6:Throw Errors:-'True'=On failure, errors will be thrown back to the task 'False'=On failure the result will be 'Failed', but the task will continue

7:Duplex printing 'True' or 'False' (optional,default is false)

8:Short Edge Binding 'True' or 'False' (optional,default is false) applies with duplex printing

Security Functions

&ValidateWindowsUserAndPassword{DOMAIN/USER, PASSWORD, AD SERVER PORT, CLASS FACTORY}

Validates windows user and password details are valid using Windows Acitve Directory and Fast Binding.

returns string 'true' or 'false', throws an error on failure.

Parameters:-

1:Username domain\User 2:Password 3:LDAP url 4:Factory class

&ValidateWindowsUserAndPassword{"mydomain\robert", "password", "ldap://adserver:389", "com.sun.jndi.ldap.LdapCtxFactory"}
Returns false as this is not the correct password.
&createSHAHash{VALUE,ITERATIONS}

A secure one-way hash function that converts the input value into a fixed length hash value, using an SHA (secure hash algorithm) digest.

The original input value can never be retrieved from the hash value. This is useful for storing passwords etc, where the original value never needs to be known but the hashed value can be compared for correctness.

Parameter 1: Input value Parameter 2: Number of iterations to use (optional, default 1)

&createSHAHash{"Input Value"}
Returns a4c9cbd6e25fd7ae420dbe02ecf40785fb89099c
&createSHAHash{"Input Value",3}
Returns a9676f44e0ae8b65c393a1463e97d20552b93d33
&decrypt{ENCRYPTED TEXT, KEY(optional)}

Decrypts the encrypted value specified to provide the original text value. Uses the Triple DES algorithm and a key that is unique to your Presence installation.

Parameter 1: An encrypted value Parameter 2 (optional): Encryption key Result: A decrypted value

&encrypt{TEXT TO ENCRYPT, KEY(optional)}

Encrypts the specified value using a triple DES cipher algorithm. The key used is unique to each Presence installation. The resulting value can be decrypted using the decrypt{String} function.

Parameter 1: The string value to be encrypted. Result: An encrypted string, which can only be decrypted on the same Presence installation.

Parameter 2 (optional): A string to use as an encryption key.

String Functions