Search in sources :

Example 21 with ScriptException

use of javax.script.ScriptException in project zaproxy by zaproxy.

the class ExtensionScript method handleScriptException.

/**
	 * Handles exceptions thrown by scripts.
	 * <p>
	 * The given {@code exception} (if of type {@code ScriptException} the cause will be used instead) will be written to the
	 * given {@code writer} and the given {@code script} will be disabled and flagged that has an error.
	 *
	 * @param script the script that resulted in an exception, must not be {@code null}
	 * @param writer the writer associated with the script, must not be {@code null}
	 * @param exception the exception thrown , must not be {@code null}
	 * @see #setError(ScriptWrapper, Exception)
	 * @see #setEnabled(ScriptWrapper, boolean)
	 * @see ScriptException
	 */
private void handleScriptException(ScriptWrapper script, Writer writer, Exception exception) {
    Exception cause = exception;
    if (cause instanceof ScriptException && cause.getCause() instanceof Exception) {
        // Dereference one level
        cause = (Exception) cause.getCause();
    }
    try {
        writer.append(cause.toString());
    } catch (IOException ignore) {
        logger.error(cause.getMessage(), cause);
    }
    this.setError(script, cause);
    this.setEnabled(script, false);
}
Also used : ScriptException(javax.script.ScriptException) IOException(java.io.IOException) MalformedInputException(java.nio.charset.MalformedInputException) InvalidParameterException(java.security.InvalidParameterException) ScriptException(javax.script.ScriptException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException)

Example 22 with ScriptException

use of javax.script.ScriptException in project apex-core by apache.

the class StramClientUtils method evalProperties.

public static void evalProperties(Properties target, Configuration vars) {
    ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript");
    Pattern substitutionPattern = Pattern.compile("\\$\\{(.+?)\\}");
    Pattern evalPattern = Pattern.compile("\\{% (.+?) %\\}");
    try {
        engine.eval("var _prop = {}");
        for (Map.Entry<String, String> entry : vars) {
            String evalString = String.format("_prop[\"%s\"] = \"%s\"", StringEscapeUtils.escapeJava(entry.getKey()), StringEscapeUtils.escapeJava(entry.getValue()));
            engine.eval(evalString);
        }
    } catch (ScriptException ex) {
        LOG.warn("Javascript error: {}", ex.getMessage());
    }
    for (Map.Entry<Object, Object> entry : target.entrySet()) {
        String value = entry.getValue().toString();
        Matcher matcher = substitutionPattern.matcher(value);
        if (matcher.find()) {
            StringBuilder newValue = new StringBuilder();
            int cursor = 0;
            do {
                newValue.append(value.substring(cursor, matcher.start()));
                String subst = vars.get(matcher.group(1));
                if (subst != null) {
                    newValue.append(subst);
                }
                cursor = matcher.end();
            } while (matcher.find());
            newValue.append(value.substring(cursor));
            target.put(entry.getKey(), newValue.toString());
        }
        matcher = evalPattern.matcher(value);
        if (matcher.find()) {
            StringBuilder newValue = new StringBuilder();
            int cursor = 0;
            do {
                newValue.append(value.substring(cursor, matcher.start()));
                try {
                    Object result = engine.eval(matcher.group(1));
                    String eval = result.toString();
                    if (eval != null) {
                        newValue.append(eval);
                    }
                } catch (ScriptException ex) {
                    LOG.warn("JavaScript exception {}", ex.getMessage());
                }
                cursor = matcher.end();
            } while (matcher.find());
            newValue.append(value.substring(cursor));
            target.put(entry.getKey(), newValue.toString());
        }
    }
}
Also used : Pattern(java.util.regex.Pattern) ScriptException(javax.script.ScriptException) Matcher(java.util.regex.Matcher) ScriptEngineManager(javax.script.ScriptEngineManager) Map(java.util.Map) HashMap(java.util.HashMap) ScriptEngine(javax.script.ScriptEngine)

Example 23 with ScriptException

use of javax.script.ScriptException in project incubator-atlas by apache.

the class Titan0Graph method executeGremlinScript.

private Object executeGremlinScript(String gremlinQuery) throws AtlasBaseException {
    Object result = null;
    ScriptEngine engine = getGremlinScriptEngine();
    try {
        Bindings bindings = engine.createBindings();
        bindings.put("g", getGraph());
        result = engine.eval(gremlinQuery, bindings);
    } catch (ScriptException e) {
        throw new AtlasBaseException(AtlasErrorCode.GREMLIN_SCRIPT_EXECUTION_FAILED, gremlinQuery);
    } finally {
        releaseGremlinScriptEngine(engine);
    }
    return result;
}
Also used : ScriptException(javax.script.ScriptException) AtlasBaseException(org.apache.atlas.exception.AtlasBaseException) Bindings(javax.script.Bindings) ScriptEngine(javax.script.ScriptEngine)

Example 24 with ScriptException

use of javax.script.ScriptException in project jmeter by apache.

the class JSR223PostProcessor method process.

@Override
public void process() {
    try {
        ScriptEngine scriptEngine = getScriptEngine();
        processFileOrScript(scriptEngine, null);
    } catch (ScriptException | IOException e) {
        log.error("Problem in JSR223 script, {}", getName(), e);
    }
}
Also used : ScriptException(javax.script.ScriptException) IOException(java.io.IOException) ScriptEngine(javax.script.ScriptEngine)

Example 25 with ScriptException

use of javax.script.ScriptException in project jmeter by apache.

the class JSR223TestElement method processFileOrScript.

/**
     * This method will run inline script or file script with special behaviour for file script:
     * - If ScriptEngine implements Compilable script will be compiled and cached
     * - If not if will be run
     * @param scriptEngine ScriptEngine
     * @param bindings {@link Bindings} might be null
     * @return Object returned by script
     * @throws IOException when reading the script fails
     * @throws ScriptException when compiling or evaluation of the script fails
     */
protected Object processFileOrScript(ScriptEngine scriptEngine, Bindings bindings) throws IOException, ScriptException {
    if (bindings == null) {
        bindings = scriptEngine.createBindings();
    }
    populateBindings(bindings);
    File scriptFile = new File(getFilename());
    // Hack: bsh-2.0b5.jar BshScriptEngine implements Compilable but throws
    // "java.lang.Error: unimplemented"
    boolean supportsCompilable = scriptEngine instanceof Compilable && // NOSONAR // $NON-NLS-1$
    !("bsh.engine.BshScriptEngine".equals(scriptEngine.getClass().getName()));
    try {
        if (!StringUtils.isEmpty(getFilename())) {
            if (scriptFile.exists() && scriptFile.canRead()) {
                if (supportsCompilable) {
                    String cacheKey = // $NON-NLS-1$
                    getScriptLanguage() + "#" + scriptFile.getAbsolutePath() + // $NON-NLS-1$
                    "#" + scriptFile.lastModified();
                    CompiledScript compiledScript = compiledScriptsCache.get(cacheKey);
                    if (compiledScript == null) {
                        synchronized (compiledScriptsCache) {
                            compiledScript = compiledScriptsCache.get(cacheKey);
                            if (compiledScript == null) {
                                // TODO Charset ?
                                try (BufferedReader fileReader = new BufferedReader(new FileReader(scriptFile), (int) scriptFile.length())) {
                                    compiledScript = ((Compilable) scriptEngine).compile(fileReader);
                                    compiledScriptsCache.put(cacheKey, compiledScript);
                                }
                            }
                        }
                    }
                    return compiledScript.eval(bindings);
                } else {
                    // TODO Charset ?
                    try (BufferedReader fileReader = new BufferedReader(new FileReader(scriptFile), (int) scriptFile.length())) {
                        return scriptEngine.eval(fileReader, bindings);
                    }
                }
            } else {
                throw new ScriptException("Script file '" + scriptFile.getAbsolutePath() + "' does not exist or is unreadable for element:" + getName());
            }
        } else if (!StringUtils.isEmpty(getScript())) {
            if (supportsCompilable && !StringUtils.isEmpty(cacheKey)) {
                computeScriptMD5();
                CompiledScript compiledScript = compiledScriptsCache.get(this.scriptMd5);
                if (compiledScript == null) {
                    synchronized (compiledScriptsCache) {
                        compiledScript = compiledScriptsCache.get(this.scriptMd5);
                        if (compiledScript == null) {
                            compiledScript = ((Compilable) scriptEngine).compile(getScript());
                            compiledScriptsCache.put(this.scriptMd5, compiledScript);
                        }
                    }
                }
                return compiledScript.eval(bindings);
            } else {
                return scriptEngine.eval(getScript(), bindings);
            }
        } else {
            throw new ScriptException("Both script file and script text are empty for element:" + getName());
        }
    } catch (ScriptException ex) {
        Throwable rootCause = ex.getCause();
        if (isStopCondition(rootCause)) {
            throw (RuntimeException) ex.getCause();
        } else {
            throw ex;
        }
    }
}
Also used : CompiledScript(javax.script.CompiledScript) ScriptException(javax.script.ScriptException) Compilable(javax.script.Compilable) BufferedReader(java.io.BufferedReader) FileReader(java.io.FileReader) File(java.io.File)

Aggregations

ScriptException (javax.script.ScriptException)98 IOException (java.io.IOException)41 ScriptEngine (javax.script.ScriptEngine)36 Bindings (javax.script.Bindings)27 ScriptEngineManager (javax.script.ScriptEngineManager)17 CompiledScript (javax.script.CompiledScript)12 InputStreamReader (java.io.InputStreamReader)11 Invocable (javax.script.Invocable)11 ScriptContext (javax.script.ScriptContext)10 Map (java.util.Map)9 SimpleBindings (javax.script.SimpleBindings)8 Reader (java.io.Reader)7 HashMap (java.util.HashMap)7 File (java.io.File)6 Writer (java.io.Writer)6 ArrayList (java.util.ArrayList)6 SlingBindings (org.apache.sling.api.scripting.SlingBindings)6 MissingMethodException (groovy.lang.MissingMethodException)5 MissingPropertyException (groovy.lang.MissingPropertyException)5 DelegatingMetaClass (groovy.lang.DelegatingMetaClass)4