biz.neustar.wpm.api
Interface Utils


public interface Utils

A set of general purpose utilities to assist with scripting.

This object is available as the variable utils from within the a JavaScript-enabled script.

In the following example, the utils API are used to send a zipped XML over HTTP PUT:

    var c = test.openHttpClient();

    test.beginTransaction();
    test.beginStep("Send zipped XML over HTTP PUT");

    var file = test.getFile("test.xml");
    var contents = file.readContents();
    // ... do something on the 'contents' string here ...

    // Now, zip the string
    var zippedContents = utils.gzip(contents);
    var base64Md5ZippedContents = zippedContents.md5(true).base64();

    // Prepare for HTTP PUT call
    var put = c.newPut("https://example.com/rest/api/endpoint");
    put.addRequestHeader("Authorization", "***********");
    put.addRequestHeader("Content-Encoding", "gzip");
    put.addRequestHeader("Content-MD5", base64Md5ZippedContents);
    put.addRequestHeader("Content-Type", "application/xml");
    put.addRequestHeader("X-MQ-Transaction-ID", "");
    put.addRequestHeader("X-MQ-Delivery-Attempt", "1");
    put.addRequestHeader("X-MQ-Queue-Duration", "1");
    put.addRequestHeader("X-MQ-Tag-Time-Produced", "2012-04-28T05:02:00Z");
    put.setRequestBody(zippedContents);

    // Execute the PUT
    var resp = put.execute();

    // Log the Response
    test.log(resp.getBody());
    test.log(resp.getInfo().getStatusCode());

    test.endStep();
    test.endTransaction();
 


Method Summary
 java.util.Date addDays(java.util.Date date, int days)
          Add the given number of days to the given date
 java.util.Date addMonths(java.util.Date date, int months)
          Add the given number of months to the given date
 java.util.Date addTime(java.util.Date date, int hours, int minutes, int seconds)
          Add time to the given date.
 java.lang.String base64(java.lang.Object obj)
          Returns a base64 string representation of the given object.
 java.lang.String decrypt(java.lang.String cipherText)
          Returns decrypted value of cipherText.
 Bytes deflate(java.lang.Object obj)
          Compress the provided content using Deflate and return a byte array.
 java.lang.String encrypt(java.lang.String text)
          Returns encrypted value of text which can be used by the decrypt function.
 java.lang.String formatDate(java.lang.String format, java.util.Date date)
          Format a date as a string.
 java.lang.String formatDate(java.lang.String format, java.util.Date date, java.lang.String language)
          Format a date as a string using the given language.
 Bytes fromHex(java.lang.String hex)
          Decoded a string of hex values into a raw byte array.
 java.lang.String getBaseUrl(java.lang.String url)
          Get the base url for the given url.
 java.lang.String getTimeZone()
          Return the current timezone.
 long getTimezoneOffset(java.lang.String timezone, java.util.Date date)
          Get the timezone offset for the given timezone from the current timezone.
 long getTimezoneOffsetUTC(java.lang.String timezone, java.util.Date date)
          Get the timezone offset for the given timezone.
 java.lang.String getUUID()
          Returns a randomly generated 128 bit, 32 byte UUID in the form 067e6162-3b6f-4ae2-a171-2470b63dff00.
 Bytes gzip(java.lang.Object obj)
          Compress the provided content using Gzip and return a byte array.
 java.lang.String md5(java.lang.Object obj)
          Returns a string representing the hex values of the MD5 for the given object.
 java.lang.Object md5(java.lang.Object obj, boolean binary)
          Returns either a hex string or a set of Bytes representing the MD5 for the given object.
 java.lang.String resolveUrl(java.lang.String baseUrl, java.lang.String path)
          Combine the given Url and path into one Url.
 java.lang.String sha1(java.lang.String text)
          Returns a sha1 string representation of given string.
 java.lang.String sha256(java.lang.String text)
          Returns a sha256 string representation of given string.
 Bytes sha256WithRSA(NativeObject object, java.lang.String content)
          Creates and returns a sha256WithRSA signed signature.
 java.lang.String toHex(Bytes val)
          Returns data hex string of the binary byte values.
 java.lang.String toHex(java.lang.String val)
          Returns data hex string of the binary byte values.
 java.lang.String xmlToJson(java.lang.String xml)
          Convert XML to JSON.
 Bytes zlib(java.lang.Object obj)
          Compress the provided content using zlib and return a byte array.
 

Method Detail

gzip

Bytes gzip(java.lang.Object obj)
Compress the provided content using Gzip and return a byte array. The byte array can then be converted to an MD5 hash md5(Object), base64 encoded base64(Object) or used as the body of an HTTP request HttpRequest.setRequestBody(Object).

Parameters:
obj - the content to be zipped, such as a string or a DataFile.
Returns:
a simple object representing a chunk of bytes

zlib

Bytes zlib(java.lang.Object obj)
Compress the provided content using zlib and return a byte array. The byte array can then be converted to an MD5 hash md5(Object), base64 encoded base64(Object) or used as the body of an HTTP request HttpRequest.setRequestBody(Object).

Parameters:
obj - the content to be zipped, such as a string or a DataFile.
Returns:
a simple object representing a chunk of bytes

deflate

Bytes deflate(java.lang.Object obj)
Compress the provided content using Deflate and return a byte array. The byte array can then be converted to an MD5 hash md5(Object), base64 encoded base64(Object) or used as the body of an HTTP request HttpRequest.setRequestBody(Object).

Parameters:
obj - the content to be zipped, such as a string or a DataFile.
Returns:
a simple object representing a chunk of bytes

md5

java.lang.String md5(java.lang.Object obj)
Returns a string representing the hex values of the MD5 for the given object. The object may be a string, a DataFile, or a set of Bytes. This is the same as calling md5(Object, boolean) with false as the second argument.

Parameters:
obj - the content to have its MD5 calculated from
Returns:
a string containing hex characters

md5

java.lang.Object md5(java.lang.Object obj,
                     boolean binary)
Returns either a hex string or a set of Bytes representing the MD5 for the given object. The object may be a string, a DataFile, or a set of Bytes. The binary parameter decides whether raw bytes (16 bytes) should be returned or a hex string should be returned.

Parameters:
obj - the content to have its MD5 calculated from
binary - true if the MD5 should be returned in raw byte form, false if it should be in a hex string
Returns:
the MD5 result (string or bytes)

base64

java.lang.String base64(java.lang.Object obj)
Returns a base64 string representation of the given object. The object may be a string, a DataFile, or a set of Bytes.

Parameters:
obj - the content to have its base64 calculated
Returns:
the string representing the base64 encoding

sha1

java.lang.String sha1(java.lang.String text)
Returns a sha1 string representation of given string.

Parameters:
text - the string to have its sha1 calculated
Returns:
the sha1 result

sha256

java.lang.String sha256(java.lang.String text)
Returns a sha256 string representation of given string.

Parameters:
text - the string to have its sha256 calculated
Returns:
the sha256 result

getUUID

java.lang.String getUUID()
Returns a randomly generated 128 bit, 32 byte UUID in the form 067e6162-3b6f-4ae2-a171-2470b63dff00. The UUID is generated using a cryptographically strong pseudo random number generator.

Returns:
the unique uuid string

xmlToJson

java.lang.String xmlToJson(java.lang.String xml)
                           throws java.lang.RuntimeException
Convert XML to JSON. If the XML is valid, the data are "restructured" into JSON format; otherwise, it throws an exception.

Parameters:
xml - the XML string
Returns:
A conversion of XML to JSON (as string)
Throws:
java.lang.RuntimeException - If the given XML is malformed or can't be converted to JSON

encrypt

java.lang.String encrypt(java.lang.String text)
Returns encrypted value of text which can be used by the decrypt function.
Note: using this method in local validator requires "accountid" command line argument.

Parameters:
text - value to encrypt
Returns:
encrypted value

decrypt

java.lang.String decrypt(java.lang.String cipherText)
Returns decrypted value of cipherText.
Note: using this method in local validator requires "accountid" command line argument.

Parameters:
cipherText - hex string of encrypted value
Returns:
decrypted value

toHex

java.lang.String toHex(Bytes val)
Returns data hex string of the binary byte values.

Parameters:
val - the binary bytes Bytes
Returns:
hex string of the binary byte values

toHex

java.lang.String toHex(java.lang.String val)
Returns data hex string of the binary byte values.

Parameters:
val - the binary byte values.
Returns:
hex string of the binary byte values

fromHex

Bytes fromHex(java.lang.String hex)
Decoded a string of hex values into a raw byte array.

Parameters:
hex - the string of hex values
Returns:
bytes decoded from the hex string

resolveUrl

java.lang.String resolveUrl(java.lang.String baseUrl,
                            java.lang.String path)
Combine the given Url and path into one Url.

If path is a full Url, then path is returned without any modification.

Examples:

 utils.resolveUrl("http://www.foo.com", "/"); -> "http://www.foo.com/"
 utils.resolveUrl("http://www.foo.com", "/bar"); -> "http://www.foo.com/bar"
 utils.resolveUrl("http://www.foo.com", "bar"); -> "http://www.foo.com/bar"
 utils.resolveUrl("http://www.foo.com/foobar", "bar"); -> "http://www.foo.com/bar"
 utils.resolveUrl("http://www.foo.com/foobar/", "bar"); -> "http://www.foo.com/foobar/bar"
 utils.resolveUrl("http://www.foo.com/foobar/", "/bar"); -> "http://www.foo.com/bar"
 utils.resolveUrl("http://www.foo.com/foobar/bla?", "bar"); -> "http://www.foo.com/foobar/bar"
 utils.resolveUrl("http://www.foo.com/bar", "http://www.bar.com/foo"); -> "http://www.bar.com/foo"
 

Parameters:
baseUrl - the base url
path - the path for the base url
Returns:
the combined base url with the path

getBaseUrl

java.lang.String getBaseUrl(java.lang.String url)
Get the base url for the given url. Examples:
 utils.getBaseUrl("http://www.foo.com"); -> "http://www.foo.com"
 utils.getBaseUrl("http://www.foo.com/bar"); -> "http://www.foo.com/"
 utils.getBaseUrl("http://www.foo.com/bar/"); -> "http://www.foo.com/bar/"
 utils.getBaseUrl("http://www.foo.com/bar/foo"); -> "http://www.foo.com/bar/"
 utils.getBaseUrl("http://www.foo.com/bar/foo?bar"); -> "http://www.foo.com/bar/"
 

Parameters:
url - the url
Returns:
the base url of the given url

formatDate

java.lang.String formatDate(java.lang.String format,
                            java.util.Date date)
Format a date as a string. NOTE: Most of our agents are set to UTC time and not the timezone the agent is in.

Date and Time Patterns

Date and time formats are specified by date and time pattern strings. Within date and time pattern strings, unquoted letters from 'A' to 'Z' and from 'a' to 'z' are interpreted as pattern letters representing the components of a date or time string. Text can be quoted using single quotes (') to avoid interpretation. "''" represents a single quote. All other characters are not interpreted; they're simply copied into the output string during formatting or matched against the input string during parsing.

The following pattern letters are defined (all other characters from 'A' to 'Z' and from 'a' to 'z' are reserved):

Letter Date or Time Component Presentation Examples
G Era designator Text AD
y Year Year 1996; 96
Y Week year Year 2009; 09
M Month in year Month July; Jul; 07
w Week in year Number 27
W Week in month Number 2
D Day in year Number 189
d Day in month Number 10
F Day of week in month Number 2
E Day name in week Text Tuesday; Tue
u Day number of week (1 = Monday, ..., 7 = Sunday) Number 1
a Am/pm marker Text PM
H Hour in day (0-23) Number 0
k Hour in day (1-24) Number 24
K Hour in am/pm (0-11) Number 0
h Hour in am/pm (1-12) Number 12
m Minute in hour Number 30
s Second in minute Number 55
S Millisecond Number 978
z Time zone General time zone Pacific Standard Time; PST; GMT-08:00
Z Time zone RFC 822 time zone -0800
X Time zone ISO 8601 time zone -08; -0800; -08:00
Pattern letters are usually repeated, as their number determines the exact presentation:

Examples

The following examples show how date and time patterns. The given date and time are 2001-07-04 12:08:56 local time in the U.S. Pacific Time time zone.
Date and Time Pattern Result
"yyyy/MM/dd" 2001/07/04
"yyyy-MM-dd" 2001-07-04
"h:mm a" 12:08 PM
"EEE, MMM d, ''yy" Wed, Jul 4, '01
"EEEE, MMMM d" Wednesday, July 4
"yyyy.MM.dd G 'at' HH:mm:ss z" 2001.07.04 AD at 12:08:56 PDT
"EEE, d MMM yyyy HH:mm:ss Z" Wed, 4 Jul 2001 12:08:56 -0700
"yyyy-MM-dd'T'HH:mm:ss.SSSZ" 2001-07-04T12:08:56.235-0700
   date = new Date("2014/06/23");
   var s = utils.formatDate("yyyy-MM-dd", date);
   test.assertEquals("2014-06-23", s);
 

Parameters:
format - the target format for the date string
date - the date
Returns:
string representation of the date

formatDate

java.lang.String formatDate(java.lang.String format,
                            java.util.Date date,
                            java.lang.String language)
Format a date as a string using the given language.
   date = new Date("2014/06/23");
   s = utils.formatDate("MMMM", date, "en");
   test.assertEquals("June", s);
   s = utils.formatDate("MMMM", date, "es");
   test.assertEquals("junio", s);
   s = utils.formatDate("MMMM", date, "fr");
   test.assertEquals("juin", s);
   s = utils.formatDate("MMMM", date, "it");
   test.assertEquals("giugno", s);
 

Parameters:
format - See formatDate(java.lang.String, java.util.Date) for details.
date - the date
language - The language/locale to to use for text presentation. It's an ISO 639 alpha-2 or alpha-3 language code, or a language subtag up to 8 characters in length. Country code and language variant can be specified using underscores. E.g. "zh_TW" v.s. "zh_CN".
Returns:
string representation of the date

addDays

java.util.Date addDays(java.util.Date date,
                       int days)
Add the given number of days to the given date
   date = new Date("2014/06/23");
   var t = utils.formatDate("yy/MM/dd", utils.addDays(date, 1));
   test.assertEquals("14/06/24", t);
   t = utils.formatDate("yy/MM/dd", utils.addDays(date, -1));
   test.assertEquals("14/06/22", t);
   t = utils.formatDate("yy/MM/dd", utils.addDays(date, 20));
   test.assertEquals("14/07/13", t);
 

Parameters:
date - the date object.
days - number of days to add to date object.
Returns:
the new date offset by the given number of days.

addMonths

java.util.Date addMonths(java.util.Date date,
                         int months)
Add the given number of months to the given date
   date = new Date("2014/06/23");
   var t = utils.formatDate("yy/MM/dd", utils.addMonths(date, 1));
   test.assertEquals("14/07/23", t);
   t = utils.formatDate("yy/MM/dd", utils.addMonths(date, -1));
   test.assertEquals("14/05/23", t);
 

Parameters:
date - the date object.
months - the number of months to add to date object.
Returns:
the new date offset by the given number of months

addTime

java.util.Date addTime(java.util.Date date,
                       int hours,
                       int minutes,
                       int seconds)
Add time to the given date.
   date = new Date("2014/06/23");
   var t = utils.formatDate("yy/MM/dd", utils.addTime(date, -1, 0, 0));
   test.assertEquals("14/06/22", t);
 

Parameters:
date - the date object
hours - the number of hours to add to date object
minutes - the number of minutes to add to date object
seconds - the number of seconds to add to daet object
Returns:
a new date object offset by the given hour, minutes and seconds

getTimezoneOffset

long getTimezoneOffset(java.lang.String timezone,
                       java.util.Date date)
Get the timezone offset for the given timezone from the current timezone.

The return value is milliseconds from the Unix Epoch.

   date = new Date();
   var offset = utils.getTimezoneOffset("US/Pacific", date);
   date = new Date(date.getTime() + offset);
 
Some example timezones:
     US/Pacific
     US/Mountain
     US/Eastern
     Europe/Berlin
     Europe/London
     Asia/Singapore
     Asia/Tokyo
     CTT
     PST
     IST
     GMT+8
 

Note CST is US Central Standard Time, CTT is China Standard Time.

Parameters:
timezone - the timezone
date - the date object
Returns:
long the timezone offset

getTimezoneOffsetUTC

long getTimezoneOffsetUTC(java.lang.String timezone,
                          java.util.Date date)
Get the timezone offset for the given timezone.

The return value is milliseconds from the Unix Epoch.

   date = new Date();
   var offset = utils.getTimezoneOffsetUTC("US/Pacific", date);
   date = new Date(date.getTime() + offset);
 
Some example timezones:
     US/Pacific
     US/Mountain
     US/Eastern
     Europe/Berlin
     Europe/London
     Asia/Singapore
     Asia/Tokyo
     CTT
     PST
     IST
     GMT+8
 

Note CST is US Central Standard Time, CTT is China Standard Time.

Parameters:
timezone - the timezone
date - the date object
Returns:
long the timezone offset in UTC

getTimeZone

java.lang.String getTimeZone()
Return the current timezone.

Most of our agents are set to GMT. When running a script in Local Validator or via Private Agent the timezone may not be GMT.

Returns:
the time zone

sha256WithRSA

Bytes sha256WithRSA(NativeObject object,
                    java.lang.String content)
Creates and returns a sha256WithRSA signed signature. The result returned is a Bytes object. The object must be like one of the following:
     sha256WithRSA({"pem": test.getFile("secret.pem")}, "myData")
     sha256WithRSA({"pem": pemString}, "myData")
     sha256WithRSA({"p12": test.getFile("secret.p12"), "alias": "privatekey", "password": "notasecret"}, "myData")
     sha256WithRSA({"p12": p12String, "alias": "privatekey", "password": "notasecret"}, "myData")
 

Parameters:
object - the javascript object with the necessary parameters for retrieving private key
content - the payload to sha256WithRSA sign
Returns:
the signature Bytes

© 2023 Vercara, LLC. All Rights Reserved.