groovy.lang.Closure Java Examples

The following examples show how to use groovy.lang.Closure. 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 File: Node.java    From groovy with 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 File: DefaultRepositoryHandler.java    From Pushjet-Android with 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 File: Continuable.java    From groovy-cps with 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
Source File: DependentConfiguration.java    From brooklyn-server with 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 #5
Source File: TaskFactory.java    From Pushjet-Android with 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 #6
Source File: DefaultManifest.java    From Pushjet-Android with 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 #7
Source File: BaseDispatchClosure.java    From arcusplatform with 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 #8
Source File: DefaultDependencyFactory.java    From Pushjet-Android with 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 #9
Source File: StringGroovyMethodsTest.java    From groovy with 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 #10
Source File: Contract.java    From spring-cloud-contract with 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 #11
Source File: IOGroovyMethods.java    From groovy with 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 #12
Source File: DefaultPolymorphicDomainObjectContainer.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
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 #13
Source File: DefaultCopySpec.java    From Pushjet-Android with 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 #14
Source File: ProGuardTask.java    From bazel with 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 #15
Source File: Test.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public TestFramework testFramework(Closure testFrameworkConfigure) {
    if (testFramework == null) {
        useJUnit(testFrameworkConfigure);
    }

    return testFramework;
}
 
Example #16
Source File: OSGiTest.java    From smarthome with 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 File: DefaultSourceSet.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public SourceSet java(Closure configureClosure) {
    ConfigureUtil.configure(configureClosure, getJava());
    return this;
}
 
Example #18
Source File: CapabilityEnvironmentBinding.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
public void getAttributes(Closure<?> closure) {
   builder.addGetAttributesProvider(closure);
}
 
Example #19
Source File: DefaultComponentMetadataHandler.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
private void executeRuleClosures(ModuleComponentResolveMetaData metadata, ComponentMetadataDetails details) {
    for (Closure<?> closure : ruleClosures) {
        executeRuleClosure(metadata, details, closure);
    }
}
 
Example #20
Source File: AbstractMavenResolver.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public MavenPom addFilter(String name, Closure filter) {
    return pomFilterContainer.addFilter(name, filter);
}
 
Example #21
Source File: AbstractProject.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public void repositories(Closure configureClosure) {
    ConfigureUtil.configure(configureClosure, getRepositories());
}
 
Example #22
Source File: ClosureToSpecNotationParser.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public Spec<T> parseNotation(Object notation) throws UnsupportedNotationException {
    if (notation instanceof Closure) {
        return Specs.convertClosureToSpec((Closure) notation);
    }
    throw new UnsupportedNotationException(notation);
}
 
Example #23
Source File: DefaultConfiguration.java    From pushfish-android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public FileCollection fileCollection(Closure dependencySpecClosure) {
    return new ConfigurationFileCollection(dependencySpecClosure);
}
 
Example #24
Source File: ErrorHandlingArtifactDependencyResolver.java    From pushfish-android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public void allDependencies(Closure closure) {
    resolutionResult.allDependencies(closure);
}
 
Example #25
Source File: CliExecExtension.java    From gradle-plugins with Apache License 2.0 4 votes vote down vote up
public ExecResult exec(Closure<CliExecSpec> closure) {
	CliExecSpec spec = new CliExecSpec();
	project.configure(spec, closure);
	return exec(spec);
}
 
Example #26
Source File: DefaultDomainObjectCollection.java    From pushfish-android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public void whenObjectAdded(Closure action) {
    whenObjectAdded(toAction(action));
}
 
Example #27
Source File: AbstractCopyTask.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
public AbstractCopyTask eachFile(Closure closure) {
    getMainSpec().eachFile(closure);
    return this;
}
 
Example #28
Source File: DefaultGradle.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public void settingsEvaluated(Closure closure) {
    buildListenerBroadcast.add(new ClosureBackedMethodInvocationDispatch("settingsEvaluated", closure));
}
 
Example #29
Source File: PatternSet.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public PatternSet include(Closure closure) {
    include(Specs.<FileTreeElement>convertClosureToSpec(closure));
    return this;
}
 
Example #30
Source File: AbstractFileCollection.java    From pushfish-android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public FileCollection filter(Closure filterClosure) {
    return filter(Specs.convertClosureToSpec(filterClosure));
}