private static Object writeCollectionWithClosure(Writer writer, Iterable coll, @DelegatesTo(StreamingJsonDelegate.class) Closure closure, JsonGenerator generator) throws IOException { writer.write(JsonOutput.OPEN_BRACKET); boolean first = true; for (Object it : coll) { if (!first) { writer.write(JsonOutput.COMMA); } else { first = false; } writeObject(writer, it, closure, generator); } writer.write(JsonOutput.CLOSE_BRACKET); return writer; }
/** * Configures the deployment descriptor for this EAR archive. * * <p>The given closure is executed to configure the deployment descriptor. The {@link DeploymentDescriptor} is passed to the closure as its delegate.</p> * * @param configureClosure The closure. * @return This. */ public Ear deploymentDescriptor(@DelegatesTo(value = DeploymentDescriptor.class, strategy = Closure.DELEGATE_FIRST) Closure configureClosure) { if (deploymentDescriptor == null) { deploymentDescriptor = getInstantiator().newInstance(DefaultDeploymentDescriptor.class, getFileResolver(), getInstantiator()); } ConfigureUtil.configure(configureClosure, deploymentDescriptor); return this; }
/** * 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; }
/** * Configures multipart request content using a Groovy closure (delegated to {@link MultipartContent}). * * @param closure the configuration closure * @return a configured instance of {@link MultipartContent} */ public static MultipartContent multipart(@DelegatesTo(MultipartContent.class) Closure closure) { MultipartContent content = new MultipartContent(); closure.setDelegate(content); closure.call(); return content; }
/** * If you use named arguments and a closure as last argument, * the key/value pairs of the map (as named arguments) * and the key/value pairs represented in the closure * will be merged together — * the closure properties overriding the map key/values * in case the same key is used. * * <pre class="groovyTestCase"> * new StringWriter().with { w -> * def json = new groovy.json.StreamingJsonBuilder(w) * json.person(name: "Tim", age: 35) { town "Manchester" } * * assert w.toString() == '{"person":{"name":"Tim","age":35,"town":"Manchester"}}' * } * </pre> * * @param name The name of the JSON object * @param map The attributes of the JSON object * @param callable Additional attributes of the JSON object represented by the closure * @throws IOException */ public void call(String name, Map map, @DelegatesTo(StreamingJsonDelegate.class) Closure callable) throws IOException { writer.write(JsonOutput.OPEN_BRACE); writer.write(generator.toJson(name)); writer.write(COLON_WITH_OPEN_BRACE); boolean first = true; for (Object it : map.entrySet()) { if (!first) { writer.write(JsonOutput.COMMA); } else { first = false; } Map.Entry entry = (Map.Entry) it; String key = entry.getKey().toString(); if (generator.isExcludingFieldsNamed(key)) { continue; } Object value = entry.getValue(); if (generator.isExcludingValues(value)) { return; } writer.write(generator.toJson(key)); writer.write(JsonOutput.COLON); writer.write(generator.toJson(value)); } StreamingJsonDelegate.cloneDelegateAndGetContent(writer, callable, map.size() == 0, generator); writer.write(DOUBLE_CLOSE_BRACKET); }
/** * Writes the name and value of a JSON attribute * * @param name The attribute name * @param value The value * @throws IOException */ public void call(String name, Object value, @DelegatesTo(StreamingJsonDelegate.class) Closure callable) throws IOException { if (generator.isExcludingFieldsNamed(name)) { return; } writeName(name); verifyValue(); writeObject(writer, value, callable, generator); }
/** * Writes the name and another JSON object * * @param name The attribute name * @param value The value * @throws IOException */ public void call(String name,@DelegatesTo(StreamingJsonDelegate.class) Closure value) throws IOException { if (generator.isExcludingFieldsNamed(name)) { return; } writeName(name); verifyValue(); writer.write(JsonOutput.OPEN_BRACE); StreamingJsonDelegate.cloneDelegateAndGetContent(writer, value, true, generator); writer.write(JsonOutput.CLOSE_BRACE); }
private static void cloneDelegateAndGetContent(Writer w, @DelegatesTo(StreamingJsonDelegate.class) Closure c, boolean first, JsonGenerator generator) { StreamingJsonDelegate delegate = new StreamingJsonDelegate(w, first, generator); Closure cloned = (Closure) c.clone(); cloned.setDelegate(delegate); cloned.setResolveStrategy(Closure.DELEGATE_FIRST); cloned.call(); }
private static void curryDelegateAndGetContent(Writer w, @DelegatesTo(StreamingJsonDelegate.class) Closure c, Object o, boolean first, JsonGenerator generator) { StreamingJsonDelegate delegate = new StreamingJsonDelegate(w, first, generator); Closure curried = c.curry(o); curried.setDelegate(delegate); curried.setResolveStrategy(Closure.DELEGATE_FIRST); curried.call(); }
public static EmbeddedApp build(@DelegatesTo(value = Spec.class, strategy = Closure.DELEGATE_FIRST) Closure<?> closure) { return new LaunchConfigEmbeddedApp() { @Override protected LaunchConfig createLaunchConfig() { final SpecWrapper spec = new SpecWrapper(); configureDelegateFirst(spec.getSpec(), closure); LaunchConfigBuilder launchConfigBuilder; if (spec.baseDirSupplier != null) { Path baseDirPath = spec.baseDirSupplier.get(); launchConfigBuilder = LaunchConfigBuilder.baseDir(baseDirPath); } else { launchConfigBuilder = LaunchConfigBuilder.noBaseDir(); } configureDelegateFirst(launchConfigBuilder.port(0), spec.launchConfig); final Action<? super BindingsSpec> bindingsAction = bindingsSpec -> configureDelegateFirst(new DefaultGroovyBindingsSpec(bindingsSpec), spec.bindings); return launchConfigBuilder.build(launchConfig -> { Guice.Builder builder = Guice.builder(launchConfig); if (spec.parentInjector != null) { builder.parent(spec.parentInjector); } return builder.bindings(bindingsAction).build(chain -> Groovy.chain(chain, spec.handlers)); }); } }; }
/** * Configures the reports to be generated by this task. */ public PmdReports reports(@DelegatesTo(value = PmdReports.class, strategy = Closure.DELEGATE_FIRST) Closure closure) { return reports(new ClosureBackedAction<PmdReports>(closure)); }
public void beforeExecute(@DelegatesTo(GradleExecuter.class) Closure action) { beforeExecute.add(new ClosureBackedAction<GradleExecuter>(action)); }
public void afterExecute(@DelegatesTo(GradleExecuter.class) Closure action) { afterExecute.add(new ClosureBackedAction<GradleExecuter>(action)); }
/** * Delegates to {@link #call(Iterable, Closure)} */ public Object call(Collection coll, @DelegatesTo(StreamingJsonDelegate.class) Closure c) throws IOException { return call((Iterable)coll, c); }
/** * Delegates to {@link #call(String, Iterable, Closure)} */ public void call(String name, Collection coll, @DelegatesTo(StreamingJsonDelegate.class) Closure c) throws IOException { call(name, (Iterable)coll, c); }
private void writeObjects(Iterable coll, @DelegatesTo(StreamingJsonDelegate.class) Closure c) throws IOException { verifyValue(); writeCollectionWithClosure(writer, coll, c, generator); }
public static Object writeCollectionWithClosure(Writer writer, Collection coll, @DelegatesTo(StreamingJsonDelegate.class) Closure closure) throws IOException { return writeCollectionWithClosure(writer, (Iterable)coll, closure, JsonOutput.DEFAULT_GENERATOR); }
public static void cloneDelegateAndGetContent(Writer w, @DelegatesTo(StreamingJsonDelegate.class) Closure c) { cloneDelegateAndGetContent(w, c, true); }
public static void cloneDelegateAndGetContent(Writer w, @DelegatesTo(StreamingJsonDelegate.class) Closure c, boolean first) { cloneDelegateAndGetContent(w, c, first, JsonOutput.DEFAULT_GENERATOR); }
public static void curryDelegateAndGetContent(Writer w, @DelegatesTo(StreamingJsonDelegate.class) Closure c, Object o) { curryDelegateAndGetContent(w, c, o, true); }
public static void curryDelegateAndGetContent(Writer w, @DelegatesTo(StreamingJsonDelegate.class) Closure c, Object o, boolean first) { curryDelegateAndGetContent(w, c, o, first, JsonOutput.DEFAULT_GENERATOR); }
public boolean matches(@DelegatesTo(value=ASTNode.class, strategy=Closure.DELEGATE_FIRST) Closure<Boolean> predicate) { return MatcherUtils.cloneWithDelegate(predicate, node).call(); }
public void afterVisit(@DelegatesTo(value=TreeContext.class, strategy=Closure.DELEGATE_FIRST) Closure<?> action) { Closure<?> clone = MatcherUtils.cloneWithDelegate(action, this); afterVisit(DefaultGroovyMethods.asType(clone, TreeContextAction.class)); }
public static <T> T macro(Object self, @DelegatesTo(MacroValuePlaceholder.class) Closure cl) { throw new IllegalStateException("MacroGroovyMethods.macro(Closure) should never be called at runtime. Are you sure you are using it correctly?"); }
public static <T> T macro(Object self, boolean asIs, @DelegatesTo(MacroValuePlaceholder.class) Closure cl) { throw new IllegalStateException("MacroGroovyMethods.macro(boolean, Closure) should never be called at runtime. Are you sure you are using it correctly?"); }
public static <T> T macro(Object self, CompilePhase compilePhase, @DelegatesTo(MacroValuePlaceholder.class) Closure cl) { throw new IllegalStateException("MacroGroovyMethods.macro(CompilePhase, Closure) should never be called at runtime. Are you sure you are using it correctly?"); }
public static <T> T macro(Object self, CompilePhase compilePhase, boolean asIs, @DelegatesTo(MacroValuePlaceholder.class) Closure cl) { throw new IllegalStateException("MacroGroovyMethods.macro(CompilePhase, boolean, Closure) should never be called at runtime. Are you sure you are using it correctly?"); }
/** * Allows the closure to be called for the object reference self. * <p/> * Any method invoked inside the closure will first be invoked on the * self reference. For example, the following method calls to the append() * method are invoked on the StringBuilder instance and then, because * 'returning' is true, the self instance is returned: * <pre class="groovyTestCase"> * def b = new StringBuilder().with(true) { * append('foo') * append('bar') * } * assert b.toString() == 'foobar' * </pre> * The returning parameter is commonly set to true when using with to simplify object * creation, such as this example: * <pre> * def p = new Person().with(true) { * firstName = 'John' * lastName = 'Doe' * } * </pre> * Alternatively, 'tap' is an alias for 'with(true)', so that method can be used instead. * * The other main use case for with is when returning a value calculated using self as shown here: * <pre> * def fullName = person.with(false){ "$firstName $lastName" } * </pre> * Alternatively, 'with' is an alias for 'with(false)', so the boolean parameter can be ommitted instead. * * @param self the object to have a closure act upon * @param returning if true, return the self object; otherwise, the result of calling the closure * @param closure the closure to call on the object * @return the self object or the result of calling the closure depending on 'returning' * @see #with(Object, Closure) * @see #tap(Object, Closure) * @since 2.5.0 */ public static <T,U extends T, V extends T> T with( @DelegatesTo.Target("self") U self, boolean returning, @DelegatesTo(value=DelegatesTo.Target.class, target="self", strategy=Closure.DELEGATE_FIRST) @ClosureParams(FirstParam.class) Closure<T> closure) { @SuppressWarnings("unchecked") final Closure<V> clonedClosure = (Closure<V>) closure.clone(); clonedClosure.setResolveStrategy(Closure.DELEGATE_FIRST); clonedClosure.setDelegate(self); V result = clonedClosure.call(self); return returning ? self : result; }
public void author(@Nonnull @DelegatesTo(Person.class) Closure c) { Person person = new Person(); ConfigureUtil.configure(c, person); // LOG.info("Adding author " + person); authors.add(person); }
/** * Allows executing a consumer with some context to setup events. * Defaults the timestamp to current time. * Defaults the user to "anonymous". * * @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 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, @DelegatesTo(OnSpec.class) Closure closure) { return on(aggregate, entityConsumer, positionSupplier, Date::new, closure); }
/** * Creates an `HttpBuilder` configured with the provided configuration closure, using the `defaultFactory` as the client factory. * * The configuration closure delegates to the {@link HttpObjectConfig} interface, which is an extension of the {@link HttpConfig} interface - * configuration properties from either may be applied to the global client configuration here. See the documentation for those interfaces for * configuration property details. * * [source,groovy] * ---- * def factory = { c -> new ApacheHttpBuilder(c); } as Function * * def http = HttpBuilder.configure(factory){ * request.uri = 'http://localhost:10101' * } * ---- * * @param factory the {@link HttpObjectConfig} factory function ({@link JavaHttpBuilder} or {@link groovyx.net.http.ApacheHttpBuilder}) * @param closure the configuration closure (delegated to {@link HttpObjectConfig}) * @return the configured `HttpBuilder` */ public static HttpBuilder configure(final Function<HttpObjectConfig, ? extends HttpBuilder> factory, @DelegatesTo(HttpObjectConfig.class) final Closure closure) { HttpObjectConfig impl = new HttpObjectConfigImpl(); closure.setDelegate(impl); closure.setResolveStrategy(Closure.DELEGATE_FIRST); closure.call(); return factory.apply(impl); }
/** * A closure passed to a JSON builder will create a root JSON object * <p> * Example: * <pre class="groovyTestCase"> * new StringWriter().with { w -> * def json = new groovy.json.StreamingJsonBuilder(w) * json { * name "Tim" * age 39 * } * * assert w.toString() == '{"name":"Tim","age":39}' * } * </pre> * * @param c a closure whose method call statements represent key / values of a JSON object */ public Object call(@DelegatesTo(StreamingJsonDelegate.class) Closure c) throws IOException { writer.write(JsonOutput.OPEN_BRACE); StreamingJsonDelegate.cloneDelegateAndGetContent(writer, c, true, generator); writer.write(JsonOutput.CLOSE_BRACE); return null; }
/** * A name and a closure passed to a JSON builder will create a key with a JSON object * <p> * Example: * <pre class="groovyTestCase"> * new StringWriter().with { w -> * def json = new groovy.json.StreamingJsonBuilder(w) * json.person { * name "Tim" * age 39 * } * * assert w.toString() == '{"person":{"name":"Tim","age":39}}' * } * </pre> * * @param name The key for the JSON object * @param c a closure whose method call statements represent key / values of a JSON object */ public void call(String name, @DelegatesTo(StreamingJsonDelegate.class) Closure c) throws IOException { writer.write(JsonOutput.OPEN_BRACE); writer.write(generator.toJson(name)); writer.write(JsonOutput.COLON); call(c); writer.write(JsonOutput.CLOSE_BRACE); }
/** * A name, a collection and closure passed to a JSON builder will create a root JSON array applying * the closure to each object in the collection * <p> * Example: * <pre class="groovyTestCase"> * class Author { * String name * } * def authors = [new Author (name: "Guillaume"), new Author (name: "Jochen"), new Author (name: "Paul")] * * new StringWriter().with { w -> * def json = new groovy.json.StreamingJsonBuilder(w) * json.people authors, { Author author -> * name author.name * } * * assert w.toString() == '{"people":[{"name":"Guillaume"},{"name":"Jochen"},{"name":"Paul"}]}' * } * </pre> * @param coll a collection * @param c a closure used to convert the objects of coll */ public void call(String name, Iterable coll, @DelegatesTo(StreamingJsonDelegate.class) Closure c) throws IOException { writer.write(JsonOutput.OPEN_BRACE); writer.write(generator.toJson(name)); writer.write(JsonOutput.COLON); call(coll, c); writer.write(JsonOutput.CLOSE_BRACE); }
/** * A collection and closure passed to a JSON builder will create a root JSON array applying * the closure to each object in the collection * <p> * Example: * <pre class="groovyTestCase"> * class Author { * String name * } * def authorList = [new Author (name: "Guillaume"), new Author (name: "Jochen"), new Author (name: "Paul")] * * new StringWriter().with { w -> * def json = new groovy.json.StreamingJsonBuilder(w) * json.book { * authors authorList, { Author author -> * name author.name * } * } * * assert w.toString() == '{"book":{"authors":[{"name":"Guillaume"},{"name":"Jochen"},{"name":"Paul"}]}}' * } * </pre> * @param coll a collection * @param c a closure used to convert the objects of coll */ public void call(String name, Iterable coll, @DelegatesTo(StreamingJsonDelegate.class) Closure c) throws IOException { if (generator.isExcludingFieldsNamed(name)) { return; } writeName(name); writeObjects(coll, c); }
/** * Allows the closure to be called for the object reference self. * Synonym for 'with()'. * * @param self the object to have a closure act upon * @param closure the closure to call on the object * @return result of calling the closure * @see #with(Object, Closure) * @since 1.0 */ public static <T,U> T identity( @DelegatesTo.Target("self") U self, @DelegatesTo(value=DelegatesTo.Target.class, target="self", strategy=Closure.DELEGATE_FIRST) @ClosureParams(FirstParam.class) Closure<T> closure) { return DefaultGroovyMethods.with(self, closure); }
/** * Allows the closure to be called for the object reference self. * <p> * Any method invoked inside the closure will first be invoked on the * self reference. For instance, the following method calls to the append() * method are invoked on the StringBuilder instance: * <pre class="groovyTestCase"> * def b = new StringBuilder().with { * append('foo') * append('bar') * return it * } * assert b.toString() == 'foobar' * </pre> * This is commonly used to simplify object creation, such as this example: * <pre> * def p = new Person().with { * firstName = 'John' * lastName = 'Doe' * return it * } * </pre> * The other typical usage, uses the self object while creating some value: * <pre> * def fullName = person.with{ "$firstName $lastName" } * </pre> * * @param self the object to have a closure act upon * @param closure the closure to call on the object * @return result of calling the closure * @see #with(Object, boolean, Closure) * @see #tap(Object, Closure) * @since 1.5.0 */ @SuppressWarnings("unchecked") public static <T,U> T with( @DelegatesTo.Target("self") U self, @DelegatesTo(value=DelegatesTo.Target.class, target="self", strategy=Closure.DELEGATE_FIRST) @ClosureParams(FirstParam.class) Closure<T> closure) { return (T) with(self, false, (Closure<Object>)closure); }
/** * Allows the closure to be called for the object reference self (similar * to <code>with</code> and always returns self. * <p> * Any method invoked inside the closure will first be invoked on the * self reference. For instance, the following method calls to the append() * method are invoked on the StringBuilder instance: * <pre> * def b = new StringBuilder().tap { * append('foo') * append('bar') * } * assert b.toString() == 'foobar' * </pre> * This is commonly used to simplify object creation, such as this example: * <pre> * def p = new Person().tap { * firstName = 'John' * lastName = 'Doe' * } * </pre> * * @param self the object to have a closure act upon * @param closure the closure to call on the object * @return self * @see #with(Object, boolean, Closure) * @see #with(Object, Closure) * @since 2.5.0 */ @SuppressWarnings("unchecked") public static <T,U> U tap( @DelegatesTo.Target("self") U self, @DelegatesTo(value=DelegatesTo.Target.class, target="self", strategy=Closure.DELEGATE_FIRST) @ClosureParams(FirstParam.class) Closure<T> closure) { return (U) with(self, true, (Closure<Object>)closure); }
/** * A shortcut for directly creating an object using {@code AutoBuilder}. * * <p> Interaction with the {@link BuilderDSL} is done inside the passed-in {@code * Closure} by setting properties as if the closure directly acted upon the * to-be-created object. Properties are specified by their names as strings, and * nested properties are supported using a dot '{@code .}' as a separator. Setting a * property inside the closure is equivalent to calling the {@link * BuilderDSL#with(String, Object)} method. * * <p> For example: * <pre>{@code * class Person { * String name; * Address address; * } * * // Groovy code: * def person = Person.of { * name = "Granger, Hermione" * address.city = LONDON * } * }</pre> * * @param self an object on which this extension method is invoked * @param instanceData the closure that sets the property values on the built object * @param <T> the type of the object to be built * * @return an instance of {@code T}, or {@code null} if configured so, equivalent to * calling the {@link BuilderDSL#build()} method */ @Nullable public static <T> T of( @DelegatesTo.Target Class<T> self, @DelegatesTo(strategy = DELEGATE_FIRST, genericTypeIndex = 0) Closure<?> instanceData) { return TableDSL.parseSingle(AutoBuilder.instanceOf(self), instanceData); }