use of groovy.lang.Script in project hale by halestudio.
the class GroovyTransformationPage method validate.
@Override
protected boolean validate(String document) {
super.validate(document);
List<PropertyValue> values = new ArrayList<PropertyValue>();
for (EntityDefinition var : getVariables()) {
if (var instanceof PropertyEntityDefinition) {
PropertyEntityDefinition property = (PropertyEntityDefinition) var;
values.add(new PropertyValueImpl(testValues.get(property), property));
}
}
Property targetProperty = (Property) CellUtil.getFirstEntity(getWizard().getUnfinishedCell().getTarget());
if (targetProperty == null) {
// not yet selected (NewRelationWizard)
return false;
}
InstanceBuilder builder = GroovyTransformation.createBuilder(targetProperty.getDefinition());
Cell cell = getWizard().getUnfinishedCell();
boolean useInstanceValues = CellUtil.getOptionalParameter(cell, GroovyTransformation.PARAM_INSTANCE_VARIABLES, Value.of(false)).as(Boolean.class);
AlignmentService as = PlatformUI.getWorkbench().getService(AlignmentService.class);
GroovyService gs = HaleUI.getServiceProvider().getService(GroovyService.class);
Script script = null;
try {
Collection<? extends Cell> typeCells = as.getAlignment().getTypeCells(cell);
// select one matching type cell, the script has to run for all
// matching cells
// if there is no matching cell it may produce a npe, which is okay
Cell typeCell = null;
if (!typeCells.isEmpty()) {
typeCell = typeCells.iterator().next();
}
CellLog log = new CellLog(new DefaultTransformationReporter("dummy", false), cell);
ExecutionContext context = new DummyExecutionContext(HaleUI.getServiceProvider());
groovy.lang.Binding binding;
if (cell.getTransformationIdentifier().equals(GroovyGreedyTransformation.ID)) {
binding = GroovyGreedyTransformation.createGroovyBinding(values, null, cell, typeCell, builder, useInstanceValues, log, context, targetProperty.getDefinition().getDefinition().getPropertyType());
} else {
binding = GroovyTransformation.createGroovyBinding(values, null, cell, typeCell, builder, useInstanceValues, log, context, targetProperty.getDefinition().getDefinition().getPropertyType());
}
script = gs.parseScript(document, binding);
GroovyTransformation.evaluate(script, builder, targetProperty.getDefinition().getDefinition().getPropertyType(), gs, log);
} catch (NoResultException e) {
// continue
} catch (final Exception e) {
return handleValidationResult(script, e);
}
return handleValidationResult(script, null);
}
use of groovy.lang.Script in project hale by halestudio.
the class GroovySnippets method invokeMethod.
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public Object invokeMethod(String name, Object args) {
List<?> argList = new ArrayList<>(InvokerHelper.asList(args));
try {
Map<Object, Object> vars = new HashMap<>();
Optional<?> firstMap = argList.stream().filter(v -> v instanceof Map).findFirst();
if (firstMap.isPresent()) {
vars.putAll((Map) firstMap.get());
argList.remove(firstMap.get());
}
Script script = loadScript(name, vars);
if (script == null) {
throw new IllegalArgumentException(MessageFormat.format("Snippet with identifer \"{0}\" not found.", name));
}
if (argList.isEmpty()) {
// run script
return script.run();
} else if (argList.size() == 1 && argList.get(0) instanceof Closure) {
// run closure on script
Closure cl = (Closure) argList.get(0);
cl.setDelegate(script);
cl.setResolveStrategy(Closure.OWNER_FIRST);
return cl.call();
}
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
return super.invokeMethod(name, args);
}
use of groovy.lang.Script in project cuba by cuba-platform.
the class AbstractScripting method createScript.
protected Script createScript(String text) {
StringBuilder sb = new StringBuilder();
for (String importItem : imports) {
sb.append("import ").append(importItem).append("\n");
}
Matcher matcher = IMPORT_PATTERN.matcher(text);
String result;
if (matcher.find()) {
StringBuffer s = new StringBuffer();
matcher.appendReplacement(s, sb + "$0");
result = matcher.appendTail(s).toString();
} else {
Matcher packageMatcher = PACKAGE_PATTERN.matcher(text);
if (packageMatcher.find()) {
StringBuffer s = new StringBuffer();
packageMatcher.appendReplacement(s, "$0\n" + sb);
result = packageMatcher.appendTail(s).toString();
} else {
result = sb.append(text).toString();
}
}
CompilerConfiguration cc = new CompilerConfiguration();
cc.setClasspath(groovyClassPath);
cc.setRecompileGroovySource(true);
GroovyShell shell = new GroovyShell(javaClassLoader, new Binding(), cc);
// noinspection UnnecessaryLocalVariable
Script script = shell.parse(result);
return script;
}
use of groovy.lang.Script in project gremlin by tinkerpop.
the class GremlinGroovyScriptEngine method eval.
Object eval(final Class scriptClass, final ScriptContext context) throws ScriptException {
this.checkClearCache();
context.setAttribute("context", context, ScriptContext.ENGINE_SCOPE);
java.io.Writer writer = context.getWriter();
context.setAttribute("out", writer instanceof PrintWriter ? writer : new PrintWriter(writer), ScriptContext.ENGINE_SCOPE);
Binding binding = new Binding() {
public Object getVariable(String name) {
synchronized (context) {
int scope = context.getAttributesScope(name);
if (scope != -1) {
return context.getAttribute(name, scope);
}
throw new MissingPropertyException(name, getClass());
}
}
public void setVariable(String name, Object value) {
synchronized (context) {
int scope = context.getAttributesScope(name);
if (scope == -1) {
scope = ScriptContext.ENGINE_SCOPE;
}
context.setAttribute(name, value, scope);
}
}
};
try {
Script scriptObject = InvokerHelper.createScript(scriptClass, binding);
Method[] methods = scriptClass.getMethods();
Map<String, MethodClosure> closures = new HashMap<String, MethodClosure>();
for (Method m : methods) {
String name = m.getName();
closures.put(name, new MethodClosure(scriptObject, name));
}
globalClosures.putAll(closures);
final MetaClass oldMetaClass = scriptObject.getMetaClass();
scriptObject.setMetaClass(new DelegatingMetaClass(oldMetaClass) {
public Object invokeMethod(Object object, String name, Object args) {
if (args == null) {
return invokeMethod(object, name, MetaClassHelper.EMPTY_ARRAY);
} else if (args instanceof Tuple) {
return invokeMethod(object, name, ((Tuple) args).toArray());
} else if (args instanceof Object[]) {
return invokeMethod(object, name, (Object[]) args);
} else {
return invokeMethod(object, name, new Object[] { args });
}
}
public Object invokeMethod(Object object, String name, Object[] args) {
try {
return super.invokeMethod(object, name, args);
} catch (MissingMethodException mme) {
return callGlobal(name, args, context);
}
}
public Object invokeStaticMethod(Object object, String name, Object[] args) {
try {
return super.invokeStaticMethod(object, name, args);
} catch (MissingMethodException mme) {
return callGlobal(name, args, context);
}
}
});
return scriptObject.run();
} catch (Exception e) {
throw new ScriptException(e);
}
}
use of groovy.lang.Script in project groovy by apache.
the class GroovyMain method processFiles.
/**
* Process the input files.
*/
private void processFiles() throws CompilationFailedException, IOException, URISyntaxException {
GroovyShell groovy = new GroovyShell(Thread.currentThread().getContextClassLoader(), conf);
setupContextClassLoader(groovy);
Script s = groovy.parse(getScriptSource(isScriptFile, script));
if (args.isEmpty()) {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
PrintWriter writer = new PrintWriter(System.out);
processReader(s, reader, writer);
writer.flush();
}
} else {
for (String filename : args) {
// TODO: These are the arguments for -p and -i. Why are we searching using Groovy script extensions?
// Where is this documented?
File file = huntForTheScriptFile(filename);
processFile(s, file);
}
}
}
Aggregations