Example usage for javax.script ScriptEngine eval

List of usage examples for javax.script ScriptEngine eval

Introduction

In this page you can find the example usage for javax.script ScriptEngine eval.

Prototype

public Object eval(Reader reader) throws ScriptException;

Source Link

Document

Same as eval(String) except that the source of the script is provided as a Reader

Usage

From source file:com.seajas.search.contender.service.modifier.ModifierScriptProcessor.java

/**
 * Evaluate the given script./*from   w  ww  .  j  a  va2s . c  om*/
 *
 * @param settings
 * @param script
 * @param input
 * @param uri
 * @return String
 * @throws ScriptException
 */
private String evaluateScript(final WebResolverSettings settings, final ModifierScript script, String input,
        URI uri) throws ScriptException {
    final ScriptCacheEntry entry = scriptCache.acquireScript(script);

    try {
        final ScriptEngine engine = entry != null ? entry.getScript().getEngine()
                : engineManager.getEngineByName(script.getScriptLanguage().toLowerCase());

        FeedScriptEvaluation evaluation = new FeedScriptEvaluation(settings);
        evaluation.setScriptResolver(new ScriptCacheResolver<FeedScript>() {
            @Override
            public FeedScript resolve(final Bindings bindings) throws ScriptException {
                for (Map.Entry<String, Object> binding : bindings.entrySet())
                    engine.put(binding.getKey(), binding.getValue());

                if (entry != null) {
                    if (logger.isTraceEnabled())
                        logger.trace("Executing compiled script with ID " + script.getId());

                    entry.getScript().eval();
                } else {
                    if (logger.isTraceEnabled())
                        logger.trace(String.format("Executing non-compiled script with ID %d and content '%s'",
                                script.getId(), script.getScriptContent()));

                    engine.eval(script.getScriptContent());
                }

                return ((Invocable) engine).getInterface(FeedScript.class);
            }
        });

        evaluation.setFeedURI(uri);
        evaluation.setFeedContent(input);

        evaluation.setEngine(engine);

        evaluation.setCacheResolver(new FeedScriptCacheResolver() {
            @Override
            public boolean isCached(final String resource) {
                logger.info("Cache requested URI: " + resource);

                String cacheKey = cacheService.createCompositeKey(resource, settings.getResultParameters());

                return cacheService.isCached(cacheKey);
            }
        });

        evaluation.setWebPages(new WebPages());
        DefaultWebResolver resolver = new DefaultWebResolver();
        resolver.setSettings(settings);
        resolver.setContenderService(contenderService);
        evaluation.setWebResolver(resolver);

        evaluation.init();
        evaluation.run();

        SyndFeed feed = evaluation.getFeed();
        if (feed == null)
            throw new ScriptException("No result available");

        try {
            WebFeeds.validate(feed, uri);

            SyndFeedOutput serializer = new SyndFeedOutput();

            return serializer.outputString(feed, true);
        } catch (FeedException e) {
            throw new ScriptException("Can't serialize feed result: " + e);
        }
    } finally {
        scriptCache.releaseScript(script, entry);
    }
}

From source file:org.eclairjs.nashorn.Utils.java

public static Object javaToJs(Object o, ScriptEngine engine) {
    if (o == null)
        return o;
    if (engine == null) {
        engine = NashornEngineSingleton.getEngine();
    }//from  w  w w .ja  v  a2  s .  co m
    String packageName = o.getClass().getCanonicalName();
    switch (packageName) {
    case "java.lang.String":
    case "java.lang.Integer":
    case "java.lang.Float":
    case "java.lang.Double":
    case "java.lang.Boolean":
        return o;
    case "org.json.simple.JSONObject":
        JSONObject json = (JSONObject) o;
        if (ModuleUtils.isModule(json)) {
            Object mod = ModuleUtils.getRequiredFile(json, engine);
            // System.out.println("mod" + mod);
            //    Serialize.logger.debug("Serialize.JSModule found a lambda required module: "+mod);
            return mod;
            // return (mod && mod.exportname) ? mod.exports[mod.exportname] : (mod ? mod.exports : false);
        }
        //System.out.println("JSONObject" + json.toJSONString());
        Invocable invocable = (Invocable) engine;
        try {

            String cmd = "JSON.parse('" + json.toJSONString() + "')";
            /*
            If the JSON string has a "string" the result is \"string\" which is invalid JSON
            SO we need to change to \\"string\\" so JSON.parse will be happy
             */
            cmd = cmd.replace("\\\"", "\\\\\"");
            Object r = engine.eval(cmd);
            return r;
        } catch (javax.script.ScriptException e) {

            throw new RuntimeException(e.toString());
        }
        //             er  = invocable.invokeFunction("convertJavaJSONObject",params);
        //        throw new RuntimeException("java2js NOT HANDLED:"+packageName);

    case "java.util.ArrayList":
        ArrayList fromList = (ArrayList) o;
        ArrayList alist = new ArrayList(fromList.size());
        Iterator iter = fromList.iterator();
        while (iter.hasNext()) {
            alist.add(javaToJs(iter.next(), engine));
        }

        return Utils.createJavaScriptObject(alist); // FIXME Java wrapper needed
    case "org.apache.spark.mllib.recommendation.Rating":
        return new org.eclairjs.nashorn.wrap.mllib.recommendation.Rating(
                (org.apache.spark.mllib.recommendation.Rating) o);
    case "org.apache.spark.mllib.linalg.SparseVector":
        return new org.eclairjs.nashorn.wrap.mllib.linalg.SparseVector(
                (org.apache.spark.mllib.linalg.SparseVector) o);
    case "org.apache.spark.mllib.linalg.DenseVector":
        return new org.eclairjs.nashorn.wrap.mllib.linalg.DenseVector(
                (org.apache.spark.mllib.linalg.DenseVector) o);
    case "org.apache.spark.mllib.regression.LabeledPoint":
        return new org.eclairjs.nashorn.wrap.mllib.regression.LabeledPoint(
                (org.apache.spark.mllib.regression.LabeledPoint) o);
    case "org.apache.spark.ml.linalg.SparseVector":
        return new org.eclairjs.nashorn.wrap.ml.linalg.SparseVector(
                (org.apache.spark.ml.linalg.SparseVector) o);
    case "org.apache.spark.ml.linalg.DenseVector":
        return new org.eclairjs.nashorn.wrap.ml.linalg.DenseVector((org.apache.spark.ml.linalg.DenseVector) o);
    case "org.apache.spark.sql.catalyst.expressions.GenericRowWithSchema":
    case "org.apache.spark.sql.catalyst.expressions.GenericRow":
    case "org.apache.spark.sql.Row":
        return new org.eclairjs.nashorn.wrap.sql.Row((org.apache.spark.sql.Row) o);
    case "org.apache.spark.sql.Dataset":
        return new org.eclairjs.nashorn.wrap.sql.Dataset((org.apache.spark.sql.Dataset) o);
    case "org.apache.spark.sql.streaming.DataStreamReader":
        return new org.eclairjs.nashorn.wrap.sql.streaming.DataStreamReader(
                (org.apache.spark.sql.streaming.DataStreamReader) o);
    case "org.apache.spark.sql.streaming.DataStreamWriter":
        return new org.eclairjs.nashorn.wrap.sql.streaming.DataStreamWriter(
                (org.apache.spark.sql.streaming.DataStreamWriter) o);
    case "org.apache.spark.sql.streaming.SinkStatus":
        return new org.eclairjs.nashorn.wrap.sql.streaming.SinkStatus(
                (org.apache.spark.sql.streaming.SinkStatus) o);
    case "org.apache.spark.sql.streaming.SourceStatus":
        return new org.eclairjs.nashorn.wrap.sql.streaming.SourceStatus(
                (org.apache.spark.sql.streaming.SourceStatus) o);
    case "org.apache.spark.sql.streaming.StreamingQueryInfo":
        return new org.eclairjs.nashorn.wrap.sql.streaming.StreamingQueryInfo(
                (org.apache.spark.sql.streaming.StreamingQueryInfo) o);
    case "org.apache.spark.sql.streaming.StreamingQueryManager":
        return new org.eclairjs.nashorn.wrap.sql.streaming.StreamingQueryManager(
                (org.apache.spark.sql.streaming.StreamingQueryManager) o);
    case "org.apache.spark.sql.streaming.StreamingQuery":
    case "org.apache.spark.sql.execution.streaming.StreamExecution":
        return new org.eclairjs.nashorn.wrap.sql.streaming.StreamingQuery(
                (org.apache.spark.sql.streaming.StreamingQuery) o);
    case "org.apache.spark.api.java.JavaRDD":
        return new org.eclairjs.nashorn.wrap.RDD((org.apache.spark.api.java.JavaRDD) o);
    case "org.apache.spark.api.java.JavaPairRDD":
        return new org.eclairjs.nashorn.wrap.PairRDD((org.apache.spark.api.java.JavaPairRDD) o);
    case "org.apache.spark.api.java.JavaDoubleRDD":
        return new org.eclairjs.nashorn.wrap.FloatRDD((org.apache.spark.api.java.JavaDoubleRDD) o);
    case "java.sql.Timestamp":
        return new org.eclairjs.nashorn.wrap.sql.SqlTimestamp((java.sql.Timestamp) o);
    case "java.sql.Date":
        return new org.eclairjs.nashorn.wrap.sql.SqlDate((java.sql.Date) o);
    case "scala.Tuple2":
        return new org.eclairjs.nashorn.wrap.Tuple2((scala.Tuple2) o);
    case "scala.Tuple3":
        return new org.eclairjs.nashorn.wrap.Tuple3((scala.Tuple3) o);
    case "scala.Tuple4":
        return new org.eclairjs.nashorn.wrap.Tuple4((scala.Tuple4) o);
    case "scala.Tuple5":
        return new org.eclairjs.nashorn.wrap.Tuple5((scala.Tuple5) o);
    case "scala.collection.convert.Wrappers.IterableWrapper": {
        scala.collection.convert.Wrappers.IterableWrapper iterable = (scala.collection.convert.Wrappers.IterableWrapper) o;
        Iterator iterater = iterable.iterator();
        List newList = new ArrayList<>();
        while (iterater.hasNext())
            newList.add(Utils.javaToJs(iterater.next(), engine));
        return Utils.createJavaScriptObject(newList); // FIXME replace JavaScript wrapper with Java
    }
    default:
        if (o.getClass().isArray()) {

            List from = null;
            if (o instanceof int[] || o instanceof double[] || o instanceof String[]) {
                return Utils.toJsArray(o);
            } else {
                from = Arrays.asList((Object[]) o);
                alist = new ArrayList(from.size());
                for (int i = 0; i < from.size(); i++) {
                    alist.add(javaToJs(from.get(i), engine));
                }
                return Utils.toJsArray(alist.toArray());
            }

        } else {
            return Utils.createJavaScriptObject(o); //FIXME we should move this from JavaScript to Java
        }
        //throw new RuntimeException("java2js NOT HANDLED:"+packageName);

    }

    // return o;
}

From source file:org.siphon.db2js.DbjsUnitManager.java

@Override
protected JsEngineHandlerContext createEngineContext(String srcFile, String aliasPath, DataSource dataSource,
        final Map<String, Object> otherArgs) throws Exception {
    ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");

    JsEngineUtil.initEngine(engine, (Object[]) otherArgs.get("jslib"));

    File path = new File(srcFolder);

    engine.put("logger", logger);
    engine.put("dataSource", dataSource);
    engine.put("application", otherArgs.get("application"));
    //  js ??? java 
    if (otherArgs.get("preloadJs") != null) {
        String[] preloadJs = (String[]) otherArgs.get("preloadJs"); // [abs path, alias]
        logger.info("evaluate preload js: " + preloadJs[0]);
        JsEngineUtil.eval(engine, preloadJs[0], preloadJs[1],
                FileUtils.readFileToString(new File(preloadJs[0]), "utf-8"), true, false);
    }//from   w w  w  . j  av a  2  s  . com

    File src = new File(srcFile);
    String code = FileUtils.readFileToString(src, "utf-8");
    String covertedCode = this.convertCode(code, src);
    File tmp = new File(srcFile + ".converted.js");
    FileUtils.write(tmp, covertedCode, "utf-8");
    if (logger.isDebugEnabled())
        logger.debug(srcFile + " converted as " + tmp.getAbsolutePath());

    JsEngineUtil.eval(engine, srcFile, aliasPath, covertedCode, false, true);

    JsEngineHandlerContext ctxt = new JsEngineHandlerContext();
    ctxt.setScriptEngine(engine);
    ctxt.setHandler((ScriptObjectMirror) engine.eval("dbjs"));
    ctxt.setJson(new JSON(engine)); // jdk has a NativeJSON class inside but
    // it's sealed
    ctxt.setJsTypeUtil(new JsTypeUtil(engine));

    return ctxt;
}

From source file:org.wso2.carbon.event.template.manager.core.internal.util.TemplateManagerHelper.java

/**
 * Create a JavaScript engine packed with given scripts. If two scripts have methods with same name,
 * later method will override the previous method.
 *
 * @param domain//w  ww  .  j av  a 2s  .  co  m
 * @return JavaScript engine
 * @throws TemplateDeploymentException if there are any errors in JavaScript evaluation
 */
public static ScriptEngine createJavaScriptEngine(Domain domain) throws TemplateDeploymentException {

    ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
    ScriptEngine scriptEngine = scriptEngineManager
            .getEngineByName(TemplateManagerConstants.JAVASCRIPT_ENGINE_NAME);

    if (scriptEngine == null) {
        // Exception will be thrown later, only if function calls are used in the template
        log.warn("JavaScript engine is not available. Function calls in the templates cannot be evaluated");
    } else {
        if (domain != null && domain.getScripts() != null && domain.getScripts().getScript() != null) {
            Path scriptDirectory = Paths.get(TemplateManagerConstants.TEMPLATE_SCRIPT_PATH);
            if (Files.exists(scriptDirectory, LinkOption.NOFOLLOW_LINKS)
                    && Files.isDirectory(scriptDirectory)) {
                for (Script script : domain.getScripts().getScript()) {
                    String src = script.getSrc();
                    String content = script.getContent();
                    if (src != null) {
                        // Evaluate JavaScript file
                        Path scriptFile = scriptDirectory.resolve(src).normalize();
                        if (Files.exists(scriptFile, LinkOption.NOFOLLOW_LINKS)
                                && Files.isReadable(scriptFile)) {
                            if (!scriptFile.startsWith(scriptDirectory)) {
                                // The script file is not in the permitted directory
                                throw new TemplateDeploymentException("Script file "
                                        + scriptFile.toAbsolutePath() + " is not in the permitted directory "
                                        + scriptDirectory.toAbsolutePath());
                            }
                            try {
                                scriptEngine
                                        .eval(Files.newBufferedReader(scriptFile, Charset.defaultCharset()));
                            } catch (ScriptException e) {
                                throw new TemplateDeploymentException("Error in JavaScript "
                                        + scriptFile.toAbsolutePath() + ": " + e.getMessage(), e);
                            } catch (IOException e) {
                                throw new TemplateDeploymentException(
                                        "Error in reading JavaScript file: " + scriptFile.toAbsolutePath());
                            }
                        } else {
                            throw new TemplateDeploymentException("JavaScript file not exist at: "
                                    + scriptFile.toAbsolutePath() + " or not readable.");
                        }
                    }
                    if (content != null) {
                        // Evaluate JavaScript content
                        try {
                            scriptEngine.eval(content);
                        } catch (ScriptException e) {
                            throw new TemplateDeploymentException(
                                    "JavaScript declared in " + domain.getName() + " has error", e);
                        }
                    }
                }
            } else {
                log.warn("Script directory not found at: " + scriptDirectory.toAbsolutePath());
            }
        }
    }

    return scriptEngine;
}

From source file:com.servioticy.dispatcher.SOProcessor010.java

public SensorUpdate getResultSU(String streamId, Map<String, SensorUpdate> inputSUs, String origin,
        long timestamp) throws JsonParseException, JsonMappingException, IOException, ScriptException {

    Map<String, String> inputDocs = new HashMap<String, String>();
    for (Map.Entry<String, SensorUpdate> inputSUEntry : inputSUs.entrySet()) {
        inputDocs.put(inputSUEntry.getKey(), this.mapper.writeValueAsString(inputSUEntry.getValue()));
    }/*from   w  w  w .  j  av  a2s  . c  o m*/
    PSOStream pstream = this.streams.get(streamId);
    if (!checkFilter(pstream.preFilter, inputDocs)) {
        return null;
    }
    ScriptEngineManager factory = new ScriptEngineManager();
    ScriptEngine engine = factory.getEngineByName("JavaScript");

    SensorUpdate su = new SensorUpdate();

    su.setLastUpdate(timestamp);
    su.setChannels(new LinkedHashMap<String, SUChannel>());

    int nulls = 0;
    for (Entry<String, PSOChannel> channelEntry : pstream.channels.entrySet()) {
        PSOChannel pchannel = channelEntry.getValue();
        SUChannel suChannel = new SUChannel();
        if (pchannel.currentValue == null) {
            suChannel.setCurrentValue(null);
            nulls++;
        } else {
            String currentValueCode = pchannel.currentValue.replace(inputDocs);
            Class type;
            String typeName;
            Object result = null;
            typeName = pchannel.type.toLowerCase();
            if (typeName.equals("number")) {
                type = Double.class;
            } else if (typeName.equals("boolean")) {
                type = Boolean.class;
            } else if (typeName.equals("string")) {
                type = String.class;
            } else if (typeName.equals("geo_point")) {
                type = GeoPoint.class;

            } else {
                return null;
            }

            engine.eval("var result = JSON.stringify(" + currentValueCode + ")");
            result = this.mapper.readValue((String) engine.get("result"), type);
            if (type == GeoPoint.class)
                result = ((GeoPoint) result).getLat() + "," + ((GeoPoint) result).getLon();
            suChannel.setCurrentValue(result);

        }
        suChannel.setUnit(pchannel.unit);

        su.getChannels().put(channelEntry.getKey(), suChannel);
    }

    if (nulls >= su.getChannels().size()) {
        // This stream is mapping a Web Object.
        return null;
    }

    su.setTriggerPath(new ArrayList<ArrayList<String>>());

    su.setPathTimestamps(new ArrayList<Long>());

    this.mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    String resultSUDoc = this.mapper.writeValueAsString(su);
    if (!inputDocs.containsKey("result")) {
        inputDocs.put("result", resultSUDoc);
    }

    if (!checkFilter(pstream.postFilter, inputDocs)) {
        return null;
    }
    return su;
}

From source file:org.ngrinder.perftest.service.PerfTestService.java

/**
 * Get the optimal process and thread count.
 *
 * @param newVuser the count of virtual users per agent
 * @return optimal process thread count//from   w w w.  j  av  a  2s . c o m
 */
public ProcessAndThread calcProcessAndThread(int newVuser) {
    try {
        String script = getProcessAndThreadPolicyScript();
        ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript");
        engine.eval(script);
        int processCount = ((Double) engine.eval("getProcessCount(" + newVuser + ")")).intValue();
        int threadCount = ((Double) engine.eval("getThreadCount(" + newVuser + ")")).intValue();
        return new ProcessAndThread(processCount, threadCount);
    } catch (ScriptException e) {
        LOGGER.error("Error occurs while calc process and thread", e);
    }
    return new ProcessAndThread(1, 1);
}

From source file:org.rhq.enterprise.server.plugins.alertScriptlang.ScriptLangSender.java

@Override
public SenderResult send(Alert alert) {

    String scriptName = alertParameters.getSimpleValue("name", null);
    if (scriptName == null) {
        return new SenderResult(ResultState.FAILURE, "No script given");
    }//from   ww w  . j  a  va 2  s. com
    String language = alertParameters.getSimpleValue("language", "jruby");

    ScriptEngine engine = pluginComponent.getEngineByLanguage(language);
    //        ScriptEngineManager manager = new ScriptEngineManager(serverPluginEnvironment.getPluginClassLoader());
    //        engine = manager.getEngineByName(language);

    if (engine == null) {
        return new SenderResult(ResultState.FAILURE,
                "Script engine with name [" + language + "] does not exist");
    }

    File file = new File(pluginComponent.baseDir + scriptName);
    if (!file.exists() || !file.canRead()) {
        return new SenderResult(ResultState.FAILURE, "Script [" + scriptName
                + "] does not exist or is not readable at [" + file.getAbsolutePath() + "]");
    }

    Object result;
    try {
        BufferedReader br = new BufferedReader(new FileReader(file));

        Map<String, String> preferencesMap = new HashMap<String, String>();
        for (String key : preferences.getSimpleProperties().keySet())
            preferencesMap.put(key, preferences.getSimple(key).getStringValue());

        Map<String, String> parameterMap = new HashMap<String, String>();
        for (String key : alertParameters.getSimpleProperties().keySet())
            parameterMap.put(key, alertParameters.getSimple(key).getStringValue());

        ScriptContext sc = engine.getContext();
        sc.setAttribute("alertPreferences", preferencesMap, ScriptContext.ENGINE_SCOPE);
        sc.setAttribute("alertParameters", parameterMap, ScriptContext.ENGINE_SCOPE);
        engine.eval(br);

        AlertManagerLocal alertManager = LookupUtil.getAlertManager();

        Object[] args = new Object[3];
        args[0] = alert;
        args[1] = alertManager.prettyPrintAlertURL(alert);
        args[2] = alertManager.prettyPrintAlertConditions(alert, false);
        result = ((Invocable) engine).invokeFunction("sendAlert", args);

        if (result == null) {
            return new SenderResult(ResultState.FAILURE,
                    "Script ]" + scriptName + "] returned null, so success is unknown");
        }
        if (result instanceof SenderResult)
            return (SenderResult) result;

        return new SenderResult(ResultState.SUCCESS, "Sending via script resulted in " + result.toString());
    } catch (Exception e) {
        e.printStackTrace();
        return new SenderResult(ResultState.FAILURE,
                "Sending via [" + scriptName + "] failed: " + e.getMessage());
    }
}

From source file:azkaban.execapp.FlowRunner.java

private boolean evaluateExpression(final String expression) {
    boolean result = false;
    final ScriptEngineManager sem = new ScriptEngineManager();
    final ScriptEngine se = sem.getEngineByName("JavaScript");

    // Restrict permission using the two-argument form of doPrivileged()
    try {/*from w  w  w .  j ava  2s  .c  o m*/
        final Object object = AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
            @Override
            public Object run() throws ScriptException {
                return se.eval(expression);
            }
        }, new AccessControlContext(new ProtectionDomain[] { new ProtectionDomain(null, null) }) // no permissions
        );
        if (object != null) {
            result = (boolean) object;
        }
    } catch (final Exception e) {
        this.logger.error("Failed to evaluate the expression.", e);
    }

    this.logger.info("Evaluate expression result: " + result);
    return result;
}

From source file:jeplus.EPlusTask.java

protected final void parseTagsAndVals(ArrayList<String> prevkey, ArrayList<String> prevval) {
    // Parse search strings for hybrid parameters "@@a@@|@@b@@"
    SearchStringList = new ArrayList<>();
    AltValueList = new ArrayList<>();
    Scripts = new ArrayList<>();
    // Initialize Jython script engine
    ScriptEngine engine = JEPlusProject.getScript_Engine();

    // size of keys and vals must be the same
    for (int i = 0; i < prevkey.size(); i++) {
        String[] sstrs = prevkey.get(i).split("\\s*\\|\\s*");
        SearchStringList.addAll(Arrays.asList(sstrs));
        String[] vstrs = prevval.get(i).split("\\s*\\|\\s*");
        for (int j = 0; j < Math.min(vstrs.length, sstrs.length); j++) {
            // for each val string, perform calculations if it starts with "?="
            String formula = vstrs[j];
            if (formula.startsWith("?=")) {
                formula = formula.substring(2);
                // Create a new parser
                //                    Parser parser = new Parser();
                // Map search tags to variables and then assign values to variables
                HashMap<String, String> map = new HashMap<>();
                for (int k = 0; k < SearchStringList.size() - sstrs.length; k++) {
                    String var = "p" + k;
                    map.put(SearchStringList.get(k), var);
                    String statement = var + " = " + AltValueList.get(k);
                    try {
                        engine.eval(statement);
                    } catch (ScriptException spe) {
                        logger.error("Error evaluating expression " + statement + ".");
                    }//from  w  ww  .j a va  2  s .c om
                }
                for (String tag : map.keySet()) {
                    formula = formula.replaceAll(tag, map.get(tag));
                }
                try {
                    vstrs[j] = engine.eval(formula).toString();
                } catch (ScriptException spe) {
                    logger.error("Error evaluating expression " + formula + ".");
                }
                // If starts with "call(", create a script record and add "script" to vstrs
            } else if (formula.startsWith("call(")) {
                formula = formula.substring(5, formula.length() - 1);
                Scripts.add(PythonFunc.fromString(formula));
                vstrs[j] = "script";
            }
            // Add the result string to the list
            AltValueList.add(vstrs[j]);
        }
        // If val strings set is shorter than search strings set, repeating the last val string
        for (int j = vstrs.length; j < sstrs.length; j++) {
            AltValueList.add(vstrs[vstrs.length - 1]);
        }
    }
}

From source file:org.jgentleframework.integration.scripting.ScriptingInstantiationInterceptor.java

@Override
public Object instantiate(ObjectInstantiation oi) throws Throwable {

    Object result = null;/*from w  ww  .  jav  a  2s. co  m*/
    Class<?> target = oi.getTargetClass();
    Definition definition = this.definitionManager.getDefinition(target);
    if (definition.isAnnotationPresent(ScriptingInject.class)) {
        if (!target.isInterface()) {
            if (log.isFatalEnabled()) {
                log.fatal("Could not binding to Scripting service",
                        new ScriptException("Target class must be a interface!"));
            }
        }
        final ScriptingInject scriptingInject = definition.getAnnotation(ScriptingInject.class);
        Object previous = oi.getPreviousResult();
        if (previous == null) {
            ScriptEngineManager engineManager = new ScriptEngineManager();
            ScriptEngine engine = engineManager.getEngineByName(scriptingInject.lang().getType());
            if (engine == null) {
                if (log.isFatalEnabled()) {
                    log.fatal(
                            "Script engine with name : " + scriptingInject.lang().getType() + " is not found!",
                            new ScriptException("Script engine with name : " + scriptingInject.lang().getType()
                                    + " is not found!"));
                }
                throw new ScriptException(
                        "Script engine with name : " + scriptingInject.lang().getType() + " is not found!");
            }
            File parentFile = null;
            if (!(PathType.CLASSPATH.equals(scriptingInject.pathType())
                    || PathType.CLASSPATH.equals(scriptingInject.pathType()))) {
                parentFile = new File(scriptingInject.pathType().getType());
            }
            File sourceFile = null;
            if (parentFile != null) {
                sourceFile = new File(parentFile, scriptingInject.scriptFile());
            } else {
                if (PathType.CLASSPATH.equals(scriptingInject.pathType())) {
                    sourceFile = new File(ScriptingInstantiationInterceptor.class
                            .getResource(scriptingInject.scriptFile()).toURI());
                } else {
                    sourceFile = new File(scriptingInject.scriptFile());
                }
            }
            engine.eval(new FileReader(sourceFile));
            Invocable inv = (Invocable) engine;
            final Object scriptObject = inv.getInterface(target);
            result = scriptObject;
            final Enhancer enhancer = new Enhancer();
            enhancer.setInterfaces(new Class<?>[] { target });
            enhancer.setCallback(new MethodInterceptor() {
                @Override
                public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy)
                        throws Throwable {

                    if (method.getName().equals("hashCode")) {
                        final int prime = 31;
                        int result = 1;
                        result = prime * result + super.hashCode();
                        result = prime * result + enhancer.hashCode();
                        return result;
                    } else {
                        MethodInvocation invocation = new BasicMethodInvocation(obj, method, args);
                        return invoke(invocation, scriptObject);
                    }
                }

                protected Object invoke(MethodInvocation invocation, Object stub) throws NoSuchMethodException,
                        IllegalArgumentException, IllegalAccessException, InvocationTargetException {

                    Object result = null;
                    Method method = null;
                    Method methodType = invocation.getMethod();
                    Class<?> clazz = stub.getClass();
                    Class<?>[] classType = ReflectUtils.getClassTypeOf(invocation.getArguments());
                    method = ReflectUtils.getSupportedMethod(clazz, methodType.getName(), classType);
                    result = method.invoke(stub, invocation.getArguments());
                    return result;
                }
            });
            if (oi.args() != null && oi.argTypes() != null)
                result = enhancer.create(oi.argTypes(), oi.args());
            else
                result = enhancer.create();
            oi.setPreviousResult(result);
        } else {
            if (log.isFatalEnabled()) {
                log.fatal(
                        "Does not support multible Instantiation Interceptor "
                                + "conjointly with Scripting Instantiation",
                        new ScriptException("Does not support multible Instantiation Interceptor!"));
            }
        }
        return oi.proceed();
    } else {
        if (log.isWarnEnabled()) {
            log.warn("The target interface is not annotated with [" + ScriptingInject.class + "]");
        }
    }
    return result;
}