use of groovy.lang.Script in project groovy by apache.
the class GroovyScriptEngineImpl method eval.
// package-privates
Object eval(Class<?> scriptClass, final ScriptContext ctx) throws ScriptException {
/*
* 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);
}
// Redirect script output to context writer, if out var is not already provided
if ("out".equals(name)) {
Writer writer = ctx.getWriter();
if (writer != null) {
return (writer instanceof PrintWriter) ? (PrintWriter) writer : new PrintWriter(writer, true);
}
}
// Provide access to engine context, if context var is not already provided
if ("context".equals(name)) {
return ctx;
}
}
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);
}
}
use of groovy.lang.Script in project groovy by apache.
the class XmlTemplateEngine method createTemplate.
public Template createTemplate(Reader reader) throws CompilationFailedException, ClassNotFoundException, IOException {
Node root;
try {
root = xmlParser.parse(reader);
} catch (SAXException e) {
throw new RuntimeException("Parsing XML source failed.", e);
}
if (root == null) {
throw new IOException("Parsing XML source failed: root node is null.");
}
StringWriter writer = new StringWriter(1024);
writer.write("/* Generated by XmlTemplateEngine */\n");
new GspPrinter(new PrintWriter(writer), indentation).print(root);
Script script;
try {
script = groovyShell.parse(writer.toString(), "XmlTemplateScript" + counter++ + ".groovy");
} catch (Exception e) {
throw new GroovyRuntimeException("Failed to parse template script (your template may contain an error or be trying to use expressions not currently supported): " + e.getMessage());
}
return new XmlTemplate(script);
}
use of groovy.lang.Script in project intellij-community by JetBrains.
the class ScriptSupport method checkValidScript.
public static String checkValidScript(String scriptText) {
try {
final File scriptFile = new File(scriptText);
final GroovyShell shell = new GroovyShell();
final Script script = scriptFile.exists() ? shell.parse(scriptFile) : shell.parse(scriptText);
return null;
} catch (IOException e) {
return e.getMessage();
} catch (MultipleCompilationErrorsException e) {
final ErrorCollector errorCollector = e.getErrorCollector();
final List<Message> errors = errorCollector.getErrors();
for (Message error : errors) {
if (error instanceof SyntaxErrorMessage) {
final SyntaxErrorMessage errorMessage = (SyntaxErrorMessage) error;
final SyntaxException cause = errorMessage.getCause();
return cause.getMessage();
}
}
return e.getMessage();
} catch (CompilationFailedException ex) {
return ex.getLocalizedMessage();
}
}
use of groovy.lang.Script in project sulky by huxi.
the class GroovyInstanceTest method broken.
@SuppressWarnings({ "ThrowableResultOfMethodCallIgnored" })
@Test
public void broken() throws IOException, InterruptedException {
JUnitTools.copyResourceToFile("/Foo.groovy", fooFile, System.currentTimeMillis() - 2 * ONE_MINUTE);
GroovyInstance instance = new GroovyInstance();
instance.setGroovyFileName(fooFile.getAbsolutePath());
instance.setRefreshInterval(1);
Class instanceClass = instance.getInstanceClass();
assertNotNull(instanceClass);
assertEquals("Foo", instanceClass.getName());
Object object = instance.getInstance();
assertNotNull(object);
assertTrue(object instanceof Script);
Script script = (Script) object;
String result = (String) script.run();
assertEquals("Foo", result);
JUnitTools.copyResourceToFile("/Broken.b0rken", fooFile, System.currentTimeMillis() - ONE_MINUTE);
Thread.sleep(100);
assertNull(instance.getInstanceClass());
assertNull(instance.getInstance());
// error should be logged only once...
Thread.sleep(10);
assertNull(instance.getInstanceClass());
assertNull(instance.getInstance());
Thread.sleep(10);
assertNull(instance.getInstanceClass());
assertNull(instance.getInstance());
Thread.sleep(10);
assertNotNull(instance.getErrorCause());
assertNotNull(instance.getErrorMessage());
JUnitTools.copyResourceToFile("/Bar.groovy", fooFile, System.currentTimeMillis());
object = instance.getInstance();
assertTrue(object instanceof Script);
script = (Script) object;
result = (String) script.run();
assertEquals("Bar", result);
assertNull(instance.getErrorCause());
assertNull(instance.getErrorMessage());
}
use of groovy.lang.Script in project sulky by huxi.
the class GroovyInstanceTest method normal.
@SuppressWarnings({ "ThrowableResultOfMethodCallIgnored" })
@Test
public void normal() throws IOException {
JUnitTools.copyResourceToFile("/Foo.groovy", fooFile, System.currentTimeMillis() - ONE_MINUTE);
GroovyInstance instance = new GroovyInstance();
instance.setGroovyFileName(fooFile.getAbsolutePath());
Class instanceClass = instance.getInstanceClass();
assertNotNull(instanceClass);
assertEquals("Foo", instanceClass.getName());
Object object = instance.getInstance();
assertNotNull(object);
assertTrue(object instanceof Script);
Script script = (Script) object;
String result = (String) script.run();
assertEquals("Foo", result);
assertNull(instance.getErrorCause());
assertNull(instance.getErrorMessage());
Object newObject = instance.getNewInstance();
assertNotNull(object);
assertTrue(newObject instanceof Script);
Script newScript = (Script) newObject;
String newResult = (String) newScript.run();
assertEquals("Foo", newResult);
assertNotSame(newScript, script);
assertNotSame(instance.getNewInstance(), newScript);
assertSame(instance.getInstance(), script);
assertSame(script, instance.getInstanceAs(Script.class));
assertNotSame(script, instance.getNewInstanceAs(Script.class));
newScript = instance.getNewInstanceAs(Script.class);
newResult = (String) newScript.run();
assertEquals("Foo", newResult);
assertNull(instance.getInstanceAs(Comparable.class));
assertNull(instance.getNewInstanceAs(Comparable.class));
}
Aggregations