Java Code Examples for javax.script.CompiledScript#eval()

The following examples show how to use javax.script.CompiledScript#eval() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@Test
public void invokeFunctionWithCustomScriptContextTest() throws Exception {
    final ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");

    // create an engine and a ScriptContext, but don't set it as default
    final ScriptContext scriptContext = new SimpleScriptContext();

    // Set some value in the context
    scriptContext.setAttribute("myString", "foo", ScriptContext.ENGINE_SCOPE);

    // Evaluate script with custom context and get back a function
    final String script = "function (c) { return myString.indexOf(c); }";
    final CompiledScript compiledScript = ((Compilable)engine).compile(script);
    final Object func = compiledScript.eval(scriptContext);

    // Invoked function should be able to see context it was evaluated with
    final Object result = ((Invocable) engine).invokeMethod(func, "call", func, "o", null);
    assertTrue(((Number)result).intValue() == 1);
}
 
Example 2
private void callBeforeExecuteScript(AeiObjects aeiObjects) throws Exception {
	if (aeiObjects.getActivityProcessingConfigurator().getCallBeforeExecuteScript()) {
		if (this.hasBeforeExecuteScript(aeiObjects.getProcess(), aeiObjects.getActivity())) {
			ScriptContext scriptContext = aeiObjects.scriptContext();
			CompiledScript cs = null;
			if (this.hasBeforeExecuteScript(aeiObjects.getProcess())) {
				cs = aeiObjects.business().element().getCompiledScript(aeiObjects.getApplication().getId(),
						aeiObjects.getProcess(), Business.EVENT_BEFOREEXECUTE);
				cs.eval(scriptContext);
			}
			if (this.hasBeforeExecuteScript(aeiObjects.getActivity())) {
				cs = aeiObjects.business().element().getCompiledScript(aeiObjects.getApplication().getId(),
						aeiObjects.getActivity(), Business.EVENT_BEFOREEXECUTE);
				cs.eval(scriptContext);
			}
		}
	}
}
 
Example 3
private static List<String> duty(AeiObjects aeiObjects, Manual manual) throws Exception {
	List<String> list = new ArrayList<>();
	if (StringUtils.isNotEmpty(manual.getTaskDuty())) {
		JsonArray array = XGsonBuilder.instance().fromJson(manual.getTaskDuty(), JsonArray.class);
		Iterator<JsonElement> iterator = array.iterator();
		while (iterator.hasNext()) {
			JsonObject o = iterator.next().getAsJsonObject();
			String name = o.get("name").getAsString();
			String code = o.get("code").getAsString();
			CompiledScript compiledScript = aeiObjects.business().element()
					.getCompiledScript(aeiObjects.getActivity(), Business.EVENT_TASKDUTY, name, code);
			Object objectValue = compiledScript.eval(aeiObjects.scriptContext());
			List<String> ds = ScriptFactory.asDistinguishedNameList(objectValue);
			if (ListTools.isNotEmpty(ds)) {
				for (String str : ds) {
					List<String> os = aeiObjects.business().organization().unitDuty()
							.listIdentityWithUnitWithName(str, name);
					if (ListTools.isNotEmpty(os)) {
						list.addAll(os);
					}
				}
			}
		}
	}
	return ListTools.trim(list, true, true);
}
 
Example 4
Source Project: netbeans   File: OQLEngineImpl.java    License: Apache License 2.0 6 votes vote down vote up
private void init(Snapshot snapshot) throws RuntimeException {
    this.snapshot = snapshot;
    try {
        ScriptEngineManager manager = Scripting.newBuilder().allowAllAccess(true).build();
        engine = manager.getEngineByName("JavaScript"); // NOI18N
        InputStream strm = getInitStream();
        CompiledScript cs = ((Compilable)engine).compile(new InputStreamReader(strm));
        cs.eval();
        Object heap = ((Invocable)engine).invokeFunction("wrapHeapSnapshot", snapshot); // NOI18N
        engine.put("heap", heap); // NOI18N
        engine.put("cancelled", cancelled); // NOI18N
    } catch (Exception ex) {
        LOGGER.log(Level.INFO, "Error initializing snapshot", ex); // NOI18N
        throw new RuntimeException(ex);
    }
}
 
Example 5
Source Project: jstarcraft-core   File: LuaFunction.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public <T> T doWith(Class<T> clazz, Object... arguments) {
    try {
        LuaHolder holder = threadHolder.get();
        for (int index = 0, size = classes.length; index < size; index++) {
            holder.attributes.put(StringUtility.format("argument{}", index), arguments[index]);
        }
        holder.attributes.putAll(holder.scope.getAttributes());
        CompiledScript script = holder.script;
        T object = (T) script.eval();
        holder.scope.deleteAttributes();
        return object;
    } catch (ScriptException exception) {
        throw new ScriptExpressionException(exception);
    }
}
 
Example 6
private Map<String, String> jaxrsEvalHead(AeiObjects aeiObjects, Invoke invoke) throws Exception {
	Map<String, String> map = new LinkedHashMap<>();
	if ((StringUtils.isNotEmpty(invoke.getJaxrsHeadScript()))
			|| (StringUtils.isNotEmpty(invoke.getJaxrsHeadScriptText()))) {

		ScriptContext scriptContext = aeiObjects.scriptContext();
		scriptContext.getBindings(ScriptContext.ENGINE_SCOPE).put(ScriptFactory.BINDING_NAME_JAXRSHEAD, map);
		/* 重新注入对象需要重新运行 */
		ScriptFactory.initialScriptText().eval(scriptContext);
		CompiledScript cs = aeiObjects.business().element().getCompiledScript(aeiObjects.getWork().getApplication(),
				aeiObjects.getActivity(), Business.EVENT_INVOKEJAXRSHEAD);
		cs.eval(scriptContext);

	}
	return map;
}
 
Example 7
private void callAfterInquireScript(AeiObjects aeiObjects) throws Exception {
	if (aeiObjects.getActivityProcessingConfigurator().getCallAfterInquireScript()) {
		if (this.hasAfterInquireScript(aeiObjects.getProcess(), aeiObjects.getActivity())) {
			ScriptContext scriptContext = aeiObjects.scriptContext();
			CompiledScript cs = null;
			if (this.hasAfterInquireScript(aeiObjects.getProcess())) {
				cs = aeiObjects.business().element().getCompiledScript(aeiObjects.getApplication().getId(),
						aeiObjects.getProcess(), Business.EVENT_AFTERINQUIRE);
				cs.eval(scriptContext);
			}
			if (this.hasAfterInquireScript(aeiObjects.getActivity())) {
				cs = aeiObjects.business().element().getCompiledScript(aeiObjects.getApplication().getId(),
						aeiObjects.getActivity(), Business.EVENT_AFTERINQUIRE);
				cs.eval(scriptContext);
			}
		}
	}
}
 
Example 8
/** 取到script指定的identity */
private static List<String> script(AeiObjects aeiObjects) throws Exception {
	List<String> list = new ArrayList<>();
	if ((StringUtils.isNotEmpty(aeiObjects.getActivity().getReadScript()))
			|| (StringUtils.isNotEmpty(aeiObjects.getActivity().getReadScriptText()))) {
		ScriptContext scriptContext = aeiObjects.scriptContext();
		CompiledScript compiledScript = aeiObjects.business().element().getCompiledScript(
				aeiObjects.getWork().getApplication(), aeiObjects.getActivity(), Business.EVENT_READ);
		Object objectValue = compiledScript.eval(scriptContext);
		List<String> os = ScriptFactory.asDistinguishedNameList(objectValue);
		if (ListTools.isNotEmpty(os)) {
			list.addAll(os);
		}
	}
	return list;
}
 
Example 9
private void callAfterExecuteScript(AeiObjects aeiObjects) throws Exception {
	if (aeiObjects.getActivityProcessingConfigurator().getCallAfterExecuteScript()) {
		if (this.hasAfterExecuteScript(aeiObjects.getProcess(), aeiObjects.getActivity())) {
			ScriptContext scriptContext = aeiObjects.scriptContext();
			CompiledScript cs = null;
			if (this.hasAfterExecuteScript(aeiObjects.getProcess())) {
				cs = aeiObjects.business().element().getCompiledScript(aeiObjects.getApplication().getId(),
						aeiObjects.getProcess(), Business.EVENT_AFTEREXECUTE);
				cs.eval(scriptContext);
			}
			if (this.hasAfterExecuteScript(aeiObjects.getActivity())) {
				cs = aeiObjects.business().element().getCompiledScript(aeiObjects.getApplication().getId(),
						aeiObjects.getActivity(), Business.EVENT_AFTEREXECUTE);
				cs.eval(scriptContext);
			}
		}
	}
}
 
Example 10
private void callBeforeArriveScript(AeiObjects aeiObjects) throws Exception {
	if (aeiObjects.getActivityProcessingConfigurator().getCallBeforeArriveScript()) {
		if (this.hasBeforeArriveScript(aeiObjects.getProcess(), aeiObjects.getActivity())) {
			ScriptContext scriptContext = aeiObjects.scriptContext();
			CompiledScript cs = null;
			if (this.hasBeforeArriveScript(aeiObjects.getProcess())) {
				cs = aeiObjects.business().element().getCompiledScript(aeiObjects.getApplication().getId(),
						aeiObjects.getProcess(), Business.EVENT_BEFOREARRIVE);
				cs.eval(scriptContext);
			}
			if (this.hasBeforeArriveScript(aeiObjects.getActivity())) {
				cs = aeiObjects.business().element().getCompiledScript(aeiObjects.getApplication().getId(),
						aeiObjects.getActivity(), Business.EVENT_BEFOREARRIVE);
				cs.eval(scriptContext);
			}
		}
	}
}
 
Example 11
@Override
protected List<Work> executeProcessing(AeiObjects aeiObjects) throws Exception {
	Manual manual = (Manual) aeiObjects.getActivity();
	List<Work> os = executing(aeiObjects, manual);
	if (ListTools.isEmpty(os)) {
		/** Manual Work 还没有处理完 发生了停留,出发了停留事件 */
		if (this.hasManualStayScript(manual)) {
			ScriptContext scriptContext = aeiObjects.scriptContext();
			CompiledScript cs = null;
			cs = aeiObjects.business().element().getCompiledScript(aeiObjects.getApplication().getId(),
					aeiObjects.getActivity(), Business.EVENT_MANUALSTAY);
			cs.eval(scriptContext);
		}
	}
	return os;
}
 
Example 12
private void jaxwsExternal(AeiObjects aeiObjects, Invoke invoke) throws Exception {
	Object[] parameters = this.jaxwsEvalParameters(aeiObjects, invoke);
	JaxwsObject jaxwsObject = new JaxwsObject();
	jaxwsObject.setAddress(invoke.getJaxwsAddress());
	jaxwsObject.setMethod(invoke.getJaxwsMethod());
	jaxwsObject.setParameters(parameters);
	if (BooleanUtils.isTrue(invoke.getAsync())) {
		ThisApplication.syncJaxwsInvokeQueue.send(jaxwsObject);
	} else {
		InvokeExecutor executor = new InvokeExecutor();
		Object response = executor.execute(jaxwsObject);
		if ((StringUtils.isNotEmpty(invoke.getJaxwsResponseScript()))
				|| (StringUtils.isNotEmpty(invoke.getJaxwsResponseScriptText()))) {
			ScriptContext scriptContext = aeiObjects.scriptContext();
			scriptContext.getBindings(ScriptContext.ENGINE_SCOPE).put(ScriptFactory.BINDING_NAME_JAXWSRESPONSE,
					response);
			/* 重新注入对象需要重新运行 */
			ScriptFactory.initialScriptText().eval(scriptContext);
			CompiledScript cs = aeiObjects.business().element().getCompiledScript(
					aeiObjects.getWork().getApplication(), aeiObjects.getActivity(),
					Business.EVENT_INVOKEJAXWSRESPONSE);
			cs.eval(scriptContext);
		}
	}
}
 
Example 13
Source Project: openjdk-jdk9   File: Test6.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    System.out.println("\nTest6\n");
    ScriptEngineManager m = new ScriptEngineManager();
    ScriptEngine engine = Helper.getJsEngine(m);
    if (engine == null) {
        System.out.println("Warning: No js engine found; test vacuously passes.");
        return;
    }

    try (Reader reader = new FileReader(
        new File(System.getProperty("test.src", "."), "Test6.js"))) {
        engine.eval(reader);
    }
    Object res = engine.get("res");

    CompiledScript scr = null;
    try (Reader reader = new FileReader(
        new File(System.getProperty("test.src", "."), "Test6.js"))) {
        scr = ((Compilable)engine).compile(reader);
    }

    if (scr == null) {
        throw new RuntimeException("compilation failed!");
    }

    scr.eval();
    Object res1 = engine.get("res");
    if (! res.equals(res1)) {
        throw new RuntimeException("values not equal");
    }
}
 
Example 14
Source Project: SubTitleSearcher   File: Test2.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
	ScriptEngineManager manager = new ScriptEngineManager();
	ScriptEngine engine = manager.getEngineByName("JavaScript");
	try {
		String script = "function getUrl(){var url='adsf';return url;} getUrl()";
		Compilable compilable = (Compilable) engine;
		CompiledScript JSFunction = compilable.compile(script);
		Object result = JSFunction.eval();
		System.out.println(result);
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 15
Source Project: SubTitleSearcher   File: ExeJsUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 执行js并返回结果
 * @param jsStr
 * @return
 */
public static String getJsVal(String jsStr) {
	ScriptEngineManager manager = new ScriptEngineManager();
	ScriptEngine engine = manager.getEngineByName("JavaScript");
	try {
		Compilable compilable = (Compilable) engine;
		CompiledScript JSFunction = compilable.compile(jsStr);
		Object result = JSFunction.eval();
		return result != null ? result.toString() : null;
	} catch (Exception e) {
		e.printStackTrace();
	}
	return null;
}
 
Example 16
private Object[] jaxwsEvalParameters(AeiObjects aeiObjects, Invoke invoke) throws Exception {
	List<?> parameters = new ArrayList<>();
	if ((StringUtils.isNotEmpty(invoke.getJaxwsParameterScript()))
			|| (StringUtils.isNotEmpty(invoke.getJaxwsParameterScriptText()))) {
		ScriptContext scriptContext = aeiObjects.scriptContext();
		scriptContext.getBindings(ScriptContext.ENGINE_SCOPE).put(ScriptFactory.BINDING_NAME_PARAMETERS,
				parameters);
		/* 重新注入对象需要重新运行 */
		ScriptFactory.initialScriptText().eval(scriptContext);
		CompiledScript cs = aeiObjects.business().element().getCompiledScript(aeiObjects.getWork().getApplication(),
				aeiObjects.getActivity(), Business.EVENT_INVOKEJAXWSPARAMETER);
		cs.eval(scriptContext);
	}
	return parameters.toArray();
}
 
Example 17
public Object eval(ScriptEngine engine, String script, ScriptContext context) throws ScriptException
{
	if (engine instanceof Compilable && ATTEMPT_COMPILATION)
	{
		Compilable eng = (Compilable) engine;
		CompiledScript cs = eng.compile(script);
		return context != null ? cs.eval(context) : cs.eval();
	} else
		return context != null ? engine.eval(script, context) : engine.eval(script);
}
 
Example 18
@Override
protected List<Work> executing(AeiObjects aeiObjects, Agent agent) throws Exception {
	List<Work> results = new ArrayList<>();
	if (StringUtils.isNotEmpty(agent.getScript()) || StringUtils.isNotEmpty(agent.getScriptText())) {
		CompiledScript compiledScript = aeiObjects.business().element().getCompiledScript(
				aeiObjects.getWork().getApplication(), aeiObjects.getActivity(), Business.EVENT_AGENT);
		compiledScript.eval(aeiObjects.scriptContext());
	}
	results.add(aeiObjects.getWork());
	return results;
}
 
Example 19
private void convert(Business business, DataItemConverter<Item> converter, CompiledScript outValueCompiledScript,
		CompiledScript inValueCompiledScript, CompiledScript attachmentCompiledScript, LanguageProcessingHelper lph,
		Model model, WorkCompleted workCompleted, TreeSet<String> inValue, TreeSet<String> outValue)
		throws Exception {
	logger.debug("神经网络多层感知机 ({}) 正在生成条目: {}.", model.getName(), workCompleted.getTitle());
	List<Item> items = business.entityManagerContainer().listEqualAndEqual(Item.class, Item.itemCategory_FIELDNAME,
			ItemCategory.pp, Item.bundle_FIELDNAME, workCompleted.getJob());
	/* 先计算output,在后面可以在data的text先把output替换掉 */
	Data data = XGsonBuilder.convert(converter.assemble(items), Data.class);
	ScriptContext scriptContext = new SimpleScriptContext();
	scriptContext.getBindings(ScriptContext.ENGINE_SCOPE).put(ScriptFactory.BINDING_NAME_DATA, data);
	Object objectValue = outValueCompiledScript.eval(scriptContext);
	outValue.addAll(ScriptFactory.asStringList(objectValue));
	StringBuffer text = new StringBuffer();
	String dataText = converter.text(items, true, true, true, true, true, ",");
	dataText = StringUtils.replaceEach(dataText, outValue.toArray(new String[outValue.size()]),
			StringTools.fill(outValue.size(), ","));
	text.append(dataText);
	List<Attachment> attachmentObjects = business.entityManagerContainer().listEqual(Attachment.class,
			Attachment.job_FIELDNAME, workCompleted.getJob());
	/* 把不需要的附件过滤掉 */
	if (null != attachmentCompiledScript) {
		List<String> attachments = ListTools.extractProperty(attachmentObjects, Attachment.name_FIELDNAME,
				String.class, true, true);
		scriptContext.getBindings(ScriptContext.ENGINE_SCOPE).put(BaseAction.PROPERTY_ATTACHMENTS, attachments);
		attachmentCompiledScript.eval(scriptContext);
		attachmentObjects = ListTools.removePropertyNotIn(attachmentObjects, Attachment.name_FIELDNAME,
				attachments);
	}
	for (Attachment att : attachmentObjects) {
		/* 文件小于10M */
		if (att.getLength() < BaseAction.MAX_ATTACHMENT_BYTE_LENGTH) {
			StorageMapping mapping = ThisApplication.context().storageMappings().get(Attachment.class,
					att.getStorage());
			if (null != mapping) {
				att.dumpContent(mapping);
				text.append(ExtractTextHelper.extract(att.getBytes(), att.getName(), true, true, true, false));
			}
		}
	}
	switch (StringUtils.trimToEmpty(model.getAnalyzeType())) {
	case Model.ANALYZETYPE_FULL:
		lph.word(text.toString()).stream().limit(MapTools.getInteger(model.getPropertyMap(),
				Model.PROPERTY_MLP_GENERATEINTEXTCUTOFFSIZE, Model.DEFAULT_MLP_GENERATEINTEXTCUTOFFSIZE))
				.forEach(w -> {
					inValue.add(w.getValue());
				});
		break;
	case Model.ANALYZETYPE_CUSTOMIZED:
		break;
	default:
		inValue.addAll(HanLP
				.extractKeyword(text.toString(),
						MapTools.getInteger(model.getPropertyMap(), Model.PROPERTY_MLP_GENERATEINTEXTCUTOFFSIZE,
								Model.DEFAULT_MLP_GENERATEINTEXTCUTOFFSIZE) * 2)
				.stream().filter(o -> o.length() > 1).limit(MapTools.getInteger(model.getPropertyMap(),
						Model.PROPERTY_MLP_GENERATEINTEXTCUTOFFSIZE, Model.DEFAULT_MLP_GENERATEINTEXTCUTOFFSIZE))
				.collect(Collectors.toList()));
		break;
	}
	if (null != inValueCompiledScript) {
		scriptContext.getBindings(ScriptContext.ENGINE_SCOPE).put(BaseAction.PROPERTY_INVALUES, inValue);
		inValueCompiledScript.eval(scriptContext);
	}
}
 
Example 20
Source Project: netbeans   File: OQLEngineImpl.java    License: Apache License 2.0 4 votes vote down vote up
public Object evalScript(String script) throws Exception {
    cancelled.set(false);
    CompiledScript cs = ((Compilable)engine).compile(script);
    return cs.eval();
}