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:org.jahia.services.render.scripting.JSR223Script.java

/**
 * Execute the script and return the result as a string
 *
 * @param resource resource to display//from w ww.j a v  a 2s  .c  om
 * @param context
 * @return the rendered resource
 * @throws org.jahia.services.render.RenderException
 */
public String execute(Resource resource, RenderContext context) throws RenderException {
    ScriptEngine scriptEngine = null;

    ClassLoader tccl = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(view.getModule().getChainedClassLoader());

    try {
        scriptEngine = ScriptEngineUtils.getInstance().scriptEngine(view.getFileExtension());

        if (scriptEngine != null) {
            ScriptContext scriptContext = new SimpleScriptContext();
            final Bindings bindings = new SimpleBindings();
            Enumeration<?> attrNamesEnum = context.getRequest().getAttributeNames();
            while (attrNamesEnum.hasMoreElements()) {
                String currentAttributeName = (String) attrNamesEnum.nextElement();
                if (!"".equals(currentAttributeName)) {
                    bindings.put(currentAttributeName, context.getRequest().getAttribute(currentAttributeName));
                }
            }
            bindings.put("params", context.getRequest().getParameterMap());
            Reader scriptContent = null;
            try {
                InputStream scriptInputStream = getViewInputStream();
                if (scriptInputStream != null) {
                    scriptContent = new InputStreamReader(scriptInputStream);
                    scriptContext.setWriter(new StringWriter());
                    scriptContext.setErrorWriter(new StringWriter());
                    // 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);

                    StringWriter writer = (StringWriter) scriptContext.getWriter();
                    return writer.toString().trim();
                } else {
                    throw new RenderException(
                            "Error while retrieving input stream for the resource " + view.getPath());
                }
            } catch (ScriptException e) {
                throw new RenderException("Error while executing script " + view.getPath(), e);
            } catch (IOException e) {
                throw new RenderException(
                        "Error while retrieving input stream for the resource " + view.getPath(), e);
            } finally {
                if (scriptContent != null) {
                    IOUtils.closeQuietly(scriptContent);
                }
            }
        }

    } catch (ScriptException e) {
        logger.error(e.getMessage(), e);
    } finally {
        Thread.currentThread().setContextClassLoader(tccl);
    }

    return null;
}

From source file:org.graphwalker.machines.ExtendedFiniteStateMachine.java

@Override
public boolean walkEdge(Edge edge) {
    boolean hasWalkedEdge = super.walkEdge(edge);
    if (hasWalkedEdge) {
        if (hasAction(edge)) {
            PrintStream ps = System.out;
            System.setOut(Void);

            if (jsEngine != null) {
                try {
                    jsEngine.eval(getAction(edge));
                } catch (ScriptException e) {
                    logger.error("Problem when running: '" + getAction(edge) + "' in Java Script engine");
                    logger.error("EvalError: " + e);
                    logger.error(e.getCause());
                    throw new RuntimeException("Malformed action sequence\n\t" + edge + "\n\tAction sequence: "
                            + edge.getActionsKey() + "\n\tJava Script error message: '" + e.getMessage()
                            + "'\nDetails: " + e.getCause());
                } finally {
                    System.setOut(ps);
                }/*from ww  w . j a v a2  s .co m*/
            } else if (beanShellEngine != null) {
                try {
                    beanShellEngine.eval(getAction(edge));
                } catch (EvalError e) {
                    logger.error("Problem when running: '" + getAction(edge) + "' in BeanShell");
                    logger.error("EvalError: " + e);
                    logger.error(e.getCause());
                    throw new RuntimeException("Malformed action sequence\n\t" + edge + "\n\tAction sequence: "
                            + edge.getActionsKey() + "\n\tBeanShell error message: '" + e.getMessage()
                            + "'\nDetails: " + e.getCause());
                } finally {
                    System.setOut(ps);
                }
            }
        }
    }
    return hasWalkedEdge;
}

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

@Override
public Object execute(final NodeModel node) {
    try {/*from  ww w.j a  va 2s .  c  o m*/
        if (errorsInScript != null && compileTimeStrategy.canUseOldCompiledScript()) {
            throw new ExecuteScriptException(errorsInScript.getMessage(), errorsInScript);
        }
        final ScriptingSecurityManager scriptingSecurityManager = createScriptingSecurityManager();
        final ScriptingPermissions originalScriptingPermissions = new ScriptingPermissions(
                ResourceController.getResourceController().getProperties());
        final FreeplaneSecurityManager securityManager = (FreeplaneSecurityManager) System.getSecurityManager();
        final boolean needToSetFinalSecurityManager = securityManager.needToSetFinalSecurityManager();
        final PrintStream oldOut = System.out;
        try {
            final SimpleScriptContext context = createScriptContext(node);
            if (compilationEnabled && engine instanceof Compilable) {
                compileAndCache((Compilable) engine);
                if (needToSetFinalSecurityManager)
                    securityManager.setFinalSecurityManager(scriptingSecurityManager);
                System.setOut(outStream);
                return compiledScript.eval(context);
            } else {
                if (needToSetFinalSecurityManager)
                    securityManager.setFinalSecurityManager(scriptingSecurityManager);
                System.setOut(outStream);
                return engine.eval(scriptSource.getScript(), context);
            }
        } finally {
            System.setOut(oldOut);
            if (needToSetFinalSecurityManager && securityManager.hasFinalSecurityManager())
                securityManager.removeFinalSecurityManager(scriptingSecurityManager);
            /* restore preferences (and assure that the values are unchanged!). */
            originalScriptingPermissions.restorePermissions();
        }
    } catch (final ScriptException e) {
        handleScriptRuntimeException(e);
        // :fixme: This throw is only reached, if handleScriptRuntimeException
        // does not raise an exception. Should it be here at all?
        // And if: Shouldn't it raise an ExecuteScriptException?
        throw new RuntimeException(e);
    } catch (final Throwable e) {
        if (Controller.getCurrentController().getSelection() != null)
            Controller.getCurrentModeController().getMapController().select(node);
        throw new ExecuteScriptException(e.getMessage(), e);
    }
}

From source file:org.wso2.carbon.identity.application.authentication.framework.config.model.graph.JsGraphBuilder.java

/**
 * Creates the graph with the given Script and step map.
 *
 * @param script the Dynamic authentication script.
 *///from  w  w  w .j  a  v  a 2  s  . co m
public JsGraphBuilder createWith(String script) {

    try {
        currentBuilder.set(this);
        Bindings globalBindings = engine.getBindings(ScriptContext.GLOBAL_SCOPE);
        Bindings engineBindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
        globalBindings.put(FrameworkConstants.JSAttributes.JS_FUNC_EXECUTE_STEP,
                (StepExecutor) this::executeStep);
        globalBindings.put(FrameworkConstants.JSAttributes.JS_FUNC_SEND_ERROR,
                (BiConsumer<String, Map>) this::sendError);
        globalBindings.put(FrameworkConstants.JSAttributes.JS_FUNC_SHOW_PROMPT,
                (PromptExecutor) this::addShowPrompt);
        engineBindings.put("exit", (RestrictedFunction) this::exitFunction);
        engineBindings.put("quit", (RestrictedFunction) this::quitFunction);
        JsFunctionRegistry jsFunctionRegistrar = FrameworkServiceDataHolder.getInstance()
                .getJsFunctionRegistry();
        if (jsFunctionRegistrar != null) {
            Map<String, Object> functionMap = jsFunctionRegistrar
                    .getSubsystemFunctionsMap(JsFunctionRegistry.Subsystem.SEQUENCE_HANDLER);
            functionMap.forEach(globalBindings::put);
        }
        Invocable invocable = (Invocable) engine;
        engine.eval(script);
        invocable.invokeFunction(FrameworkConstants.JSAttributes.JS_FUNC_ON_LOGIN_REQUEST,
                new JsAuthenticationContext(authenticationContext));
        JsGraphBuilderFactory.persistCurrentContext(authenticationContext, engine);
    } catch (ScriptException e) {
        result.setBuildSuccessful(false);
        result.setErrorReason("Error in executing the Javascript. Nested exception is: " + e.getMessage());
        if (log.isDebugEnabled()) {
            log.debug("Error in executing the Javascript.", e);
        }
    } catch (NoSuchMethodException e) {
        result.setBuildSuccessful(false);
        result.setErrorReason("Error in executing the Javascript. "
                + FrameworkConstants.JSAttributes.JS_FUNC_ON_LOGIN_REQUEST + " function is not defined.");
        if (log.isDebugEnabled()) {
            log.debug("Error in executing the Javascript.", e);
        }
    } finally {
        clearCurrentBuilder();
    }
    return this;
}

From source file:org.jwebsocket.plugins.scripting.ScriptingPlugIn.java

/**
 * Loads an script application.//from   w  ww.  j a v a  2 s .  com
 *
 * @param aAppName The application name
 * @param aAppPath The application home path
 * @param aHotLoad
 * @return
 * @throws Exception
 */
private void loadApp(final String aAppName, String aAppPath, boolean aHotLoad) throws Exception {
    // notifying before app reload event here
    BaseScriptApp lScript = mApps.get(aAppName);
    if (null != lScript) {
        lScript.notifyEvent(BaseScriptApp.EVENT_BEFORE_APP_RELOAD, new Object[] { aHotLoad });
        if (!aHotLoad) {
            destroyAppBeans(lScript);
        }
    }

    // parsing app manifest
    File lManifestFile = new File(aAppPath + "/manifest.json");

    // parsing app manifest file
    ObjectMapper lMapper = new ObjectMapper();
    Map<String, Object> lTree = lMapper.readValue(lManifestFile, Map.class);
    Token lManifestJSON = TokenFactory.createToken();
    lManifestJSON.setMap(lTree);

    // getting script language extension
    String lExt = lManifestJSON.getString(Manifest.LANGUAGE_EXT, "js");

    // validating bootstrap file
    final File lBootstrap = new File(aAppPath + "/App." + lExt);

    // support hot app load
    if (aHotLoad && mApps.containsKey(aAppName)) {
        try {
            // loading app
            mApps.get(aAppName).eval(lBootstrap.getPath());
        } catch (ScriptException lEx) {
            mLog.error("Script applicaton '" + aAppName + "' failed to start: " + lEx.getMessage());
            mApps.remove(aAppName);
            throw new ScriptException(lEx.getMessage());
        }
    } else {
        LocalLoader lClassLoader = new LocalLoader((URLClassLoader) ClassLoader.getSystemClassLoader());
        ScriptEngineManager lManager = new ScriptEngineManager(lClassLoader);

        final ScriptEngine lScriptApp;
        if ("js".equals(lExt)) {
            // making "nashorn" the default engine for JavaScript
            if (null != lManager.getEngineByName("nashorn")) {
                lScriptApp = lManager.getEngineByName("nashorn");
            } else {
                lScriptApp = lManager.getEngineByExtension(lExt);
            }
        } else {
            lScriptApp = lManager.getEngineByExtension(lExt);
        }

        // crating the high level script app instance
        if ("js".equals(lExt)) {
            mApps.put(aAppName, new JavaScriptApp(this, aAppName, aAppPath, lScriptApp, lClassLoader));
        } else {
            String lMsg = "The extension '" + lExt + "' is not currently supported!";
            mLog.error(lMsg);
            throw new Exception(lMsg);
        }

        final BaseScriptApp lApp = mApps.get(aAppName);
        // loading application into security sandbox
        Tools.doPrivileged(mSettings.getAppPermissions(aAppName, aAppPath), new PrivilegedAction<Object>() {
            @Override
            public Object run() {
                try {
                    // loading app
                    lApp.eval(lBootstrap.getPath());
                    return null;
                } catch (Exception lEx) {
                    mLog.error("Script applicaton '" + aAppName + "' failed to start: " + lEx.getMessage());
                    mApps.remove(aAppName);
                    throw new RuntimeException(lEx);
                }
            }
        });
    }

    // notifying app loaded event
    mApps.get(aAppName).notifyEvent(BaseScriptApp.EVENT_APP_LOADED, new Object[] { aHotLoad });

    if (mLog.isDebugEnabled()) {
        mLog.debug(aAppName + "(" + lExt + ") application loaded successfully!");
    }
}

From source file:org.apache.tinkerpop.gremlin.groovy.engine.GremlinExecutor.java

private ScriptEngines createScriptEngines() {
    // plugins already on the path - ones static to the classpath
    final List<GremlinPlugin> globalPlugins = new ArrayList<>();
    ServiceLoader.load(GremlinPlugin.class).forEach(globalPlugins::add);

    return new ScriptEngines(se -> {
        // this first part initializes the scriptengines Map
        for (Map.Entry<String, EngineSettings> config : settings.entrySet()) {
            final String language = config.getKey();
            se.reload(language, new HashSet<>(config.getValue().getImports()),
                    new HashSet<>(config.getValue().getStaticImports()), config.getValue().getConfig());
        }/*from w  w  w .  j  av  a 2 s  . c  o  m*/

        // use grabs dependencies and returns plugins to load
        final List<GremlinPlugin> pluginsToLoad = new ArrayList<>(globalPlugins);
        use.forEach(u -> {
            if (u.size() != 3)
                logger.warn(
                        "Could not resolve dependencies for [{}].  Each entry for the 'use' configuration must include [groupId, artifactId, version]",
                        u);
            else {
                logger.info("Getting dependencies for [{}]", u);
                pluginsToLoad.addAll(se.use(u.get(0), u.get(1), u.get(2)));
            }
        });

        // now that all dependencies are in place, the imports can't get messed up if a plugin tries to execute
        // a script (as the script engine appends the import list to the top of all scripts passed to the engine).
        // only enable those plugins that are configured to be enabled.
        se.loadPlugins(pluginsToLoad.stream().filter(plugin -> enabledPlugins.contains(plugin.getName()))
                .collect(Collectors.toList()));

        // initialization script eval can now be performed now that dependencies are present with "use"
        for (Map.Entry<String, EngineSettings> config : settings.entrySet()) {
            final String language = config.getKey();

            // script engine initialization files that fail will only log warnings - not fail server initialization
            final AtomicBoolean hasErrors = new AtomicBoolean(false);
            config.getValue().getScripts().stream().map(File::new).filter(f -> {
                if (!f.exists()) {
                    logger.warn("Could not initialize {} ScriptEngine with {} as file does not exist", language,
                            f);
                    hasErrors.set(true);
                }

                return f.exists();
            }).map(f -> {
                try {
                    return Pair.with(f, Optional.of(new FileReader(f)));
                } catch (IOException ioe) {
                    logger.warn("Could not initialize {} ScriptEngine with {} as file could not be read - {}",
                            language, f, ioe.getMessage());
                    hasErrors.set(true);
                    return Pair.with(f, Optional.<FileReader>empty());
                }
            }).filter(p -> p.getValue1().isPresent()).map(p -> Pair.with(p.getValue0(), p.getValue1().get()))
                    .forEachOrdered(p -> {
                        try {
                            final Bindings bindings = new SimpleBindings();
                            bindings.putAll(globalBindings);

                            // evaluate init scripts with hard reference so as to ensure it doesn't get garbage collected
                            bindings.put(GremlinGroovyScriptEngine.KEY_REFERENCE_TYPE,
                                    GremlinGroovyScriptEngine.REFERENCE_TYPE_HARD);

                            // the returned object should be a Map of initialized global bindings
                            final Object initializedBindings = se.eval(p.getValue1(), bindings, language);
                            if (initializedBindings != null && initializedBindings instanceof Map)
                                globalBindings.putAll((Map) initializedBindings);
                            else
                                logger.warn(
                                        "Initialization script {} did not return a Map - no global bindings specified",
                                        p.getValue0());

                            logger.info("Initialized {} ScriptEngine with {}", language, p.getValue0());
                        } catch (ScriptException sx) {
                            hasErrors.set(true);
                            logger.warn(
                                    "Could not initialize {} ScriptEngine with {} as script could not be evaluated - {}",
                                    language, p.getValue0(), sx.getMessage());
                        }
                    });
        }
    });
}

From source file:ro.uaic.info.nlptools.ggs.engine.core.StateMachine.java

protected void initJsEngine() throws GGSException {
    jsEngine = new ScriptEngineManager().getEngineByName("JavaScript");
    try {//from   ww  w  .  j a  v a2s.co  m
        jsEngine.eval(new InputStreamReader(getClass().getResourceAsStream("jsInitCode.js")));
    } catch (ScriptException e) {
        throw new CoreCriticalException(e);
    }

    StringBuilder sb = new StringBuilder();

    sb.append("var global = {};\n\n");
    sb.append("var grammarClones = [];\n");
    sb.append("\n\n//////////////grammar code\nvar grammar = {}; var network = grammar;");
    try {
        jsEngine.eval(sb.toString());
    } catch (ScriptException e) {
        throw new CoreCriticalException(e);
    }

    sb.delete(0, sb.length());
    sb.append("\ngrammar.jsCode = function(){\n");
    if (grammar.getJsCode() != null && !grammar.getJsCode().trim().isEmpty())
        sb.append(grammar.getJsCode()).append("\n");
    sb.append("};");
    try {
        jsEngine.eval(sb.toString());
    } catch (ScriptException e) {
        throw new GrammarJsException(e.getMessage());
    }

    try {
        jsEngine.eval("grammar.jsCode()");
    } catch (ScriptException e) {
        throw new GrammarJsException(e.getMessage());
    }

    for (Graph graph : grammar.getGraphs().values()) {
        for (GraphNode gn : graph.getGraphNodes().values()) {
            if (gn == null || gn.getJsCode() == null)
                continue;
            if (gn.nodeType == GraphNode.NodeType.Comment)
                continue;

            sb.delete(0, sb.length());
            sb.append("var graph_").append(graph.getId()).append("_node_").append(gn.getIndex())
                    .append("_jsCode = function(token){\n\t").append(gn.getJsCode())
                    .append("\n\treturn true;\n};\n\n");
            try {
                jsEngine.eval(sb.toString());
            } catch (ScriptException e) {
                throw new GraphNodeJsException(e, gn);
            }
        }
    }

    resetJsVariables();
}

From source file:com.ikanow.infinit.e.harvest.enrichment.custom.UnstructuredAnalysisHarvester.java

public void intializeScriptEngine(SourcePojo source, UnstructuredAnalysisConfigPojo uap) {
    if (null == engine) {
        //use the passed in sah one if possible
        if (null != this.get_sahEngine()) {
            engine = this.get_sahEngine();
        } else if (null == factory) //otherwise create our own
        {// w w w.  ja v a  2  s .  co m
            factory = new ScriptEngineManager();
            engine = factory.getEngineByName("JavaScript");
            //grab any json cache and make it available to the engine
        }
        //once engine is created, do some initialization
        if (null != engine) {
            if (null != source) {
                loadLookupCaches(uap.getCaches(), source.getCommunityIds(), source.getOwnerId());
                List<String> scriptFiles = null;
                if (null != uap.getScriptFiles()) {
                    scriptFiles = Arrays.asList(uap.getScriptFiles());
                }
                loadGlobalFunctions(scriptFiles, uap.getScript());
            }
            if (null == parsingScript) {
                parsingScript = JavaScriptUtils.generateParsingScript();
            }
            try {
                securityManager.eval(engine, parsingScript);
            } catch (ScriptException e) { // Just do nothing and log
                e.printStackTrace();
                logger.error("intializeScriptEngine: " + e.getMessage());
            }

        }
    } //end start engine up      

}