Java Code Examples for groovy.lang.Closure

The following examples show how to use groovy.lang.Closure. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: groovy   Author: apache   File: Node.java    License: Apache License 2.0 6 votes vote down vote up
private void breadthFirstRest(boolean preorder, int level, Closure c) {
    Stack<Tuple2<Object, Integer>> stack = new Stack<Tuple2<Object, Integer>>();
    List nextLevelChildren = preorder ? getDirectChildren() : DefaultGroovyMethods.reverse(getDirectChildren());
    while (!nextLevelChildren.isEmpty()) {
        List working = new NodeList(nextLevelChildren);
        nextLevelChildren = new NodeList();
        for (Object child : working) {
            if (preorder) {
                callClosureForNode(c, child, level);
            } else {
                stack.push(new Tuple2<Object, Integer>(child, level));
            }
            if (child instanceof Node) {
                Node childNode = (Node) child;
                List children = childNode.getDirectChildren();
                if (children.size() > 1 || (children.size() == 1 && !(children.get(0) instanceof String))) nextLevelChildren.addAll(preorder ? children : DefaultGroovyMethods.reverse(children));
            }
        }
        level++;
    }
    while (!stack.isEmpty()) {
        Tuple2<Object, Integer> next = stack.pop();
        callClosureForNode(c, next.getV1(), next.getV2());
    }
}
 
Example #2
Source Project: Pushjet-Android   Author: Pushjet   File: DefaultRepositoryHandler.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
public DependencyResolver mavenRepo(Map<String, ?> args, Closure configClosure) {
    DeprecationLogger.nagUserOfReplacedMethod("RepositoryHandler.mavenRepo()", "maven()");
    Map<String, Object> modifiedArgs = new HashMap<String, Object>(args);
    if (modifiedArgs.containsKey("urls")) {
        List<?> urls = flattenCollections(modifiedArgs.remove("urls"));
        if (!urls.isEmpty()) {
            modifiedArgs.put("url", urls.get(0));
            List<?> extraUrls = urls.subList(1, urls.size());
            modifiedArgs.put("artifactUrls", extraUrls);
        }
    }

    MavenArtifactRepository repository = repositoryFactory.createMavenRepository();
    ConfigureUtil.configureByMap(modifiedArgs, repository);
    DependencyResolver resolver = repositoryFactory.toResolver(repository);
    ConfigureUtil.configure(configClosure, resolver);
    addRepository(repositoryFactory.createResolverBackedRepository(resolver), "mavenRepo");
    return resolver;
}
 
Example #3
Source Project: groovy-cps   Author: cloudbees   File: Continuable.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Resumes this program by either returning the value from {@link Continuable#suspend(Object)} or
 * throwing an exception
 */
public Outcome run0(final Outcome cn, List<Class> categories) {
    return GroovyCategorySupport.use(categories, new Closure<Outcome>(null) {
        @Override
        public Outcome call() {
            Next n = cn.resumeFrom(e,k);

            while(n.yield==null) {
                if (interrupt!=null) {
                    // TODO: correctly reporting a source location requires every block to have the line number
                    n = new Next(new ThrowBlock(UNKNOWN, new ConstantBlock(interrupt), true),n.e,n.k);
                    interrupt = null;
                }
                n = n.step();
            }

            e = n.e;
            k = n.k;

            return n.yield;
        }
    });
}
 
Example #4
public <U extends T> void registerFactory(Class<U> type, final Closure<? extends U> factory) {
    registerFactory(type, new NamedDomainObjectFactory<U>() {
        public U create(String name) {
            return factory.call(name);
        }
    });
}
 
Example #5
Source Project: spring-cloud-contract   Author: spring-cloud   File: Contract.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Groovy point of entry to build a contract. Left for backward compatibility reasons.
 * @param closure function to manipulate the contract
 * @return manipulated contract
 */
public static Contract make(@DelegatesTo(Contract.class) Closure closure) {
	Contract dsl = new Contract();
	closure.setDelegate(dsl);
	closure.call();
	Contract.assertContract(dsl);
	return dsl;
}
 
Example #6
Source Project: arcusplatform   Author: arcus-smart-home   File: BaseDispatchClosure.java    License: Apache License 2.0 5 votes vote down vote up
protected void addHandler(MessageType messageType, String event, String parameter, Closure<?> closure) {
   IpcdDispatchMatcher matcher = new IpcdDispatchMatcher();
   matcher.setType(messageType);
   matcher.setEvent(event);
   matcher.setParameter(parameter);
   matcher.setHandler(DriverBinding.wrapAsHandler(closure));
   binding.getBuilder().addEventMatcher(matcher);
}
 
Example #7
Source Project: Pushjet-Android   Author: Pushjet   File: DefaultManifest.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
public DefaultManifest from(Object mergePaths, Closure closure) {
    DefaultManifestMergeSpec mergeSpec = new DefaultManifestMergeSpec();
    mergeSpec.from(mergePaths);
    manifestMergeSpecs.add(mergeSpec);
    ConfigureUtil.configure(closure, mergeSpec);
    return this;
}
 
Example #8
Source Project: Pushjet-Android   Author: Pushjet   File: TaskFactory.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
public TaskInternal createTask(Map<String, ?> args) {
    Map<String, Object> actualArgs = new HashMap<String, Object>(args);
    checkTaskArgsAndCreateDefaultValues(actualArgs);

    String name = actualArgs.get(Task.TASK_NAME).toString();
    if (!GUtil.isTrue(name)) {
        throw new InvalidUserDataException("The task name must be provided.");
    }

    Class<? extends TaskInternal> type = (Class) actualArgs.get(Task.TASK_TYPE);
    Boolean generateSubclass = Boolean.valueOf(actualArgs.get(GENERATE_SUBCLASS).toString());
    TaskInternal task = createTaskObject(project, type, name, generateSubclass);

    Object dependsOnTasks = actualArgs.get(Task.TASK_DEPENDS_ON);
    if (dependsOnTasks != null) {
        task.dependsOn(dependsOnTasks);
    }
    Object description = actualArgs.get(Task.TASK_DESCRIPTION);
    if (description != null) {
        task.setDescription(description.toString());
    }
    Object group = actualArgs.get(Task.TASK_GROUP);
    if (group != null) {
        task.setGroup(group.toString());
    }
    Object action = actualArgs.get(Task.TASK_ACTION);
    if (action instanceof Action) {
        Action<? super Task> taskAction = (Action<? super Task>) action;
        task.doFirst(taskAction);
    } else if (action != null) {
        Closure closure = (Closure) action;
        task.doFirst(closure);
    }

    return task;
}
 
Example #9
Source Project: Pushjet-Android   Author: Pushjet   File: Test.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
public TestFramework testFramework(Closure testFrameworkConfigure) {
    if (testFramework == null) {
        useJUnit(testFrameworkConfigure);
    }

    return testFramework;
}
 
Example #10
Source Project: brooklyn-server   Author: apache   File: DependentConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @deprecated since 0.11.0; explicit groovy utilities/support will be deleted.
 */
@Deprecated
public static <T,V> Task<V> attributePostProcessedWhenReady(Entity source, AttributeSensor<T> sensor, Closure<Boolean> ready, Closure<V> postProcess) {
    Predicate<? super T> readyPredicate = (ready != null) ? GroovyJavaMethods.predicateFromClosure(ready) : JavaGroovyEquivalents.groovyTruthPredicate();
    Function<? super T, V> postProcessFunction = GroovyJavaMethods.<T,V>functionFromClosure(postProcess);
    return attributePostProcessedWhenReady(source, sensor, readyPredicate, postProcessFunction);
}
 
Example #11
Source Project: Pushjet-Android   Author: Pushjet   File: DefaultDependencyFactory.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
public ClientModule createModule(Object dependencyNotation, Closure configureClosure) {
    ClientModule clientModule = clientModuleNotationParser.parseNotation(dependencyNotation);
    ModuleFactoryDelegate moduleFactoryDelegate = new ModuleFactoryDelegate(clientModule, this);
    moduleFactoryDelegate.prepareDelegation(configureClosure);
    if (configureClosure != null) {
        configureClosure.call();
    }
    return clientModule;
}
 
Example #12
Source Project: groovy   Author: apache   File: StringGroovyMethodsTest.java    License: Apache License 2.0 5 votes vote down vote up
private Closure<String> createClosureForFindOrFindAll() {
    return new Closure<String>(this) {
        @Override
        public String call(Object arguments) {
            assertTrue(arguments instanceof List);
            return ((List) arguments).get(2).toString();
        }

        @Override
        public String call(Object... args) {
            return call((Object) args);
        }
    };
}
 
Example #13
Source Project: groovy   Author: apache   File: IOGroovyMethods.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Filter the lines from this Reader, and return a Writable which can be
 * used to stream the filtered lines to a destination.  The closure should
 * return <code>true</code> if the line should be passed to the writer.
 *
 * @param reader  this reader
 * @param closure a closure used for filtering
 * @return a Writable which will use the closure to filter each line
 *         from the reader when the Writable#writeTo(Writer) is called.
 * @since 1.0
 */
public static Writable filterLine(Reader reader, @ClosureParams(value=SimpleType.class, options="java.lang.String") final Closure closure) {
    final BufferedReader br = new BufferedReader(reader);
    return new Writable() {
        public Writer writeTo(Writer out) throws IOException {
            BufferedWriter bw = new BufferedWriter(out);
            String line;
            BooleanClosureWrapper bcw = new BooleanClosureWrapper(closure);
            while ((line = br.readLine()) != null) {
                if (bcw.call(line)) {
                    bw.write(line);
                    bw.newLine();
                }
            }
            bw.flush();
            return out;
        }

        public String toString() {
            Writer buffer = new StringBuilderWriter();
            try {
                writeTo(buffer);
            } catch (IOException e) {
                throw new StringWriterIOException(e);
            }
            return buffer.toString();
        }
    };
}
 
Example #14
Source Project: Pushjet-Android   Author: Pushjet   File: DefaultCopySpec.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
public CopySpec filter(final Closure closure) {
    actions.add(new Action<FileCopyDetails>() {
        public void execute(FileCopyDetails fileCopyDetails) {
            fileCopyDetails.filter(closure);
        }
    });
    return this;
}
 
Example #15
Source Project: bazel   Author: bazelbuild   File: ProGuardTask.java    License: Apache License 2.0 5 votes vote down vote up
public void keepclassmembers(Map     keepClassSpecificationArgs,
                             Closure classMembersClosure)
throws ParseException
{
    configuration.keep =
        extendClassSpecifications(configuration.keep,
        createKeepClassSpecification(false,
                                     false,
                                     false,
                                     keepClassSpecificationArgs,
                                     classMembersClosure));
}
 
Example #16
Source Project: smarthome   Author: eclipse-archived   File: OSGiTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
protected void setDefaultLocale(Locale locale) throws Exception {
    assertThat(locale, is(notNullValue()));

    ConfigurationAdmin configAdmin = (ConfigurationAdmin) getService(
            Class.forName("org.osgi.service.cm.ConfigurationAdmin"));
    assertThat(configAdmin, is(notNullValue()));

    LocaleProvider localeProvider = (LocaleProvider) getService(
            Class.forName("org.eclipse.smarthome.core.i18n.LocaleProvider"));
    assertThat(localeProvider, is(notNullValue()));

    Configuration config = configAdmin.getConfiguration("org.eclipse.smarthome.core.i18nprovider", null);
    assertThat(config, is(notNullValue()));

    Dictionary<String, Object> properties = config.getProperties();
    if (properties == null) {
        properties = new Hashtable<>();
    }

    properties.put("language", locale.getLanguage());
    properties.put("script", locale.getScript());
    properties.put("region", locale.getCountry());
    properties.put("variant", locale.getVariant());

    config.update(properties);

    waitForAssert(new Closure<Object>(null) {
        private static final long serialVersionUID = -5083904877474902686L;

        public Object doCall() {
            assertThat(localeProvider.getLocale(), is(locale));
            return null;
        }
    });
}
 
Example #17
Source Project: Pushjet-Android   Author: Pushjet   File: AbstractGradleExecuter.java    License: BSD 2-Clause "Simplified" License 4 votes vote down vote up
public void afterExecute(Closure action) {
    afterExecute.add(new ClosureBackedAction<GradleExecuter>(action));
}
 
Example #18
Source Project: Pushjet-Android   Author: Pushjet   File: DefaultSourceSet.java    License: BSD 2-Clause "Simplified" License 4 votes vote down vote up
public SourceSet java(Closure configureClosure) {
    ConfigureUtil.configure(configureClosure, getJava());
    return this;
}
 
Example #19
Source Project: pushfish-android   Author: PushFish   File: DefaultDomainObjectCollection.java    License: BSD 2-Clause "Simplified" License 4 votes vote down vote up
protected <S extends Collection<? super T>> S findAll(Closure cl, S matches) {
    for (T t : filteredStore(createFilter(Specs.<Object>convertClosureToSpec(cl)))) {
        matches.add(t);
    }
    return matches;
}
 
Example #20
Source Project: mdw   Author: CenturyLinkCloud   File: TestCaseScript.java    License: Apache License 2.0 4 votes vote down vote up
public TestCaseActivityStub activity(Closure<Boolean> matcher, Closure<String> completer) throws TestException {
    return new TestCaseActivityStub(matcher, completer);
}
 
Example #21
Source Project: groovy   Author: apache   File: ClosureStaticMetaMethod.java    License: Apache License 2.0 4 votes vote down vote up
public ClosureStaticMetaMethod(String name, Class declaringClass, Closure c, Class[] paramTypes) {
    super(paramTypes);
    this.callable = c;
    this.declaringClass = ReflectionCache.getCachedClass(declaringClass);
    this.name = name;
}
 
Example #22
Source Project: pushfish-android   Author: PushFish   File: DelegatingDomainObjectSet.java    License: BSD 2-Clause "Simplified" License 4 votes vote down vote up
public DomainObjectSet<T> matching(Closure spec) {
    return backingSet.matching(spec);
}
 
Example #23
private boolean isConfigureMethod(String name, Object... arguments) {
    return (arguments.length == 1 && arguments[0] instanceof Closure
            || arguments.length == 1 && arguments[0] instanceof Class
            || arguments.length == 2 && arguments[0] instanceof Class && arguments[1] instanceof Closure)
            && hasProperty(name);
}
 
Example #24
Source Project: kan-java   Author: pfmiles   File: VisitAssertHook.java    License: Eclipse Public License 1.0 4 votes vote down vote up
void afterVisitDetail(AssertTree node, List<ErrMsg> errMsgs, GlobalContext ctx, Closure<List<Map<String, Long>>> resolveRowAndCol,
Closure<Void> setError);
 
Example #25
Source Project: groovy   Author: apache   File: Tt1cgo.java    License: Apache License 2.0 4 votes vote down vote up
public Closure getX() {
    return this.p1;
}
 
Example #26
Source Project: groovy   Author: apache   File: ComposedClosure.java    License: Apache License 2.0 4 votes vote down vote up
public void setResolveStrategy(int resolveStrategy) {
    ((Closure) getOwner()).setResolveStrategy(resolveStrategy);
    second.setResolveStrategy(resolveStrategy);
}
 
Example #27
Source Project: pushfish-android   Author: PushFish   File: DefaultComponentSelectionRules.java    License: BSD 2-Clause "Simplified" License 4 votes vote down vote up
public ComponentSelectionRules all(Closure<?> closure) {
    return addRule(createAllSpecRulesAction(ruleActionAdapter.createFromClosure(ComponentSelection.class, closure)));
}
 
Example #28
Source Project: groovy   Author: apache   File: FactoryBuilderSupport.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * @return the explicit methods map (Unmodifiable Map).
 */
public Map<String, Closure> getLocalExplicitMethods() {
    return Collections.unmodifiableMap(explicitMethods);
}
 
Example #29
Source Project: pushfish-android   Author: PushFish   File: DefaultResolutionResult.java    License: BSD 2-Clause "Simplified" License 4 votes vote down vote up
public void allDependencies(final Closure closure) {
    allDependencies(new ClosureBackedAction<DependencyResult>(closure));
}
 
Example #30
Source Project: gradle-plugins   Author: freefair   File: WarOverlay.java    License: MIT License 4 votes vote down vote up
public CopySpec include(Closure includeSpec) {
    return getWarCopySpec().include(includeSpec);
}