Search in sources :

Example 96 with Closure

use of groovy.lang.Closure in project groovy by apache.

the class GPathResult method getBody.

/**
 * Creates a Closure representing the body of this GPathResult.
 *
 * @return the body of this GPathResult, converted to a <code>Closure</code>
 */
public Closure getBody() {
    return new Closure(this.parent, this) {

        public void doCall(Object[] args) {
            final GroovyObject delegate = (GroovyObject) getDelegate();
            final GPathResult thisObject = (GPathResult) getThisObject();
            Node node = (Node) thisObject.getAt(0);
            List children = node.children();
            for (Object child : children) {
                delegate.getProperty("mkp");
                if (child instanceof Node) {
                    delegate.invokeMethod("yield", new Object[] { new NodeChild((Node) child, thisObject, "*", null) });
                } else {
                    delegate.invokeMethod("yield", new Object[] { child });
                }
            }
        }
    };
}
Also used : Closure(groovy.lang.Closure) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) List(java.util.List) GroovyObject(groovy.lang.GroovyObject) GroovyObject(groovy.lang.GroovyObject)

Example 97 with Closure

use of groovy.lang.Closure in project groovy by apache.

the class Builder method fettleMethodMap.

private static Map fettleMethodMap(final Closure defaultGenerator, final Map methodMap) {
    final Map newMethodMap = new HashMap();
    for (Object o : methodMap.keySet()) {
        final Object key = o;
        final Object value = methodMap.get(key);
        if ((value instanceof Closure)) {
            newMethodMap.put(key, value);
        } else {
            newMethodMap.put(key, defaultGenerator.curry((Object[]) value));
        }
    }
    return newMethodMap;
}
Also used : Closure(groovy.lang.Closure) HashMap(java.util.HashMap) Map(java.util.Map) HashMap(java.util.HashMap)

Example 98 with Closure

use of groovy.lang.Closure in project groovy by apache.

the class ObjectGraphBuilder method setReferenceResolver.

/**
 * Sets the current ReferenceResolver.<br>
 * It will assign DefaultReferenceResolver if null.<br>
 * It accepts a ReferenceResolver instance, a String or a Closure.
 */
public void setReferenceResolver(final Object referenceResolver) {
    if (referenceResolver instanceof ReferenceResolver) {
        this.referenceResolver = (ReferenceResolver) referenceResolver;
    } else if (referenceResolver instanceof String) {
        this.referenceResolver = nodeName -> (String) referenceResolver;
    } else if (referenceResolver instanceof Closure) {
        final ObjectGraphBuilder self = this;
        this.referenceResolver = nodeName -> {
            Closure cls = (Closure) referenceResolver;
            cls.setDelegate(self);
            return (String) cls.call(new Object[] { nodeName });
        };
    } else {
        this.referenceResolver = new DefaultReferenceResolver();
    }
}
Also used : InvokerHelper(org.codehaus.groovy.runtime.InvokerHelper) Collection(java.util.Collection) Closure(groovy.lang.Closure) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) GString(groovy.lang.GString) List(java.util.List) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) Map(java.util.Map) MetaProperty(groovy.lang.MetaProperty) Pattern(java.util.regex.Pattern) MissingPropertyException(groovy.lang.MissingPropertyException) Closure(groovy.lang.Closure) GString(groovy.lang.GString)

Example 99 with Closure

use of groovy.lang.Closure in project groovy by apache.

the class ResourceGroovyMethods method traverse.

private static FileVisitResult traverse(final File self, final Map<String, ?> options, final Closure closure, final int maxDepth) throws FileNotFoundException, IllegalArgumentException {
    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");
    final File[] origFiles = self.listFiles();
    // null check because of http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4803836
    if (origFiles != null) {
        List<File> files = Arrays.asList(origFiles);
        if (sort != null)
            files = DefaultGroovyMethods.sort((Iterable<File>) files, sort);
        for (File file : files) {
            if (file.isDirectory()) {
                if (type != FileType.FILES) {
                    if (closure != null && notFiltered(file, filter, nameFilter, excludeFilter, excludeNameFilter)) {
                        Object closureResult = closure.call(file);
                        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(file);
                    }
                    if (preResult == FileVisitResult.SKIP_SIBLINGS)
                        break;
                    if (preResult == FileVisitResult.TERMINATE)
                        return FileVisitResult.TERMINATE;
                    if (preResult != FileVisitResult.SKIP_SUBTREE) {
                        FileVisitResult terminated = traverse(file, options, closure, maxDepth - 1);
                        if (terminated == FileVisitResult.TERMINATE)
                            return terminated;
                    }
                    Object postResult = null;
                    if (post != null) {
                        postResult = post.call(file);
                    }
                    if (postResult == FileVisitResult.SKIP_SIBLINGS)
                        break;
                    if (postResult == FileVisitResult.TERMINATE)
                        return FileVisitResult.TERMINATE;
                }
            } else if (type != FileType.DIRECTORIES) {
                if (closure != null && notFiltered(file, filter, nameFilter, excludeFilter, excludeNameFilter)) {
                    Object closureResult = closure.call(file);
                    if (closureResult == FileVisitResult.SKIP_SIBLINGS)
                        break;
                    if (closureResult == FileVisitResult.TERMINATE)
                        return FileVisitResult.TERMINATE;
                }
            }
        }
    }
    return FileVisitResult.CONTINUE;
}
Also used : Closure(groovy.lang.Closure) FileType(groovy.io.FileType) FileVisitResult(groovy.io.FileVisitResult) File(java.io.File)

Example 100 with Closure

use of groovy.lang.Closure in project groovy by apache.

the class ResourceGroovyMethods method traverse.

/**
 * Processes each descendant file in this directory and any sub-directories.
 * Processing consists of potentially calling <code>closure</code> passing it the current
 * file (which may be a normal file or subdirectory) and then if a subdirectory was encountered,
 * recursively processing the subdirectory.
 * <p>
 * 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. Particularly useful when strict depth-first traversal is required.</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(java.lang.Object, java.lang.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(java.lang.Object, java.lang.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(java.lang.Object, java.lang.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(java.lang.Object, java.lang.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 {@code ->}
 *     a.isFile() != b.isFile() ? a.isFile() {@code <=>} b.isFile() : a.name {@code <=>} 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 {@code ->} totalSize += it.size(); count++ }
 * </pre>
 *
 * @param self    a File (that happens to be a folder/directory)
 * @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 FileNotFoundException    if the given directory does not exist
 * @throws IllegalArgumentException if the provided File object does not represent a directory or illegal filter combinations are supplied
 * @see DefaultGroovyMethods#sort(Iterable, groovy.lang.Closure)
 * @see groovy.io.FileVisitResult
 * @see groovy.io.FileType
 * @since 1.7.1
 */
public static void traverse(final File self, @NamedParam(value = "type", type = FileType.class) @NamedParam(value = "preDir", type = Closure.class) @NamedParam(value = "preRoot", type = Boolean.class) @NamedParam(value = "postDir", type = Closure.class) @NamedParam(value = "postRoot", type = Boolean.class) @NamedParam(value = "visitRoot", type = Boolean.class) @NamedParam(value = "maxDepth", type = Integer.class) @NamedParam(value = "filter") @NamedParam(value = "nameFilter") @NamedParam(value = "excludeFilter") @NamedParam(value = "excludeNameFilter") @NamedParam(value = "sort", type = Closure.class) final Map<String, ?> options, @ClosureParams(value = SimpleType.class, options = "java.io.File") final Closure closure) throws FileNotFoundException, IllegalArgumentException {
    final int maxDepth;
    final boolean preRoot;
    final boolean postRoot;
    final boolean visitRoot;
    {
        Object maxDepthValue = options.remove("maxDepth");
        maxDepth = maxDepthValue == null ? -1 : DefaultGroovyMethods.asType(maxDepthValue, Number.class).intValue();
        Object preRootValue = options.get("preRoot");
        preRoot = preRootValue == null ? false : DefaultGroovyMethods.asType(preRootValue, Boolean.class).booleanValue();
        Object postRootValue = options.get("postRoot");
        postRoot = postRootValue == null ? false : DefaultGroovyMethods.asType(postRootValue, Boolean.class).booleanValue();
        Object visitRootValue = options.get("visitRoot");
        visitRoot = visitRootValue == null ? false : DefaultGroovyMethods.asType(visitRootValue, Boolean.class).booleanValue();
    }
    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);
}
Also used : Closure(groovy.lang.Closure) FileType(groovy.io.FileType) FileVisitResult(groovy.io.FileVisitResult)

Aggregations

Closure (groovy.lang.Closure)251 Map (java.util.Map)55 HashMap (java.util.HashMap)38 ArrayList (java.util.ArrayList)37 GroovyObject (groovy.lang.GroovyObject)33 List (java.util.List)33 Binding (groovy.lang.Binding)22 GString (groovy.lang.GString)21 LinkedHashMap (java.util.LinkedHashMap)20 LinkedList (java.util.LinkedList)19 Collection (java.util.Collection)17 GroovyShell (groovy.lang.GroovyShell)14 Test (org.junit.Test)14 MethodClosure (org.codehaus.groovy.runtime.MethodClosure)13 FileType (groovy.io.FileType)12 FileVisitResult (groovy.io.FileVisitResult)12 File (java.io.File)12 Iterator (java.util.Iterator)10 GroovyBugError (org.codehaus.groovy.GroovyBugError)10 IOException (java.io.IOException)9