javax.script.CompiledScript#eval ( )源码实例Demo

下面列出了javax.script.CompiledScript#eval ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: openjdk-jdk9   文件: ScopeTest.java
@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);
}
 
源代码2 项目: o2oa   文件: AbstractProcessor.java
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);
			}
		}
	}
}
 
源代码3 项目: o2oa   文件: TranslateTaskIdentityTools.java
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);
}
 
源代码4 项目: netbeans   文件: OQLEngineImpl.java
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);
    }
}
 
源代码5 项目: jstarcraft-core   文件: LuaFunction.java
@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);
    }
}
 
源代码6 项目: o2oa   文件: InvokeProcessor.java
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;
}
 
源代码7 项目: o2oa   文件: AbstractProcessor.java
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);
			}
		}
	}
}
 
源代码8 项目: o2oa   文件: TranslateReadIdentityTools.java
/** 取到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;
}
 
源代码9 项目: o2oa   文件: AbstractProcessor.java
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);
			}
		}
	}
}
 
源代码10 项目: o2oa   文件: AbstractProcessor.java
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);
			}
		}
	}
}
 
源代码11 项目: o2oa   文件: AbstractManualProcessor.java
@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;
}
 
源代码12 项目: o2oa   文件: InvokeProcessor.java
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);
		}
	}
}
 
源代码13 项目: openjdk-jdk9   文件: Test6.java
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");
    }
}
 
源代码14 项目: SubTitleSearcher   文件: Test2.java
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();
	}
}
 
源代码15 项目: SubTitleSearcher   文件: ExeJsUtil.java
/**
 * 执行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;
}
 
源代码16 项目: o2oa   文件: InvokeProcessor.java
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();
}
 
源代码17 项目: L2jBrasil   文件: L2ScriptEngineManager.java
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);
}
 
源代码18 项目: o2oa   文件: AgentProcessor.java
@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;
}
 
源代码19 项目: o2oa   文件: Generate.java
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);
	}
}
 
源代码20 项目: netbeans   文件: OQLEngineImpl.java
public Object evalScript(String script) throws Exception {
    cancelled.set(false);
    CompiledScript cs = ((Compilable)engine).compile(script);
    return cs.eval();
}
 
 方法所在类
 同类方法