예제 #1
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();
   }
 }
  /**
   * Convenience method to update a template bean definition from overriding XML data. If <code>
   * overrides</code> contains attribute <code>attribute</code> or a child element with name <code>
   * attribute</code>, transfer that attribute as a bean property onto <code>template</code>,
   * overwriting the default value.
   *
   * @param reference if true, the value of the attribute is to be interpreted as a runtime bean
   *     name reference; otherwise it is interpreted as a literal value
   */
  public static boolean overrideProperty(
      String attribute, BeanDefinition template, Element overrides, boolean reference) {
    Object value = null;
    if (overrides.hasAttribute(attribute)) {
      value = overrides.getAttribute(attribute);
    } else {
      NodeList children = overrides.getElementsByTagNameNS("*", attribute);
      if (children.getLength() == 1) {
        Element child = (Element) children.item(0);
        value = child.getTextContent();
      }
    }

    if (value != null) {
      if (reference) value = new RuntimeBeanReference(value.toString());

      String propName = Conventions.attributeNameToPropertyName(attribute);
      MutablePropertyValues props = template.getPropertyValues();
      props.removePropertyValue(propName);
      props.addPropertyValue(propName, value);
      return true;
    }

    return false;
  }
  private void registerBeanDefinitionsWithRegistry(BeanDefinitionRegistry registry) {
    for (Object key : beanDefinitions.keySet()) {
      BeanDefinition bd = beanDefinitions.get(key);
      if (LOG.isDebugEnabled()) {
        LOG.debug("[RuntimeConfiguration] Registering bean [" + key + "]");
        if (LOG.isTraceEnabled()) {
          PropertyValue[] pvs = bd.getPropertyValues().getPropertyValues();
          for (PropertyValue pv : pvs) {
            LOG.trace(
                "[RuntimeConfiguration] With property ["
                    + pv.getName()
                    + "] set to ["
                    + pv.getValue()
                    + "]");
          }
        }
      }
      final String beanName = key.toString();
      if (registry.containsBeanDefinition(beanName)) {
        removeBeanDefinition(registry, beanName);
      }

      registry.registerBeanDefinition(beanName, bd);
      registerBeanAliases(registry, beanName);
    }
  }
  @SuppressWarnings({"unchecked"})
  private void parseProcessors(
      Element element, ParserContext parserContext, GenericBeanDefinition beanDefinition) {
    Element processorsElement =
        DomUtils.getChildElementByTagName(element, EVENT_PROCESSORS_ELEMENT);

    Element snapshotTriggerElement =
        DomUtils.getChildElementByTagName(element, SNAPSHOT_TRIGGER_ELEMENT);
    if (snapshotTriggerElement != null) {
      BeanDefinition triggerDefinition =
          snapshotterTriggerParser.parse(snapshotTriggerElement, parserContext);
      PropertyValue aggregateCache = beanDefinition.getPropertyValues().getPropertyValue("cache");
      if (aggregateCache != null) {
        triggerDefinition.getPropertyValues().add("aggregateCache", aggregateCache.getValue());
      }
      beanDefinition.getPropertyValues().add(SNAPSHOTTER_TRIGGER_PROPERTY, triggerDefinition);
    }

    if (processorsElement != null) {
      List<Object> processorsList =
          parserContext.getDelegate().parseListElement(processorsElement, beanDefinition);
      if (!processorsList.isEmpty()) {
        beanDefinition.getPropertyValues().add(EVENT_STREAM_DECORATORS_PROPERTY, processorsList);
      }
    }
  }
  @Test
  public void testGetAnonymousInnerBeanFromScope() throws Exception {
    TestBean bean = (TestBean) this.beanFactory.getBean("outerBean");
    assertFalse(AopUtils.isAopProxy(bean));
    assertTrue(AopUtils.isCglibProxy(bean.getSpouse()));

    BeanDefinition beanDef = this.beanFactory.getBeanDefinition("outerBean");
    BeanDefinitionHolder innerBeanDef =
        (BeanDefinitionHolder) beanDef.getPropertyValues().getPropertyValue("spouse").getValue();
    String name = innerBeanDef.getBeanName();

    MockHttpServletRequest request = new MockHttpServletRequest();
    RequestAttributes requestAttributes = new ServletRequestAttributes(request);
    RequestContextHolder.setRequestAttributes(requestAttributes);

    try {
      assertNull(request.getAttribute("scopedTarget." + name));
      assertEquals("scoped", bean.getSpouse().getName());
      assertNotNull(request.getAttribute("scopedTarget." + name));
      assertEquals(TestBean.class, request.getAttribute("scopedTarget." + name).getClass());
      assertEquals("scoped", ((TestBean) request.getAttribute("scopedTarget." + name)).getName());
    } finally {
      RequestContextHolder.setRequestAttributes(null);
    }
  }
예제 #6
0
  public BeanDefinitionHolder decorate(
      Node node, BeanDefinitionHolder definition, ParserContext parserContext) {

    BeanDefinition bd = definition.getBeanDefinition();
    List<?> list = parserContext.getDelegate().parseListElement((Element) node, bd);
    bd.getPropertyValues().addPropertyValue(getPropertyName(node), list);
    return definition;
  }
 @SuppressWarnings("unchecked")
 @Test
 public void initParameters() throws IOException {
   BeanDefinition servletRegistrationBean = getBeanDefinition(InitParametersServlet.class);
   MutablePropertyValues propertyValues = servletRegistrationBean.getPropertyValues();
   assertThat((Map<String, String>) propertyValues.get("initParameters"))
       .containsEntry("a", "alpha")
       .containsEntry("b", "bravo");
 }
예제 #8
0
  /**
   * Retrieves the configured property values for the view bean definition associated with the given
   * id
   *
   * <p>Since constructing the View object can be expensive, when metadata only is needed this
   * method can be used to retrieve the configured property values. Note this looks at the merged
   * bean definition
   *
   * @param viewId - id for the view to retrieve
   * @return PropertyValues configured on the view bean definition, or null if view is not found
   */
  public PropertyValues getViewPropertiesById(String viewId) {
    String beanName = viewBeanEntriesById.get(viewId);
    if (StringUtils.isNotBlank(beanName)) {
      BeanDefinition beanDefinition = ddBeans.getMergedBeanDefinition(beanName);

      return beanDefinition.getPropertyValues();
    }

    return null;
  }
 @Test
 public void servletWithCustomName() throws IOException {
   ScannedGenericBeanDefinition scanned =
       new ScannedGenericBeanDefinition(
           new SimpleMetadataReaderFactory().getMetadataReader(CustomNameServlet.class.getName()));
   this.handler.handle(scanned, this.registry);
   BeanDefinition servletRegistrationBean = this.registry.getBeanDefinition("custom");
   MutablePropertyValues propertyValues = servletRegistrationBean.getPropertyValues();
   assertThat(propertyValues.get("name")).isEqualTo("custom");
 }
  private void addKieBaseModels(
      ConfigurableListableBeanFactory beanFactory, KieModuleModelImpl kieModuleModel) {
    for (String beanDef : beanFactory.getBeanDefinitionNames()) {
      BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanDef);
      if (beanDefinition.getBeanClassName().equalsIgnoreCase(KBaseFactoryBean.class.getName())) {
        KieBaseModelImpl kBase = new KieBaseModelImpl();
        kBase.setKModule(kieModuleModel);

        kBase.setName(getPropertyValue(beanDefinition, "kBaseName"));
        kBase.setDefault("true".equals(getPropertyValue(beanDefinition, "def")));

        String packages = getPropertyValue(beanDefinition, "packages");
        if (!packages.isEmpty()) {
          for (String pkg : packages.split(",")) {
            kBase.addPackage(pkg.trim());
          }
        }

        String includes = getPropertyValue(beanDefinition, "includes");
        if (!includes.isEmpty()) {
          for (String include : includes.split(",")) {
            kBase.addInclude(include.trim());
          }
        }

        String eventMode = getPropertyValue(beanDefinition, "eventProcessingMode");
        if (!eventMode.isEmpty()) {
          kBase.setEventProcessingMode(
              EventProcessingOption.determineEventProcessingMode(eventMode));
        }

        String equalsBehavior = getPropertyValue(beanDefinition, "equalsBehavior");
        if (!equalsBehavior.isEmpty()) {
          kBase.setEqualsBehavior(EqualityBehaviorOption.determineEqualityBehavior(equalsBehavior));
        }

        String declarativeAgenda = getPropertyValue(beanDefinition, "declarativeAgenda");
        if (!declarativeAgenda.isEmpty()) {
          kBase.setDeclarativeAgenda(
              DeclarativeAgendaOption.determineDeclarativeAgenda(declarativeAgenda));
        }

        String scope = getPropertyValue(beanDefinition, "scope");
        if (!scope.isEmpty()) {
          kBase.setScope(scope.trim());
        }

        kieModuleModel.getRawKieBaseModels().put(kBase.getName(), kBase);
        beanDefinition
            .getPropertyValues()
            .addPropertyValue(new PropertyValue("releaseId", releaseId));
        addKieSessionModels(beanFactory, kBase);
      }
    }
  }
예제 #11
0
 @Override
 public void postProcessBeanFactory(ConfigurableListableBeanFactory factory)
     throws BeansException {
   System.out.println("postProcessBeanFactory接口被调用");
   BeanDefinition bean = factory.getBeanDefinition("MyBean");
   // 拿到这个bean的所有属性
   MutablePropertyValues pv = bean.getPropertyValues();
   if (pv.contains("name")) {
     pv.addPropertyValue("name", "被修改了");
   }
 }
 /** {@inheritDoc} */
 public void postProcess(
     BundleContext bundleContext, ConfigurableListableBeanFactory beanFactory) {
   String[] beanDefinitionNames = beanFactory.getBeanDefinitionNames();
   for (String name : beanDefinitionNames) {
     BeanDefinition beanDefinition = beanFactory.getBeanDefinition(name);
     if (isServiceImportDefinition(beanDefinition)) {
       MutablePropertyValues propertyValues = beanDefinition.getPropertyValues();
       propertyValues.addPropertyValue(
           PROPERTY_CONTEXT_CLASS_LOADER, ImportContextClassLoaderEnum.UNMANAGED);
     }
   }
 }
 @SuppressWarnings("unchecked")
 public void customiseBeanDefinition(
     BeanDefinition beanDef, Element element, ParserContext parserContext) {
   String cronExpression = element.getAttribute("cronExpression");
   String startTime = element.getAttribute("startTime");
   String endTime = element.getAttribute("endTime");
   String taskScheduler = element.getAttribute("taskScheduler");
   String concurrent = element.getAttribute("concurrent");
   if (StringUtils.isEmpty(taskScheduler)) {
     taskScheduler = "taskScheduler";
   }
   String stepCommit = element.getAttribute("stepCommit");
   if (StringUtils.isNotEmpty(stepCommit)) {
     beanDef.getPropertyValues().addPropertyValue("stepCommit", Boolean.parseBoolean(stepCommit));
   }
   beanDef.getPropertyValues().addPropertyValue("cronExpression", cronExpression);
   beanDef.getPropertyValues().addPropertyValue("startTime", startTime);
   beanDef.getPropertyValues().addPropertyValue("endTime", endTime);
   beanDef
       .getPropertyValues()
       .addPropertyValue("taskScheduler", new RuntimeBeanReference(taskScheduler));
   if (StringUtils.isNotEmpty(concurrent)) {
     beanDef.getPropertyValues().addPropertyValue("concurrent", Boolean.parseBoolean(concurrent));
   }
   String[] timerProcessors = element.getAttribute("timerProcessors").split(",");
   List partitionProcessorList = new ManagedList();
   for (String timerProcessor : timerProcessors) {
     partitionProcessorList.add(new RuntimeBeanReference(timerProcessor.trim()));
   }
   beanDef.getPropertyValues().addPropertyValue("timerProcessors", partitionProcessorList);
 }
 @SuppressWarnings({"rawtypes"})
 public static void configureAndSetAdviceChainIfPresent(
     Element adviceChainElement,
     Element txElement,
     BeanDefinition parentBeanDefinition,
     ParserContext parserContext,
     String propertyName) {
   ManagedList adviceChain =
       configureAdviceChain(adviceChainElement, txElement, parentBeanDefinition, parserContext);
   if (adviceChain != null) {
     parentBeanDefinition.getPropertyValues().add(propertyName, adviceChain);
   }
 }
  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);
      }
    }
  }
  /**
   * 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();
    }
  }
 @Override
 protected void postProcessBuilder(BeanDefinitionBuilder builder, Element element) {
   BeanDefinition templateDefinition =
       (BeanDefinition)
           builder
               .getRawBeanDefinition()
               .getConstructorArgumentValues()
               .getIndexedArgumentValues()
               .values()
               .iterator()
               .next()
               .getValue();
   templateDefinition.getPropertyValues().add("existsMode", FtpRemoteFileTemplate.ExistsMode.NLST);
 }
예제 #18
0
  /**
   * Retrieves the configured property values for the view bean definition associated with the given
   * type and index
   *
   * <p>Since constructing the View object can be expensive, when metadata only is needed this
   * method can be used to retrieve the configured property values. Note this looks at the merged
   * bean definition
   *
   * @param viewTypeName - type name for the view
   * @param indexKey - Map of index key parameters, these are the parameters the indexer used to
   *     index the view initially and needs to identify an unique view instance
   * @return PropertyValues configured on the view bean definition, or null if view is not found
   */
  public PropertyValues getViewPropertiesByType(
      ViewType viewTypeName, Map<String, String> indexKey) {
    String index = buildTypeIndex(indexKey);

    ViewTypeDictionaryIndex typeIndex = getTypeIndex(viewTypeName);

    String beanName = typeIndex.get(index);
    if (StringUtils.isNotBlank(beanName)) {
      BeanDefinition beanDefinition = ddBeans.getMergedBeanDefinition(beanName);

      return beanDefinition.getPropertyValues();
    }

    return null;
  }
 @SuppressWarnings("unchecked")
 @Test
 public void defaultServletConfiguration() throws IOException {
   ScannedGenericBeanDefinition scanned =
       new ScannedGenericBeanDefinition(
           new SimpleMetadataReaderFactory()
               .getMetadataReader(DefaultConfigurationServlet.class.getName()));
   this.handler.handle(scanned, this.registry);
   BeanDefinition servletRegistrationBean =
       this.registry.getBeanDefinition(DefaultConfigurationServlet.class.getName());
   MutablePropertyValues propertyValues = servletRegistrationBean.getPropertyValues();
   assertThat(propertyValues.get("asyncSupported")).isEqualTo(false);
   assertThat(((Map<String, String>) propertyValues.get("initParameters"))).isEmpty();
   assertThat((Integer) propertyValues.get("loadOnStartup")).isEqualTo(-1);
   assertThat(propertyValues.get("name")).isEqualTo(DefaultConfigurationServlet.class.getName());
   assertThat((String[]) propertyValues.get("urlMappings")).isEmpty();
   assertThat(propertyValues.get("servlet")).isEqualTo(scanned);
 }
예제 #20
0
  protected void injectBeanPostProcessor(
      Element element,
      ParserContext parserContext,
      String contextId,
      BeanDefinitionBuilder builder) {
    Element childElement = element.getOwnerDocument().createElement("beanPostProcessor");
    element.appendChild(childElement);

    String beanPostProcessorId = contextId + ":beanPostProcessor";
    childElement.setAttribute("id", beanPostProcessorId);
    BeanDefinition definition = beanPostProcessorParser.parse(childElement, parserContext);
    // only register to camel context id as a String. Then we can look it up later
    // otherwise we get a circular reference in spring and it will not allow custom bean post
    // processing
    // see more at CAMEL-1663
    definition.getPropertyValues().addPropertyValue("camelId", contextId);
    builder.addPropertyReference("beanPostProcessor", beanPostProcessorId);
  }
예제 #21
0
 private void registerEndpoint(
     Element childElement, ParserContext parserContext, String contextId) {
   String id = childElement.getAttribute("id");
   // must have an id to be registered
   if (ObjectHelper.isNotEmpty(id)) {
     BeanDefinition definition = endpointParser.parse(childElement, parserContext);
     definition
         .getPropertyValues()
         .addPropertyValue("camelContext", new RuntimeBeanReference(contextId));
     // Need to add this dependency of CamelContext for Spring 3.0
     try {
       Method method = definition.getClass().getMethod("setDependsOn", String[].class);
       method.invoke(definition, (Object) new String[] {contextId});
     } catch (Exception e) {
       // Do nothing here
     }
     parserContext.registerBeanComponent(new BeanComponentDefinition(definition, id));
   }
 }
  @Test
  public void parseInternal_withDefaultDestination_mustBeSetOnTemplate() throws Exception {
    // Arrange
    SimpleBeanDefinitionRegistry registry = new SimpleBeanDefinitionRegistry();
    XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(registry);

    // Act
    reader.loadBeanDefinitions(
        new ClassPathResource(
            getClass().getSimpleName() + "-with-default-destination.xml", getClass()));

    // Assert
    BeanDefinition notificationMessagingTemplateBeanDefinition =
        registry.getBeanDefinition("notificationMessagingTemplate");
    assertEquals(
        "myDefaultDestination",
        notificationMessagingTemplateBeanDefinition
            .getPropertyValues()
            .getPropertyValue("defaultDestinationName")
            .getValue());
  }
  private void addKieSessionModels(
      ConfigurableListableBeanFactory beanFactory, KieBaseModelImpl kBase) {
    for (String beanDef : beanFactory.getBeanDefinitionNames()) {
      BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanDef);
      if (beanDefinition.getBeanClassName().equalsIgnoreCase(KSessionFactoryBean.class.getName())) {
        String kBaseName = getPropertyValue(beanDefinition, "kBaseName");
        if (kBase.getName().equalsIgnoreCase(kBaseName)) {
          String name = getPropertyValue(beanDefinition, "name");
          String type = getPropertyValue(beanDefinition, "type");
          KieSessionModelImpl kSession = new KieSessionModelImpl(kBase, name);

          kSession.setType(
              !type.isEmpty()
                  ? KieSessionModel.KieSessionType.valueOf(type.toUpperCase())
                  : KieSessionModel.KieSessionType.STATEFUL);
          Map<String, KieSessionModel> rawKieSessionModels = kBase.getRawKieSessionModels();
          rawKieSessionModels.put(kSession.getName(), kSession);
          beanDefinition
              .getPropertyValues()
              .addPropertyValue(new PropertyValue("releaseId", releaseId));

          kSession.setDefault("true".equals(getPropertyValue(beanDefinition, "def")));

          String clockType = getPropertyValue(beanDefinition, "clockType");
          if (!clockType.isEmpty()) {
            kSession.setClockType(ClockTypeOption.get(clockType));
          }

          String scope = getPropertyValue(beanDefinition, "scope");
          if (!scope.isEmpty()) {
            kSession.setScope(scope.trim());
          }
        }
      }
    }
  }
 @Test
 public void urlMappings() throws IOException {
   BeanDefinition servletRegistrationBean = getBeanDefinition(UrlPatternsServlet.class);
   MutablePropertyValues propertyValues = servletRegistrationBean.getPropertyValues();
   assertThat((String[]) propertyValues.get("urlMappings")).contains("alpha", "bravo");
 }
예제 #25
0
    @Override
    protected void doParse(
        Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
      renameNamespaceRecursive(element);
      super.doParse(element, parserContext, builder);

      String contextId = element.getAttribute("id");
      boolean implicitId = false;

      // lets avoid folks having to explicitly give an ID to a camel context
      if (ObjectHelper.isEmpty(contextId)) {
        // if no explicit id was set then use a default auto generated name
        CamelContextNameStrategy strategy = new DefaultCamelContextNameStrategy();
        contextId = strategy.getName();
        element.setAttributeNS(null, "id", contextId);
        implicitId = true;
      }

      // now lets parse the routes with JAXB
      Binder<Node> binder;
      try {
        binder = getJaxbContext().createBinder();
      } catch (JAXBException e) {
        throw new BeanDefinitionStoreException("Failed to create the JAXB binder", e);
      }
      Object value = parseUsingJaxb(element, parserContext, binder);

      if (value instanceof CamelContextFactoryBean) {
        // set the property value with the JAXB parsed value
        CamelContextFactoryBean factoryBean = (CamelContextFactoryBean) value;
        builder.addPropertyValue("id", contextId);
        builder.addPropertyValue("implicitId", implicitId);
        builder.addPropertyValue("routes", factoryBean.getRoutes());
        builder.addPropertyValue("intercepts", factoryBean.getIntercepts());
        builder.addPropertyValue("interceptFroms", factoryBean.getInterceptFroms());
        builder.addPropertyValue(
            "interceptSendToEndpoints", factoryBean.getInterceptSendToEndpoints());
        builder.addPropertyValue("dataFormats", factoryBean.getDataFormats());
        builder.addPropertyValue("onCompletions", factoryBean.getOnCompletions());
        builder.addPropertyValue("onExceptions", factoryBean.getOnExceptions());
        builder.addPropertyValue("builderRefs", factoryBean.getBuilderRefs());
        builder.addPropertyValue("routeRefs", factoryBean.getRouteRefs());
        builder.addPropertyValue("properties", factoryBean.getProperties());
        builder.addPropertyValue("packageScan", factoryBean.getPackageScan());
        builder.addPropertyValue("contextScan", factoryBean.getContextScan());
        if (factoryBean.getPackages().length > 0) {
          builder.addPropertyValue("packages", factoryBean.getPackages());
        }
        builder.addPropertyValue(
            "camelPropertyPlaceholder", factoryBean.getCamelPropertyPlaceholder());
        builder.addPropertyValue("camelJMXAgent", factoryBean.getCamelJMXAgent());
        builder.addPropertyValue(
            "camelStreamCachingStrategy", factoryBean.getCamelStreamCachingStrategy());
        builder.addPropertyValue("threadPoolProfiles", factoryBean.getThreadPoolProfiles());
        // add any depends-on
        addDependsOn(factoryBean, builder);
      }

      NodeList list = element.getChildNodes();
      int size = list.getLength();
      for (int i = 0; i < size; i++) {
        Node child = list.item(i);
        if (child instanceof Element) {
          Element childElement = (Element) child;
          String localName = child.getLocalName();
          if (localName.equals("endpoint")) {
            registerEndpoint(childElement, parserContext, contextId);
          } else if (localName.equals("routeBuilder")) {
            addDependsOnToRouteBuilder(childElement, parserContext, contextId);
          } else {
            BeanDefinitionParser parser = parserMap.get(localName);
            if (parser != null) {
              BeanDefinition definition = parser.parse(childElement, parserContext);
              String id = childElement.getAttribute("id");
              if (ObjectHelper.isNotEmpty(id)) {
                parserContext.registerComponent(new BeanComponentDefinition(definition, id));
                // set the templates with the camel context
                if (localName.equals("template")
                    || localName.equals("consumerTemplate")
                    || localName.equals("proxy")
                    || localName.equals("export")) {
                  // set the camel context
                  definition
                      .getPropertyValues()
                      .addPropertyValue("camelContext", new RuntimeBeanReference(contextId));
                }
              }
            }
          }
        }
      }

      // register as endpoint defined indirectly in the routes by from/to types having id explicit
      // set
      registerEndpointsWithIdsDefinedInFromOrToTypes(element, parserContext, contextId, binder);

      // register templates if not already defined
      registerTemplates(element, parserContext, contextId);

      // lets inject the namespaces into any namespace aware POJOs
      injectNamespaces(element, binder);

      // inject bean post processor so we can support @Produce etc.
      // no bean processor element so lets create it by our self
      injectBeanPostProcessor(element, parserContext, contextId, builder);
    }
 @Test
 public void asyncSupported() throws IOException {
   BeanDefinition servletRegistrationBean = getBeanDefinition(AsyncSupportedServlet.class);
   MutablePropertyValues propertyValues = servletRegistrationBean.getPropertyValues();
   assertThat(propertyValues.get("asyncSupported")).isEqualTo(true);
 }
 private String getPropertyValue(BeanDefinition beanDefinition, String propertyName) {
   PropertyValue propertyValue = beanDefinition.getPropertyValues().getPropertyValue(propertyName);
   return propertyValue != null ? (String) propertyValue.getValue() : "";
 }
예제 #28
0
  private boolean needRemove(String beanName, BeanDefinition beanDefinition) {

    if (ArrayUtils.isNotEmpty(removedBeanNames)) {
      for (String removedBeanName : removedBeanNames) {
        if (beanName.equals(removedBeanName)) {
          return true;
        }
        if (beanDefinition.getBeanClassName().equals(removedBeanName)) {
          return true;
        }
      }
    }

    if (this.removedBeanProperties != null) {
      Set<String[]> propertiesSet = removedBeanProperties.get(beanName);
      if (propertiesSet != null) {
        Iterator<String[]> iter = propertiesSet.iterator();
        MutablePropertyValues propertyValues = beanDefinition.getPropertyValues();

        while (iter.hasNext()) {
          String[] properties = iter.next();
          if (properties.length == 1) {

            // 先移除
            propertyValues.removePropertyValue(properties[0]);

            // 如果需要替换,替换掉值(只支持基本属性)
            if (this.replaceBeanProperties != null) {
              String key = beanName + "@" + properties[0];
              if (this.replaceBeanProperties.containsKey(key)) {
                propertyValues.add(properties[0], this.replaceBeanProperties.get(key));
              }
            }
          } else {
            PropertyValue propertyValue = propertyValues.getPropertyValue(properties[0]);
            if (propertyValue != null) {
              Object nextValue = propertyValue.getValue();
              // 目前只支持 二级 + 移除Map的
              if (nextValue instanceof ManagedMap) {

                TypedStringValue typedStringValue = new TypedStringValue(properties[1]);
                ((ManagedMap) nextValue).remove(typedStringValue);

                // 如果需要替换,替换掉值(只支持基本属性)
                if (this.replaceBeanProperties != null) {
                  String key = beanName + "@" + properties[0] + "@" + properties[1];
                  if (this.replaceBeanProperties.containsKey(key)) {
                    ((ManagedMap) nextValue)
                        .put(properties[1], this.replaceBeanProperties.get(key));
                  }
                }
              }
            }
          }
        }
      }
    }

    String className = beanDefinition.getBeanClassName();

    // spring data jpa
    if (className.equals("com.sishuok.es.common.repository.support.SimpleBaseRepositoryFactoryBean")
        || className.equals(
            "org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean")) {
      PropertyValue repositoryInterfaceValue =
          beanDefinition.getPropertyValues().getPropertyValue("repositoryInterface");
      if (repositoryInterfaceValue != null) {
        className = repositoryInterfaceValue.getValue().toString();
      }
    }

    if (ArrayUtils.isEmpty(this.removedClassPatterns)) {
      return false;
    }

    if (ArrayUtils.isNotEmpty(this.includeClassPatterns)) {
      for (String includeClassPattern : includeClassPatterns) {
        if (className.matches(includeClassPattern)) {
          return false;
        }
      }
    }

    for (String removedClassPattern : removedClassPatterns) {
      if (className.matches(removedClassPattern)) {
        return true;
      }
    }

    return false;
  }
  /**
   * Adds the annotated classes and the mapping resources to the existing Session Factory
   * configuration.
   *
   * @param configurableListableBeanFactory the good ol' bean factory
   */
  @SuppressWarnings("unchecked")
  public void postProcessBeanFactory(
      ConfigurableListableBeanFactory configurableListableBeanFactory) {
    if (configurableListableBeanFactory.containsBean(sessionFactoryBeanName)) {
      BeanDefinition sessionFactoryBeanDefinition =
          configurableListableBeanFactory.getBeanDefinition(sessionFactoryBeanName);
      MutablePropertyValues propertyValues = sessionFactoryBeanDefinition.getPropertyValues();

      if (mappingResources != null) {
        // do we have existing resourses?
        PropertyValue propertyValue = propertyValues.getPropertyValue("mappingResources");

        if (propertyValue == null) {
          propertyValue = new PropertyValue("mappingResources", new ArrayList());
          propertyValues.addPropertyValue(propertyValue);
        }

        // value is expected to be a list.
        List existingMappingResources = (List) propertyValue.getValue();
        existingMappingResources.addAll(mappingResources);
      }

      if (annotatedClasses != null) {
        // do we have existing resources?
        PropertyValue propertyValue = propertyValues.getPropertyValue("annotatedClasses");

        if (propertyValue == null) {
          propertyValue = new PropertyValue("annotatedClasses", new ArrayList());
          propertyValues.addPropertyValue(propertyValue);
        }

        // value is expected to be a list.
        List existingMappingResources = (List) propertyValue.getValue();
        existingMappingResources.addAll(annotatedClasses);
      }

      if (configLocations != null) {
        PropertyValue propertyValue = propertyValues.getPropertyValue("configLocations");
        if (propertyValue == null) {
          propertyValue = new PropertyValue("configLocations", new ArrayList());
          propertyValues.addPropertyValue(propertyValue);
        }
        List existingConfigLocations = (List) propertyValue.getValue();
        existingConfigLocations.addAll(configLocations);
      }

      if (hibernateProperties != null) {
        PropertyValue propertyValue = propertyValues.getPropertyValue("hibernateProperties");
        if (propertyValue == null) {
          propertyValue = new PropertyValue("hibernateProperties", new Properties());
          propertyValues.addPropertyValue(propertyValue);
        }
        Properties existingHibernateProperties = (Properties) propertyValue.getValue();
        existingHibernateProperties.putAll(hibernateProperties);
      }
    } else {
      throw new NoSuchBeanDefinitionException(
          "No bean named ["
              + sessionFactoryBeanName
              + "] exists within the bean factory. "
              + "Cannot post process session factory to add Hibernate resource definitions.");
    }
  }
예제 #30
0
  /**
   * Initializes the view index {@code Map} then iterates through all the beans in the factory that
   * implement {@code View}, adding them to the index
   */
  protected void buildViewIndicies() {
    LOG.info("Starting View Index Building");

    viewBeanEntriesById = new HashMap<String, String>();
    viewEntriesByType = new HashMap<String, ViewTypeDictionaryIndex>();
    viewPools = new HashMap<String, UifViewPool>();

    boolean inDevMode =
        Boolean.parseBoolean(
            ConfigContext.getCurrentContextConfig()
                .getProperty(KRADConstants.ConfigParameters.KRAD_DEV_MODE));

    ExecutorService executor = Executors.newFixedThreadPool(threadPoolSize);

    String[] beanNames = ddBeans.getBeanNamesForType(View.class);
    for (final String beanName : beanNames) {
      BeanDefinition beanDefinition = ddBeans.getMergedBeanDefinition(beanName);
      PropertyValues propertyValues = beanDefinition.getPropertyValues();

      String id = ViewModelUtils.getStringValFromPVs(propertyValues, "id");
      if (StringUtils.isBlank(id)) {
        id = beanName;
      }

      if (viewBeanEntriesById.containsKey(id)) {
        throw new DataDictionaryException(
            "Two views must not share the same id. Found duplicate id: " + id);
      }

      viewBeanEntriesById.put(id, beanName);

      indexViewForType(propertyValues, id);

      // pre-load views if necessary
      if (!inDevMode) {
        String poolSizeStr = ViewModelUtils.getStringValFromPVs(propertyValues, "preloadPoolSize");
        if (StringUtils.isNotBlank(poolSizeStr)) {
          int poolSize = Integer.parseInt(poolSizeStr);
          if (poolSize < 1) {
            continue;
          }

          final View view = (View) ddBeans.getBean(beanName);
          final UifViewPool viewPool = new UifViewPool();
          viewPool.setMaxSize(poolSize);
          for (int j = 0; j < poolSize; j++) {
            Runnable createView =
                new Runnable() {
                  @Override
                  public void run() {
                    viewPool.addViewInstance((View) CopyUtils.copy(view));
                  }
                };

            executor.execute(createView);
          }
          viewPools.put(id, viewPool);
        }
      }
    }

    executor.shutdown();

    LOG.info("Completed View Index Building");
  }