3 OpenScript Basic API Reference

This chapter provides a complete listing and reference for the methods in the Basic OpenScript Application Programming Interface (API).

3.1 OpenScript Basic API Reference

The following section provides an alphabetical listing of the methods in the Basic OpenScript API.

3.1.1 Alphabetical Command Listing

The following table lists the OpenScript Basic API methods in alphabetical order.

Table 3-1 List of EnterpriseOneService Methods

Method Description

abort

Immediately aborts the VUser as soon as possible.

beginStep

Specifies the begining of a new Step Group withor without delay timing.

callEncryptedFunctionByPath

Calls functions from remote encrypted scripts that are not attached as script assets.

callFunction

Call a function in the current script.

callFunctionByPath

Calls functions from remote scripts that are not attached as script assets.

decrypt

Decrypts a string previously encrypted with the Base-64 Crypt algorithm.

delay

Delays the current VUser for the specified number of milliseconds.

deobfuscate

Deobfuscates a string previously obfuscated with the Base-64 Crypt algorithm.

encrypt

Encrypts a string with the Base-64 Crypt algorithm.

endStep

Ends the Step Group that was most recently started using beginStep().

eval

Transforms a string of data, substituting the values of variables where applicable.

fail

Allows the user to call a fail(String) operation in the script.

finish

Defines the finish() section of a script.

getController

Service containing controller information.

getCounters

Service for reporting numeric counter values to a controller.

getDatabank

Gets the Databank defined by the specified alias.

getIteration

Service containing iteration information.

getIterationResult

Gets and sets iteration results in a script.

getLastError

Helper method to find the AbstractScriptException in latest run Result.

getLastResult

Helper method to find the latest run Result.

getLogger

Service for logging debug messages to a log file.

getScript

Gets a child script that can run from this script or a public function defined in the child script can be called.

getScriptPackage

Gets script package information.

getSession

Gets session information.

getSettings

Gets the script settings.

getStepResult

Gets and set step results.

getTotalIterationsCompleted

Gets the total number of completed iterations.

getVariables

Gets variables for this virtual user.

hasLastError

Checks whether last run Result has exception.

info

Writes a comment message to the console/log file, and to the Result View.

initialize

Defines the initialize() section of a script.

obfuscate

Obfuscate a string with the Base-64 Crypt algorithm.

reportFailure

Writes a failure message to the console/log file, and to the Result View.

reportPassed

Writes a passed message to the console/log file, and to the Result View.

resume

Resume the script after abort.

run

Defines the run() section of a script.

runScript

Find and run the specified script.

setErrorRecovery

Sets the script Error Recovery settings.

setLastResult

Helper method to set the last run Result.

syncPointWait

Notify the controller that the virtual user has reached the specified synchronization point.

think

Inserts "think time" delay into the script.

toBoolean

Helper method to parse a String as a boolean.

toDate

Helper method to parse a String as a Date.

toDouble

Helper method to parse a String as a signed decimal double in base 10.

toInt

Helper method to parse a String as a signed decimal integer in base 10.

toList

Helper method to convert a list of arguments into a List<String>.

toLong

Helper method to parse a String as a signed decimal long in base 10.

toMap

Helper method to convert a list of arguments into a Map<String>.

warn

Writes a warning message to the console/log file, and to the Result View


The following sections provide detailed reference information for each method in the OpenScript Basic Application Programming Interface.

abort

Immediately aborts the VUser as soon as possible. The remaining actions in the iteration, including any parent scripts and functions, will not complete.

The finish() section will not be run. The currently running script will return a failed result indicating that the VUser was aborted.

If a VUser is aborted, it is possible to resume the script by catching the abort user exception and calling resume().

Format

The abort method has the following command format:

abort();

Throws

StopScriptRuntimeException

To stop script execution immediately.

Example

Abort a script at any point.

info("Running a script...");
abort()
info("This line will not be run.");

Abort and then resume.

try {
 info("Perform any steps inside a try-catch block...");
 abort()
 info("This line will not be run.");
} catch (StopScriptRuntimeException e) {
 // optionally take any corrective action and optionally resume script
 resume();
}

beginStep

Specifies the begining of a new Step Group withor without delay timing. Steps Groups may be used to group sequences of actions together and to report timing information.

beginStep() must always be closed with endStep().

Format

The beginStep method has the following command format:

beginStep(stepName);

beginStep(stepName, delayMs);

Command Parameters

stepName

a String specifying the name used to identify this step, similar to a page title.

delayMs

an Integer specifying the amount of time to wait in milliseconds before beginning the step. The delayMs value will be adjusted based on the VUser's current delay settings.

Throws

AbstractScriptException

represents an exception that may be thrown during the execution of a script where the exception should be reported to an end user through the controller.

Example

Specifies the begining of a new Step Group named "[1] Stocks" with a delay of 5 milliseconds.

beginStep("[1] Stocks", 5)
{
  http.window(15, "window[@index='0']").get(
    "http://example.com/fmstocks/", null, null,
    true, "ASCII", "ASCII");
}
endStep();

callEncryptedFunctionByPath

This API enables the invoking of functions from remote encrypted scripts that are not attached as script assets as long as the remote script is stored within a user defined script repository location.

Format

The callEncryptedFunctionByPath method has the following command format:

callEncryptedFunctionByPath(repository, scriptPathRelToRepository, scriptPassword, functionName, args);

Command Parameters

repository

a String specifying the name of the user defined repository mapping where the remote script is stored. Must not be null.

scriptPathRelToRepository

a String specifying the path to the script within the named repository. Any leading file separator on the path, such as / or \, is ignored. Must not be null.

scriptPassword

a String specifying the password of the specified script. May be null if the script is not encrypted.

functionName

a String specifying the name of the function to call within the specified script. Must not be null.

args

an Object specifying an optional list of arguments to pass to the called function. All String arguments will be evaluated before sending to the function.

Throws

Exception

on any exception while invoking the specified function.

Returns

Optional result of function call. If function is void, then the result will be null. User should cast return result to correct return object type. Thus if function returns int or Integer, then result should be cast to Integer.

Example

Example of calling function with API that is defined in same repository without any sub level directories.

public void run() throws Exception
{
  beginStep("Call Remote Function Example");
  {
  callEncryptedFunctionByPath("Default", "myRemoteScript", "myEncryptionKey", "calculateTax", (Object[])null);
  }
  endStep();
}

Example of calling function with API that is defined in different repository with 'n' sub level directories.

public void run() throws Exception
{
  beginStep("Call Remote Function Example");
  {
  callEncryptedFunctionByPath("ProductionScripts", "ApplicationOne/Finance/English/myRemoteScript", "myEncryptionKey", "calculateTax", (Object[])null);
  }
  endStep();
}

Example of calling function with API that is defined in the same repository with a return type of String.

public void run() throws Exception
{
  beginStep("Call Remote Function Example");
  {
  String taxCalculationOutcome = (String)callEncryptedFunctionByPath("ProductionScripts", "ApplicationOne/Finance/English/myRemoteScript", "myEncryptionKey", "calculateTax", (Object[])null);
  info("Result of Tax calculation: "+taxCalculationOutcome);
  }
  endStep();
}

callFunction

Call a function in the current script.

Format

The callFunction method has the following command format:

callFunction(functionName, args);

Command Parameters

functionName

a String specifying the name of function to call. Must not be null.

args

an Object specifying an optional list of arguments to pass to the called function. All String arguments will be evaluated before sending to the function.

Throws

Exception

on any exception while invoking the specified function.

Returns

Optional result of function call. If function is void, then the result will be null. User should cast return result to proper class. Thus if function returns int or Integer, then result should be cast to Integer. If function returns boolean or Boolean, then result should be cast to Boolean.

Example

Calls the function "myFunction" with arguments String, Int, double, long, boolean, Selectlist List<String>, and Map<String, String>.

callFunction("myFunction", "name", "1", "10.0", "100", "true", "val2", toList("list1", "list2", "list3"), toMap("key1=val1", "key2=val2", "key3=val3"));

callFunctionByPath

This API enables the invoking of functions from remote scripts that are not attached as script assets as long as the remote script is stored within a user defined script repository location.

Format

The callFunctionByPath method has the following command format:

callFunctionByPath(repository, scriptPathRelToRepository, functionName, args);

Command Parameters

repository

a String specifying the name of the user defined repository mapping where the remote script is stored. Must not be null.

scriptPathRelToRepository

a String specifying the path to the script within the named repository. Any leading file separator on the path, such as / or \, is ignored. Must not be null.

functionName

a String specifying the name of the function to call within the specified script. Must not be null.

args

an Object specifying an optional list of arguments to pass to the called function. All String arguments will be evaluated before sending to the function.

Throws

Exception

on any exception while invoking the specified function.

Returns

Optional result of function call. If function is void, then the result will be null. User should cast return result to correct return object type. Thus if function returns int or Integer, then result should be cast to Integer.

Example

Example of calling function with API that is defined in same repository without any sub level directories.

public void run() throws Exception
{
  beginStep("Call Remote Function Example");
  {
  callFunctionByPath("Default", "myRemoteScript", "calculateTax", (Object[])null);
  }
  endStep();
}

Example of calling function with API that is defined in different repository with 'n' sub level directories.

public void run() throws Exception
{
  beginStep("Call Remote Function Example");
  {
  callFunctionByPath("ProductionScripts", "ApplicationOne/Finance/English/myRemoteScript", "calculateTax", (Object[])null);
  }
  endStep();
}

Example of calling function with API that is defined in the same repository with a return type of String.

public void run() throws Exception
{
  beginStep("Call Remote Function Example");
  {
  String taxCalculationOutcome = (String)callEncryptedFunctionByPath("ProductionScripts", "ApplicationOne/Finance/English/myRemoteScript", "calculateTax", (Object[])null);
  info("Result of Tax calculation: "+taxCalculationOutcome);
  }
  endStep();
}

decrypt

Decrypts a string previously encrypted with the Base-64 Crypt algorithm.

Format

The decrypt method has the following command format:

decrypt(data);

Command Parameters

data

a String specifying the encrypted text to decrypt.

Throws

AbstractScriptException

represents an exception that may be thrown during the execution of a script where the exception should be reported to an end user through the controller.

EncryptionServiceNotInitializedException

if no password is specified for the encryption service.

Example

Decrypts the specified string.

String encrypted = encrypt("encrypt this string");
  info(encrypted);
String decrypted = decrypt(encrypted);
  info(decrypted);

delay

Delays the current VUser for the specified number of milliseconds.

This method does NOT honor the VU Pacing settings defined in playback preferences. If the VUser is stopped for any reason (for example, if the Stop button is pressed), the VUser will be awakened immediately.

The VUser's status will be updated to reflect the fact that it is sleeping.

Format

The delay method has the following command format:

delay(milliseconds);

Command Parameters

milliseconds

an Integer specifying the number of milliseconds to delay the VUser.

Throws

EncryptionServiceNotInitializedException

if no password is specified for the encryption service.

Returns

false if the delay operation is interrupted prematurely, otherwise returntrue.

Example

Delays the current VUser for 1000 milliseconds.

delay(1000);

deobfuscate

Deobfuscates a string previously obfuscated with the Base-64 Crypt algorithm.

Format

The deobfuscate method has the following command format:

deobfuscate(data);

Command Parameters

data

a String specifying the text to deobfuscate.

Throws

AbstractScriptException

represents an exception that may be thrown during the execution of a script where the exception should be reported to an end user through the controller.

Example

Deobfuscates the specified string.

String obfuscated = obfuscate("obfuscate this string");
  info(obfuscated);
String deobfuscated = deobfuscate(obfuscated);
  info(deobfuscated);

encrypt

Encrypts a string with the Base-64 Crypt algorithm.

Format

The encrypt method has the following command format:

encrypt(data);

Command Parameters

data

a String specifying the text to encrypt.

Throws

AbstractScriptException

represents an exception that may be thrown during the execution of a script where the exception should be reported to an end user through the controller.

EncryptionServiceNotInitializedException

if no password is specified for the encryption service.

Example

Encrypts the specified string.

String encrypted = encrypt("encrypt this string");
  info(encrypted);
String decrypted = decrypt(encrypted);
  info(decrypted);

endStep

Ends the Step Group that was most recently started using beginStep() .

Format

The endStep method has the following command format:

endStep();

endStep(stepName);

Command Parameters

stepName

a String specifying the name of step that was previously started using beginStep(stepName).

Throws

AbstractScriptException

represents an exception that may be thrown during the execution of a script where the exception should be reported to an end user through the controller.

Example

Specifies the end of the Step Group previously started as "[1] Stocks".

beginStep("[1] Stocks", 5)
{
  http.window(15, "window[@index='0']").get(
    "http://example.com/fmstocks/", null, null,
    true, "ASCII", "ASCII");
}
endStep();

eval

Transforms a string of data, substituting the values of variables where applicable.

The Transforms class provides utility functions for performing variable substitution inside strings containing custom transform syntax notation.

Many scripting languages support the ability to easily embed variable values inside strings. For example:

Ruby:

varDay = "Monday"
puts "Today is #{varDay}."

Perl:

$varDay = "Monday"
print "Today is $varDay."

The above examples would print "Today is Monday." to the standard output. In Java, the user has to type a more wordy expression to solve the above example:

String varDay = "Monday";
System.out.println("Today is " + varDay + ".");

OpenScript scripts provide an API to reference script variables using a special string format consisting of double-curly braces {{ }}, dubbed "custom transform syntax". Here is an example:

getVariables().set("varDay", "Monday");
getLogger().info("Today is {{varDay}}");

This class providers helper methods to substitute a collection of named variables and functions into a transform-syntax-formatted string. Transform syntax may contain zero or more variable or function references embedded inside double-curly brace characters.

Example:

"X is {{varX}} and Y is {{varY}}"

Indexed variable values may be referenced directly in the transform syntax by specifying the variable name and its 0-based indexed value inside brackets [ ]. The 0-based indexed value is returned if no index is specified.

Example:

"X is {{varX}} and {{varX[0]}}. X[1] is {{varX[1]}}."

Nested curly brace expressions are supported, and are evaluated from the inner-most expression to the outer-most expression.

Example:

"X[varIndex] is {{varX[{{varIndex}}]}}."

Function references are denoted by an @ sign preceding the function ID. Arguments are separated by commas. Literal commas inside arguments are escaped using two comma characters. See also: CustomFunction.

Example:

"Current timestamp is {{@timestamp()}}.

Variable and function references may be annotated with the variable's recorded value by appending a comma and the recorded value after the variable or function reference name.

Example:

"X is {{varX,123}}.

Literal {{ and/or }} sequences inside a string should be escaped with a # character prefix. Any literal # characters inside a string containing escaped {{ or }} sequences should be doubled.

Example (without transform syntax):

"Today is Monday. Other characters: {{}}!@#$%"

Example (with transform syntax):

"Today is {{varDay}}. Other characters: #{{#}}!@##$%"

Format

The eval method has the following command format:

eval(data);

Command Parameters

data

a String containing custom transform syntax to transform.

Throws

AbstractScriptException

represents an exception that may be thrown during the execution of a script where the exception should be reported to an end user through the controller.

Example

Evaluate a @today function transform syntax string.

info("evaluate @today function transform");
info eval("{{@today(MM/dd/yyyy)}}"));

fail

Allows the user to call a fail(String) operation in the script.

When this operation is called it stops execution of the script and displays the error string as a new step in results log.

Aborts the script playback by throwing a UserCausedFailureException.

Format

The fail method has the following command format:

fail(message);

Command Parameters

message

a String specifying the message to be written to the results log.

Throws

AbstractScriptException

represents an exception that may be thrown during the execution of a script where the exception should be reported to an end user through the controller.

UserCausedFailureException

when the fail(String) is invoked.

Example

Prints a Failure message to the Results view.

fail("a Failure message");

finish

Defines the finish() section of a script. The finish() section is automatically added to the script code when you create a script project in OpenScript.

Add any cleanup code or perform any operations after all iterations are performed for this virtual user.

Format

The finish method has the following command format:

finish();

Throws

Exception

on any exception. On error, scripts should throw AbstractScriptException instead of Exception whenever possible to provide more detail.

Example

Defines the finish() section of a script.

public void finish() throws Exception {
}

getController

Service containing controller information.

Format

The getController method has the following command format:

getController();

Example

Gets the controller name. May be null.

String contName = getController().getControllerName();
info("Controller Name " + contName);

getCounters

Service for reporting numeric counter values to a controller.

Format

The getCounters method has the following command format:

getCounters();

Example

Check how timeres are treated and report counters to load controller.

boolean isPageTimer = getCounters().isTreatPageAsTimers();
if(isPageTimer){
  info("treat page as timer");
}
else{
  info("do not treat page as timer");
}

boolean isResTimer = getCounters().isTreatResourcesAsTimers();
if(isResTimer{
  info("treat resource as timer");
}
else{
  info("do not treat resource as timer");
}

boolean isTestTimer = getCounters().isTreatTestsAsTimers();
if(isTestTimer){
  info("treat test as timer");
}
else{
  info("do not treat test as timer");
}

getCounters().report("scriptName", "timerName", "timerId",
  "myCounter", AggType.Average, 10.0);

getCounters().report("scriptName", "timerName", "timerId",
  "myNextcounter", 10.0, 0, 10);

getCounters().setSessionName("mySessionName");

getDatabank

Gets the Databank defined by the specified alias.

The Databank file or database and alias must be specified in the Script Assets of the Script Properties.

Format

The getDatabank method has the following command format:

getDatabank(dbAlias);

Command Parameters

dbAlias

a String specifying the Databank alias.

Example

Gets the Databank specified by the alias "customer".

getDatabank("customer").getNextDatabankRecord();

getIteration

Service containing iteration information.

Format

The getIteration method has the following command format:

getIteration();

Example

Gets the total iterations completed.

int i = getIteration().getTotalIterationsCompleted();
info("Total Iterations completed = " + i);

getIterationResult

Gets and sets iteration results in a script.

Use in the Finish section of the script.

Format

The getIterationResult method has the following command format:

getIterationResult();

Returns

The virtual user's current iteration result.

Example

Gets and sets iteration results in a script.

public void finish() throws Exception {
  //Iterations completed
  int totalComp = getTotalIterationsCompleted();
  String competedIterations = String.valueOf(totalComp);
  info("Total Completed Iterations = " + competedIterations);
  
  //Comments and Warnings
  getIterationResult().addComment("iteration result comment");
  getIterationResult().addWarning("iteration result warning");
  String sCommentString = getIterationResult().getCommentString();
  info("Comment String : " + sCommentString);
  String sWarningString = getIterationResult().getWarningsString();
  info("Warining String: " + sWarningString);
  
  //Data Used 1
  getIterationResult().addDataUsed("add data used1");
  getIterationResult().addDataUsed("add data used2");
  String dataUsedString = getIterationResult().getDataUsed();
  info("Data used String: " + dataUsedString);
  //Data Used 2
  ArrayList<String> dataUsed = new ArrayList<String>();
  dataUsed.add("Data used 1");
  dataUsed.add("Data used 2");
  dataUsed.add("Data used 3");
  getIterationResult().setDataUsed(dataUsed);
  info("Data Used" + dataUsed);
  
  //Get and Set Error (Sets Script failure)
  getIterationResult().setError("error string");
  String getErrorString = getIterationResult().getErrorString();
  info("Error String: " + getErrorString);
  getIterationResult().getError();// check for exception
  
  boolean isScriptPassed = getIterationResult().isPassed();
  if(isScriptPassed){
    info("script passed");
  }
  else{
    info("script not passed");
  }
  
  //Start and Finish time
  long lFinishTime = getIterationResult().getFinishTime();
  String sFinishTime = String.valueOf(lFinishTime);
  info("Finish time: " + sFinishTime);
  String outcome = getIterationResult().getOutcome();
  info("Outcome: " + outcome);
  long lStartTime = getIterationResult().getStartTime();
  String sStartTime = String.valueOf(lStartTime);
  info("Start time: " + sStartTime);
  getIterationResult().setFinishTime(lFinishTime);
  getIterationResult().setStartTime(lStartTime);
  
  //Step Name
  String sStepName = getIterationResult().getStepName();
  info("Step Name: " + sStepName);
  getIterationResult().setStepName("stepName");
}

getLastError

Helper method to find the AbstractScriptException in latest run Result.

Format

The getLastError method has the following command format:

getLastError();

Returns

AbstractScriptException on any exception in the last run Result.

Example

Gets the last error. Use String.valueOf instead of toString() to prevent throwing a NullPointerException if the value returned is null.

//Correct - String.valueOf(...);
info(String.valueOf(getLastError());

//Incorrect - if null is returned will result in NullPointerException
info(getLastError().toString());

getLastResult

Helper method to find the latest run Result.

Format

The getLastResult method has the following command format:

getLastResult();

Returns

IResult. The result contains last run status or null if there is no result generated yet.

Example

Gets the last result.

AttachedData attachedData = getLastResult().getAttachedData();
info("Response Time: " + attachedData.get(ResultDeclaration.responseTime));

String summary = getLastResult().getSummary();
info("Summary = " + summary);

Long dur = getLastResult().getDuration();
info("duration = " + dur);

if (getLastResult().isFailed()) {
  info("Failed");
}

getLogger

Service for logging debug messages to a log file.

Format

The getLogger method has the following command format:

getLogger();

Example

Log various messages.

getLogger().debug("A debug string");
getLogger().error("An error string");
getLogger().fatal("A fatal error string");
getLogger().info("An info string");

getScript

Gets a child script that can run from this script or a public function defined in the child script can be called.

The script file and alias must be specified in the Script Assets of the Script Properties.

Format

The getScript method has the following command format:

getScript(alias);

Command Parameters

alias

a String specifying the alias of the script to find.

Throws

ScriptException

if script cannot be found.

Returns

IScript for script to get.

Example

Gets the script specified by the alias "http1".

getScript("http1").run(1);

getScriptPackage

Gets script package information.

Reference to the virtual user's script (i.e. .JWG package) that the controller is running. Script package data is shared across all virtual users in an agent process.

Format

The getScriptPackage method has the following command format:

getScriptPackage();

Example

Gets script package information.

String scriptID = getScriptPackage().getScriptId();
info("Script Id: " + scriptID);

ArrayList<String> dbAliases = getScriptPackage().getDatabankAliases();
info("dbAliases" + dbAliases);

getSession

Gets session information.

Service containing session information.

Format

The getSession method has the following command format:

getSession();

Example

Sets and gets Session Name.

getSession().setName("session0001");
getVariables().set("Session Name", getSession().getName());
info("{{Session Name}}");

getSettings

Gets the script settings.

The error recovery settings use IDs specific to the script type as follows:

Basic Script Settings:

getSettings().getErrorRecovery(BasicErrorRecovery.setting));

Utilities Settings:

getSettings().getErrorRecovery(UtilitiesErrorRecovery.setting));

Functional Test Module Script Settings:

getSettings().getErrorRecovery(FTErrorRecovery.setting));

Web Functional Module Script Settings:

getSettings().getErrorRecovery(WebErrorRecovery.setting));

Oracle EBS/Forms Functional Module Script Settings:

getSettings().getErrorRecovery(FormsErrorRecovery.setting));

Http Load Module Script Settings:

getSettings().getErrorRecovery(HttpErrorRecovery.setting));

Adobe Flex (AMF) Load Module Script Settings:

getSettings().getErrorRecovery(AmfErrorRecovery.setting));

Oracle EBS/Forms Load Module Script Settings:

getSettings().getErrorRecovery(NcaErrorRecovery.setting));

Format

The getSettings method has the following command format:

getSettings();

Example

Gets the script settings and prints the value to the Results view.

VUserSettings VUSettings = getSettings();
info("Delay Between Iterations: " + VUSettings.getDelayBetweenIterations());
info("Delay Between Steps: " + VUSettings.getDelayBetweenSteps(0));
info("Encryption Properties File: " + VUSettings.getEncryptionPropertiesFile());
info("Machine Unique Number: " + VUSettings.getMachineUniqueNumber());
info("Max Save Cont Size: " + VUSettings.getMaxSaveContSize());
info("Port Number Maximum: " + VUSettings.getPortNumberMaximum());
info("Port Number Minimum: " + VUSettings.getPortNumberMinimum());
info("Replace URLs: " + VUSettings.getReplaceURLs());
info("Report Sender Interval: " + VUSettings.getReportSenderInterval());
info("Result Report Folder: " + VUSettings.getResultReportFolder());
info("Is On Error Stop VU: " + VUSettings.getIsOnErrorStopVU());
info("Is Using Databank: " + VUSettings.getIsUsingDatabank());
info("Report Counters: " + VUSettings.getReportCounters());
info("Use Recorded Value: " + VUSettings.getUseRecordedValue());
info("VU Logging Options: " + VUSettings.getVULoggingOptions());
info("is Execute User Defined Tests: " + VUSettings.isExecuteUserDefinedTests());
info("is No Report: " + VUSettings.isNoReport());
info("set Date Format: M/d/yy" );
  VUSettings.setDateFormat("M/d/yy");
info("set Is Using Databank: false" );
  VUSettings.setIsUsingDatabank(false);
info("File not found error setting: " +
  VUSettings.getErrorRecovery(BasicErrorRecovery.ERR_FILE_NOT_FOUND));

getStepResult

Gets and set step results.

Use in Step Groups in the Run section of the script

Format

The getStepResult method has the following command format:

getStepResult();

Returns

The virtual user's current StepResult.

Example

Gets and sets step results in a script.

//Comments and Warnings
getStepResult().addComment("step result comment");
getStepResult().addWarning("step result warning");
String sCommentString = getStepResult().getCommentString();
info("Comment String : " + sCommentString);
String sWarningString = getStepResult().getWarningsString();
info("Warining String: " + sWarningString);

//Data Used 1
getStepResult().addDataUsed("add data used1");
getStepResult().addDataUsed("add data used2");
String dataUsedString = getStepResult().getDataUsed();
info("Data used String: " + dataUsedString);
//Data Used 2
ArrayList<String> dataUsed = new ArrayList<String>();
dataUsed.add("Data used 1");
dataUsed.add("Data used 2");
dataUsed.add("Data used 3");
getStepResult().setDataUsed(dataUsed);
info("Data Used" + dataUsed);

//Get and Set Error (Sets Step failure)
getStepResult().setError("error string");
String getErrorString = getStepResult().getErrorString();
info("Error String: " + getErrorString);
getStepResult().getError();// check for exception

boolean isStepPassed = getStepResult().isPassed();
if(isStepPassed){
  info("step passed");
}
else{
  info("step not passed");
}

//Start and Finish time
long lFinishTime = getStepResult().getFinishTime();
String sFinishTime = String.valueOf(lFinishTime);
info("Finish time: " + sFinishTime);
String outcome = getStepResult().getOutcome();
info("Outcome: " + outcome);
long lStartTime = getStepResult().getStartTime();
String sStartTime = String.valueOf(lStartTime);
info("Start time: " + sStartTime);
getStepResult().setFinishTime(lFinishTime);
getStepResult().setStartTime(lStartTime);

//Step Name
String sStepName = getStepResult().getStepName();
info("Step Name: " + sStepName);
getStepResult().setStepName("stepName");

getTotalIterationsCompleted

Gets the total number of completed iterations.

Format

The getTotalIterationsCompleted method has the following command format:

getTotalIterationsCompleted();

Returns

The number of completed iterations.

Example

Get the total number of completed iterations and prints the value to the Results view.

public void finish() throws Exception {
  int totalComp =  getTotalIterationsCompleted();
  String completedIterations = String.valueOf(totalComp);
  info("Total Completed Iterations = " + completedIterations);
}

getVariables

Gets variables for this virtual user. Variables persist for the lifetime of the virtual user.

Format

The getVariables method has the following command format:

getVariables();

Returns

Script variables.

Example

Examples of using getVariables() to get and set script variables.

getVariables().set("myTodayVar", "{{@today(MM/dd/yyyy)}}",
  Variables.Scope.LOCAL);
getVariables().set("timestamp", "{{@timestamp}}", Variables.Scope.GLOBAL);
String myToday = getVariables().get("myTodayVar");
String myTime = getVariables().get("timestamp");
info(myToday);
info(myTime);

Variables variables = new Variables();
variables.set("myvarname", "myVarValue");
variables.set("myvarname1", "myVarValue1");
getVariables().addVariables(variables);
info(getVariables().get("myvarname"));
info(getVariables().get("myvarname1"));

String[] myVarArray = { "now", "then", "later" };
getVariables().setAll("myVarArray", myVarArray, Scope.LOCAL);
getVariables().getAll("myVarArray");
info("{{myVarArray[0]}}");
info("{{myVarArray[1]}}");
info("{{myVarArray[2]}}");

String[] allLocalVarNames = getVariables().getAllVariableNames(Scope.LOCAL);
for (int i = 0; i < allLocalVarNames.length; i++)
info("local var name: " + allLocalVarNames[i]);

String[] myGlobalVarArray = { "US", "Europe", "Asia" };
getVariables().setAll("myGlobalVarArray", myGlobalVarArray, Scope.GLOBAL);
info("{{myGlobalVarArray[0]}}");
info("{{myGlobalVarArray[1]}}");
info("{{myGlobalVarArray[2]}}");

String[] allGlobalVarNames = getVariables().getAllVariableNames(Scope.GLOBAL);
for (int i = 0; i < allGlobalVarNames.length; i++)
info("global var name: " + allGlobalVarNames[i]);

String[] allVarNames = getVariables().getAllVariableNames();
for (int i = 0; i < allVarNames.length; i++)
info("var name: " + allVarNames[i]);

getVariables().clearVariables();

hasLastError

Checks whether last run Result has exception.

Format

The hasLastError method has the following command format:

hasLastError();

Throws

ResultUnavailableException

if Result is unavailable.

Returns

The boolean to indicate whether last run Result has exception.

Example

Checks last run result for error.

if (hasLastError()) {
  info("has error");
  }

info

Writes a comment message to the console/log file, and to the Result View.

This method will never alter the flow of a script, such as stopping the script. Any variables specified in message will be evaluated to their current values.

If a variable expression is specified in message that does not exist, or if message cannot be evaluated for any reason:

1. A warning-level message will be printed to the console/log file indicating why the message could not be evaluated.

2. The original message, not evaluated, will be printed to the console/log file.

3. The Results View comment field will contain the original message, plus a warning note explaining why the message could not be evaluated.

4. Any problems that occur when evaluating the message will not be counted as a warning in the results report warnings total.

5. The execution of the script will continue as if no problem occurred.

Format

The info method has the following command format:

info(message);

Command Parameters

message

a String specifying the message to write to the console/log file and Results view. May contain embedded function and variable expressions using the Transforms syntax. Must NOT be null.

Throws

AbstractScriptException

represents an exception that may be thrown during the execution of a script where the exception should be reported to an end user through the controller.

Example

Get the total number of completed iterations and prints the value to the Results view.

public void finish() throws Exception {
  int totalComp = getTotalIterationsCompleted();
  String completedIterations = String.valueOf(totalComp);
  info("Total Completed Iterations = " + completedIterations);
}

initialize

Defines the initialize() section of a script. The initialize() section is automatically added to the script code when you create a script project in OpenScript.

Add code to be executed once before any iterations are run for this virtual user.

Format

The initialize method has the following command format:

initialize();

Throws

Exception

on any exception. On error, scripts should throw AbstractScriptException instead of Exception whenever possible to provide more detail.

Example

Defines the initialize() section of a script.

public void initialize() throws Exception {
}

obfuscate

Obfuscate a string with the Base-64 Crypt algorithm.

Format

The obfuscate method has the following command format:

obfuscate(stepName);

Command Parameters

data

a String specifying the name used to identify this step, similar to a page title.

Throws

AbstractScriptException

represents an exception that may be thrown during the execution of a script where the exception should be reported to an end user through the controller.

Example

Obfuscates the specified string.

String obfuscated = obfuscate("obfuscate this string");
  info(obfuscated);
String deobfuscated = deobfuscate(obfuscated);
  info(deobfuscated);

reportFailure

Writes a failure message to the console/log file, and to the Result View.

This method will never alter the flow of a script, such as stopping the script. Any variables specified in message will be evaluated to their current values.

If a variable expression is specified in message that does not exist, or if message cannot be evaluated for any reason:

1. A warning-level message will be printed to the console/log file indicating why the message could not be evaluated.

2. The original message, not evaluated, will be printed to the console/log file.

3. The Results View comment field will contain the original message, plus a warning note explaining why the message could not be evaluated.

4. Any problems that occur when evaluating the message will not be counted as a warning in the results report warnings total.

5. The execution of the script will continue as if no problem occurred.

Format

The reportFailure method has the following command format:

reportFailure(message);

Command Parameters

message

a String specifying the message to write to the console/log file and Results view. May contain embedded function and variable expressions using the Transforms syntax. Must NOT be null.

Throws

AbstractScriptException

represents an exception that may be thrown during the execution of a script where the exception should be reported to an end user through the controller.

Example

Prints a reported Failure message to the Results view.

reportFailure("a reported Failure message");

reportPassed

Writes a passed message to the console/log file, and to the Result View.

This method will never alter the flow of a script, such as stopping the script. Any variables specified in message will be evaluated to their current values.

If a variable expression is specified in message that does not exist, or if message cannot be evaluated for any reason:

1. A warning-level message will be printed to the console/log file indicating why the message could not be evaluated.

2. The original message, not evaluated, will be printed to the console/log file.

3. The Results View comment field will contain the original message, plus a warning note explaining why the message could not be evaluated.

4. Any problems that occur when evaluating the message will not be counted as a warning in the results report warnings total.

5. The execution of the script will continue as if no problem occurred.

Format

The reportPassed method has the following command format:

reportPassed(message);

Command Parameters

message

a String specifying the message to write to the console/log file and Results view. May contain embedded function and variable expressions using the Transforms syntax. Must NOT be null.

Throws

AbstractScriptException

represents an exception that may be thrown during the execution of a script where the exception should be reported to an end user through the controller.

Example

Prints a reported Passed message to the Results view.

reportPassed("a reported Passed message");

resume

Resume the script after abort. Allows the caller to reset a previously fired abort request so that script execution can successfully continue from that point on. Caller must first catch the StopScriptRuntimeException that gets thrown by the abort() request and then call resume().

Format

The resume method has the following command format:

resume();

Example

Aborts, catches exception and then resumes.

try {
 info("Perform any steps inside a try-catch block...");
 abort()
 info("This line will not be run.");
} catch (StopScriptRuntimeException e) {
 // optionally take any corrective action and optionally resume script
 resume();
}

run

Defines the run() section of a script. The run() section is automatically added to the script code when you create a script project in OpenScript.

Add code to be executed during each iteration for this virtual user.

Format

The run method has the following command format:

run();

Throws

Exception

on any exception. On error, scripts should throw AbstractScriptException instead of Exception whenever possible to provide more detail.

Example

Defines the run() section of a script.

public void run() throws Exception {
}

runScript

Find and run an encrypted script given the script's name, workspace, repository and its password.

If the script cannot be found on the local machine using the given repository, this method will ask this script's controller to find the script on its machine.

In order to run this script, iterationCount must be greater or equal to 1.

The script's initialize and finish sections will be executed exactly once. The initialize section will be executed first; the finish section will be executed last; the run section may be executed at most iterationCount times between the initialize and finish sections.

If there is an error in the initialize section, the run section will not be executed.

If the playback error handling preference "On iteration failure, do not run more iterations" is true and there is an error thrown during the run section, the remaining iterations will not be executed.

If there is an error during child script execution, the "Child Script Failed" error recovery setting will recover the error according to its setting.

Format

The runScript method has the following command format:

runScript(repository, scriptPathRelToRepository, iterationCount);

runScript(repository, scriptPathRelToRepository, iterationCount, scriptPassword);

Command Parameters

repository

a String specifying the name of the repository where the script is stored. For example, "Repository1".

scriptPathRelToRepository

a String specifying the path to the script within the named repository. Any leading file separator on the path, such as / or \, is ignored. Must not be null. Legacy repository structures required a trailing "!" character at the end of folder names.

iterationCount

an integer that defines how many times this script's run section should run. If iterationCount is less than 1, then the script will not run at all.

scriptPassword

a String specifying the password of the script. May be null if the script is not encrypted.

Throws

AbstractScriptException

represents an exception that may be thrown during the execution of a script where the exception should be reported to an end user through the controller.

Example

Run an encrypted script for 5 iterations.

runScript("Repository1", "scripts/crmApp/staging/Script19", 5, "MyEncryptionKey")

setErrorRecovery

Sets the script Error Recovery settings.

The error recovery action can be set to the following:

.Fail
.Ignore
.Pause
.ReportErrorAndContinue
.Warn

The error recovery settings IDs are specific to the script type as follows:

Basic Script Settings

setErrorRecovery(BasicErrorRecovery.setting,
  ErrorRecoveryAction.setting);

Utilities Settings

setErrorRecovery(UtilitiesErrorRecovery.setting,
  ErrorRecoveryAction.setting);

Functional Test Module Script Settings

setErrorRecovery(FTErrorRecovery.setting,
  ErrorRecoveryAction.setting);

Web Functional Module Script Settings

setErrorRecovery(WebErrorRecovery.setting,
  ErrorRecoveryAction.setting);

Oracle EBS/Forms Functional Module Script Settings

setErrorRecovery(FormsErrorRecovery.setting,
  ErrorRecoveryAction.setting);

Http Load Module Script Settings

setErrorRecovery(HttpErrorRecovery.setting,
  ErrorRecoveryAction.setting);

Adobe Flex (AMF) Load Module Script Settings

setErrorRecovery(AmfErrorRecovery.setting,
  ErrorRecoveryAction.setting);

Oracle EBS/Forms Load Module Script Settings

setErrorRecovery(NcaErrorRecovery.setting,
  ErrorRecoveryAction.setting);

Format

The setErrorRecovery method has the following command format:

setErrorRecovery(id, action);

Command Parameters

id

an ErrorRecoveryId enum specifying the error recovery type.

action

an ErrorRecoveryAction enum specifying the error recovery action.

Example

Sets the error recovery action for "file not found" to Warn.

setErrorRecovery(BasicErrorRecovery.ERR_FILE_NOT_FOUND,
  ErrorRecoveryAction.Warn);

setLastResult

Helper method to set the last run Result.

Format

The setLastResult method has the following command format:

setLastResult(result);

Command Parameters

result

an IResult object specifying the last result details.

Example

How to build Result object for http.verifyText() API.

import oracle.oats.scripting.modules.functionalTest.api.exceptions.MatchException;
import oracle.oats.scripting.modules.basic.api.IResult.ResultCode;
//[...]
AttachedData data = new AttachedData();
data.set(ResultDeclaration.verifyText_expected, "expected text");
data.set(ResultDeclaration.verifyText_actual, "actual text");
long duration = 1000;
MatchException matchException = new MatchException("Text match test failed", null, 
  false);
IResult result = new Result(ResultCode.FAIL, duration, matchException, data, 
  matchException.getLocalizedMessage());
setLastResult(result);

syncPointWait

Notify the controller that the virtual user has reached the specified synchronization point.

The virtual user will wait until the controller responds indicating that it is OK to proceed. The controller defines when it is OK to proceed; for example, continue running only after 80% of virtual users have reached the synchronization point.

When running from within OpenScript, the synchronization point will be released immediately; the virtual user will not wait.

This method will update the last result object with details of the synchronization point operation, including how long the operation took.

Format

The syncPointWait method has the following command format:

syncPointWait(syncPointName);

Command Parameters

syncPointName

a String specifing the unique synchronization point name upon which to notify and wait, as defined in the controller.

Throws

AbstractScriptException

represents an exception that may be thrown during the execution of a script where the exception should be reported to an end user through the controller.

Example

Prints a reported Passed message to the Results view.

info("VU reached the 'Login' sync point. " +
  "Waiting for other users to reach it before proceeding...");
syncPointWait("login");
info("VU passed the 'Login' sync point");

think

Inserts "think time" delay into the script.

This method honors the VU Pacing settings defined in playback preferences. Invoke this method to sleep the current VUser for a given number of seconds. If the VUser is stopped for any reason (for example, if the Stop button is pressed), the VUser will be awakened immediately.

The VUser's status will be updated to reflect the fact that it is "thinking."

Format

The think method has the following command format:

think(seconds);

Command Parameters

seconds

a String specifing the unique synchronization point name upon which to notify and wait, as defined in the controller.

Throws

AbstractScriptException

represents an exception that may be thrown during the execution of a script where the exception should be reported to an end user through the controller.

Returns

false if the delay operation is interrupted prematurely, otherwise returns true.

Example

Prints a reported Passed message to the Results view.

Inserts 10.0 seconds of "think time" into the script.
think(10.0);

toBoolean

Helper method to parse a String as a boolean.

The string is also transformed before it is returned using eval(String).

Format

The toBoolean method has the following command format:

toBoolean(data);

Command Parameters

data

a String specifying the data to parse. Must not be null.

Throws

AbstractScriptException

on any failure to transform the string.

Returns

The boolean form of the parsed, evaluated data.

Example

Convert as String to a Boolean.

boolean result = toBoolean("true");

toDate

Helper method to parse a String as a Date.

The string is also transformed before it is returned using eval(String).

Format

The toDate method has the following command format:

toDate(data);

Command Parameters

data

a String specifying the data to parse. Must not be null.

Throws

AbstractScriptException

on any failure to transform the string.

ParseException

on failure to parse the string.

Returns

The Date form of the parsed, evaluated data.

Example

Convert a String to a date.

import java.util.Date;
//[...]
Date today = toDate("{{@today(MM/dd/yyyy)}}");
info("Today transform: " + today.toString());
Date stoday = toDate("01/04/2016");
info("Today string: " + stoday.toString());

toDouble

Helper method to parse a String as a signed decimal double in base 10.

The string is also transformed before it is returned using eval(String).

Format

The toDouble method has the following command format:

toDouble(data);

Command Parameters

data

a String specifying the data to parse. Must not be null.

Throws

AbstractScriptException

on any failure to transform the string.

NumberFormatException

if the string does not contain a parsable double.

Returns

The double form of the parsed, evaluated data.

Example

Convert a String to a Double.

double value = toDouble("10.0");

toInt

Helper method to parse a String as a signed decimal integer in base 10.

The string is also transformed before it is returned using eval(String).

Format

The toInt method has the following command format:

toInt(data);

Command Parameters

data

a String specifying the data to parse. Must not be null.

Throws

AbstractScriptException

on any failure to transform the string.

NumberFormatException

if the string does not contain a parsable Integer.

Returns

The integer form of the parsed, evaluated data.

Example

Convert a String to an Integer.

int count = toInt("10");

toList

Helper method to convert a list of arguments into a List<String>.

The string is also transformed before it is returned using eval(String).

Format

The toList method has the following command format:

toList(values);

Command Parameters

values

The Strings specifying the list of values.

Throws

AbstractScriptException

on any failure to transform any of the the values.

Returns

The List<String, String>.

Example

Converts a list of arguments into a List<String>.

callFunction("myFunction", "name", "1", "10.0", "100", "true", "val2",
  toList("list1", "list2", "list3"),
  toMap("key1=val1", "key2=val2", "key3=val3"));

toLong

Helper method to parse a String as a signed decimal long in base 10.

The string is also transformed before it is returned using eval(String).

Format

The toLong method has the following command format:

toLong(data);

Command Parameters

data

a String specifying the data to parse. Must not be null.

Throws

AbstractScriptException

on any failure to transform the string.

NumberFormatException

if the string does not contain a parsable long.

Returns

The long form of the parsed, evaluated data.

Example

Convert as String to a Long.

long counter = toLong("100");

toMap

Helper method to convert a list of arguments into a Map<String>.

The string is also transformed before it is returned using eval(String).

Format

The toMap method has the following command format:

toMap(values);

Command Parameters

values

The Strings specifying the key=value pairs.

Throws

AbstractScriptException

on any failure to transform any of the the values.

Returns

The Map<String, String>.

Example

Converts a list of arguments into a Map<String>.

callFunction("myFunction", "name", "1", "10.0", "100", "true", "val2",
  toList("list1", "list2", "list3"),
  toMap("key1=val1", "key2=val2", "key3=val3"));

warn

Writes a warning message to the console/log file, and to the Result View.

This method will never alter the flow of a script, such as stopping the script. Any variables specified in message will be evaluated to their current values.

If a variable expression is specified in message that does not exist, or if message cannot be evaluated for any reason:

1. A warning-level message will be printed to the console/log file indicating why the message could not be evaluated.

2. The original message, not evaluated, will be printed to the console/log file.

3. The Results View comment field will contain the original message, plus a warning note explaining why the message could not be evaluated.

4. Any problems that occur when evaluating the message will not be counted as a warning in the results report warnings total.

5. The execution of the script will continue as if no problem occurred.

Format

The warn method has the following command format:

warn(message);

Command Parameters

message

a String specifying the message to write to the console/log file and Results view. May contain embedded function and variable expressions using the Transforms syntax. Must NOT be null.

Throws

AbstractScriptException

represents an exception that may be thrown during the execution of a script where the exception should be reported to an end user through the controller.

Example

Prints a warning message to the console and Results view.

warn("a Warning message");