List of usage examples for jdk.nashorn.api.scripting ScriptObjectMirror callMember
public Object callMember(final String functionName, final Object... args)
From source file:JavaScriptTest.java
public static void main2(String[] args) throws Exception { ScriptEngineManager factory = new ScriptEngineManager(); ScriptEngine engine = factory.getEngineByName("JavaScript"); System.out.println(((ScriptObjectMirror) engine.getBindings(ScriptContext.ENGINE_SCOPE)).size()); System.out.println("x:" + engine.get("x")); System.out.println("var x:" + engine.eval("function p(x){print(x);};x=10;")); System.out.println("x:" + engine.get("x")); System.out.println(((ScriptObjectMirror) engine.getBindings(ScriptContext.ENGINE_SCOPE)).size()); ScriptObjectMirror bind = ((ScriptObjectMirror) engine.getBindings(ScriptContext.ENGINE_SCOPE)); bind.callMember("p", "Hola"); engine = factory.getEngineByName("JavaScript"); //engine.setBindings(engine.createBindings(),ScriptContext.ENGINE_SCOPE); System.out.println(((ScriptObjectMirror) engine.getBindings(ScriptContext.ENGINE_SCOPE)).size()); System.out.println("x:" + engine.get("x")); System.out.println("var x:" + engine.eval("function p(x){print(x);};x=10;")); System.out.println("x:" + engine.get("x")); System.out.println(((ScriptObjectMirror) engine.getBindings(ScriptContext.ENGINE_SCOPE)).size()); }
From source file:com.baasbox.service.scripting.js.Nashorn.java
License:Apache License
private Object emitEvent(ScriptObjectMirror mirror, String eventName, Object eventData) throws ScriptEvalException { Object event = mMapper.convertEvent(eventName, eventData); Object o = mirror.callMember(EMIT_FUNCTION, event); return o;/*from www .j a v a2 s . c om*/ }
From source file:com.bytelightning.opensource.pokerface.NashornCompiledScriptTest.java
License:Open Source License
@Test public void testSingleThread() throws ScriptException { ScriptObjectMirror obj = (ScriptObjectMirror) compiledScript.eval(); obj.callMember("setI", 3); Number result = (Number) obj.callMember("getI"); Assert.assertEquals("Getter/Setter works", 3, result.intValue()); obj.callMember("addTwice", 2); result = (Number) obj.callMember("getI"); Assert.assertEquals("addTwice works", 7, result.intValue()); }
From source file:com.bytelightning.opensource.pokerface.NashornCompiledScriptTest.java
License:Open Source License
/** * This test answers the question of whether we can: * 1.) Compile a script using an engine created on the main thread. * 2.) Eval that script (also on the main thread) to produce an object with immutable methods *and* mutable methods which *modify* internal object state/properties encapsulated/protected within a closure. * 3.) Safely invoke the objects immutable methods from *ANY* thread (often simultaneously). * 4.) Safely invoke the objects mutable methods from *ANY* thread as long as the object is synchronized (e.g. not invoked *simultaneously* from multiple threads). * 5.) Safely invoke immutable methods from multiple threads while a synchronized mutable method is being simultaneously executed in another thread. * 6.) Variables declared within the scope of the objects methods (not object properties), are not affected by executing that same method in other threads simultaneously. *///ww w . j a v a 2s . c om @Test public void testMultiThread() throws ScriptException, InterruptedException, ExecutionException { final ScriptObjectMirror obj = (ScriptObjectMirror) compiledScript.eval(); obj.callMember("setI", 2); final SquareInterface sq = ((Invocable) engine).getInterface(obj, SquareInterface.class); Callable<Boolean> testMutableTask = new Callable<Boolean>() { @Override public Boolean call() { int i = (int) (Math.random() * 10); int j = (int) (Math.random() * 10); // Validate that if the object is synchronized, it's state may be altered from different threads. synchronized (obj) { obj.callMember("setI", i); Number result = (Number) obj.callMember("getI"); if (result.intValue() != i) return false; obj.callMember("addTwice", j); result = (Number) obj.callMember("getI"); if (result.intValue() != (i + (j * 2))) return false; } return true; } }; Callable<Boolean> testImutableTask = new Callable<Boolean>() { @Override public Boolean call() { int i = (int) (Math.random() * 10); // Validate that methods which do not alter the objects state may be invoked from multiple threads simultaneously. Number result = (Number) obj.callMember("square", i); if (result.intValue() != (i * i)) return false; int secondResult = sq.square(i); if (secondResult != (i * i)) return false; return true; } }; ExecutorService executor = Executors.newCachedThreadPool(); ArrayList<Future<Boolean>> results = new ArrayList<Future<Boolean>>(); for (int i = 0; i < 500; i++) { if (Math.random() > 0.5) { results.add(executor.submit(testMutableTask)); results.add(executor.submit(testImutableTask)); } else { results.add(executor.submit(testImutableTask)); results.add(executor.submit(testMutableTask)); } } for (Future<Boolean> result : results) { boolean jsResult = result.get(); Assert.assertTrue("Threads did not interfere", jsResult); } executor.awaitTermination(1, TimeUnit.SECONDS); executor.shutdownNow(); }
From source file:com.tod.utils.logging.FleepAppender.java
License:Open Source License
private static String toJSONString(ScriptObjectMirror object) throws ScriptException { ScriptObjectMirror json = (ScriptObjectMirror) engine.eval("JSON"); return json.callMember("stringify", object).toString(); }
From source file:org.phoenicis.containers.GenericContainersManager.java
License:Open Source License
/** * {@inheritDoc}//from ww w. j a va2s.c om * @param container * @param errorCallback */ @Override public void deleteContainer(ContainerDTO container, Consumer<Exception> errorCallback) { try { this.fileUtilities.remove(new File(container.getPath())); } catch (IOException e) { LOGGER.error("Cannot delete container (" + container.getPath() + ")! Exception: " + e.toString()); errorCallback.accept(e); } // TODO: better way to get engine ID final String engineId = container.getEngine().toLowerCase(); List<ShortcutCategoryDTO> categories = this.libraryManager.fetchShortcuts(); categories.stream().flatMap(shortcutCategoryDTO -> shortcutCategoryDTO.getShortcuts().stream()) .forEach(shortcutDTO -> { final InteractiveScriptSession interactiveScriptSession = this.scriptInterpreter .createInteractiveSession(); interactiveScriptSession.eval( "include([\"engines\", \"" + engineId + "\", \"shortcuts\", \"reader\"]);", ignored -> interactiveScriptSession.eval("new ShortcutReader()", output -> { final ScriptObjectMirror shortcutReader = (ScriptObjectMirror) output; shortcutReader.callMember("of", shortcutDTO); final String containerName = (String) shortcutReader.callMember("container"); if (containerName.equals(container.getName())) { this.shortcutManager.deleteShortcut(shortcutDTO); } }, errorCallback), errorCallback); }); }
From source file:org.phoenicis.javafx.views.mainwindow.library.LibraryView.java
License:Open Source License
/** * creates a new shortcut//from w ww . j a v a 2 s . co m * * @param shortcutCreationDTO DTO describing the new shortcut */ private void createShortcut(ShortcutCreationDTO shortcutCreationDTO) { // get container // TODO: smarter way using container manager final String executablePath = shortcutCreationDTO.getExecutable().getAbsolutePath(); final String pathInContainers = executablePath.replace(containersPath, ""); final String[] split = pathInContainers.split("/"); final String engineContainer = split[0]; final String engine = (Character.toUpperCase(engineContainer.charAt(0)) + engineContainer.substring(1)) .replace("prefix", ""); // TODO: better way to get engine ID final String engineId = engine.toLowerCase(); final String container = split[1]; final InteractiveScriptSession interactiveScriptSession = scriptInterpreter.createInteractiveSession(); final String scriptInclude = "include([\"engines\", \"" + engineId + "\", \"shortcuts\", \"" + engineId + "\"]);"; interactiveScriptSession.eval(scriptInclude, ignored -> interactiveScriptSession.eval("new " + engine + "Shortcut()", output -> { final ScriptObjectMirror shortcutObject = (ScriptObjectMirror) output; shortcutObject.callMember("name", shortcutCreationDTO.getName()); shortcutObject.callMember("category", shortcutCreationDTO.getCategory()); shortcutObject.callMember("description", shortcutCreationDTO.getDescription()); shortcutObject.callMember("miniature", shortcutCreationDTO.getMiniature()); shortcutObject.callMember("search", shortcutCreationDTO.getExecutable().getName()); shortcutObject.callMember("prefix", container); shortcutObject.callMember("create"); }, e -> Platform.runLater(() -> { final ErrorDialog errorDialog = ErrorDialog.builder() .withMessage(tr("Error while creating shortcut")).withException(e) .withOwner(getContent().getScene().getWindow()).build(); errorDialog.showAndWait(); })), e -> Platform.runLater(() -> { final ErrorDialog errorDialog = ErrorDialog.builder() .withMessage(tr("Error while creating shortcut")).withException(e) .withOwner(getContent().getScene().getWindow()).build(); errorDialog.showAndWait(); })); }
From source file:org.phoenicis.library.ShortcutManager.java
License:Open Source License
public void uninstallFromShortcut(ShortcutDTO shortcutDTO, Consumer<Exception> errorCallback) { final InteractiveScriptSession interactiveScriptSession = scriptInterpreter.createInteractiveSession(); interactiveScriptSession.eval("include([\"engines\", \"wine\", \"shortcuts\", \"reader\"]);", ignored -> interactiveScriptSession.eval("new ShortcutReader()", output -> { final ScriptObjectMirror shortcutReader = (ScriptObjectMirror) output; shortcutReader.callMember("of", shortcutDTO); shortcutReader.callMember("uninstall"); }, errorCallback), errorCallback); }
From source file:org.phoenicis.library.ShortcutRunner.java
License:Open Source License
public void run(ShortcutDTO shortcutDTO, List<String> arguments, Consumer<Exception> errorCallback) { final InteractiveScriptSession interactiveScriptSession = scriptInterpreter.createInteractiveSession(); interactiveScriptSession.eval("include([\"engines\", \"wine\", \"shortcuts\", \"reader\"]);", ignored -> interactiveScriptSession.eval("new ShortcutReader()", output -> { final ScriptObjectMirror shortcutReader = (ScriptObjectMirror) output; shortcutReader.callMember("of", shortcutDTO); shortcutReader.callMember("run", arguments); }, errorCallback), errorCallback); }
From source file:org.phoenicis.library.ShortcutRunner.java
License:Open Source License
public void stop(ShortcutDTO shortcutDTO, Consumer<Exception> errorCallback) { final InteractiveScriptSession interactiveScriptSession = scriptInterpreter.createInteractiveSession(); interactiveScriptSession.eval("include([\"engines\", \"wine\", \"shortcuts\", \"reader\"]);", ignored -> interactiveScriptSession.eval("new ShortcutReader()", output -> { final ScriptObjectMirror shortcutReader = (ScriptObjectMirror) output; shortcutReader.callMember("of", shortcutDTO); shortcutReader.callMember("stop"); }, errorCallback), errorCallback); }