Search in sources :

Example 46 with ScriptEngine

use of javax.script.ScriptEngine in project adempiere by adempiere.

the class ModelValidationEngine method fireDocValidate.

//	removeDocValidate
/**
	 * 	Fire Document Validation.
	 * 	Call docValidate method of added validators
	 *	@param po persistent objects
	 *	@param timing see ModelValidator.TIMING_ constants
     *	@return error message or null
	 */
public String fireDocValidate(PO po, int docTiming) {
    if (po == null || m_docValidateListeners.size() == 0)
        return null;
    String propertyName = po.get_TableName() + "*";
    ArrayList<ModelValidator> list = m_docValidateListeners.get(propertyName);
    if (list != null) {
        //ad_entitytype.modelvalidationclasses
        String error = fireDocValidate(po, docTiming, list);
        if (error != null && error.length() > 0)
            return error;
    }
    propertyName = po.get_TableName() + po.getAD_Client_ID();
    list = m_docValidateListeners.get(propertyName);
    if (list != null) {
        //ad_client.modelvalidationclasses
        String error = fireDocValidate(po, docTiming, list);
        if (error != null && error.length() > 0)
            return error;
    }
    // now process the script model validator for this event
    List<MTableScriptValidator> scriptValidators = MTableScriptValidator.getModelValidatorRules(po.getCtx(), po.get_Table_ID(), ModelValidator.documentEventValidators[docTiming]);
    if (scriptValidators != null) {
        for (MTableScriptValidator scriptValidator : scriptValidators) {
            MRule rule = MRule.get(po.getCtx(), scriptValidator.getAD_Rule_ID());
            // currently just JSR 223 supported
            if (rule != null && rule.isActive() && rule.getRuleType().equals(MRule.RULETYPE_JSR223ScriptingAPIs) && rule.getEventType().equals(MRule.EVENTTYPE_ModelValidatorDocumentEvent)) {
                String error;
                try {
                    ScriptEngine engine = rule.getScriptEngine();
                    // no window
                    MRule.setContext(engine, po.getCtx(), 0);
                    // now add the method arguments to the engine 
                    engine.put(MRule.ARGUMENTS_PREFIX + "Ctx", po.getCtx());
                    engine.put(MRule.ARGUMENTS_PREFIX + "PO", po);
                    engine.put(MRule.ARGUMENTS_PREFIX + "Type", docTiming);
                    engine.put(MRule.ARGUMENTS_PREFIX + "Event", ModelValidator.documentEventValidators[docTiming]);
                    Object retval = engine.eval(rule.getScript());
                    error = (retval == null ? "" : retval.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                    error = e.toString();
                }
                if (error != null && error.length() > 0)
                    return error;
            }
        }
    }
    return null;
}
Also used : ScriptEngine(javax.script.ScriptEngine)

Example 47 with ScriptEngine

use of javax.script.ScriptEngine in project adempiere by adempiere.

the class ModelValidationEngine method fireModelChange.

//	removeModelValidator
/**
	 * 	Fire Model Change.
	 * 	Call modelChange method of added validators
	 *	@param po persistent objects
	 *	@param type ModelValidator.TYPE_*
	 *	@return error message or NULL for no veto
	 */
public String fireModelChange(PO po, int changeType) {
    if (po == null || m_modelChangeListeners.size() == 0)
        return null;
    String propertyName = po.get_TableName() + "*";
    ArrayList<ModelValidator> list = m_modelChangeListeners.get(propertyName);
    if (list != null) {
        //ad_entitytype.modelvalidationclasses
        String error = fireModelChange(po, changeType, list);
        if (error != null && error.length() > 0)
            return error;
    }
    propertyName = po.get_TableName() + po.getAD_Client_ID();
    list = m_modelChangeListeners.get(propertyName);
    if (list != null) {
        //ad_client.modelvalidationclasses
        String error = fireModelChange(po, changeType, list);
        if (error != null && error.length() > 0)
            return error;
    }
    // now process the script model validator for this event
    List<MTableScriptValidator> scriptValidators = MTableScriptValidator.getModelValidatorRules(po.getCtx(), po.get_Table_ID(), ModelValidator.tableEventValidators[changeType]);
    if (scriptValidators != null) {
        for (MTableScriptValidator scriptValidator : scriptValidators) {
            MRule rule = MRule.get(po.getCtx(), scriptValidator.getAD_Rule_ID());
            // currently just JSR 223 supported
            if (rule != null && rule.isActive() && rule.getRuleType().equals(MRule.RULETYPE_JSR223ScriptingAPIs) && rule.getEventType().equals(MRule.EVENTTYPE_ModelValidatorTableEvent)) {
                String error;
                try {
                    ScriptEngine engine = rule.getScriptEngine();
                    // no window
                    MRule.setContext(engine, po.getCtx(), 0);
                    // now add the method arguments to the engine 
                    engine.put(MRule.ARGUMENTS_PREFIX + "Ctx", po.getCtx());
                    engine.put(MRule.ARGUMENTS_PREFIX + "PO", po);
                    engine.put(MRule.ARGUMENTS_PREFIX + "Type", changeType);
                    engine.put(MRule.ARGUMENTS_PREFIX + "Event", ModelValidator.tableEventValidators[changeType]);
                    Object retval = engine.eval(rule.getScript());
                    error = (retval == null ? "" : retval.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                    error = e.toString();
                }
                if (error != null && error.length() > 0)
                    return error;
            }
        }
    }
    return null;
}
Also used : ScriptEngine(javax.script.ScriptEngine)

Example 48 with ScriptEngine

use of javax.script.ScriptEngine in project adempiere by adempiere.

the class BrowserRow method processCallOut.

/**
     * ***********************************************************************
     * Adapted for Browse CallOuts
     * Process Callout(s) Adapted.
     * <p/>
     * The Callout is in the string of
     * "class.method;class.method;"
     * If there is no class name, i.e. only a method name, the class is regarded
     * as CalloutSystem.
     * The class needs to comply with the Interface Callout.
     * <p/>
     * For a limited time, the old notation of Sx_matheod / Ux_menthod is maintained.
     *
     * @param field field
     * @return error message or ""
     * @see org.compiere.model.Callout
     */
public String processCallOut(Properties ctx, int WindowNo, GridField field, Object value, Object oldValue, int currentRow, int currentColumn) {
    //	Set current Row
    setCurrentRow(currentRow);
    //	Valid Callout
    String callout = field.getCallout();
    if (callout.length() == 0)
        return "";
    //Object value = field.getValue();
    //Object oldValue = field.getOldValue();
    log.fine(field.getColumnName() + "=" + value + " (" + callout + ") - old=" + oldValue);
    StringTokenizer st = new StringTokenizer(callout, ";,", false);
    while (//  for each callout
    st.hasMoreTokens()) {
        String cmd = st.nextToken().trim();
        //detect infinite loop
        if (activeCallOuts.contains(cmd))
            continue;
        String retValue = "";
        // Victor Perez  - vpj-cd implement JSR 223 Scripting
        if (cmd.toLowerCase().startsWith(MRule.SCRIPT_PREFIX)) {
            MRule rule = MRule.get(ctx, cmd.substring(MRule.SCRIPT_PREFIX.length()));
            if (rule == null) {
                retValue = "Callout " + cmd + " not found";
                log.log(Level.SEVERE, retValue);
                return retValue;
            }
            if (!(rule.getEventType().equals(MRule.EVENTTYPE_Callout) && rule.getRuleType().equals(MRule.RULETYPE_JSR223ScriptingAPIs))) {
                retValue = "Callout " + cmd + " must be of type JSR 223 and event Callout";
                log.log(Level.SEVERE, retValue);
                return retValue;
            }
            ScriptEngine engine = rule.getScriptEngine();
            // Window context are    W_
            // Login context  are    G_
            MRule.setContext(engine, ctx, WindowNo);
            // now add the callout parameters windowNo, tab, field, value, oldValue to the engine
            // Method arguments context are A_
            engine.put(MRule.ARGUMENTS_PREFIX + "WindowNo", WindowNo);
            engine.put(MRule.ARGUMENTS_PREFIX + "Tab", this);
            engine.put(MRule.ARGUMENTS_PREFIX + "Field", field);
            engine.put(MRule.ARGUMENTS_PREFIX + "Value", value);
            engine.put(MRule.ARGUMENTS_PREFIX + "OldValue", oldValue);
            engine.put(MRule.ARGUMENTS_PREFIX + "currentRow", currentRow);
            engine.put(MRule.ARGUMENTS_PREFIX + "currentColumn", currentColumn);
            engine.put(MRule.ARGUMENTS_PREFIX + "Ctx", ctx);
            try {
                activeCallOuts.add(cmd);
                retValue = engine.eval(rule.getScript()).toString();
            } catch (Exception e) {
                log.log(Level.SEVERE, "", e);
                retValue = "Callout Invalid: " + e.toString();
                return retValue;
            } finally {
                activeCallOuts.remove(cmd);
            }
        } else {
            BrowserCallOut call = null;
            String method = null;
            int methodStart = cmd.lastIndexOf('.');
            try {
                if (//  no class
                methodStart != -1) {
                    Class<?> cClass = Class.forName(cmd.substring(0, methodStart));
                    call = (BrowserCallOut) cClass.newInstance();
                    method = cmd.substring(methodStart + 1);
                }
            } catch (Exception e) {
                log.log(Level.SEVERE, "class", e);
                return "Callout Invalid: " + cmd + " (" + e.toString() + ")";
            }
            if (call == null || method == null || method.length() == 0)
                return "Callout Invalid: " + method;
            try {
                activeCallOuts.add(cmd);
                activeCallOutInstance.add(call);
                retValue = call.start(ctx, method, WindowNo, this, field, value, oldValue, currentRow, currentColumn);
            } catch (Exception e) {
                log.log(Level.SEVERE, "start", e);
                retValue = "Callout Invalid: " + e.toString();
                return retValue;
            } finally {
                activeCallOuts.remove(cmd);
                activeCallOutInstance.remove(call);
            }
        }
        if (//	interrupt on first error
        !Util.isEmpty(retValue)) {
            log.severe(retValue);
            return retValue;
        }
    }
    //  for each callout
    return "";
}
Also used : StringTokenizer(java.util.StringTokenizer) MRule(org.compiere.model.MRule) ScriptEngine(javax.script.ScriptEngine)

Example 49 with ScriptEngine

use of javax.script.ScriptEngine in project lucene-solr by apache.

the class ScriptTransformer method initEngine.

private void initEngine(Context context) {
    String scriptText = context.getScript();
    String scriptLang = context.getScriptLanguage();
    if (scriptText == null) {
        throw new DataImportHandlerException(SEVERE, "<script> tag is not present under <dataConfig>");
    }
    ScriptEngineManager scriptEngineMgr = new ScriptEngineManager();
    ScriptEngine scriptEngine = scriptEngineMgr.getEngineByName(scriptLang);
    if (scriptEngine == null) {
        throw new DataImportHandlerException(SEVERE, "Cannot load Script Engine for language: " + scriptLang);
    }
    if (scriptEngine instanceof Invocable) {
        engine = (Invocable) scriptEngine;
    } else {
        throw new DataImportHandlerException(SEVERE, "The installed ScriptEngine for: " + scriptLang + " does not implement Invocable.  Class is " + scriptEngine.getClass().getName());
    }
    try {
        scriptEngine.eval(scriptText);
    } catch (ScriptException e) {
        wrapAndThrow(SEVERE, e, "'eval' failed with language: " + scriptLang + " and script: \n" + scriptText);
    }
}
Also used : Invocable(javax.script.Invocable) ScriptException(javax.script.ScriptException) ScriptEngineManager(javax.script.ScriptEngineManager) ScriptEngine(javax.script.ScriptEngine)

Example 50 with ScriptEngine

use of javax.script.ScriptEngine in project lucene-solr by apache.

the class ScriptEngineTest method testJRuby.

public void testJRuby() throws ScriptException, NoSuchMethodException {
    // Simply adding jruby.jar to Solr's lib/ directory gets this test passing
    ScriptEngine engine = manager.getEngineByName("jruby");
    Assume.assumeNotNull(engine);
    assertNotNull(engine);
    engine.eval("def add(a,b); a + b; end");
    Number result = (Number) ((Invocable) engine).invokeFunction("add", 1, 2);
    assertNotNull(result);
    assertEquals(3, result.intValue());
}
Also used : ScriptEngine(javax.script.ScriptEngine)

Aggregations

ScriptEngine (javax.script.ScriptEngine)175 ScriptEngineManager (javax.script.ScriptEngineManager)70 ScriptException (javax.script.ScriptException)46 Test (org.junit.Test)29 Bindings (javax.script.Bindings)20 IOException (java.io.IOException)19 Map (java.util.Map)14 Invocable (javax.script.Invocable)13 File (java.io.File)11 FileReader (java.io.FileReader)11 ScriptEngineFactory (javax.script.ScriptEngineFactory)11 HashMap (java.util.HashMap)10 ScriptContext (javax.script.ScriptContext)10 SimpleBindings (javax.script.SimpleBindings)10 InputStreamReader (java.io.InputStreamReader)9 GroovyTest (org.enumerable.lambda.support.groovy.GroovyTest)9 ScalaTest (org.enumerable.lambda.support.scala.ScalaTest)9 PrintWriter (java.io.PrintWriter)7 JavaScriptTest (org.enumerable.lambda.support.javascript.JavaScriptTest)7 JRubyTest (org.enumerable.lambda.support.jruby.JRubyTest)7