use of javax.script.Invocable in project sling by apache.
the class DefaultSlingScript method call.
/**
* @see org.apache.sling.api.scripting.SlingScript#call(org.apache.sling.api.scripting.SlingBindings, java.lang.String, java.lang.Object[])
* @throws ScriptEvaluationException
*/
public Object call(SlingBindings props, String method, Object... args) {
Bindings bindings = null;
Reader reader = null;
boolean disposeScriptHelper = !props.containsKey(SLING);
ResourceResolver oldResolver = null;
try {
bindings = verifySlingBindings(props);
// use final variable for inner class!
final Bindings b = bindings;
// create script context
final ScriptContext ctx = new ScriptContext() {
private Bindings globalScope;
private Bindings engineScope = b;
private Writer writer = (Writer) b.get(OUT);
private Writer errorWriter = new LogWriter((Logger) b.get(LOG));
private Reader reader = (Reader) b.get(READER);
private Bindings slingScope = new SimpleBindings();
/**
* @see javax.script.ScriptContext#setBindings(javax.script.Bindings, int)
*/
public void setBindings(final Bindings bindings, final int scope) {
switch(scope) {
case SlingScriptConstants.SLING_SCOPE:
this.slingScope = bindings;
break;
case 100:
if (bindings == null)
throw new NullPointerException("Bindings for ENGINE scope is null");
this.engineScope = bindings;
break;
case 200:
this.globalScope = bindings;
break;
default:
throw new IllegalArgumentException("Invalid scope");
}
}
/**
* @see javax.script.ScriptContext#getBindings(int)
*/
public Bindings getBindings(final int scope) {
switch(scope) {
case SlingScriptConstants.SLING_SCOPE:
return slingScope;
case 100:
return this.engineScope;
case 200:
return this.globalScope;
}
throw new IllegalArgumentException("Invalid scope");
}
/**
* @see javax.script.ScriptContext#setAttribute(java.lang.String, java.lang.Object, int)
*/
public void setAttribute(final String name, final Object value, final int scope) {
if (name == null)
throw new IllegalArgumentException("Name is null");
final Bindings bindings = getBindings(scope);
if (bindings != null) {
bindings.put(name, value);
}
}
/**
* @see javax.script.ScriptContext#getAttribute(java.lang.String, int)
*/
public Object getAttribute(final String name, final int scope) {
if (name == null)
throw new IllegalArgumentException("Name is null");
final Bindings bindings = getBindings(scope);
if (bindings != null) {
return bindings.get(name);
}
return null;
}
/**
* @see javax.script.ScriptContext#removeAttribute(java.lang.String, int)
*/
public Object removeAttribute(final String name, final int scope) {
if (name == null)
throw new IllegalArgumentException("Name is null");
final Bindings bindings = getBindings(scope);
if (bindings != null) {
return bindings.remove(name);
}
return null;
}
/**
* @see javax.script.ScriptContext#getAttribute(java.lang.String)
*/
public Object getAttribute(String name) {
if (name == null)
throw new IllegalArgumentException("Name is null");
for (final int scope : SCOPES) {
final Bindings bindings = getBindings(scope);
if (bindings != null) {
final Object o = bindings.get(name);
if (o != null) {
return o;
}
}
}
return null;
}
/**
* @see javax.script.ScriptContext#getAttributesScope(java.lang.String)
*/
public int getAttributesScope(String name) {
if (name == null)
throw new IllegalArgumentException("Name is null");
for (final int scope : SCOPES) {
if ((getBindings(scope) != null) && (getBindings(scope).containsKey(name))) {
return scope;
}
}
return -1;
}
/**
* @see javax.script.ScriptContext#getScopes()
*/
public List<Integer> getScopes() {
return Arrays.asList(SCOPES);
}
/**
* @see javax.script.ScriptContext#getWriter()
*/
public Writer getWriter() {
return this.writer;
}
/**
* @see javax.script.ScriptContext#getErrorWriter()
*/
public Writer getErrorWriter() {
return this.errorWriter;
}
/**
* @see javax.script.ScriptContext#setWriter(java.io.Writer)
*/
public void setWriter(Writer writer) {
this.writer = writer;
}
/**
* @see javax.script.ScriptContext#setErrorWriter(java.io.Writer)
*/
public void setErrorWriter(Writer writer) {
this.errorWriter = writer;
}
/**
* @see javax.script.ScriptContext#getReader()
*/
public Reader getReader() {
return this.reader;
}
/**
* @see javax.script.ScriptContext#setReader(java.io.Reader)
*/
public void setReader(Reader reader) {
this.reader = reader;
}
};
// set the current resource resolver if a request is available from the bindings
if (props.getRequest() != null) {
oldResolver = requestResourceResolver.get();
requestResourceResolver.set(props.getRequest().getResourceResolver());
}
// set the script resource resolver as an attribute
ctx.setAttribute(SlingScriptConstants.ATTR_SCRIPT_RESOURCE_RESOLVER, this.scriptResource.getResourceResolver(), SlingScriptConstants.SLING_SCOPE);
reader = getScriptReader();
if (method != null && !(this.scriptEngine instanceof Invocable)) {
reader = getWrapperReader(reader, method, args);
}
// evaluate the script
final Object result;
if (method == null && this.scriptEngine instanceof Compilable) {
CachedScript cachedScript = scriptCache.getScript(scriptName);
if (cachedScript == null) {
ScriptNameAwareReader snReader = new ScriptNameAwareReader(reader, scriptName);
CompiledScript compiledScript = ((Compilable) scriptEngine).compile(snReader);
cachedScript = new CachedScriptImpl(scriptName, compiledScript);
scriptCache.putScript(cachedScript);
LOGGER.debug("Adding {} to the script cache.", scriptName);
} else {
LOGGER.debug("Script {} was already cached.", scriptName);
}
result = cachedScript.getCompiledScript().eval(ctx);
} else {
result = scriptEngine.eval(reader, ctx);
}
// call method - if supplied and script engine supports direct invocation
if (method != null && (this.scriptEngine instanceof Invocable)) {
try {
((Invocable) scriptEngine).invokeFunction(method, Arrays.asList(args).toArray());
} catch (NoSuchMethodException e) {
throw new ScriptEvaluationException(this.scriptName, "Method " + method + " not found in script.", e);
}
}
// optionall flush the output channel
Object flushObject = bindings.get(FLUSH);
if (flushObject instanceof Boolean && (Boolean) flushObject) {
ctx.getWriter().flush();
}
// allways flush the error channel
ctx.getErrorWriter().flush();
return result;
} catch (IOException ioe) {
throw new ScriptEvaluationException(this.scriptName, ioe.getMessage(), ioe);
} catch (ScriptException se) {
Throwable cause = (se.getCause() == null) ? se : se.getCause();
throw new ScriptEvaluationException(this.scriptName, se.getMessage(), cause);
} finally {
if (props.getRequest() != null) {
requestResourceResolver.set(oldResolver);
}
// close the script reader (SLING-380)
if (reader != null) {
try {
reader.close();
} catch (IOException ignore) {
// don't care
}
}
// dispose of the SlingScriptHelper
if (bindings != null && disposeScriptHelper) {
final InternalScriptHelper helper = (InternalScriptHelper) bindings.get(SLING);
if (helper != null) {
helper.cleanup();
}
}
}
}
use of javax.script.Invocable in project cas by apereo.
the class ScriptingUtils method executeGroovyScriptEngine.
/**
* Execute groovy script engine t.
*
* @param <T> the type parameter
* @param scriptFile the script file
* @param args the args
* @param clazz the clazz
* @return the t
*/
public static <T> T executeGroovyScriptEngine(final String scriptFile, final Object[] args, final Class<T> clazz) {
try {
final String engineName = getScriptEngineName(scriptFile);
final ScriptEngine engine = new ScriptEngineManager().getEngineByName(engineName);
if (engine == null || StringUtils.isBlank(engineName)) {
LOGGER.warn("Script engine is not available for [{}]", engineName);
return null;
}
final AbstractResource resourceFrom = ResourceUtils.getResourceFrom(scriptFile);
final File theScriptFile = resourceFrom.getFile();
if (theScriptFile.exists()) {
LOGGER.debug("Created object instance from class [{}]", theScriptFile.getCanonicalPath());
engine.eval(Files.newBufferedReader(theScriptFile.toPath(), StandardCharsets.UTF_8));
final Invocable invocable = (Invocable) engine;
LOGGER.debug("Executing script's run method, with parameters [{}]", args);
final Object result = invocable.invokeFunction("run", args);
LOGGER.debug("Groovy script result is [{}]", result);
if (result != null && !clazz.isAssignableFrom(result.getClass())) {
throw new ClassCastException("Result [" + result + " is of type " + result.getClass() + " when we were expecting " + clazz);
}
return (T) result;
}
LOGGER.warn("[{}] script [{}] does not exist, or cannot be loaded", StringUtils.capitalize(engineName), scriptFile);
} catch (final Exception e) {
LOGGER.error(e.getMessage(), e);
}
return null;
}
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);
}
}
}
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();
}
use of javax.script.Invocable in project wso2-synapse by wso2.
the class ScriptMediator method mediateWithExternalScript.
/**
* Mediation implementation when the script to be executed should be loaded from the registry
*
* @param synCtx the message context
* @return script result
* @throws ScriptException For any errors , when compile, run the script
* @throws NoSuchMethodException If the function is not defined in the script
*/
private Object mediateWithExternalScript(MessageContext synCtx) throws ScriptException, NoSuchMethodException {
ScriptEngineWrapper sew = null;
Object obj;
try {
sew = prepareExternalScript(synCtx);
XMLHelper helper;
if (language.equalsIgnoreCase(JAVA_SCRIPT) || language.equals(NASHORN_JAVA_SCRIPT)) {
helper = xmlHelper;
} else {
helper = XMLHelper.getArgHelper(sew.getEngine());
}
ScriptMessageContext scriptMC;
scriptMC = getScriptMessageContext(synCtx, helper);
processJSONPayload(synCtx, scriptMC);
Invocable invocableScript = (Invocable) sew.getEngine();
obj = invocableScript.invokeFunction(function, new Object[] { scriptMC });
} finally {
if (sew != null) {
// return engine to front of queue or drop if queue is full (i.e. if getNewScriptEngine() spawns a new engine)
pool.offer(sew);
}
}
return obj;
}
Aggregations