Search in sources :

Example 46 with Invocable

use of javax.script.Invocable in project nifi by apache.

the class ScriptedLookupService method onEnabled.

@Override
@OnEnabled
public void onEnabled(final ConfigurationContext context) {
    synchronized (scriptingComponentHelper.isInitialized) {
        if (!scriptingComponentHelper.isInitialized.get()) {
            scriptingComponentHelper.createResources();
        }
    }
    super.onEnabled(context);
    // Call an non-interface method onEnabled(context), to allow a scripted LookupService the chance to set up as necessary
    final Invocable invocable = (Invocable) scriptEngine;
    if (configurationContext != null) {
        try {
            // Get the actual object from the script engine, versus the proxy stored in lookupService. The object may have additional methods,
            // where lookupService is a proxied interface
            final Object obj = scriptEngine.get("lookupService");
            if (obj != null) {
                try {
                    invocable.invokeMethod(obj, "onEnabled", context);
                } catch (final NoSuchMethodException nsme) {
                    if (getLogger().isDebugEnabled()) {
                        getLogger().debug("Configured script LookupService does not contain an onEnabled() method.");
                    }
                }
            } else {
                throw new ScriptException("No LookupService was defined by the script.");
            }
        } catch (ScriptException se) {
            throw new ProcessException("Error executing onEnabled(context) method", se);
        }
    }
}
Also used : Invocable(javax.script.Invocable) ScriptException(javax.script.ScriptException) ProcessException(org.apache.nifi.processor.exception.ProcessException) OnEnabled(org.apache.nifi.annotation.lifecycle.OnEnabled)

Example 47 with Invocable

use of javax.script.Invocable in project nifi by apache.

the class ScriptedRecordSetWriter method reloadScript.

/**
 * Reloads the script RecordSetWriterFactory. This must be called within the lock.
 *
 * @param scriptBody An input stream associated with the script content
 * @return Whether the script was successfully reloaded
 */
@Override
protected 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("writer");
            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 RecordSetWriterFactory does not contain a setLogger method.");
                    }
                }
                if (configurationContext != null) {
                    try {
                        // set the logger if the processor wants it
                        invocable.invokeMethod(obj, "setConfigurationContext", configurationContext);
                    } catch (final NoSuchMethodException nsme) {
                        if (logger.isDebugEnabled()) {
                            logger.debug("Configured script RecordSetWriterFactory does not contain a setConfigurationContext method.");
                        }
                    }
                }
                // record the processor for use later
                final RecordSetWriterFactory scriptedWriter = invocable.getInterface(obj, RecordSetWriterFactory.class);
                recordFactory.set(scriptedWriter);
            } else {
                throw new ScriptException("No RecordSetWriterFactory 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();
}
Also used : ScriptEngineConfigurator(org.apache.nifi.processors.script.ScriptEngineConfigurator) ValidationResult(org.apache.nifi.components.ValidationResult) ComponentLog(org.apache.nifi.logging.ComponentLog) IOException(java.io.IOException) SchemaNotFoundException(org.apache.nifi.schema.access.SchemaNotFoundException) UndeclaredThrowableException(java.lang.reflect.UndeclaredThrowableException) ScriptException(javax.script.ScriptException) Invocable(javax.script.Invocable) ScriptException(javax.script.ScriptException) RecordSetWriterFactory(org.apache.nifi.serialization.RecordSetWriterFactory) HashSet(java.util.HashSet)

Example 48 with Invocable

use of javax.script.Invocable in project vorto by eclipse.

the class JavascriptEvalFunction method invoke.

@Override
@SuppressWarnings({ "rawtypes" })
public Object invoke(ExpressionContext context, Object[] parameters) {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("JavaScript");
    try {
        engine.eval(functionBody);
    } catch (ScriptException e) {
        throw new JXPathException("Problem evaluating " + functionName, e);
    }
    Invocable inv = (Invocable) engine;
    try {
        Object[] args;
        int pi = 0;
        Class[] types = toTypes(parameters);
        if (types.length >= 1 && ExpressionContext.class.isAssignableFrom(types[0])) {
            pi = 1;
        }
        args = new Object[parameters.length + pi];
        if (pi == 1) {
            args[0] = context;
        }
        for (int i = 0; i < parameters.length; i++) {
            args[i + pi] = TypeUtils.convert(parameters[i], types[i + pi]);
        }
        return inv.invokeFunction(functionName, unwrap(args));
    } catch (Throwable ex) {
        throw new JXPathInvalidAccessException("Cannot invoke " + functionName, ex);
    }
}
Also used : ScriptEngineManager(javax.script.ScriptEngineManager) JXPathInvalidAccessException(org.apache.commons.jxpath.JXPathInvalidAccessException) ScriptEngine(javax.script.ScriptEngine) ScriptException(javax.script.ScriptException) Invocable(javax.script.Invocable) ExpressionContext(org.apache.commons.jxpath.ExpressionContext) JXPathException(org.apache.commons.jxpath.JXPathException)

Example 49 with Invocable

use of javax.script.Invocable in project mamute by caelum.

the class MarkDown method parse.

public static synchronized String parse(String content) {
    if (content == null || content.isEmpty())
        return null;
    try {
        Invocable invocable = (Invocable) js;
        Object result = invocable.invokeFunction("marked", content);
        return result.toString();
    } catch (ScriptException | NoSuchMethodException e) {
        throw new RuntimeException(e);
    }
}
Also used : Invocable(javax.script.Invocable) ScriptException(javax.script.ScriptException)

Example 50 with Invocable

use of javax.script.Invocable in project HeavenMS by ronancpl.

the class NPCScriptManager method action.

public void action(MapleClient c, byte mode, byte type, int selection) {
    Invocable iv = scripts.get(c);
    if (iv != null) {
        try {
            c.setClickedNPC();
            iv.invokeFunction("action", mode, type, selection);
        } catch (ScriptException | NoSuchMethodException t) {
            if (getCM(c) != null) {
                FilePrinter.printError(FilePrinter.NPC + getCM(c).getNpc() + ".txt", t);
            }
            dispose(c);
        }
    }
}
Also used : Invocable(javax.script.Invocable) ScriptException(javax.script.ScriptException)

Aggregations

Invocable (javax.script.Invocable)74 ScriptException (javax.script.ScriptException)45 ScriptEngine (javax.script.ScriptEngine)34 ScriptEngineManager (javax.script.ScriptEngineManager)24 IOException (java.io.IOException)19 File (java.io.File)10 InputStreamReader (java.io.InputStreamReader)10 UndeclaredThrowableException (java.lang.reflect.UndeclaredThrowableException)10 FileReader (java.io.FileReader)9 Reader (java.io.Reader)9 Compilable (javax.script.Compilable)8 CompiledScript (javax.script.CompiledScript)8 Bindings (javax.script.Bindings)7 Map (java.util.Map)5 BufferedReader (java.io.BufferedReader)4 HashSet (java.util.HashSet)4 Test (org.junit.Test)4 Writer (java.io.Writer)3 HashMap (java.util.HashMap)3 ScriptContext (javax.script.ScriptContext)3