use of groovy.lang.Closure in project rest-assured by rest-assured.
the class EncoderRegistry method encodeJSON.
/**
* <p>Accepts a Collection or a JavaBean object which is converted to JSON.
* A Map or Collection will be converted to a {@link JsonBuilder}.. A
* String or GString will be interpreted as valid JSON and passed directly
* as the request body (with charset conversion if necessary.)</p>
* <p/>
* <p>If a Closure is passed as the model, it will be executed as if it were
* a JSON object definition passed to a {@link JsonBuilder}. In order
* for the closure to be interpreted correctly, there must be a 'root'
* element immediately inside the closure. For example:</p>
* <p/>
* <pre>builder.post( JSON ) {
* body = {
* root {
* first {
* one = 1
* two = '2'
* }
* second = 'some string'
* }
* }
* }</pre>
* <p> will return the following JSON string:<pre>
* {"root":{"first":{"one":1,"two":"2"},"second":"some string"}}</pre></p>
*
* @param model data to be converted to JSON, as specified above.
* @return an {@link HttpEntity} encapsulating this request data
* @throws UnsupportedEncodingException
*/
@SuppressWarnings("unchecked")
public HttpEntity encodeJSON(Object contentType, Object model) throws UnsupportedEncodingException {
String contentTypeAsString = contentTypeToString(contentType);
Object json;
if (model instanceof Map || model instanceof Collection) {
json = new JsonBuilder(model);
} else if (model instanceof Closure) {
Closure closure = (Closure) model;
closure.setDelegate(new JsonBuilder());
json = closure.call();
} else if (model instanceof String || model instanceof GString || model instanceof byte[]) {
// assume valid JSON already.
json = model;
} else if (model instanceof File) {
json = toString((File) model, contentTypeAsString);
} else {
throw new UnsupportedOperationException("Internal error: Can't encode " + model + " to JSON.");
}
return createEntity(contentTypeAsString, json);
}
use of groovy.lang.Closure in project grails-core by grails.
the class GrailsMetaClassUtils method copyExpandoMetaClass.
/**
* Copies the ExpandoMetaClass dynamic methods and properties from one Class to another.
*
* @param fromClass The source class
* @param toClass The destination class
* @param removeSource Whether to remove the source class after completion. True if yes
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static void copyExpandoMetaClass(Class<?> fromClass, Class<?> toClass, boolean removeSource) {
MetaClassRegistry registry = getRegistry();
MetaClass oldMetaClass = registry.getMetaClass(fromClass);
AdaptingMetaClass adapter = null;
ExpandoMetaClass emc;
if (oldMetaClass instanceof AdaptingMetaClass) {
adapter = ((AdaptingMetaClass) oldMetaClass);
emc = (ExpandoMetaClass) adapter.getAdaptee();
if (LOG.isDebugEnabled()) {
LOG.debug("Obtained adapted MetaClass [" + emc + "] from AdapterMetaClass instance [" + adapter + "]");
}
if (removeSource) {
registry.removeMetaClass(fromClass);
}
} else {
emc = (ExpandoMetaClass) oldMetaClass;
if (LOG.isDebugEnabled()) {
LOG.debug("No adapter MetaClass found, using original [" + emc + "]");
}
}
ExpandoMetaClass replacement = new ExpandoMetaClass(toClass, true, true);
for (Object obj : emc.getExpandoMethods()) {
if (obj instanceof ClosureInvokingMethod) {
ClosureInvokingMethod cim = (ClosureInvokingMethod) obj;
Closure callable = cim.getClosure();
if (!cim.isStatic()) {
replacement.setProperty(cim.getName(), callable);
} else {
((GroovyObject) replacement.getProperty(ExpandoMetaClass.STATIC_QUALIFIER)).setProperty(cim.getName(), callable);
}
}
}
for (Object o : emc.getExpandoProperties()) {
if (o instanceof ThreadManagedMetaBeanProperty) {
ThreadManagedMetaBeanProperty mbp = (ThreadManagedMetaBeanProperty) o;
replacement.setProperty(mbp.getName(), mbp.getInitialValue());
}
}
replacement.initialize();
if (adapter == null) {
if (LOG.isDebugEnabled()) {
LOG.debug("Adding MetaClass for class [" + toClass + "] MetaClass [" + replacement + "]");
}
registry.setMetaClass(toClass, replacement);
} else {
if (LOG.isDebugEnabled()) {
LOG.debug("Adding MetaClass for class [" + toClass + "] MetaClass [" + replacement + "] with adapter [" + adapter + "]");
}
try {
Constructor c = adapter.getClass().getConstructor(new Class[] { MetaClass.class });
MetaClass newAdapter = (MetaClass) BeanUtils.instantiateClass(c, new Object[] { replacement });
registry.setMetaClass(toClass, newAdapter);
} catch (NoSuchMethodException e) {
if (LOG.isDebugEnabled()) {
LOG.debug("Exception thrown constructing new MetaClass adapter when reloading: " + e.getMessage(), e);
}
}
}
}
use of groovy.lang.Closure in project groovy-core by groovy.
the class NioGroovyMethods method traverse.
/**
* Invokes <code>closure</code> for each descendant file in this directory tree.
* Sub-directories are recursively traversed as found.
* The traversal can be adapted by providing various options in the <code>options</code> Map according
* to the following keys:<dl>
* <dt>type</dt><dd>A {@link groovy.io.FileType} enum to determine if normal files or directories or both are processed</dd>
* <dt>preDir</dt><dd>A {@link groovy.lang.Closure} run before each directory is processed and optionally returning a {@link groovy.io.FileVisitResult} value
* which can be used to control subsequent processing.</dd>
* <dt>preRoot</dt><dd>A boolean indicating that the 'preDir' closure should be applied at the root level</dd>
* <dt>postDir</dt><dd>A {@link groovy.lang.Closure} run after each directory is processed and optionally returning a {@link groovy.io.FileVisitResult} value
* which can be used to control subsequent processing.</dd>
* <dt>postRoot</dt><dd>A boolean indicating that the 'postDir' closure should be applied at the root level</dd>
* <dt>visitRoot</dt><dd>A boolean indicating that the given closure should be applied for the root dir
* (not applicable if the 'type' is set to {@link groovy.io.FileType#FILES})</dd>
* <dt>maxDepth</dt><dd>The maximum number of directory levels when recursing
* (default is -1 which means infinite, set to 0 for no recursion)</dd>
* <dt>filter</dt><dd>A filter to perform on traversed files/directories (using the {@link DefaultGroovyMethods#isCase(Object, Object)} method). If set,
* only files/dirs which match are candidates for visiting.</dd>
* <dt>nameFilter</dt><dd>A filter to perform on the name of traversed files/directories (using the {@link DefaultGroovyMethods#isCase(Object, Object)} method). If set,
* only files/dirs which match are candidates for visiting. (Must not be set if 'filter' is set)</dd>
* <dt>excludeFilter</dt><dd>A filter to perform on traversed files/directories (using the {@link DefaultGroovyMethods#isCase(Object, Object)} method).
* If set, any candidates which match won't be visited.</dd>
* <dt>excludeNameFilter</dt><dd>A filter to perform on the names of traversed files/directories (using the {@link DefaultGroovyMethods#isCase(Object, Object)} method).
* If set, any candidates which match won't be visited. (Must not be set if 'excludeFilter' is set)</dd>
* <dt>sort</dt><dd>A {@link groovy.lang.Closure} which if set causes the files and subdirectories for each directory to be processed in sorted order.
* Note that even when processing only files, the order of visited subdirectories will be affected by this parameter.</dd>
* </dl>
* This example prints out file counts and size aggregates for groovy source files within a directory tree:
* <pre>
* def totalSize = 0
* def count = 0
* def sortByTypeThenName = { a, b ->
* a.isFile() != b.isFile() ? a.isFile() <=> b.isFile() : a.name <=> b.name
* }
* rootDir.traverse(
* type : FILES,
* nameFilter : ~/.*\.groovy/,
* preDir : { if (it.name == '.svn') return SKIP_SUBTREE },
* postDir : { println "Found $count files in $it.name totalling $totalSize bytes"
* totalSize = 0; count = 0 },
* postRoot : true
* sort : sortByTypeThenName
* ) {it -> totalSize += it.size(); count++ }
* </pre>
*
* @param self a Path
* @param options a Map of options to alter the traversal behavior
* @param closure the Closure to invoke on each file/directory and optionally returning a {@link groovy.io.FileVisitResult} value
* which can be used to control subsequent processing
* @throws java.io.FileNotFoundException if the given directory does not exist
* @throws IllegalArgumentException if the provided Path object does not represent a directory or illegal filter combinations are supplied
* @see DefaultGroovyMethods#sort(java.util.Collection, groovy.lang.Closure)
* @see groovy.io.FileVisitResult
* @see groovy.io.FileType
* @since 2.3.0
*/
public static void traverse(final Path self, final Map<String, Object> options, @ClosureParams(value = SimpleType.class, options = "java.nio.file.Path") final Closure closure) throws IOException {
// throws FileNotFoundException, IllegalArgumentException {
Number maxDepthNumber = DefaultGroovyMethods.asType(options.remove("maxDepth"), Number.class);
int maxDepth = maxDepthNumber == null ? -1 : maxDepthNumber.intValue();
Boolean visitRoot = DefaultGroovyMethods.asType(get(options, "visitRoot", false), Boolean.class);
Boolean preRoot = DefaultGroovyMethods.asType(get(options, "preRoot", false), Boolean.class);
Boolean postRoot = DefaultGroovyMethods.asType(get(options, "postRoot", false), Boolean.class);
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");
Object preResult = null;
if (preRoot && pre != null) {
preResult = pre.call(self);
}
if (preResult == FileVisitResult.TERMINATE || preResult == FileVisitResult.SKIP_SUBTREE)
return;
FileVisitResult terminated = traverse(self, options, closure, maxDepth);
if (type != FileType.FILES && visitRoot) {
if (closure != null && notFiltered(self, filter, nameFilter, excludeFilter, excludeNameFilter)) {
Object closureResult = closure.call(self);
if (closureResult == FileVisitResult.TERMINATE)
return;
}
}
if (postRoot && post != null && terminated != FileVisitResult.TERMINATE)
post.call(self);
}
use of groovy.lang.Closure in project groovy-core by groovy.
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-core by groovy.
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());
}
}
Aggregations