scope

$$from

$$from : Array

Shortcut for the JLinq library for easy query and access to arrays/objects. To see all the available options please refer to http://hugoware.net/Projects/jlinq and the list of available functions by executing, in the openaf-console: "desc $$from([])".

$a2m

$a2m(aDef, aArray) : Array

Tries to convert aArray into a map using the aDef array of keys for the map keys' value assignment in the output map. Example:

$a2m(['a', 'b', 'c'], [1, 2, 3])    // { a: 1, b: 2, c: 3 }


$a4m

$a4m(anArray, aKey, dontRemove) : Array

Tries to create a map of maps from the provided anArrays. Optionally if aKey is provided it will be used to create the map keys (otherwise will fallback to "row[number]"). And can also optionally indicate by dontRemove = true that aKey shouldn't be removed from each map. 
var a = [
  { "abc": "123", "xpt": "000", "key": "A1" },
  { "abc": "456", "xpt": "001", "key": "A2" },
  { "abc": "789", "xpt": "002", "key": "A3" }
]

$a4m(a, "key");
// {
//   "A1": { "abc": "123", "xpt": "000" },
//   "A2": { "abc": "456", "xpt": "001" },
//   "A3": { "abc": "789", "xpt": "002" }
// }


$atomic

$atomic(aInitValue, aType) : Object

Creates an atomic object of aType (defaults to long) to be get/set atomically on a multithreading script initialized with aInitValue. aType can be "int", "long" and "boolean". Each with different methods:

   int.dec          - Decrement an integer
   int.inc          - Increment an integer
   int.get          - Get the current integer
   int.getSet(n)    - Get and Set the current integer
   int.getAdd(n)    - Get and Add to the current integer
   int.setIf(t, n)  - Set the current integer to n if current value is t
   int.set          - Set the current integer

   long.dec         - Decrement an long
   long.inc         - Increment an long
   long.get         - Get the current long
   long.getSet(n)   - Get and Set the current long
   long.getAdd(n)   - Get and Add to the current long
   long.setIf(t, n) - Set the current long to n if current value is t
   long.set         - Set the current long

   boolean.get         - Get the current boolean
   boolean.set         - Set the current boolean
   boolean.getSet      - Get and Set the current boolean
   boolean.setIf(t, n) - Set the current boolean to n if current value is t


$await

$await(aName) : Object

Wrapper around the Java wait/notify mechanism. For the provided name will returen an object with the following  functions wait (will block until a notify is invoked), notify (will notify and unblock one of the wait invocations),  notifyAll (will notify and unblock all wait invocations) and destroy existing references to aName.

$bottleneck.destroy

$bottleneck.destroy()

Destroys any existing bottleneck definition.

$bottleneck.exec

$bottleneck.exec(args) : Object

Creates a bottleneck aName to execute aFunction with the provided args. Returns what the function returns:

$bottleneck("myFunc", (a, b) => { ... return result; })
.maxExec(3)
.maxWait(5000)
.exec(2, 4);

$bottleneck("myFunc").exec(2, 2);


$bottleneck.maxExec

$bottleneck.maxExec(aMaxNumber) : Object

Creates a bottleneck to a maximum concurrent execution number of aMaxNumber.

$bottleneck.maxWait

$bottleneck.maxWait(aMs) : Object

Creates a bottleneck holding the function execution for a max period of aMs.

$cache.ch

$cache.ch(aChannelName) : Object

Uses a pre-existing channel (e.g. aChannelName) as the cache channel.

$cache.fn

$cache.fn(aFunction) : Object

Defines the aFunction use to get aKey. The returned object will be cached.

$cache.get

$cache.get(aKey) : Object

Shortcut to use a cache channel. Returns an object that can be used like this:

$cache("numbers")
.ttl(30000)
.fn((aKey) => { ... return result; })
.create()

$cache("numbers").get(myKey);

$cache("numbers").destroy();


$cache.inFile

$cache.inFile(aFile) : Object

Creates a mvs channel to hold the cache data in aFile. Note: don't use $cache.ch if you use this option.

$cache.maxSize

$cache.maxSize(aSize) : Object

Establishes the max number of entries cached at any given point in time.

$cache.ttl

$cache.ttl(aTTL) : Object

Defines the time-to-live (aTTL) to consider a cached result as valid.

$ch

$ch(aChannel)

Please check more details with the help from ow.ch. The available methods are:

Channel basics:

- create(shouldCompress, aType, options)
- list()
- destroy()
- size()
- subscribe(aFunction, onlyFromNow, anId)
- unsubscribe(aId)
- forEach(aFunction)
- getAll()
- getKeys(fullInfo)
- getSortedKeys(fullInfo)
- set(aKey, aValue, aForcedTimestamp)
- setAll(keysArray, valuesArray, aForcedTimestamp)
- get(aKey)
- getSet(aMatch, aKey, aValue, aForcedTimestamp)
- unset(aKey, aForcedTimestamp)
- push(aKey, aValue)
- pop(aKey)
- shift(aKey)
- stopJobs()
- waitForJobs(aTimeout)
- getName()

Channel basic persistence:

- storeAdd(aFilename, anArrayOfKeys, shouldCompress)
- storeRestore(aFilename, anArrayOfKeys)

Inter-channel HTTP REST:

- expose(aLocalPortOrServer, aPath, aAuthFunc, aUnAuthFunc)
- peer(aLocalPortOrServer, aPath, aRemoteURL, aAuthFunc, aUnAuthFunc)
- unpeer(aRemoteURL)
- createRemote(aURL, aTimeout)

$channels

$channels(aChannel)

Please check more details with the help from ow.ch. The available methods are:

Channel basics:

- create(shouldCompress, aType, options)
- list()
- destroy()
- size()
- subscribe(aFunction, onlyFromNow, anId)
- unsubscribe(aId)
- forEach(aFunction)
- getAll(fullInfo)
- getKeys(fullInfo)
- getSortedKeys(fullInfo)
- set(aKey, aValue, aForcedTimestamp)
- setAll(keysArray, valuesArray, aForcedTimestamp)
- unsetAll(keysArray, valuesArray, aForcedTimestamp)
- get(aKey)
- getSet(aMatch, aKey, aValue, aForcedTimestamp)
- unset(aKey, aForcedTimestamp)
- push(aKey, aValue)
- pop(aKey)
- shift(aKey)
- stopJobs()
- waitForJobs(aTimeout)
- getName()

Channel basic persistence:

- storeAdd(aFilename, anArrayOfKeys, shouldCompress, runSubscribersForAll)
- storeRestore(aFilename, anArrayOfKeys)

Inter-channel HTTP REST:

- expose(aLocalPortOrServer, aPath, aLogin, aPassword)
- peer(aLocalPortOrServer, aPath, aRemoteURL, aAuthFunc, aUnAuthFunc, aMaxTime, aMaxCount)
- unpeer(aRemoteURL)
- createRemote(aURL, aTimeout, aLogin, aPass)

$csv

$csv(aMap) : $csv

Provides a shortcut to access CSV functionality. Optionally you can provide options through aMap.

Examples:
  $csv().fromInArray(anArray)
  $csv().fromInFile("test.csv").toOutArray()
  $csv().fromInFile("test.csv").toOutFn(m => print( af.toSLON(m) ))
  $csv().fromInString( $csv().fromInArray( io.listFiles(".").files ) ).toOutArray()

$do

$do(aFunction, aRejFunction) : oPromise

Instantiates and returns a oPromise. If you provide aFunction, this aFunction will be executed async in a thread and oPromise object will be immediatelly returned. Optionally this aFunction can receive a resolve and reject functions for to you use inside aFunction to provide a result with resolve(aResult) or an exception with reject(aReason). If you don't call theses functions the returned value will be used for resolve or any exception thrown will be use for reject. You can use the "then" method to add more aFunction that will execute once the previous as executed successfully (in a stack fashion). The return/resolve value from the  previous function will be passed as the value for the second. You can use the "catch" method to add aFunction that will receive a string or exception for any exception thrown with the reject functions. You can also provide aRejFunction to work as a "catch" method as previously described before.

$doA2B

$doA2B(aAFunction, aBFunction, numberOfDoPromises, defaultTimeout, aErrorFunction)

Will call aAFunction with a function as argument that should be used to "send" values to aBFunction. aBFunction will be call asynchronously in individual $do up to the numberOfDoPromises limit. The defaultTimeout it 2500ms. If aErrorFunction is defined it will received any exceptions thrown from aBFunction with the corresponding arguments array.

$doAll

$doAll(anArray) : oPromise

Returns an oPromise that will be resolved when all oPromise part of the anArray are fullfiled. If any of the oPromises fails/rejects the returned oPromise will also be rejected/fail.

$doFirst

$doFirst(anArray) : oPromise

Returns an oPromise that will be resolved when any oPromise part of the anArray is fullfiled. If any of the oPromises fails/rejects the returned oPromise will also be rejected/fail.

$doWait

$doWait(aPromise, aWaitTimeout) : oPromise

Blocks until aPromise is fullfilled or rejected. Optionally you can specify aWaitTimeout between checks. Returns aPromise.

$f

$f(aString, arg1, arg2, …) : String

Formats aString with arg1, arg2 and any other arguments provided using java.util.Formatter. The format is composed of "%[argument_index$][flags][width][.precision]conversion". Do note that javascript numbers are converted to java.lang.Float. If you need it to convert to Integer, Long, Double, Float and BigDecimal please use $ft. The javascript Date type will be converted to java Calendar. So possible values:

   argument_index: number
   flags         : '-' (left-justified); '#'; '+' (include sign); ' ' (leading space); '0' (zero-padded); ',' (separators); '(' (enclose negative values)
   conversion    : b/B (boolean), h/H (hash), s/S (string), "-" (left justify), c/C (character)

Examples:

   $f("Time %tT", new Date())
   $f("Date: %1$tm %1te, %1tY %1$tT", new Date())

   $f("%.2f", 1.9)
   $f("%10.2f", 1.9)


$flock.destroy

$flock.destroy()

Given aLockFile will destroy the provided lock entry.

   $flock(aLockFile).destroy()


$flock.isLocalLocked

$flock.isLocalLocked() : Boolean

Given aLockFile will return true if locked in the current OpenAF instance otherwise false (see also isLocked).

   $flock(aLockFile).isLocalLocked()


$flock.isLocked

$flock.isLocked() : Boolean

Given aLockFile will return true if locked in the current OpenAF instance or on the filesystem (by using $flock.tryLock) otherwise false (see also isLocalLocked).

   $flock(aLockFile).isLocked()


$flock.lock

$flock.lock()

Given aLockFile will use the file to filesystem lock until unlock is called.

   $flock(aLockFile).lock()


$flock.tryLock

$flock.tryLock(aFunction) : Boolean

Given aLockFile only execute aFunction if it's unlocked. If it executed aFunction it will return true otherwise false.

   $flock(aLockFile).tryLock(() => { ... })


$flock.unlock

$flock.unlock()

Given aLockFile will unlock freeing any previous calls to lock.

   $flock(aLockFile).unlock()


$fnDef4Help

$fnDef4Help(aFnName) : Array

Tries to retrieve an array of function argument names for the provided search string aFnName.

$fnM

$fnM(aFnName, aMap) : Object

Calls aFnName function trying to determine the name of the arguments from OpenAF's help or accessible source code (throws an exception if it can't determine the arguments) and then builds the arguments used to call aFnName using the values of keys in aMap. Example:

plugin("HTTP"); var h = new HTTP();
$fnM("h.get", { aUrl: "https://openaf.io/release" });


$fnM2A

$fnM2A(aFn, aInstance, aDefinitionArray, aMap) : Object

Tries to execute aFn, with aInstance if it's a function of an instance, using aMap of arguments that translate to aFn list of arguments. Returns whatever the function executed returns. Example:

plugin("HTTP");
var h = new HTTP();
$fnM2A(h.get, h, $fnDef4Help("HTTP.get"), { aUrl: "https://openaf.io/build", isBytes: false, returnStream: false });


$from

$from : Array

Shortcut for the nLinq library for easy query and access to arrays/objects. To see all the available options please refer to https://github.com/nmaguiar/nLinq/blob/main/Reference.md and the list of available functions by executing, in the openaf-console: "desc $from([])".

$ft

$ft(aString, arg1, arg2, …) : String

Equivalant to $f but number types are converted to Integer, Long, Double, Float and BigDecimal.

$get

$get(aKey) : Object

Returns a value previously set with $set with aKey.

$job

$job(aJob, args, aId, isolate) : Object

Shortcut to oJobRunJob and ow.oJob.runJob to execute aJob with args and returned the changed arguments. Optionally aId can be also provided. If isolate=true it will also clean the key 'res' and try to return the result of ow.oJob.output.

$llm

$llm(aModel) : $llm

Shortcut for $gpt on the owrap.AI library.

$lock.destroy

$lock.destroy()

Given aLockName will destroy the provided lock entry.

   $lock(aLockName).destroy()


$lock.isLocked

$lock.isLocked() : Boolean

Given aLockName will return true if locked otherwise false.

   $lock(aLockName).isLocked()


$lock.lock

$lock.lock()

Given aLockName will lock until unlock is called.

   $lock(aLockName).lock()


$lock.tryLock

$lock.tryLock(aFunction, aTimeoutMS) : Boolean

Given aLockName only execute aFunction when it's able to lock or after aTimeoutMS. If it executed aFunction it will return true otherwise false.

   $lock(aLockName).tryLock(() => { ... })


$lock.unlock

$lock.unlock()

Given aLockName will unlock freeing any previous calls to lock.

   $lock(aLockName).unlock()


$m2a

$m2a(aDef, aMap) : Array

Tries to convert aMap into an array using the aDef array of keys for the values order in the output array. Example:

$m2a(['c', 'b', 'a'], { a: 1, b: 2, c: 3 })    // [ 3, 2, 1 ]


$m4a

$m4a(aMap, aKey) : Array

Tries to create an array of maps from the provided aMap map of maps. Optionally if aKey is provided it will be added to each array map with the map key. Example:

var a = {
   "A1": { "abc": "123", "xpt": "000" },
   "A2": { "abc": "456", "xpt": "001" },
   "A3": { "abc": "789", "xpt": "002" }
}

$m4a(a, "key");
// [
//  { "key": "A1", "abc": "123", "xpt": "000" },
//  { "key": "A2", "abc": "456", "xpt": "001" },
//  { "key": "A3", "abc": "789", "xpt": "002" }
// ]


$openaf

$openaf(aScript, aPMIn, aOpenAF, extraJavaParamsArray) : Object

Tries to start an external process running openaf (if aOpenAF is provided, as a string or array, it will be used as the command to invoke openaf) to execute aScript setting the __pm variable to aPMIn. Upon execution end the __pm contents will be returned by the function.

$path

$path(obj, path, customFunctions) : Object

Shortcut for the JMESPath library for easy query and access to arrays/objects. To see all the available options please refer to http://jmespath.org. Optional you can provide a map of customFunctions. Examples:

[Slicing]: 
  $path(arr, "[0:5]"); $path(arr, "[5:10]"); $path(arr, "[:5]"); $path(arr, "[::2]"); $path(arr, "[::-1]");

[Projections]: 
  $path(arr, "a[*].first"); $path(arr, "a.*.b"); $path(arr, "[]");

[Filters]: 
  $path(arr, "a[?b=='xyz'].c"); $path(arr, "a[?b>`1`].x");

[MultiSelect]: 
  $path(arr, "a[].[x, y]"); $path(arr, "a[].{ x: x, y: y }");

[Pipe]: 
  $path(arr, "a[*].b | [0]"); 

[Functions]: 
  abs(x), avg(x), contains(x, y), ceil(x), floor(x), join(x, arr), keys(obj), length(x), map(expr, arr), max(x), max_by(x, y), merge(a, b), min(a), min_by(a, b), not_null(a), reverse(arr), sort(arr), sort_by(a, y), starts_with(a, b), ends_with(a, b), sum(a), to_array(a), to_string(a), to_number(a), type(a), values(a)
  $path(arr, "a[?contains(@, 'b') == `true`]")

[OpenAF custom functions]: 
  a2m(arrFields, arrValues), a4m(arr, 'key', dontRemove), m2a(arrFields, obj), m4a(obj, 'key'), count_by(arr, 'field'), format(x, 'format'), formatn(x, 'format'), group(arr, 'field'), group_by(arr, 'field1,field2'), unique(arr), to_map(arr, 'field'), to_date(x), to_datef(x, format) from_datef(x, format), to_isoDate(x), flat_map(x), search_keys(arr, 'text'), search_values(arr, 'text'), delete(map, 'field'), substring(a, ini, end),
 template(a, 'template'), t(a, 'template'), templateF(x, 'template'), tF(x, 'template'), to_bytesAbbr(x), to_numAbbr(x), from_bytesAbbr(x), from_siAbbr(x), from_timeAbbr(x), timeago(x), from_ms(x, 'format'), replace(x, 're', 'flags', 'replaceText'), split(x, 'sep'), trim(x), index_of(x, 'search'), last_index_of(x, 'search'), lower_case(x), upper_case(x), concat(x, y), match(x, 're', 'flags'), amerge(x, y), to_slon(x), from_slon(x), to_json(x), from_json(x, str), to_yaml(x, isMultiDoc), from_yaml(x), trim(x), nvl(x, v) add(x, y), sub(x, y), mul(x, y), div(x, y), mod(x, y)
split(x, sep), split_re(x, sepRE), split_sep(x, sepRE, encls), date_diff(d, unit, nullValue)
insert(obj, 'field', value), now(negativeTimeDiff)
get(nameOrPath), set(obj, path), setp(obj, path, name)

Custom functions:
  $path(2, "example(@)", { example: { _func: (a) => { return Number(a) + 10; }, _signature: [ { types: [ $path().number ] } ] } });


$py

$py(aPythonCodeOrFile, aInput, aOutputArray) : Map

Executes aPythonCodeOrFile using a map aInput as variables in python and returns a map with python  variables in aOutputArray.

$pyStart

$pyStart()

Start python process on the background. Should be stopped with $pyStop.

$pyStop

$pyStop()

Stops the background python process started by $pyStart.

$rest.delete

$rest.delete(aBaseURI, aIdxMap) : Map

Shortcut for ow.obj.rest.jsonRemove (see help ow.obj.rest.jsonRemove) using aOptions ($rest(aOptions).): login (function or string),  pass (word), connectionTimeout (in ms), requestHeaders (map), urlEncode (boolean), uriQuery (boolean), httpClient (ow.obj.http object), default (map to return when there is an exception), throwExceptions (boolean defaulting to false controlling between throwing exceptions on different from 2xx http codes or connection issues or returning a map (merge with default if available)  and an error entry), collectAllStats (boolean with default false to store per uri or host:port statitics), preAction function that receives and returns a map with changes (aBaseURL, aIdxMap, aDataRowMap, login, pass, conTimeout, reqHeaders, urlEncode and httpClient), retry (number) and retryWait (time in ms).

$rest.delete2File

$rest.delete2File(aFilePath, aBaseURI, aIdxMap)

Shortcut for ow.obj.rest.jsonRemove (see help ow.obj.rest.jsonRemove) using aOptions ($rest(aOptions).): login (function or string),  pass (word), connectionTimeout (in ms), requestHeaders (map), urlEncode (boolean), uriQuery (boolean), httpClient (ow.obj.http object), default (map to return when there is an exception), throwExceptions (boolean defaulting to false controlling between throwing exceptions on different from 2xx http codes or connection issues or returning a map (merge with default if available)  and an error entry), collectAllStats (boolean with default false to store per uri or host:port statitics), preAction function that receives and returns a map with changes (aBaseURL, aIdxMap, aDataRowMap, login, pass, conTimeout, reqHeaders, urlEncode and httpClient), retry (number) and retryWait (time in ms). The byte output will be saved into aFilePath. Optional $rest(aOptions.downloadResume = true) will resume download of a file if it exists.

$rest.delete2Stream

$rest.delete2Stream(aBaseURI, aIdxMap) : JavaStream

Shortcut for ow.obj.rest.jsonRemove (see help ow.obj.rest.jsonRemove) using aOptions ($rest(aOptions).): login (function or string),  pass (word), connectionTimeout (in ms), requestHeaders (map), urlEncode (boolean), uriQuery (boolean), httpClient (ow.obj.http object), default (map to return when there is an exception), throwExceptions (boolean defaulting to false controlling between throwing exceptions on different from 2xx http codes or connection issues or returning a map (merge with default if available)  and an error entry), collectAllStats (boolean with default false to store per uri or host:port statitics), preAction function that receives and returns a map with changes (aBaseURL, aIdxMap, aDataRowMap, login, pass, conTimeout, reqHeaders, urlEncode and httpClient), retry (number) and retryWait (time in ms).

$rest.get

$rest.get(aBaseURI, aIdxMap) : Map

Shortcut for ow.obj.rest.jsonGet (see help ow.obj.rest.jsonGet) using aOptions ($rest(aOptions).): login (function or string),  pass (word), connectionTimeout (in ms), requestHeaders (map), urlEncode (boolean), uriQuery (boolean), httpClient (ow.obj.http object), default (map to return when there is an exception), throwExceptions (boolean defaulting to false controlling between throwing exceptions on different from 2xx http codes or connection issues or returning a map (merge with default if available)  and an error entry), collectAllStats (boolean with default false to store per uri or host:port statitics), preAction function that receives and returns a map with changes (aBaseURL, aIdxMap, aDataRowMap, login, pass, conTimeout, reqHeaders, urlEncode and httpClient), retry (number) and retryWait (time in ms).

$rest.get2File

$rest.get2File(aFilePath, aBaseURI, aIdxMap)

Shortcut for ow.obj.rest.jsonGet (see help ow.obj.rest.jsonGet) using aOptions ($rest(aOptions).): login (function or string),  pass (word), connectionTimeout (in ms), requestHeaders (map), urlEncode (boolean), uriQuery (boolean), httpClient (ow.obj.http object), default (map to return when there is an exception), throwExceptions (boolean defaulting to false controlling between throwing exceptions on different from 2xx http codes or connection issues or returning a map (merge with default if available)  and an error entry), collectAllStats (boolean with default false to store per uri or host:port statitics), preAction function that receives and returns a map with changes (aBaseURL, aIdxMap, aDataRowMap, login, pass, conTimeout, reqHeaders, urlEncode and httpClient), retry (number) and retryWait (time in ms). The byte output will be saved into aFilePath. Optional $rest(aOptions.downloadResume = true) will resume download of a file if it exists.

$rest.get2Stream

$rest.get2Stream(aBaseURI, aIdxMap) : JavaStream

Shortcut for ow.obj.rest.jsonGet (see help ow.obj.rest.jsonGet) using aOptions ($rest(aOptions).): login (function or string),  pass (word), connectionTimeout (in ms), requestHeaders (map), urlEncode (boolean), uriQuery (boolean), httpClient (ow.obj.http object), default (map to return when there is an exception), throwExceptions (boolean defaulting to false controlling between throwing exceptions on different from 2xx http codes or connection issues or returning a map (merge with default if available)  and an error entry), collectAllStats (boolean with default false to store per uri or host:port statitics), preAction function that receives and returns a map with changes (aBaseURL, aIdxMap, aDataRowMap, login, pass, conTimeout, reqHeaders, urlEncode and httpClient), retry (number) and retryWait (time in ms).

$rest.head

$rest.head(aBaseURI, aIdxMap)

Shortcut for ow.obj.rest.head (see help ow.obj.rest.head) using aOptions ($rest(aOptions).): login (function or string),  pass (word), connectionTimeout (in ms), requestHeaders (map), urlEncode (boolean), uriQuery (boolean), httpClient (ow.obj.http object), default (map to return when there is an exception), throwExceptions (boolean defaulting to false controlling between throwing exceptions on different from 2xx http codes or connection issues or returning a map (merge with default if available)  and an error entry), collectAllStats (boolean with default false to store per uri or host:port statitics), preAction function that receives and returns a map with changes (aBaseURL, aIdxMap, login, pass, conTimeout, reqHeaders, urlEncode and httpClient), retry (number) and retryWait (time in ms).

$rest.index

$rest.index(aMap) : String

Shortcut for ow.obj.rest.writeIndexes (see help ow.obj.rest.writeIndexes).

$rest.patch

$rest.patch(aBaseURI, aDataRowMap, aIdxMap) : Map

Shortcut for ow.obj.rest.jsonPatch (see help ow.obj.rest.jsonPatch) using aOptions ($rest(aOptions).): login (function or string),  pass (word), connectionTimeout (in ms), requestHeaders (map), urlEncode (boolean), uriQuery (boolean), httpClient (ow.obj.http object), default (map to return when there is an exception), throwExceptions (boolean defaulting to false controlling between throwing exceptions on different from 2xx http codes or connection issues or returning a map (merge with default if available)  and an error entry), collectAllStats (boolean with default false to store per uri or host:port statitics), preAction function that receives and returns a map with changes (aBaseURL, aIdxMap, aDataRowMap, login, pass, conTimeout, reqHeaders, urlEncode and httpClient), retry (number) and retryWait (time in ms).

$rest.patch2File

$rest.patch2File(aFilePath, aBaseURI, aDataRowMap, aIdxMap)

Shortcut for ow.obj.rest.jsonPatch (see help ow.obj.rest.jsonPatch) using aOptions ($rest(aOptions).): login (function or string),  pass (word), connectionTimeout (in ms), requestHeaders (map), urlEncode (boolean), uriQuery (boolean), httpClient (ow.obj.http object), default (map to return when there is an exception), throwExceptions (boolean defaulting to false controlling between throwing exceptions on different from 2xx http codes or connection issues or returning a map (merge with default if available)  and an error entry), collectAllStats (boolean with default false to store per uri or host:port statitics), preAction function that receives and returns a map with changes (aBaseURL, aIdxMap, aDataRowMap, login, pass, conTimeout, reqHeaders, urlEncode and httpClient), retry (number) and retryWait (time in ms).  The byte output will be saved into aFilePath. Optional $rest(aOptions.downloadResume = true) will resume download of a file if it exists.

$rest.patch2Stream

$rest.patch2Stream(aBaseURI, aDataRowMap, aIdxMap) : JavaStream

Shortcut for ow.obj.rest.jsonPatch (see help ow.obj.rest.jsonPatch) using aOptions ($rest(aOptions).): login (function or string),  pass (word), connectionTimeout (in ms), requestHeaders (map), urlEncode (boolean), uriQuery (boolean), httpClient (ow.obj.http object), default (map to return when there is an exception), throwExceptions (boolean defaulting to false controlling between throwing exceptions on different from 2xx http codes or connection issues or returning a map (merge with default if available)  and an error entry), collectAllStats (boolean with default false to store per uri or host:port statitics), preAction function that receives and returns a map with changes (aBaseURL, aIdxMap, aDataRowMap, login, pass, conTimeout, reqHeaders, urlEncode and httpClient), retry (number) and retryWait (time in ms).

$rest.patchUpload

$rest.patchUpload(aBaseURI, aDataRowMap, aIdxMap) : Map

Shortcut for ow.obj.rest.upload (see help ow.obj.rest.upload with patch) using aOptions ($rest(aOptions).): login (function or string),  pass (word), connectionTimeout (in ms), requestHeaders (map), urlEncode (boolean), uriQuery (boolean), httpClient (ow.obj.http object), default (map to return when there is an exception), throwExceptions (boolean defaulting to false controlling between throwing exceptions on different from 2xx http codes or connection issues or returning a map (merge with default if available)  and an error entry), collectAllStats (boolean with default false to store per uri or host:port statitics), preAction function that receives and returns a map with changes (aBaseURL, aIdxMap, aDataRowMap, login, pass, conTimeout, reqHeaders, urlEncode and httpClient), retry (number) and retryWait (time in ms).

$rest.patchUpload2Stream

$rest.patchUpload2Stream(aBaseURI, aDataRowMap, aIdxMap) : JavaStream

Shortcut for ow.obj.rest.upload (see help ow.obj.rest.upload with patch) using aOptions ($rest(aOptions).): login (function or string),  pass (word), connectionTimeout (in ms), requestHeaders (map), urlEncode (boolean), uriQuery (boolean), httpClient (ow.obj.http object), default (map to return when there is an exception), throwExceptions (boolean defaulting to false controlling between throwing exceptions on different from 2xx http codes or connection issues or returning a map (merge with default if available)  and an error entry), collectAllStats (boolean with default false to store per uri or host:port statitics), preAction function that receives and returns a map with changes (aBaseURL, aIdxMap, aDataRowMap, login, pass, conTimeout, reqHeaders, urlEncode and httpClient), retry (number) and retryWait (time in ms).

$rest.post

$rest.post(aBaseURI, aDataRowMap, aIdxMap) : Map

Shortcut for ow.obj.rest.jsonCreate (see help ow.obj.rest.jsonCreate) using aOptions ($rest(aOptions).): login (function or string),  pass (word), connectionTimeout (in ms), requestHeaders (map), urlEncode (boolean), uriQuery (boolean), httpClient (ow.obj.http object), default (map to return when there is an exception), throwExceptions (boolean defaulting to false controlling between throwing exceptions on different from 2xx http codes or connection issues or returning a map (merge with default if available)  and an error entry), collectAllStats (boolean with default false to store per uri or host:port statitics), preAction function that receives and returns a map with changes (aBaseURL, aIdxMap, aDataRowMap, login, pass, conTimeout, reqHeaders, urlEncode and httpClient), retry (number) and retryWait (time in ms).

$rest.post2File

$rest.post2File(aFilePath, aBaseURI, aDataRowMap, aIdxMap)

Shortcut for ow.obj.rest.jsonCreate (see help ow.obj.rest.jsonCreate) using aOptions ($rest(aOptions).): login (function or string),  pass (word), connectionTimeout (in ms), requestHeaders (map), urlEncode (boolean), uriQuery (boolean), httpClient (ow.obj.http object), default (map to return when there is an exception), throwExceptions (boolean defaulting to false controlling between throwing exceptions on different from 2xx http codes or connection issues or returning a map (merge with default if available)  and an error entry), collectAllStats (boolean with default false to store per uri or host:port statitics), preAction function that receives and returns a map with changes (aBaseURL, aIdxMap, aDataRowMap, login, pass, conTimeout, reqHeaders, urlEncode and httpClient), retry (number) and retryWait (time in ms). The byte output will be saved into aFilePath. Optional $rest(aOptions.downloadResume = true) will resume download of a file if it exists.

$rest.post2Stream

$rest.post2Stream(aBaseURI, aDataRowMap, aIdxMap) : JavaStream

Shortcut for ow.obj.rest.jsonCreate (see help ow.obj.rest.jsonCreate) using aOptions ($rest(aOptions).): login (function or string),  pass (word), connectionTimeout (in ms), requestHeaders (map), urlEncode (boolean), uriQuery (boolean), httpClient (ow.obj.http object), default (map to return when there is an exception), throwExceptions (boolean defaulting to false controlling between throwing exceptions on different from 2xx http codes or connection issues or returning a map (merge with default if available)  and an error entry), collectAllStats (boolean with default false to store per uri or host:port statitics), preAction function that receives and returns a map with changes (aBaseURL, aIdxMap, aDataRowMap, login, pass, conTimeout, reqHeaders, urlEncode and httpClient), retry (number) and retryWait (time in ms).

$rest.postUpload

$rest.postUpload(aBaseURI, aDataRowMap, aIdxMap) : Map

Shortcut for ow.obj.rest.upload (see help ow.obj.rest.upload with post) using aOptions ($rest(aOptions).): login (function or string),  pass (word), connectionTimeout (in ms), requestHeaders (map), urlEncode (boolean), uriQuery (boolean), httpClient (ow.obj.http object), default (map to return when there is an exception), throwExceptions (boolean defaulting to false controlling between throwing exceptions on different from 2xx http codes or connection issues or returning a map (merge with default if available)  and an error entry), collectAllStats (boolean with default false to store per uri or host:port statitics), preAction function that receives and returns a map with changes (aBaseURL, aIdxMap, aDataRowMap, login, pass, conTimeout, reqHeaders, urlEncode and httpClient), retry (number) and retryWait (time in ms).

$rest.postUpload2Stream

$rest.postUpload2Stream(aBaseURI, aDataRowMap, aIdxMap) : JavaStream

Shortcut for ow.obj.rest.upload (see help ow.obj.rest.upload with post) using aOptions ($rest(aOptions).): login (function or string),  pass (word), connectionTimeout (in ms), requestHeaders (map), urlEncode (boolean), uriQuery (boolean), httpClient (ow.obj.http object), default (map to return when there is an exception), throwExceptions (boolean defaulting to false controlling between throwing exceptions on different from 2xx http codes or connection issues or returning a map (merge with default if available)  and an error entry), collectAllStats (boolean with default false to store per uri or host:port statitics), preAction function that receives and returns a map with changes (aBaseURL, aIdxMap, aDataRowMap, login, pass, conTimeout, reqHeaders, urlEncode and httpClient), retry (number) and retryWait (time in ms).

$rest.put

$rest.put(aBaseURI, aDataRowMap, aIdxMap) : Map

Shortcut for ow.obj.rest.jsonSet (see help ow.obj.rest.jsonSet) using aOptions ($rest(aOptions).): login (function or string),  pass (word), connectionTimeout (in ms), requestHeaders (map), urlEncode (boolean), uriQuery (boolean), httpClient (ow.obj.http object), default (map to return when there is an exception), throwExceptions (boolean defaulting to false controlling between throwing exceptions on different from 2xx http codes or connection issues or returning a map (merge with default if available)  and an error entry), collectAllStats (boolean with default false to store per uri or host:port statitics), preAction function that receives and returns a map with changes (aBaseURL, aIdxMap, aDataRowMap, login, pass, conTimeout, reqHeaders, urlEncode and httpClient), retry (number) and retryWait (time in ms).

$rest.put2File

$rest.put2File(aFilePath, aBaseURI, aDataRowMap, aIdxMap)

Shortcut for ow.obj.rest.jsonSet (see help ow.obj.rest.jsonSet) using aOptions ($rest(aOptions).): login (function or string),  pass (word), connectionTimeout (in ms), requestHeaders (map), urlEncode (boolean), uriQuery (boolean), httpClient (ow.obj.http object), default (map to return when there is an exception), throwExceptions (boolean defaulting to false controlling between throwing exceptions on different from 2xx http codes or connection issues or returning a map (merge with default if available)  and an error entry), collectAllStats (boolean with default false to store per uri or host:port statitics), preAction function that receives and returns a map with changes (aBaseURL, aIdxMap, aDataRowMap, login, pass, conTimeout, reqHeaders, urlEncode and httpClient), retry (number) and retryWait (time in ms). The byte output will be saved into aFilePath. Optional $rest(aOptions.downloadResume = true) will resume download of a file if it exists.

$rest.put2Stream

$rest.put2Stream(aBaseURI, aDataRowMap, aIdxMap) : JavaStream

Shortcut for ow.obj.rest.jsonSet (see help ow.obj.rest.jsonSet) using aOptions ($rest(aOptions).): login (function or string),  pass (word), connectionTimeout (in ms), requestHeaders (map), urlEncode (boolean), uriQuery (boolean), httpClient (ow.obj.http object), default (map to return when there is an exception), throwExceptions (boolean defaulting to false controlling between throwing exceptions on different from 2xx http codes or connection issues or returning a map (merge with default if available)  and an error entry), collectAllStats (boolean with default false to store per uri or host:port statitics), preAction function that receives and returns a map with changes (aBaseURL, aIdxMap, aDataRowMap, login, pass, conTimeout, reqHeaders, urlEncode and httpClient), retry (number) and retryWait (time in ms).

$rest.putUpload

$rest.putUpload(aBaseURI, aDataRowMap, aIdxMap) : Map

Shortcut for ow.obj.rest.upload (see help ow.obj.rest.upload with put) using aOptions ($rest(aOptions).): login (function or string),  pass (word), connectionTimeout (in ms), requestHeaders (map), urlEncode (boolean), uriQuery (boolean), httpClient (ow.obj.http object), default (map to return when there is an exception), throwExceptions (boolean defaulting to false controlling between throwing exceptions on different from 2xx http codes or connection issues or returning a map (merge with default if available)  and an error entry), collectAllStats (boolean with default false to store per uri or host:port statitics), preAction function that receives and returns a map with changes (aBaseURL, aIdxMap, aDataRowMap, login, pass, conTimeout, reqHeaders, urlEncode and httpClient), retry (number) and retryWait (time in ms).

$rest.putUpload2Stream

$rest.putUpload2Stream(aBaseURI, aDataRowMap, aIdxMap) : JavaStream

Shortcut for ow.obj.rest.upload (see help ow.obj.rest.upload with post) using aOptions ($rest(aOptions).): login (function or string),  pass (word), connectionTimeout (in ms), requestHeaders (map), urlEncode (boolean), uriQuery (boolean), httpClient (ow.obj.http object), default (map to return when there is an exception), throwExceptions (boolean defaulting to false controlling between throwing exceptions on different from 2xx http codes or connection issues or returning a map (merge with default if available)  and an error entry), collectAllStats (boolean with default false to store per uri or host:port statitics), preAction function that receives and returns a map with changes (aBaseURL, aIdxMap, aDataRowMap, login, pass, conTimeout, reqHeaders, urlEncode and httpClient), retry (number) and retryWait (time in ms).

$rest.query

$rest.query(aMap) : String

Shortcut for ow.obj.rest.writeQuery (see help ow.obj.rest.writeQuery).

$retry

$retry(aFunction, aNumOfTriesOrFunction) : Object

Tries to execute aFunction and return the corresponding returned result. If aNumOfTriesOrFunction is a number (defaults to 1) and aFunction throws an exception it will repeat aFunction until it doesn't throw an exception or for the number of aNumOfTriesOrFunc. If aNumOfTriesOrFunction is a function it will be called whenever aFunction throws an exception with the corresponding exception as argument and it will retry until aNumOfTriesOrFunction returns false.

$set

$set(aKey, aValue)

Sets aValue with aKey so it can be retrieved with $get later.

$sh.cb

$sh.cb(aCallbackFunc) : $sh

When executing aCmd (with .get) use aCallbackFunc function.

$sh.cp

$sh.cp(aSource, aTarget) : $sh

Immediately copies aSource to aTarget before executing aCmd (with .exec).

$sh.dontWait

$sh.dontWait(aBooleanValue) : $sh

If aBooleanValue = true the execution won't wait for output (default: false).

$sh.envs

$sh.envs(aMap, includeExisting) : $sh

Uses aMap of strings as the environment variables map. If includeExisting = true it will include the current environment variables also.

$sh.exec

$sh.exec(aIdx) : Object

Immediately copies the result of executing aCmd string or array (and any other commands in queue added using sh). If aIdx is provided it will return the map entry for the corresponding command on the array otherwise it will return the array.

$sh.exit

$sh.exit(aFunc) : $sh

Sets aFunc function to execute after the execution of aCmd (with .exec).

$sh.get

$sh.get(aIdx) : Object

Immediately copies the result of executing aCmd string or array (and any other commands in queue added using sh). If aIdx is provided it will return the map entry for the corresponding command on the array otherwise it will return the array.

$sh.getJson

$sh.getJson(aIdx) : Object

Immediately copies the result of executing aCmd string or array (and any other commands in queue added using sh) trying to parse it as json. If aIdx is provided it will return the map entry for the corresponding command on the array otherwise it will return the array.

$sh.getYaml

$sh.getYaml(aIdx) : Object

Immediately copies the result of executing aCmd string or array (and any other commands in queue added using sh) trying to parse it as yaml. If aIdx is provided it will return the map entry for the corresponding command on the array otherwise it will return the array.

$sh.mkdir

$sh.mkdir(aDir) : $sh

Immediately creates aDir before executing aCmd (with .exec).

$sh.mv

$sh.mv(aSource, aTarget) : $sh

Immediately moves aSource to aTarget before executing aCmd (with .exec).

$sh.prefix

$sh.prefix(aPrefix, aTemplate) : $sh

When executing aCmd (with .get) it will use ow.format.streamSHPrefix with aPrefix and optionally aTemplate.

$sh.pwd

$sh.pwd(aPwd) : $sh

When executing aCmd (with .exec) use aPwd as the current working directory.

$sh.rename

$sh.rename(aSource, aTarget) : $sh

Immediately renames aSource to aTarget before executing aCmd (with .exec).

$sh.rm

$sh.rm(aFilePath) : $sh

Immediately removes aFilePath before executing aCmd (with .exec).

$sh.sh

$sh.sh(aCmd, aIn) : $sh

When executing aCmd (with .exec) sets additional aCmds (with the optional corresponding aIn) to use.

$sh.timeout

$sh.timeout(aTimeout) : $sh

When executing aCmd (with .exec) uses aTimeout.

$sh.useEncoding

$sh.useEncoding(aEncoding) : $sh

Forces the aEncoding to be used.

$sql

$sql(aObject, aSQL, aMethod) : Array

Given an aObject (map or array) will try to execute aSQL (SQL expression) and return the corresponding results. Optionally you can provide aMethod to be used (e.g. "auto" (default) or "nlinq" or "h2"). "nlinq" it's the fastest but doesn't support aggregations or multi-field combinations; "h2" is the more complete but will require a lot more resources, it's slower.

NOTE: In "h2" you can use the table _TMP for your queries.

$ssh.$ssh

$ssh.$ssh(aMap) : $ssh

Builds an object to allow access through ssh. aMap should be a ssh string with the format: ssh://user:pass@host:port/identificationKey?timeout=1234&compression=true or a map with the keys: host, port, login, pass, id (file key) / key (string representation), compress and timeout. See "help SSH.SSH" for more info.

$ssh.cb

$ssh.cb(aCallback) : $ssh

Sets aCallback function to execute during the execution of commands on a remote host defined by aMap (host, port, login, pass, id, compress and timeout).

$ssh.close

$ssh.close() : $ssh

Closes a remote host connection defined by aMap (host, port, login, pass, id, compress and timeout).

$ssh.exec

$ssh.exec(aIdx) : Array

Executes a list of commands previously set on a remote host connection defined by aMap (host, port, login, pass, id, compress and timeout). IO is inherit. If aIdx is provided it will return the map entry for the corresponding command on the array otherwise it will return the array.

$ssh.exit

$ssh.exit(aFunc) : $ssh

Sets a callback aFunc to execute upon a command execution s a remote host connection defined by aMap (host, port, login, pass, id, compress and timeout).

$ssh.get

$ssh.get(aIdx) : Object

Executes a list of commands previously set on a remote host connection defined by aMap (host, port, login, pass, id, compress and timeout). IO is not inherit. If aIdx is provided it will return the map entry for the corresponding command on the array otherwise it will return the array.

$ssh.getFile

$ssh.getFile(aSource, aTarget) : $ssh

Gets aSource filepath and stores it locally on aTarget from a remote host defined by aMap (host, port, login, pass, id, compress and timeout).

$ssh.getJson

$ssh.getJson(aIdx) : Object

Executes a list of commands previously set on a remote host connection defined by aMap (host, port, login, pass, id, compress and timeout). IO is not inherit. If aIdx is provided it will return the map entry for the corresponding command on the array otherwise it will return the array. The stdout and stderr will be pre-parsed from json to objects.

$ssh.listFiles

$ssh.listFiles(aRemotePath) : Array

Returns an array of maps with the listing of aRemotePath provided.

$ssh.mkdir

$ssh.mkdir(aDirectory) : $ssh

Creates aDirectory via SFTP on a remote host defined by aMap (host, port, login, pass, id, compress and timeout).

$ssh.prefix

$ssh.prefix(aPrefix, aTemplate) : $ssh

When executing aCmd (with .get) it will use ow.format.streamSHPrefix with aPrefix and optionally aTemplate.

$ssh.pty

$ssh.pty(aFlag) : $ssh

Sets the flag to use or not a pty term allocation on the ssh connection to a remote host defined by aMap (host, port, login, pass, id, key, compress and timeout).

$ssh.putFile

$ssh.putFile(aSource, aTarget) : $ssh

Puts aSource local filepath and stores it remotely in aTarget on a remote host defined by aMap (host, port, login, pass, id, compress and timeout).

$ssh.pwd

$ssh.pwd(aPwd) : $ssh

Sets aPwd directory for getting and sending files to a remote host defined by aMap (host, port, login, pass, id, compress and timeout).

$ssh.rename

$ssh.rename(aSource, aTarget) : $ssh

Renames aSource filepath to aTarget filepath on a remote host defined by aMap (host, port, login, pass, id, compress and timeout).

$ssh.rm

$ssh.rm(aFilePath) : $ssh

Remove aFilePath from a remote host defined by aMap (host, port, login, pass, id, compress and timeout).

$ssh.rmdir

$ssh.rmdir(aFilePath) : $ssh

Removes a directory from a remote host defined by aMap (host, port, login, pass, id, compress and timeout).

$ssh.sh

$ssh.sh(aCmd, aIn) : $ssh

Sets aCmd to be executed with an optional aIn (stdin) on the remote host defined by aMap (host, port, login, pass, id, compress and timeout).

$ssh.timeout

$ssh.timeout(aTimeout) : $ssh

Sets aTimeout in ms for the ssh/sftp connection to a remote host defined by aMap (host, port, login, pass, id, compress and timeout).

$ssh.tunnelLocal

$ssh.tunnelLocal(aLocalPort, aRemoteHost, aRemotePort) : $ssh

Creates a local tunnel mapping aLocalPort to aRemoteHost:aRemotePort using the ssh connection defined by aMap (host, port, login, pass, id, compress and timeout).

$ssh.tunnelLocalBind

$ssh.tunnelLocalBind(aLocalInterface, aLocalPort, aRemoteHost, aRemotePort) : $ssh

Creates a local tunnel mapping aLocalInterface:aLocalPort to aRemoteHost:aRemotePort using the ssh connection defined by aMap (host, port, login, pass, id, compress and timeout).

$ssh.tunnelRemote

$ssh.tunnelRemote(aRemotePort, aLocalAddress aLocalPort) : $ssh

Creates a remote tunnel mapping aRemotePort to aLocalAddress:aLocalPort using the ssh connection defined by aMap (host, port, login, pass, id, compress and timeout).

$ssh.tunnelRemoteBind

$ssh.tunnelRemoteBind(aRemoteInterface, aRemotePort, aLocalAddress aLocalPort) : $ssh

Creates a remote tunnel mapping aRemoteInterface:aRemotePort to aLocalAddress:aLocalPort using the ssh connection defined by aMap (host, port, login, pass, id, compress and timeout).

$stream

$stream

Shortcut for the streamjs library for easy query and access to streams of data. To see all the available options please refer to https://github.com/winterbe/streamjs/blob/master/APIDOC.md.

$tb

$tb(aFunction) : Result

Shorcut for a "thread-box" to execute aFunction. The "thread" will timeout with the provided execution timeout (in ms) or stop whenever the stopWhen function returns true (called continuously or after each timeout). Examples:

   $tb().timeout(5000).exec(aFunc);  // Executes aFunc to a maximum of 5 seconds. Afterwards the aFunc is stopped.
   $tb(aFunc).timeout(5000).exec();  // Sames as previous, aFunc can be provided before or on exec.
   $tb().timeout(500).stopWhen(aStopFunc).exec(); // Stops when aStopFunc is true.

$throwIfUnDef

$throwIfUnDef(aFunc) : Function

Returns a function that tries to execute aFunc and throws and exception if the result if undefined otherwise returns the result. Usefull with $retry when waiting for a "defined" result.

$unset

$unset(aKey)

Unset a previously set value with aKey.

_i$

_i$(aValue, aPrefixMessage) : Object

Same as _$ but if aValue is not defined and aPrefixMessage if defined it will use ask() or askEncrypt() to  interactively ask the user for the value with the prompt "[aPrefixMessage]: ". Should only be used if user interaction is expected but to force not be interactiv you can set __i$interactive to false). Note: askEncrypt will be used if aPrefixMessage has any reference to "secret" or "pass".

addOnOpenAFShutdown

addOnOpenAFShutdown(aFunction) : Boolean

Adds aFunction to try to execute whenever OpenAF is going to shutdown. The latest hook added will be the first to be executed until the first hook added (actually a shortcut for Threads.addOpenAFShutdownHook).

addOPackRemoteDB

addOPackRemoteDB(aURL)

Adds a path to an opack.db file to the current search path.

AF.encryptText

AF.encryptText()

Interactevly asks to enter a text and then uses af.encrypt to print to stdout the result.

AF.fromJavaArray

AF.fromJavaArray(aJavaArray) : Array

Tries to convert aJavaArray into a native an array.

AF.fromJSSLON

AF.fromJSSLON(aString) : Object

Tries to convert the provided aString into an object. The string might be JSON or SLON.

AF.fromNLinq

AF.fromNLinq(aString) : Map

Converts a nLinq chained command line string representation into a suitable map to be used with $from.query.

af.fromObj2XML

af.fromObj2XML(aMap, sanitize) : String

Tries to convert aMap into a similiar XML strucuture returned as string. Note that no validation of XML strucuture is performed.  Tips: ensure each map is under a map key.

AF.fromSLON

AF.fromSLON(aString) : Map

Converts a SLON (https://github.com/nmaguiar/slon) string representation into the original map.

AF.fromSQL

AF.fromSQL(aString) : Map

Converts a SQL expression into an ASP map.

AF.fromSQL2NLinq

AF.fromSQL2NLinq(aSQL) : Map

Converts a SQL expression into a suitable map to be used with $from.query.

af.fromXML2Obj

af.fromXML2Obj(xml, ignored, aPrefix, reverseIgnored) : Object

Tries to convert a XML object into a javascript object. Tag attributes will be ignored unless the corresponding tag name is included on the ignored array and attributes will be added to the corresponding map with a prefix "_" (or aPrefix). Optionally if reverseIgnored = true the ignored array will be used to not include the tag name in the ignored array.

AF.fromYAML

AF.fromYAML(aYaml) : Object

Tries to parse aYaml into a javascript map.

AF.getEncoding

AF.getEncoding(anArrayOfBytesORString) : String

Given anArrayOfBytesORString will try to detect which encode is used and returns a string with the identified charset encoding.

AF.printStackTrace

AF.printStackTrace(aFunction) : Object

Executes aFunction but if it throws an exception and the exception is a Java exception it will print the exception's stack trace.

AF.protectSystemExit

AF.protectSystemExit(shouldProtect, aMessage)

Protects the current execution against a exit instruction if shouldProtect = true (otherwise it will unprotect). If protected a security exception with aMessage (string) followed by the exit status will be thrown or the result of calling function aMessage with the exit status as a parameter.

af.runFromExternalClass

af.runFromExternalClass(aClassName, aPath)

Tries to "execute" aClassName from a previously compiled OpenAF script, with af.compileToClasses, on aPath.

Example:
   af.compileToClasses("MyClass", "var myOpen = 'AF Class'", ".");
   af.runFromExternalClass("MyClass", ".");
   myOpen; // AF Class


AF.toCSLON

AF.toCSLON(aObject, aTheme) : String

Converts aObject map/array into SLON representation with ansi colors (see more in help for ow.format.toCSLON)

AF.toSLON

AF.toSLON(aObject, aTheme) : String

Converts aObject map/array into SLON representation (see more in help for ow.format.toSLON)

AF.toYAML

AF.toYAML(aJson, multiDoc, sanitize) : String

Tries to dump aJson into a YAML string. If multiDoc = true and aJson is an array the output will be multi-document. If sanitize = true all Java objects will be converted to avoid parsing errors.

ansiColor

ansiColor(aAnsi, aString, force, noCache, noReset) : String

Returns the ANSI codes together with aString, if determined that the current terminal can handle ANSI codes (overridden by force = true), with the attributes defined in aAnsi. Please use with ansiStart() and ansiStop(). The optional noReset boolean flag will remove ansi reset as part of the string returned. The attributes separated by commas can be:

BLACK; RED; GREEN; YELLOW; BLUE; MAGENTA; CYAN; WHITE;
FG_BLACK; FG_RED; FG_GREEN; FG_YELLOW; FG_BLUE; FG_MAGENTA; FG_CYAN; FG_WHITE;
BG_BLACK; BG_RED; BG_GREEN; BG_YELLOW; BG_BLUE; BG_MAGENTA; BG_CYAN; BG_WHITE;
BOLD; FAINT; INTENSITY_BOLD; INTENSITY_FAINT; ITALIC; UNDERLINE; BLINK_SLOW; BLINK_FAST; BLINK_OFF; NEGATIVE_ON; NEGATIVE_OFF; CONCEAL_ON; CONCEAL_OFF; UNDERLINE_DOUBLE; UNDERLINE_OFF;


ansiLength

ansiLength(aString) : Number

Tries to return the aString length without any ansi control sequences.

ansiStart

ansiStart(force)

Prepares to output ansi codes if the current terminal is capable off (unless force = true). Use with ansiColor() and ansiStop().

ansiStop

ansiStop(force)

Disables the output of ansi codes if the current terminal is capable off (unless force = true). Use with ansiColor() and ansiStart().

ansiWinTermCap

ansiWinTermCap() : boolean

Determines in Windows if the current terminal has support for newer capabilities or not (e.g. cmd.exe)

arrayContains

arrayContains(anArray, aObj, aPreFilter) : Number

Tries to find aObj in anArray returning the position where it's first found or -1 if not found. Optionally aPreFilter function can prepare each object for comparing.

ask

ask(aPrompt, aMask) : String

Stops for user interaction prompting aPrompt waiting for an entire line of characters and, optionally, masking the user input with aMask (e.g. "*"). Returns the user input.

ask1

ask1(aPrompt, allowed) : String

Stops for user interaction prompting aPrompt waiting for a single character within the allowed string (a set of characters). Returns the user input.

askChoose

askChoose(aPrompt, anArray, aMaxDisplay) : Number

Stops for user interaction prompting aPrompt waiting for a single character to choose from the provided anArray of options. Optionally you can provide aMaxDisplay to limit the number of options displayed at a time. Returns the index of the chosen option.

askDef

askDef(aInit, aQuestion, isSecret, isVoidable) : String

If aInit is not defined will ask aQuestion (if isSecret = true it will askEncrypt) and return the value. If isVoidable = true and no answer is provided it will return undefined.

askEncrypt

askEncrypt(aPrompt) : String

Similar to ask but the return user input will be encrypted. If an empty string is entered by the user the function will return undefined.

askN

askN(aPromptFn, aStopFn) : String

Stops for a multi-line user interaction prompting, for each line, the result of calling aPromptFn that receives the current user input  (if a string is provided it will default to a function that returns that string). The interaction will stop when aStopFn function, that receives the current user input as an argument, returns true (if the function is not provided it will default to 3 new lines).

bcrypt

bcrypt(aText, aVerifyHash, hashingRounds) : String/boolean

If aText is provided it will return the resulting string of applying the bcrypt hash to aText. Optionally the bcrypt hashingRounds (between 4 and  31, default 10) can be provided (note: the more rounds, the more slower and secure). If aVerifyHash is provided it will return a boolean determining if the provided aVerifyHash (result of a previous bcrypt) matches the aText provided (hashingRounds will be ignored since the hash string already provides the rounds used).

beautifier

beautifier(anObject) : String

Shortcut for the af.js2s function providing a human readable representation of the javascript object provided.

beep

beep()

Tries to produce a beep sound.

bprint

bprint(aStr)

"Beautifies" and prints the aStr to the stdout (with a new line on the end) (example: bprint("hello world!"))

bprintErr

bprintErr(aStr)

"Beautifies" and prints the aStr to the stderr (with a new line on the end) (example: bprintErr("Hupps!! A problem!"))

bprintErrnl

bprintErrnl(aStr)

"Beautifies" and prints the aStr to the stderr (without adding a new line on the end) (example: bprintErrnl("Hupps!! A problem!"))

bprintnl

bprintnl(aStr)

"Beautifies" and prints the aStr to the stdout (without adding a new line on the end) (example: bprintnl("hello world!"))

checkLatestVersion

checkLatestVersion() : String

Tries to determine what is the latest available version for OpenAF. Compare it with getVersion() to determine if you need an update.

clone

clone(anObject) : aClonedObject

Creates a new copy of a JavaScript object.

cls

cls()

Tries to clear the screen. The commands to try to clean the screen are given in ANSI.

colorify

colorify(aObject) : String

Tries to ANSI colorify a json aObject for use with cprint, cprintErr, cprintErrnl and cprintnl

compare

compare(X, Y) : Boolean

Compares a X object to a Y object at the content level. If they are equal the function will return true otherwise it will return false.

compress

compress(anObject) : ArrayOfBytes

Compresses a JSON object into an array of bytes suitable to be uncompressed using the uncompress function.

conReset

conReset() : boolean

Tries to reset the console to its original state. Returns true if successful.

cprint

cprint(aStr)

"Stringifies" in ANSI color and prints the aStr to the stdout (with a new line on the end) (example: cprint("hello world!"))

cprintErr

cprintErr(aStr)

"Stringifies" in ANSI color and prints the aStr to the stderr (with a new line on the end) (example: cprintErr("Hupps!! A problem!"))

cprintErrnl

cprintErrnl(aStr)

"Stringifies" in ANSI color and prints the aStr to the stderr (with a new line on the end) (example: cprintErrnl("Hupps!! A problem!"))

cprintnl

cprintnl(aStr)

"Stringifies" in ANSI color and prints the aStr to the stdout (with a new line on the end) (example: cprintnl("hello world!"))

createDB

createDB(aFile, aLogin, aPass) : DB

Creates a DB object instantiated with a file based H2 database for the aFile provided. Optionally you can use aLogin and aPass(word).

createDBInMem

createDBInMem(aName, dontClose, aLogin, aPass, inMemFileSystem, inMemCompressed, useNIO) : DB

Creates a DB object instantiated with an in-memory database for the given name. Optionally you can  specify that you don't want it to close on db.close (but all data will be lost on exiting OpenAF). Optionally you can also specify aLogin and aPass. This is a H2 database so do check more documentation on http://www.h2database.com/.  Also optionally you can specify if you want the in-memory database to be file based (inMemFileSystem) which  is slower than normal; to be compressed (inMemCompressed) which is slower than normal and inMemFileSystem; to store data outside the VM's heap (useNIO). Do note that if inMemFileSystem and inMemCompressed are selected only inMemCompressed will be used. And useNIO will only affect inMemFileSystem or inMemCompressed options.

createDBServer

createDBServer(aFile, aPort, aLogin, aPass) : DB

Creates a DB object instantiated with a server based H2 database, on the provided aPort (defaults to 9090), for the aFile provided. Optionally you can use aLogin and aPass(word).

csv.fromArray2File

csv.fromArray2File(anArray, aFile, withHeadersOrStreamFormat) : Number

Tries to wirte anArray to aFile. If withHeadersOrStreamFormat is provided, if an array it will  be interpreted as the files of headers otherwise as the new streamFormat object to use.

csv.fromFile2Array

csv.fromFile2Array(aFile, withHeadersOrStreamFormat) : Array

Tries to read a CSV file and convert it into an array. If withHeadersOrStreamFormat is provided, if an array it will  be interpreted as the files of headers otherwise as the new streamFormat object to use.

deleteFromArray

deleteFromArray(anArray, anIndex) : Array

Deletes the array element at anIndex from the provided anArray. Returns the new array with the element removed.

descType

descType(aObject) : String

Given aObject will try to return the apparent type withing: undefined, null, bytearray, javaclass, java, boolean, array, number, string, function, date, map and object.

dumpLog

dumpLog() : Array

Returns an array with collected log messages. Each entry has: d - timestamp; t - type; m - message.

exit

exit(anExitCode, force)

Immediately exits execution with the provided exit code.  Optionally force=true can be provided but no shutdown triggers will be executed (use only as a last option)

extend

extend([deep], target [, object1][, objectN]) : Object

Merges the contents of two or more objects together into the first object (target). If deep is specified the copy will be recursive. This function is equivalent to JQuery's extend function. See more in  https://api.jquery.com/jquery.extend/

findRandomOpenPort

findRandomOpenPort() : number

Tries to find a random open port on all network interfaces. Useful to start network servers on an available port.

flatten

flatten(aObject, noKeyValSeparation) : Array

Given aObject it will traverse it and create an array where each element will have a key and a val(ue). The key will  begin with a "." whenever it's a children key on aObject. This function is useful when trying to find specific keys or values across a Map. Optionally you can specify that you don't want each array element with the key and the value as separate elements but rather a directly as key and value.

forkOpenAF

forkOpenAF(aCommandLineArray, preCommandLineArray) : Promise

Starts another OpenAF with the same command line, if aCommandLineArray is not provided.  If aCommandLineArray is provided each array element will be use sequentially to build the command line to start a new OpenAF instance. preCommandLineArray can be used to  provide java arguments if defined.

genUUID

genUUID(useSecureRandom) : String

Generates and returns an UUID using a javascript algorithm (if needed you can refer to the  AF operation AF.KeyGenerator.GenerateUUID).

getChLog

getChLog() : Channel

Returns the current log dump channel.

getCPULoad

getCPULoad(useAlternative) : Number

Tries to obtain the current system load average (equivalent to top). If not available a negative value will be returned. Optionally you can specify to use the current system load if useAlternative = true. If the current system doesn't provide a load average it will fallback to the current system load.

getDistribution

getDistribution() : String

Returns the current distribution channel for this version of OpenAF.

getEnv

getEnv(anEnvironmentVariable) : String

Returns the current value of the operating system anEnvironmentVariable.

getEnvs

getEnvs() : Map

Returns a map of key and values with the operating system environment variables.

getEnvsDef

getEnvsDef(aEnv, aVar, aDefault, isJson) : Object

Given an environment variable aEnv name will check if a value is provided and return it if so. Otherwise it will check the value of aVar and return it if defined. If aVar is also not defined it will return aDefault. Optionally if isJson=true the value of the provided aEnv will be parsed from JSON.

getFromZip

getFromZip(aZipFile, aResource, inBytes, anEncoding, notInMemory) : anArrayOfBytes

Retrieves aResource, as anArrayOfBytes, from aZipFile. This resource can be inBytes = true or not and anEncoding can be provided. If the resource to retrieve is big you can use notInMemory = true for a slower but less memory retrieval.

getJavaStackTrace

getJavaStackTrace(anException) : Array

Given a javascript anException, if it's a wrapped or directly a java exception it will try to obtain the corresponding stack trace information in the form of an array.

getNumberOfCores

getNumberOfCores(realValue) : Number

Try to identify the current number of cores on the system where the script is being executed.

getOPackLocalDB

getOPackLocalDB() : Array

Returns an Array of maps. Each map element is an opack package description of the currently  locally, and per user, installed opack packages.

getOPackPath

getOPackPath(aPackage) : String

Given aPackage name (a opack name) will search the opack and if installed will return the filesystem path where the opack is installed.

getOPackPaths

getOPackPaths() : Array

Returns an array of strings with the paths for each of the installed opacks.

getOPackRemoteDB

getOPackRemoteDB() : Array

Returns an Array of maps. Each map element is an opack package description registered in the OpenAF central repository.

getOpenAFJar

getOpenAFJar() : String

Returns the complete filepath and name for the OpenAF jar file. (Shortcut for af.getOpenAFJar()). If __forcedOpenAFJar is defined the corresponding value will be used (useful when detection of the OpenAF jar doesn't work as expected or when OpenAF is embedded.

getOpenAFPath

getOpenAFPath() : String

Returns the filesystem path to the openaf.jar currently being used for the script execution.

getPid

getPid() : String

Tries to retrieve the current script execution operating system PID and returns it.

getVersion

getVersion() : String

Shortcut for the af.getVersion (see more af.getVersion) function. Will return the current version of OpenAF being used.

hmacSHA1

hmacSHA1(data, key, toHex) : ArrayOfBytes

Given data and a key will calculate the hash-based message authentication code (HMAC) using the SHA1 hash function. Optionally if toHex = true the output will be converted to hexadecimal lower case.

hmacSHA256

hmacSHA256(data, key, toHex) : ArrayOfBytes

Given data and a key will calculate the hash-based message authentication code (HMAC) using the SHA256 hash function. Optionally if toHex = true the output will be converted to hexadecimal lower case.

hmacSHA384

hmacSHA384(data, key, toHex) : ArrayOfBytes

Given data and a key will calculate the hash-based message authentication code (HMAC) using the SHA384 hash function. Optionally if toHex = true the output will be converted to hexadecimal lower case.

hmacSHA512

hmacSHA512(data, key, toHex) : ArrayOfBytes

Given data and a key will calculate the hash-based message authentication code (HMAC) using the SHA512 hash function. Optionally if toHex = true the output will be converted to hexadecimal lower case.

includeOPack

includeOPack(aOPackName, aMinVersion)

Ensures that aOPackName is installed. Optionally you can provide a minimal opack version. If the opack is not installed, can't be installed or cannot be updated to a version bigger or equal to aMinVersion an exception will be thrown.

inherit

inherit(Child, Parent)

Associates a Child object to a Parent simulating a inheritance relationship. This is done by copying the Parent prototype to the Child prototype. This is similar to "Parent.call(this, arg1, arg2)"

io.isBinaryFile

io.isBinaryFile(aFile, confirmLimit) : boolean

Tries to determine if the provided aFile is a binary or text file by checking the first 1024 chars (limit can be changed using confirmLimit). Returns true if file is believed to be binary. Based on the function isBinaryArray.

io.listFilesTAR

io.listFilesTAR(aTARfile, isGzip) : Array

Given aTARfile (or output stream (with isGzip = true/false)) will return an array with the TAR file entries. Each entry will have: isDirectory (boolean), isFile (boolean), canonicalPath (string), filepath (string), filename (string), size (number), lastModified (date), groupId (string), group (string), userId (string) and user (string).

io.onDirEvent

io.onDirEvent(aPath, aFn, aFnErr) : Promise

Given aPath of a directory will return a promise ($do) that, for every create, modify or delete event that happens on aPath it will call aFn with two parameters: kind and filename.  The 'kind' string can be one of four events: ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY, OVERFLOW (meaning events were lost or discarded). The 'filename' represents the filename affected. Optionally aFnErr function can be provided to handle any errors and, in case aPath no longer exists, aFnErr will be called with the string "ENTRY_NA". Example:

var p = io.onDirEvent("myDir", (kind, filename) => {
   log("Event '" + kind + "' on '" + filename + "'");
}, e => {
   if (isString(e) && e == "ENTRY_NA") logWarn("myDir no longer exists."); else logErr(e);
});

$doWait(p);


io.pipeCh

io.pipeCh(aFunc)

Starts a wait on stdin calling aFunc everytime a character is sent to stdin. The wait cycle breaks when aFunc returns true.

io.pipeLn

io.pipeLn(aFunc)

Starts a wait on stdin calling aFunc everytime a line is sent to stdin. The wait cycle breaks when aFunc returns true.

io.readFileBytesRO

io.readFileBytesRO(aFile) : ByteArray

Tries to read aFile in read-only mode (even if being used by another process) and returns the corresponding byte array.

io.readFileJSON

io.readFileJSON(aJSONFile) : Object

Tries to read aJSONFile into a javascript object.

io.readFileTAR2Stream

io.readFileTAR2Stream(aTARfile, isGzip, aFunc)

Given aTARFile (or stream) will call aFunc(tion) with the corresponding Java TAR input stream. If aTARFile is a stream you should specify with isGzip = true/false if it has been "gzipped". Note: for direct usage use io.readFileTARStream

io.readFileTARBytes

io.readFileTARBytes(aTARFile, aFilePath, isGzip) : ByteArray

Given aTARFile (or stream) will try to retrieve aFilePath and return the corresponding byte array. If aTARFile is a stream you should specify with isGzip = true/false if it has been "gzipped".

io.readFileTARStream

io.readFileTARStream(aTARFile, aFilePath, isGzip, aFunc)

Given aTARFile (or stream) will try to retrieve aFilePath and call aFunc(tion) with the corresponding Java input stream. If aTARFile is a stream you should specify with isGzip = true/false if it has been "gzipped".

io.readFileYAML

io.readFileYAML(aYAMLFile) : Object

Tries to read aYAMLFile into a javascript object.

io.readLinesNDJSON

io.readLinesNDJSON(aNDJSONFile, aFuncCallback, aErrorCallback, anEncoding)

Opens aNDJSONFile (a newline delimited JSON) (a filename or an input stream) as a stream call aFuncCallback with each parse JSON. If aFuncCallback returns true the cycle will be interrupted. For any parse error it calls the aErrorCallback  with each exception.

io.readStreamJSON

io.readStreamJSON(aJSONFile, aValFunc) : Map

Reads a JSON file (aJSONFile) without loading all structures to memory (usefull to handling large JSON files). The aValFunc receives a single string argument with the current JSON path being processed (for example $.log.entries[123].request), where "$" is the root of the JSON document. When aValFunc returns true the current JSON structure is recorded in memory. If aValFunc is not defined it will return true for all paths. Returns the JSON structure recorded in memory.

Example:

   var amap = io.readStreamJSON("someFile.har",
                                path => (/^\$\.log\.entries\[\d+\]\.request/).test(path))


io.writeFileJSON

io.writeFileJSON(aJSONFile, aObj, aSpace)

Tries to write a javascript aObj into a aJSONFile with an optional aSpace.

io.writeFileTAR4Stream

io.writeFileTAR4Stream(aTARfile, isGzip, aFunc)

Given aTARfile (or output stream (with isGzip = true/false)) will call aFunc with the Java TAR output stream. Note: for direct usage use io.writeFileTARStream

io.writeFileTARBytes

io.writeFileTARBytes(aTARfile, aFilePath, isGzip, aArrayBytes)

Given aTARfile (or output stream (with isGzip = true/false)) will write aArrayBytes into aFilePath in the TAR file/stream. Note: for multiple files use io.writeFileTARStream

io.writeFileTARStream

io.writeFileTARStream(aTARfile, isGzip, aFunc, aDefaultMap)

Given aTARfile (or output stream (with isGzip = true/false)) will call aFunc(tion) providing, as argument, a writer function with three arguments: aFilePath, a Java input stream for the contents and the modification date for the target file.  Optionally aDefaultDate can be provided to be used whenever a date is not provided or for folders.

io.writeFileYAML

io.writeFileYAML(aYAMLFile, aObj, multidoc)

Tries to write a javascript aObj into a aYAMLFile. If multiDoc = true and aJson is an array the output will be multi-document.

io.writeLineNDJSON

io.writeLineNDJSON(aNDJSONFile, aObj, aEncode)

Writes aObj into a single line on aNDJSONFile (newline delimited JSON) (or an output stream). Optionally you can provide an encoding (only is a string filename is provided)

ioSetNIO

ioSetNIO(aFlag)

Sets the default use of NIO in ioStream* functions. It's overridden if the ioStream* function defines a value for the useNIO function argument.

ioStreamCopy

ioStreamCopy(aOutputStream, aInputStream)

Copies the contents of a Java aInputStream to a Java aOutputStream. The two streams will  be closed in the end.

ioStreamRead

ioStreamRead(aStream, aFunction, aBufferSize, useNIO, encoding)

Given a Java input or output stream helps to read strings by using aFunction with a string argument for each buffer size  (default 1024 characters). Optionally you can provide a different aBufferSize (default: 1024) and/or also specify that  Java NIO functionality should be used. If aFunction returns true the read operation stops.

ioStreamReadBytes

ioStreamReadBytes(aStream, aFunction, aBufferSize, useNIO)

Given a Java input or output stream helps to read an array of bytes by using aFunction with anArrayOfBytes argument for  each buffer size (default 1024 characters). Optionally you can provide a different aBufferSize (default: 1024) and/or  also specify that Java NIO functionality should be used. If aFunction returns true the read operation stops.

ioStreamReadLines

ioStreamReadLines(aStream, aFunctionPerLine, aSeparator, useNIO, anEncoding)

Given aStream will read the entire buffer and call aFunctionPerLine(withALine) per each \n found. Aditionally you can specify a different aSeparator for each line other than "\n".  If aFunctionPerLine returns true the read operation stops. Optionally you can also provide anEncoding.

ioStreamWrite

ioStreamWrite(aStream, aString, aBufferSize, useNIO)

Given a Java input or output stream helps to write aString into the same. Optionally you can provide a different aBufferSize (default: 1024) and/or also specify that Java NIO functionality should be used.

ioStreamWriteBytes

ioStreamWriteBytes(aStream, aArrayBytes, aBufferSize, useNIO)

Given a Java input or output stream helps to write aArrayBytes into the same. Optionally you can provide a different aBufferSize (default: 1024) and/or also specify that Java NIO functionality should be used.

isArray

isArray(aObj) : boolean

Returns true if aObj is an array, false otherwise.

isBinaryArray

isBinaryArray(anArrayOfChars, confirmLimit, previousResult) : boolean

Tries to determine if the provided anArrayOfChars is binary or text. The detection is performed with the first 1024 chars ( that can be changed if confirmLimit is provided). Additionally is possible to link multiple calls providing the last result on previousResult for multiple subsequences of a main array of chars sequence. Should work for utf8, iso-8859-1, iso-8859-7, *  windows-1252 and windows-1253. Returns true if file is believed to be binary.

isBoolean

isBoolean(aObj) : boolean

Returns true if aObj is boolean, false otherwise

isByteArray

isByteArray(aObj) : boolean

Returns true if aObj is a byte array object, false otherwise.

isDate

isDate(aObj) : boolean

Returns true if aObj is a date, false otherwise

isDecimal

isDecimal(aObj) : boolean

Returns true if aObj has a decimal component.

isDef

isDef(aObject) : boolean

Returns true if the provided aObject is defined as a javascript variable. It will return false otherwise. (see also isUnDef). Shortcut for the isDefined function.

isDefined

isDefined(aObject) : boolean

Returns true if the provided aObject is defined as a javascript variable. It will return false otherwise. (see also isUndefined)

isFunction

isFunction(aObj) : boolean

Returns true if aObj is a function, false otherwise;

isInteger

isInteger(aObj) : boolean

Returns true if aObj doesn't have a decimal component.

isJavaClass

isJavaClass(aObj) : boolean

Return true if aObj is a Java class, false otherwise

isJavaException

isJavaException(aObject) : boolean

Determines if aObject is a java exception object or a javascript exception with an embeeded java exception.

isJavaObject

isJavaObject(aObj) : boolean

Returns true if aObj is a Java object, false otherwise

isMap

isMap(aObj) : boolean

Returns true if aObj is a map, false otherwise.

isNull

isNull(aObj) : boolean

Returns true if aObj is null, false otherwise

isNumber

isNumber(aObj) : boolean

Returns true if aObj can be a number, false otherwise

isObject

isObject(aObj) : boolean

Returns true if aObj is an object, false otherwise;

isString

isString(aObj) : boolean

Returns true if aObj is a string, false otherwise

isTNumber

isTNumber(aObj) : boolean

Returns true if aObj is of type number, false otherwise

isUnDef

isUnDef(aObject) : boolean

Returns true if the provided aObject is undefined as a javascript variable. It will return false otherwise. (see also isDef). Shortcut for the isUndefined function.

isUndefined

isUndefined(aObject) : boolean

Returns true if the provided aObject is undefined as a javascript variable. It will return false otherwise. (see also isDefined)

isUUID

isUUID(aObj) : boolean

Returns true if aObj is an UUID.

javaRegExp

javaRegExp(text).test(regExp, mods) : boolean

Mimics, using Java, the javascript RegExp test function. Supported mods are "g", "m" and "i" or the java integer composed  mods. Returns the corresponding boolean value.

jsonParse

jsonParse(aString, alternative, unsafe, ignoreNonJson) : Map

Shorcut for the native JSON.parse that returns an empty map if aString is not defined, empty or unparsable.

listFilesRecursive

listFilesRecursive(aPath, usePosix) : Map

Performs the io.listFiles function recursively given aPath. The returned map will be equivalent to the io.listFiles function (see more in io.listFiles). Alternatively you can specify to usePosix=true and it will add to the map the owner, group and full permissions of each file and folder.

load

load(aScript)

Provides a shortcut for the af.load function (see more af.load). If the provided aScript is not found this function will try to search the script on the openaf.jar::js folder and on the installed opacks. If it doesn't find the provided aScript it will throw an exception "Couldn't find aScript".

loadCompiled

loadCompiled(aScript, dontCompile, dontLoad) : boolean

Tries to load an OpenAF script as a compiled class. If a compiled class file doesn't exist in the same path  it will try to compile and load from the compiled code. If a compiled class file exists in the same path it will recompile it if the modified date of the original aScript is newer than the class.  If the class was already loaded or can't be loaded it will return false. Returns true otherwise. Optionally you can force to not compile dontCompile=true or just to compile with dontLoad=true

loadCompiledLib

loadCompiledLib(aLibClass, forceReload, aFunction, withSync) : boolean

Loads the corresponding compiled javascript library class and keeps track if it was already loaded or not (in __loadedLibs). Optionally you can force reload and provide aFunction to execute after the successful loading. Returns true if successfull, false otherwise.

loadDBInMem

loadDBInMem(aDB, aFilename)

Tries to load to a in-memory database, aDB object, previously created by the function createDBInMem from a SQL aFilename probably created by the function persistDBInMem.

loadDiff

loadDiff()

Loads the JsDiff javascript library into scope (check https://github.com/kpdecker/jsdiff).

loadExternalJars

loadExternalJars(aPath, dontCheck)

Given a path will try to add to the current classpath (using af.externalAddClasspath) all files with the extension '.jar'. Optionally you can override the dontCheck if it was loaded with this command previously.

loadFuse

loadFuse()

Loads the FuseJS javascript library into scope.

See more in: http://fusejs.io/

loadHandlebars

loadHandlebars()

Loads the Handlebars javascript library into scope. Example:

loadHandlebards();
var source = "<m>\t<s name=\"\"></s>\n\n</m>";
var data = { "lines": [ { "name": "n1", "value": "v1" }, { "name": "n2", "value": "v2" } ] };
var template = Handlebars.compile(source);
print(template(data));
data.lines.push({"name": "n3", "value": "v3"});
print(template(data));

See more documentation in: http://handlebarsjs.com/


loadHelp

loadHelp()

Loads into scope the ODoc objects for documentation support.

loadJSYAML

loadJSYAML()

Loads the JS-YAML library.

loadLib

loadLib(aLib, forceReload, aFunction) : boolean

Loads the corresponding javascript library and keeps track if it was already loaded or not (in __loadedLibs). Optionally you can force reload and provide aFunction to execute after the successful loading. Returns true if successfull, false otherwise.

loadLodash

loadLodash()

Loads the loadash javascript library.

See more in https://lodash.com/docs

loadPy

loadPy(aPyScript, aInput, aOutputArray, dontStop) : Map

Provides a shortcut for the $py function (see more in $py). If the provided aPyScript is not found this function will try to search the python script on the installed opacks. If it doesn't find the provided aScript it will throw an exception "Couldn't find aPyScript". If aInput map is defined each entry will be converted into python variables. If aOutputArray is defined the python variables string names in the array will be returned as a map.

loadUnderscore

loadUnderscore()

Loads the Underscore javascript library into scope (using the loadash alternative).

See more in: http://underscorejs.org and https://lodash.com/docs

log

log(msg, formatOptions)

Outputs to the current stdout a line composed of the current date, indication of INFO and the provided msg. Optionally you can provide a formatOptions map for overriding the defaults from setLog. Note: you can use startLog, stopLog and dumpLog to keep an internal record of theses messages.

logErr

logErr(msg, formatOptions)

Outputs to the current stderr a line composed of the current date, indication of ERROR and the provided msg. Optionally you can provide a formatOptions map for overriding the defaults from setLog. Note: you can use startLog, stopLog and dumpLog to keep an internal record of theses messages.

lognl

lognl(msg, formatOptions)

Outputs to the current stdout, without a new line, a sentence composed of the current date, indication of INFO and the provided msg. Optionally you can provide a formatOptions map for overriding the defaults from setLog. Note: you can use startLog, stopLog and dumpLog to keep an internal record of theses messages.

logWarn

logWarn(msg, formatOptions)

Outputs to the current warning in a line composed of the current date, indication of WARN and the provided msg. Optionally you can provide a formatOptions map for overriding the defaults from setLog. Note: you can use startLog, stopLog and dumpLog to keep an internal record of theses messages.

lprint

lprint(aStr, withColor)

"SLONs" and prints the aStr to the stdout (with a new line on the end)

lprintErr

lprintErr(aStr, withColor)

"SLONs" and prints the aStr to the stderr (with a new line on the end)

lprintErrnl

lprintErrnl(aStr, withColor)

"SLONs" and prints the aStr to the stderr (without adding a new line on the end)

lprintnl

lprintnl(aStr, withColor)

"SLONs" and prints the aStr to the stdout (without adding a new line on the end)

mapArray

mapArray(anArray, selectors, limit) : Array

Helper functions to map selectors (inputs for ow.obj.getPath) from anArray returning the filtered array. IF selectors is a string or just one array entry the result will be an array with just the value results. Optionally you can also limit the number of results to the first "limit" (number).

md2

md2(anObject) : String

Will return of the MD2 in hexadecimal format for a given anObject.
For files you can provide a file stream: var s = io.readFileStream(getOpenAFJar()); md2(s); s.close()

md5

md5(anObject) : String

Will return of the MD5 in hexadecimal format for a given anObject.
For files you can provide a file stream: var s = io.readFileStream(getOpenAFJar()); md5(s); s.close()

merge

merge(anObjectA, anObjectB) : aMergedObject

Merges a JavaScript object A with a JavaScript object B a returns the result as a new object.

newFn

newFn() : Function

Builds a new Function handling any debug needs if necessary.

newJavaArray

newJavaArray(aJavaClass, aSize) : JavaArrayClass

Creates a new Java Array object for the aJavaClass type for a provided aSize.

Examples:

newJavaArray(java.lang.String, 5);
newJavaArray(java.lang.Integer.TYPE, 2);


now

now() : Number

Will return the current system time in milliseconds.

nowE

nowE() : Number

Returns the current epoch time in seconds.

nowNano

nowNano() : Number

Will return the current system time in nanoseconds.

nowNanoE

nowNanoE() : Number

Returns the current epoch time in nanoseconds.

nowTZ

nowTZ() : Number

Returns the same as now() but adjusted with the local timezone offset.

nowUTC

nowUTC() : Number

Will return the current system time in milliseconds.

objOrStr

objOrStr(aObj, aStr) : String

Given aObj (a map or an array) will try to assess if aStr is an aObj key (using $$.get). If yes, it will return the corresponding aObj value otherwise it will return aStr.

oJob

oJob(aFile, args, aId, aOptionsMap)

Shortcut for oJobRunFile return the result on the variable __pm. Keep in mind that it doesn't support concurrency.

oJobRun

oJobRun(aJson, args, aId)

Runs a oJob from aJson definition with the provided args (arguments). Optionally you can provide aId to segment these specific jobs.

oJobRunFile

oJobRunFile(aFile, args, aId, aOptionsMap, isSubJob)

Runs a oJob aFile with the provided args (arguments). Optionally you can provide aId to segment these specific jobs.

oJobRunFileAsync

oJobRunFileAsync(aFile, args, aId, aOptionsMap, isSubJob) : oPromise

Runs a oJob aFile async with the provided args (arguments). Optionally you can provide aId to segment these specific jobs. Returns the corresponding promise.

oJobRunJob

oJobRunJob(aJob, args, aId, waitForFinish) : boolean

Shortcut for ow.oJob.runJob. Please see help for ow.oJob.runJob. Optionally you can provide aId to segment this specific job. If aJob is a string it will try to retrieve the job from the jobs channel. Returns true if the job executed or false otherwise (e.g. failed deps).

oJobRunJobAsync

oJobRunJobAsync(aJob, args, aId) : oPromise

Creates an oPromise to run the same arguments for oJobRunJob thus executing the job async. Returns the generate oPromise.

oPack

oPack(aParameters)

Tries to execute oPack with aParameters string. These string is equivalent to the opack command-line commands. aParameters = "help" will, for example, print all the help information.

opackExec

opackExec(aPackageName)

Tries to execute the provided opack aPackageName.

openInBrowser

openInBrowser(anURL) : Boolean

Tries to open anURL on the current OS desktop browser. Returns false if it's unable to open the OS desktop browser for some reason.

oPromise

oPromise(aFunction, aRejFunction) : oPromise

Custom Promise-like implementation. If you provide aFunction, this aFunction will be executed async in a thread and oPromise object will be immediatelly returned. Optionally this aFunction can receive a resolve and reject functions for to you use inside aFunction to provide a result with resolve(aResult) or an exception with reject(aReason). If you don't call theses functions the returned value will be used for resolve or any exception thrown will be use for reject. You can use the "then" method to add more aFunction that will execute once the previous as executed successfully (in a stack fashion). The return/resolve value from the  previous function will be passed as the value for the second. You can use the "catch" method to add aFunction that will receive a string or exception for any exception thrown with the reject functions. You can also provide a aRejFunction that works like a "catch" method as previously described.

oPromise.all

oPromise.all(anArray) : oPromise

Returns an oPromise that will be resolved when all oPromise part of the anArray are fullfiled. If any of the oPromises fails/rejects the returned oPromise will also be rejected/fail.

oPromise.catch

oPromise.catch(onReject) : oPromise

Adds onRejected to the current oPromise stack to execute if the previous function was rejected and receives the reason as parameter.

oPromise.race

oPromise.race(anArray) : oPromise

Returns an oPromise that will be resolved when any oPromise part of the anArray is fullfiled. If any of the oPromises fails/rejects the returned oPromise will also be rejected/fail.

oPromise.then

oPromise.then(onFulfilled, onRejected) : oPromise

Adds onFulfilled to the current oPromise stack to execute if the previous function was resolved successfully and receives the resolve/return value as parameter. Also adds onRejected to the current oPromise stack to execute if the previous function was rejected and receives the reason as parameter.

ow.loadAI

ow.loadAI()

Loads OpenWrap AI functionality.

ow.loadCh

ow.loadCh()

Loads OpenWrap channels functionality.

ow.loadDebug

ow.loadDebug()

Loads OpenWrap debug functionality.

ow.loadDev

ow.loadDev()

Loads OpenWrap dev functionality. Basically functions being tested.

ow.loadFormat

ow.loadFormat()

Loads OpenWrap format functionality. Basically functions to help with the formatting of strings, numbers, dates, etc...

ow.loadJava

ow.loadJava()

Loads OpenWrap Java functionality.

ow.loadMetrics

ow.loadMetrics()

Loads OpenWrap Metrics functionality. Basically functions to wrap access to server functionality.

ow.loadNet

ow.loadNet()

Loads OpenWrap net functionality. Basically functions for net.

ow.loadObj

ow.loadObj()

Loads OpenWrap object functionality.

ow.loadOBook

ow.loadOBook()

Loads OpenWrap oBook functionality.

ow.loadOJob

ow.loadOJob()

Loads OpenWrap oJob functionality.

ow.loadPython

ow.loadPython()

Loads OpenWrap Python functionality.

ow.loadSec

ow.loadSec()

Loads OpenWrap sec functionality. Basically functions for sec.

ow.loadServer

ow.loadServer()

Loads OpenWrap Server functionality. Basically functions to wrap access to server functionality.

ow.loadTemplate

ow.loadTemplate()

Loads OpenWrap template functionality. Basically functions to wrap access to Handlebars functionality.

ow.loadTest

ow.loadTest()

Loads OpenWrap test functionality. Basically functions to unit test other functionality.

parallel

parallel(aFunction, numThreads, aAggFunction, aControlMap) : Object

Executes a function in a specific number of threads (each function will receive a corresponding uuid).  The returned result of each function execution is kept in an array. If no aAggFunction is provided this array will be returned, otherwise the array will be passed to the aAggFunction for processing and the corresponding result of aAggFunction will be returned. If no numThreads is provided, the number of threads will be automatically determined. Optionally you can provide a empty map as aControlMap that it will be filled with aControlMap.__threads with the  threads object, the aControlMap.__numThreads for the number of threads in use and a thread __uuid list.

parallel4Array

parallel4Array(anArray, aFunction, numThreads, aControlMap) : Object

Given anArray, divides it in subsets for processing in a specific number of threads. In each thread aFunction(aValue) will be executed for each value in sequence. An array with all the aFunction results will be returned. If no numThreads is  provided, the number of threads will be automatically determined. Optionally you can provide a empty map as aControlMap that it will be filled with aControlMap.__threads with the threads object, the aControlMap.__numThreads for the number of threads in use and a thread __uuid list. Example:

var count = 0;
var ctrl = {};
var res = parallel4Array(thingsToProcess,
   function(aValue) {
      ctrl.__threads.sync(function() { count++; }) // Sync access to a shared variable
      return processValue(aValue);
   },
   undefined,
   ctrl
);

parallelArray

parallelArray(anArray, aReduceFunction, initValue, aAggFunction, numThreads, aControlMap) : Object

Given anArray, divides it in subsets for processing in a specific number of threads. In each thread aReduceFunction(pr, cv, i, arr), where pr = previous result, cv = current value, i = index and arr = array subset, will be executed for each value in sequence. The pr value for the first execution on each thread will have the value initValue if provided. The returned result, in each thread, will be placed into an array. If aAggFunction is defined, the resulting array will be passed to the aAggFunction for processing and the corresponding result of aAggFunction will be returned. If no numThreads is provided, the number of threads will be  automatically determined. Optionally you can provide a empty map as aControlMap that it will be filled with aControlMap.__threads with the threads object, the aControlMap.__numThreads for the number of threads in use and a thread __uuid list.

persistDBInMem

persistDBInMem(aDB, aFilename) : Array

Tries to persist a in-memory database, aDB object, previously created by the function createDBInMem into a SQL aFilename. This can later be used to load again using the loadDBInMem function.

pidCheck

pidCheck(aPid) : Boolean

Verifies if aPid is running (returning true) or not (returning false).

pidCheckIn

pidCheckIn(aFilename) : boolean

Uses the contents of aFilename to determine if there is an existing process running with the pid  recorded on the file. If it's running it will return false, if not it will return true and record the current pid on the aFilename. The function pidCheckOut will be added as a hook to run on the  end of the current process.

pidCheckOut

pidCheckOut(aFilename) : boolean

Removes the pid information from aFilename and deletes the file if possible.  If successful returns true, if not returns false.

pidKill

pidKill(aPidNumber, isForce) : boolean

Tries to terminate a process with aPidNumber. If successful it will return true otherwise it will return false. If necessary, a boolean true value on isForce, will force the termination of the process.

plugin

plugin(aPlugin, aClass)

Provides a shortcut for the af.plugin function. It also provides a shortcut for plugins with the java package "openaf.plugins" (e.g. af.plugin("openaf.plugins.HTTP") is the same as plugin("HTTP")). In alternative you can provide plugin aClass if it's different from aPlugin.

pods.declare

pods.declare(aId, exports)

Declares a new module, aId, as the provided exports literal.

pods.define

pods.define(aId, aDepsArray, aFactoryFunction)

Defines a new module given aId, aDepsArray with depend id modules and a factory function.

pods.require

pods.require(aIds, aCallbackFunction)

Requires a module or a list of modules and all of its dependencies. Optionally you can provide aCallbackFunction to inject the required modules into.

print

print(aStr)

Prints the aStr to the stdout (with a new line on the end) (example: print("hello world!"))

printBars

printBars(aFormatString, hSize, aMax, aMin, aIndicatorChar, aSpaceChar) : String

Produces horizontal bars given aFormatString, a hSize (horizontal max size), aMax (the axis max value) and aMin  (the axis min value). The aFormatString should be composed of "<units> [<function[:color][:legend]> ...]":

   The units can be: int, dec1, dec2, dec3, dec, bytes and si;
   Each function should return the corresponding current value (optionally it can be a number directly);
   Optionally each color should use any combinations similar to ansiColor (check 'help ansiColor');
   Optionally each legend, if used, will be included in a bottom legend;


printChart

printChart(aFormatString, hSize, vSize, aMax, aMin, dColor) : String

Produces a line chart given aFormatString, a hSize (horizontal max size), a vSize (vertical max size), aMax (the axis max value) and aMin  (the axis min value). The aFormatString should be composed of "<dataset> <units> [<function[:color][:legend]> ...]":

   The dataset should be an unique name (data can be cleaned with ow.format.string.dataClean);
   The units can be: int, dec1, dec2, dec3, dec4, dec, bytes and si;
   Each function should return the corresponding current value (optionally it can be a number directly);
   Optionally each color should use any combinations similar to ansiColor (check 'help ansiColor');
   Optionally each legend, if used, will be included in a bottom legend;

   If function "-min" it will overwrite the aMin
   If function "-max" it will overwrite the aMax
   If function "-hsize" it will overwrite the hSize
   If function "-vsize" it will overwrite the vSize


printErr

printErr(aStr)

Prints the aStr to the stderr (with a new line on the end) (example: printErr("Hupps!! A problem!"))

printErrnl

printErrnl(aStr)

Prints the aStr to the stderr (without adding a new line on the end) (example: printErrnl("Hupps!! A problem!"))

printMap

printMap(aMap, aWidth, aTheme, useAnsi) : String

Returns a ASCII map representation of aMap optionally with a give aWidth, aTheme and/or useAnsi boolean. aTheme can be "utf" or "plain" depending on the terminal capabilities.

printnl

printnl(aStr)

Prints the aStr to the stdout (without adding a new line on the end) (example: printnl("hello world!"))

printTable

printTable(anArrayOfEntries, aWidthLimit, displayCount, useAnsi, aTheme, aBgColor, wordWrap, useRowSep, bandRows) : String

Returns a ASCII table representation of anArrayOfEntries where each entry is a Map with the same keys. Optionally you can specify aWidthLimit, useAnsi, bandRows and/or aBgColor. If you want to include a count of rows just use displayCount = true. If useAnsi = true you can provide a theme (e.g. "utf" or "plain")

printTree

printTree(aObj, aWidth, aOptions) : String

Given aObj(ect) will return a tree with the object elements. Optionaly you can specificy aWidth and/or aOptions: noansi (boolean) no ansi character sequences, curved (boolean) for UTF curved characters, wordWrap (boolean) to wrap long string values, compact (boolean) to compact tree lines, fullKeySize (boolean) to pad the each entry key, fullValSize (boolean) to pad the entire key and value and withValues (boolean) to include or not each key values

printTreeOrS

printTreeOrS(aObj, aWidth, aOptions) : String

Tries to use printTree with the provided arguments. In case printTree throws an exception (like insufficient width) if will fallback to colorify or stringify (if the noansi option is true).

processExpr

processExpr(aSeparator, ignoreCase, aSource) : Map

Will access the current contents of the OpenAF -e argument (if a different aSource is not defined) looking for pairs of key values in the form "a=5;b=1;c=xpto\\;" and will produce a Map with { "a": 5, "b": 1, "c": "xpto;" }. If no aSeparator is provided ';' will be assumed. __pmIn values will be also included. If ignoreCase = true all keys will be lower cased.

quickSort

quickSort(items, aCompareFunction) : Array

Performs a quick sort algorithm on the items array provided. Optionally aCompareFunction can be provided. The sorted array will be returned.

range

range(aCount, aStart, aStep) : Array

Generates an array with aCount of numbers starting at 1. Optionally you can provide a different aStart number and/or aStep increment.

repeat

repeat(nTimes, aStr) : String

Will build a string composed of aStr repeated nTimes.

require

require(aScript) : Object

Will try to load aScript from the directories specified in the loadRequire function (by default all opack directories plus the current working directory). Returns the exports object manipulated in aScript (note: results are cached)

requireCompiled

requireCompiled(aScript, dontCompile, dontLoad) : Object

Loads aScript, through require, previously compile or it will be compiled if (dontCompile is not true). IF dontLoad = true the module exports won't be returned.

restartOpenAF

restartOpenAF(aCommandLineArray, preCommandLineArray)

Terminates the current OpenAF execution and tries to start a new with the same command line, if aCommandLineArray is not provided. If aCommandLineArray is provided each array element will be use sequentially to build the command line to start a new OpenAF instance.  preCommandLineArray can be used to provide java arguments if defined.

saveHelp

saveHelp(aPath, aMapOfFiles)

Given aMapOfFiles, or basically an array of JavaScript or Java source filenames, each file will  be processed for ODoc XML tags and the corresponding ODoc database will be generated on the  provided aPath suitable for offline use.

saveHelpWeb

saveHelpWeb(aPath, aMapOfFiles)

Given aMapOfFiles, or basically an array of JavaScript or Java source filenames, each file will  be processed for ODoc XML tags and the corresponding ODoc database will be generated on the  provided aPath suitable for online use.

searchArray

searchArray(anArray, aPartialMap, useRegEx, ignoreCase, useParallel) : Array

Shortcut to ow.obj.searchArray.

searchHelp

searchHelp(aTerm, aPath, anArrayOfIds) : Map

Searches the OpenAF ODoc help system for a specific term. Optionally you can provide a path of where to  search for ODoc help files. If an exact match is found the function will return an array with a single a map with the corresponding ODoc id, key, fullkey and text. If no exact match is found the function will return an array of alternative matches or an empty array if no alternatives are found. Optionally you can also restrict by anArrayOfIds.

searchKeys

searchKeys(aObject, aSearchKey, useCase, actFunc) : Map

Traverses aObject looking for key matches, ignoring case if useCase is true, of the regular expression aSearchKey. Each element found is added to the returned Map. The element key will represent the path from aObject to it. Tip: The actFunc  can use ow.obj.setPath to replace a value: "(key, value, path) => { ow.obj.setPath(aObject, path + '.' + key, replaceValue); }"

searchValues

searchValues(aObject, aSearchValue, useCase, actFunc) : Map

Traverse aObject looking for value matches, ignoring case if useCase is true, of the regular expression aSearchKey.  Each value found is added to the returned Map linked to the path representation of where it was found. Optionally you can provide an actFunc that receives the key, value and path. Tip: The actFunc can use ow.obj.setPath to  replace a value: "(key, value, path) => { ow.obj.setPath(aObject, path + '.' + key, replaceValue); }"

setLog

setLog(aMap)

Sets the current log output settings:

- off        (boolean) Turns off output to stdout/stderr
- offInfo    (boolean) Turns off output of INFO
- offError   (boolean) Turns off output of ERROR
- offWarn    (boolean) Turns off output of WARN
- dateFormat (string)  ow.format.fromDate format for date
- dateTZ     (string)  Time zone to use with ow.format.fromDate
- separator  (string)  String to use as separator
- async      (boolean) Run in async mode
- profile    (boolean) Gathers memory and system load stats
- format     (string)  Sets the format to output logs (e.g. json, slon, human)


setOfflineHelp

setOfflineHelp(aBoolean)

Forces help (odoc) to be retrieved locally (if aBoolean is true) or reestablishes the normal behaviour of retrieving from online first (if aBoolean is false)

sh

sh(commandArguments, aStdIn, aTimeout, shouldInheritIO, aDirectory, returnMap, callbackFunc, anEncoding, dontWait, envsMap) : String

Tries to execute commandArguments (either a String or an array of strings) in the operating system as a shortcut for  AF.sh except that it will run them through the OS shell. Optionally aStdIn can be provided, aTimeout can be defined  for the execution and if shouldInheritIO is true the stdout, stderr and stdin will be inherit from OpenAF. If  shouldInheritIO is not defined or false it will return the stdout of the command execution. It's possible also to  provide a different working aDirectory. If envsMap (a map of strings) is defined the environment variables will be replaced by envsMap. The variables __exitcode and __stderr can be checked for the command exit code and the stderr output correspondingly. In alternative if returnMap = true a map will be returned with stdout, stderr and exitcode. A callbackFunc can be provided, if shouldInheritIO is undefined or false, that will receive, as parameters, an output  stream, a error stream and an input stream (see help af.sh for an example). If defined the stdout and stderr won't be available for the returnMap if true.

sha1

sha1(anObject) : String

Will return of the SHA-1 in hexadecimal format for a given anObject.
For files you can provide a file stream: var s = io.readFileStream(getOpenAFJar()); sha1(s); s.close()

sha256

sha256(anObject) : String

Will return of the SHA-256 in hexadecimal format for a given anObject.
For files you can provide a file stream: var s = io.readFileStream(getOpenAFJar()); sha256(s); s.close()

sha384

sha384(anObject) : String

Will return of the SHA-384 in hexadecimal format for a given anObject.
For files you can provide a file stream: var s = io.readFileStream(getOpenAFJar()); sha384(s); s.close()

sha512

sha512(anObject) : String

Will return of the SHA-512 in hexadecimal format for a given anObject.
For files you can provide a file stream: var s = io.readFileStream(getOpenAFJar()); sha512(s); s.close()

showH2Console

showH2Console() : Console

Instantiates and returns a H2 Console object openning a browser (if possible) to interact with the H2 Console. With  the returned object you can later invoke .shutdown() or unload it from the console. Invoking a second time will result in a port bind error since it the first instance wasn't shutdown.

sleep

sleep(millis, shouldCheck)

Shortcut for af.sleep function. Will pause execution for a given period of time expressed in milliseconds. If shouldCheck is true it will enforce checking if the time has really passed or not.

sortMapKeys

sortMapKeys(aMap, moreLevels) : Map

Tries to sort the first level map keys returning the rewritten map.  If moreLevels=true it will try to recursively map sub maps.

splitArray

splitArray(anArray, numberOfParts) : Array

Returns the result of the split of anArray into equals numberOfParts (when possible). If numberOfParts is not provided the current result of getNumberOfCores() will be used.

splitBySeparator

splitBySeparator(aString, aSeparator) : Array

Will split aString using the provided aSeparator. If the aSeparator is escaped (for example if ';' is the aSeparator and  aString 'abc\\;def;123" only the second ';' will be considered.

splitBySepWithEnc

splitBySepWithEnc(text, separator, enclosures, includeEnclosures) : array

Given a text, a separator, a list of enclosures and a flag includeEnclosures, this function will split the text by the separator while ignoring the separator inside the enclosures. If includeEnclosures is true, the enclosures will be included in the result. If includeEnclosures is false, the enclosures will be removed from the result.

splitKVBySeparator

splitKVBySeparator(aString, aOptions) : Map

Given aString with multiple key/value entries will return a map with the same. Optionally you can provide aOptions:

   sep  - the key/value entries separator (defaults to " ")
   ksep - the key separator from a value (defaults to "=")
   esc  - the escape character (defaults to "\\")
   qto  - the quote character (defaults to "\"")
   nul  - the null representation (defaults to null)


sprint

sprint(aStr)

"Stringifies" and prints the aStr to the stdout (with a new line on the end) (example: sprint("hello world!"))

sprintErr

sprintErr(aStr)

"Stringifies" and prints the aStr to the stderr (with a new line on the end) (example: sprintErr("Hupps!! A problem!"))

sprintErrnl

sprintErrnl(aStr)

"Stringifies" and prints the aStr to the stderr (without adding a new line on the end) (example: sprintErrnl("Hupps!! A problem!"))

sprintnl

sprintnl(aStr)

"Stringifies" and prints the aStr to the stdout (without adding a new line on the end) (example: sprintnl("hello world!"))

startLog

startLog(externalLogging, hkItems)

Starts collecting log messages logged with log* functions. See stopLog() and dumpLog(). You can also specify externalLogging, a custom channel subscribe function and a different number of hkItems (housekeeping items) from the default 100 (if -1 it won't delete items).

stopLog

stopLog()

Will stop collecting log messages and will reset everything. User dumpLog() before stopping if you intend to keep the recorded log messages.

stopOpenAFAndRun

stopOpenAFAndRun(aCommandLineArray, addCommand)

Terminates the current OpenAF execution while trying to execute the commands on the aCommandLineArray. Optionally you can use addCommand boolean flag (true) to allow for shell like commands on the current operating system. To restart OpenAF please use the restartOpenAF function.

stringify

stringify(anObject, replacer, space) : String

Converts anObject into a string representation of the same. This is equivalent to the JSON.stringify function. If space isn't defined a "  " (2 spaces) is assumed as the default value. Reverts to the beautifier function if it isn't possible to apply stringify to the current object.  To see more info on the remaining parameters please check https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

sync

sync(aFunction, anObject)

Will ensure that aFunction is synchronized, in multi-threaded scripts. Optionally you can provide anObject to synchronized upon.

syncFn

syncFn(aFunction, anObject) : Object

Will ensure that aFunction is synchronized, in multi-threaded scripts (alternative to sync). Optionally you can provide anObject to synchronized upon. Returns the result of aFunction.

templify

templify(aTemplateString, someData) : String

Using Handlebars and the functionality provided in ow.template, will use the aTemplateString as a Handlebars template and return the parsed output. Optionally you can provide someData as data for the Handlebars template  otherwise the current scope will be used.

Example:

var someText = "Hello World!";
var retText = templify("Hi, "); // Hi, Hello World!

threadBox

threadBox(aExecFunction, aTimeout, aStopFunction)

Tries to execute aExecFunction inside a thread. If aTimeout is defined the thread will be terminated if it's still executing after aTimeout. If aStopFunction is defined  it will receive, as argument, a boolean indicating if the thread has stopped (true). If this function returns true the thread execution will be terminated, if false will continue.
Note: see threadBoxCtrlC as aStopFunction to stop executing on Ctrl-C

threadBoxCtrlC

threadBoxCtrlC() : Boolean

Meant to be use as a stopFunction for threadBox will return true if Ctrl-C is detected and false otherwise. If the current terminal can't support ANSI if will default to false.

tlog

tlog(msg, someData, formatOptions)

Outputs to the current stdout a line composed of the current date, indication of INFO and the provided msg using the templify function. Optionally you can provide also someData and you can provide a formatOptions map for overriding the defaults from setLog. Note: you can use startLog, stopLog and dumpLog to keep an internal record of theses messages.

tlogErr

tlogErr(msg, someData, formatOptions)

Outputs to the current stderr a line composed of the current date, indication of ERROR and the provided msg using the templify function. Optionally you can provide a formatOptions map for overriding the defaults from setLog.  Optinionally you can provide also someData.

tlognl

tlognl(msg, someData, formatOptions)

Outputs to the current stdout, without a new line, a sentence composed of the current date, indication of INFO and the provided msg using the templify function. Optionally you can provide a formatOptions map for overriding the defaults from setLog. Optinionally you can provide also someData.

tlogWarn

tlogWarn(msg, someData, formatOptions)

Outputs to the current warning in a line composed of the current date, indication of WARN and the provided msg using the templify function. Optionally you can provide a formatOptions map for overriding the defaults from setLog.  Optinionally you can provide also someData.

toBoolean

toBoolean(aObj) : Boolean

Tries to convert aObj (String, Number or Boolean) into a boolean value

toCSV

toCSV(anArray) : CSV

Converts a given javascript anArray into a CSV object instance.

toEncoding

toEncoding(aString, anEncoding) : String

Converts the provided aString to a different anEncoding (by default UTF-8).

tprint

tprint(aTemplateString, someData)

Using Handlebars and the functionality provided in ow.template, will use the aTemplateString as a Handlebars template and print the parsed output. Optionally you can provide someData as data for the Handlebars template  otherwise the current scope will be used.

Example:

var someText = "Hello World!";
tprint("Hi, "); // Hi, Hello World!

tprintErr

tprintErr(aTemplateString, someData)

Using Handlebars and the functionality provided in ow.template, will use the aTemplateString as a Handlebars template and print, to the stderr, the parsed output. Optionally you can provide someData as data for the Handlebars template  otherwise the current scope will be used.

Example:

var someText = "Hello World!";
tprintErr("Hi, "); // Hi, Hello World!

tprintErrnl

tprintErrnl(aTemplateString, someData)

Using Handlebars and the functionality provided in ow.template, will use the aTemplateString as a Handlebars template and print, to the stderr without new line, the parsed output. Optionally you can provide someData as data for the Handlebars template  otherwise the current scope will be used.

Example:

var someText = "Hello World!";
tprintErrnl("Hi, "); // Hi, Hello World!

tprintln

tprintln(aTemplateString, someData)

Using Handlebars and the functionality provided in ow.template, will use the aTemplateString as a Handlebars template and print, withouth a new line, the parsed output. Optionally you can provide someData as data for the Handlebars template  otherwise the current scope will be used.

Example:

var someText = "Hello World!";
tprintln("Hi, "); // Hi, Hello World!

traverse

traverse(aObject, aFunction) : Map

Traverses aObject executing aFunction for every single element. The aFunction will receive the arguments: aKey, aValue, aPath, aObject.

uncompress

uncompress(aResultOfTheCompressFunction) : Object

Uncompresses a JSON object, compressed by using the compress function, into a JSON object.

uniqArray

uniqArray(anArray) : Array

Returns anArray with no duplicates entries (including duplicate maps).

utf8

utf8(aString) : String

Converts the provided aString into UTF-8 encoding.

visibleLength

visibleLength(aString) : Number

More complete af.visibleLength function

watch

watch(waitFor, aCommand, beautifyFlag, noPrint)

Executes javascript aCommand provided every waitFor periods of time (expressed in ms). The screen will be cleared and the execution will repeat indefinitely until the 'q' key is pressed.  Optionally a beautifyFlag can be provided to execute the beautifier function on the aCommand result.

wedoDate

wedoDate(year, month, day, hour, minute, second, ms) : Map

Builds and returns a wedoDate JSON object given either a year, a month, a day, a hour, a minute, a second and ms or a Date object.

yprint

yprint(aObj, multidoc, sanitize)

Prints aObj in YAML. If multiDoc = true and aJson is an array the output will be multi-document. If sanitize = true all Java objects will be converted to avoid parsing errors.

yprintErr

yprintErr(aObj, multidoc)

Prints aObj in YAML to stderr. If multiDoc = true and aJson is an array the output will be multi-document.