Example usage for javax.script ScriptException toString

List of usage examples for javax.script ScriptException toString

Introduction

In this page you can find the example usage for javax.script ScriptException toString.

Prototype

public String toString() 

Source Link

Document

Returns a short description of this throwable.

Usage

From source file:io.lightlink.translator.JSBeautifyPostProcessor.java

@Override
public String process(String script) throws IOException {
    String beautifier = IOUtils.toString(Thread.currentThread().getContextClassLoader()
            .getResourceAsStream("io/lightlink/translator/beautify.js"));

    ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
    try {//  ww w. j a  v  a2 s .  c  o m
        engine.eval(beautifier);
        engine.getBindings(ScriptContext.ENGINE_SCOPE).put("$originalScript", script);
        return engine.eval("js_beautify($originalScript, {})") + "";
    } catch (ScriptException e) {
        LOG.error(e.toString(), e);
        return script;
    }

}

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  . j  a  v  a 2  s. com
    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:com.yahoo.validatar.execution.rest.JSON.java

/**
 * Uses the user provided query to process and return a JSON columnar format of the data.
 *
 * @param data The data from the REST call.
 * @param function The function name to invoke.
 * @param query The Query object being run.
 * @return The String JSON response of the call, null if exception (query is failed).
 */// w  w  w. ja  v  a  2  s. c o m
String convertToColumnarJSON(String data, String function, Query query) {
    try {
        log.info("Evaluating query using Javascript function: {}\n{}", function, query.value);
        evaluator.eval(query.value);
        Invocable invocable = (Invocable) evaluator;
        String columnarJSON = (String) invocable.invokeFunction(function, data);
        log.info("Processed response using query into JSON: {}", columnarJSON);
        return columnarJSON;
    } catch (ScriptException se) {
        log.error("Exception while processing input Javascript", se);
        query.setFailure(se.toString());
        query.addMessage(se.toString());
    } catch (NoSuchMethodException nsme) {
        log.error("Method {} not found in {}\n{}", function, query.value, nsme);
        query.setFailure(nsme.toString());
    }
    return null;
}

From source file:com.cubeia.ProtocolGeneratorMojo.java

private void generateCode(String lang, File protocolFile, File outputBaseDirectory, String packageName,
        boolean generateVisitors, String version, boolean failOnBadPacketOrder, String javascript_package_name)
        throws MojoExecutionException, MojoFailureException {

    if (append_language_to_output_base_dir) {
        outputBaseDirectory = appendLangToBaseDir(lang, outputBaseDirectory);
        getLog().info("Appended language '" + lang + "' to base dir, new base dir: " + outputBaseDirectory);
    }/* www.j ava 2  s  .c o  m*/

    ScriptEngineManager factory = new ScriptEngineManager();

    // Create a JRuby engine.
    ScriptEngine engine = factory.getEngineByName("jruby");

    // Evaluate JRuby code from string.
    InputStream scriptIn = getClass().getResourceAsStream(GENERATOR_WRAPPER_SCRIPT);
    if (scriptIn == null) {
        new MojoExecutionException(
                "unable to find code generator script resource: " + GENERATOR_WRAPPER_SCRIPT);
    }

    Object[] args = new Object[] { protocolFile.getPath(), lang, outputBaseDirectory.getPath(), packageName,
            generateVisitors ? "true" : null, version, failOnBadPacketOrder ? "true" : null,
            javascript_package_name };

    InputStreamReader scriptReader = new InputStreamReader(scriptIn);

    try {
        engine.eval(scriptReader);
        Invocable invocableEngine = (Invocable) engine;
        invocableEngine.invokeFunction("generate_code", args);
    } catch (ScriptException e) {
        throw new MojoFailureException("code generation error: " + e.toString());
    } catch (NoSuchMethodException e) {
        throw new MojoExecutionException("error calling code generator script: " + e.getMessage());
    }
}

From source file:com.yahoo.validatar.execution.rest.JSON.java

/**
 * Converts the String columnar JSON data into a Map of column names to List of column values. Internal use only.
 *
 * @param columnarData The String columnar JSON data.
 * @param query The Query object being run.
 * @return The Map version of the JSON data, null if exception (query is failed).
 *///from   w w w.  ja  v a 2 s .  c o  m
Map<String, List<TypedObject>> convertToMap(String columnarData, Query query) {
    try {
        log.info("Converting processed JSON into a map...");
        // Type erasure will make this not enough if the JSON parses into a map but with the wrong keys, values.
        Map<String, List<Object>> result = (Map<String, List<Object>>) evaluator
                .eval(String.format(JSON_TO_MAP_FORMAT, columnarData));
        // But this will catch it.
        Map<String, List<TypedObject>> typed = type(result);
        log.info("Conversion complete!");
        return typed;
    } catch (ScriptException se) {
        log.error("Could not convert the processed JSON to the required format", se);
        query.setFailure("Invalid JSON (try a linter): " + columnarData);
        query.addMessage(se.toString());
    } catch (ClassCastException cce) {
        log.error("The returned JSON is not in the map of columns format", cce);
        query.setFailure("Your extracted JSON is not in a map of columns format: " + columnarData);
        query.addMessage(cce.toString());
    }
    return null;
}

From source file:org.forgerock.openidm.jaspi.modules.IDMJaspiModuleWrapper.java

/**
 * Gets the ScriptEntry for the specified script config.
 *
 * @param scriptConfig The script config.
 * @return The ScriptEntry.// www  .  j  a  va2  s  . c o m
 * @throws JaspiAuthException If there is a problem retrieving the ScriptEntry.
 */
ScriptEntry getAugmentScript(JsonValue scriptConfig) throws JaspiAuthException {
    try {
        return authnFilterHelper.getScriptRegistry().takeScript(scriptConfig);
    } catch (ScriptException e) {
        logger.error("{} when attempting to register script {}", e.toString(), scriptConfig, e);
        throw new JaspiAuthException(e.toString(), e);
    }
}

From source file:org.forgerock.openidm.auth.modules.IDMAuthModuleWrapper.java

/**
 * Gets the ScriptEntry for the specified script config.
 *
 * @param scriptConfig The script config.
 * @return The ScriptEntry./* ww  w . j a v  a2 s. c o m*/
 * @throws AuthenticationException If there is a problem retrieving the ScriptEntry.
 */
ScriptEntry getAugmentScript(JsonValue scriptConfig) throws AuthenticationException {
    try {
        return scriptRegistry.takeScript(scriptConfig);
    } catch (ScriptException e) {
        logger.error("{} when attempting to register script {}", e.toString(), scriptConfig, e);
        throw new AuthenticationException(e.toString(), e);
    }
}

From source file:org.lsc.utils.JScriptEvaluator.java

/**
 * Local instance evaluation./*from w  w  w  . j  av a  2s .  c  o m*/
 *
 * @param expression
 *                the expression to eval
 * @param params
 *                the keys are the name used in the
 * @return the evaluation result
 * @throws LscServiceException 
 */
private Object instanceEval(final Task task, final String expression, final Map<String, Object> params)
        throws LscServiceException {
    //      Script script = null;
    Bindings bindings = engine.createBindings();

    /* Allow to have shorter names for function in the package org.lsc.utils.directory */
    String expressionImport = "var version = java.lang.System.getProperty(\"java.version\");\n"
            + "if (version.startsWith(\"1.8.0\")) { load(\"nashorn:mozilla_compat.js\"); }\n"
            + "importPackage(org.lsc.utils.directory);\n" + "importPackage(org.lsc.utils);\n" + expression;

    //      if (cache.containsKey(expressionImport)) {
    //         script = cache.get(expressionImport);
    //      } else {
    //         script = cx.compileString(expressionImport, "<cmd>", 1, null);
    //         cache.put(expressionImport, script);
    //      }

    // add LDAP interface for destination
    if (!bindings.containsKey("ldap") && task.getDestinationService() instanceof AbstractSimpleJndiService) {
        ScriptableJndiServices dstSjs = new ScriptableJndiServices();
        dstSjs.setJndiServices(((AbstractSimpleJndiService) task.getDestinationService()).getJndiServices());
        bindings.put("ldap", dstSjs);
    }

    // add LDAP interface for source
    if (!bindings.containsKey("srcLdap") && task.getSourceService() instanceof AbstractSimpleJndiService) {
        ScriptableJndiServices srcSjs = new ScriptableJndiServices();
        srcSjs.setJndiServices(((AbstractSimpleJndiService) task.getSourceService()).getJndiServices());
        bindings.put("srcLdap", srcSjs);
    }

    if (params != null) {
        for (String paramName : params.keySet()) {
            bindings.put(paramName, params.get(paramName));
        }
    }

    Object ret = null;
    try {
        if (task.getScriptIncludes() != null) {
            for (File scriptInclude : task.getScriptIncludes()) {
                if ("js".equals(FilenameUtils.getExtension(scriptInclude.getAbsolutePath()))) {
                    FileReader reader = new FileReader(scriptInclude);
                    try {
                        engine.eval(reader, bindings);
                    } finally {
                        reader.close();
                    }
                }
            }
        }
        ret = engine.eval(expressionImport, bindings);
    } catch (ScriptException e) {
        LOGGER.error("Fail to compute expression: " + expression + " on "
                + (params.containsKey("srcBean") && ((IBean) params.get("srcBean")).getMainIdentifier() != null
                        ? "id=" + ((IBean) params.get("srcBean")).getMainIdentifier()
                        : (params.containsKey("dstBean")
                                && ((IBean) params.get("dstBean")).getMainIdentifier() != null
                                        ? "id=" + ((IBean) params.get("dstBean")).getMainIdentifier()
                                        : "unknown id !"))
                + "\nReason: " + e.toString());
        LOGGER.debug(e.toString(), e);
        throw new LscServiceException(e);
    } catch (RuntimeException e) {
        throw new LscServiceException(e);
    } catch (Exception e) {
        LOGGER.error(e.toString());
        LOGGER.debug(e.toString(), e);
        return null;
    }

    return ret;
}