本文整理汇总了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;
}
示例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"));
}
示例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);
}
}
}
示例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);
}
}
示例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);
}
}
示例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);
}
}
示例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);
}
}
示例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);
}
}
示例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;
}
示例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;
}
示例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;
}
示例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);
}
});
}
示例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));
}
}
示例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());
}
示例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);
}