Search in sources :

Example 1 with Invocable

use of javax.script.Invocable in project cas by apereo.

the class ScriptedRegisteredServiceAttributeReleasePolicy method getAttributesInternal.

@Override
protected Map<String, Object> getAttributesInternal(final Map<String, Object> attributes, final RegisteredService service) {
    try {
        String engineName = null;
        if (this.scriptFile.endsWith(".py")) {
            engineName = "python";
        } else if (this.scriptFile.endsWith(".js")) {
            engineName = "js";
        } else if (this.scriptFile.endsWith(".groovy")) {
            engineName = "groovy";
        }
        final ScriptEngine engine = new ScriptEngineManager().getEngineByName("python");
        if (engine == null || StringUtils.isBlank(engineName)) {
            LOGGER.warn("Script engine is not available for [{}]", engineName);
        } else {
            final File theScriptFile = ResourceUtils.getResourceFrom(this.scriptFile).getFile();
            if (theScriptFile.exists()) {
                LOGGER.debug("Created python object instance from class [{}]", theScriptFile.getCanonicalPath());
                final Object[] args = { attributes, LOGGER };
                LOGGER.debug("Executing python script's run method, with parameters [{}]", args);
                engine.eval(new FileReader(theScriptFile));
                final Invocable invocable = (Invocable) engine;
                final Map<String, Object> personAttributesMap = (Map<String, Object>) invocable.invokeFunction("run", args);
                LOGGER.debug("Final set of attributes determined by the script are [{}]", personAttributesMap);
                return personAttributesMap;
            }
            LOGGER.warn("Python script [{}] does not exist, or cannot be loaded", scriptFile);
        }
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
    }
    return new HashMap<>();
}
Also used : Invocable(javax.script.Invocable) HashMap(java.util.HashMap) ScriptEngineManager(javax.script.ScriptEngineManager) FileReader(java.io.FileReader) File(java.io.File) Map(java.util.Map) HashMap(java.util.HashMap) ScriptEngine(javax.script.ScriptEngine)

Example 2 with Invocable

use of javax.script.Invocable in project lucene-solr by apache.

the class ScriptTransformer method initEngine.

private void initEngine(Context context) {
    String scriptText = context.getScript();
    String scriptLang = context.getScriptLanguage();
    if (scriptText == null) {
        throw new DataImportHandlerException(SEVERE, "<script> tag is not present under <dataConfig>");
    }
    ScriptEngineManager scriptEngineMgr = new ScriptEngineManager();
    ScriptEngine scriptEngine = scriptEngineMgr.getEngineByName(scriptLang);
    if (scriptEngine == null) {
        throw new DataImportHandlerException(SEVERE, "Cannot load Script Engine for language: " + scriptLang);
    }
    if (scriptEngine instanceof Invocable) {
        engine = (Invocable) scriptEngine;
    } else {
        throw new DataImportHandlerException(SEVERE, "The installed ScriptEngine for: " + scriptLang + " does not implement Invocable.  Class is " + scriptEngine.getClass().getName());
    }
    try {
        scriptEngine.eval(scriptText);
    } catch (ScriptException e) {
        wrapAndThrow(SEVERE, e, "'eval' failed with language: " + scriptLang + " and script: \n" + scriptText);
    }
}
Also used : Invocable(javax.script.Invocable) ScriptException(javax.script.ScriptException) ScriptEngineManager(javax.script.ScriptEngineManager) ScriptEngine(javax.script.ScriptEngine)

Example 3 with Invocable

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

the class ScriptedLookupService method reloadScript.

/**
 * Reloads the script RecordReaderFactory. 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 LookupService from the script (if it exists)
            final Object obj = scriptEngine.get("lookupService");
            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("Scripted LookupService does not contain a setLogger method.");
                    }
                }
                // record the processor for use later
                final LookupService<Object> scriptedLookupService = invocable.getInterface(obj, LookupService.class);
                lookupService.set(scriptedLookupService);
                if (scriptedLookupService != null) {
                    try {
                        scriptedLookupService.initialize(new ControllerServiceInitializationContext() {

                            @Override
                            public String getIdentifier() {
                                return ScriptedLookupService.this.getIdentifier();
                            }

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

                            @Override
                            public StateManager getStateManager() {
                                return ScriptedLookupService.this.getStateManager();
                            }

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

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

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

                            @Override
                            public File getKerberosConfigurationFile() {
                                return ScriptedLookupService.this.kerberosConfigFile;
                            }
                        });
                    } catch (final Exception e) {
                        logger.error("Unable to initialize scripted LookupService: " + e.getLocalizedMessage(), e);
                        throw new ProcessException(e);
                    }
                }
            } else {
                throw new ScriptException("No LookupService was defined by the script.");
            }
        } else {
            throw new ScriptException("Script engine is not Invocable, cannot be used for ScriptedLookupService");
        }
    } 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("ScriptedLookupServiceValidation").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 : ControllerServiceInitializationContext(org.apache.nifi.controller.ControllerServiceInitializationContext) ScriptEngineConfigurator(org.apache.nifi.processors.script.ScriptEngineConfigurator) ValidationResult(org.apache.nifi.components.ValidationResult) ComponentLog(org.apache.nifi.logging.ComponentLog) LookupFailureException(org.apache.nifi.lookup.LookupFailureException) ProcessException(org.apache.nifi.processor.exception.ProcessException) ScriptException(javax.script.ScriptException) Invocable(javax.script.Invocable) ScriptException(javax.script.ScriptException) ProcessException(org.apache.nifi.processor.exception.ProcessException) StateManager(org.apache.nifi.components.state.StateManager) File(java.io.File) ControllerServiceLookup(org.apache.nifi.controller.ControllerServiceLookup) HashSet(java.util.HashSet)

Example 4 with Invocable

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

the class InvokeScriptedProcessor method reloadScript.

/**
 * 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
 */
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();
}
Also used : AbstractSessionFactoryProcessor(org.apache.nifi.processor.AbstractSessionFactoryProcessor) Processor(org.apache.nifi.processor.Processor) NodeTypeProvider(org.apache.nifi.controller.NodeTypeProvider) ValidationResult(org.apache.nifi.components.ValidationResult) ComponentLog(org.apache.nifi.logging.ComponentLog) ProcessorInitializationContext(org.apache.nifi.processor.ProcessorInitializationContext) ProcessException(org.apache.nifi.processor.exception.ProcessException) ScriptException(javax.script.ScriptException) Invocable(javax.script.Invocable) ScriptException(javax.script.ScriptException) ProcessException(org.apache.nifi.processor.exception.ProcessException) File(java.io.File) ControllerServiceLookup(org.apache.nifi.controller.ControllerServiceLookup) HashSet(java.util.HashSet)

Example 5 with Invocable

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

the class ScriptedReader method reloadScript.

/**
 * Reloads the script RecordReaderFactory. This must be called within the lock.
 *
 * @param scriptBody An input stream associated with the script content
 * @return Whether the script was successfully reloaded
 */
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("reader");
            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 RecordReaderFactory 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 RecordReaderFactory does not contain a setConfigurationContext method.");
                        }
                    }
                }
                // record the processor for use later
                final RecordReaderFactory scriptedReader = invocable.getInterface(obj, RecordReaderFactory.class);
                recordFactory.set(scriptedReader);
            } else {
                throw new ScriptException("No RecordReader 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) MalformedRecordException(org.apache.nifi.serialization.MalformedRecordException) IOException(java.io.IOException) SchemaNotFoundException(org.apache.nifi.schema.access.SchemaNotFoundException) UndeclaredThrowableException(java.lang.reflect.UndeclaredThrowableException) ScriptException(javax.script.ScriptException) RecordReaderFactory(org.apache.nifi.serialization.RecordReaderFactory) Invocable(javax.script.Invocable) ScriptException(javax.script.ScriptException) HashSet(java.util.HashSet)

Aggregations

Invocable (javax.script.Invocable)68 ScriptException (javax.script.ScriptException)41 ScriptEngine (javax.script.ScriptEngine)30 ScriptEngineManager (javax.script.ScriptEngineManager)22 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)5 CompiledScript (javax.script.CompiledScript)5 BufferedReader (java.io.BufferedReader)4 HashSet (java.util.HashSet)4 Map (java.util.Map)4 Bindings (javax.script.Bindings)4 ScriptContext (javax.script.ScriptContext)4 Writer (java.io.Writer)3 SimpleScriptContext (javax.script.SimpleScriptContext)3 ValidationResult (org.apache.nifi.components.ValidationResult)3