Executing arbitrary script

From Trephine

Jump to: navigation, search

Basic interactive demo showing how to execute arbitrary JavaScript within the privileged trephine applet context.

You must have JavaScript enabled to run this demo.

/* Status and element functions. */
var e = function(tag,index){ return demotab.getElementsByTagName(tag)[index||0]; };
var status = function(msg) {
  if (!msg) return e('p').style.display = 'none';
  e('p').style.display = '';
  e('p').innerHTML = msg;
};
 
/* Setup demo */
var setup = function() {
  e('form').onsubmit = function(event) {
    try {
      if (!trephine || !trephine.loaded) throw "Error: trephine not loaded.";
      if (!trephine.hasPermission()) throw "Error: elevated permissions have not been granted.";
      var result = trephine.exec( 'js', e('textarea').value );
      var boxtype = result.success ? 'success' : 'error';
      e('div').innerHTML = '<p class="' + boxtype + 'box" style="float:none">' + (result.result.toString() + '' || result.error) + '</p>';
    } catch(err) {
      e('div').innerHTML = '<p class="errorbox" style="float:none">' + err + '</p>';
    }
    return false;
  };
};
 
/* Load trephine */
status('<span class="spinner"></span> Loading trephine...');
trephine.load({
  debug: true, // Enables debug logging to the Java Console
  engines: ['js'], // Initialize the JavaScript engine as soon as possible
  onload: function() { // Immediately prompt for permissions
    status('<span class="spinner"></span> Asking for elevated permissions...');
    trephine.askPermission( function(response) {
      if (!response) { // Short-circuit if permission request was denied
        return demotab.innerHTML = '<div class="error">Sorry, you must grant trephine privileges to enjoy this demo.</div>';
      }
      setup();
      status('Permission request granted.');
      setTimeout( function(){ status(); }, 2000 );
    } );
  },
  onerror: function() {
    e('form').innerHTML = '<p class="error">Sorry, you must be have Java 1.5 or higher to use trephine.</p>';
    status();
  }
});
<p class="notice"></p>
<form class="arbitraryscript">
  <input class="button" type="submit" value="execute"/>
  <h4>Code:</h4>
  <textarea></textarea>
  <h4>Result:</h4>
  <div></div>
</form>
.arbitraryscript input {
  float: right;
}
.arbitraryscript textarea {
  width: 890px;
  height: 100px;
  background: #fffff0;
  margin-bottom: 18px;
}
.arbitraryscript h4 {
  font-weight: bold;
}
.demotab .spinner {
  float: left;
  height: 20px;
  width: 25px;
  background: url("skins/common/images/spinner.gif");
  background-repeat: no-repeat;
}

Contents

Activation

  1. Activate the demo by clicking the specified link.
  2. You may see a Java Security dialog, if so, click "Run" or "Trust" to indicate your acceptance
  3. In the "Trephine permission request" dialog, answer the math challenge and click "OK" to grant scripts on this page elevated privileges.

Usage

  1. Enter desired JavaScript into the code box provided.
  2. Click the execute button in the upper-right corner to trigger trephine's exec() function.
  3. Repeat as many times as you like.
Note
  • For return value, the script engine sends back the result of the last successfully executed command or expression, or an exception if one was thrown.

Examples

More complicated examples can be found on other Demo pages, but here are a few to get you started.

List available ScriptEngineFactories

This bit of script will display a list of all the ScriptEngineFactory instances available to the ScriptEngineManager. On this page, this will only show the Rhino JavaScript engine. Adapted from Sun's article on Scripting for the Java Platform (Code Example 3).

var buf = [];
for (var i=0; i<manager.engineFactories.size(); i++) {
    buf.push(manager.engineFactories.get(i).toString());
}
buf.join("\n");

FileDialog

This script will launch a native FileDialog to allow the user to pick a file, then output the full path to the selected location.

var dialog = new java.awt.FileDialog(
  new java.awt.Frame(),
  "Pick something",
  java.awt.FileDialog.LOAD
); 
dialog.show(); 
dialog.getDirectory() + dialog.getFile(); // Full path to file

Note: As written, the above will deadlock Mac OS X 10.4 (both Firefox and Safari) to the point that Force Quit is the only option for regaining control of the browser. To safely launch a FileDialog, it must be executed from within a separate child thread. See the file browser demo for an example.

Simple JFrame

This script creates a very simple non-modal JFrame window with no visible text. Adapted from Sun's FrameDemo.java

javax.swing.SwingUtilities.invokeLater(new java.lang.Runnable({
  run: function() {
    var frame = new javax.swing.JFrame("WOOT!");
    frame.setDefaultCloseOperation(javax.swing.JFrame.DISPOSE_ON_CLOSE);
    var emptyLabel = new javax.swing.JLabel("");
    emptyLabel.setPreferredSize(new java.awt.Dimension(175, 100));
    frame.getContentPane().add(emptyLabel, java.awt.BorderLayout.CENTER);
    frame.pack();
    frame.setVisible(true);
  }
}));

Copy from System Clipboard

This script will pull text data from the System clipboard. Other types of data can also be read, depending on the DataFlavor provided to the getTransferData() method.

Note: This is known to fail in Ubuntu Linux 8.04. Your experience with other operating systems may vary.

var transferable = java.awt.Toolkit.defaultToolkit.systemClipboard.getContents(null);
var stringReader = transferable.getTransferData(java.awt.datatransfer.DataFlavor.plainTextFlavor)
var buf = new java.io.BufferedReader(stringReader), line, data = [];
while ((line=buf.readLine())!=null) data[data.length] = line;
data.join("\n");