/** * Switches the builder's proxyBuilder during the execution of a closure.<br> * This is useful to temporary change the building context to another builder without the need for * a contrived setup. It will also take care of restoring the previous proxyBuilder when the * execution finishes, even if an exception was thrown from inside the closure. * * @param builder the temporary builder to switch to as proxyBuilder. * @param closure the closure to be executed under the temporary builder. * @return the execution result of the closure. * @throws RuntimeException - any exception the closure might have thrown during execution. */ public Object withBuilder(FactoryBuilderSupport builder, Closure closure) { if (builder == null || closure == null) { return null; } Object result = null; Object previousContext = getProxyBuilder().getContext(); FactoryBuilderSupport previousProxyBuilder = localProxyBuilder.get(); try { localProxyBuilder.set(builder); closure.setDelegate(builder); result = closure.call(); } catch (RuntimeException e) { // remove contexts created after we started localProxyBuilder.set(previousProxyBuilder); if (getProxyBuilder().getContexts().contains(previousContext)) { Map<String, Object> context = getProxyBuilder().getContext(); while (context != null && context != previousContext) { getProxyBuilder().popContext(); context = getProxyBuilder().getContext(); } } throw e; } finally { localProxyBuilder.set(previousProxyBuilder); } return result; }
/** * The field tag is a helper, based on the spirit of Don't Repeat Yourself. * * @param args tag attributes * @param body tag inner body * @param out the output writer * @param template enclosing template * @param fromLine template line number where the tag is defined */ public static void _field( Map<?, ?> args, Closure body, PrintWriter out, ExecutableTemplate template, int fromLine) { Map<String, Object> field = new HashMap<String, Object>(); String _arg = args.get("arg").toString(); field.put("name", _arg); field.put("id", _arg.replace('.', '_')); field.put("flash", Flash.current().get(_arg)); field.put( "flashArray", field.get("flash") != null && !StringUtils.isEmpty(field.get("flash").toString()) ? field.get("flash").toString().split(",") : new String[0]); field.put("error", Validation.error(_arg)); field.put("errorClass", field.get("error") != null ? "hasError" : ""); String[] pieces = _arg.split("\\."); Object obj = body.getProperty(pieces[0]); if (obj != null) { if (pieces.length > 1) { try { String path = _arg.substring(_arg.indexOf(".") + 1); Object value = PropertyUtils.getProperty(obj, path); field.put("value", value); } catch (Exception e) { // if there is a problem reading the field we dont set any value } } else { field.put("value", obj); } } body.setProperty("field", field); body.call(); }
protected void applyPropertyToBeanDefinition(String name, Object value) { if (value instanceof GString) { value = value.toString(); } if (addDeferredProperty(name, value)) { return; } else if (value instanceof Closure) { GroovyBeanDefinitionWrapper current = this.currentBeanDefinition; try { Closure callable = (Closure) value; Class<?> parameterType = callable.getParameterTypes()[0]; if (Object.class == parameterType) { this.currentBeanDefinition = new GroovyBeanDefinitionWrapper(""); callable.call(this.currentBeanDefinition); } else { this.currentBeanDefinition = new GroovyBeanDefinitionWrapper(null, parameterType); callable.call((Object) null); } value = this.currentBeanDefinition.getBeanDefinition(); } finally { this.currentBeanDefinition = current; } } this.currentBeanDefinition.addProperty(name, value); }
@Override public V call(Object... args) { Object temp = first.call(args); if (temp instanceof List && second.getParameterTypes().length > 1) temp = ((List) temp).toArray(); return temp instanceof Object[] ? second.call((Object[]) temp) : second.call(temp); }
/** * Sends a message and execute continuation when reply became available. * * @param message message to send * @param closure closure to execute when reply became available * @return The message that came in reply to the original send. */ @SuppressWarnings({"AssignmentToMethodParameter"}) public final <T> MessageStream sendAndContinue(final T message, Closure closure) { closure = (Closure) closure.clone(); closure.setDelegate(this); closure.setResolveStrategy(Closure.DELEGATE_FIRST); return send(message, new DataCallback(closure, parallelGroup)); }
public static QueryBuilder prepare( SearchService service, final @DelegatesTo(value = QueryBuilder.class, strategy = Closure.DELEGATE_FIRST) Closure<?> c) { final QueryBuilder builder = new QueryBuilder( c.getThisObject() instanceof Script ? ((Script) c.getThisObject()).getBinding() : new Binding()); GroovyCategorySupport.use( SearchQueryStringCategory.class, new Closure<Object>(builder) { public Object call(Object... args) { return DefaultGroovyMethods.with(builder, c); }; }); if (builder.getIndexName() == null) { throw new IllegalStateException("Index name cannot be null"); } ; if (builder.getQueryString() == null) { throw new IllegalStateException("Query String name cannot be null"); } ; return builder; }
/** * Define an inner bean definition. * * @param type the bean type * @param args the constructors arguments and closure configurer * @return the bean definition */ public AbstractBeanDefinition bean(Class<?> type, Object... args) { GroovyBeanDefinitionWrapper current = this.currentBeanDefinition; try { Closure callable = null; Collection constructorArgs = null; if (!ObjectUtils.isEmpty(args)) { int index = args.length; Object lastArg = args[index - 1]; if (lastArg instanceof Closure) { callable = (Closure) lastArg; index--; } if (index > -1) { constructorArgs = resolveConstructorArguments(args, 0, index); } } this.currentBeanDefinition = new GroovyBeanDefinitionWrapper(null, type, constructorArgs); if (callable != null) { callable.call(this.currentBeanDefinition); } return this.currentBeanDefinition.getBeanDefinition(); } finally { this.currentBeanDefinition = current; } }
public static void _set( Map<?, ?> args, Closure body, PrintWriter out, ExecutableTemplate template, int fromLine) { // Simple case : #{set title:'Yop' /} for (Map.Entry<?, ?> entry : args.entrySet()) { Object key = entry.getKey(); if (!key.toString().equals("arg")) { BaseTemplate.layoutData .get() .put( key, (entry.getValue() != null && entry.getValue() instanceof String) ? __safe(template.template, entry.getValue()) : entry.getValue()); return; } } // Body case Object name = args.get("arg"); if (name != null && body != null) { Object oldOut = body.getProperty("out"); StringWriter sw = new StringWriter(); body.setProperty("out", new PrintWriter(sw)); body.call(); BaseTemplate.layoutData.get().put(name, sw.toString()); body.setProperty("out", oldOut); } }
public T parseNotation(Object notation) { if (notation == null) { return null; } if (notation instanceof CharSequence || notation instanceof Number || notation instanceof Boolean) { return (T) notation.toString(); } if (notation instanceof Closure) { final Closure closure = (Closure) notation; final Object called = closure.call(); return parseNotation(called); } if (notation instanceof Callable) { try { final Callable callableNotation = (Callable) notation; final Object called = callableNotation.call(); return parseNotation(called); } catch (Exception e) { throw UncheckedException.throwAsUncheckedException(e); } } DeprecationLogger.nagUserOfDeprecated( String.format( "Converting class %s to path using toString() method", notation.getClass().getName()), "Please use java.io.File, java.lang.CharSequence, java.lang.Number, java.util.concurrent.Callable or groovy.lang.Closure"); return (T) notation.toString(); }
/** * Returns a copy of this closure where the "owner", "delegate" and "thisObject" fields are null, * allowing proper serialization when one of them is not serializable. * * @return a serializable closure. * @since 1.8.5 */ @SuppressWarnings("unchecked") public Closure<V> dehydrate() { Closure<V> result = (Closure<V>) this.clone(); result.delegate = null; result.owner = null; result.thisObject = null; return result; }
/** * Returns a copy of this closure for which the delegate, owner and thisObject are replaced with * the supplied parameters. Use this when you want to rehydrate a closure which has been made * serializable thanks to the {@link #dehydrate()} method. * * @param delegate the closure delegate * @param owner the closure owner * @param thisObject the closure "this" object * @return a copy of this closure where owner, delegate and thisObject are replaced * @since 1.8.5 */ @SuppressWarnings("unchecked") public Closure<V> rehydrate(Object delegate, Object owner, Object thisObject) { Closure<V> result = (Closure<V>) this.clone(); result.delegate = delegate; result.owner = owner; result.thisObject = thisObject; return result; }
Object callClosure(Object entity, Closure callable) { if (cloneFirst) { callable = (Closure) callable.clone(); } callable.setResolveStrategy(Closure.DELEGATE_FIRST); callable.setDelegate(entity); return callable.call(); }
private void invokeClosureNode(Object args) { if (args instanceof Closure) { Closure callable = (Closure) args; callable.setDelegate(this); callable.setResolveStrategy(Closure.DELEGATE_FIRST); callable.call(); } }
@Override public void doWithWebDescriptor(GPathResult webXml) { if (pluginBean.isReadableProperty(DO_WITH_WEB_DESCRIPTOR)) { Closure c = (Closure) plugin.getProperty(DO_WITH_WEB_DESCRIPTOR); c.setResolveStrategy(Closure.DELEGATE_FIRST); c.setDelegate(this); c.call(webXml); } }
private List<?> evaluateMappings(GroovyObject go, Closure<?> mappings, Binding binding) { UrlMappingBuilder builder = new UrlMappingBuilder(binding, servletContext); mappings.setDelegate(builder); mappings.call(); builder.urlDefiningMode = false; configureUrlMappingDynamicObjects(go); return builder.getUrlMappings(); }
@Override public boolean onNodeChildren( final FactoryBuilderSupport builder, final Object node, final Closure childContent) { if (node instanceof ImportCustomizer) { Closure clone = (Closure) childContent.clone(); clone.setDelegate(new ImportHelper((ImportCustomizer) node)); clone.call(); } return false; }
private static DocumentDefinitions applyDefinitionsClosure( @DelegatesTo(value = DocumentDefinitions.class, strategy = Closure.DELEGATE_FIRST) Closure<?> closure) { Closure<?> docDefClosure = (Closure<?>) closure.clone(); docDefClosure.setResolveStrategy(Closure.DELEGATE_FIRST); DocumentDefinitions definitions = new DocumentDefinitions(); docDefClosure.setDelegate(definitions); docDefClosure.call(); return definitions; }
@DSLMethod(production = "if ( p0 ) then { p1 } else { p2 }") public boolean ifThenElse(boolean check, Closure thenBlock, Closure elseBlock) { if (check) { thenBlock.call(); } else { elseBlock.call(); } return check; }
@SuppressWarnings("rawtypes") public List evaluateMappings(Closure closure) { UrlMappingBuilder builder = new UrlMappingBuilder(null, servletContext); closure.setDelegate(builder); closure.setResolveStrategy(Closure.DELEGATE_FIRST); closure.call(applicationContext); builder.urlDefiningMode = false; configureUrlMappingDynamicObjects(closure); return builder.getUrlMappings(); }
/* * @see org.eclipse.swt.browser.ProgressListener#completed(org.eclipse.swt.browser.ProgressEvent) */ public void completed(ProgressEvent event) { if (closure == null) { throw new NullPointerException("No closure has been configured for this Listener"); } if ("completed".equals(type)) { closure.setProperty("event", new CustomProgressEvent(event)); closure.call(event); } }
private Object evaluateCondition(Closure condition) { condition.setDelegate(new PreconditionContext()); condition.setResolveStrategy(Closure.DELEGATE_ONLY); try { return condition.call(); } catch (Exception e) { throw new ExtensionException("Failed to evaluate @Requires condition", e); } }
public void testFindAllAndCurry() { Map<String, Integer> expected = new HashMap<String, Integer>(zoo); expected.remove("Lions"); Closure<Boolean> keyBiggerThan = new Closure<Boolean>(null) { public Boolean doCall(Map.Entry<String, Integer> e, Integer size) { return e.getKey().length() > size; } }; Closure<Boolean> keyBiggerThan6 = keyBiggerThan.rcurry(6); assertEquals(expected, findAll(zoo, keyBiggerThan6)); }
@Override public Class<?>[] visitGroovy(Map<String, Object> p) { @SuppressWarnings("unchecked") Closure<Object> transactOn = (Closure<Object>) p.get(GVY_PROCEDURE_ENTRY_CLOSURE); // closure with no parameters has an object as the default parameter Class<?>[] parameterTypes = transactOn.getParameterTypes(); if (parameterTypes.length == 1 && parameterTypes[0] == Object.class) { return new Class<?>[0]; } return transactOn.getParameterTypes(); }
/** * Times the execution of a closure, which can include a target. For example, * * <p>profile("compile", compile) * * <p>where 'compile' is the target. */ public void profile(String name, Closure<?> callable) { if (enableProfile) { long now = System.currentTimeMillis(); GrailsConsole console = GrailsConsole.getInstance(); console.addStatus("Profiling [" + name + "] start"); callable.call(); long then = System.currentTimeMillis() - now; console.addStatus("Profiling [" + name + "] finish. Took " + then + " ms"); } else { callable.call(); } }
protected Object doInvokeMethod(String s, Object name, Object args) { // TODO use setDelegate() from Groovy JSR Object answer = super.doInvokeMethod(s, name, args); List list = InvokerHelper.asList(args); if (!list.isEmpty()) { Object o = list.get(list.size() - 1); if (o instanceof Closure) { Closure closure = (Closure) o; closure.setDelegate(answer); } } return answer; }
private void invokeOnChangeListener(Map event) { onChangeListener.setDelegate(this); onChangeListener.call(new Object[] {event}); // Apply any factory post processors in case the change listener has changed any // bean definitions (GRAILS-5763) if (applicationContext instanceof GenericApplicationContext) { GenericApplicationContext ctx = (GenericApplicationContext) applicationContext; ConfigurableListableBeanFactory beanFactory = ctx.getBeanFactory(); for (BeanFactoryPostProcessor postProcessor : ctx.getBeanFactoryPostProcessors()) { postProcessor.postProcessBeanFactory(beanFactory); } } }
public void registerExplicitProperty( String name, String groupName, Closure getter, Closure setter) { // set the delegate to FBS so the closure closes over the builder if (getter != null) getter.setDelegate(this); if (setter != null) setter.setDelegate(this); explicitProperties.put(name, new Closure[] {getter, setter}); String methodNameBase = MetaClassHelper.capitalize(name); if (getter != null) { getRegistrationGroup(groupName).add("get" + methodNameBase); } if (setter != null) { getRegistrationGroup(groupName).add("set" + methodNameBase); } }
protected boolean checkExplicitMethod(String methodName, Object args, Reference result) { Closure explicitMethod = resolveExplicitMethod(methodName, args); if (explicitMethod != null) { if (args instanceof Object[]) { result.set(explicitMethod.call((Object[]) args)); } else { // todo push through InvokerHelper.asList? result.set(explicitMethod.call(args)); } return true; } else { return false; } }
/** @throws DSLException . */ @Test public void testPropertyInCustomCommand() throws DSLException { final File testParsingExtendDslFile = new File(TEST_PARSING_RESOURCE_PATH + "test_property_in_custom_command-service.groovy"); final File testParsingExtendWorkDir = new File(TEST_PARSING_RESOURCE_PATH); final Service service = ServiceReader.getServiceFromFile(testParsingExtendDslFile, testParsingExtendWorkDir) .getService(); final Closure<?> customCommand = ((ClosureExecutableEntry) service.getCustomCommands().get("custom_command")).getCommand(); final String[] params = new String[2]; params[0] = "name"; params[1] = "port"; customCommand.call((Object[]) params); customCommand.call((Object[]) params); }
public GPathResult find(final Closure closure) { if (DefaultTypeTransformation.castToBoolean(closure.call(new Object[] {this}))) { return this; } else { return new NoChildren(this, "", this.namespaceTagHints); } }