aboutsummaryrefslogtreecommitdiff
path: root/test/src/jdk/nashorn/api/scripting/test/PluggableJSObjectTest.java
blob: 918e9318785b718b0c45473270176f441482dd10 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
/*
 * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

package jdk.nashorn.api.scripting.test;

import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;

import java.nio.IntBuffer;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Set;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import jdk.nashorn.api.scripting.AbstractJSObject;
import jdk.nashorn.api.scripting.ScriptObjectMirror;
import org.testng.annotations.Test;

/**
 * Tests for pluggable external impls. of jdk.nashorn.api.scripting.JSObject.
 *
 * JDK-8024615: Refactor ScriptObjectMirror and JSObject to support external
 * JSObject implementations.
 */
@SuppressWarnings("javadoc")
public class PluggableJSObjectTest {
    public static class MapWrapperObject extends AbstractJSObject {
        private final HashMap<String, Object> map = new LinkedHashMap<>();

        public HashMap<String, Object> getMap() {
            return map;
        }

        @Override
        public Object getMember(final String name) {
            return map.get(name);
        }

        @Override
        public void setMember(final String name, final Object value) {
            map.put(name, value);
        }

        @Override
        public boolean hasMember(final String name) {
            return map.containsKey(name);
        }

        @Override
        public void removeMember(final String name) {
            map.remove(name);
        }

        @Override
        public Set<String> keySet() {
            return map.keySet();
        }

        @Override
        public Collection<Object> values() {
            return map.values();
        }
    }

    @Test
    // Named property access on a JSObject
    public void namedAccessTest() {
        final ScriptEngineManager m = new ScriptEngineManager();
        final ScriptEngine e = m.getEngineByName("nashorn");
        try {
            final MapWrapperObject obj = new MapWrapperObject();
            e.put("obj", obj);
            obj.getMap().put("foo", "bar");

            // property-like access on MapWrapperObject objects
            assertEquals(e.eval("obj.foo"), "bar");
            e.eval("obj.foo = 'hello'");
            assertEquals(e.eval("'foo' in obj"), Boolean.TRUE);
            assertEquals(e.eval("obj.foo"), "hello");
            assertEquals(obj.getMap().get("foo"), "hello");
            e.eval("delete obj.foo");
            assertFalse(obj.getMap().containsKey("foo"));
            assertEquals(e.eval("'foo' in obj"), Boolean.FALSE);
        } catch (final Exception exp) {
            exp.printStackTrace();
            fail(exp.getMessage());
        }
    }

    // @bug 8062030: Nashorn bug retrieving array property after key string concatenation
    @Test
    // ConsString attribute access on a JSObject
    public void consStringTest() {
        final ScriptEngineManager m = new ScriptEngineManager();
        final ScriptEngine e = m.getEngineByName("nashorn");
        try {
            final MapWrapperObject obj = new MapWrapperObject();
            e.put("obj", obj);
            e.put("f", "f");
            e.eval("obj[f + 'oo'] = 'bar';");

            assertEquals(obj.getMap().get("foo"), "bar");
            assertEquals(e.eval("obj[f + 'oo']"), "bar");
            assertEquals(e.eval("obj['foo']"), "bar");
            assertEquals(e.eval("f + 'oo' in obj"), Boolean.TRUE);
            assertEquals(e.eval("'foo' in obj"), Boolean.TRUE);
            e.eval("delete obj[f + 'oo']");
            assertFalse(obj.getMap().containsKey("foo"));
            assertEquals(e.eval("obj[f + 'oo']"), null);
            assertEquals(e.eval("obj['foo']"), null);
            assertEquals(e.eval("f + 'oo' in obj"), Boolean.FALSE);
            assertEquals(e.eval("'foo' in obj"), Boolean.FALSE);
        } catch (final Exception exp) {
            exp.printStackTrace();
            fail(exp.getMessage());
        }
    }

    public static class BufferObject extends AbstractJSObject {
        private final IntBuffer buf;

        public BufferObject(final int size) {
            buf = IntBuffer.allocate(size);
        }

        public IntBuffer getBuffer() {
            return buf;
        }

        @Override
        public Object getMember(final String name) {
            return name.equals("length")? buf.capacity() : null;
        }

        @Override
        public boolean hasSlot(final int i) {
            return i > -1 && i < buf.capacity();
        }

        @Override
        public Object getSlot(final int i) {
            return buf.get(i);
        }

        @Override
        public void setSlot(final int i, final Object value) {
            buf.put(i, ((Number)value).intValue());
        }

        @Override
        public boolean isArray() {
            return true;
        }
    }

    @Test
    // array-like indexed access for a JSObject
    public void indexedAccessTest() {
        final ScriptEngineManager m = new ScriptEngineManager();
        final ScriptEngine e = m.getEngineByName("nashorn");
        try {
            final BufferObject buf = new BufferObject(2);
            e.put("buf", buf);

            // array-like access on BufferObject objects
            assertEquals(e.eval("buf.length"), buf.getBuffer().capacity());
            e.eval("buf[0] = 23");
            assertEquals(buf.getBuffer().get(0), 23);
            assertEquals(e.eval("buf[0]"), 23);
            assertEquals(e.eval("buf[1]"), 0);
            buf.getBuffer().put(1, 42);
            assertEquals(e.eval("buf[1]"), 42);
            assertEquals(e.eval("Array.isArray(buf)"), Boolean.TRUE);
        } catch (final Exception exp) {
            exp.printStackTrace();
            fail(exp.getMessage());
        }
    }

    public static class Adder extends AbstractJSObject {
        @Override
        public Object call(final Object thiz, final Object... args) {
            double res = 0.0;
            for (final Object arg : args) {
                res += ((Number)arg).doubleValue();
            }
            return res;
        }

        @Override
        public boolean isFunction() {
            return true;
        }
    }

    @Test
    // a callable JSObject
    public void callableJSObjectTest() {
        final ScriptEngineManager m = new ScriptEngineManager();
        final ScriptEngine e = m.getEngineByName("nashorn");
        try {
            e.put("sum", new Adder());
            // check callability of Adder objects
            assertEquals(e.eval("typeof sum"), "function");
            assertEquals(((Number)e.eval("sum(1, 2, 3, 4, 5)")).intValue(), 15);
        } catch (final Exception exp) {
            exp.printStackTrace();
            fail(exp.getMessage());
        }
    }

    public static class Factory extends AbstractJSObject {
        @SuppressWarnings("unused")
        @Override
        public Object newObject(final Object... args) {
            return new HashMap<Object, Object>();
        }

        @Override
        public boolean isFunction() {
            return true;
        }
    }

    @Test
    // a factory JSObject
    public void factoryJSObjectTest() {
        final ScriptEngineManager m = new ScriptEngineManager();
        final ScriptEngine e = m.getEngineByName("nashorn");
        try {
            e.put("Factory", new Factory());

            // check new on Factory
            assertEquals(e.eval("typeof Factory"), "function");
            assertEquals(e.eval("typeof new Factory()"), "object");
            assertEquals(e.eval("(new Factory()) instanceof java.util.Map"), Boolean.TRUE);
        } catch (final Exception exp) {
            exp.printStackTrace();
            fail(exp.getMessage());
        }
    }

    @Test
    // iteration tests
    public void iteratingJSObjectTest() {
        final ScriptEngineManager m = new ScriptEngineManager();
        final ScriptEngine e = m.getEngineByName("nashorn");
        try {
            final MapWrapperObject obj = new MapWrapperObject();
            obj.setMember("foo", "hello");
            obj.setMember("bar", "world");
            e.put("obj", obj);

            // check for..in
            Object val = e.eval("var str = ''; for (i in obj) str += i; str");
            assertEquals(val.toString(), "foobar");

            // check for..each..in
            val = e.eval("var str = ''; for each (i in obj) str += i; str");
            assertEquals(val.toString(), "helloworld");
        } catch (final Exception exp) {
            exp.printStackTrace();
            fail(exp.getMessage());
        }
    }

    // @bug 8137258: JSObjectLinker and BrowserJSObjectLinker should not expose internal JS objects
    @Test
    public void hidingInternalObjectsForJSObjectTest() throws Exception {
        final ScriptEngineManager engineManager = new ScriptEngineManager();
        final ScriptEngine e = engineManager.getEngineByName("nashorn");

        final String code = "function func(obj) { obj.foo = [5, 5]; obj.bar = {} }";
        e.eval(code);

        // call the exposed function but pass user defined JSObject impl as argument
        ((Invocable)e).invokeFunction("func", new AbstractJSObject() {
            @Override
            public void setMember(final String name, final Object value) {
                // make sure that wrapped objects are passed (and not internal impl. objects)
                assertTrue(value.getClass() == ScriptObjectMirror.class);
            }
        });
    }
}