Example usage for javax.script ScriptException getMessage

List of usage examples for javax.script ScriptException getMessage

Introduction

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

Prototype

public String getMessage() 

Source Link

Document

Returns a message containing the String passed to a constructor as well as line and column numbers and filename if any of these are known.

Usage

From source file:io.cloudslang.lang.runtime.bindings.ScriptEvaluator.java

public Serializable evalExpr(String expr, Map<String, ? extends Serializable> context) {
    ScriptContext scriptContext = new SimpleScriptContext();
    for (Map.Entry<String, ? extends Serializable> entry : context.entrySet()) {
        scriptContext.setAttribute(entry.getKey(), entry.getValue(), ScriptContext.ENGINE_SCOPE);
    }/* ww  w  .  j  a  v a 2  s. com*/
    if (scriptContext.getAttribute(TRUE) == null)
        scriptContext.setAttribute(TRUE, Boolean.TRUE, ScriptContext.ENGINE_SCOPE);
    if (scriptContext.getAttribute(FALSE) == null)
        scriptContext.setAttribute(FALSE, Boolean.FALSE, ScriptContext.ENGINE_SCOPE);
    try {
        return (Serializable) engine.eval(expr, scriptContext);
    } catch (ScriptException e) {
        ScriptException scriptException = new ScriptException(e);
        throw new RuntimeException("Error in running script expression or variable reference, for expression: '"
                + expr + "',\n\tScript exception is: " + scriptException.getMessage(), scriptException);
    }
}

From source file:org.apache.tinkerpop.gremlin.groovy.jsr223.GremlinGroovyScriptEngineCompileStaticTest.java

@Test
public void shouldCompileStatic() throws Exception {
    // with no type checking this should pass
    try (GremlinGroovyScriptEngine scriptEngine = new GremlinGroovyScriptEngine()) {
        assertEquals(255, scriptEngine.eval("((Object) new java.awt.Color(255, 255, 255)).getRed()"));
    }/*w  w w . j  a v  a2s  . c  om*/

    final CompileStaticCustomizerProvider provider = new CompileStaticCustomizerProvider();
    try (GremlinGroovyScriptEngine scriptEngine = new GremlinGroovyScriptEngine(provider)) {
        scriptEngine.eval("((Object) new java.awt.Color(255, 255, 255)).getRed()");
        fail("Should have failed type checking");
    } catch (ScriptException se) {
        final Throwable root = ExceptionUtils.getRootCause(se);
        assertEquals(MultipleCompilationErrorsException.class, root.getClass());
        assertThat(se.getMessage(), containsString(
                "[Static type checking] - Cannot find matching method java.lang.Object#getRed(). Please check if the declared type is right and if the method exists."));
    }
}

From source file:org.apache.tinkerpop.gremlin.groovy.jsr223.GremlinGroovyScriptEngineTypeCheckedTest.java

@Test
public void shouldTypeCheck() throws Exception {
    // with no type checking this should pass
    try (GremlinGroovyScriptEngine scriptEngine = new GremlinGroovyScriptEngine()) {
        assertEquals(255, scriptEngine.eval("((Object) new java.awt.Color(255, 255, 255)).getRed()"));
    }//  ww  w .java 2  s .c o m

    final TypeCheckedCustomizerProvider provider = new TypeCheckedCustomizerProvider();
    try (GremlinGroovyScriptEngine scriptEngine = new GremlinGroovyScriptEngine(provider)) {
        scriptEngine.eval("((Object) new java.awt.Color(255, 255, 255)).getRed()");
        fail("Should have failed type checking");
    } catch (ScriptException se) {
        final Throwable root = ExceptionUtils.getRootCause(se);
        assertEquals(MultipleCompilationErrorsException.class, root.getClass());
        assertThat(se.getMessage(), containsString(
                "[Static type checking] - Cannot find matching method java.lang.Object#getRed(). Please check if the declared type is right and if the method exists."));
    }
}

From source file:com.blackbear.flatworm.config.ScriptletBO.java

/**
 * Set the script snippet to be used in running the {@code matchesIdentity} test.
 *
 * @param script The script that will be executed - should take two parameters with the first being (@link FileFormat} and the second
 *               being a {@link String}, which will be the line of data to examine. The script should return a {@link Boolean}.
 * @throws FlatwormConfigurationException should the script be invalid or should the {@code scriptEngineName} not resolve to a valid
 *                                        script engine.
 *//*from w ww. jav a  2s.c om*/
public void setScript(String script) throws FlatwormConfigurationException {
    this.script = script;
    try {
        scriptEngine.eval(script);
    } catch (ScriptException e) {
        throw new FlatwormConfigurationException(
                String.format("The script provided failed to evaluate: %s%n%s", e.getMessage(), script), e);
    }
}

From source file:org.jahia.services.scheduler.JSR223ScriptJob.java

@Override
public void executeJahiaJob(JobExecutionContext jobExecutionContext) throws Exception {
    final JobDataMap map = jobExecutionContext.getJobDetail().getJobDataMap();
    String jobScriptPath;/* w w  w .j a  va  2  s  .c o  m*/
    boolean isAbsolutePath = false;
    if (map.containsKey(JOB_SCRIPT_ABSOLUTE_PATH)) {
        isAbsolutePath = true;
        jobScriptPath = map.getString(JOB_SCRIPT_ABSOLUTE_PATH);
    } else {
        jobScriptPath = map.getString(JOB_SCRIPT_PATH);
    }
    logger.info("Start executing JSR223 script job {}", jobScriptPath);

    ScriptEngine scriptEngine = ScriptEngineUtils.getInstance()
            .scriptEngine(FilenameUtils.getExtension(jobScriptPath));
    if (scriptEngine != null) {
        ScriptContext scriptContext = new SimpleScriptContext();
        final Bindings bindings = new SimpleBindings();
        bindings.put("jobDataMap", map);

        InputStream scriptInputStream;
        if (!isAbsolutePath) {
            scriptInputStream = JahiaContextLoaderListener.getServletContext()
                    .getResourceAsStream(jobScriptPath);
        } else {
            scriptInputStream = FileUtils.openInputStream(new File(jobScriptPath));
        }
        if (scriptInputStream != null) {
            Reader scriptContent = null;
            try {
                scriptContent = new InputStreamReader(scriptInputStream);
                StringWriter out = new StringWriter();
                scriptContext.setWriter(out);
                // The following binding is necessary for Javascript, which doesn't offer a console by default.
                bindings.put("out", new PrintWriter(scriptContext.getWriter()));
                scriptContext.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
                scriptContext.setBindings(scriptEngine.getContext().getBindings(ScriptContext.GLOBAL_SCOPE),
                        ScriptContext.GLOBAL_SCOPE);
                scriptEngine.eval(scriptContent, scriptContext);
                map.put(JOB_SCRIPT_OUTPUT, out.toString());
                logger.info("...JSR-223 script job {} execution finished", jobScriptPath);
            } catch (ScriptException e) {
                logger.error("Error during execution of the JSR-223 script job " + jobScriptPath
                        + " execution failed with error " + e.getMessage(), e);
                throw new Exception("Error during execution of script " + jobScriptPath, e);
            } finally {
                if (scriptContent != null) {
                    IOUtils.closeQuietly(scriptContent);
                }
            }
        }
    }
}

From source file:org.freeplane.plugin.script.GenericScript.java

private void handleScriptRuntimeException(final ScriptException e) {
    outStream.print("message: " + e.getMessage());
    int lineNumber = e.getLineNumber();
    outStream.print("Line number: " + lineNumber);
    errorHandler.gotoLine(lineNumber);//from   www .  ja v  a2 s.  co m
    throw new ExecuteScriptException(e.getMessage() + " at line " + lineNumber,
            // The ScriptException should have a cause. Use
            // that, it is what we want to know.
            (e.getCause() == null) ? e : e.getCause());
}

From source file:org.jahia.modules.macros.filter.MacrosFilter.java

@Override
public String execute(String previousOut, RenderContext renderContext, Resource resource, RenderChain chain)
        throws Exception {
    if (StringUtils.isEmpty(previousOut)) {
        return previousOut;
    }//from  ww  w.  j  a va  2  s .  c o  m
    long timer = System.currentTimeMillis();
    boolean evaluated = false;

    Matcher matcher = macrosPattern.matcher(previousOut);
    while (matcher.find()) {
        evaluated = true;
        String macroName = matcher.group(1);
        String[] macro = getMacro(macroName);
        if (macro != null) {
            try {
                // execute macro
                ScriptEngine scriptEngine = scriptEngineUtils.scriptEngine(macro[1]);
                ScriptContext scriptContext = scriptEngine.getContext();
                scriptContext.setWriter(new StringWriter());
                scriptContext.setErrorWriter(new StringWriter());
                scriptEngine.eval(macro[0], getBindings(renderContext, resource, scriptContext, matcher));
                String scriptResult = scriptContext.getWriter().toString().trim();
                previousOut = matcher.replaceFirst(scriptResult);
            } catch (ScriptException e) {
                logger.warn("Error during execution of macro " + macroName + " with message " + e.getMessage(),
                        e);
                previousOut = matcher.replaceFirst(macroName);
            }
            matcher = macrosPattern.matcher(previousOut);
        } else if (replaceByErrorMessageOnMissingMacros) {
            previousOut = matcher.replaceFirst("macro " + macroName + " not found");
            logger.warn("Unknown macro '{}'", macroName);
            matcher = macrosPattern.matcher(previousOut);
        }
    }

    if (evaluated && logger.isDebugEnabled()) {
        logger.debug("Evaluation of macros took {} ms", (System.currentTimeMillis() - timer));
    }
    return previousOut;
}

From source file:de.pixida.logtest.engine.EmbeddedScript.java

public void compile(final ScriptEngine scriptingEngine) {
    if (!this.exists()) {
        LOG.trace("Not compiling empty script");
        return;/*from  w w  w . j  a  v  a  2 s  .  c  o  m*/
    }
    if (!(scriptingEngine instanceof Compilable)) {
        // We compile scripts to improve performance. The code could be rewritten to support engines which are not capable of
        // precompiling, but for now, the current engine does, so there's no reason to handle this, as it can be easily found out
        // during unit testing. Therefore, we should never get here under real conditions.
        throw new RuntimeException("Scripting engine does not support precompiling scripts");
    }

    LOG.trace("Compiling script: {}", this.script);
    try {
        this.compiledScript = ((Compilable) scriptingEngine).compile(this.script);
    } catch (final ScriptException se) {
        // The error message draws ascii art, so it is important it starts on a new line. E.g.:
        // Line 5: for [
        //             ^ Expected '('
        throw new InvalidAutomatonDefinitionException("Script compilation error:\n" + se.getMessage());
    }
    LOG.trace("Script compilation finished");
}

From source file:org.jahia.tools.patches.GroovyPatcher.java

public void initAfterAllServicesAreStarted() throws JahiaInitializationException {
    if (!SettingsBean.getInstance().isProcessingServer()) {
        logger.info("Script watchdog is disabled on a non-processing Jahia server");
        return;/*from   ww w. j  ava 2 s  .  c o m*/
    }

    if (interval > 5000 && SettingsBean.getInstance().isDevelopmentMode()) {
        // in development mode reduce monitoring interval to 5 seconds
        interval = 5000;
    }

    if (interval <= 0) {
        logger.info("The interval for the Groovy patcher is <= 0. Skip starting file watcher.");
        return;
    }

    if (patchesLookup == null) {
        File patchesFolder = getPatchesFolder(servletContext);
        if (patchesFolder != null) {
            String absolutePath = patchesFolder.getAbsolutePath();
            absolutePath = StringUtils.replaceChars(absolutePath, '\\', '/');
            absolutePath = StringUtils.replace(absolutePath, " ", "%20");
            patchesLookup = "file://" + absolutePath + "/**/*.groovy";
        }
    }

    if (StringUtils.isEmpty(patchesLookup)) {
        logger.info("The patches lookup path is not set. Skip starting file watcher.");
        return;
    }

    try {
        if (getEngine() == null) {
            logger.error("The Groovy engine is not evailable. Skip starting file watcher.");
            return;
        }
    } catch (ScriptException e) {
        throw new JahiaInitializationException(e.getMessage(), e);
    }

    // execute scripts right now
    perform();

    // start watchdog for monitoring
    watchdog = new Timer(true);
    watchdog.schedule(new TimerTask() {
        @Override
        public void run() {
            perform();
        }
    }, 0, interval);
}

From source file:org.rhq.enterprise.client.commands.ScriptCommand.java

private boolean executeScriptFile(Reader reader, ClientMain client) {
    try {//from   ww w.j  av a 2 s  .co  m
        Object result = getScriptEngine().eval(reader);
        if (result != null) {
            if (client.isInteractiveMode()) {
                new TabularWriter(client.getPrintWriter()).print(result);
            }
        }
    } catch (ScriptException e) {
        if (client.isInteractiveMode()) {
            client.getPrintWriter().println(e.getMessage());
            client.getPrintWriter().println("^");
        } else {
            throw new CLIScriptException(e);
        }
    }
    return true;
}