javax.script.CompiledScript Java Examples

The following examples show how to use javax.script.CompiledScript. 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
Source File: TranslateReadIdentityTools.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
/** 取到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 #2
Source File: SetExternalNameWizard.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
public void setExternalName ( final CompiledScript script ) throws Exception
{
    final CompoundManager manager = new CompoundManager ();

    for ( final ExternalValue v : SelectionHelper.iterable ( this.selection, ExternalValue.class ) )
    {
        final EditingDomain domain = AdapterFactoryEditingDomain.getEditingDomainFor ( v );
        if ( domain == null )
        {
            continue;
        }
        final String name = evalName ( script, v );
        manager.append ( domain, SetCommand.create ( domain, v, ComponentPackage.Literals.EXTERNAL_VALUE__SOURCE_NAME, name ) );
    }

    manager.executeAll ();
}
 
Example #3
Source File: ScopeTest.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
@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
    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); }";
    CompiledScript compiledScript = ((Compilable)engine).compile(script);
    Object func = compiledScript.eval(scriptContext);

    // Invoked function should be able to see context it was evaluated with
    Object result = ((Invocable) engine).invokeMethod(func, "call", func, "o", null);
    assertTrue(((Number)result).intValue() == 1);
}
 
Example #4
Source File: OQLEngineImpl.java    From netbeans with 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 File: ScopeTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
@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
    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); }";
    CompiledScript compiledScript = ((Compilable)engine).compile(script);
    Object func = compiledScript.eval(scriptContext);

    // Invoked function should be able to see context it was evaluated with
    Object result = ((Invocable) engine).invokeMethod(func, "call", func, "o", null);
    assertTrue(((Number)result).intValue() == 1);
}
 
Example #6
Source File: SystemSelectorEvaluator.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
private boolean evaluate(String expression, Map<String, Object> context) {
    CompiledScript compiledScript = getOrCreateCompileScript(expression);
    if (compiledScript != null) {
        ScriptContext scriptContext = scriptEngine.getContext();
        for (Map.Entry<String, Object> entry : context.entrySet()) {
            scriptContext.setAttribute(entry.getKey(), entry.getValue(), ScriptContext.ENGINE_SCOPE);
        }
        try {
            logger.debug("Evaluating expression: {}", expression);
            Object result = scriptEngine.eval(expression, scriptContext);
            logger.debug("Evaluated expression: {} and got result: {}", expression, result);
            if (result == Boolean.TRUE) {
                return true;
            }

        } catch (ScriptException e) {
            logger.debug("Unable to evaluate expression: {}", expression, e);
            throw SchedulerException.systemSelectorEvaluationError("Unable to evaluate expression: %s", e, expression);
        }
    }
    return false;
}
 
Example #7
Source File: SetExternalNameWizard.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
public static String evalName ( final CompiledScript script, final ExternalValue v ) throws Exception
{
    final SimpleScriptContext ctx = new SimpleScriptContext ();

    ctx.setAttribute ( "item", v, ScriptContext.ENGINE_SCOPE ); //$NON-NLS-1$

    final Object result = Scripts.executeWithClassLoader ( Activator.class.getClassLoader (), new Callable<Object> () {

        @Override
        public Object call () throws Exception
        {
            return script.eval ( ctx );
        }
    } );

    if ( result == null )
    {
        return null;
    }

    return result.toString ();
}
 
Example #8
Source File: AbstractProcessor.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
private void callBeforeInquireScript(AeiObjects aeiObjects) throws Exception {
	if (aeiObjects.getActivityProcessingConfigurator().getCallBeforeInquireScript()) {
		if (this.hasBeforeInquireScript(aeiObjects.getProcess(), aeiObjects.getActivity())) {
			ScriptContext scriptContext = aeiObjects.scriptContext();
			CompiledScript cs = null;
			if (this.hasBeforeInquireScript(aeiObjects.getProcess())) {
				cs = aeiObjects.business().element().getCompiledScript(aeiObjects.getApplication().getId(),
						aeiObjects.getProcess(), Business.EVENT_BEFOREINQUIRE);
				cs.eval(scriptContext);
			}
			if (this.hasBeforeInquireScript(aeiObjects.getActivity())) {
				cs = aeiObjects.business().element().getCompiledScript(aeiObjects.getApplication().getId(),
						aeiObjects.getActivity(), Business.EVENT_BEFOREINQUIRE);
				cs.eval(scriptContext);
			}
		}
	}
}
 
Example #9
Source File: AbstractProcessor.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
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
Source File: AbstractProcessor.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
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 #11
Source File: AbstractProcessor.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
private void callAfterArriveScript(AeiObjects aeiObjects) throws Exception {
	if (aeiObjects.getActivityProcessingConfigurator().getCallAfterArriveScript()) {
		if (this.hasAfterArriveScript(aeiObjects.getProcess(), aeiObjects.getActivity())) {
			ScriptContext scriptContext = aeiObjects.scriptContext();
			CompiledScript cs = null;
			if (this.hasAfterArriveScript(aeiObjects.getProcess())) {
				cs = aeiObjects.business().element().getCompiledScript(aeiObjects.getApplication().getId(),
						aeiObjects.getProcess(), Business.EVENT_AFTERARRIVE);
				cs.eval(scriptContext);
			}
			if (this.hasAfterArriveScript(aeiObjects.getActivity())) {
				cs = aeiObjects.business().element().getCompiledScript(aeiObjects.getApplication().getId(),
						aeiObjects.getActivity(), Business.EVENT_AFTERARRIVE);
				cs.eval(scriptContext);
			}
		}
	}
}
 
Example #12
Source File: ServiceProcessor.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
protected List<Work> executing(AeiObjects aeiObjects, Service service) throws Exception {
	List<Work> results = new ArrayList<>();

	boolean passThrough = false;
	if (StringUtils.isNotEmpty(service.getScript()) || StringUtils.isNotEmpty(service.getScriptText())) {
		ScriptContext scriptContext = aeiObjects.scriptContext();
		scriptContext.getBindings(ScriptContext.ENGINE_SCOPE).put(ScriptFactory.BINDING_NAME_SERVICEVALUE,
				gson.toJson(aeiObjects.getWork().getProperties().getServiceValue()));
		CompiledScript cs = aeiObjects.business().element().getCompiledScript(aeiObjects.getWork().getApplication(),
				aeiObjects.getActivity(), Business.EVENT_SERVICE);
		passThrough = ScriptFactory.asBoolean(cs.eval(scriptContext));
	} else {
		passThrough = true;
	}
	if (passThrough) {
		results.add(aeiObjects.getWork());
	}

	return results;
}
 
Example #13
Source File: LuaFunction.java    From jstarcraft-core with 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 #14
Source File: AbstractAgentProcessor.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
protected List<Work> executeProcessing(AeiObjects aeiObjects) throws Exception {
	Agent agent = (Agent) aeiObjects.getActivity();
	List<Work> os = new ArrayList<>();
	try {
		os = executing(aeiObjects, agent);
		return os;
	} catch (Exception e) {
		if (this.hasAgentInterruptScript(agent)) {
			CompiledScript compiledScript = aeiObjects.business().element().getCompiledScript(
					aeiObjects.getWork().getApplication(), aeiObjects.getActivity(), Business.EVENT_AGENTINTERRUPT);
			compiledScript.eval(aeiObjects.scriptContext());
		}
		throw e;
	}
}
 
Example #15
Source File: AbstractManualProcessor.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
@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 #16
Source File: TranslateTaskIdentityTools.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
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 #17
Source File: InvokeProcessor.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
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 #18
Source File: ScopeTest.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
@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
    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); }";
    CompiledScript compiledScript = ((Compilable)engine).compile(script);
    Object func = compiledScript.eval(scriptContext);

    // Invoked function should be able to see context it was evaluated with
    Object result = ((Invocable) engine).invokeMethod(func, "call", func, "o", null);
    assertTrue(((Number)result).intValue() == 1);
}
 
Example #19
Source File: InvokeProcessor.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
private String jaxrsUrl(AeiObjects aeiObjects, Invoke invoke) throws Exception {
	String url = invoke.getJaxrsAddress();
	Map<String, String> parameters = new HashMap<>();
	if ((StringUtils.isNotEmpty(invoke.getJaxrsParameterScript()))
			|| (StringUtils.isNotEmpty(invoke.getJaxrsParameterScriptText()))) {

		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_INVOKEJAXRSPARAMETER);
		cs.eval(scriptContext);
	}
	for (Entry<String, String> entry : parameters.entrySet()) {
		url = StringUtils.replace(url, "{" + entry.getKey() + "}", entry.getValue());
	}
	return url;
}
 
Example #20
Source File: InvokeProcessor.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
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 #21
Source File: ScopeTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@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 #22
Source File: AbstractProcessor.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
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 #23
Source File: NashornScriptEngine.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
private CompiledScript asCompiledScript(final Source source) throws ScriptException {
    final Context.MultiGlobalCompiledScript mgcs;
    final ScriptFunction func;
    final Global oldGlobal = Context.getGlobal();
    final Global newGlobal = getNashornGlobalFrom(context);
    final boolean globalChanged = (oldGlobal != newGlobal);
    try {
        if (globalChanged) {
            Context.setGlobal(newGlobal);
        }

        mgcs = nashornContext.compileScript(source);
        func = mgcs.getFunction(newGlobal);
    } catch (final Exception e) {
        throwAsScriptException(e, newGlobal);
        throw new AssertionError("should not reach here");
    } finally {
        if (globalChanged) {
            Context.setGlobal(oldGlobal);
        }
    }

    return new CompiledScript() {
        @Override
        public Object eval(final ScriptContext ctxt) throws ScriptException {
            final Global globalObject = getNashornGlobalFrom(ctxt);
            // Are we running the script in the same global in which it was compiled?
            if (func.getScope() == globalObject) {
                return evalImpl(func, ctxt, globalObject);
            }

            // different global
            return evalImpl(mgcs, ctxt, globalObject);
        }
        @Override
        public ScriptEngine getEngine() {
            return NashornScriptEngine.this;
        }
    };
}
 
Example #24
Source File: ScriptRouter.java    From dubbox-hystrix with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public <T> List<Invoker<T>> route(List<Invoker<T>> invokers, URL url, Invocation invocation) throws RpcException {
    try {
        List<Invoker<T>> invokersCopy = new ArrayList<Invoker<T>>(invokers);
        Compilable compilable = (Compilable) engine;
        Bindings bindings = engine.createBindings();
        bindings.put("invokers", invokersCopy);
        bindings.put("invocation", invocation);
        bindings.put("context", RpcContext.getContext());
        CompiledScript function = compilable.compile(rule);
        Object obj = function.eval(bindings);
        if (obj instanceof Invoker[]) {
            invokersCopy = Arrays.asList((Invoker<T>[]) obj);
        } else if (obj instanceof Object[]) {
            invokersCopy = new ArrayList<Invoker<T>>();
            for (Object inv : (Object[]) obj) {
                invokersCopy.add((Invoker<T>)inv);
            }
        } else {
            invokersCopy = (List<Invoker<T>>) obj;
        }
        return invokersCopy;
    } catch (ScriptException e) {
        //fail then ignore rule .invokers.
        logger.error("route error , rule has been ignored. rule: " + rule + ", method:" + invocation.getMethodName() + ", url: " + RpcContext.getContext().getUrl(), e);
        return invokers;
    }
}
 
Example #25
Source File: AgentProcessor.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
@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 #26
Source File: BeginProcessor.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
protected void executingCommitted(AeiObjects aeiObjects, Begin begin) throws Exception {
	if (StringUtils.isNotEmpty(aeiObjects.getProcess().getAfterBeginScript())
			|| StringUtils.isNotEmpty(aeiObjects.getProcess().getAfterBeginScriptText())) {
		CompiledScript compiledScript = aeiObjects.business().element().getCompiledScript(
				aeiObjects.getWork().getApplication(), aeiObjects.getProcess(), Business.EVENT_PROCESSAFTERBEGIN);
		compiledScript.eval(aeiObjects.scriptContext());
	}
}
 
Example #27
Source File: Test6.java    From openjdk-jdk9 with 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 #28
Source File: TranslateReviewPersonTools.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
private static List<String> script(AeiObjects aeiObjects) throws Exception {
	List<String> list = new ArrayList<>();
	if ((StringUtils.isNotEmpty(aeiObjects.getActivity().getReviewScript()))
			|| (StringUtils.isNotEmpty(aeiObjects.getActivity().getReviewScriptText()))) {
		ScriptContext scriptContext = aeiObjects.scriptContext();
		CompiledScript compiledScript = aeiObjects.business().element().getCompiledScript(
				aeiObjects.getWork().getApplication(), aeiObjects.getActivity(), Business.EVENT_REVIEW);
		Object objectValue = compiledScript.eval(scriptContext);
		List<String> os = ScriptFactory.asDistinguishedNameList(objectValue);
		if (ListTools.isNotEmpty(os)) {
			list.addAll(os);
		}
	}
	return list;
}
 
Example #29
Source File: VirtualChestItem.java    From VirtualChest with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static VirtualChestItem deserialize(VirtualChestPlugin plugin, DataView data) throws InvalidDataException
{
    DataView serializedStack = data.getView(ITEM).orElseThrow(() -> new InvalidDataException("Expected Item"));

    String requirementString = data.getString(REQUIREMENTS).orElse("");
    Tuple<String, CompiledScript> requirements = plugin.getScriptManager().prepare(requirementString);

    List<String> ignoredPermissions = data.getStringList(IGNORED_PERMISSIONS).orElse(ImmutableList.of());

    List<DataView> actionList = getViewListOrSingletonList(ACTION, data);
    List<DataView> primaryList = getViewListOrSingletonList(PRIMARY_ACTION, data);
    List<DataView> secondaryList = getViewListOrSingletonList(SECONDARY_ACTION, data);
    List<DataView> primaryShiftList = getViewListOrSingletonList(PRIMARY_SHIFT_ACTION, data);
    List<DataView> secondaryShiftList = getViewListOrSingletonList(SECONDARY_SHIFT_ACTION, data);

    List<DataView> primaryListFinal = primaryList.isEmpty() ? actionList : primaryList;
    List<DataView> secondaryListFinal = secondaryList.isEmpty() ? actionList : secondaryList;
    List<DataView> primaryShiftListFinal = primaryShiftList.isEmpty() ? primaryListFinal : primaryShiftList;
    List<DataView> secondaryShiftListFinal = secondaryShiftList.isEmpty() ? secondaryListFinal : secondaryShiftList;

    VirtualChestActionDispatcher primaryAction = new VirtualChestActionDispatcher(primaryListFinal);
    VirtualChestActionDispatcher secondaryAction = new VirtualChestActionDispatcher(secondaryListFinal);
    VirtualChestActionDispatcher primaryShiftAction = new VirtualChestActionDispatcher(primaryShiftListFinal);
    VirtualChestActionDispatcher secondaryShiftAction = new VirtualChestActionDispatcher(secondaryShiftListFinal);

    return new VirtualChestItem(plugin, serializedStack, requirements,
            primaryAction, secondaryAction, primaryShiftAction, secondaryShiftAction, ignoredPermissions);
}
 
Example #30
Source File: ScriptEngineTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void compileAndEvalInDiffContextTest() throws ScriptException {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine engine = m.getEngineByName("js");
    final Compilable compilable = (Compilable) engine;
    final CompiledScript compiledScript = compilable.compile("foo");
    final ScriptContext ctxt = new SimpleScriptContext();
    ctxt.setAttribute("foo", "hello", ScriptContext.ENGINE_SCOPE);
    assertEquals(compiledScript.eval(ctxt), "hello");
}