當前位置: 首頁>>代碼示例>>Java>>正文


Java ScriptObjectMirror類代碼示例

本文整理匯總了Java中jdk.nashorn.api.scripting.ScriptObjectMirror的典型用法代碼示例。如果您正苦於以下問題:Java ScriptObjectMirror類的具體用法?Java ScriptObjectMirror怎麽用?Java ScriptObjectMirror使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


ScriptObjectMirror類屬於jdk.nashorn.api.scripting包,在下文中一共展示了ScriptObjectMirror類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: convert

import jdk.nashorn.api.scripting.ScriptObjectMirror; //導入依賴的package包/類
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;
}
 
開發者ID:marrow16,項目名稱:Nasapi,代碼行數:27,代碼來源:ScriptObjectMirrors.java

示例2: test6

import jdk.nashorn.api.scripting.ScriptObjectMirror; //導入依賴的package包/類
@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"));

    }
 
開發者ID:justice-code,項目名稱:Thrush,代碼行數:23,代碼來源:LoginTest.java

示例3: process

import jdk.nashorn.api.scripting.ScriptObjectMirror; //導入依賴的package包/類
@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);
        }
    }
}
 
開發者ID:VISNode,項目名稱:VISNode,代碼行數:21,代碼來源:ObjectExtractionProcess.java

示例4: logMessage

import jdk.nashorn.api.scripting.ScriptObjectMirror; //導入依賴的package包/類
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);
    }
}
 
開發者ID:line,項目名稱:centraldogma,代碼行數:22,代碼來源:Polyfills.java

示例5: evalFunctionCall

import jdk.nashorn.api.scripting.ScriptObjectMirror; //導入依賴的package包/類
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);
    }
}
 
開發者ID:intuit,項目名稱:karate,代碼行數:20,代碼來源:Script.java

示例6: getAsJsonDocument

import jdk.nashorn.api.scripting.ScriptObjectMirror; //導入依賴的package包/類
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);
    }
}
 
開發者ID:intuit,項目名稱:karate,代碼行數:19,代碼來源:ScriptValue.java

示例7: convertToJavaScriptType

import jdk.nashorn.api.scripting.ScriptObjectMirror; //導入依賴的package包/類
/**
 * 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);
    }
}
 
開發者ID:mcdcorp,項目名稱:opentest,代碼行數:30,代碼來源:TestActor.java

示例8: getPrototypeOf

import jdk.nashorn.api.scripting.ScriptObjectMirror; //導入依賴的package包/類
/**
 * 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);
    }
}
 
開發者ID:SunburstApps,項目名稱:OpenJSharp,代碼行數:25,代碼來源:NativeObject.java

示例9: bindAllProperties

import jdk.nashorn.api.scripting.ScriptObjectMirror; //導入依賴的package包/類
/**
 * 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;
}
 
開發者ID:SunburstApps,項目名稱:OpenJSharp,代碼行數:26,代碼來源:NativeObject.java

示例10: findMainLibraryPaths

import jdk.nashorn.api.scripting.ScriptObjectMirror; //導入依賴的package包/類
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;
}
 
開發者ID:chipKIT32,項目名稱:chipKIT-importer,代碼行數:23,代碼來源:ArduinoBuilderRunner.java

示例11: bindToExpression

import jdk.nashorn.api.scripting.ScriptObjectMirror; //導入依賴的package包/類
@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;
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:21,代碼來源:WithObject.java

示例12: hidingInternalObjectsForJSObjectTest

import jdk.nashorn.api.scripting.ScriptObjectMirror; //導入依賴的package包/類
@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);
        }
    });
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:18,代碼來源:PluggableJSObjectTest.java

示例13: indexPropertiesExternalBufferTest

import jdk.nashorn.api.scripting.ScriptObjectMirror; //導入依賴的package包/類
@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));
    }
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:23,代碼來源:ScriptObjectMirrorTest.java

示例14: functionalInterfaceObjectTest

import jdk.nashorn.api.scripting.ScriptObjectMirror; //導入依賴的package包/類
@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());
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:17,代碼來源:ScriptEngineTest.java

示例15: getTicketInfoForPassengerForm

import jdk.nashorn.api.scripting.ScriptObjectMirror; //導入依賴的package包/類
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);
}
 
開發者ID:justice-code,項目名稱:Thrush,代碼行數:15,代碼來源:TokenUtil.java


注:本文中的jdk.nashorn.api.scripting.ScriptObjectMirror類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。