@Override
  protected void doParse(
      final Element element,
      final ParserContext parserContext,
      final BeanDefinitionBuilder builder) {
    String serviceRef = element.getAttribute("service-ref");
    builder.addConstructorArgValue(":" + serviceRef);
    builder.addConstructorArgReference(serviceRef);
    String marker = element.getAttribute("marker");
    if (StringUtils.hasLength(marker)) {
      Class<?> theClass =
          ClassUtils.resolveClassName(marker, Thread.currentThread().getContextClassLoader());
      if (!theClass.isAnnotation()) {
        throw new ConfigurationException(
            String.format("The class '%s' is not an annotation", marker));
      }
      builder.addPropertyValue("markerAnnotation", theClass);
    }

    // Register the post processor if there is not already one in this context
    String beanName = NamespaceBeanFactoryPostProcessor.class.getName();
    if (!parserContext.getRegistry().containsBeanDefinition(beanName)) {
      BeanDefinitionBuilder namespacePostProcessor =
          BeanDefinitionBuilder.genericBeanDefinition(NamespaceBeanFactoryPostProcessor.class);
      parserContext.registerBeanComponent(
          new BeanComponentDefinition(namespacePostProcessor.getBeanDefinition(), beanName));
    }
  }
  @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;
  }
 @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;
 }
Esempio n. 4
0
  private void autoRegisterBeanDefinition(
      String id, BeanDefinition definition, ParserContext parserContext, String contextId) {
    // it is a bit cumbersome to work with the spring bean definition parser
    // as we kinda need to eagerly register the bean definition on the parser context
    // and then later we might find out that we should not have done that in case we have multiple
    // camel contexts
    // that would have a id clash by auto registering the same bean definition with the same id such
    // as a producer template

    // see if we have already auto registered this id
    BeanDefinition existing = autoRegisterMap.get(id);
    if (existing == null) {
      // no then add it to the map and register it
      autoRegisterMap.put(id, definition);
      parserContext.registerComponent(new BeanComponentDefinition(definition, id));
      if (LOG.isDebugEnabled()) {
        LOG.debug(
            "Registered default: {} with id: {} on camel context: {}",
            new Object[] {definition.getBeanClassName(), id, contextId});
      }
    } else {
      // ups we have already registered it before with same id, but on another camel context
      // this is not good so we need to remove all traces of this auto registering.
      // end user must manually add the needed XML elements and provide unique ids access all camel
      // context himself.
      LOG.debug(
          "Unregistered default: {} with id: {} as we have multiple camel contexts and they must use unique ids."
              + " You must define the definition in the XML file manually to avoid id clashes when using multiple camel contexts",
          definition.getBeanClassName(),
          id);

      parserContext.getRegistry().removeBeanDefinition(id);
    }
  }
Esempio n. 5
0
 @SuppressWarnings("unchecked")
 public void handleListenersElement(
     Element stepElement, BeanDefinition beanDefinition, ParserContext parserContext) {
   MutablePropertyValues propertyValues = beanDefinition.getPropertyValues();
   List<Element> listenersElements =
       DomUtils.getChildElementsByTagName(stepElement, LISTENERS_ELE);
   if (listenersElements.size() == 1) {
     Element listenersElement = listenersElements.get(0);
     CompositeComponentDefinition compositeDef =
         new CompositeComponentDefinition(
             listenersElement.getTagName(), parserContext.extractSource(stepElement));
     parserContext.pushContainingComponent(compositeDef);
     ManagedList listenerBeans = new ManagedList();
     if (propertyValues.contains("listeners")) {
       listenerBeans = (ManagedList) propertyValues.getPropertyValue("listeners").getValue();
     }
     listenerBeans.setMergeEnabled(
         listenersElement.hasAttribute(MERGE_ATTR)
             && Boolean.valueOf(listenersElement.getAttribute(MERGE_ATTR)));
     List<Element> listenerElements =
         DomUtils.getChildElementsByTagName(listenersElement, "listener");
     if (listenerElements != null) {
       for (Element listenerElement : listenerElements) {
         listenerBeans.add(parse(listenerElement, parserContext));
       }
     }
     propertyValues.addPropertyValue("listeners", listenerBeans);
     parserContext.popAndRegisterContainingComponent();
   }
 }
  @SuppressWarnings("unchecked")
  public static BeanMetadataElement parseListenerElement(
      Element element, ParserContext parserContext, BeanDefinition enclosing) {
    String listenerRef = element.getAttribute(REF_ATTR);
    List<Element> beanElements = DomUtils.getChildElementsByTagName(element, BEAN_ELE);
    List<Element> refElements = DomUtils.getChildElementsByTagName(element, REF_ELE);

    verifyListenerAttributesAndSubelements(
        listenerRef, beanElements, refElements, element, parserContext);

    if (StringUtils.hasText(listenerRef)) {
      return new RuntimeBeanReference(listenerRef);
    } else if (beanElements.size() == 1) {
      Element beanElement = beanElements.get(0);
      BeanDefinitionHolder beanDefinitionHolder =
          parserContext.getDelegate().parseBeanDefinitionElement(beanElement, enclosing);
      parserContext
          .getDelegate()
          .decorateBeanDefinitionIfRequired(beanElement, beanDefinitionHolder);
      return beanDefinitionHolder;
    } else {
      return (BeanMetadataElement)
          parserContext.getDelegate().parsePropertySubElement(refElements.get(0), null);
    }
  }
  @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);
  }
  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);
  }
  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;
  }
  private static void registerComponent(
      ParserContext parserContext, BeanDefinitionBuilder builder, String beanName) {

    builder.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
    parserContext.getRegistry().registerBeanDefinition(beanName, builder.getBeanDefinition());
    BeanDefinitionHolder holder = new BeanDefinitionHolder(builder.getBeanDefinition(), beanName);
    parserContext.registerComponent(new BeanComponentDefinition(holder));
  }
 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;
  }
  @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();
  }
 /**
  * If the given parse operation is nested inside an instance of {@link
  * TemplateBeanDefinitionParser.TemplateComponentDefinition}, return the template bean
  * configuration associated with that component. Otherwise return null.
  */
 public static DefaultListableBeanFactory findEnclosingTemplateFactory(ParserContext context) {
   if (context.isNested()) {
     // TODO: support deeper nesting.  this logic breaks completely with bt:persister-chain.
     CompositeComponentDefinition parent = context.getContainingComponent();
     if (parent instanceof TemplateComponentDefinition)
       return ((TemplateComponentDefinition) parent).getTemplateFactory();
   }
   return null;
 }
  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;
  }
  @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);
  }
 private ManagedList<Object> extractBeanSubElements(
     Element parentElement, ParserContext parserContext) {
   ManagedList<Object> list = new ManagedList<Object>();
   list.setSource(parserContext.extractSource(parentElement));
   for (Element beanElement : DomUtils.getChildElementsByTagName(parentElement, "bean", "ref")) {
     Object object = parserContext.getDelegate().parsePropertySubElement(beanElement, null);
     list.add(object);
   }
   return list;
 }
  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));
    }
  }
Esempio n. 20
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);
  }
  /* (non-Javadoc)
   * @see org.springframework.beans.factory.xml.BeanDefinitionParser#parse(org.w3c.dom.Element, org.springframework.beans.factory.xml.ParserContext)
   */
  @Override
  public BeanDefinition parse(Element element, ParserContext parserContext) {
    Object source = parserContext.extractSource(element);

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

    VertxConfigUtils.registerAnnotationComponents(parserContext, source);
    parserContext.popAndRegisterContainingComponent();

    return null;
  }
  /**
   * Load the template BeanDefinition and call {@link #transform(ConfigurableListableBeanFactory,
   * BeanDefinition, Element, ParserContext)} to apply runtime configuration value to it. <code>
   * builder</code> will be configured to instantiate the bean in the Spring context that we are
   * parsing.
   *
   * <p>During parsing, an instance of {@link
   * TemplateBeanDefinitionParser.TemplateComponentDefinition} is pushed onto <code>ParserContext
   * </code> so that nested tags can access the enclosing template configuration with a call to
   * {@link #findEnclosingTemplateFactory(ParserContext)}. Subclasses can override {@link
   * #newComponentDefinition(String, Object, DefaultListableBeanFactory)} to provide a subclass of
   * {@link TemplateBeanDefinitionParser.TemplateComponentDefinition} to the parser context if
   * necessary.
   */
  @Override
  protected final void doParse(
      Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {

    // if we have multiple nested bean definitions, we only parse the template factory
    // once.  this allows configuration changes made by enclosing bean parsers to be inherited
    // by contained beans, which is quite useful.
    DefaultListableBeanFactory templateFactory = findEnclosingTemplateFactory(parserContext);
    TemplateComponentDefinition tcd = null;
    if (templateFactory == null) {

      // no nesting -- load the template XML configuration from the classpath.
      final BeanFactory parentFactory = (BeanFactory) parserContext.getRegistry();
      templateFactory = new DefaultListableBeanFactory(parentFactory);

      // load template bean definitions
      DefaultResourceLoader loader = new DefaultResourceLoader();
      XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(templateFactory);
      reader.setResourceLoader(loader);
      reader.setEntityResolver(new ResourceEntityResolver(loader));
      reader.loadBeanDefinitions(templateResource);

      // propagate factory post-processors from the source factory into the template
      // factory.
      BeanDefinition ppChain = new RootBeanDefinition(ChainingBeanFactoryPostProcessor.class);
      ppChain.getPropertyValues().addPropertyValue("targetFactory", templateFactory);
      parserContext.getReaderContext().registerWithGeneratedName(ppChain);

      // push component definition onto the parser stack for the benefit of
      // nested bean definitions.
      tcd =
          newComponentDefinition(
              element.getNodeName(), parserContext.extractSource(element), templateFactory);
      parserContext.pushContainingComponent(tcd);
    }

    try {
      // allow subclasses to apply overrides to the template bean definition.
      BeanDefinition def = templateFactory.getBeanDefinition(templateId);
      transform(templateFactory, def, element, parserContext);

      // setup our factory bean to instantiate the modified bean definition upon request.
      builder.addPropertyValue("beanFactory", templateFactory);
      builder.addPropertyValue("beanName", templateId);
      builder.getRawBeanDefinition().setAttribute("id", def.getAttribute("id"));

    } finally {
      if (tcd != null) parserContext.popContainingComponent();
    }
  }
  private ClassPathBeanDefinitionScanner configureScanner(
      ParserContext parserContext, BeanDefinitionRegistry registry) {
    XmlReaderContext readerContext = parserContext.getReaderContext();
    // Delegate bean definition registration to scanner class.
    ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(registry, false);
    scanner.setIncludeAnnotationConfig(false);
    scanner.addIncludeFilter(new AnnotationTypeFilter(Entity.class));

    scanner.setResourceLoader(readerContext.getResourceLoader());
    scanner.setBeanDefinitionDefaults(parserContext.getDelegate().getBeanDefinitionDefaults());
    scanner.setAutowireCandidatePatterns(
        parserContext.getDelegate().getAutowireCandidatePatterns());

    return scanner;
  }
 @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");
 }
 /**
  * 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) {
    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);
  }
Esempio n. 27
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);
  }
  @Override
  protected final void doParse(
      final Element e, final ParserContext parserContext, final BeanDefinitionBuilder builder) {

    builder.addConstructorArgValue(
        parserContext.getDelegate().parseListElement(e, builder.getBeanDefinition()));
  }
 public static BeanComponentDefinition parseInnerHandlerDefinition(
     Element element, ParserContext parserContext) {
   // parses out the inner bean definition for concrete implementation if defined
   List<Element> childElements = DomUtils.getChildElementsByTagName(element, "bean");
   BeanComponentDefinition innerComponentDefinition = null;
   if (childElements != null && childElements.size() == 1) {
     Element beanElement = childElements.get(0);
     BeanDefinitionParserDelegate delegate = parserContext.getDelegate();
     BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(beanElement);
     bdHolder = delegate.decorateBeanDefinitionIfRequired(beanElement, bdHolder);
     BeanDefinition inDef = bdHolder.getBeanDefinition();
     innerComponentDefinition = new BeanComponentDefinition(inDef, bdHolder.getBeanName());
   }
   String ref = element.getAttribute(REF_ATTRIBUTE);
   Assert.isTrue(
       !(StringUtils.hasText(ref) && innerComponentDefinition != null),
       "Ambiguous definition. Inner bean "
           + (innerComponentDefinition == null
               ? innerComponentDefinition
               : innerComponentDefinition.getBeanDefinition().getBeanClassName())
           + " declaration and \"ref\" "
           + ref
           + " are not allowed together.");
   return innerComponentDefinition;
 }
 private String createJobConfiguration(final Element element, final ParserContext parserContext) {
   BeanDefinitionBuilder factory =
       BeanDefinitionBuilder.rootBeanDefinition(getJobConfigurationDTO());
   factory.addConstructorArgValue(element.getAttribute(ID_ATTRIBUTE));
   if (!getJobConfigurationDTO().isAssignableFrom(ScriptJobConfigurationDto.class)) {
     factory.addConstructorArgValue(element.getAttribute(CLASS_ATTRIBUTE));
   }
   factory.addConstructorArgValue(element.getAttribute(SHARDING_TOTAL_COUNT_ATTRIBUTE));
   factory.addConstructorArgValue(element.getAttribute(CRON_ATTRIBUTE));
   if (getJobConfigurationDTO().isAssignableFrom(ScriptJobConfigurationDto.class)) {
     factory.addConstructorArgValue(element.getAttribute(SCRIPT_COMMAND_LINE_ATTRIBUTE));
   }
   addPropertyValueIfNotEmpty(
       SHARDING_ITEM_PARAMETERS_ATTRIBUTE, "shardingItemParameters", element, factory);
   addPropertyValueIfNotEmpty(JOB_PARAMETER_ATTRIBUTE, "jobParameter", element, factory);
   addPropertyValueIfNotEmpty(MONITOR_EXECUTION_ATTRIBUTE, "monitorExecution", element, factory);
   addPropertyValueIfNotEmpty(MONITOR_PORT_ATTRIBUTE, "monitorPort", element, factory);
   addPropertyValueIfNotEmpty(
       MAX_TIME_DIFF_SECONDS_ATTRIBUTE, "maxTimeDiffSeconds", element, factory);
   addPropertyValueIfNotEmpty(FAILOVER_ATTRIBUTE, "failover", element, factory);
   addPropertyValueIfNotEmpty(MISFIRE_ATTRIBUTE, "misfire", element, factory);
   addPropertyValueIfNotEmpty(
       JOB_SHARDING_STRATEGY_CLASS_ATTRIBUTE, "jobShardingStrategyClass", element, factory);
   addPropertyValueIfNotEmpty(DESCRIPTION_ATTRIBUTE, "description", element, factory);
   addPropertyValueIfNotEmpty(DISABLED_ATTRIBUTE, "disabled", element, factory);
   addPropertyValueIfNotEmpty(OVERWRITE_ATTRIBUTE, "overwrite", element, factory);
   setPropertiesValue(element, factory);
   String result = element.getAttribute(ID_ATTRIBUTE) + "Conf";
   parserContext.getRegistry().registerBeanDefinition(result, factory.getBeanDefinition());
   return result;
 }