Java 类groovy.lang.Closure 实例源码

项目:Reer    文件:ClosureBackedAction.java   
public void execute(T delegate) {
    if (closure == null) {
        return;
    }

    try {
        if (configureableAware && delegate instanceof Configurable) {
            ((Configurable) delegate).configure(closure);
        } else {
            Closure copy = (Closure) closure.clone();
            copy.setResolveStrategy(resolveStrategy);
            copy.setDelegate(delegate);
            if (copy.getMaximumNumberOfParameters() == 0) {
                copy.call();
            } else {
                copy.call(delegate);
            }
        }
    } catch (groovy.lang.MissingMethodException e) {
        if (Objects.equal(e.getType(), closure.getClass()) && Objects.equal(e.getMethod(), "doCall")) {
            throw new InvalidActionClosureException(closure, delegate);
        }
        throw e;
    }
}
项目:Reer    文件:DefaultDependencyHandler.java   
public Object methodMissing(String name, Object args) {
    Object[] argsArray = (Object[]) args;
    Configuration configuration = configurationContainer.findByName(name);
    if (configuration == null) {
        throw new MissingMethodException(name, this.getClass(), argsArray);
    }

    List<?> normalizedArgs = CollectionUtils.flattenCollections(argsArray);
    if (normalizedArgs.size() == 2 && normalizedArgs.get(1) instanceof Closure) {
        return doAdd(configuration, normalizedArgs.get(0), (Closure) normalizedArgs.get(1));
    } else if (normalizedArgs.size() == 1) {
        return doAdd(configuration, normalizedArgs.get(0), null);
    } else {
        for (Object arg : normalizedArgs) {
            doAdd(configuration, arg, null);
        }
        return null;
    }
}
项目:gradle-lazy-credentials    文件:LazyCredentialsExtension.java   
@Override
public LazyCredentialsExtension configure(Closure c) {
    if (!Closure.class.isInstance(c.getDelegate()) ||
        DefaultMavenArtifactRepository.class.isInstance(((Closure)c.getDelegate()))) {
        throw new IllegalStateException("This extension can only be used in maven repository config.");
    }

    LazyCredentials credentials = new LazyCredentials(project);

    Object originalDelegate = ((Closure)c.getDelegate()).getDelegate();
    c.setResolveStrategy(Closure.DELEGATE_FIRST);
    c.setDelegate(credentials);
    c.call();

    ((DefaultMavenArtifactRepository) originalDelegate).setConfiguredCredentials(credentials);
    return this;
}
项目:Reer    文件:SigningExtension.java   
/**
 * Signs the POM artifact for the given Maven deployment.
 *
 * <p>You can use this method to sign the generated POM when publishing to a Maven repository with the Maven plugin. </p> <pre autoTested=''> uploadArchives { repositories { mavenDeployer {
 * beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) } } } } </pre> <p>You can optionally provide a configuration closure to fine tune the {@link SignOperation sign
 * operation} for the POM.</p> <p> If {@link #isRequired()} is false and the signature cannot be generated (e.g. no configured signatory), this method will silently do nothing. That is, a
 * signature for the POM file will not be uploaded.
 *
 * @param mavenDeployment The deployment to sign the POM of
 * @param closure the configuration of the underlying {@link SignOperation sign operation} for the POM (optional)
 * @return the generated signature artifact
 */
public Signature signPom(final MavenDeployment mavenDeployment, final Closure closure) {
    SignOperation signOperation = doSignOperation(new Action<SignOperation>() {
        public void execute(SignOperation so) {
            so.sign(mavenDeployment.getPomArtifact());
            so.configure(closure);
        }
    });

    Signature pomSignature = signOperation.getSingleSignature();
    if (!pomSignature.getFile().exists()) {
        // This means that the signature was not required and we couldn't generate the signature
        // (most likely project.required == false and there is no signatory)
        // So just noop
        return null;
    }

    // Have to alter the "type" of the artifact to match what is published
    // See https://issues.gradle.org/browse/GRADLE-1589
    pomSignature.setType("pom." + pomSignature.getSignatureType().getExtension());
    mavenDeployment.addArtifact(pomSignature);
    return pomSignature;
}
项目:Reer    文件:DefaultConfigurableFileTree.java   
public WorkResult copy(final Closure closure) {
    return fileCopier.copy(new Action<CopySpec>() {
        public void execute(CopySpec copySpec) {
            copySpec.from(DefaultConfigurableFileTree.this);
            ConfigureUtil.configure(closure, copySpec);
        }
    });
}
项目:Reer    文件:DefaultManifest.java   
@Override
public DefaultManifest from(Object mergePaths, Closure<?> closure) {
    DefaultManifestMergeSpec mergeSpec = new DefaultManifestMergeSpec();
    mergeSpec.from(mergePaths);
    manifestMergeSpecs.add(mergeSpec);
    ConfigureUtil.configure(closure, mergeSpec);
    return this;
}
项目:Reer    文件:PatternSetAntBuilderDelegate.java   
private static Object logical(Object node, String op, final Action<Object> withNode) {
    GroovyObject groovyObject = (GroovyObject) node;
    groovyObject.invokeMethod(op, new Closure(null, null) {
        void doCall() {
            withNode.execute(getDelegate());
        }
    });
    return node;
}
项目:grooves    文件:GroovyEventsDsl.java   
/**
 * Allows executing a consumer with some context to setup events.
 *
 * @param aggregate         The aggregate on which the consumer must operate
 * @param entityConsumer    A Consumer that decides what happens when apply is called on an
 *                          entity
 * @param positionSupplier  A supplier which offers the default position number for an event
 *                          when it is not provided
 * @param timestampSupplier A supplier that provides the date for an event if it isn't set
 * @param closure           The block of code to execute with the aggregate
 *
 * @return The aggregate after all the code has been executed
 */
public AggregateT on(
        AggregateT aggregate, Consumer entityConsumer, Supplier<Long> positionSupplier,
        Supplier<Date> timestampSupplier, @DelegatesTo(OnSpec.class) Closure closure) {

    OnSpec<AggregateT, EventIdT, EventT, ?, ?> spec = new OnSpec<>();
    spec.setAggregate(aggregate);
    spec.setEntityConsumer(entityConsumer);
    spec.setTimestampSupplier(timestampSupplier);
    spec.setPositionSupplier(positionSupplier);
    closure.setDelegate(spec);
    closure.call(spec);
    return aggregate;
}
项目:Reer    文件:DefaultDependencyFactory.java   
public ClientModule createModule(Object dependencyNotation, Closure configureClosure) {
    ClientModule clientModule = clientModuleNotationParser.parseNotation(dependencyNotation);
    if (configureClosure != null) {
        configureModule(clientModule, configureClosure);
    }
    return clientModule;
}
项目:Reer    文件:DefaultIsolatedAntBuilder.java   
public void execute(final Closure antClosure) {
    classLoaderCache.withCachedClassLoader(libClasspath, gradleApiGroovyLoader, antAdapterGroovyLoader,
        new Factory<ClassLoader>() {
            @Override
            public ClassLoader create() {
                return new VisitableURLClassLoader(baseAntLoader, libClasspath);
            }
        }, new Action<CachedClassLoader>() {
            @Override
            public void execute(CachedClassLoader cachedClassLoader) {
                ClassLoader classLoader = cachedClassLoader.getClassLoader();
                Object antBuilder = newInstanceOf("org.gradle.api.internal.project.ant.BasicAntBuilder");
                Object antLogger = newInstanceOf("org.gradle.api.internal.project.ant.AntLoggingAdapter");

                // This looks ugly, very ugly, but that is apparently what Ant does itself
                ClassLoader originalLoader = Thread.currentThread().getContextClassLoader();
                Thread.currentThread().setContextClassLoader(classLoader);

                try {
                    configureAntBuilder(antBuilder, antLogger);

                    // Ideally, we'd delegate directly to the AntBuilder, but its Closure class is different to our caller's
                    // Closure class, so the AntBuilder's methodMissing() doesn't work. It just converts our Closures to String
                    // because they are not an instanceof its Closure class.
                    Object delegate = new AntBuilderDelegate(antBuilder, classLoader);
                    ClosureBackedAction.execute(delegate, antClosure);
                } finally {
                    Thread.currentThread().setContextClassLoader(originalLoader);
                    disposeBuilder(antBuilder, antLogger);
                }
            }
        });
}
项目:Reer    文件:DefaultSourceSet.java   
public SourceSet resources(Closure configureClosure) {
    return resources(ClosureBackedAction.of(configureClosure));
}
项目:Reer    文件:DefaultNamedDomainObjectCollection.java   
public T getByName(String name, Closure configureClosure) throws UnknownDomainObjectException {
    T t = getByName(name);
    ConfigureUtil.configure(configureClosure, t);
    return t;
}
项目:Reer    文件:DefaultTaskGraphExecuter.java   
public void beforeTask(final Closure closure) {
    taskListeners.add(new ClosureBackedMethodInvocationDispatch("beforeExecute", closure));
}
项目:Reer    文件:TypedDomainObjectContainerWrapper.java   
public U getByName(String name, Closure configureClosure) throws UnknownDomainObjectException {
    return delegate.getByName(name, configureClosure);
}
项目:Reer    文件:AndSpec.java   
@SuppressWarnings("unchecked")
public AndSpec<T> and(Closure spec) {
    return and(new ClosureSpec<T>(spec));
}
项目:Reer    文件:PatternSet.java   
public PatternSet include(Closure closure) {
    include(Specs.<FileTreeElement>convertClosureToSpec(closure));
    return this;
}
项目:Reer    文件:MapFileTree.java   
/**
 * Adds an element to this tree. The given closure is passed an OutputStream which it can use to write the content
 * of the element to.
 */
public void add(String path, Closure contentClosure) {
    Action<OutputStream> action = ConfigureUtil.configureUsing(contentClosure);
    add(path, action);
}
项目:lams    文件:GroovyBeanDefinitionReader.java   
/**
 * This method overrides method invocation to create beans for each method name that
 * takes a class argument.
 */
public Object invokeMethod(String name, Object arg) {
    Object[] args = (Object[])arg;
    if ("beans".equals(name) && args.length == 1 && args[0] instanceof Closure) {
        return beans((Closure) args[0]);
    }
    else if ("ref".equals(name)) {
        String refName;
        if (args[0] == null)
            throw new IllegalArgumentException("Argument to ref() is not a valid bean or was not found");

        if (args[0] instanceof RuntimeBeanReference) {
            refName = ((RuntimeBeanReference)args[0]).getBeanName();
        }
        else {
            refName = args[0].toString();
        }
        boolean parentRef = false;
        if (args.length > 1) {
            if (args[1] instanceof Boolean) {
                parentRef = (Boolean) args[1];
            }
        }
        return new RuntimeBeanReference(refName, parentRef);
    }
    else if (this.namespaces.containsKey(name) && args.length > 0 && (args[0] instanceof Closure)) {
        GroovyDynamicElementReader reader = createDynamicElementReader(name);
        reader.invokeMethod("doCall", args);
    }
    else if (args.length > 0 && args[0] instanceof Closure) {
        // abstract bean definition
        return invokeBeanDefiningMethod(name, args);
    }
    else if (args.length > 0 && (args[0] instanceof Class || args[0] instanceof RuntimeBeanReference || args[0] instanceof Map)) {
        return invokeBeanDefiningMethod(name, args);
    }
    else if (args.length > 1 && args[args.length -1] instanceof Closure) {
        return invokeBeanDefiningMethod(name, args);
    }
    MetaClass mc = DefaultGroovyMethods.getMetaClass(getRegistry());
    if (!mc.respondsTo(getRegistry(), name, args).isEmpty()){
        return mc.invokeMethod(getRegistry(), name, args);
    }
    return this;
}
项目:Reer    文件:DefaultJvmApiSpec.java   
@Override
public void dependencies(Closure<?> configureAction) {
    ConfigureUtil.configure(configureAction, dependencies);
}
项目:Reer    文件:AbstractNamedDomainObjectContainer.java   
public AbstractNamedDomainObjectContainer<T> configure(Closure configureClosure) {
    ConfigureDelegate delegate = createConfigureDelegate(configureClosure);
    ConfigureUtil.configureSelf(configureClosure, this, delegate);
    return this;
}
项目:Reer    文件:DefaultNamedDomainObjectSet.java   
@Override
public NamedDomainObjectSet<T> matching(Closure spec) {
    return matching(Specs.<T>convertClosureToSpec(spec));
}
项目:Reer    文件:BinaryTasksCollectionWrapper.java   
@SuppressWarnings("rawtypes")
@Override
public DomainObjectSet<Task> matching(Closure spec) {
    return delegate.matching(spec);
}
项目:Reer    文件:DelegatingDomainObjectSet.java   
public Set<T> findAll(Closure spec) {
    return backingSet.findAll(spec);
}
项目:Reer    文件:DefaultScript.java   
@Override
public void apply(Closure closure) {
    DefaultObjectConfigurationAction action = createObjectConfigurationAction();
    ConfigureUtil.configure(closure, action);
    action.execute();
}
项目:Reer    文件:DefaultConfigurableFileTree.java   
public DefaultConfigurableFileTree include(Closure includeSpec) {
    patternSet.include(includeSpec);
    return this;
}
项目:crnk-framework    文件:TSGeneratorExtension.java   
public TSNpmConfiguration npm(Closure closure) {
    return (TSNpmConfiguration) project.configure(getNpm(), closure);
}
项目:Reer    文件:DefaultTaskGraphExecuter.java   
public void afterTask(final Closure closure) {
    taskListeners.add(new ClosureBackedMethodInvocationDispatch("afterExecute", closure));
}
项目:Reer    文件:DefaultDomainObjectCollection.java   
public Collection<T> findAll(Closure cl) {
    return findAll(cl, new ArrayList<T>());
}
项目:Reer    文件:InitScript.java   
public void initscript(Closure configureClosure) {
    buildscript(configureClosure);
}
项目:Reer    文件:DelegatingCopySpecInternal.java   
public CopySpec exclude(Closure excludeSpec) {
    return getDelegateCopySpec().exclude(excludeSpec);
}
项目:Reer    文件:DefaultArtifactRepositoryContainer.java   
public DefaultArtifactRepositoryContainer configure(Closure closure) {
    return ConfigureUtil.configureSelf(closure, this);
}
项目:Reer    文件:DefaultProject.java   
public void allprojects(Closure configureClosure) {
    configure(getAllprojects(), configureClosure);
}
项目:Reer    文件:DelegatingDomainObjectSet.java   
public DomainObjectSet<T> matching(Closure spec) {
    return matching(Specs.convertClosureToSpec(spec));
}
项目:Reer    文件:ModelMapGroovyView.java   
public <S> void afterEach(Class<S> type, Closure<? super S> configAction) {
    afterEach(type, new ClosureBackedAction<S>(configAction));
}
项目:Reer    文件:DefaultMavenPom.java   
public DefaultMavenPom whenConfigured(final Closure closure) {
    whenConfiguredActions.add(ConfigureUtil.configureUsing(closure));
    return this;
}
项目:Reer    文件:DefaultMavenRepositoryHandlerConvention.java   
public MavenResolver mavenInstaller(Closure configureClosure) {
    return container.addRepository(createMavenInstaller(), DEFAULT_MAVEN_INSTALLER_NAME, ConfigureUtil.configureUsing(configureClosure));
}
项目:Reer    文件:RealizableTaskCollection.java   
@Override
public void whenObjectAdded(Closure action) {
    delegate.whenObjectAdded(action);
}
项目:Reer    文件:AbstractMavenResolver.java   
public MavenPom pom(String name, Closure configureClosure) {
    return pomFilterContainer.pom(name, configureClosure);
}
项目:Reer    文件:DefaultSourceDirectorySet.java   
public PatternFilterable include(Closure includeSpec) {
    patterns.include(includeSpec);
    return this;
}
项目:Reer    文件:BasePomFilterContainer.java   
public MavenPom addFilter(String name, Closure filter) {
    return addFilter(name, toFilter(filter));
}