| Share
  1. Explore
    Introduction, screen-shots, features, limitations
  2. Getting started
    Prerequisites, download, install, browser configuration, record, playback, view logs
  3. Sahi Scripting Basics - I
    Statements, variables, functions, conditions and looping, _include
  4. Sahi Scripting Basics - II
  5. Sahi APIs (built-in functions)
    1. Browser Accessor APIs
    2. Browser Action APIs
    3. Miscellaneous APIs
  6. Sahi Scripting - Calling Java
  7. Exception handling using try-catch
  8. Recovering without try-catch using _setRecovery
  9. Data Driven Testing
    _getDB, CSV Files, Excel, Databases
  10. Multithreaded Playback (Parallel execution)
    suites, commandline, ant
  11. Advanced techniques, tips and examples
    1. HTTPS/SSL Sites
    2. Configuring an External proxy
    3. Adding jars to Sahi's classpath
  12. Other language drivers Driving Sahi from Java, Ruby etc.
    1. Java
    2. Ruby

Sahi Scripting - Calling Java ·

Sahi scripts run on the Rhino javascript engine. This allows Sahi to call any Java code in the classpath of Sahi.

Calling Java code only requires prepending the full package name with “Packages.”

Below is a simple example to print on the console.

function printThroughJava(s){
    Packages.java.lang.System.out.println("Through Java: " + s);
}
printThroughJava("Hi there");
// Should print "Through Java: Hi there" on the console.

Another thing to note is that Javascript does not have types, so variable types are declared with just var.

For example:

function printThroughJava(s){
    var sysout = Packages.java.lang.System.out; 
    // sysout would have been of type java.io.PrintStream in java. 
    // but here declared with only var
    sysout.println("Through Java: " + s);
}

This is how _readFile is implemented in Sahi:

// Part of lib.js
// Note: ""+ is used to convert Java string to Javascript string
Sahi.prototype._readFile = function (filePath) {
    return "" + Packages.net.sf.sahi.util.Utils.readFileAsString(filePath);
};

Have a look at Rhino’s documentation for a detailed discussion on Scripting Java through Rhino



---