Example usage for javax.script ScriptException ScriptException

List of usage examples for javax.script ScriptException ScriptException

Introduction

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

Prototype

public ScriptException(Exception e) 

Source Link

Document

Creates a ScriptException wrapping an Exception thrown by an underlying interpreter.

Usage

From source file:org.wso2.carbon.apimgt.hostobjects.oidc.OIDCRelyingPartyObject.java

public static boolean jsFunction_isSessionAuthenticated(Context cx, Scriptable thisObj, Object[] args,
        Function funObj) throws ScriptException {
    int argLength = args.length;
    if (argLength != 1 || !(args[0] instanceof String)) {
        throw new ScriptException("Invalid argument. Session id is missing.");
    }/*from w w w .ja va  2 s. co m*/
    OIDCRelyingPartyObject relyingPartyObject = (OIDCRelyingPartyObject) thisObj;

    return relyingPartyObject.isSessionIdExists((String) args[0]);

}

From source file:org.wso2.carbon.apimgt.hostobjects.oidc.OIDCRelyingPartyObject.java

/**
 * Invalidate current browser authenticated session based on session id.
 * Session will be invalidated after user log out request get succeeded.
 *
 * @param cx/*  w ww  . ja v a 2s .  c o  m*/
 * @param thisObj
 * @param args
 * @param funObj
 * @throws Exception
 */
public static void jsFunction_invalidateSessionBySessionId(Context cx, Scriptable thisObj, Object[] args,
        Function funObj) throws Exception {
    int argLength = args.length;
    if (argLength != 1 || !(args[0] instanceof String)) {
        throw new ScriptException("Invalid argument. Session id is missing.");
    }
    OIDCRelyingPartyObject relyingPartyObject = (OIDCRelyingPartyObject) thisObj;

    relyingPartyObject.invalidateSessionBySessionId((String) args[0]);
    // this is to invalidate relying party object after user log out. To release memory allocations.
    invalidateRelyingPartyObject("API_STORE");

}

From source file:org.wso2.carbon.apimgt.hostobjects.oidc.OIDCRelyingPartyObject.java

/**
 * Set OIDC Configuration key,values/* w w  w.  j  ava 2 s. c o  m*/
 *
 * @param cx
 * @param thisObj
 * @param args
 * @param funObj
 * @throws ScriptException
 */
public static void jsFunction_setProperty(Context cx, Scriptable thisObj, Object[] args, Function funObj)
        throws ScriptException {
    int argLength = args.length;
    if (argLength != 2 || !(args[0] instanceof String) || !(args[1] instanceof String)) {
        throw new ScriptException("Invalid arguments when setting OIDC configuration values.");
    }
    if (log.isDebugEnabled()) {
        log.debug("OIDC key values pair properties that set on relying party object is " + args[0] + " "
                + args[1]);
    }
    OIDCRelyingPartyObject relyingPartyObject = (OIDCRelyingPartyObject) thisObj;
    relyingPartyObject.setOIDCProperty((String) args[0], (String) args[1]);

}

From source file:de.axelfaust.alfresco.nashorn.repo.processor.NashornScriptProcessor.java

protected Object executeScriptFromResource(final URL resource) throws ScriptException {
    this.initialisationStateLock.readLock().lock();
    try {//from   w  ww . j  a  v  a 2  s.com
        LOGGER.debug("Executing script from resource {}", resource);
        try (Reader reader = new URLReader(resource)) {
            this.engine.getContext().setAttribute(ScriptEngine.FILENAME, resource.toString(),
                    ScriptContext.ENGINE_SCOPE);
            return this.engine.eval(reader);
        } catch (final IOException e) {
            throw new ScriptException(e);
        } finally {
            LOGGER.trace("Execution of script from resource {} completed", resource);
        }
    } finally {
        this.initialisationStateLock.readLock().unlock();
    }
}

From source file:org.apache.jmeter.util.JSR223TestElement.java

protected ScriptEngine getScriptEngine() throws ScriptException {
    final String lang = getScriptLanguage();

    ScriptEngine scriptEngine = getInstance().getEngineByName(lang);
    if (scriptEngine == null) {
        throw new ScriptException("Cannot find engine named: '" + lang
                + "', ensure you set language field in JSR223 Test Element:" + getName());
    }//from  ww  w  .  j  a  v  a 2 s  .  co  m

    return scriptEngine;
}

From source file:org.apache.jmeter.util.JSR223TestElement.java

/**
 * 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/*from   www .  j a  va 2  s  .  c o  m*/
 * @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
            && !(scriptEngine.getClass().getName().equals("bsh.engine.BshScriptEngine")); // $NON-NLS-1$
    if (!StringUtils.isEmpty(getFilename())) {
        if (scriptFile.exists() && scriptFile.canRead()) {
            BufferedReader fileReader = null;
            try {
                if (supportsCompilable) {
                    String cacheKey = getScriptLanguage() + "#" + // $NON-NLS-1$
                            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 ?
                                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 ?
                    fileReader = new BufferedReader(new FileReader(scriptFile), (int) scriptFile.length());
                    return scriptEngine.eval(fileReader, bindings);
                }
            } finally {
                IOUtils.closeQuietly(fileReader);
            }
        } 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());
    }
}

From source file:org.apache.nifi.processors.script.InvokeScriptedProcessor.java

/**
 * Reloads the script Processor. This must be called within the lock.
 *
 * @param scriptBody An input stream associated with the script content
 * @return Whether the script was successfully reloaded
 *///  w  w w . j a  v a  2 s .  c o m
private boolean reloadScript(final String scriptBody) {
    // note we are starting here with a fresh listing of validation
    // results since we are (re)loading a new/updated script. any
    // existing validation results are not relevant
    final Collection<ValidationResult> results = new HashSet<>();

    try {
        // get the engine and ensure its invocable
        if (scriptEngine instanceof Invocable) {
            final Invocable invocable = (Invocable) scriptEngine;

            // Find a custom configurator and invoke their eval() method
            ScriptEngineConfigurator configurator = scriptingComponentHelper.scriptEngineConfiguratorMap
                    .get(scriptingComponentHelper.getScriptEngineName().toLowerCase());
            if (configurator != null) {
                configurator.eval(scriptEngine, scriptBody, scriptingComponentHelper.getModules());
            } else {
                // evaluate the script
                scriptEngine.eval(scriptBody);
            }

            // get configured processor from the script (if it exists)
            final Object obj = scriptEngine.get("processor");
            if (obj != null) {
                final ComponentLog logger = getLogger();

                try {
                    // set the logger if the processor wants it
                    invocable.invokeMethod(obj, "setLogger", logger);
                } catch (final NoSuchMethodException nsme) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Configured script Processor does not contain a setLogger method.");
                    }
                }

                // record the processor for use later
                final Processor scriptProcessor = invocable.getInterface(obj, Processor.class);
                processor.set(scriptProcessor);

                if (scriptProcessor != null) {
                    try {
                        scriptProcessor.initialize(new ProcessorInitializationContext() {
                            @Override
                            public String getIdentifier() {
                                return InvokeScriptedProcessor.this.getIdentifier();
                            }

                            @Override
                            public ComponentLog getLogger() {
                                return logger;
                            }

                            @Override
                            public ControllerServiceLookup getControllerServiceLookup() {
                                return InvokeScriptedProcessor.super.getControllerServiceLookup();
                            }

                            @Override
                            public NodeTypeProvider getNodeTypeProvider() {
                                return InvokeScriptedProcessor.super.getNodeTypeProvider();
                            }

                            @Override
                            public String getKerberosServicePrincipal() {
                                return InvokeScriptedProcessor.this.kerberosServicePrincipal;
                            }

                            @Override
                            public File getKerberosServiceKeytab() {
                                return InvokeScriptedProcessor.this.kerberosServiceKeytab;
                            }

                            @Override
                            public File getKerberosConfigurationFile() {
                                return InvokeScriptedProcessor.this.kerberosConfigFile;
                            }
                        });
                    } catch (final Exception e) {
                        logger.error("Unable to initialize scripted Processor: " + e.getLocalizedMessage(), e);
                        throw new ProcessException(e);
                    }
                }
            } else {
                throw new ScriptException("No processor was defined by the script.");
            }
        }

    } catch (final Exception ex) {
        final ComponentLog logger = getLogger();
        final String message = "Unable to load script: " + ex.getLocalizedMessage();

        logger.error(message, ex);
        results.add(new ValidationResult.Builder().subject("ScriptValidation").valid(false)
                .explanation("Unable to load script due to " + ex.getLocalizedMessage())
                .input(scriptingComponentHelper.getScriptPath()).build());
    }

    // store the updated validation results
    validationResults.set(results);

    // return whether there was any issues loading the configured script
    return results.isEmpty();
}

From source file:org.apache.sling.scripting.javascript.internal.RhinoJavaScriptEngine.java

public CompiledScript compile(Reader scriptReader) throws ScriptException {
    final String scriptName = getScriptName(scriptReader);
    CachedScript cachedScript = scriptCache.getScript(scriptName);
    if (cachedScript != null) {
        LOGGER.debug("Detected cached script for {}.", scriptName);
        return cachedScript.getCompiledScript();
    } else {/*from  ww w.j av a2 s.c o  m*/
        scriptReader = wrapReaderIfEspScript(scriptReader, scriptName);
        try {
            final Context rhinoContext = Context.enter();
            rhinoContext.setOptimizationLevel(optimizationLevel());

            if (!ScriptRuntime.hasTopCall(rhinoContext)) {
                // setup the context for use
                WrapFactory wrapFactory = ((RhinoJavaScriptEngineFactory) getFactory()).getWrapFactory();
                rhinoContext.setWrapFactory(wrapFactory);
            }

            final int lineNumber = 1;
            final Object securityDomain = null;

            final Script script = rhinoContext.compileReader(scriptReader, scriptName, lineNumber,
                    securityDomain);
            final SlingCompiledScript slingCompiledScript = new SlingCompiledScript(script, this);
            cachedScript = new CachedScript() {
                @Override
                public String getScriptPath() {
                    return scriptName;
                }

                @Override
                public CompiledScript getCompiledScript() {
                    return slingCompiledScript;
                }
            };
            // SLING-4935 avoid caching scripts for which we cannot determine a name
            if (!scriptName.equals(NO_SCRIPT_NAME)) {
                scriptCache.putScript(cachedScript);
            }
            LOGGER.debug("Added {} script to Script Cache.", scriptName);
            return slingCompiledScript;
        } catch (IOException e) {
            final ScriptException se = new ScriptException(
                    "Failure running script " + scriptName + ": " + e.getMessage());
            se.initCause(e);
            throw se;
        } finally {
            Context.exit();
        }
    }
}

From source file:org.apache.synapse.mediators.bsf.CommonScriptMessageContext.java

/**
 * Saves the payload of this message context as a JSON payload.
 *
 * @param jsonPayload Javascript native object to be set as the message body
 * @throws ScriptException in case of creating a JSON object out of
 *                         the javascript native object.
 *//*from   w  w  w  .ja v a  2s  . co m*/
public void setPayloadJSON0(Object jsonPayload) throws ScriptException {
    org.apache.axis2.context.MessageContext messageContext;
    messageContext = ((Axis2MessageContext) mc).getAxis2MessageContext();

    String jsonString;
    if (jsonPayload instanceof String) {
        jsonString = (String) jsonPayload;
    } else {
        jsonString = serializeJSON(jsonPayload);
    }
    try {
        JsonUtil.getNewJsonPayload(messageContext, jsonString, true, true);
    } catch (AxisFault axisFault) {
        throw new ScriptException(axisFault);
    }
    Object jsonObject = scriptEngine.eval('(' + jsonString + ')');
    setJsonObject(mc, jsonObject);
}

From source file:org.apache.synapse.mediators.bsf.CommonScriptMessageContext.java

@Override
public void setPayloadJSON(Object jsonPayload) throws ScriptException {
    org.apache.axis2.context.MessageContext messageContext;
    messageContext = ((Axis2MessageContext) mc).getAxis2MessageContext();

    byte[] json = { '{', '}' };
    if (jsonPayload instanceof String) {
        json = jsonPayload.toString().getBytes();
    } else if (jsonPayload != null) {
        try {//from w w  w. j  ava  2s  .c o m
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            serializeJson(jsonPayload, out);
            json = out.toByteArray();
        } catch (IOException e) {
            logger.error("#setPayloadJSON. Could not retrieve bytes from JSON object.", e);
        }
    }
    // save this JSON object as the new payload.
    try {
        JsonUtil.getNewJsonPayload(messageContext, json, 0, json.length, true, true);
    } catch (AxisFault axisFault) {
        throw new ScriptException(axisFault);
    }
    //JsonUtil.setContentType(messageContext);
    Object jsonObject = scriptEngine.eval(JsonUtil.newJavaScriptSourceReader(messageContext));
    setJsonObject(mc, jsonObject);
}