List of usage examples for jdk.nashorn.api.scripting JSObject setMember
public void setMember(final String name, final Object value);
From source file:com.eas.client.queries.ScriptedQuery.java
@Override public JSObject execute(Scripts.Space aSpace, Consumer<JSObject> onSuccess, Consumer<Exception> onFailure) throws Exception { assert Scripts.getSpace() == aSpace : "Scripts.Space TLS assumption failed"; if (onSuccess != null) { ScriptedResource._require(new String[] { entityName }, null, aSpace, new HashSet<>(), (Void v) -> { JSObject source = aSpace.createModule(entityName); if (source.hasMember("fetch")) { Object oFetch = source.getMember("fetch"); if (oFetch instanceof JSObject) { JSObject jsFetch = (JSObject) oFetch; if (jsFetch.isFunction()) { JSObject jsParams = aSpace.makeObj(); for (int i = 0; i < params.getParametersCount(); i++) { Parameter p = params.get(i + 1); jsParams.setMember(p.getName(), aSpace.toJs(p.getValue())); }// www .j a v a2 s . c o m final ExecutionChecker exChecker = new ExecutionChecker(); Object oRowset = jsFetch.call(source, aSpace.toJs(new Object[] { jsParams, new AbstractJSObject() { @Override public Object call(final Object thiz, final Object... args) { if (exChecker.isExecutionNeeded()) { try { JSObject jsRowset = args.length > 0 ? (JSObject) aSpace.toJava(args[0]) : null; try { onSuccess.accept(jsRowset); } catch (Exception ex) { Logger.getLogger(ScriptedQuery.class.getName()) .log(Level.SEVERE, null, ex); } } catch (Exception ex) { if (onFailure != null) { onFailure.accept(ex); } } } return null; } }, new AbstractJSObject() { @Override public Object call(final Object thiz, final Object... args) { if (exChecker.isExecutionNeeded()) { if (onFailure != null) { if (args.length > 0) { if (args[0] instanceof Exception) { onFailure.accept((Exception) args[0]); } else { onFailure.accept(new Exception( String.valueOf(aSpace.toJava(args[0])))); } } else { onFailure.accept(new Exception( "No error information from fetch method")); } } } return null; } } })); if (!JSType.nullOrUndefined(oRowset)) { onSuccess.accept((JSObject) aSpace.toJava(oRowset)); exChecker.setExecutionNeeded(false); } } } } }, onFailure); return null; } else { JSObject source = aSpace.createModule(entityName); if (source.hasMember("fetch")) { Object oFetch = source.getMember("fetch"); if (oFetch instanceof JSObject) { JSObject jsFetch = (JSObject) oFetch; if (jsFetch.isFunction()) { JSObject jsParams = aSpace.makeObj(); Object oRowset = jsFetch.call(source, aSpace.toJs(new Object[] { jsParams })); if (!JSType.nullOrUndefined(oRowset)) { return (JSObject) aSpace.toJava(oRowset); } } } } return null; } }
From source file:com.eas.server.websocket.JsClientEndPoint.java
@OnMessage public void onMessage(Session websocketSession, String aData) { if (onmessage != null) { space.process(context, () -> { JSObject messageEvent = Scripts.getSpace().makeObj(); messageEvent.setMember("data", aData); onmessage.call(session.getPublished(), new Object[] { messageEvent }); });/*from w w w.ja v a 2 s . c om*/ } }
From source file:com.eas.server.websocket.JsClientEndPoint.java
@OnClose public void onClose(Session websocketSession, CloseReason aReason) { if (onclose != null) { space.process(context, () -> { JSObject closeEvent = Scripts.getSpace().makeObj(); closeEvent.setMember("wasClean", aReason.getCloseCode() == CloseReason.CloseCodes.NORMAL_CLOSURE); closeEvent.setMember("code", aReason.getCloseCode().getCode()); closeEvent.setMember("reason", aReason.getReasonPhrase()); onclose.call(session.getPublished(), new Object[] { closeEvent }); });//from w ww . ja v a 2 s.c o m } }
From source file:com.eas.server.websocket.JsClientEndPoint.java
@OnError public void onError(Session websocketSession, Throwable aError) { if (onerror != null) { space.process(context, () -> { JSObject errorEvent = Scripts.getSpace().makeObj(); errorEvent.setMember("message", aError.getMessage()); onerror.call(session.getPublished(), new Object[] { errorEvent }); });//from www . j av a 2 s .c o m } }
From source file:io.apigee.rowboat.internal.ScriptRunner.java
License:Open Source License
/** * One-time initialization of the built-in modules and objects. *//* w ww. j a va 2 s .c o m*/ private void initGlobals() throws NodeException { // As part of bootstrapping, we need to supply a "module" object for "process" to set up for us JSObject bootstrapModule = new DefaultScriptObject(); JSObject exports = new DefaultScriptObject(); bootstrapModule.setMember("exports", exports); // Bootstrap the whole thing with "process," which is our own internal JS/Java code // This is implemented by the "process" internal module in each node implementation Object exp = initializeModule("process", true, null, bootstrapModule, exports, "process.js"); try { process = (JSObject) invocableEngine.invokeMethod(exp, "createProcess", new Object[] { this }); } catch (ScriptException | NoSuchMethodException e) { throw new NodeException(e); } engine.getBindings(ScriptContext.ENGINE_SCOPE).put("global", new DefaultScriptObject()); // The buffer module needs special handling because of the "charsWritten" variable // TODO //buffer = (Buffer.BufferModuleImpl)require("buffer", cx); }
From source file:io.lightlink.config.NashornTestManual.java
License:Open Source License
public void test() throws ScriptException { ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("nashorn"); ScriptContext context = engine.getContext(); Compilable compilable = (Compilable) engine; CompiledScript newObjectCreator = compilable.compile("({})"); JSObject jsObject = (JSObject) newObjectCreator.eval(); jsObject.setMember("a", "a"); context.setAttribute("myObject", jsObject, ScriptContext.ENGINE_SCOPE); context.setAttribute("ctx", this, ScriptContext.ENGINE_SCOPE); Object aA = engine.eval("print(myObject.a)"); Object obj = engine.eval("(function (a,b){print(a+' '+b)})"); engine.eval("ctx.setJSFunction(function(a,b){return a+b})"); int x = 0;/* w w w .j av a 2 s.co m*/ }
From source file:io.lightlink.core.RunnerContext.java
License:Open Source License
public JSObject mapToJSObject(Map<String, Object> inputParams) throws ScriptException { JSObject params = (JSObject) newObjectScript.eval(); for (Map.Entry<String, Object> entry : inputParams.entrySet()) { params.setMember(entry.getKey(), entry.getValue()); }// w w w .j av a 2 s . c om return params; }
From source file:io.lightlink.sql.SQLHandler.java
License:Open Source License
private void loadResultSet(RunnerContext runnerContext, String rsName, ResultSet rs, JSObject rowHandler) throws SQLException, IOException { ResponseStream resp = runnerContext.getResponseStream(); resp.writePropertyArrayStart(rsName); rs.setFetchSize(facade.getFetchSize()); try {/*from ww w .ja v a 2 s . co m*/ ResultSetMetaData metaData = rs.getMetaData(); int cnt = metaData.getColumnCount(); String[] cols = new String[cnt]; String[] outNames = new String[cnt]; AbstractConverter[] convertors = new AbstractConverter[cnt]; for (int i = 0; i < cols.length; i++) { String label = metaData.getColumnLabel(i + 1); cols[i] = label; if (label.startsWith("(")) { ArgInfo argInfo = new ArgInfo(label); applyDirectivesToArgInfo(runnerContext, argInfo); convertors[i] = argInfo.getConverter(); outNames[i] = label.substring(label.lastIndexOf(")") + 1); } else { outNames[i] = label; } } JSObject line = (rowHandler == null) ? null // not needed without rowHandler : runnerContext.newJSObject(); int index = 0; while (rs.next()) { if (rowHandler != null) { for (int i = 0; i < cols.length; i++) { Object value = (convertors[i] != null) ? convertors[i].readFromResultSet(rs, i + 1, runnerContext, cols[i]) : rs.getObject(i + 1); line.setMember(outNames[i], value); } Object res = rowHandler.call(rowHandler, line, index, rsName); if (res instanceof Map) res = new LinkedHashMap((Map) res); else if (res instanceof List) res = new ArrayList((List) res); // todo : real deep copy resp.writeFullObjectToArray(genericConvertFromJdbc(runnerContext, res)); } else { resp.writeObjectStart(); for (int i = 0; i < cols.length; i++) { Object value = (convertors[i] != null) ? convertors[i].readFromResultSet(rs, i + 1, runnerContext, cols[i]) : rs.getObject(i + 1); resp.writeProperty(outNames[i], genericConvertFromJdbc(runnerContext, value)); } resp.writeObjectEnd(); } index++; } } finally { resp.writePropertyArrayEnd(); rs.close(); } }
From source file:reactor.js.core.module.JavaScriptModuleLoader.java
License:Open Source License
private JSObject loadPackageDefinition(String id) { return (JSObject) pkgDefCache.computeIfAbsent(id, s -> { JSObject pkgDef = null; for (String searchPath : searchPaths) { if (!searchPath.endsWith("/")) { searchPath += "/"; }/*www . jav a 2 s. c om*/ String baseUri; try { if (searchPath.startsWith("classpath:")) { baseUri = concatRelative(searchPath, id); if (baseUri.charAt(13) == '/') { baseUri = baseUri.substring(13); } else { baseUri = baseUri.substring(12); } // Read package.json to find what file to load String pkgJson = read(cl.getResourceAsStream(concatRelative(baseUri, "./package.json"))); if (null == pkgJson) { continue; } pkgDef = JsonFunctions.parse(pkgJson); } else { baseUri = concatRelative(searchPath, id); // Read package.json to find what file to load pkgDef = readJSON(URI.create(concatRelative(baseUri, "./package.json"))); } if (null != pkgDef) { pkgDef.setMember(PARENT_URI, searchPath); pkgDef.setMember(BASE_URI, searchPath + id); if (log.isDebugEnabled()) { log.debug("Read package.json: {}", pkgDef); } return pkgDef; } } catch (IOException e) { if (!e.getMessage().contains("No such file or directory")) { if (log.isDebugEnabled()) { log.debug(e.getMessage()); } } } } return null; }); }