A secure sandbox for executing JavaScript in Java apps using the Nashorn engine.
Also see Rhino Sandbox.
Part of the Java Delight Suite.
The sandbox by default blocks access to all Java classes.
Classes, which should be used in JavaScript, must be explicitly allowed.
NashornSandbox sandbox = NashornSandboxes.create();
sandbox.allow(File.class);
sandbox.eval("var File = Java.type('java.io.File'); File;")
Or you can inject your java object as a JS global variable
NashornSandboxes sandbox = NashornSandboxes.create();
sandbox.inject("fromJava", new Object());
sandbox.eval("fromJava.getClass();");
The sandbox also allows limiting the CPU time of scripts. This allows terminating scripts which contain infinite loops and other problematic code.
NashornSandbox sandbox = NashornSandboxes.create();
sandbox.setMaxCPUTime(100);
sandbox.setExecutor(Executors.newSingleThreadExecutor());
sandbox.eval("while (true) { };");
This code will raise a ScriptCPUAbuseException.
<dependency>
<groupId>org.javadelight</groupId>
<artifactId>delight-nashorn-sandbox</artifactId>
<version>0.0.6</version>
</dependency>
Find out latest version here.
If you are looking for a JAR with all dependencies, you can download it from here.
Eduardo Velasques: API extensions to block/allow Rhino system functions; Capability to block/allow variables after Sandbox has been created.