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);
   }
 }
示例#2
0
 /**
  * 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));
 }
  /**
   * 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;
  }
示例#4
0
 public void setProperty(String property, Object newValue) {
   if ("delegate".equals(property)) {
     setDelegate(newValue);
   } else if ("metaClass".equals(property)) {
     setMetaClass((MetaClass) newValue);
   } else if ("resolveStrategy".equals(property)) {
     setResolveStrategy(((Number) newValue).intValue());
   } else if ("directive".equals(property)) {
     setDirective(((Number) newValue).intValue());
   } else {
     switch (resolveStrategy) {
       case DELEGATE_FIRST:
         setPropertyDelegateFirst(property, newValue);
         break;
       case DELEGATE_ONLY:
         InvokerHelper.setProperty(this.delegate, property, newValue);
         break;
       case OWNER_ONLY:
         InvokerHelper.setProperty(this.owner, property, newValue);
         break;
       case TO_SELF:
         super.setProperty(property, newValue);
         break;
       default:
         setPropertyOwnerFirst(property, newValue);
     }
   }
 }
 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);
   }
 }
 @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();
 }
  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();
  }
示例#10
0
 @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;
 }
示例#11
0
  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);
    }
  }
示例#12
0
 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;
 }
示例#13
0
 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 doWithDynamicMethods(ApplicationContext ctx) {
    try {
      if (pluginBean.isReadableProperty(DO_WITH_DYNAMIC_METHODS)) {
        Closure c = (Closure) plugin.getProperty(DO_WITH_DYNAMIC_METHODS);
        if (enableDocumentationGeneration()) {
          DocumentationContext.getInstance().setActive(true);
        }

        c.setDelegate(this);
        c.call(new Object[] {ctx});
      }
    } finally {
      if (enableDocumentationGeneration()) {
        DocumentationContext.getInstance().reset();
      }
    }
  }
  public void doWithApplicationContext(ApplicationContext ctx) {
    try {
      if (pluginBean.isReadableProperty(DO_WITH_APPLICATION_CONTEXT)) {
        Closure c = (Closure) plugin.getProperty(DO_WITH_APPLICATION_CONTEXT);
        if (enableDocumentationGeneration()) {
          DocumentationContext.getInstance().setActive(true);
        }

        c.setDelegate(this);
        c.call(new Object[] {ctx});
      }
    } finally {
      if (enableDocumentationGeneration()) {
        DocumentationContext.getInstance().reset();
      }
    }
  }
  /**
   * Triggers an event for the given name and arguments
   *
   * @param eventName The name of the event
   * @param arguments The arguments
   */
  @SuppressWarnings("rawtypes")
  public void triggerEvent(String eventName, Object... arguments) {
    List<Closure> handlers = globalEventHooks.get(eventName);
    if (handlers != null) {
      for (Closure handler : handlers) {
        handler.setDelegate(binding);
        try {
          handler.call(arguments);
        } catch (MissingPropertyException mpe) {
          // ignore
        }
      }
    }

    for (GrailsBuildListener buildListener : buildListeners) {
      buildListener.receiveGrailsBuildEvent(eventName, arguments);
    }
  }
  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()) {
        try {
          postProcessor.postProcessBeanFactory(beanFactory);
        } catch (IllegalStateException e) {
          // post processor doesn't allow running again, just continue
        }
      }
    }
  }
  public void doWithRuntimeConfiguration(RuntimeSpringConfiguration springConfig) {

    if (pluginBean.isReadableProperty(DO_WITH_SPRING)) {
      if (LOG.isDebugEnabled()) {
        LOG.debug("Plugin " + this + " is participating in Spring configuration...");
      }

      Closure c = (Closure) plugin.getProperty(DO_WITH_SPRING);
      BeanBuilder bb = new BeanBuilder(getParentCtx(), springConfig, application.getClassLoader());
      Binding b = new Binding();
      b.setVariable("application", application);
      b.setVariable("manager", getManager());
      b.setVariable("plugin", this);
      b.setVariable("parentCtx", getParentCtx());
      b.setVariable("resolver", getResolver());
      bb.setBinding(b);
      c.setDelegate(bb);
      bb.invokeMethod("beans", new Object[] {c});
    }
  }
  @Override
  public void doWithWebDescriptor(final Element webXml) {
    if (!pluginBean.isReadableProperty(DO_WITH_WEB_DESCRIPTOR)) {
      return;
    }

    final Closure c = (Closure) plugin.getProperty(DO_WITH_WEB_DESCRIPTOR);
    c.setResolveStrategy(Closure.DELEGATE_FIRST);
    c.setDelegate(this);
    DefaultGroovyMethods.use(
        this,
        DOMCategory.class,
        new Closure<Object>(this) {
          private static final long serialVersionUID = 1;

          @Override
          public Object call(Object... args) {
            return c.call(webXml);
          }
        });
  }
  protected String evaluateNameForValue(Object value, GrailsWebRequest webRequest) {
    if (value == null) {
      return null;
    }

    String name;
    if (value instanceof Closure) {
      Closure callable = (Closure) value;
      final Closure cloned = (Closure) callable.clone();
      cloned.setDelegate(webRequest);
      cloned.setResolveStrategy(Closure.DELEGATE_FIRST);
      Object result = cloned.call();
      name = result != null ? result.toString() : null;
    } else if (value instanceof Map) {
      Map httpMethods = (Map) value;
      name = (String) httpMethods.get(webRequest.getCurrentRequest().getMethod());
    } else {
      name = value.toString();
    }
    return name != null ? name.trim() : null;
  }
  /**
   * This method is called when a bean definition node is called.
   *
   * @param beanName the name of the bean to define
   * @param args the arguments to the bean. The first argument is the class name, the last argument
   *     is sometimes a closure. All the arguments in between are constructor arguments.
   * @return the bean definition wrapper
   */
  private GroovyBeanDefinitionWrapper invokeBeanDefiningMethod(String beanName, Object[] args) {
    boolean hasClosureArgument = (args[args.length - 1] instanceof Closure);
    if (args[0] instanceof Class) {
      Class<?> beanClass = (Class<?>) args[0];
      if (args.length >= 1) {
        if (hasClosureArgument) {
          if (args.length - 1 != 1) {
            this.currentBeanDefinition =
                new GroovyBeanDefinitionWrapper(
                    beanName, beanClass, resolveConstructorArguments(args, 1, args.length - 1));
          } else {
            this.currentBeanDefinition = new GroovyBeanDefinitionWrapper(beanName, beanClass);
          }
        } else {
          this.currentBeanDefinition =
              new GroovyBeanDefinitionWrapper(
                  beanName, beanClass, resolveConstructorArguments(args, 1, args.length));
        }
      }
    } else if (args[0] instanceof RuntimeBeanReference) {
      this.currentBeanDefinition = new GroovyBeanDefinitionWrapper(beanName);
      this.currentBeanDefinition
          .getBeanDefinition()
          .setFactoryBeanName(((RuntimeBeanReference) args[0]).getBeanName());
    } else if (args[0] instanceof Map) {
      // named constructor arguments
      if (args.length > 1 && args[1] instanceof Class) {
        List constructorArgs =
            resolveConstructorArguments(
                args, 2, hasClosureArgument ? args.length - 1 : args.length);
        this.currentBeanDefinition =
            new GroovyBeanDefinitionWrapper(beanName, (Class) args[1], constructorArgs);
        Map namedArgs = (Map) args[0];
        for (Object o : namedArgs.keySet()) {
          String propName = (String) o;
          setProperty(propName, namedArgs.get(propName));
        }
      }
      // factory method syntax
      else {
        this.currentBeanDefinition = new GroovyBeanDefinitionWrapper(beanName);
        // First arg is the map containing factoryBean : factoryMethod
        Map.Entry factoryBeanEntry = (Map.Entry) ((Map) args[0]).entrySet().iterator().next();
        // If we have a closure body, that will be the last argument.
        // In between are the constructor args
        int constructorArgsTest = hasClosureArgument ? 2 : 1;
        // If we have more than this number of args, we have constructor args
        if (args.length > constructorArgsTest) {
          // factory-method requires args
          int endOfConstructArgs = (hasClosureArgument ? args.length - 1 : args.length);
          this.currentBeanDefinition =
              new GroovyBeanDefinitionWrapper(
                  beanName, null, resolveConstructorArguments(args, 1, endOfConstructArgs));
        } else {
          this.currentBeanDefinition = new GroovyBeanDefinitionWrapper(beanName);
        }
        this.currentBeanDefinition
            .getBeanDefinition()
            .setFactoryBeanName(factoryBeanEntry.getKey().toString());
        this.currentBeanDefinition
            .getBeanDefinition()
            .setFactoryMethodName(factoryBeanEntry.getValue().toString());
      }

    } else if (args[0] instanceof Closure) {
      this.currentBeanDefinition = new GroovyBeanDefinitionWrapper(beanName);
      this.currentBeanDefinition.getBeanDefinition().setAbstract(true);
    } else {
      List constructorArgs =
          resolveConstructorArguments(args, 0, hasClosureArgument ? args.length - 1 : args.length);
      currentBeanDefinition = new GroovyBeanDefinitionWrapper(beanName, null, constructorArgs);
    }

    if (hasClosureArgument) {
      Closure callable = (Closure) args[args.length - 1];
      callable.setDelegate(this);
      callable.setResolveStrategy(Closure.DELEGATE_FIRST);
      callable.call(new Object[] {currentBeanDefinition});
    }

    GroovyBeanDefinitionWrapper beanDefinition = currentBeanDefinition;
    this.currentBeanDefinition = null;
    beanDefinition
        .getBeanDefinition()
        .setAttribute(GroovyBeanDefinitionWrapper.class.getName(), beanDefinition);
    getRegistry().registerBeanDefinition(beanName, beanDefinition.getBeanDefinition());
    return beanDefinition;
  }
    private Object _invoke(String methodName, Object arg, Object delegate) {
      Object[] args = (Object[]) arg;
      final boolean isResponseCode = isResponseCode(methodName);
      if (methodName.startsWith(SLASH) || isResponseCode) {
        // Create a new parameter map for this mapping.
        parameterValues = new HashMap<String, Object>();
        try {
          urlDefiningMode = false;
          args = args != null && args.length > 0 ? args : new Object[] {Collections.EMPTY_MAP};
          if (args[0] instanceof Closure) {
            UrlMappingData urlData = createUrlMappingData(methodName, isResponseCode);

            Closure callable = (Closure) args[0];
            if (delegate != null) callable.setDelegate(delegate);
            callable.call();

            @SuppressWarnings("hiding")
            Object controllerName;
            @SuppressWarnings("hiding")
            Object actionName;
            @SuppressWarnings("hiding")
            Object viewName;
            @SuppressWarnings("hiding")
            Object uri;

            if (binding != null) {
              controllerName = binding.getVariables().get(GrailsControllerClass.CONTROLLER);
              actionName = binding.getVariables().get(GrailsControllerClass.ACTION);
              viewName = binding.getVariables().get(GrailsControllerClass.VIEW);
              uri = binding.getVariables().get("uri");
            } else {
              controllerName = this.controllerName;
              actionName = this.actionName;
              viewName = this.viewName;
              uri = this.uri;
            }

            ConstrainedProperty[] constraints =
                previousConstraints.toArray(new ConstrainedProperty[previousConstraints.size()]);
            UrlMapping urlMapping;
            if (uri != null) {
              try {
                urlMapping = new RegexUrlMapping(urlData, new URI(uri.toString()), constraints, sc);
              } catch (URISyntaxException e) {
                throw new UrlMappingException("Cannot map to invalid URI: " + e.getMessage(), e);
              }
            } else {
              urlMapping =
                  createURLMapping(
                      urlData, isResponseCode, controllerName, actionName, viewName, constraints);
            }

            if (binding != null) {
              Map bindingVariables = binding.getVariables();
              Object parseRequest = getParseRequest(Collections.EMPTY_MAP, bindingVariables);
              if (parseRequest instanceof Boolean) {
                urlMapping.setParseRequest((Boolean) parseRequest);
              }
            }
            configureUrlMapping(urlMapping);
            return urlMapping;
          }

          if (args[0] instanceof Map) {
            Map namedArguments = (Map) args[0];
            UrlMappingData urlData = createUrlMappingData(methodName, isResponseCode);
            if (args.length > 1 && args[1] instanceof Closure) {
              Closure callable = (Closure) args[1];
              callable.call();
            }

            UrlMapping urlMapping =
                getURLMappingForNamedArgs(namedArguments, urlData, methodName, isResponseCode);
            configureUrlMapping(urlMapping);
            return urlMapping;
          }
          return null;
        } finally {
          if (binding != null) {
            binding.getVariables().clear();
          } else {
            controllerName = null;
            actionName = null;
            viewName = null;
          }
          previousConstraints.clear();
          urlDefiningMode = true;
        }
      } else if (!urlDefiningMode && CONSTRAINTS.equals(methodName)) {
        ConstrainedPropertyBuilder builder = new ConstrainedPropertyBuilder(this);
        if (args.length > 0 && (args[0] instanceof Closure)) {

          Closure callable = (Closure) args[0];
          callable.setDelegate(builder);
          for (ConstrainedProperty constrainedProperty : previousConstraints) {
            builder
                .getConstrainedProperties()
                .put(constrainedProperty.getPropertyName(), constrainedProperty);
          }
          callable.call();
        }
        return builder.getConstrainedProperties();
      } else {
        return super.invokeMethod(methodName, arg);
      }
    }
 public void registerExplicitMethod(String name, String groupName, Closure closure) {
   // set the delegate to FBS so the closure closes over the builder
   closure.setDelegate(this);
   explicitMethods.put(name, closure);
   getRegistrationGroup(groupName).add(name);
 }
 private void callEvent(Closure closureHook, Map event) {
   if (closureHook != null) {
     closureHook.setDelegate(this);
     closureHook.call(new Object[] {event});
   }
 }
 /**
  * When a method argument is only a closure it is a set of bean definitions.
  *
  * @param callable the closure argument
  * @return this {@code GroovyBeanDefinitionReader} instance
  */
 protected GroovyBeanDefinitionReader invokeBeanDefiningClosure(Closure callable) {
   callable.setDelegate(this);
   callable.call();
   finalizeDeferredProperties();
   return this;
 }
 public Object eval(
     @SuppressWarnings("rawtypes") HashMap map, @SuppressWarnings("rawtypes") Closure cl) {
   cl.setDelegate(this);
   cl.setResolveStrategy(Closure.DELEGATE_FIRST);
   return cl.call();
 }
 public void invoke(Closure body, Object[] args) {
   body.setDelegate(getGroovyWorld());
   body.call(args);
 }
示例#29
0
 public void execute(Closure callable) {
   callable.setDelegate(this);
   //            callable.setDelegate(Closure.DELEGATE_FIRST);
   invokeMethod("json", new Object[] {callable});
 }
 /**
  * A strategy method to allow derived builders to use builder-trees and switch in different kinds
  * of builders. This method should call the setDelegate() method on the closure which by default
  * passes in this but if node is-a builder we could pass that in instead (or do something wacky
  * too)
  *
  * @param closure the closure on which to call setDelegate()
  * @param node the node value that we've just created, which could be a builder
  */
 @SuppressWarnings({"UnusedDeclaration"})
 protected void setClosureDelegate(Closure closure, Object node) {
   closure.setDelegate(this);
 }