Versions Compared


  • This line was added.
  • This line was removed.
  • Formatting was changed.


Code Block
import java.util.PropertyPermission;
import org.codehaus.janino.ScriptEvaluator;

public class SandboxDemo {

    public static void
    main(String[] args) throws Exception {

        // Create a JANINO script evaluator. The example, however, will work as fine with ExpressionEvaluators,
        // ClassBodyEvaluators and SimpleCompilers - or with any class you do not trust, e.g. a third-party
        // library.
        ScriptEvaluator se = new ScriptEvaluator();

        // Compile a simple script which reads two system variables - 'foo' and 'bar'.
            "System.getProperty(\"foo\");\n" +

        // Now we create a 'Permissions' object which permitsallows to read the system variable 'foo', and forbids
        // everything else.
        Permissions permissions = new Permissions();
        permissions.add(new PropertyPermission("foo", "read"));

        // Before we evaluate the script, we confine the permissions on all classes loaded through the
        // ScriptEvaluator's class loader. Each *Evaluator creates a new class loader exclusively for loading the
        // classes it generates.
        Sandbox.confine(se.getMethod().getDeclaringClass().getClassLoader(), permissions);

        // Finally we evaluate the script. Getting system property 'foo' will succeed, and getting 'bar' will
        // throw an InvocationTargetException caused by
        // access denied (java.util.PropertyPermission bar read)
        se// Et voila!

"" lives in is available on "de.unkrig.commons".