use of groovy.lang.Closure in project enumerable by hraberg.
the class JavaScriptTest method interactingWithGroovy.
@Test
public void interactingWithGroovy() throws Exception {
ScriptEngine groovy = GroovyTest.getGroovyEngine();
Closure<?> closure = (Closure<?>) groovy.eval("{ n, m -> n * m }");
FunctionFn2 f = toFunction(LambdaGroovy.toFn2(closure));
js.put("f", f);
assertEquals(6.0, js.eval("f(2, 3)"));
}
use of groovy.lang.Closure in project enumerable by hraberg.
the class JRubyTest method interactingWithGroovy.
@Test
public void interactingWithGroovy() throws Exception {
Ruby ruby = Ruby.getGlobalRuntime();
ScriptEngine groovy = GroovyTest.getGroovyEngine();
Closure<?> closure = (Closure<?>) groovy.eval("{ n, m -> n * m }");
RubyProc proc = toProc(LambdaGroovy.toFn2(closure));
assertEquals(ruby.newFixnum(6), proc.call(ruby.getThreadService().getCurrentContext(), new IRubyObject[] { ruby.newFixnum(2), ruby.newFixnum(3) }));
rb.put("block", proc);
assertEquals(120L, rb.eval("[1, 2, 3, 4, 5].inject &block"));
}
use of groovy.lang.Closure in project groovy by apache.
the class NioGroovyMethods method traverse.
private static FileVisitResult traverse(final Path self, final Map<String, Object> options, @ClosureParams(value = SimpleType.class, options = "java.nio.file.Path") final Closure closure, final int maxDepth) throws IOException {
checkDir(self);
final Closure pre = (Closure) options.get("preDir");
final Closure post = (Closure) options.get("postDir");
final FileType type = (FileType) options.get("type");
final Object filter = options.get("filter");
final Object nameFilter = options.get("nameFilter");
final Object excludeFilter = options.get("excludeFilter");
final Object excludeNameFilter = options.get("excludeNameFilter");
final Closure sort = (Closure) options.get("sort");
try (DirectoryStream<Path> stream = Files.newDirectoryStream(self)) {
final Iterator<Path> itr = stream.iterator();
List<Path> files = new LinkedList<Path>();
while (itr.hasNext()) {
files.add(itr.next());
}
if (sort != null)
files = DefaultGroovyMethods.sort(files, sort);
for (Path path : files) {
if (Files.isDirectory(path)) {
if (type != FileType.FILES) {
if (closure != null && notFiltered(path, filter, nameFilter, excludeFilter, excludeNameFilter)) {
Object closureResult = closure.call(path);
if (closureResult == FileVisitResult.SKIP_SIBLINGS)
break;
if (closureResult == FileVisitResult.TERMINATE)
return FileVisitResult.TERMINATE;
}
}
if (maxDepth != 0) {
Object preResult = null;
if (pre != null) {
preResult = pre.call(path);
}
if (preResult == FileVisitResult.SKIP_SIBLINGS)
break;
if (preResult == FileVisitResult.TERMINATE)
return FileVisitResult.TERMINATE;
if (preResult != FileVisitResult.SKIP_SUBTREE) {
FileVisitResult terminated = traverse(path, options, closure, maxDepth - 1);
if (terminated == FileVisitResult.TERMINATE)
return terminated;
}
Object postResult = null;
if (post != null) {
postResult = post.call(path);
}
if (postResult == FileVisitResult.SKIP_SIBLINGS)
break;
if (postResult == FileVisitResult.TERMINATE)
return FileVisitResult.TERMINATE;
}
} else if (type != FileType.DIRECTORIES) {
if (closure != null && notFiltered(path, filter, nameFilter, excludeFilter, excludeNameFilter)) {
Object closureResult = closure.call(path);
if (closureResult == FileVisitResult.SKIP_SIBLINGS)
break;
if (closureResult == FileVisitResult.TERMINATE)
return FileVisitResult.TERMINATE;
}
}
}
return FileVisitResult.CONTINUE;
}
}
use of groovy.lang.Closure in project groovy by apache.
the class GroovyServlet method service.
/**
* Handle web requests to the GroovyServlet
*/
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
// Get the script path from the request - include aware (GROOVY-815)
final String scriptUri = getScriptUri(request);
// Set it to HTML by default
response.setContentType("text/html; charset=" + encoding);
// Set up the script context
final ServletBinding binding = new ServletBinding(request, response, servletContext);
setVariables(binding);
// Run the script
try {
Closure closure = new Closure(gse) {
public Object call() {
try {
return ((GroovyScriptEngine) getDelegate()).run(scriptUri, binding);
} catch (ResourceException e) {
throw new RuntimeException(e);
} catch (ScriptException e) {
throw new RuntimeException(e);
}
}
};
GroovyCategorySupport.use(ServletCategory.class, closure);
} catch (RuntimeException runtimeException) {
StringBuilder error = new StringBuilder("GroovyServlet Error: ");
error.append(" script: '");
error.append(scriptUri);
error.append("': ");
Throwable e = runtimeException.getCause();
/*
* Null cause?!
*/
if (e == null) {
error.append(" Script processing failed.\n");
error.append(runtimeException.getMessage());
if (runtimeException.getStackTrace().length > 0)
error.append(runtimeException.getStackTrace()[0].toString());
servletContext.log(error.toString());
System.err.println(error.toString());
runtimeException.printStackTrace(System.err);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error.toString());
return;
}
/*
* Resource not found.
*/
if (e instanceof ResourceException) {
error.append(" Script not found, sending 404.");
servletContext.log(error.toString());
System.err.println(error.toString());
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
/*
* Other internal error. Perhaps syntax?!
*/
servletContext.log("An error occurred processing the request", runtimeException);
error.append(e.getMessage());
if (e.getStackTrace().length > 0)
error.append(e.getStackTrace()[0].toString());
servletContext.log(e.toString());
System.err.println(e.toString());
runtimeException.printStackTrace(System.err);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
}
}
use of groovy.lang.Closure in project groovy by apache.
the class BindPathSnooper method createBinding.
public FullBinding createBinding(SourceBinding source, TargetBinding target) {
if (source != this) {
throw new RuntimeException("Source binding must the Trigger Binding as well");
}
final BindPathSnooper delegate = new BindPathSnooper();
try {
// create our own local copy of the closure
final Class closureClass = closure.getClass();
// do in privileged block since we may be looking at private stuff
Closure closureLocalCopy = java.security.AccessController.doPrivileged(new PrivilegedAction<Closure>() {
public Closure run() {
// assume closures have only 1 constructor, of the form (Object, Reference*)
Constructor constructor = closureClass.getConstructors()[0];
int paramCount = constructor.getParameterTypes().length;
Object[] args = new Object[paramCount];
args[0] = delegate;
for (int i = 1; i < paramCount; i++) {
args[i] = new Reference(new BindPathSnooper());
}
try {
boolean acc = constructor.isAccessible();
constructor.setAccessible(true);
Closure localCopy = (Closure) constructor.newInstance(args);
if (!acc) {
constructor.setAccessible(false);
}
localCopy.setResolveStrategy(Closure.DELEGATE_ONLY);
for (Field f : closureClass.getDeclaredFields()) {
acc = f.isAccessible();
f.setAccessible(true);
if (f.getType() == Reference.class) {
delegate.fields.put(f.getName(), (BindPathSnooper) ((Reference) f.get(localCopy)).get());
}
if (!acc) {
f.setAccessible(false);
}
}
return localCopy;
} catch (Exception e) {
throw new RuntimeException("Error snooping closure", e);
}
}
});
try {
closureLocalCopy.call();
} catch (DeadEndException e) {
// we want this exception exposed.
throw e;
} catch (Exception e) {
//LOGME
// ignore it, likely failing because we are faking out properties
// such as a call to Math.min(int, BindPathSnooper)
}
} catch (Exception e) {
e.printStackTrace(System.out);
throw new RuntimeException("A closure expression binding could not be created because of " + e.getClass().getName() + ":\n\t" + e.getMessage());
}
List<BindPath> rootPaths = new ArrayList<BindPath>();
for (Map.Entry<String, BindPathSnooper> entry : delegate.fields.entrySet()) {
BindPath bp = createBindPath(entry.getKey(), entry.getValue());
bp.currentObject = closure;
rootPaths.add(bp);
}
PropertyPathFullBinding fb = new PropertyPathFullBinding();
fb.setSourceBinding(new ClosureSourceBinding(closure));
fb.setTargetBinding(target);
fb.bindPaths = rootPaths.toArray(new BindPath[rootPaths.size()]);
return fb;
}
Aggregations