classfilter.js revision 974:57500636de77
1/*
2 * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 */
23
24/**
25 * ClassFilter to filter out java classes in a script engine.
26 *
27 * @test
28 * @run
29 */
30
31var NashornScriptEngineFactory = Java.type("jdk.nashorn.api.scripting.NashornScriptEngineFactory");
32
33var fac = new NashornScriptEngineFactory();
34// allow only "java.*" classes to be accessed
35var e = fac.getScriptEngine(
36    function(name) name.startsWith("java."));
37
38function evalIt(str) {
39    print(str + " evalutes to " + e.eval(str));
40}
41
42function evalExpectError(str) {
43    try {
44        print(e.eval(str));
45        fail("expected error for: " + str);
46    } catch(exp) {
47        print(str + " throws " + exp);
48    }
49}
50
51evalIt("typeof javax.script.ScriptContext");
52evalIt("typeof javax.script.ScriptEngine");
53evalIt("typeof java.util.Vector");
54evalIt("typeof java.util.Map");
55evalIt("typeof java.util.HashMap");
56// should be able to call methods, create objects of java.* classes
57evalIt("var m = new java.util.HashMap(); m.put('foo', 42); m");
58evalIt("java.lang.System.out.println");
59evalIt("java.lang.System.exit");
60
61evalExpectError("new javax.script.SimpleBindings");
62evalExpectError("Java.type('javax.script.ScriptContext')");
63evalExpectError("java.lang.Class.forName('javax.script.ScriptContext')");
64
65try {
66    fac["getScriptEngine(ClassFilter)"](null);
67    fail("should have thrown NPE");
68} catch (e) {
69    if (! (e instanceof java.lang.NullPointerException)) {
70        fail("NPE expected, got " + e);
71    }
72}
73