Java Code Examples for jdk.nashorn.api.scripting.ScriptObjectMirror

The following are top voted examples for showing how to use jdk.nashorn.api.scripting.ScriptObjectMirror. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: Nasapi   File: ScriptObjectMirrors.java   Source Code and License 8 votes vote down vote up
public static Object convert(Object original) {
	if (original == null) {
		return null;
	} else if (original instanceof String || original instanceof Integer || original instanceof Long || original instanceof Boolean || original instanceof Double) {
		return original;
	} else if (original instanceof ScriptObjectMirror) {
		ScriptObjectMirror jsOriginal = (ScriptObjectMirror)original;
		if (jsOriginal.isArray()) {
			List<Object> listResult = new ArrayList<Object>();
			Integer length = (Integer)jsOriginal.get("length");
			for (int i = 0; i < length; i++) {
				listResult.add(convert(jsOriginal.get("" + i)));
			}
			return listResult;
		} else if (jsOriginal.isFunction()) {
			// can't convert it...
			return null;
		}
		Map<String,Object> mapResult = new LinkedHashMap<String,Object>();
		for (Map.Entry<String,Object> entry: jsOriginal.entrySet()) {
			mapResult.put(entry.getKey(), convert(entry.getValue()));
		}
		return mapResult;
	}
	return original;
}
 
Example 2
Project: Thrush   File: LoginTest.java   Source Code and License 7 votes vote down vote up
@Test
    public void test6() throws Exception {
        Document document = Jsoup.parse(FileUtils.readFileToString(new File("/Users/eddy/Desktop/content")));
        Elements elements = document.getElementsByTag("script");
//        String result = elements.stream().filter(e -> e.data().contains("globalRepeatSubmitToken") && e.childNodes().size() > 0)
//                .findFirst().map(e -> e.childNode(0).outerHtml()).orElse(StringUtils.EMPTY);

        ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
        ScriptEngine engine = scriptEngineManager.getEngineByExtension("js");
//        engine.eval(result);
//        Object o = engine.get("globalRepeatSubmitToken");
//        System.out.println(o);

//        ticketInfoForPassengerForm
        String ticketInfo = elements.stream().filter(e -> e.data().contains("ticketInfoForPassengerForm") && e.childNodes().size() > 0)
                .findFirst().map(e -> e.childNode(0).outerHtml()).orElse(StringUtils.EMPTY);
        ticketInfo = ticketInfo.substring(0, ticketInfo.lastIndexOf("var"));
        engine.eval(ticketInfo);
        ScriptObjectMirror o2 = (ScriptObjectMirror) engine.get("ticketInfoForPassengerForm");
        System.out.println(o2.get("purpose_codes"));

    }
 
Example 3
Project: VISNode   File: ObjectExtractionProcess.java   Source Code and License 6 votes vote down vote up
@Override
public void process() {
    if (objectList == null) {
        return;
    }
    Object obj = scriptRunner.invokeFunction("process", objectList);
    if (obj != null) {
        if (obj instanceof ExtractedObject) {
            resultImage = ((ExtractedObject) obj).getMatrix();
        }
        if (obj instanceof ScriptObjectMirror) {
            ScriptObjectMirror res = (ScriptObjectMirror) obj;
            List<ExtractedObject> list = res.values().stream().map((o) -> (ExtractedObject) o).collect(Collectors.toList());
            resultImage = resultFromObjects(list);
        }
        if (obj instanceof List) {
            resultImage = resultFromObjects((List<ExtractedObject>) obj);
        }
    }
}
 
Example 4
Project: centraldogma   File: Polyfills.java   Source Code and License 6 votes vote down vote up
private static String logMessage(Object value) {
    final int length = length(value);
    if (length < 0) {
        return String.valueOf(value);
    }

    if (length == 1) {
        @SuppressWarnings("unchecked")
        final Object first = ((Map<String, Object>) value).get("0");
        if (first instanceof ScriptObjectMirror) {
            final ScriptObjectMirror firstMirror = (ScriptObjectMirror) first;
            if (firstMirror.isArray()) {
                return logMessage(firstMirror, length(firstMirror));
            }
        }

        return String.valueOf(first);
    } else {
        return logMessage((ScriptObjectMirror) value, length);
    }
}
 
Example 5
Project: karate   File: Script.java   Source Code and License 6 votes vote down vote up
public static ScriptValue evalFunctionCall(ScriptObjectMirror som, Object callArg, ScriptContext context) {
    // injects the 'karate' variable into the js function body
    // also ensure that things like 'karate.get' operate on the latest variable state
    som.setMember(ScriptBindings.KARATE, context.bindings.bridge);
    Object result;
    try {
        if (callArg != null) {
            result = som.call(som, callArg);
        } else {
            result = som.call(som);
        }
        return new ScriptValue(result);
    } catch (Exception e) {
        String message = "javascript function call failed: " + e.getMessage();
        context.logger.error(message);
        context.logger.error("failed function body: " + som);
        throw new KarateException(message);
    }
}
 
Example 6
Project: karate   File: ScriptValue.java   Source Code and License 6 votes vote down vote up
public DocumentContext getAsJsonDocument() {
    switch (type) {
        case JSON:
            return getValue(DocumentContext.class);
        case JS_ARRAY: // happens for json resulting from nashorn
            ScriptObjectMirror som = getValue(ScriptObjectMirror.class);
            return JsonPath.parse(som.values());
        case JS_OBJECT: // is a map-like object, happens for json resulting from nashorn
        case MAP: // this happens because some jsonpath operations result in Map
            Map<String, Object> map = getValue(Map.class);
            return JsonPath.parse(map);
        case LIST: // this also happens because some jsonpath operations result in List
            List list = getValue(List.class);
            return JsonPath.parse(list);
        default:
            throw new RuntimeException("cannot convert to json: " + this);
    }
}
 
Example 7
Project: opentest   File: TestActor.java   Source Code and License 6 votes vote down vote up
/**
 * Converts a value from a Java type to a JavaScript native type, by first
 * serializing it to a JSON string and then using JSON.parse. This is
 * necessary to allow the use of JS APIs on arrays and objects (e.g.
 * Array.prototype.join, Object.keys, etc.), instead of requiring test
 * automation developers to work with those values using Java APIs. Types
 * that map to native JS primitive values (number, string, etc.) apparently
 * cannot be converted to native JS objects.
 */
private Object convertToJavaScriptType(Object value) {
    try {
        // Check if the value is a List or Map, but exclude ScriptObjectMirror
        // instances, because they are already JS native types
        if ((value instanceof List || value instanceof Map)
                && !(value instanceof ScriptObjectMirror)) {

            Gson gson = new Gson();
            String json = gson.toJson(value);
            json = json.replace("\\", "\\\\");
            return this.scriptEngine.eval(String.format("JSON.parse('%s')", json));
        } else {
            return value;
        }
    } catch (Exception ex) {
        throw new RuntimeException(String.format(
                "Failed to convert value %s to a native JavaScript type",
                value), ex);
    }
}
 
Example 8
Project: OpenJSharp   File: NativeObject.java   Source Code and License 6 votes vote down vote up
/**
 * ECMA 15.2.3.2 Object.getPrototypeOf ( O )
 *
 * @param  self self reference
 * @param  obj object to get prototype from
 * @return the prototype of an object
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
public static Object getPrototypeOf(final Object self, final Object obj) {
    if (obj instanceof ScriptObject) {
        return ((ScriptObject)obj).getProto();
    } else if (obj instanceof ScriptObjectMirror) {
        return ((ScriptObjectMirror)obj).getProto();
    } else {
        final JSType type = JSType.of(obj);
        if (type == JSType.OBJECT) {
            // host (Java) objects have null __proto__
            return null;
        }

        // must be some JS primitive
        throw notAnObject(obj);
    }
}
 
Example 9
Project: OpenJSharp   File: NativeObject.java   Source Code and License 6 votes vote down vote up
/**
 * Binds the source mirror object's properties to the target object. Binding
 * properties allows two-way read/write for the properties of the source object.
 * All inherited, enumerable properties are also bound. This method is used to
 * to make 'with' statement work with ScriptObjectMirror as scope object.
 *
 * @param target the target object to which the source object's properties are bound
 * @param source the source object whose properties are bound to the target
 * @return the target object after property binding
 */
public static Object bindAllProperties(final ScriptObject target, final ScriptObjectMirror source) {
    final Set<String> keys = source.keySet();
    // make accessor properties using dynamic invoker getters and setters
    final AccessorProperty[] props = new AccessorProperty[keys.size()];
    int idx = 0;
    for (final String name : keys) {
        final MethodHandle getter = Bootstrap.createDynamicInvoker("dyn:getMethod|getProp|getElem:" + name, MIRROR_GETTER_TYPE);
        final MethodHandle setter = Bootstrap.createDynamicInvoker("dyn:setProp|setElem:" + name, MIRROR_SETTER_TYPE);
        props[idx] = AccessorProperty.create(name, 0, getter, setter);
        idx++;
    }

    target.addBoundProperties(source, props);
    return target;
}
 
Example 10
Project: openjdk-jdk10   File: NativeObject.java   Source Code and License 6 votes vote down vote up
/**
 * ECMA 15.2.3.2 Object.getPrototypeOf ( O )
 *
 * @param  self self reference
 * @param  obj object to get prototype from
 * @return the prototype of an object
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
public static Object getPrototypeOf(final Object self, final Object obj) {
    if (obj instanceof ScriptObject) {
        return ((ScriptObject)obj).getProto();
    } else if (obj instanceof ScriptObjectMirror) {
        return ((ScriptObjectMirror)obj).getProto();
    } else {
        final JSType type = JSType.of(obj);
        if (type == JSType.OBJECT) {
            // host (Java) objects have null __proto__
            return null;
        }

        // must be some JS primitive
        throw notAnObject(obj);
    }
}
 
Example 11
Project: chipKIT-importer   File: ArduinoBuilderRunner.java   Source Code and License 6 votes vote down vote up
private List<Path> findMainLibraryPaths() throws ScriptException, FileNotFoundException {
    LOGGER.info("Looking for main library paths");
    
    Path includesCachePath = Paths.get(preprocessDirPath.toAbsolutePath().toString(), "includes.cache");
    ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByExtension("js");
    ScriptObjectMirror mirror = (ScriptObjectMirror) scriptEngine.eval(new FileReader(includesCachePath.toString()));
    List<Path> libraryPaths = new ArrayList<>();
    mirror.entrySet().forEach(e -> {
        if (e.getValue() instanceof ScriptObjectMirror) {
            ScriptObjectMirror m = (ScriptObjectMirror) e.getValue();
            Object sourceFile = m.get("Sourcefile");
            if (sourceFile != null && !sourceFile.toString().trim().isEmpty()) {
                String entry = m.get("Includepath").toString();
                if ( !entry.trim().isEmpty() ) {
                    LOGGER.log( Level.INFO, "Found library path: {0}", entry );
                    libraryPaths.add( Paths.get(entry) );
                }
            }
        }
    });
    return libraryPaths;
}
 
Example 12
Project: openjdk-jdk10   File: WithObject.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("unused")
private static Object bindToExpression(final Object fn, final Object receiver) {
    if (fn instanceof ScriptFunction) {
        return bindToExpression((ScriptFunction) fn, receiver);
    } else if (fn instanceof ScriptObjectMirror) {
        final ScriptObjectMirror mirror = (ScriptObjectMirror)fn;
        if (mirror.isFunction()) {
            // We need to make sure correct 'this' is used for calls with Ident call
            // expressions. We do so here using an AbstractJSObject instance.
            return new AbstractJSObject() {
                @Override
                public Object call(final Object thiz, final Object... args) {
                    return mirror.call(withFilterExpression(receiver), args);
                }
            };
        }
    }

    return fn;
}
 
Example 13
Project: openjdk-jdk10   File: PluggableJSObjectTest.java   Source Code and License 6 votes vote down vote up
@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);
        }
    });
}
 
Example 14
Project: openjdk-jdk10   File: ScriptObjectMirrorTest.java   Source Code and License 6 votes vote down vote up
@Test
public void indexPropertiesExternalBufferTest() throws ScriptException {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    final ScriptObjectMirror obj = (ScriptObjectMirror)e.eval("var obj = {}; obj");
    final ByteBuffer buf = ByteBuffer.allocate(5);
    int i;
    for (i = 0; i < 5; i++) {
        buf.put(i, (byte)(i+10));
    }
    obj.setIndexedPropertiesToExternalArrayData(buf);

    for (i = 0; i < 5; i++) {
        assertEquals((byte)(i+10), ((Number)e.eval("obj[" + i + "]")).byteValue());
    }

    e.eval("for (i = 0; i < 5; i++) obj[i] = 0");
    for (i = 0; i < 5; i++) {
        assertEquals((byte)0, ((Number)e.eval("obj[" + i + "]")).byteValue());
        assertEquals((byte)0, buf.get(i));
    }
}
 
Example 15
Project: openjdk-jdk10   File: ScriptEngineTest.java   Source Code and License 6 votes vote down vote up
@Test
public void functionalInterfaceObjectTest() throws Exception {
    final ScriptEngineManager manager = new ScriptEngineManager();
    final ScriptEngine e = manager.getEngineByName("nashorn");
    final AtomicBoolean invoked = new AtomicBoolean(false);
    e.put("c", new Consumer<Object>() {
        @Override
        public void accept(final Object t) {
            assertTrue(t instanceof ScriptObjectMirror);
            assertEquals(((ScriptObjectMirror)t).get("a"), "xyz");
            invoked.set(true);
        }
    });
    e.eval("var x = 'xy'; x += 'z';c({a:x})");
    assertTrue(invoked.get());
}
 
Example 16
Project: Thrush   File: TokenUtil.java   Source Code and License 5 votes vote down vote up
private static String getTicketInfoForPassengerForm(String html, String key) throws ScriptException {
    Document document = Jsoup.parse(html);

    Elements elements = document.getElementsByTag("script");
    String jsContent = elements.stream().filter(e -> e.data().contains("ticketInfoForPassengerForm") && e.childNodes().size() > 0)
            .findFirst().map(e -> e.childNode(0).outerHtml()).orElse(StringUtils.EMPTY);
    jsContent = jsContent.substring(0, jsContent.lastIndexOf("var"));

    ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
    ScriptEngine engine = scriptEngineManager.getEngineByExtension("js");
    engine.eval(jsContent);
    ScriptObjectMirror objectMirror = (ScriptObjectMirror) engine.get("ticketInfoForPassengerForm");
    return (String) objectMirror.get(key);
}
 
Example 17
Project: a6y-server   File: Action.java   Source Code and License 5 votes vote down vote up
private org.antology.db.Node jsToNode(Object object) throws Exception {
    if (object instanceof ScriptObjectMirror) {
        ScriptObjectMirror mirror = (ScriptObjectMirror) object;

        if (mirror.isArray()) {
            List<org.antology.db.Node> list = new LinkedList<>();
            for (int i = 0; i < mirror.size(); i++) {
                list.add(jsToNode(mirror.get(Integer.toString(i))));
            }
            return new Node(Schema.Type.LIST, list);
        } else {
            Map<String, org.antology.db.Node> struct = new HashMap<>();
            for (String key : mirror.getOwnKeys(false)) {
                java.lang.Object value = mirror.get(key);
                struct.put(key, jsToNode(value));
            }
            return new Node(Schema.Type.STRUCT, struct);
        }
    } else if (object instanceof String) {
        return new Node(Schema.Type.STRING, object);
    } else if (object instanceof Integer) {
        return new Node(Schema.Type.INTEGER, object);
    } else if (object instanceof Double) {
        return new Node(Schema.Type.FLOAT, object);
    } else if (object instanceof Boolean) {
        return new Node(Schema.Type.BOOLEAN, object);
    } else {
        throw new Exception("Unknown type " + object.getClass().getName());
    }
}
 
Example 18
Project: centraldogma   File: Polyfills.java   Source Code and License 5 votes vote down vote up
private static String logMessage(ScriptObjectMirror mirror, int length) {
    final Object first = mirror.get("0");
    if (first instanceof String) {
        final String format = (String) first;
        if (SUBSTITUTIONS.matcher(format).find()) {
            // The first element is a string and it contains substitution(s).
            return logMessageFormat(format, mirror, length);
        }
    }

    // The first element does not contain substitution(s).
    return logMessageSimple(new StringBuilder(64), mirror, 0, length);
}
 
Example 19
Project: centraldogma   File: Polyfills.java   Source Code and License 5 votes vote down vote up
private static String logMessageFormat(String format, ScriptObjectMirror values, int length) {
    final StringBuilder buf = new StringBuilder(format.length() << 1);
    boolean wasPercent = false; // if the previous character was '%';
    int argIdx = 1;
    for (int i = 0; i < format.length(); i++) {
        final char ch = format.charAt(i);
        if (wasPercent) {
            switch (ch) {
            case '%':
                buf.append('%');
                break;
            case 'd':
            case 'f':
            case 'i':
            case 'j':
            case 'o':
            case 's':
                buf.append(values.get(int2str(argIdx++)));
                break;
            default:
                buf.append('%');
                buf.append(ch);
            }

            wasPercent = false;
        } else if (ch == '%') {
            wasPercent = true;
        } else {
            buf.append(ch);
        }
    }

    return logMessageSimple(buf, values, argIdx, length);
}
 
Example 20
Project: centraldogma   File: Polyfills.java   Source Code and License 5 votes vote down vote up
private static String logMessageSimple(StringBuilder out, ScriptObjectMirror values, int start, int end) {
    for (int i = start; i < end; i++) {
        if (out.length() != 0) {
            out.append(' ');
        }
        out.append(values.get(int2str(i)));
    }

    return out.toString();
}
 
Example 21
Project: Nasapi   File: Authenticator.java   Source Code and License 5 votes vote down vote up
@Override
public void registerAuthentication(Object registerFunction) throws ScriptException, NashornException, NasapiException {
	if (registerFunction == null) {
		throw new NasapiException("registerAuthentication argument cannot be null");
	} else if (registerFunction instanceof ScriptObjectMirror && ((ScriptObjectMirror)registerFunction).isFunction()) {
		authenticateFunction = (ScriptObjectMirror)registerFunction;
	} else {
		throw new NasapiException("registerAuthentication argument must be a function");
	}
}
 
Example 22
Project: RefDiff   File: EsprimaParser.java   Source Code and License 5 votes vote down vote up
@Override
public List<String> tokenize(String source) {
	try {
		ScriptObjectMirror array = (ScriptObjectMirror) this.invocableScript.invokeFunction("tokenize", source);
		List<String> tokens = new ArrayList<>(array.size());
		for (int i = 0; i < array.size(); i++) {
			String token = ((ScriptObjectMirror) array.getSlot(i)).getMember("value").toString();
			tokens.add(token);
		}
		return tokens;
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
}
 
Example 23
Project: karate   File: JsonUtils.java   Source Code and License 5 votes vote down vote up
@Override
public <E extends ScriptObjectMirror> void writeJSONString(E value, Appendable out, JSONStyle compression) throws IOException {
    if (value.isArray()) {
        Object[] array = value.values().toArray();
        JsonWriter.arrayWriter.writeJSONString(array, out, compression);
    } else if (value.isFunction()) {
        JsonWriter.toStringWriter.writeJSONString("\"#function\"", out, compression);
    } else { // JSON
        JsonWriter.JSONMapWriter.writeJSONString(value, out, compression);
    }
}
 
Example 24
Project: karate   File: ScriptBridge.java   Source Code and License 5 votes vote down vote up
public Object call(String fileName, Object arg) {
    ScriptValue sv = FileUtils.readFile(fileName, context);
    switch(sv.getType()) {
        case FEATURE_WRAPPER:
            FeatureWrapper feature = sv.getValue(FeatureWrapper.class);
            return Script.evalFeatureCall(feature, arg, context, false).getValue();
        case JS_FUNCTION:
            ScriptObjectMirror som = sv.getValue(ScriptObjectMirror.class);
            return Script.evalFunctionCall(som, arg, context).getValue();
        default:
            context.logger.warn("not a js function or feature file: {} - {}", fileName, sv);
            return null;
    }        
}
 
Example 25
Project: karate   File: ScriptValue.java   Source Code and License 5 votes vote down vote up
public List getAsList() {
    switch (type) {
        case JS_ARRAY:
            ScriptObjectMirror som = (ScriptObjectMirror) value;
            return new ArrayList(som.values());
        case LIST:
            return getValue(List.class);
        case JSON:
            DocumentContext doc = (DocumentContext) value;
            return doc.json();
        default:
            throw new RuntimeException("cannot convert to list: " + this);
    }
}
 
Example 26
Project: karate   File: ScriptValue.java   Source Code and License 5 votes vote down vote up
public ScriptValue(Object value, String source) {
    this.value = value;
    this.source = source;
    if (value == null) {
        type = Type.NULL;
    } else if (value instanceof DocumentContext) {
        type = Type.JSON;
    } else if (value instanceof Node) {
        type = Type.XML;
    } else if (value instanceof List) {
        type = Type.LIST;
    } else if (value instanceof Map) {
        if (value instanceof ScriptObjectMirror) {
            ScriptObjectMirror som = (ScriptObjectMirror) value;
            if (som.isArray()) {
                type = Type.JS_ARRAY;
            } else if (som.isFunction()) {
                type = Type.JS_FUNCTION;
            } else {
                type = Type.JS_OBJECT;
            }
        } else {
            type = Type.MAP;
        }
    } else if (value instanceof String) {
        type = Type.STRING;
    } else if (value instanceof byte[]) {
        type = Type.BYTE_ARRAY;
    } else if (value instanceof InputStream) {
        type = Type.INPUT_STREAM;
    } else if (Script.isPrimitive(value.getClass())) {
        type = Type.PRIMITIVE;
    } else if (value instanceof FeatureWrapper) {
        type = Type.FEATURE_WRAPPER;
    } else {
        type = Type.UNKNOWN;
    }
}
 
Example 27
Project: openjdk-jdk10   File: FunctionalInterfaceProvider.java   Source Code and License 5 votes vote down vote up
public static Functional getImpl() {
    return (l) -> {
        // Make sure parameters are properly exported
        for (final Object o : l) {
            Assert.assertTrue(o == RETURN_TOKEN
                    || o instanceof ScriptObjectMirror
                    || o instanceof String);
        }
        return RETURN_TOKEN;
    };
}
 
Example 28
Project: opentest   File: ScriptObjectMirrorSerializer.java   Source Code and License 5 votes vote down vote up
@Override
public JsonElement serialize(ScriptObjectMirror src, java.lang.reflect.Type typeOfSrc, JsonSerializationContext context) {
    Gson gson = new Gson();
    
    if (src.isArray()) {
        return gson.toJsonTree(src.values());
    } else {
        return gson.toJsonTree(src);
    }
}
 
Example 29
Project: opentest   File: Factory.java   Source Code and License 5 votes vote down vote up
public static GsonBuilder getGsonBuilder() {
    GsonBuilder builder = new GsonBuilder()
            .disableHtmlEscaping()
            .registerTypeAdapter(BufferedImage.class, new BufferedImageSerializer())
            .registerTypeAdapter(ScriptObjectMirror.class, new ScriptObjectMirrorSerializer())
            .addDeserializationExclusionStrategy(new DuplicateFieldExclusionStrategy())
            .addSerializationExclusionStrategy(new DuplicateFieldExclusionStrategy());
    return builder;
}
 
Example 30
Project: OpenJSharp   File: Global.java   Source Code and License 5 votes vote down vote up
/**
 * Hook to search missing variables in ScriptContext if available
 * @param self used to detect if scope call or not (this function is 'strict')
 * @param name name of the variable missing
 * @return value of the missing variable or undefined (or TypeError for scope search)
 */
public static Object __noSuchProperty__(final Object self, final Object name) {
    final Global global = Global.instance();
    final ScriptContext sctxt = global.scontext;
    final String nameStr = name.toString();

    if (sctxt != null) {
        final int scope = sctxt.getAttributesScope(nameStr);
        if (scope != -1) {
            return ScriptObjectMirror.unwrap(sctxt.getAttribute(nameStr, scope), global);
        }
    }

    switch (nameStr) {
    case "context":
        return sctxt;
    case "engine":
        return global.engine;
    default:
        break;
    }

    if (self == UNDEFINED) {
        // scope access and so throw ReferenceError
        throw referenceError(global, "not.defined", nameStr);
    }

    return UNDEFINED;
}
 
Example 31
Project: OpenJSharp   File: NativeObject.java   Source Code and License 5 votes vote down vote up
/**
 * Nashorn extension: Object.setPrototypeOf ( O, proto )
 * Also found in ES6 draft specification.
 *
 * @param  self self reference
 * @param  obj object to set prototype for
 * @param  proto prototype object to be used
 * @return object whose prototype is set
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
public static Object setPrototypeOf(final Object self, final Object obj, final Object proto) {
    if (obj instanceof ScriptObject) {
        ((ScriptObject)obj).setPrototypeOf(proto);
        return obj;
    } else if (obj instanceof ScriptObjectMirror) {
        ((ScriptObjectMirror)obj).setProto(proto);
        return obj;
    }

    throw notAnObject(obj);
}
 
Example 32
Project: OpenJSharp   File: NativeObject.java   Source Code and License 5 votes vote down vote up
/**
 * ECMA 15.2.3.4 Object.getOwnPropertyNames ( O )
 *
 * @param self self reference
 * @param obj  object to query for property names
 * @return array of property names
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
public static ScriptObject getOwnPropertyNames(final Object self, final Object obj) {
    if (obj instanceof ScriptObject) {
        return new NativeArray(((ScriptObject)obj).getOwnKeys(true));
    } else if (obj instanceof ScriptObjectMirror) {
        return new NativeArray(((ScriptObjectMirror)obj).getOwnKeys(true));
    } else {
        throw notAnObject(obj);
    }
}
 
Example 33
Project: OpenJSharp   File: NativeObject.java   Source Code and License 5 votes vote down vote up
/**
 * ECMA 15.2.3.8 Object.seal ( O )
 *
 * @param self self reference
 * @param obj  object to seal
 * @return sealed object
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
public static Object seal(final Object self, final Object obj) {
    if (obj instanceof ScriptObject) {
        return ((ScriptObject)obj).seal();
    } else if (obj instanceof ScriptObjectMirror) {
        return ((ScriptObjectMirror)obj).seal();
    } else {
        throw notAnObject(obj);
    }
}
 
Example 34
Project: OpenJSharp   File: NativeObject.java   Source Code and License 5 votes vote down vote up
/**
 * ECMA 15.2.3.9 Object.freeze ( O )
 *
 * @param self self reference
 * @param obj object to freeze
 * @return frozen object
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
public static Object freeze(final Object self, final Object obj) {
    if (obj instanceof ScriptObject) {
        return ((ScriptObject)obj).freeze();
    } else if (obj instanceof ScriptObjectMirror) {
        return ((ScriptObjectMirror)obj).freeze();
    } else {
        throw notAnObject(obj);
    }
}
 
Example 35
Project: OpenJSharp   File: NativeObject.java   Source Code and License 5 votes vote down vote up
/**
 * ECMA 15.2.3.10 Object.preventExtensions ( O )
 *
 * @param self self reference
 * @param obj  object, for which to set the internal extensible property to false
 * @return object
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
public static Object preventExtensions(final Object self, final Object obj) {
    if (obj instanceof ScriptObject) {
        return ((ScriptObject)obj).preventExtensions();
    } else if (obj instanceof ScriptObjectMirror) {
        return ((ScriptObjectMirror)obj).preventExtensions();
    } else {
        throw notAnObject(obj);
    }
}
 
Example 36
Project: OpenJSharp   File: NativeObject.java   Source Code and License 5 votes vote down vote up
/**
 * ECMA 15.2.3.11 Object.isSealed ( O )
 *
 * @param self self reference
 * @param obj check whether an object is sealed
 * @return true if sealed, false otherwise
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
public static boolean isSealed(final Object self, final Object obj) {
    if (obj instanceof ScriptObject) {
        return ((ScriptObject)obj).isSealed();
    } else if (obj instanceof ScriptObjectMirror) {
        return ((ScriptObjectMirror)obj).isSealed();
    } else {
        throw notAnObject(obj);
    }
}
 
Example 37
Project: OpenJSharp   File: NativeObject.java   Source Code and License 5 votes vote down vote up
/**
 * ECMA 15.2.3.12 Object.isFrozen ( O )
 *
 * @param self self reference
 * @param obj check whether an object
 * @return true if object is frozen, false otherwise
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
public static boolean isFrozen(final Object self, final Object obj) {
    if (obj instanceof ScriptObject) {
        return ((ScriptObject)obj).isFrozen();
    } else if (obj instanceof ScriptObjectMirror) {
        return ((ScriptObjectMirror)obj).isFrozen();
    } else {
        throw notAnObject(obj);
    }
}
 
Example 38
Project: OpenJSharp   File: NativeObject.java   Source Code and License 5 votes vote down vote up
/**
 * ECMA 15.2.3.13 Object.isExtensible ( O )
 *
 * @param self self reference
 * @param obj check whether an object is extensible
 * @return true if object is extensible, false otherwise
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
public static boolean isExtensible(final Object self, final Object obj) {
    if (obj instanceof ScriptObject) {
        return ((ScriptObject)obj).isExtensible();
    } else if (obj instanceof ScriptObjectMirror) {
        return ((ScriptObjectMirror)obj).isExtensible();
    } else {
        throw notAnObject(obj);
    }
}
 
Example 39
Project: OpenJSharp   File: NativeObject.java   Source Code and License 5 votes vote down vote up
/**
 * ECMA 15.2.3.14 Object.keys ( O )
 *
 * @param self self reference
 * @param obj  object from which to extract keys
 * @return array of keys in object
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
public static ScriptObject keys(final Object self, final Object obj) {
    if (obj instanceof ScriptObject) {
        final ScriptObject sobj = (ScriptObject)obj;
        return new NativeArray(sobj.getOwnKeys(false));
    } else if (obj instanceof ScriptObjectMirror) {
        final ScriptObjectMirror sobjMirror = (ScriptObjectMirror)obj;
        return new NativeArray(sobjMirror.getOwnKeys(false));
    } else {
        throw notAnObject(obj);
    }
}
 
Example 40
Project: OpenJSharp   File: NashornLinker.java   Source Code and License 5 votes vote down vote up
private static GuardedInvocation getMirrorConverter(final Class<?> sourceType, final Class<?> targetType) {
    // Could've also used (targetType.isAssignableFrom(ScriptObjectMirror.class) && targetType != Object.class) but
    // it's probably better to explicitly spell out the supported target types
    if (targetType == Map.class || targetType == Bindings.class || targetType == JSObject.class || targetType == ScriptObjectMirror.class) {
        if(ScriptObject.class.isAssignableFrom(sourceType)) {
            return new GuardedInvocation(CREATE_MIRROR);
        }
        return new GuardedInvocation(CREATE_MIRROR, IS_SCRIPT_OBJECT);
    }
    return null;
}