List of usage examples for jdk.nashorn.api.scripting ScriptObjectMirror hasMember
@Override public boolean hasMember(final String name)
From source file:com.baasbox.service.scripting.js.NashornMapper.java
License:Apache License
private JsonNode convertMirror(ScriptObjectMirror mirror) throws ScriptEvalException { if (mirror == null) { return NullNode.getInstance(); } else if (ScriptObjectMirror.isUndefined(mirror)) { return MissingNode.getInstance(); } else if (mirror.isFunction()) { return MissingNode.getInstance(); } else if (mirror.isArray()) { Collection<Object> values = mirror.values(); ArrayNode node = Json.mapper().createArrayNode(); for (Object o : values) { JsonNode e = convertDeepJson(o); if (e.isMissingNode()) { continue; }/*from www. ja va2 s.co m*/ node.add(e); } return node; } else if (mirror.hasMember("toJSON")) { Object toJSON = mirror.callMember("toJSON"); return convertDeepJson(toJSON); } else { ObjectNode obj = Json.mapper().createObjectNode(); Set<Map.Entry<String, Object>> entries = mirror.entrySet(); for (Map.Entry<String, Object> e : entries) { Object obv = e.getValue(); JsonNode jsonNode = convertDeepJson(obv); if (jsonNode.isMissingNode()) { continue; } obj.put(e.getKey(), jsonNode); } return obj; } }
From source file:com.bytelightning.opensource.pokerface.PokerFace.java
License:Open Source License
/** * If requested by the user, this method walks the script directory discovering, loading, compiling, and initialing an .js javascript files it finds in the specified directory or it's children. * @param baseScriptDirectory The contents of this directory should be structured in the same layout as the url's we wish to interfere with. * @param watchScriptDirectory If true, a watch will be placed on <code>baseScriptDirectory</code> and any javascript file modifications (cud) will be dynamically rebuilt and reflected in the running server. * @return True if all scripts were successfully loaded. *//*from w ww .java 2 s .c om*/ protected boolean configureScripts(final List<Path> jsLibs, final HierarchicalConfiguration scriptConfig, final Path baseScriptDirectory, boolean watchScriptDirectory) { // Our unit test has verified that CompiledScripts can produce objects (endpoints) that can be executed from ANY thread (and even concurrently execute immutable methods). // However we have not validated that Nashorn can compile *and* recompile scripts from multiple threads. //TODO: Write unit test to see if we can use all available processors to compile discovered javascript files. ScriptCompilationExecutor = Executors.newSingleThreadScheduledExecutor(); // This is done to make sure the engine is allocated in the same thread that will be doing the compiling. Callable<Boolean> compileScriptsTask = new Callable<Boolean>() { @Override public Boolean call() { Nashorn = new ScriptEngineManager().getEngineByName("nashorn"); if (jsLibs != null) for (Path lib : jsLibs) if (!loadScriptLibrary(lib)) return false; // Recursively discover javascript files, compile, load, and setup any that are found. EnumSet<FileVisitOption> opts = EnumSet.of(FileVisitOption.FOLLOW_LINKS); try { Files.walkFileTree(baseScriptDirectory, opts, Integer.MAX_VALUE, new SimpleFileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { if (Files.isDirectory(dir) && dir.getFileName().toString().startsWith("#")) return FileVisitResult.SKIP_SUBTREE; return super.preVisitDirectory(dir, attrs); } @Override public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException { if (Files.isRegularFile(path)) { if (path.toString().toLowerCase().endsWith(".js")) { MakeJavaScriptEndPointDescriptor(baseScriptDirectory, path, scriptConfig, new NewEndpointSetupCallback()); } } return FileVisitResult.CONTINUE; } }); } catch (IOException e) { Logger.error("Unable recursively load scripts", e); return false; } return true; } }; // Walk the root directory recursively compiling all discovered javascript files (does not return until all endpoint files have been setup). try { if (!ScriptCompilationExecutor.submit(compileScriptsTask).get()) return false; } catch (Throwable e) { Logger.error("Unable to compile scripts", e); return false; } if (watchScriptDirectory) { try { // Establish a watch on the root ScriptDirectoryWatcher.establishWatch(baseScriptDirectory, new DirectoryWatchEventListener() { // Internal Callable task to load, compile, and initialize a javascript file endpoint. final class CreateEndpointTask implements Callable<Void> { public CreateEndpointTask(Path file, EndpointSetupCompleteCallback callback) { this.file = file; this.callback = callback; } private final Path file; private final EndpointSetupCompleteCallback callback; @Override public Void call() { MakeJavaScriptEndPointDescriptor(baseScriptDirectory, file, scriptConfig, callback); return null; } } // Internal Callable task that gives us the ability to schedule a delayed unload of a deleted or obsoleted endpoint. // By delaying for a period of time longer than twice the socket timeout, we can safely call the endpoint's teardown method. final class DecommisionEndpointTask implements Callable<Void> { private DecommisionEndpointTask(ScriptObjectMirror endpoint) { this.endpoint = endpoint; } private final ScriptObjectMirror endpoint; @Override public Void call() { if (endpoint.hasMember("teardown")) endpoint.callMember("teardown"); return null; } } /** * Called by the WatchService when the contents of the script directory have changed. */ @Override public void onWatchEvent(Path watchDir, final Path oldFile, final Path newFile, FileChangeType change) { if (change == FileChangeType.eRenamed) { // If it was changed to something that does *not* end .js then it should no longer be considered an endpoint. if (oldFile.toString().toLowerCase().endsWith(".js")) if (!newFile.toString().toLowerCase().endsWith(".js")) change = FileChangeType.eDeleted; } if (change == FileChangeType.eModified || change == FileChangeType.eRenamed) { // Decommission the obsolete and load the update. try { assert newFile.toString().toLowerCase().endsWith(".js"); // Will be true because of the 'rename' check at the top of this method. ScriptCompilationExecutor .submit(new CreateEndpointTask(newFile, new NewEndpointSetupCallback() { @Override public ScriptObjectMirror setupComplete(JavaScriptEndPoint endpoint) { ScriptObjectMirror old = super.setupComplete(endpoint); assert old != null; // Yeah, it's hincky, but it won't be in use this long after we remove it from the Map. ScriptCompilationExecutor.schedule(new DecommisionEndpointTask(old), 6, TimeUnit.MINUTES); return null; } })); } catch (Throwable e) { Logger.error("Unable to compile modified script found at " + newFile.toAbsolutePath().toString(), e); } } else if (change == FileChangeType.eCreated) { // This is the easy one. If a javascript file was created, load it. if (newFile.toString().toLowerCase().endsWith(".js")) { try { ScriptCompilationExecutor.submit( new CreateEndpointTask(newFile, new NewEndpointSetupCallback())); } catch (Throwable e) { Logger.error("Unable to compile new script found at " + newFile.toAbsolutePath().toString(), e); } } } else if (change == FileChangeType.eDeleted) { // Endpoint should be decommisioned. if (oldFile.toString().toLowerCase().endsWith(".js")) { String uriKey = FileToUriKey(baseScriptDirectory, oldFile); ScriptObjectMirror desc = scripts.remove(uriKey); if (desc != null) { // Yeah, it's hincky, but it won't be in use this long after we remove it from the Map. ScriptCompilationExecutor.schedule(new DecommisionEndpointTask(desc), 6, TimeUnit.MINUTES); } } } } }); } catch (IOException e) { Logger.error("Unable to establish a real time watch on the script directory.", e); } } else // Not watching for changes, so we are done with the Executor. ScriptCompilationExecutor.shutdown(); return true; }
From source file:com.bytelightning.opensource.pokerface.PokerFace.java
License:Open Source License
/** * This is where Nashorn compiles the script, evals it into global scope to get an endpoint, and invokes the setup method of the endpoint. * @param rootPath The root script directory path to assist in building a relative uri type path to discovered scripts. * @param f The javascript file.//from ww w .ja v a 2s . c o m * @param uriKey A "pass-back-by-reference" construct to w * @return */ private static void MakeJavaScriptEndPointDescriptor(Path rootPath, Path f, HierarchicalConfiguration scriptConfig, EndpointSetupCompleteCallback cb) { CompiledScript compiledScript; try (Reader r = Files.newBufferedReader(f, Charset.forName("utf-8"))) { compiledScript = ((Compilable) Nashorn).compile(r); } catch (Throwable e) { cb.setupFailed(f, "Unable to load and compile script at " + f.toAbsolutePath().toString(), e); return; } ScriptObjectMirror obj; try { obj = (ScriptObjectMirror) compiledScript.eval(Nashorn.getBindings(ScriptContext.GLOBAL_SCOPE)); } catch (Throwable e) { cb.setupFailed(f, "Unable to eval the script at " + f.toAbsolutePath().toString(), e); return; } assert f.startsWith(rootPath); String uriKey = FileToUriKey(rootPath, f); final JavaScriptEndPoint retVal = new JavaScriptEndPoint(uriKey, obj); try { if (obj.hasMember("setup")) { obj.callMember("setup", uriKey, scriptConfig, ScriptHelper.ScriptLogger, new SetupCompleteCallback() { @Override public void setupComplete() { cb.setupComplete(retVal); } @Override public void setupFailed(String msg) { cb.setupFailed(f, msg, null); } }); } else { cb.setupComplete(retVal); } } catch (Throwable e) { cb.setupFailed(f, "The script at " + f.toAbsolutePath().toString() + " did not expose the expected 'setup' method", e); return; } }
From source file:com.qwazr.library.files.FileBrowser.java
License:Apache License
FileBrowser(final ScriptObjectMirror browser, final int max_depth, final Path rootPath) throws IOException { this.max_depth = max_depth; if (browser != null) { file_method = browser.hasMember("file"); dir_method = browser.hasMember("directory"); } else {//from w ww . j a va2s . c om file_method = false; dir_method = false; } if (Files.exists(rootPath)) browse(browser, rootPath, 0); }
From source file:io.vertx.lang.js.VertxGenConverterList.java
License:Open Source License
public VertxGenConverterList(List other) { for (Object entry : other) { if (entry == null) { add(null);/* w ww . j ava 2 s. co m*/ } else { if (!(entry instanceof ScriptObjectMirror)) { throw new IllegalArgumentException("Array does not contain objects"); } ScriptObjectMirror mirror = (ScriptObjectMirror) entry; if (mirror.hasMember("_jdel")) { add(mirror.getMember("_jdel")); } else { throw new IllegalArgumentException("Object in array is not @VertxGen object"); } } } }
From source file:io.vertx.lang.js.VertxGenConverterMap.java
License:Open Source License
public VertxGenConverterMap(Map<String, Object> other) { for (Map.Entry<String, Object> entry : other.entrySet()) { if (entry.getValue() == null) { put(entry.getKey(), null);//from w w w . j a v a 2 s . c o m } else { if (!(entry.getValue() instanceof ScriptObjectMirror)) { throw new IllegalArgumentException("Array does not contain objects"); } ScriptObjectMirror mirror = (ScriptObjectMirror) entry.getValue(); if (mirror.hasMember("_jdel")) { put(entry.getKey(), mirror.getMember("_jdel")); } else { throw new IllegalArgumentException("Object in array is not @VertxGen object"); } } } }
From source file:io.vertx.lang.js.VertxGenConverterSet.java
License:Open Source License
public VertxGenConverterSet(List other) { for (Object entry : other) { if (entry == null) { add(null);//from w w w.ja va 2s . c o m } else { if (!(entry instanceof ScriptObjectMirror)) { throw new IllegalArgumentException("Array does not contain objects"); } ScriptObjectMirror mirror = (ScriptObjectMirror) entry; if (mirror.hasMember("_jdel")) { add(mirror.getMember("_jdel")); } else { throw new IllegalArgumentException("Object in array is not @VertxGen object"); } } } }
From source file:org.eclairjs.nashorn.Utils.java
License:Apache License
public static Object jsToJava(Object o) { if (o != null && !(o instanceof Undefined)) { logger.debug("jsToJava" + o.getClass().getName()); } else {/* w w w. j ava2s . co m*/ return o; } if (o instanceof jdk.nashorn.internal.objects.NativeArray) { Object array[] = ((NativeArray) o).asObjectArray(); ArrayList al = new ArrayList(); for (int i = 0; i < array.length; i++) { al.add(jsToJava(array[i])); } return al.toArray(); } if (o.getClass().isPrimitive()) return o; String packageName = o.getClass().getCanonicalName(); switch (packageName) { case "java.lang.String": case "java.lang.Integer": case "java.lang.Float": case "java.lang.Double": case "java.lang.Boolean": case "java.lang.Long": case "org.json.simple.JSONObject": case "java.lang.Object[]": case "java.lang.String[]": case "scala.Tuple2": case "scala.Tuple3": case "scala.Tuple4": return o; } if (packageName.startsWith("org.apache.spark")) return o; if (o instanceof WrappedClass) return ((WrappedClass) o).getJavaObject(); if (o instanceof ScriptObjectMirror) { ScriptObjectMirror m = (ScriptObjectMirror) o; if (m.hasMember("getJavaObject")) { return m.callMember("getJavaObject"); } if (m.isArray()) { try { if (m.containsKey("0")) { Object v = m.get("0"); if (v instanceof Double) { double[] doubleArray = (double[]) ScriptUtils.convert(m, double[].class); return doubleArray; } else if (v instanceof Integer) { int[] intArray = (int[]) ScriptUtils.convert(m, int[].class); return intArray; } else { Object[] objectArray = (Object[]) ScriptUtils.convert(m, Object[].class); return objectArray; } } } catch (ClassCastException e) { /* If the array contains ScriptObjectMirror the above conversions throws exception so we have to convert the contents of the array as well. */ ArrayList list = new ArrayList(); for (Object item : m.values()) { list.add(jsToJava(item)); } Object x = list.toArray(); return x; } } else { // throw new RuntimeException("js2java IMPLEMENT"+o); Object obj = ScriptObjectMirror.wrapAsJSONCompatible(o, null); String j = JSONValue.toJSONString(obj); return JSONValue.parse(j); } } else if (o instanceof jdk.nashorn.internal.runtime.ScriptObject) { ScriptObjectMirror jsObj = ScriptUtils.wrap((jdk.nashorn.internal.runtime.ScriptObject) o); if (jsObj.hasMember("getJavaObject")) { return jsObj.callMember("getJavaObject"); } } else if (o instanceof java.util.ArrayList) { ArrayList list = (ArrayList) o; int size = list.size(); for (int i = 0; i < size; i++) list.set(i, jsToJava(list.get(i))); return list; } else if (o instanceof StaticClass) { return o; } logger.warn("js2java NOT HANDLED " + packageName); return o; // Just return the Java object, it might user created like java.net.Socket //new RuntimeException().printStackTrace(); //throw new RuntimeException("js2java NOT HANDLED "+packageName); }
From source file:org.eclairjs.nashorn.Utils.java
License:Apache License
public static Object toObject(Object obj, boolean throwException) { if (obj instanceof WrappedClass) return ((WrappedClass) obj).getJavaObject(); if (obj instanceof ScriptObjectMirror) { ScriptObjectMirror m = (ScriptObjectMirror) obj; if (m.hasMember("getJavaObject")) { return m.callMember("getJavaObject"); }/*from ww w. jav a 2 s . c o m*/ } else if (obj instanceof jdk.nashorn.internal.runtime.ScriptObject) { jdk.nashorn.internal.runtime.ScriptObject scriptObject = (jdk.nashorn.internal.runtime.ScriptObject) obj; Object t = scriptObject.get("getJavaObject"); if (t instanceof ScriptFunction) { return ScriptRuntime.apply((ScriptFunction) t, scriptObject); } // scriptObject. } if (throwException) throw new RuntimeException("expecting spark object, got " + obj); else return null; }
From source file:org.eclipse.wst.jsdt.internal.esprima.DOMASTConverter.java
License:Open Source License
private JSdoc buildJSDoc(ScriptObjectMirror object) { if (!object.hasMember("leadingComments")) //$NON-NLS-1$ return null; Object commentObj = object.getMember("leadingComments"); //$NON-NLS-1$ if (ScriptObjectMirror.isUndefined(commentObj)) return null; ScriptObjectMirror comments = (ScriptObjectMirror) commentObj; Object[] arrayElements = comments.entrySet().toArray(); for (int i = 0; i < arrayElements.length; ++i) { Map.Entry<String, Object> entry = (java.util.Map.Entry<String, Object>) arrayElements[i]; Comment comment = EsprimaParser.createComment((ScriptObjectMirror) entry.getValue(), this.ast); if (comment.isDocComment()) return (JSdoc) comment; }/*from w ww .ja v a 2 s . co m*/ return null; }