Environment class

The single instance of the Environment class is passed as an argument to the script entry points that operate out of the context of a particular flow element. By convention, the name for the Environment object is "e" (although the script developer can choose to use another name).

Since the Switch class inherits from the Environment class, any of the functions described in this topic can be called for the Switch class as well. In other words, you can call the Environment class functions with "e.function()" or "s.function()" depending on the argument passed to the entry point.

Logging

log( type : Number, message : String, extra : String or Number )

Logs a message of the specified type (see below) outside of a job context. Where possible use the job.log() function instead, because it includes information about the job in the message.

Log messages are displayed in the Messages pane and in the Progress pane; see also viewing log messages and viewing processes.

Log Type

The "type" argument must have one of the following numeric values:

Numeric type

Display type

Description

1

Info

An informational message that has no other purpose than to inform the user of a certain occurrence

2

Warning

A warning message that informs the user of a recoverable problem or non-fatal error

3

Error

An error message that informs the user of a fatal error

4

Start

A formal message that marks the start of a task that should be displayed in the progress pane

5

Progress

A formal message that marks the completion of a particular portion of a task for which a start message was previously issued

6

End

A formal message that marks the completion of a task for which a start message was previously issued

-1

Debug

An informational message solely intended for debugging purposes

-2

Assert

A message solely intended for debugging purposes that is issued only when a coding error is discovered

Log Message

The message argument and the optional extra argument specify the message being issued, as a constant and variable part. For example:

e.log(2, "Trial period will expire in %1 days", days);

The message argument should be a constant string (that is, not constructed programmatically) because it is used as a key in the localization database. The "extra" argument, when present, replaces the placeholder "%1" in the localized version of the message. If the "extra" argument is missing or null, no replacement takes place.

If the extra argument is a number, it is rounded to the nearest integer and then converted to the corresponding decimal string representation. This allows picking alternative messages from the localization database depending on the number (example: "1 day" versus "2 days").

If the extra argument is a string, all leading and trailing white space is removed, and any remaining line breaks (CR, LF, or CRLF) are replaced by a semicolon. This allows passing multi-line text (such as the complete contents of stderr or stdout) to the extra argument without inadvertently causing line breaks in log messages.

Log: Multiple variable parts

The message argument can use the special placeholders "%11", "%12" through "%19" to access the corresponding segment (indexed 1 through 9) of the extra argument interpreted as a list of comma-separated values. If the specified segment does not exist the empty string is used. There is no support for quoted strings so individual values in the list can not contain commas.

Log: Showing progress

The messages of type "start", "progress" and "end" cause a task to be displayed in the Progress pane. The extra argument (which must be an integer) is used to indicate the total progress range and the current progress. For example, to indicate a taskconsisting of twelve more or less equal parts one might write:

e.log(4, "Task started", 12); 
for (var i=0; i < 12; i++) 
{ 
     e.log(5, "Task in progress", i); 
     ... 
} 
e.log(6, "Task ended");

Where possible use the job.log() function instead, because it includes information about the job in the Progress pane.

Maintaining global data

The data accessed by these functions is stored in a global repository that is part of the persistent state of the flow execution engine. Access to the repository is serialized (to avoid conflicts caused by access in multiple threads) and the contents of the repository persist across invocations of the flow engine.

It is the script programmer's responsibility to maintain distinct namespaces for different applications (including those written by other programmers), and to determine the extent to which the data is global. This can be accomplished by providing an appropriate value for the scope argument in the access functions.

The following table lists some examples for the value of the scope argument. The table assumes that the variable myOrg contains a URI (unique resource identifier) that uniquely identifies the programmer's organization, and that myApp contains a string that uniquely identifies the overall application under consideration (which may involve several cooperating scripts).

Value of scope argument

The data can be accessed by

myOrg + myApp

Any script that belongs to this application anywhere in the execution engine

myOrg + myApp + Switch.getFlowName()

Any script that belongs to this application and that resides in the same flow

myOrg + Switch.getScriptName()

All copies of this script (even if used in different script elements in the same flow or in different flows)

Switch.getFlowName() + Switch.getElementName()

The copy of this script for this script element (if the same script is used twice, there is a separate copy of the data for each script element)

setGlobalData( scope : String, tag : String, value : String, persistent : Boolean )

Sets the value of the global data with the specified scope and tag to the specified string. The parameter "persistent" indicates whether global data value should be preserved between Switch restarts. When set to false, the value will be lost whenever Switch is restarted. By default this parameter is set to true.

getGlobalData(scope : String, tag : String ) : String

Returns the value of the global data with the specified scope and tag, or the empty string if no global data with that scope and tag was set.

lockGlobalData( scope : String)

Acquires a global data lock on the specified scope so that multiple related get/set operations can be performed in the scope without interference from other scripts running in concurrent threads. (It is not necessary to lock global data for a single set or get operation or for multiple unrelated set and get operations).

This function blocks until the requested lock can be obtained.

A script can acquire only a single lock at a time, that is, nested locks are not allowed. While a lock is in effect, the script is allowed to access global data only in the scope on which a lock was acquired. Acquiring a nested lock (even on the same scope) or accessing data outside of the locked scope has undefined (and almost certainly undesirable) results.

unlockGlobalData( )

Releases the current global data lock, if any. Does nothing if there is no current lock.

Switch automatically releases the current lock, if any, after a script returns from the entry point. This is only a safeguard: a script should explicitly release a lock as soon as it is no longer needed.

Copying files

copy( source-path : String, destination-path : String)

Copies the file or folder (including its contents, recursively) specified by the source path to the destination path. Both paths are absolute and include a filename; that is, the destination path specifies the filename of the copied file or folder, not the parent folder in which it should be placed.

Files are copied with full support for platform-specific information such as Mac file types and resource forks (including emulations on Windows), as if copied by a regular flow operation under the control of Switch.

Note:

This function should be used only to copy files to a temporary location; use the Job.sendTo() functions for moving files to outgoing connections.

Getting special property values

The following functions allow retrieving the value of the special properties "ApplicationPath" and "ApplicationLicense" without requiring access to a Switch class instance. This is necessary in a scripted plug-in to access these properties from with the getApplicationLicensing entry point. See creating a scripted plug-in for more information on these special properties.

getApplicationPath( ) : String

Returns the centrally managed absolute path to the third-party application associated with this scripted plug-in or null if no such path is available (yet).

getApplicationLicense( ) : String

Returns the centrally managed license key for the third-party application associated with this scripted plug-in or null if no such license key is available (yet).

Getting global user preferences

getServerName( ) : String

Returns the name of the Switch server hosting this execution, as specified by the user in the communication preferences.

getLicenseeName( ) : String

Returns the name entered in the Switch licensing dialog, or the empty string if no name has been entered. If multiple licenses are activated, the license with the longest license time period is used.

getLicenseeOrganization( ) : String

Returns the organization entered in the Switch licensing dialog, or the empty string if no organization has been entered. If multiple licenses are activated, the license with the longest license time period is used.

getLanguage( ) : String

Returns the name of the currently active language preference, in English. For example, the currently implemented languages are "English" and "German".

getLanguageEnvironment( ) : String

Returns the name of the currently active language environment preference, in English. For example, the currently implemented language environments are "Western" and "Japanese".

getLicenseSerial( ) : Number

Returns the serial number (max. 9 digits) associated with the license entered in the Switch licensing dialog. If multiple licenses are activated, the license with the longest license time period is used. This is always a positive integer, or zero if Switch has not been properly licensed.

getLicenseSerials( inFeature : String ) : String[]

inFeature is the name of the feature for which the license's serial numbers are requested. It can be a string value like "Switch Core Engine", "Scripting Module" etc (see the list of constants available in the Environment class given below).

Returns the list of the serial numbers of the all active licenses for this feature. If the feature is unknown or not licensed then the empty list is returned.

The list of feature constants available in the Environment class (with the corresponding string value) are:
  • SwitchCoreEngine ("Switch Core Engine")
  • PerformanceModule ("Performance Module")
  • ConfiguratorModule ("Configurator Module")
  • DatabaseModule ("Database Module")
  • MetadataModule ("Metadata Module")
  • ScriptingModule ("Scripting Module")
  • SwitchClientModule ("SwitchClient Module")
  • SwitchWebServices ("Switch Web Services")
  • AdditionalSwitchClientLicenses ("Additional SwitchClient Licenses")

These can be accessed in the script by using expressions like e.SwitchCoreEngine or s.SwitchCoreEngine.

For Example:
var theSerials = s.getLicenseSerials( s.ScriptingModule );
job.log( 1, "Serials for Scripting module: %1" + , theSerials.join( ", " ) );
isInTrialMode( ) : Boolean

Returns true if Switch currently runs in trial mode; false otherwise.

Getting system information

isWindows( ) : Boolean

Returns true if the calling script is running on Microsoft Windows, false otherwise.

isMac( ) : Boolean

Returns true if the calling script is running on Apple Mac OS X, false otherwise.

findRegisteredApplication( key1 : String, key2 : String ) : String

Queries the system for an application that has been registered with one of the specified keys, and returns the absolute path of the application if found or null if not. The function verifies that the returned path is valid (that is, a file exists at the location); if not null is returned instead.

There are two key arguments so that a single call can specify the keys required for two different operating systems. The function automatically figures out which key to use on each operating system. The second key argument can be omitted if it is not needed.

On Windows, the function queries the system registry with the specified key, which must be an absolute registry path. Most professional application installers make a registry entry for this purpose but there is no guarantee.

Mac OS X automatically adds an entry to its application database when an application bundle is installed or copied to the system. Thus on Mac OS X the function queries the system application database with the specified key, which must be the filename of the application bundle (that is, the same name one would use to address the application from AppleScript) or the application's bundle identifier as provided in the property list located inside the application bundle (example: "com.adobe.distiller"). In the latter case, when multiple versions of the application are installed, Mac OS X will choose the most recent version.

findApplicationOnDisk( name1 : String, name2 : String ) : String

Searches the system folder in which applications are usually installed for an application with one of the specified file names and returns the absolute path of the application if found or null if not. There are two name arguments in case the application is named differently on different operating systems. The second name argument can be omitted if it is not needed.

On Windows the function recursively searches the contents of the Program Files folder. If the specified name has no extension, ".exe" is added.

On Mac OS X the function recursively searches the contents of the Applications folder. If the specified name has no extension, the function looks for the specified name AND for the name with ".app" added. The function does not search inside application bundles.

This function may use substantial resources (and time) to complete since it recursively searches the contents of a potentially large folder. Therefore, when called from the findApplicationPath entry point during Switch startup, this function is automatically disabled and immediately returns an empty string without searching.

getSpecialFolderPath( folderID : String ) : String

Returns the absolute path to the special folder indicated by the folderID argument, which must be one of the strings listed in the table below. Returns null if folderID is unknown.

folderID

Returns an absolute path to

ApplicationData

The folder that serves as a common repository for application-specific data for the current user (that is, the user who launched Switch server)

CommonApplicationData

The folder that serves as a common repository for application-specific data that is used by all users

PluginResources

The resource folder associated with the calling script; in the current implementation this is always the folder that contains the calling script package but implementations should not count in this fact

The resource folder is intended for use by scripted plug-ins (see creating a scripted plug-in) and should not be used from regular script packages except for testing; there is no reliable way to transport external resources with regular script packages

ScriptData

The folder that serves as a common repository for custom "global" Switch script data; it is shared by all scripts (and all users) so callers must provide unique names for any files stored in this folder

This is a subfolder of the Switch application data root, which has the advantage that its contents is relocated with all other information relevant to the operation of Switch, and can be easily located for diagnostics purposes

UserDocuments Returns an absolute path to the user documents folder. The typical path on Windows is C:\Users\<username>\Documents, the typical path on Mac is /Users/<username>/Documents
Applications Returns an absolute path to the applications folder. The typical path is C:\Program Files on Windows 32 bit and C:\Program Files (x86) on Windows 64 bit, the typical path on Mac is /Applications
OperatingSystem Returns an absolute path to the operating system folder. The typical path on Windows is C:\Windows, the path on Mac is always the root folder, i.e. /
System Returns an absolute path to the system data folder. The typical path on Windows is C:\Windows\system32, the typical path on Mac is /System

Fonts

Returns an absolute path to the fonts folder. The typical path on Windows is C:\Windows\Fonts, the typical path on Mac is /Library/Fonts
getSystemInfo( infoID : String ) : String

Returns the system information indicated by the infoID argument, which must be one of the strings listed in the table below. Returns null if infoID is unknown.

infoID

Returns

UserName

The login name of the current user (i.e. the user who launched Switch server)

supports64bit( ) : Boolean

Returns true if the calling script is running on a 64-bit capable operating system and processor, false otherwise.

Switch always runs in 32-compatibility mode. This function is provided solely to inform a script about operating system capabilities. For example, the script may use the information to select the appropriate version of a third-party application.

The Windows operating system comes in two distinct flavors (32-bit and 64-bit), so this function returns true only if it runs on a 64-bit Windows version.

Mac OS X supports a mix of 32-bit and 64-bit applications when running on a 64-bit capable processor, so this function returns true when running on a 64-bit capable processor. Note that all Intel-based Macs are 64-bit capable.

getServerVersion( ) : number

Returns the version of the Switch server hosting this execution as a decimal number: "major version + update number / 100".

For example, Switch 08 update 6 returns the number 8.06.

This function does not differentiate between pre-release and release builds.

This function was introduced in Switch 08 update 6. If a script may be hosted by an older version of Switch, the script should check for the presence of this function before using it. For example:

if ("getServerVersion" in s && s.getServerVersion() >= 8.07) ...

Supporting time-out

getSecondsLeft( ) : Number

Returns the number of seconds left before the maximum allotted execution time ("abort processes after" in error handling preferences), is reached for this entry point. This allows a script to fail gracefully when it detects that it is getting close to being aborted, or to choose different algorithms based on the allotted time.

Switch provides no guarantees about the actual CPU time that will be available to the script (since many other tasks may be executing in parallel).

Sleeping

sleep ( seconds : Number )

Blocks the calling script for approximately the specified amount of time (in seconds). Other Switch processes are allowed to continue execution in parallel.

Compressing

compress( source-path : String, destination-path : String, password : String, compress : Boolean ) : Boolean

Places the source file or folder (including its nested contents) into a ZIP archive at the destination path, using the specified password. If the password is null or missing, the archive is not password-protected.

By default (that is, if the compress argument is true, missing or null), the files in the ZIP archive are compressed. If the compress argument is false, the files are stored in the ZIP archive without compression, dramatically reducing processing time. This can be meaningful when speed is more important than size or when the files will not compress well (example: JPEG images).

Returns true if successful, false if not (in which case an appropriate error message is logged).

This function behaves exactly as the compress tool (except that it does not add a unique name prefix to the output archive's name).

compress( source-path : String, destination-path : String, password : String, compress : Boolean, remove_existing_archive: Boolean ) : Boolean
When
remove_existing_archive
is set to true, the zip file existing in the destination folder is removed and a new zip file is created.
If
remove_existing_archive
is set to false, the files are appended to the zip file existing in the destination folder.
For example,
  1. compress("file1.txt", "result.zip", ... , remove_existing_archieve="true");

    compress("file2.txt", "result.zip", ... , remove_existing_archieve="true");

    As a result, the result.zip file contains only file2.txt.

  2. compress("file1.txt", "result.zip", ... , remove_existing_archieve="false");

    compress("file2.txt", "result.zip", ... , remove_existing_archieve="false");

    As a result, the result.zip file contains both file1.txt and file2.txt files.

uncompress( source-path : String, destination-path : String, remove-redundant-folders : Boolean, passwords : String[ ] ) : Boolean

Extracts all files from the archive at the source path and places them as a file or folder at the destination path. If the third argument is set to yes, all but the deepest subfolder levels are removed while uncompressing. The last (optional) argument provides a list of passwords for opening password-protected archives.

Returns true if successful, false if not (in which case an appropriate error message is logged).

This function behaves exactly as the uncompress tool (except that it doesn't add a unique name prefix to the output file or folder's name). That is, it supports the same formats and the output file/folder is structured in the same way.

extract( archive-path : String, file-path : String, destination-path : String, passwords : String[ ] ) : Boolean

Extracts the single file specified by the file-path argument from the source ZIP archive and places it at the destination path in the file system. The last (optional) argument provides a list of passwords for opening password-protected archives.

Returns true if successful, false if not (in which case an appropriate error message is logged).

Note that this function supports only the ZIP archive format; it is intended to extract a manifest from the archive without having to uncompress the complete archive.

Downloading

download( source-url : String, destination-path : String ) : Boolean

Downloads the file specified by the source URL to the destination path. The source URL must specify the ‘http' or ‘ftp' protocol, including login and password if applicable. The destination path must include a filename; that is, the it specifies the filename of the copied file, not the parent folder in which it should be placed.

Returns true if the operation succeeded, false if not. Only one download attempt is made.

Note:

This function should be used only to place files in a temporary location; use the Job.sendTo() functions for moving files to outgoing connections.

Temporary location

createPathWithName( name : String, createFolder : Boolean ) : String

This function has the same semantics as the Job.createPathWithName() function. It is provided as a member of the Environment class so that one can obtain a location for storing temporary files or folders without having access to a job (for example, in the timerFired entry point).

Client connection

getClientConnection( ) : ClientConnection
Returns the valid ClientConnection object if the script code is executed in the context of a client connection, otherwise null is returned.
Note: The ClientConnection object is available only in context of a client connection. If there is a client connection which triggered evaluation of a script, then this script returns a valid ClientConnection object after calling this method. In all other cases, the method getClientConnection returns null. This means that the ClientConnection currently can be used only in JavaScript script expressions specified in Metadata properties of Submit point and Checkpoint flow elements.