use of javax.script.ScriptException in project groovy-core by groovy.
the class GroovyScriptEngineImpl method eval.
// package-privates
Object eval(Class scriptClass, final ScriptContext ctx) throws ScriptException {
// Only initialize once.
if (null == ctx.getAttribute("context", ScriptContext.ENGINE_SCOPE)) {
// add context to bindings
ctx.setAttribute("context", ctx, ScriptContext.ENGINE_SCOPE);
// direct output to ctx.getWriter
// If we're wrapping with a PrintWriter here,
// enable autoFlush because otherwise it might not get done!
final Writer writer = ctx.getWriter();
ctx.setAttribute("out", (writer instanceof PrintWriter) ? writer : new PrintWriter(writer, true), ScriptContext.ENGINE_SCOPE);
// Not going to do this after all (at least for now).
// Scripts can use context.{reader, writer, errorWriter}.
// That is a modern version of System.{in, out, err} or Console.{reader, writer}().
//
// // New I/O names consistent with ScriptContext and java.io.Console.
//
// ctx.setAttribute("writer", writer, ScriptContext.ENGINE_SCOPE);
//
// // Direct errors to ctx.getErrorWriter
// final Writer errorWriter = ctx.getErrorWriter();
// ctx.setAttribute("errorWriter", (errorWriter instanceof PrintWriter) ?
// errorWriter :
// new PrintWriter(errorWriter),
// ScriptContext.ENGINE_SCOPE);
//
// // Get input from ctx.getReader
// // We don't wrap with BufferedReader here because we expect that if
// // the host wants that they do it. Either way Groovy scripts will
// // always have readLine because the GDK supplies it for Reader.
// ctx.setAttribute("reader", ctx.getReader(), ScriptContext.ENGINE_SCOPE);
}
// Fix for GROOVY-3669: Can't use several times the same JSR-223 ScriptContext for differents groovy script
if (ctx.getWriter() != null) {
ctx.setAttribute("out", new PrintWriter(ctx.getWriter(), true), ScriptContext.ENGINE_SCOPE);
}
/*
* We use the following Binding instance so that global variable lookup
* will be done in the current ScriptContext instance.
*/
Binding binding = new Binding(ctx.getBindings(ScriptContext.ENGINE_SCOPE)) {
@Override
public Object getVariable(String name) {
synchronized (ctx) {
int scope = ctx.getAttributesScope(name);
if (scope != -1) {
return ctx.getAttribute(name, scope);
}
}
throw new MissingPropertyException(name, getClass());
}
@Override
public void setVariable(String name, Object value) {
synchronized (ctx) {
int scope = ctx.getAttributesScope(name);
if (scope == -1) {
scope = ScriptContext.ENGINE_SCOPE;
}
ctx.setAttribute(name, value, scope);
}
}
};
try {
// then simply return that class
if (!Script.class.isAssignableFrom(scriptClass)) {
return scriptClass;
} else {
// it's a script
Script scriptObject = InvokerHelper.createScript(scriptClass, binding);
// save all current closures into global closures map
Method[] methods = scriptClass.getMethods();
for (Method m : methods) {
String name = m.getName();
globalClosures.put(name, new MethodClosure(scriptObject, name));
}
MetaClass oldMetaClass = scriptObject.getMetaClass();
/*
* We override the MetaClass of this script object so that we can
* forward calls to global closures (of previous or future "eval" calls)
* This gives the illusion of working on the same "global" scope.
*/
scriptObject.setMetaClass(new DelegatingMetaClass(oldMetaClass) {
@Override
public Object invokeMethod(Object object, String name, Object args) {
if (args == null) {
return invokeMethod(object, name, MetaClassHelper.EMPTY_ARRAY);
}
if (args instanceof Tuple) {
return invokeMethod(object, name, ((Tuple) args).toArray());
}
if (args instanceof Object[]) {
return invokeMethod(object, name, (Object[]) args);
} else {
return invokeMethod(object, name, new Object[] { args });
}
}
@Override
public Object invokeMethod(Object object, String name, Object[] args) {
try {
return super.invokeMethod(object, name, args);
} catch (MissingMethodException mme) {
return callGlobal(name, args, ctx);
}
}
@Override
public Object invokeStaticMethod(Object object, String name, Object[] args) {
try {
return super.invokeStaticMethod(object, name, args);
} catch (MissingMethodException mme) {
return callGlobal(name, args, ctx);
}
}
});
return scriptObject.run();
}
} catch (Exception e) {
throw new ScriptException(e);
} finally {
// Fix for GROOVY-3669: Can't use several times the same JSR-223 ScriptContext for different groovy script
// Groovy's scripting engine implementation adds those two variables in the binding
// but should clean up afterwards
ctx.removeAttribute("context", ScriptContext.ENGINE_SCOPE);
ctx.removeAttribute("out", ScriptContext.ENGINE_SCOPE);
}
}
use of javax.script.ScriptException in project openhab1-addons by openhab.
the class EBusConfigurationProvider method transformDataTypes.
/**
* @param configurationEntry
*/
protected void transformDataTypes(TelegramConfiguration configurationEntry) {
// Use filter property if set
if (StringUtils.isNotEmpty(configurationEntry.getFilter())) {
String filter = configurationEntry.getFilter();
filter = P_PLACEHOLDER.matcher(filter).replaceAll("[0-9A-Z]{2}");
logger.trace("Compile RegEx filter: {}", filter);
configurationEntry.setFilterPattern(Pattern.compile(filter));
} else {
// Build filter string
// Always ignore first two hex bytes
String filter = "[0-9A-Z]{2} [0-9A-Z]{2}";
// Add command to filter string
if (StringUtils.isNotEmpty(configurationEntry.getCommand())) {
filter += " " + configurationEntry.getCommand();
filter += " [0-9A-Z]{2}";
}
// Add data to filter string
if (StringUtils.isNotEmpty(configurationEntry.getData())) {
Matcher matcher = P_BRACKETS_VALS.matcher(configurationEntry.getData());
filter += " " + matcher.replaceAll("[0-9A-Z]{2}");
}
// Finally add .* to end with everything
filter += " .*";
logger.trace("Compile RegEx filter: {}", filter);
configurationEntry.setFilterPattern(Pattern.compile(filter));
}
// remove brackets if used
if (StringUtils.isNotEmpty(configurationEntry.getData())) {
Matcher matcher = P_BRACKETS_CLEAN.matcher(configurationEntry.getData());
configurationEntry.setData(matcher.replaceAll(""));
}
// compile scipt's if available also once
if (configurationEntry.getValues() != null && !configurationEntry.getValues().isEmpty()) {
Map<String, TelegramValue> values = configurationEntry.getValues();
for (Entry<String, TelegramValue> entry : values.entrySet()) {
if (StringUtils.isNotEmpty(entry.getValue().getScript())) {
String script = entry.getValue().getScript();
// check if engine is available
if (StringUtils.isNotEmpty(script) && compEngine != null) {
try {
CompiledScript compile = compEngine.compile(script);
entry.getValue().setCsript(compile);
} catch (ScriptException e) {
logger.error("Error while compiling JavaScript!", e);
}
}
}
}
}
// compile scipt's if available
if (configurationEntry.getComputedValues() != null && !configurationEntry.getComputedValues().isEmpty()) {
Map<String, TelegramValue> cvalues = configurationEntry.getComputedValues();
for (Entry<String, TelegramValue> entry : cvalues.entrySet()) {
if (StringUtils.isNotEmpty(entry.getValue().getScript())) {
String script = entry.getValue().getScript();
// check if engine is available
if (StringUtils.isNotEmpty(script) && compEngine != null) {
try {
CompiledScript compile = compEngine.compile(script);
entry.getValue().setCsript(compile);
} catch (ScriptException e) {
logger.error("Error while compiling JavaScript!", e);
}
}
}
}
}
}
use of javax.script.ScriptException in project openhab1-addons by openhab.
the class EBusTelegramParser method parse.
/**
* Parses a valid eBus telegram and returns a map with key/values based on
* configuration registry.
*
* @param telegram The eBus telegram
* @return A Map with parsed key/values
*/
public Map<String, Object> parse(EBusTelegram telegram) {
// Check if a configuration provider is set
if (configurationProvider == null) {
logger.error("Configuration not loaded, can't parse telegram!");
return null;
}
// Secure null check
if (telegram == null) {
return null;
}
// All parsed values
final Map<String, Object> valueRegistry = new HashMap<String, Object>();
// All parsed values with short keys, used for script evaluation
final Map<String, Object> valueRegistryShortKeys = new HashMap<String, Object>();
// Get as byte buffer
final ByteBuffer byteBuffer = telegram.getBuffer();
// Get hex string for debugging
final String bufferString = EBusUtils.toHexDumpString(byteBuffer).toString();
// queries the configuration provider for matching registry entries
final List<TelegramConfiguration> matchedTelegramRegistry = configurationProvider.getCommandsByFilter(bufferString);
loggerAnalyses.debug(bufferString);
// No registry entries found, so this is a unknown telegram
if (matchedTelegramRegistry.isEmpty()) {
if (debugWriter != null && (debugWriteMode.contains("unknown") || debugWriteMode.contains("all"))) {
debugWriter.writeTelegram(telegram, "<unknown>");
}
loggerAnalyses.debug(" >>> Unknown ----------------------------------------");
if (loggerBrutforce.isTraceEnabled()) {
loggerBrutforce.trace(bufferString);
bruteforceEBusTelegram(telegram);
}
return null;
}
// loop thru all matching telegrams from registry
for (TelegramConfiguration registryEntry : matchedTelegramRegistry) {
int debugLevel = 0;
// get id and class key if used
String idKey = StringUtils.defaultString(registryEntry.getId());
String classKey = StringUtils.defaultString(registryEntry.getClazz());
// load debug level for this configuration entry if available
if (registryEntry.getDebug() != null) {
debugLevel = registryEntry.getDebug();
if (debugWriter != null && debugWriteMode.contains("debug")) {
debugWriter.writeTelegram(telegram, "DEBUG:" + registryEntry.getComment());
}
}
if (debugWriter != null && debugWriteMode.equals("all")) {
debugWriter.writeTelegram(telegram, registryEntry.getComment());
}
// get values block of configuration
Map<String, TelegramValue> values = registryEntry.getValues();
// debug
loggerAnalyses.debug(" >>> {}", StringUtils.defaultIfEmpty(registryEntry.getComment(), "<No comment available>"));
TelegramValue settings = null;
// loop over all entries
for (Entry<String, TelegramValue> entry : values.entrySet()) {
String uniqueKey = (classKey != "" ? classKey + "." : "") + (idKey != "" ? idKey + "." : "") + entry.getKey();
settings = entry.getValue();
// Extract the value from byte buffer
Object value = getValue(byteBuffer, entry.getValue());
if (value == null) {
// its okay if the value is null, maybe out of range min/max or replace value found
logger.trace("Returned value is null, skip ...");
continue;
}
// If compiled script available for this key, execute it now
if (settings.getCsript() != null) {
try {
// Add global variables thisValue and keyName to JavaScript context
HashMap<String, Object> bindings = new HashMap<String, Object>();
// short key
bindings.put(entry.getKey(), value);
// full key
bindings.put(uniqueKey, value);
// alias thisValue
bindings.put("thisValue", value);
// Evaluates script
value = evaluateScript(entry, bindings);
} catch (ScriptException e) {
logger.error("Error on evaluating JavaScript!", e);
break;
}
}
// debug
String label = StringUtils.defaultString(settings.getLabel());
String format = String.format("%-35s%-10s%s", uniqueKey, value, label);
String alias = null;
if (settings.getMapping() != null) {
Map<String, String> mapping = settings.getMapping();
alias = mapping.get(value.toString());
}
if (debugLevel >= 2) {
loggerAnalyses.debug(" >>> " + format);
if (alias != null) {
loggerAnalyses.debug(" >>> " + alias);
}
} else {
loggerAnalyses.trace(" >>> " + format);
if (alias != null) {
loggerAnalyses.trace(" >>> " + alias);
}
}
// Add result to registry
valueRegistry.put(uniqueKey, value);
// Add result to temp. short key registry, used for scripts
valueRegistryShortKeys.put(entry.getKey(), value);
// also use class.id as key as shortcut if we have only one value
if (values.size() == 1) {
if (!StringUtils.isEmpty(classKey) && !StringUtils.isEmpty(idKey)) {
uniqueKey = classKey + "." + idKey;
valueRegistry.put(uniqueKey, value);
}
}
}
// computes values available? if not exit here
if (registryEntry.getComputedValues() == null) {
continue;
}
// post execute the computes_values block
Map<String, TelegramValue> cvalues = registryEntry.getComputedValues();
for (Entry<String, TelegramValue> entry : cvalues.entrySet()) {
String uniqueKey = (classKey != "" ? classKey + "." : "") + (idKey != "" ? idKey + "." : "") + entry.getKey();
// Add all values to script scope
HashMap<String, Object> bindings = new HashMap<String, Object>();
bindings.putAll(valueRegistryShortKeys);
bindings.putAll(valueRegistry);
Object value;
try {
// Evaluates script
value = evaluateScript(entry, bindings);
// Add result to registry
valueRegistry.put(uniqueKey, value);
if (debugLevel >= 2) {
String label = StringUtils.defaultString(settings.getLabel());
String format = String.format("%-35s%-10s%s", uniqueKey, value, label);
loggerAnalyses.debug(" >>> " + format);
}
} catch (ScriptException e) {
logger.error("Error on evaluating JavaScript!", e);
}
}
}
return valueRegistry;
}
use of javax.script.ScriptException in project frames by tinkerpop.
the class GremlinGroovyAnnotationHandler method processVertex.
public Object processVertex(final GremlinGroovy annotation, final Method method, final Object[] arguments, final FramedGraph framedGraph, final Vertex vertex) {
try {
final CompiledScript script = this.engine.compile(annotation.value());
final Bindings bindings = getBindings(method, arguments);
bindings.put(IT, vertex);
bindings.put(G, framedGraph);
final Object result = script.eval(bindings);
// TODO: Deprecate the use of _() and replace with it
if (result instanceof Pipe & annotation.value().startsWith(PIPE)) {
LOGGER.warning("_() is deprecated in favor of using 'it' to represent the framed vertex");
((Pipe) result).setStarts(new SingleIterator<Element>(vertex));
}
if (annotation.frame()) {
if (result instanceof Iterable) {
final FramedVertexIterable r = new FramedVertexIterable(framedGraph, (Iterable) result, ClassUtilities.getGenericClass(method));
return (ClassUtilities.returnsIterable(method)) ? r : r.iterator().hasNext() ? r.iterator().next() : null;
} else if (ClassUtilities.returnsMap(method)) {
return new FramedVertexMap(framedGraph, (Map) result, ClassUtilities.getGenericClass(method));
} else if (result instanceof Vertex) {
return framedGraph.frame((Vertex) result, ClassUtilities.getGenericClass(method));
} else {
throw new IllegalStateException("The returned object can not be framed: " + result.getClass());
}
} else {
return result;
}
} catch (ScriptException e) {
//Preserve original exception functionality.
ExceptionUtils.sneakyThrow(e);
return null;
}
}
use of javax.script.ScriptException in project gremlin by tinkerpop.
the class GremlinGroovyScriptEngineTest method testFunctionsUsedInClosure.
public void testFunctionsUsedInClosure() throws ScriptException {
GremlinGroovyScriptEngine engine = new GremlinGroovyScriptEngine();
final Graph g = TinkerGraphFactory.createTinkerGraph();
final Bindings bindings = engine.createBindings();
bindings.put("g", g);
// this works on its own when the function and the line that uses it is in one "script". this is the
// current workaround
assertEquals(g.getVertex(2), engine.eval("def isVadas(v){v.name=='vadas'};g.V.filter{isVadas(it)}.next()", bindings));
// let's reset this piece and make sure isVadas is not hanging around.
engine = new GremlinGroovyScriptEngine();
// validate that isVadas throws an exception since it is not defined
try {
engine.eval("isVadas(g.v(2))", bindings);
// fail the test if the above doesn't throw an exception
fail();
} catch (Exception ex) {
// this is good...we want this. it means isVadas isn't hanging about
}
// now...define the function separately on its own in one script
engine.eval("def isVadas(v){v.name=='vadas'}", bindings);
// make sure the function works on its own...no problem
assertEquals(true, engine.eval("isVadas(g.v(2))", bindings));
// make sure the function works in a closure...this generates a StackOverflowError
assertEquals(g.getVertex(2), engine.eval("g.V.filter{isVadas(it)}.next()", bindings));
}
Aggregations