VCF Automation Blog

from Stefan Schnell

Use Java Output Stream in JavaScript Runtime Environment


In a normal case it is not possible to get the information from the Java standard output stream (stdout) and the standard error output stream (stderr) in the JavaScript runtime environment. With a tiny trick it is possible to do that. It is necessary to redirect the Java standard streams to files in the temporary directory, to read the content from the files and to delete the files finally. On this way the standard methods System.stdout and System.stderr with VCF Automation, and the methods of the Java PrintStream classes java.lang.System.out and java.lang.System.err can be used.

vcf automation with output from java standard output stream
/**
 * Example to redirect the standard streams to files.
 *
 * @author Stefan Schnell <mail@stefan-schnell.de>
 * @license MIT
 * @version 0.1.1
 *
 * Set the system property in the control center:
 * com.vmware.scripting.javascript.allow-native-object = true
 */

// Stores the base of the standard streams
var standardOut = java.lang.System.out;
var standardErr = java.lang.System.err;


var uuid = System.nextUUID();

// Generates file names, with the temporary directory as target
var stdoutFileName = System.appendToPath(
  System.getTempDirectory(), uuid + "_stdout.txt"
);
var stderrFileName = System.appendToPath(
  System.getTempDirectory(), uuid + "_stderr.txt"
);


// Redirects the standard output streams to the files
java.lang.System.setOut(
  java.io.PrintStream(java.io.FileOutputStream(stdoutFileName))
);
java.lang.System.setErr(
  java.io.PrintStream(java.io.FileOutputStream(stderrFileName))
);


// Here an example to send a few information to the standard output
// streams, otherwise your code would be here.
System.stdout("System.stdout: Hello standard output stream");
java.lang.System.out.println("java.lang.System.out.println: " +
  "Hello standard output stream");

System.stderr("System.stderr: Hello standard error output stream");
java.lang.System.err.println("java.lang.System.err.println: " +
  "Hello standard error output stream");


// Redirects the standard stream to the base
java.lang.System.setOut(java.io.PrintStream(standardOut));
java.lang.System.setErr(java.io.PrintStream(standardErr));


// Reads the files and outputs the information
var stdoutReadFile = new FileReader(stdoutFileName);
if (stdoutReadFile.exists) {
  stdoutReadFile.open();
  System.log(stdoutReadFile.readAll());
  stdoutReadFile.close();
}

var stderrReadFile = new FileReader(stderrFileName);
if (stderrReadFile.exists) {
  stderrReadFile.open();
  System.log(stderrReadFile.readAll());
  stderrReadFile.close();
}


// Deletes the files
var stdoutFile = new File(stdoutFileName);
stdoutFile.deleteFile();

var stderrFile = new File(stderrFileName);
stderrFile.deleteFile();