Java Code Examples for groovy.lang.Closure#call()

The following examples show how to use groovy.lang.Closure#call() . 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: ObjectGraphBuilder.java    From groovy with Apache License 2.0 6 votes vote down vote up
/**
 * 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();
    }
}
 
Example 2
Source File: ResourceGroovyMethods.java    From groovy with Apache License 2.0 6 votes vote down vote up
/**
 * 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. Whether the closure is called is determined by whether
 * the file was a normal file or subdirectory and the value of fileType.
 *
 * @param self     a File (that happens to be a folder/directory)
 * @param fileType if normal files or directories or both should be processed
 * @param closure  the closure to invoke on each file
 * @throws FileNotFoundException    if the given directory does not exist
 * @throws IllegalArgumentException if the provided File object does not represent a directory
 * @since 1.7.1
 */
public static void eachFileRecurse(final File self, final FileType fileType, @ClosureParams(value = SimpleType.class, options = "java.io.File") final Closure closure)
        throws FileNotFoundException, IllegalArgumentException {
    checkDir(self);
    final File[] files = self.listFiles();
    // null check because of http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4803836
    if (files == null) return;
    for (File file : files) {
        if (file.isDirectory()) {
            if (fileType != FileType.FILES) closure.call(file);
            eachFileRecurse(file, fileType, closure);
        } else if (fileType != FileType.DIRECTORIES) {
            closure.call(file);
        }
    }
}
 
Example 3
Source File: DefaultTaskInputs.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private Object unwrap(Object value) {
    while (true) {
        if (value instanceof Callable) {
            Callable callable = (Callable) value;
            try {
                value = callable.call();
            } catch (Exception e) {
                throw UncheckedException.throwAsUncheckedException(e);
            }
        } else if (value instanceof Closure) {
            Closure closure = (Closure) value;
            value = closure.call();
        } else if (value instanceof FileCollection) {
            FileCollection fileCollection = (FileCollection) value;
            return fileCollection.getFiles();
        } else {
            return value;
        }
    }
}
 
Example 4
Source File: IOGroovyMethods.java    From groovy with Apache License 2.0 6 votes vote down vote up
/**
 * Allows this writer to be used within the closure, ensuring that it
 * is flushed and closed before this method returns.
 *
 * @param writer  the writer which is used and then closed
 * @param closure the closure that the writer is passed into
 * @return the value returned by the closure
 * @throws IOException if an IOException occurs.
 * @since 1.5.2
 */
public static <T> T withWriter(Writer writer, @ClosureParams(FirstParam.class) Closure<T> closure) throws IOException {
    try {
        T result = closure.call(writer);

        try {
            writer.flush();
        } catch (IOException e) {
            // try to continue even in case of error
        }
        Writer temp = writer;
        writer = null;
        temp.close();
        return result;
    } finally {
        closeWithWarning(writer);
    }
}
 
Example 5
Source File: GroovySessionFile.java    From nifi with Apache License 2.0 5 votes vote down vote up
public GroovySessionFile withReader(String charset, Closure c) throws IOException, UnsupportedCharsetException {
    InputStream inStream = session.read(this);
    BufferedReader br = new BufferedReader(new InputStreamReader(inStream, charset));
    c.call(br);
    br.close();
    return this;
}
 
Example 6
Source File: JsonDelegate.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Factory method for creating <code>JsonDelegate</code>s from closures.
 *
 * @param c closure representing JSON objects
 * @return an instance of <code>JsonDelegate</code>
 */
public static Map<String, Object> cloneDelegateAndGetContent(Closure<?> c) {
    JsonDelegate delegate = new JsonDelegate();
    Closure<?> cloned = (Closure<?>) c.clone();
    cloned.setDelegate(delegate);
    cloned.setResolveStrategy(Closure.DELEGATE_FIRST);
    cloned.call();

    return delegate.getContent();
}
 
Example 7
Source File: DateUtilExtensions.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Iterates from the date represented by this calendar up to the date represented
 * by the given calendar, inclusive, incrementing by one day each time.
 *
 * @param self    a Calendar
 * @param to      another Calendar to go up to
 * @param closure the closure to call
 * @since 2.2
 */
public static void upto(Calendar self, Calendar to, Closure closure) {
    if (self.compareTo(to) <= 0) {
        for (Calendar i = (Calendar) self.clone(); i.compareTo(to) <= 0; i = next(i)) {
            closure.call(i);
        }
    } else
        throw new GroovyRuntimeException("The argument (" + to +
                ") to upto() cannot be earlier than the value (" + self + ") it's called on.");
}
 
Example 8
Source File: ReflexMatchContext.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
public void delay(Closure<?> config) {
   ReflexDelayContext ctx = new ReflexDelayContext(this);
   try (ReflexActionPop pop = new ReflexActionPop(ctx)) {
      config.setDelegate(ctx);
      config.call();
   } finally {
      addAction(ctx.delayed);
   }
}
 
Example 9
Source File: GroovyIndicatorValue.java    From java-trader with Apache License 2.0 5 votes vote down vote up
public GroovyIndicatorValue forEach(Closure closure) {
    BarSeries series = indicator.getBarSeries();
    List<Num> values = new ArrayList<>(series.getBarCount());
    for(int i=series.getBeginIndex(); i<=series.getEndIndex();i++) {
        Num num = indicator.getValue(i);
        Number n = (Number)closure.call(num.getDelegate());
        values.add(series.function().apply(n));
    }
    return new GroovyIndicatorValue(new SimpleIndicator(series, values));
}
 
Example 10
Source File: HttpBuilder.java    From http-builder-ng with Apache License 2.0 5 votes vote down vote up
private ChainedHttpConfig configureRequest(final Class<?> type, final HttpVerb verb, final Closure closure) {
    final HttpConfigs.BasicHttpConfig myConfig = HttpConfigs.requestLevel(getObjectConfig());
    closure.setDelegate(myConfig);
    closure.setResolveStrategy(Closure.DELEGATE_FIRST);
    closure.call();

    myConfig.getChainedRequest().setVerb(verb);
    myConfig.getChainedResponse().setType(type);

    return myConfig;
}
 
Example 11
Source File: SwarmExtension.java    From ARCHIVE-wildfly-swarm with Apache License 2.0 5 votes vote down vote up
public void properties(Closure<Properties> closure) {
    ConfigObject config = new ConfigObject();
    closure.setResolveStrategy(Closure.DELEGATE_ONLY);
    closure.setDelegate(config);
    closure.call();
    config.flatten(this.properties);
}
 
Example 12
Source File: GroovyJavaMethods.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public static <T> Predicate<T> predicateFromClosure(final Closure<Boolean> job) {
    return new Predicate<T>() {
        @Override
        public boolean apply(Object input) {
            return job.call(input);
        }
    };
}
 
Example 13
Source File: ClojureScriptBuild.java    From clojurephant with Apache License 2.0 4 votes vote down vote up
public void compiler(Closure<?> configureAction) {
  configureAction.setResolveStrategy(Closure.DELEGATE_FIRST);
  configureAction.setDelegate(compiler);
  configureAction.call(compiler);
}
 
Example 14
Source File: ZigbeeContext.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
public void call(Closure<?> configClosure) {
   configClosure.setDelegate(configContext);
   configClosure.call();
}
 
Example 15
Source File: GolangTaskSupport.java    From gradle-golang-plugin with Mozilla Public License 2.0 4 votes vote down vote up
protected void runAfter() throws Exception {
    final Closure<?> after = _after;
    if (after != null) {
        after.call();
    }
}
 
Example 16
Source File: ReflexMatchContext.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
public void on(Map<String,Object> vals, Closure<?> action) {
   action.call(new Object[] { getProtocolMatchProcessor(), vals });
}
 
Example 17
Source File: JUnit4GroovyMockery.java    From pushfish-android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
void closureInit(Closure cl, Object delegate) {
    cl.setDelegate(delegate);
    cl.call();
}
 
Example 18
Source File: Response.java    From spring-cloud-contract with Apache License 2.0 4 votes vote down vote up
/**
 * Allows to configure HTTP headers.
 * @param consumer function to manipulate the URL
 */
public void headers(@DelegatesTo(Headers.class) Closure consumer) {
	this.headers = new Response.ResponseHeaders();
	consumer.setDelegate(this.headers);
	consumer.call();
}
 
Example 19
Source File: TestCaseScript.java    From mdw with Apache License 2.0 4 votes vote down vote up
/**
 * responder closure call is delayed until stub server calls back
 */
public TestCaseAdapterStub adapter(Closure<Boolean> matcher, Closure<String> responder, Closure<?> init) throws TestException {
    final TestCaseAdapterStub adapterStub = new TestCaseAdapterStub(matcher, responder);
    if (init != null) {
        init.setResolveStrategy(Closure.DELEGATE_FIRST);
        init.setDelegate(adapterStub);
        init.call();
    }
    if (responder == null) {
        adapterStub.setResponder(new Closure<String>(this, adapterStub) {
            @Override
            public String call(Object request) {
                // binding for request
                final TestCaseRun testCaseRun = getTestCaseRun();
                if (adapterStub.getResponse().contains("${")) {
                    try {
                        Binding binding = getBinding();
                        if (request.toString().startsWith("{")) {
                            Object req = new JsonSlurper().parseText(request.toString());
                            binding.setVariable("request", req);
                        }
                        else {
                            GPathResult gpathRequest = new XmlSlurper().parseText(request.toString());
                            binding.setVariable("request", gpathRequest);
                        }
                        CompilerConfiguration compilerCfg = new CompilerConfiguration();
                        compilerCfg.setScriptBaseClass(DelegatingScript.class.getName());
                        GroovyShell shell = new GroovyShell(TestCaseScript.class.getClassLoader(), binding, compilerCfg);
                        shell.setProperty("out", testCaseRun.getLog());
                        DelegatingScript script = (DelegatingScript) shell.parse("return \"\"\"" + adapterStub.getResponse() + "\"\"\"");
                        script.setDelegate(TestCaseScript.this);
                        return script.run().toString();
                    }
                    catch (Exception ex) {
                        getTestCaseRun().getLog().println("Cannot perform stub substitutions for request: " + request);
                        ex.printStackTrace(getTestCaseRun().getLog());
                    }
                }
                return adapterStub.getResponse();
            }
        });
    }
    return adapterStub;
}
 
Example 20
Source File: StringGroovyMethods.java    From groovy with Apache License 2.0 3 votes vote down vote up
/**
 * Iterates through the given CharSequence line by line, splitting each line using
 * the given separator Pattern.  The list of tokens for each line is then passed to
 * the given closure.
 *
 * @param self    a CharSequence
 * @param pattern the regular expression Pattern for the delimiter
 * @param closure a closure
 * @return the last value returned by the closure
 *
 * @since 1.8.2
 */
public static <T> T splitEachLine(final CharSequence self, final Pattern pattern, @ClosureParams(value=FromString.class,options={"List<String>","String[]"},conflictResolutionStrategy=PickFirstResolver.class) final Closure<T> closure) {
    T result = null;
    for (String line : new LineIterable(self)) {
        List vals = Arrays.asList(pattern.split(line));
        result = closure.call(vals);
    }
    return result;
}