@Override
 protected String resolveId(
     Element element, AbstractBeanDefinition definition, ParserContext parserContext)
     throws BeanDefinitionStoreException {
   String id = super.resolveId(element, definition, parserContext);
   if (element.getAttribute("default").equals("true")) {
     if (parserContext
         .getRegistry()
         .isBeanNameInUse(PollerMetadata.DEFAULT_POLLER_METADATA_BEAN_NAME)) {
       parserContext
           .getReaderContext()
           .error("Only one default <poller/> element is allowed per context.", element);
     }
     if (StringUtils.hasText(id)) {
       parserContext
           .getRegistry()
           .registerAlias(id, PollerMetadata.DEFAULT_POLLER_METADATA_BEAN_NAME);
     } else {
       id = PollerMetadata.DEFAULT_POLLER_METADATA_BEAN_NAME;
     }
   } else if (!StringUtils.hasText(id)) {
     parserContext
         .getReaderContext()
         .error(
             "The 'id' attribute is required for a top-level poller element unless it is the default poller.",
             element);
   }
   return id;
 }
  @Override
  protected BeanMetadataElement parseSource(Element element, ParserContext parserContext) {

    final BeanDefinitionBuilder jpaPollingChannelAdapterBuilder =
        BeanDefinitionBuilder.genericBeanDefinition(JpaPollingChannelAdapter.class);

    final BeanDefinitionBuilder jpaExecutorBuilder =
        JpaParserUtils.getJpaExecutorBuilder(element, parserContext);

    String maxNumberOfResults = element.getAttribute("max-number-of-results");
    boolean hasMaxNumberOfResults = StringUtils.hasText(maxNumberOfResults);

    String maxResults = element.getAttribute("max-results");
    boolean hasMaxResults = StringUtils.hasText(maxResults);

    if (hasMaxNumberOfResults) {
      parserContext
          .getReaderContext()
          .warning("'max-number-of-results' is deprecated in favor of 'max-results'", element);
      if (hasMaxResults) {
        parserContext
            .getReaderContext()
            .error("'max-number-of-results' and 'max-results' are mutually exclusive", element);
      } else {
        element.setAttribute("max-results", maxNumberOfResults);
      }
    }

    BeanDefinition definition =
        IntegrationNamespaceUtils.createExpressionDefinitionFromValueOrExpression(
            "max-results", "max-results-expression", parserContext, element, false);
    if (definition != null) {
      jpaExecutorBuilder.addPropertyValue("maxResultsExpression", definition);
    }
    IntegrationNamespaceUtils.setValueIfAttributeDefined(
        jpaExecutorBuilder, element, "delete-after-poll");
    IntegrationNamespaceUtils.setValueIfAttributeDefined(
        jpaExecutorBuilder, element, "flush-after-delete", "flush");
    IntegrationNamespaceUtils.setValueIfAttributeDefined(
        jpaExecutorBuilder, element, "delete-in-batch");
    IntegrationNamespaceUtils.setValueIfAttributeDefined(
        jpaExecutorBuilder, element, "expect-single-result");
    IntegrationNamespaceUtils.setReferenceIfAttributeDefined(
        jpaExecutorBuilder, element, "parameter-source");

    final BeanDefinition jpaExecutorBuilderBeanDefinition = jpaExecutorBuilder.getBeanDefinition();
    final String channelAdapterId =
        this.resolveId(
            element, jpaPollingChannelAdapterBuilder.getRawBeanDefinition(), parserContext);
    final String jpaExecutorBeanName = channelAdapterId + ".jpaExecutor";

    parserContext.registerBeanComponent(
        new BeanComponentDefinition(jpaExecutorBuilderBeanDefinition, jpaExecutorBeanName));

    jpaPollingChannelAdapterBuilder.addConstructorArgReference(jpaExecutorBeanName);

    return jpaPollingChannelAdapterBuilder.getBeanDefinition();
  }
  @SuppressWarnings("unchecked")
  public BeanDefinitionHolder decorate(
      Node node, BeanDefinitionHolder holder, ParserContext parserContext) {
    BeanDefinition filterChainProxy = holder.getBeanDefinition();

    ManagedList<BeanMetadataElement> securityFilterChains = new ManagedList<BeanMetadataElement>();
    Element elt = (Element) node;

    MatcherType matcherType = MatcherType.fromElement(elt);

    List<Element> filterChainElts = DomUtils.getChildElementsByTagName(elt, Elements.FILTER_CHAIN);

    for (Element chain : filterChainElts) {
      String path = chain.getAttribute(HttpSecurityBeanDefinitionParser.ATT_PATH_PATTERN);
      String filters = chain.getAttribute(HttpSecurityBeanDefinitionParser.ATT_FILTERS);

      if (!StringUtils.hasText(path)) {
        parserContext
            .getReaderContext()
            .error(
                "The attribute '"
                    + HttpSecurityBeanDefinitionParser.ATT_PATH_PATTERN
                    + "' must not be empty",
                elt);
      }

      if (!StringUtils.hasText(filters)) {
        parserContext
            .getReaderContext()
            .error(
                "The attribute '"
                    + HttpSecurityBeanDefinitionParser.ATT_FILTERS
                    + "'must not be empty",
                elt);
      }

      BeanDefinition matcher = matcherType.createMatcher(parserContext, path, null);

      if (filters.equals(HttpSecurityBeanDefinitionParser.OPT_FILTERS_NONE)) {
        securityFilterChains.add(createSecurityFilterChain(matcher, new ManagedList(0)));
      } else {
        String[] filterBeanNames = StringUtils.tokenizeToStringArray(filters, ",");
        ManagedList filterChain = new ManagedList(filterBeanNames.length);

        for (String name : filterBeanNames) {
          filterChain.add(new RuntimeBeanReference(name));
        }

        securityFilterChains.add(createSecurityFilterChain(matcher, filterChain));
      }
    }

    filterChainProxy.getConstructorArgumentValues().addGenericArgumentValue(securityFilterChains);

    return holder;
  }
  @Override
  protected void doParse(
      Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
    String scriptLocation = element.getAttribute(LOCATION_ATTRIBUTE);
    String scriptText = DomUtils.getTextValue(element);
    if (!(StringUtils.hasText(scriptLocation) ^ StringUtils.hasText(scriptText))) {
      parserContext
          .getReaderContext()
          .error(
              "Either the 'location' attribute or inline script text must be provided, but not both.",
              element);
      return;
    }

    List<Element> variableElements = DomUtils.getChildElementsByTagName(element, "variable");
    String scriptVariableGeneratorName = element.getAttribute("script-variable-generator");

    if (StringUtils.hasText(scriptVariableGeneratorName) && variableElements.size() > 0) {
      parserContext
          .getReaderContext()
          .error(
              "'script-variable-generator' and 'variable' sub-elements are mutually exclusive.",
              element);
      return;
    }

    if (StringUtils.hasText(scriptLocation)) {
      builder.addConstructorArgValue(
          this.resolveScriptLocation(element, parserContext.getReaderContext(), scriptLocation));
    } else {
      if (getScriptSourceClassName() != null) {
        builder.addConstructorArgValue(
            new StaticScriptSource(scriptText, getScriptSourceClassName()));
      } else {
        builder.addConstructorArgValue(new StaticScriptSource(scriptText));
      }
    }

    BeanMetadataElement scriptVariableGeneratorDef = null;

    if (!StringUtils.hasText(scriptVariableGeneratorName)) {
      BeanDefinitionBuilder scriptVariableGeneratorBuilder =
          BeanDefinitionBuilder.genericBeanDefinition(DefaultScriptVariableGenerator.class);
      ManagedMap<String, Object> variableMap =
          buildVariablesMap(element, parserContext, variableElements);
      if (!CollectionUtils.isEmpty(variableMap)) {
        scriptVariableGeneratorBuilder.addConstructorArgValue(variableMap);
      }
      scriptVariableGeneratorDef = scriptVariableGeneratorBuilder.getBeanDefinition();
    } else {
      scriptVariableGeneratorDef = new RuntimeBeanReference(scriptVariableGeneratorName);
    }

    builder.addConstructorArgValue(scriptVariableGeneratorDef);
    postProcess(builder, element, parserContext);
  }
示例#5
0
  /**
   * Parse the split and turn it into a list of transitions.
   *
   * @param element the &lt;split/gt; element to parse
   * @param parserContext the parser context for the bean factory
   * @return a collection of bean definitions for {@link
   *     org.springframework.batch.core.job.flow.support.StateTransition} instances objects
   */
  public Collection<BeanDefinition> parse(Element element, ParserContext parserContext) {

    String idAttribute = element.getAttribute("id");

    BeanDefinitionBuilder stateBuilder =
        BeanDefinitionBuilder.genericBeanDefinition(
            "org.springframework.batch.core.job.flow.support.state.SplitState");

    String taskExecutorBeanId = element.getAttribute("task-executor");
    if (StringUtils.hasText(taskExecutorBeanId)) {
      RuntimeBeanReference taskExecutorRef = new RuntimeBeanReference(taskExecutorBeanId);
      stateBuilder.addPropertyValue("taskExecutor", taskExecutorRef);
    }

    List<Element> flowElements = DomUtils.getChildElementsByTagName(element, "flow");

    if (flowElements.size() < 2) {
      parserContext
          .getReaderContext()
          .error("A <split/> must contain at least two 'flow' elements.", element);
    }

    Collection<BeanDefinition> flows = new ManagedList<BeanDefinition>();
    int i = 0;
    String prefix = idAttribute;
    for (Element nextElement : flowElements) {
      String ref = nextElement.getAttribute(PARENT_ATTR);
      if (StringUtils.hasText(ref)) {
        if (nextElement.getElementsByTagName("*").getLength() > 0) {
          parserContext
              .getReaderContext()
              .error(
                  "A <flow/> in a <split/> must have ref= or nested <flow/>, but not both.",
                  nextElement);
        }
        AbstractBeanDefinition flowDefinition = new GenericBeanDefinition();
        flowDefinition.setParentName(ref);
        MutablePropertyValues propertyValues = flowDefinition.getPropertyValues();
        propertyValues.addPropertyValue("name", prefix + "." + i);
        flows.add(flowDefinition);
      } else {
        InlineFlowParser flowParser = new InlineFlowParser(prefix + "." + i, jobFactoryRef);
        flows.add(flowParser.parse(nextElement, parserContext));
      }
      i++;
    }

    stateBuilder.addConstructorArgValue(flows);
    stateBuilder.addConstructorArgValue(prefix);

    return InlineFlowParser.getNextElements(
        parserContext, stateBuilder.getBeanDefinition(), element);
  }
  @Override
  protected void doParse(
      Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
    if (element.hasAttribute(ADDRESSES)
        && (element.hasAttribute(HOST_ATTRIBUTE) || element.hasAttribute(PORT_ATTRIBUTE))) {
      parserContext
          .getReaderContext()
          .error(
              "If the 'addresses' attribute is provided, a connection "
                  + "factory can not have 'host' or 'port' attributes.",
              element);
    }

    NamespaceUtils.addConstructorArgParentRefIfAttributeDefined(
        builder, element, CONNECTION_FACTORY_ATTRIBUTE);
    NamespaceUtils.setValueIfAttributeDefined(builder, element, CHANNEL_CACHE_SIZE_ATTRIBUTE);
    NamespaceUtils.setValueIfAttributeDefined(builder, element, HOST_ATTRIBUTE);
    NamespaceUtils.setValueIfAttributeDefined(builder, element, PORT_ATTRIBUTE);
    NamespaceUtils.setValueIfAttributeDefined(builder, element, USER_ATTRIBUTE);
    NamespaceUtils.setValueIfAttributeDefined(builder, element, PASSWORD_ATTRIBUTE);
    NamespaceUtils.setValueIfAttributeDefined(builder, element, VIRTUAL_HOST_ATTRIBUTE);
    NamespaceUtils.setReferenceIfAttributeDefined(builder, element, EXECUTOR_ATTRIBUTE);
    NamespaceUtils.setValueIfAttributeDefined(builder, element, ADDRESSES);
    NamespaceUtils.setValueIfAttributeDefined(builder, element, PUBLISHER_CONFIRMS);
    NamespaceUtils.setValueIfAttributeDefined(builder, element, PUBLISHER_RETURNS);
    NamespaceUtils.setValueIfAttributeDefined(
        builder, element, REQUESTED_HEARTBEAT, "requestedHeartBeat");
    NamespaceUtils.setValueIfAttributeDefined(builder, element, CONNECTION_TIMEOUT);
    NamespaceUtils.setValueIfAttributeDefined(builder, element, CACHE_MODE);
    NamespaceUtils.setValueIfAttributeDefined(builder, element, CONNECTION_CACHE_SIZE_ATTRIBUTE);
    NamespaceUtils.setReferenceIfAttributeDefined(
        builder, element, THREAD_FACTORY, "connectionThreadFactory");
  }
  @Override
  protected void doParse(
      Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
    String exchangeName = element.getAttribute(NAME_ATTRIBUTE);
    builder.addConstructorArgValue(new TypedStringValue(exchangeName));
    parseBindings(element, parserContext, builder, exchangeName);

    NamespaceUtils.addConstructorArgBooleanValueIfAttributeDefined(
        builder, element, DURABLE_ATTRIBUTE, true);
    NamespaceUtils.addConstructorArgBooleanValueIfAttributeDefined(
        builder, element, AUTO_DELETE_ATTRIBUTE, false);

    Element argumentsElement = DomUtils.getChildElementByTagName(element, ARGUMENTS_ELEMENT);
    if (argumentsElement != null) {

      String ref = argumentsElement.getAttribute(REF_ATTRIBUTE);
      Map<?, ?> map =
          parserContext
              .getDelegate()
              .parseMapElement(argumentsElement, builder.getRawBeanDefinition());
      if (StringUtils.hasText(ref)) {
        if (map != null && map.size() > 0) {
          parserContext
              .getReaderContext()
              .error("You cannot have both a 'ref' and a nested map", element);
        }
        builder.addConstructorArgReference(ref);
      } else {
        builder.addConstructorArgValue(map);
      }
    }

    NamespaceUtils.parseDeclarationControls(element, builder);
  }
  @Override
  public BeanDefinition parse(Element element, ParserContext parserContext) {
    Object source = parserContext.extractSource(element);

    CompositeComponentDefinition compDefinition =
        new CompositeComponentDefinition(element.getTagName(), source);
    parserContext.pushContainingComponent(compDefinition);

    BeanDefinitionRegistry registry = parserContext.getRegistry();

    if (registry.containsBeanDefinition(STAT_ANNOTATION_PROCESSOR_BEAN_NAME)) {
      parserContext
          .getReaderContext()
          .error("Only one DruidStatBeanDefinitionParser may exist within the context.", source);
    } else {
      BeanDefinitionBuilder builder =
          BeanDefinitionBuilder.genericBeanDefinition(STAT_ANNOTATION_PROCESSOR_BEAN_CLASS);
      builder.getRawBeanDefinition().setSource(source);
      registerComponent(parserContext, builder, STAT_ANNOTATION_PROCESSOR_BEAN_NAME);
    }

    if (!registry.containsBeanDefinition(STAT_ANNOTATION_ADVICE_BEAN_NAME)) {
      BeanDefinitionBuilder builder =
          BeanDefinitionBuilder.genericBeanDefinition(STAT_ANNOTATION_ADVICE_BEAN_CLASS);
      builder.getRawBeanDefinition().setSource(source);
      registerComponent(parserContext, builder, STAT_ANNOTATION_ADVICE_BEAN_NAME);
    }

    parserContext.popAndRegisterContainingComponent();

    return null;
  }
  public BeanDefinition parse(Element element, ParserContext parserContext) {

    final XmlReaderContext readerContext = parserContext.getReaderContext();
    final ClassLoader beanClassLoader =
        readerContext.getBeanClassLoader() != null
            ? readerContext.getBeanClassLoader()
            : Thread.currentThread().getContextClassLoader();

    String[] basePackages =
        StringUtils.commaDelimitedListToStringArray(element.getAttribute(BASE_PACKAGE_ATTRIBUTE));

    String dataSourceId = element.getAttribute(DATA_SOURCE_ATTRIBUTE);
    if (!StringUtils.hasText(dataSourceId)) {
      throw new BeanDefinitionParsingException(
          new Problem(
              "Attribute ["
                  + DATA_SOURCE_ATTRIBUTE
                  + "] of tag <gorm:sessionFactory> must be specified!",
              new Location(readerContext.getResource())));
    }

    // Actually scan for bean definitions and register them.
    BeanDefinitionRegistry targetRegistry = parserContext.getRegistry();

    // setup the GrailsApplication instance
    parseGrailsApplication(element, parserContext, readerContext, beanClassLoader, basePackages);

    GenericBeanDefinition postProccessingBeanDef = new GenericBeanDefinition();
    postProccessingBeanDef.setBeanClass(GORMEnhancingBeanPostProcessor.class);

    targetRegistry.registerBeanDefinition("gormEnhancingPostProcessor", postProccessingBeanDef);

    return parseSessionFactory(element, dataSourceId, targetRegistry, parserContext);
  }
示例#10
0
  @Override
  protected void doParse(
      Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
    String connectionFactoryRef = element.getAttribute(CONNECTION_FACTORY_ATTRIBUTE);

    if (!StringUtils.hasText(connectionFactoryRef)) {
      parserContext
          .getReaderContext()
          .error("A '" + CONNECTION_FACTORY_ATTRIBUTE + "' attribute must be set.", element);
    }

    if (StringUtils.hasText(connectionFactoryRef)) {
      // Use constructor with connectionFactory parameter
      builder.addConstructorArgReference(connectionFactoryRef);
    }

    NamespaceUtils.setValueIfAttributeDefined(builder, element, CHANNEL_TRANSACTED_ATTRIBUTE);
    NamespaceUtils.setValueIfAttributeDefined(builder, element, QUEUE_ATTRIBUTE);
    NamespaceUtils.setValueIfAttributeDefined(builder, element, EXCHANGE_ATTRIBUTE);
    NamespaceUtils.setValueIfAttributeDefined(builder, element, ROUTING_KEY_ATTRIBUTE);
    NamespaceUtils.setValueIfAttributeDefined(builder, element, REPLY_TIMEOUT_ATTRIBUTE);
    NamespaceUtils.setValueIfAttributeDefined(builder, element, ENCODING_ATTRIBUTE);
    NamespaceUtils.setReferenceIfAttributeDefined(builder, element, MESSAGE_CONVERTER_ATTRIBUTE);
    NamespaceUtils.setReferenceIfAttributeDefined(builder, element, REPLY_QUEUE);
  }
  private ManagedList<AbstractBeanDefinition> parseListeners(
      Element element, ParserContext parserContext) {
    List<Element> listenersElements =
        DomUtils.getChildElementsByTagName(element, LISTENERS_ELEMENT);

    ManagedList<AbstractBeanDefinition> listeners = new ManagedList<AbstractBeanDefinition>();

    if (listenersElements.size() == 1) {
      Element listenersElement = listenersElements.get(0);
      CompositeComponentDefinition compositeDef =
          new CompositeComponentDefinition(
              listenersElement.getTagName(), parserContext.extractSource(element));
      parserContext.pushContainingComponent(compositeDef);
      listeners.setMergeEnabled(false);
      List<Element> listenerElements =
          DomUtils.getChildElementsByTagName(listenersElement, LISTENER_ELEMENT);
      for (Element listenerElement : listenerElements) {
        BeanDefinitionBuilder bd = BeanDefinitionBuilder.genericBeanDefinition(listenerType);
        bd.addPropertyValue(
            "delegate", new RuntimeBeanReference(listenerElement.getAttribute(REF_ATTRIBUTE)));
        listeners.add(bd.getBeanDefinition());
      }
      parserContext.popAndRegisterContainingComponent();
    } else if (listenersElements.size() > 1) {
      parserContext
          .getReaderContext()
          .error(
              "The '<listeners/>' element may not appear more than once in a single <job/>.",
              element);
    }

    return listeners;
  }
  @Override
  protected void doParse(
      Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
    attributesToProperties(element, builder, "basedir");

    URL configFileURL;

    try {
      configFileURL = parserContext.getReaderContext().getResource().getURL();
    } catch (IOException e) {
      configFileURL = null;
    }

    if (configFileURL != null) {
      builder.addPropertyValue("configFileURL", configFileURL);
    }

    ElementSelector pathSelector = and(sameNs(element), name("path"));
    List<Object> paths = createManagedList(element, parserContext);

    for (Element subElement : subElements(element, pathSelector)) {
      paths.add(parsePath(subElement, parserContext));
    }

    builder.addPropertyValue("paths", paths);
  }
 /**
  * Checks the value of an XML attribute which represents a redirect URL. If not empty or starting
  * with "$" (potential placeholder), "/" or "http" it will raise an error.
  */
 static void validateHttpRedirect(String url, ParserContext pc, Object source) {
   if (!StringUtils.hasText(url) || UrlUtils.isValidRedirectUrl(url) || url.startsWith("$")) {
     return;
   }
   pc.getReaderContext()
       .warning(url + " is not a valid redirect URL (must start with '/' or http(s))", source);
 }
 @Override
 protected void doParse(
     Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
   builder.addConstructorArgValue(this.expectReply);
   String inputChannelAttributeName = this.getInputChannelAttributeName();
   String inputChannelRef = element.getAttribute(inputChannelAttributeName);
   if (!StringUtils.hasText(inputChannelRef)) {
     parserContext
         .getReaderContext()
         .error("a '" + inputChannelAttributeName + "' reference is required", element);
   }
   builder.addPropertyReference("requestChannel", inputChannelRef);
   if (this.expectReply) {
     IntegrationNamespaceUtils.setReferenceIfAttributeDefined(builder, element, "reply-channel");
     IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "request-timeout");
     IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "reply-timeout");
     IntegrationNamespaceUtils.setValueIfAttributeDefined(
         builder, element, "extract-reply-payload");
     IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "reply-key");
     IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "convert-exceptions");
   } else {
     IntegrationNamespaceUtils.setValueIfAttributeDefined(
         builder, element, "send-timeout", "requestTimeout");
   }
   IntegrationNamespaceUtils.setValueIfAttributeDefined(
       builder, element, "supported-methods", "supportedMethodNames");
   IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "request-payload-type");
   IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "view-name");
   IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "errors-key");
   IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "error-code");
   IntegrationNamespaceUtils.setReferenceIfAttributeDefined(
       builder, element, "message-converters");
   IntegrationNamespaceUtils.setReferenceIfAttributeDefined(builder, element, "header-mapper");
 }
 private void getComponent(ParserContext parserContext, BeanDefinitionBuilder beanDefBuilder) {
   parserContext.registerComponent(
       new BeanComponentDefinition(
           beanDefBuilder.getBeanDefinition(),
           parserContext
               .getReaderContext()
               .registerWithGeneratedName(beanDefBuilder.getBeanDefinition())));
 }
  @Override
  protected BeanDefinitionBuilder parseHandler(Element element, ParserContext parserContext) {
    BeanDefinitionBuilder builder =
        BeanDefinitionBuilder.genericBeanDefinition(
            "org.springframework.integration.http.outbound.HttpRequestExecutingMessageHandler");
    builder.addConstructorArgValue(element.getAttribute("url"));
    IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "http-method");

    String restTemplate = element.getAttribute("rest-template");
    if (StringUtils.hasText(restTemplate)) {
      HttpAdapterParsingUtils.verifyNoRestTemplateAttributes(element, parserContext);
      builder.addConstructorArgReference(restTemplate);
    } else {
      for (String referenceAttributeName :
          HttpAdapterParsingUtils.REST_TEMPLATE_REFERENCE_ATTRIBUTES) {
        IntegrationNamespaceUtils.setReferenceIfAttributeDefined(
            builder, element, referenceAttributeName);
      }
    }

    String headerMapper = element.getAttribute("header-mapper");
    String mappedRequestHeaders = element.getAttribute("mapped-request-headers");
    String mappedResponseHeaders = element.getAttribute("mapped-response-headers");
    if (StringUtils.hasText(headerMapper)) {
      if (StringUtils.hasText(mappedRequestHeaders) || StringUtils.hasText(mappedResponseHeaders)) {
        parserContext
            .getReaderContext()
            .error(
                "Neither 'mappped-request-headers' or 'mapped-response-headers' "
                    + "attributes are allowed when a 'header-mapper' has been specified.",
                parserContext.extractSource(element));
        return null;
      }
      builder.addPropertyReference("headerMapper", headerMapper);
    } else {
      BeanDefinitionBuilder headerMapperBuilder =
          BeanDefinitionBuilder.genericBeanDefinition(
              "org.springframework.integration.http.support.DefaultHttpHeaderMapper");
      headerMapperBuilder.setFactoryMethod("outboundMapper");
      IntegrationNamespaceUtils.setValueIfAttributeDefined(
          headerMapperBuilder, element, "mapped-request-headers", "outboundHeaderNames");
      IntegrationNamespaceUtils.setValueIfAttributeDefined(
          headerMapperBuilder, element, "mapped-response-headers", "inboundHeaderNames");
      builder.addPropertyValue("headerMapper", headerMapperBuilder.getBeanDefinition());
    }
    IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "charset");
    IntegrationNamespaceUtils.setValueIfAttributeDefined(
        builder, element, "extract-request-payload", "extractPayload");
    IntegrationNamespaceUtils.setValueIfAttributeDefined(
        builder, element, "expected-response-type");
    IntegrationNamespaceUtils.setValueIfAttributeDefined(
        builder, element, "reply-timeout", "sendTimeout");
    IntegrationNamespaceUtils.setReferenceIfAttributeDefined(
        builder, element, "reply-channel", "outputChannel");
    HttpAdapterParsingUtils.configureUriVariableExpressions(builder, element);
    IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "transfer-cookies");
    return builder;
  }
  public static RootBeanDefinition createExpressionDefinitionFromValueOrExpression(
      String valueElementName,
      String expressionElementName,
      ParserContext parserContext,
      Element element,
      boolean oneRequired) {

    Assert.hasText(valueElementName, "'valueElementName' must not be empty");
    Assert.hasText(expressionElementName, "'expressionElementName' must no be empty");

    String valueElementValue = element.getAttribute(valueElementName);
    String expressionElementValue = element.getAttribute(expressionElementName);

    boolean hasAttributeValue = StringUtils.hasText(valueElementValue);
    boolean hasAttributeExpression = StringUtils.hasText(expressionElementValue);

    if (hasAttributeValue && hasAttributeExpression) {
      parserContext
          .getReaderContext()
          .error(
              "Only one of '"
                  + valueElementName
                  + "' or '"
                  + expressionElementName
                  + "' is allowed",
              element);
    }

    if (oneRequired && (!hasAttributeValue && !hasAttributeExpression)) {
      parserContext
          .getReaderContext()
          .error(
              "One of '" + valueElementName + "' or '" + expressionElementName + "' is required",
              element);
    }
    RootBeanDefinition expressionDef = null;
    if (hasAttributeValue) {
      expressionDef = new RootBeanDefinition(LiteralExpression.class);
      expressionDef.getConstructorArgumentValues().addGenericArgumentValue(valueElementValue);
    } else if (hasAttributeExpression) {
      expressionDef = new RootBeanDefinition(ExpressionFactoryBean.class);
      expressionDef.getConstructorArgumentValues().addGenericArgumentValue(expressionElementValue);
    }
    return expressionDef;
  }
  @Override
  protected String parseItemName(ParserContext parserContext, Element element, BeanDefinition bd) {
    String resourceName =
        assertNotNull(
            trimToNull(element.getAttribute(SCRIPT_SOURCE_ATTRIBUTE)),
            "Missing Attribute: %s",
            SCRIPT_SOURCE_ATTRIBUTE);

    Resource resource =
        parserContext.getReaderContext().getResourceLoader().getResource(resourceName);

    try {
      return resource.getURI().normalize().toString();
    } catch (IOException e) {
      parserContext.getReaderContext().error("Failed to get resource: " + resourceName, element, e);
      return null;
    }
  }
  /**
   * Create a new {@link BeanDefinitionBuilder} for the class {@link StoredProcExecutor}. Initialize
   * the wrapped {@link StoredProcExecutor} with common properties.
   *
   * @param element Must not be Null
   * @param parserContext Must not be Null
   * @return The {@link BeanDefinitionBuilder} for the {@link StoredProcExecutor}
   */
  public static BeanDefinitionBuilder getStoredProcExecutorBuilder(
      final Element element, final ParserContext parserContext) {

    Assert.notNull(element, "The provided element must not be Null.");
    Assert.notNull(parserContext, "The provided parserContext must not be Null.");

    final String dataSourceRef = element.getAttribute("data-source");

    final BeanDefinitionBuilder storedProcExecutorBuilder =
        BeanDefinitionBuilder.genericBeanDefinition(StoredProcExecutor.class);
    storedProcExecutorBuilder.addConstructorArgReference(dataSourceRef);

    final String storedProcedureName = element.getAttribute("stored-procedure-name");
    final String storedProcedureNameExpression =
        element.getAttribute("stored-procedure-name-expression");
    boolean hasStoredProcedureName = StringUtils.hasText(storedProcedureName);
    boolean hasStoredProcedureNameExpression = StringUtils.hasText(storedProcedureNameExpression);

    if (!(hasStoredProcedureName ^ hasStoredProcedureNameExpression)) {
      parserContext
          .getReaderContext()
          .error(
              "Exactly one of 'stored-procedure-name' or 'stored-procedure-name-expression' is required",
              element);
    }

    BeanDefinitionBuilder expressionBuilder;
    if (hasStoredProcedureNameExpression) {
      expressionBuilder = BeanDefinitionBuilder.genericBeanDefinition(ExpressionFactoryBean.class);
      expressionBuilder.addConstructorArgValue(storedProcedureNameExpression);
    } else {
      expressionBuilder = BeanDefinitionBuilder.genericBeanDefinition(LiteralExpression.class);
      expressionBuilder.addConstructorArgValue(storedProcedureName);
    }
    storedProcExecutorBuilder.addPropertyValue(
        "storedProcedureNameExpression", expressionBuilder.getBeanDefinition());

    IntegrationNamespaceUtils.setValueIfAttributeDefined(
        storedProcExecutorBuilder, element, "ignore-column-meta-data");
    IntegrationNamespaceUtils.setValueIfAttributeDefined(
        storedProcExecutorBuilder, element, "jdbc-call-operations-cache-size");

    final ManagedList<BeanDefinition> procedureParameterList =
        StoredProcParserUtils.getProcedureParameterBeanDefinitions(element, parserContext);
    final ManagedList<BeanDefinition> sqlParameterDefinitionList =
        StoredProcParserUtils.getSqlParameterDefinitionBeanDefinitions(element, parserContext);

    if (!procedureParameterList.isEmpty()) {
      storedProcExecutorBuilder.addPropertyValue("procedureParameters", procedureParameterList);
    }
    if (!sqlParameterDefinitionList.isEmpty()) {
      storedProcExecutorBuilder.addPropertyValue("sqlParameters", sqlParameterDefinitionList);
    }

    return storedProcExecutorBuilder;
  }
  private RootBeanDefinition parseAttributeSource(Element attrEle, ParserContext parserContext) {
    List<Element> methods = DomUtils.getChildElementsByTagName(attrEle, METHOD_ELEMENT);
    ManagedMap<TypedStringValue, RuleBasedTransactionAttribute> transactionAttributeMap =
        new ManagedMap<TypedStringValue, RuleBasedTransactionAttribute>(methods.size());
    transactionAttributeMap.setSource(parserContext.extractSource(attrEle));

    for (Element methodEle : methods) {
      String name = methodEle.getAttribute(METHOD_NAME_ATTRIBUTE);
      TypedStringValue nameHolder = new TypedStringValue(name);
      nameHolder.setSource(parserContext.extractSource(methodEle));

      RuleBasedTransactionAttribute attribute = new RuleBasedTransactionAttribute();
      String propagation = methodEle.getAttribute(PROPAGATION_ATTRIBUTE);
      String isolation = methodEle.getAttribute(ISOLATION_ATTRIBUTE);
      String timeout = methodEle.getAttribute(TIMEOUT_ATTRIBUTE);
      String readOnly = methodEle.getAttribute(READ_ONLY_ATTRIBUTE);
      if (StringUtils.hasText(propagation)) {
        attribute.setPropagationBehaviorName(
            RuleBasedTransactionAttribute.PREFIX_PROPAGATION + propagation);
      }
      if (StringUtils.hasText(isolation)) {
        attribute.setIsolationLevelName(RuleBasedTransactionAttribute.PREFIX_ISOLATION + isolation);
      }
      if (StringUtils.hasText(timeout)) {
        try {
          attribute.setTimeout(Integer.parseInt(timeout));
        } catch (NumberFormatException ex) {
          parserContext
              .getReaderContext()
              .error("Timeout must be an integer value: [" + timeout + "]", methodEle);
        }
      }
      if (StringUtils.hasText(readOnly)) {
        attribute.setReadOnly(Boolean.valueOf(methodEle.getAttribute(READ_ONLY_ATTRIBUTE)));
      }

      List<RollbackRuleAttribute> rollbackRules = new LinkedList<RollbackRuleAttribute>();
      if (methodEle.hasAttribute(ROLLBACK_FOR_ATTRIBUTE)) {
        String rollbackForValue = methodEle.getAttribute(ROLLBACK_FOR_ATTRIBUTE);
        addRollbackRuleAttributesTo(rollbackRules, rollbackForValue);
      }
      if (methodEle.hasAttribute(NO_ROLLBACK_FOR_ATTRIBUTE)) {
        String noRollbackForValue = methodEle.getAttribute(NO_ROLLBACK_FOR_ATTRIBUTE);
        addNoRollbackRuleAttributesTo(rollbackRules, noRollbackForValue);
      }
      attribute.setRollbackRules(rollbackRules);

      transactionAttributeMap.put(nameHolder, attribute);
    }

    RootBeanDefinition attributeSourceDefinition =
        new RootBeanDefinition(NameMatchTransactionAttributeSource.class);
    attributeSourceDefinition.setSource(parserContext.extractSource(attrEle));
    attributeSourceDefinition.getPropertyValues().add("nameMap", transactionAttributeMap);
    return attributeSourceDefinition;
  }
 private Class<?> lookupConfigClass(Element element, ParserContext parserContext) {
   Class<?> configClass = GrailsAnnotationConfiguration.class;
   final ClassLoader classLoader = parserContext.getReaderContext().getBeanClassLoader();
   final String configClassName = element.getAttribute(CONFIG_CLASS_ATTRIBUTE);
   if (StringUtils.hasText(configClassName)) {
     try {
       configClass = classLoader.loadClass(configClassName);
     } catch (ClassNotFoundException e) {
       throw new BeanDefinitionParsingException(
           new Problem(
               "Unable to load specified SessionFactory configClass implementation: "
                   + e.getMessage(),
               new Location(parserContext.getReaderContext().getResource()),
               null,
               e));
     }
   }
   return configClass;
 }
  @Override
  protected AbstractBeanDefinition doParse(
      Element element, ParserContext parserContext, String channelName) {
    if (parserContext.isNested()) {
      if (channelName != null) {
        String elementDescription = IntegrationNamespaceUtils.createElementDescription(element);
        parserContext
            .getReaderContext()
            .error(
                "The 'channel' attribute isn't allowed for "
                    + elementDescription
                    + " when it is used as a nested element,"
                    + " e.g. inside a <chain/>",
                element);
      }
      AbstractBeanDefinition consumerBeanDefinition = this.parseConsumer(element, parserContext);
      this.configureRequestHandlerAdviceChain(element, parserContext, consumerBeanDefinition, null);
      return consumerBeanDefinition;
    }
    BeanDefinitionBuilder builder =
        BeanDefinitionBuilder.genericBeanDefinition(ConsumerEndpointFactoryBean.class);
    Element pollerElement = DomUtils.getChildElementByTagName(element, "poller");
    BeanComponentDefinition handlerBeanComponentDefinition =
        this.doParseAndRegisterConsumer(element, parserContext);
    builder.addPropertyReference("handler", handlerBeanComponentDefinition.getBeanName());
    IntegrationNamespaceUtils.checkAndConfigureFixedSubscriberChannel(
        element, parserContext, channelName, handlerBeanComponentDefinition.getBeanName());
    if (pollerElement != null) {
      if (!StringUtils.hasText(channelName)) {
        parserContext
            .getReaderContext()
            .error(
                "outbound channel adapter with a 'poller' requires a 'channel' to poll", element);
      }
      IntegrationNamespaceUtils.configurePollerMetadata(pollerElement, builder, parserContext);
    }
    builder.addPropertyValue("inputChannelName", channelName);

    this.configureRequestHandlerAdviceChain(
        element, parserContext, handlerBeanComponentDefinition.getBeanDefinition(), builder);

    return builder.getBeanDefinition();
  }
  /**
   * @param storedProcComponent
   * @param parserContext
   */
  public static ManagedList<BeanDefinition> getSqlParameterDefinitionBeanDefinitions(
      Element storedProcComponent, ParserContext parserContext) {
    List<Element> sqlParameterDefinitionChildElements =
        DomUtils.getChildElementsByTagName(storedProcComponent, "sql-parameter-definition");
    ManagedList<BeanDefinition> sqlParameterList = new ManagedList<BeanDefinition>();

    for (Element childElement : sqlParameterDefinitionChildElements) {

      String name = childElement.getAttribute("name");
      String sqlType = childElement.getAttribute("type");
      String direction = childElement.getAttribute("direction");
      String scale = childElement.getAttribute("scale");

      final BeanDefinitionBuilder parameterBuilder;

      if ("OUT".equalsIgnoreCase(direction)) {
        parameterBuilder = BeanDefinitionBuilder.genericBeanDefinition(SqlOutParameter.class);
      } else if ("INOUT".equalsIgnoreCase(direction)) {
        parameterBuilder = BeanDefinitionBuilder.genericBeanDefinition(SqlInOutParameter.class);
      } else {
        parameterBuilder = BeanDefinitionBuilder.genericBeanDefinition(SqlParameter.class);
      }

      if (StringUtils.hasText(name)) {
        parameterBuilder.addConstructorArgValue(name);
      } else {
        parserContext
            .getReaderContext()
            .error(
                "The 'name' attribute must be set for the Sql parameter element.",
                storedProcComponent);
      }

      if (StringUtils.hasText(sqlType)) {

        JdbcTypesEnum jdbcTypeEnum = JdbcTypesEnum.convertToJdbcTypesEnum(sqlType);

        if (jdbcTypeEnum != null) {
          parameterBuilder.addConstructorArgValue(jdbcTypeEnum.getCode());
        } else {
          parameterBuilder.addConstructorArgValue(sqlType);
        }

      } else {
        parameterBuilder.addConstructorArgValue(Types.VARCHAR);
      }

      if (StringUtils.hasText(scale)) {
        parameterBuilder.addConstructorArgValue(new TypedStringValue(scale, Integer.class));
      }

      sqlParameterList.add(parameterBuilder.getBeanDefinition());
    }
    return sqlParameterList;
  }
 private void verifySchemaVersion(Element element, ParserContext parserContext) {
   if (!(matchesVersion(element)
       && matchesVersion(element.getOwnerDocument().getDocumentElement()))) {
     parserContext
         .getReaderContext()
         .error(
             "You cannot use prior versions of Spring Integration schemas with Spring Integration "
                 + VERSION
                 + ". Please upgrade your schema declarations or use versionless aliases (e.g. spring-integration.xsd).",
             element);
   }
 }
  private void checkForDeprecatedSessionControllerRef(Element element, ParserContext pc) {
    final String ATT_SESSION_CONTROLLER_REF = "session-controller-ref";

    if (StringUtils.hasText(element.getAttribute(ATT_SESSION_CONTROLLER_REF))) {
      pc.getReaderContext()
          .warning(
              ATT_SESSION_CONTROLLER_REF
                  + " is not supported in Spring Security "
                  + " 3.0 and will be ignored. Use the attribute on the <concurrent-session-control> element instead.",
              pc.extractSource(element));
    }
  }
 @Override
 protected String resolveId(
     Element element, AbstractBeanDefinition definition, ParserContext parserContext)
     throws BeanDefinitionStoreException {
   String id = super.resolveId(element, definition, parserContext);
   if (!StringUtils.hasText(id)) {
     id = element.getAttribute("name");
   }
   if (!StringUtils.hasText(id)) {
     parserContext.getReaderContext().error("The 'id' or 'name' is required.", element);
   }
   return id;
 }
  private void configureRequestHandlerAdviceChain(
      Element element,
      ParserContext parserContext,
      BeanDefinition handlerBeanDefinition,
      BeanDefinitionBuilder consumerBuilder) {
    Element adviceChainElement =
        DomUtils.getChildElementByTagName(
            element, IntegrationNamespaceUtils.REQUEST_HANDLER_ADVICE_CHAIN);
    @SuppressWarnings("rawtypes")
    ManagedList adviceChain =
        IntegrationNamespaceUtils.configureAdviceChain(
            adviceChainElement, null, handlerBeanDefinition, parserContext);
    if (adviceChain != null) {
      /*
       * For ARPMH, the advice chain is injected so just the handleRequestMessage method is advised.
       * Sometime ARPMHs do double duty as a gateway and a channel adapter. The parser subclass
       * can indicate this by overriding isUsingReplyProducer(), or we can try to determine it from
       * the bean class.
       */
      boolean isReplyProducer = this.isUsingReplyProducer();
      if (!isReplyProducer) {
        Class<?> beanClass = null;
        if (handlerBeanDefinition instanceof AbstractBeanDefinition) {
          AbstractBeanDefinition abstractBeanDefinition =
              (AbstractBeanDefinition) handlerBeanDefinition;
          if (abstractBeanDefinition.hasBeanClass()) {
            beanClass = abstractBeanDefinition.getBeanClass();
          }
        }
        isReplyProducer =
            beanClass != null
                && AbstractReplyProducingMessageHandler.class.isAssignableFrom(beanClass);
      }

      if (isReplyProducer) {
        handlerBeanDefinition.getPropertyValues().add("adviceChain", adviceChain);
      } else if (consumerBuilder != null) {
        consumerBuilder.addPropertyValue("adviceChain", adviceChain);
      } else {
        String elementDescription = IntegrationNamespaceUtils.createElementDescription(element);
        parserContext
            .getReaderContext()
            .error(
                "'request-handler-advice-chain' isn't allowed for "
                    + elementDescription
                    + " within a <chain/>, because its Handler "
                    + "isn't an AbstractReplyProducingMessageHandler",
                element);
      }
    }
  }
 /**
  * Parse a "poller" element to provide a reference for the target BeanDefinitionBuilder. If the
  * poller element does not contain a "ref" attribute, this will create and register a
  * PollerMetadata instance and then add it as a property reference of the target builder.
  *
  * @param pollerElement the "poller" element to parse
  * @param targetBuilder the builder that expects the "trigger" property
  * @param parserContext the parserContext for the target builder
  */
 public static void configurePollerMetadata(
     Element pollerElement, BeanDefinitionBuilder targetBuilder, ParserContext parserContext) {
   if (pollerElement.hasAttribute("ref")) {
     int numberOfAttributes = pollerElement.getAttributes().getLength();
     if (numberOfAttributes != 1) {
       /*
        * When importing the core namespace, e.g. into jdbc, we get a 'default="false"' attribute,
        * even if not explicitly declared.
        */
       if (!(numberOfAttributes == 2
           && pollerElement.hasAttribute("default")
           && pollerElement.getAttribute("default").equals("false"))) {
         parserContext
             .getReaderContext()
             .error(
                 "A 'poller' element that provides a 'ref' must have no other attributes.",
                 pollerElement);
       }
     }
     if (pollerElement.getChildNodes().getLength() != 0) {
       parserContext
           .getReaderContext()
           .error(
               "A 'poller' element that provides a 'ref' must have no child elements.",
               pollerElement);
     }
     targetBuilder.addPropertyReference("pollerMetadata", pollerElement.getAttribute("ref"));
   } else {
     BeanDefinition beanDefinition =
         parserContext
             .getDelegate()
             .parseCustomElement(pollerElement, targetBuilder.getBeanDefinition());
     if (beanDefinition == null) {
       parserContext.getReaderContext().error("BeanDefinition must not be null", pollerElement);
     }
     targetBuilder.addPropertyValue("pollerMetadata", beanDefinition);
   }
 }
  /**
   * @param storedProcComponent
   * @param parserContext
   */
  public static ManagedMap<String, BeanDefinition> getReturningResultsetBeanDefinitions(
      Element storedProcComponent, ParserContext parserContext) {

    List<Element> returningResultsetChildElements =
        DomUtils.getChildElementsByTagName(storedProcComponent, "returning-resultset");

    ManagedMap<String, BeanDefinition> returningResultsetMap =
        new ManagedMap<String, BeanDefinition>();

    for (Element childElement : returningResultsetChildElements) {

      String name = childElement.getAttribute("name");
      String rowMapperAsString = childElement.getAttribute("row-mapper");

      if (!StringUtils.hasText(name)) {
        parserContext
            .getReaderContext()
            .error(
                "The 'name' attribute must be set for the 'returning-resultset' element.",
                storedProcComponent);
      }

      if (!StringUtils.hasText(rowMapperAsString)) {
        parserContext
            .getReaderContext()
            .error(
                "The 'row-mapper' attribute must be set for the 'returning-resultset' element.",
                storedProcComponent);
      }

      BeanDefinitionBuilder rowMapperBuilder =
          BeanDefinitionBuilder.genericBeanDefinition(rowMapperAsString);

      returningResultsetMap.put(name, rowMapperBuilder.getBeanDefinition());
    }

    return returningResultsetMap;
  }
 private static Class<?> determineClass(Element element, ParserContext parserContext) {
   Class<?> clazz = null;
   String elementName = element.getLocalName().trim();
   if ("outbound-channel-adapter".equals(elementName)) {
     clazz = StatusUpdatingMessageHandler.class;
   } else if ("dm-outbound-channel-adapter".equals(elementName)) {
     clazz = DirectMessageSendingMessageHandler.class;
   } else {
     parserContext
         .getReaderContext()
         .error("element '" + elementName + "' is not supported by this parser.", element);
   }
   return clazz;
 }