@Test
 public void prototypeCreationIsFastEnough() {
   if (factoryLog.isTraceEnabled() || factoryLog.isDebugEnabled()) {
     // Skip this test: Trace logging blows the time limit.
     return;
   }
   GenericApplicationContext ac = new GenericApplicationContext();
   RootBeanDefinition rbd = new RootBeanDefinition(TestBean.class);
   rbd.setScope(RootBeanDefinition.SCOPE_PROTOTYPE);
   rbd.getConstructorArgumentValues().addGenericArgumentValue("#{systemProperties.name}");
   rbd.getPropertyValues().add("country", "#{systemProperties.country}");
   ac.registerBeanDefinition("test", rbd);
   ac.refresh();
   StopWatch sw = new StopWatch();
   sw.start("prototype");
   System.getProperties().put("name", "juergen");
   System.getProperties().put("country", "UK");
   try {
     for (int i = 0; i < 100000; i++) {
       TestBean tb = (TestBean) ac.getBean("test");
       assertEquals("juergen", tb.getName());
       assertEquals("UK", tb.getCountry());
     }
     sw.stop();
   } finally {
     System.getProperties().remove("country");
     System.getProperties().remove("name");
   }
   assertTrue(
       "Prototype creation took too long: " + sw.getTotalTimeMillis(),
       sw.getTotalTimeMillis() < 6000);
 }
 public void afterPropertiesSet() throws Exception {
   Assert.notNull(this.beanFactory, "'beanFactory' must not be null");
   if (!autoCreate) {
     return;
   } else {
     AutoCreateCandidatesCollector channelCandidatesCollector =
         beanFactory.getBean(
             AUTO_CREATE_CHANNEL_CANDIDATES_BEAN_NAME, AutoCreateCandidatesCollector.class);
     Assert.notNull(
         channelCandidatesCollector,
         "Failed to locate '" + ChannelInitializer.AUTO_CREATE_CHANNEL_CANDIDATES_BEAN_NAME);
     // at this point channelNames are all resolved with placeholders and SpEL
     Collection<String> channelNames = channelCandidatesCollector.getChannelNames();
     if (channelNames != null) {
       for (String channelName : channelNames) {
         if (!beanFactory.containsBean(channelName)) {
           if (this.logger.isDebugEnabled()) {
             this.logger.debug("Auto-creating channel '" + channelName + "' as DirectChannel");
           }
           RootBeanDefinition messageChannel = new RootBeanDefinition();
           messageChannel.setBeanClass(DirectChannel.class);
           BeanDefinitionHolder messageChannelHolder =
               new BeanDefinitionHolder(messageChannel, channelName);
           BeanDefinitionReaderUtils.registerBeanDefinition(
               messageChannelHolder, (BeanDefinitionRegistry) this.beanFactory);
         }
       }
     }
   }
 }
 @Test
 @SuppressWarnings({"unchecked", "rawtypes"})
 public void resolveChannelNameFromMapAndCustomeResolver() {
   final StaticApplicationContext context = new StaticApplicationContext();
   ManagedMap channelMappings = new ManagedMap();
   channelMappings.put("testKey", "testChannel");
   RootBeanDefinition routerBeanDefinition = new RootBeanDefinition(HeaderValueRouter.class);
   routerBeanDefinition.getConstructorArgumentValues().addGenericArgumentValue("testHeaderName");
   routerBeanDefinition.getPropertyValues().addPropertyValue("resolutionRequired", "true");
   routerBeanDefinition.getPropertyValues().addPropertyValue("channelMappings", channelMappings);
   routerBeanDefinition.getPropertyValues().addPropertyValue("beanFactory", context);
   routerBeanDefinition
       .getPropertyValues()
       .addPropertyValue(
           "channelResolver",
           (DestinationResolver<MessageChannel>)
               channelName -> context.getBean("anotherChannel", MessageChannel.class));
   context.registerBeanDefinition("router", routerBeanDefinition);
   context.registerBeanDefinition("testChannel", new RootBeanDefinition(QueueChannel.class));
   context.registerBeanDefinition("anotherChannel", new RootBeanDefinition(QueueChannel.class));
   context.refresh();
   MessageHandler handler = (MessageHandler) context.getBean("router");
   Message<?> message =
       MessageBuilder.withPayload("test").setHeader("testHeaderName", "testKey").build();
   handler.handleMessage(message);
   QueueChannel channel = (QueueChannel) context.getBean("anotherChannel");
   Message<?> result = channel.receive(1000);
   assertNotNull(result);
   assertSame(message, result);
   context.close();
 }
  @Test
  public void listenersInApplicationContextWithNestedChild() {
    StaticApplicationContext context = new StaticApplicationContext();
    RootBeanDefinition nestedChild = new RootBeanDefinition(StaticApplicationContext.class);
    nestedChild.getPropertyValues().add("parent", context);
    nestedChild.setInitMethodName("refresh");
    context.registerBeanDefinition("nestedChild", nestedChild);
    RootBeanDefinition listener1Def = new RootBeanDefinition(MyOrderedListener1.class);
    listener1Def.setDependsOn(new String[] {"nestedChild"});
    context.registerBeanDefinition("listener1", listener1Def);
    context.refresh();

    MyOrderedListener1 listener1 = context.getBean("listener1", MyOrderedListener1.class);
    MyEvent event1 = new MyEvent(context);
    context.publishEvent(event1);
    assertTrue(listener1.seenEvents.contains(event1));

    SimpleApplicationEventMulticaster multicaster =
        context.getBean(
            AbstractApplicationContext.APPLICATION_EVENT_MULTICASTER_BEAN_NAME,
            SimpleApplicationEventMulticaster.class);
    assertFalse(multicaster.getApplicationListeners().isEmpty());

    context.close();
    assertTrue(multicaster.getApplicationListeners().isEmpty());
  }
  private Object handleTypeMismatchException(
      String beanName, RootBeanDefinition mbd, Object[] args) {
    // type mismatch probably occured because another class was reloaded
    final Class<?> beanClass = mbd.getBeanClass();
    if (!GroovyObject.class.isAssignableFrom(beanClass)) {
      return null;
    }

    GrailsApplication application = (GrailsApplication) getBean(GrailsApplication.APPLICATION_ID);
    ClassLoader classLoader = application.getClassLoader();
    if (!(classLoader instanceof GrailsClassLoader)) {
      return null;
    }

    GrailsClassLoader gcl = (GrailsClassLoader) classLoader;
    gcl.reloadClass(beanClass.getName());
    Class<?> newBeanClass;
    try {
      newBeanClass = gcl.loadClass(beanClass.getName());
    } catch (ClassNotFoundException e) {
      return null;
    }

    mbd.setBeanClass(newBeanClass);
    if (newBeanClass.equals(beanClass)) {
      return null;
    }

    GrailsPluginManager pluginManager =
        (GrailsPluginManager) getBean(GrailsPluginManager.BEAN_NAME);
    pluginManager.informOfClassChange(newBeanClass);
    return super.doCreateBean(beanName, mbd, args);
  }
  @Test
  public void prototypeCreationReevaluatesExpressions() {
    GenericApplicationContext ac = new GenericApplicationContext();
    AnnotationConfigUtils.registerAnnotationConfigProcessors(ac);
    RootBeanDefinition rbd = new RootBeanDefinition(PrototypeTestBean.class);
    rbd.setScope(RootBeanDefinition.SCOPE_PROTOTYPE);
    rbd.getPropertyValues().add("country", "#{systemProperties.country}");
    rbd.getPropertyValues().add("country2", new TypedStringValue("#{systemProperties.country}"));
    ac.registerBeanDefinition("test", rbd);
    ac.refresh();

    try {
      System.getProperties().put("name", "juergen1");
      System.getProperties().put("country", "UK1");
      PrototypeTestBean tb = (PrototypeTestBean) ac.getBean("test");
      assertEquals("juergen1", tb.getName());
      assertEquals("UK1", tb.getCountry());
      assertEquals("UK1", tb.getCountry2());

      System.getProperties().put("name", "juergen2");
      System.getProperties().put("country", "UK2");
      tb = (PrototypeTestBean) ac.getBean("test");
      assertEquals("juergen2", tb.getName());
      assertEquals("UK2", tb.getCountry());
      assertEquals("UK2", tb.getCountry2());
    } finally {
      System.getProperties().remove("name");
      System.getProperties().remove("country");
    }
  }
 @Override
 public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry)
     throws BeansException {
   Collection<Class<?>> remotingServices = new HashSet<Class<?>>();
   remotingServices.addAll(getIncludeClasses());
   String[] basePackages = getBasePackages();
   if (basePackages != null)
     remotingServices.addAll(ClassScanner.scanAnnotated(basePackages, Remoting.class));
   Collection<Class<?>> excludeRemotingServices = getExcludeClasses();
   for (Class<?> remotingService : remotingServices) {
     if (!remotingService.isInterface() || excludeRemotingServices.contains(remotingService))
       continue;
     String beanName = StringUtils.uncapitalize(remotingService.getSimpleName());
     if (registry.containsBeanDefinition(beanName)) {
       logger.info(
           "Skip bean {} which implemented by {}",
           beanName,
           registry.getBeanDefinition(beanName).getBeanClassName());
       continue;
     }
     RootBeanDefinition beanDefinition = new RootBeanDefinition(HttpInvokerClient.class);
     beanDefinition.setTargetType(remotingService);
     beanDefinition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_NAME);
     MutablePropertyValues propertyValues = new MutablePropertyValues();
     propertyValues.addPropertyValue("serviceInterface", remotingService.getName());
     beanDefinition.setPropertyValues(propertyValues);
     registry.registerBeanDefinition(beanName, beanDefinition);
     logger.info("Registered bean {} for remoting service", beanName);
   }
 }
  @Test
  public void resolveChannelNameFromContext() {
    StaticApplicationContext context = new StaticApplicationContext();
    RootBeanDefinition routerBeanDefinition = new RootBeanDefinition(HeaderValueRouter.class);
    routerBeanDefinition.getConstructorArgumentValues().addGenericArgumentValue("testHeaderName");
    routerBeanDefinition.getPropertyValues().addPropertyValue("resolutionRequired", "true");
    context.registerBeanDefinition("router", routerBeanDefinition);
    context.registerBeanDefinition("testChannel", new RootBeanDefinition(QueueChannel.class));
    context.registerBeanDefinition("newChannel", new RootBeanDefinition(QueueChannel.class));
    context.refresh();
    MessageHandler handler = (MessageHandler) context.getBean("router");
    Message<?> message =
        MessageBuilder.withPayload("test").setHeader("testHeaderName", "testChannel").build();
    handler.handleMessage(message);
    QueueChannel channel = (QueueChannel) context.getBean("testChannel");
    Message<?> result = channel.receive(1000);
    assertNotNull(result);
    assertSame(message, result);

    // validate dynamics
    HeaderValueRouter router = (HeaderValueRouter) context.getBean("router");
    router.setChannelMapping("testChannel", "newChannel");
    router.handleMessage(message);
    QueueChannel newChannel = (QueueChannel) context.getBean("newChannel");
    result = newChannel.receive(10);
    assertNotNull(result);

    router.removeChannelMapping("testChannel");
    router.handleMessage(message);
    result = channel.receive(1000);
    assertNotNull(result);
    assertSame(message, result);
    context.close();
  }
 @Test
 public void dynamicChannelCache() {
   StaticApplicationContext context = new StaticApplicationContext();
   RootBeanDefinition routerBeanDefinition = new RootBeanDefinition(HeaderValueRouter.class);
   routerBeanDefinition.getConstructorArgumentValues().addGenericArgumentValue("testHeaderName");
   routerBeanDefinition.getPropertyValues().addPropertyValue("resolutionRequired", "true");
   routerBeanDefinition.getPropertyValues().addPropertyValue("dynamicChannelLimit", "2");
   context.registerBeanDefinition("router", routerBeanDefinition);
   context.registerBeanDefinition("channel1", new RootBeanDefinition(QueueChannel.class));
   context.registerBeanDefinition("channel2", new RootBeanDefinition(QueueChannel.class));
   context.registerBeanDefinition("channel3", new RootBeanDefinition(QueueChannel.class));
   context.refresh();
   MessageHandler handler = (MessageHandler) context.getBean("router");
   String channels = "channel1, channel2, channel1, channel3";
   Message<?> message =
       MessageBuilder.withPayload("test").setHeader("testHeaderName", channels).build();
   handler.handleMessage(message);
   QueueChannel channel1 = (QueueChannel) context.getBean("channel1");
   QueueChannel channel2 = (QueueChannel) context.getBean("channel2");
   QueueChannel channel3 = (QueueChannel) context.getBean("channel3");
   assertThat(channel1.getQueueSize(), equalTo(2));
   assertThat(channel2.getQueueSize(), equalTo(1));
   assertThat(channel3.getQueueSize(), equalTo(1));
   assertThat(
       context.getBean(HeaderValueRouter.class).getDynamicChannelNames(),
       contains("channel1", "channel3"));
   context.close();
 }
 @Test
 public void resolveMultipleChannelsWithCommaDelimitedString() {
   StaticApplicationContext context = new StaticApplicationContext();
   RootBeanDefinition routerBeanDefinition = new RootBeanDefinition(HeaderValueRouter.class);
   routerBeanDefinition.getConstructorArgumentValues().addGenericArgumentValue("testHeaderName");
   routerBeanDefinition.getPropertyValues().addPropertyValue("resolutionRequired", "true");
   context.registerBeanDefinition("router", routerBeanDefinition);
   context.registerBeanDefinition("channel1", new RootBeanDefinition(QueueChannel.class));
   context.registerBeanDefinition("channel2", new RootBeanDefinition(QueueChannel.class));
   context.refresh();
   MessageHandler handler = (MessageHandler) context.getBean("router");
   String channels = "channel1, channel2";
   Message<?> message =
       MessageBuilder.withPayload("test").setHeader("testHeaderName", channels).build();
   handler.handleMessage(message);
   QueueChannel channel1 = (QueueChannel) context.getBean("channel1");
   QueueChannel channel2 = (QueueChannel) context.getBean("channel2");
   Message<?> result1 = channel1.receive(1000);
   Message<?> result2 = channel2.receive(1000);
   assertNotNull(result1);
   assertNotNull(result2);
   assertSame(message, result1);
   assertSame(message, result2);
   context.close();
 }
  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;
  }
	@Test
	public void testExtendedResourceInjectionWithOverriding() {
		DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
		CommonAnnotationBeanPostProcessor bpp = new CommonAnnotationBeanPostProcessor();
		bpp.setBeanFactory(bf);
		bf.addBeanPostProcessor(bpp);
		bf.registerResolvableDependency(BeanFactory.class, bf);

		PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
		Properties props = new Properties();
		props.setProperty("tb", "testBean3");
		ppc.setProperties(props);
		ppc.postProcessBeanFactory(bf);

		RootBeanDefinition annotatedBd = new RootBeanDefinition(ExtendedResourceInjectionBean.class);
		TestBean tb5 = new TestBean();
		annotatedBd.getPropertyValues().add("testBean2", tb5);
		bf.registerBeanDefinition("annotatedBean", annotatedBd);
		bf.registerBeanDefinition("annotatedBean2", new RootBeanDefinition(NamedResourceInjectionBean.class));
		TestBean tb = new TestBean();
		bf.registerSingleton("testBean", tb);
		TestBean tb2 = new TestBean();
		bf.registerSingleton("testBean2", tb2);
		TestBean tb3 = new TestBean();
		bf.registerSingleton("testBean3", tb3);
		TestBean tb4 = new TestBean();
		bf.registerSingleton("testBean4", tb4);
		NestedTestBean tb6 = new NestedTestBean();
		bf.registerSingleton("xy", tb6);

		ExtendedResourceInjectionBean bean = (ExtendedResourceInjectionBean) bf.getBean("annotatedBean");
		assertTrue(bean.initCalled);
		assertTrue(bean.init2Called);
		assertSame(tb, bean.getTestBean());
		assertSame(tb5, bean.getTestBean2());
		assertSame(tb4, bean.getTestBean3());
		assertSame(tb3, bean.getTestBean4());
		assertSame(tb6, bean.testBean5);
		assertSame(tb6, bean.testBean6);
		assertSame(bf, bean.beanFactory);

		try {
			bf.getBean("annotatedBean2");
		}
		catch (BeanCreationException ex) {
			assertTrue(ex.getRootCause() instanceof NoSuchBeanDefinitionException);
			NoSuchBeanDefinitionException innerEx = (NoSuchBeanDefinitionException) ex.getRootCause();
			assertEquals("testBean9", innerEx.getBeanName());
		}

		bf.destroySingletons();
		assertTrue(bean.destroyCalled);
		assertTrue(bean.destroy2Called);
	}
	@Test
	public void testPostProcessorWithNullBean() {
		DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
		bf.addBeanPostProcessor(new CommonAnnotationBeanPostProcessor());
		RootBeanDefinition rbd = new RootBeanDefinition(NullFactory.class);
		rbd.setFactoryMethodName("create");
		bf.registerBeanDefinition("bean", rbd);

		assertNull(bf.getBean("bean"));
		bf.destroySingletons();
	}
  @Test
  public void testBeanNameAutoProxyCreator() {
    StaticApplicationContext sac = new StaticApplicationContext();
    sac.registerSingleton("testInterceptor", TestInterceptor.class);

    RootBeanDefinition proxyCreator = new RootBeanDefinition(BeanNameAutoProxyCreator.class);
    proxyCreator.getPropertyValues().add("interceptorNames", "testInterceptor");
    proxyCreator
        .getPropertyValues()
        .add("beanNames", "singletonToBeProxied,innerBean,singletonFactoryToBeProxied");
    sac.getDefaultListableBeanFactory()
        .registerBeanDefinition("beanNameAutoProxyCreator", proxyCreator);

    RootBeanDefinition bd =
        new RootBeanDefinition(TestBean.class, RootBeanDefinition.AUTOWIRE_BY_TYPE);
    RootBeanDefinition innerBean = new RootBeanDefinition(TestBean.class);
    bd.getPropertyValues().add("spouse", new BeanDefinitionHolder(innerBean, "innerBean"));
    sac.getDefaultListableBeanFactory().registerBeanDefinition("singletonToBeProxied", bd);

    sac.registerSingleton("singletonFactoryToBeProxied", DummyFactory.class);
    sac.registerSingleton("autowiredIndexedTestBean", IndexedTestBean.class);

    sac.refresh();

    MessageSource messageSource = (MessageSource) sac.getBean("messageSource");
    ITestBean singletonToBeProxied = (ITestBean) sac.getBean("singletonToBeProxied");
    assertFalse(Proxy.isProxyClass(messageSource.getClass()));
    assertTrue(Proxy.isProxyClass(singletonToBeProxied.getClass()));
    assertTrue(Proxy.isProxyClass(singletonToBeProxied.getSpouse().getClass()));

    // test whether autowiring succeeded with auto proxy creation
    assertEquals(
        sac.getBean("autowiredIndexedTestBean"), singletonToBeProxied.getNestedIndexedBean());

    TestInterceptor ti = (TestInterceptor) sac.getBean("testInterceptor");
    // already 2: getSpouse + getNestedIndexedBean calls above
    assertEquals(2, ti.nrOfInvocations);
    singletonToBeProxied.getName();
    singletonToBeProxied.getSpouse().getName();
    assertEquals(5, ti.nrOfInvocations);

    ITestBean tb = (ITestBean) sac.getBean("singletonFactoryToBeProxied");
    assertTrue(AopUtils.isJdkDynamicProxy(tb));
    assertEquals(5, ti.nrOfInvocations);
    tb.getAge();
    assertEquals(6, ti.nrOfInvocations);

    ITestBean tb2 = (ITestBean) sac.getBean("singletonFactoryToBeProxied");
    assertSame(tb, tb2);
    assertEquals(6, ti.nrOfInvocations);
    tb2.getAge();
    assertEquals(7, ti.nrOfInvocations);
  }
  @Test
  public void innerBeanAsListener() {
    StaticApplicationContext context = new StaticApplicationContext();
    RootBeanDefinition listenerDef = new RootBeanDefinition(TestBean.class);
    listenerDef.getPropertyValues().add("friends", new RootBeanDefinition(BeanThatListens.class));
    context.registerBeanDefinition("listener", listenerDef);
    context.refresh();

    context.publishEvent(new MyEvent(this));
    context.publishEvent(new MyEvent(this));
    TestBean listener = context.getBean(TestBean.class);
    assertEquals(3, ((BeanThatListens) listener.getFriends().iterator().next()).getEventCount());

    context.close();
  }
 protected void addResponseBodyAdvice(RootBeanDefinition beanDef) {
   if (jackson2Present) {
     beanDef
         .getPropertyValues()
         .add("responseBodyAdvice", new RootBeanDefinition(JsonViewResponseBodyAdvice.class));
   }
 }
  @Test
  public void listenerAndBroadcasterWithCircularReference() {
    StaticApplicationContext context = new StaticApplicationContext();
    context.registerBeanDefinition("broadcaster", new RootBeanDefinition(BeanThatBroadcasts.class));
    RootBeanDefinition listenerDef = new RootBeanDefinition(BeanThatListens.class);
    listenerDef
        .getConstructorArgumentValues()
        .addGenericArgumentValue(new RuntimeBeanReference("broadcaster"));
    context.registerBeanDefinition("listener", listenerDef);
    context.refresh();

    BeanThatBroadcasts broadcaster = context.getBean("broadcaster", BeanThatBroadcasts.class);
    context.publishEvent(new MyEvent(context));
    assertEquals("The event was not received by the listener", 2, broadcaster.receivedCount);

    context.close();
  }
 private RuntimeBeanReference getConversionService(
     Element element, Object source, ParserContext parserContext) {
   RuntimeBeanReference conversionServiceRef;
   if (element.hasAttribute("conversion-service")) {
     conversionServiceRef = new RuntimeBeanReference(element.getAttribute("conversion-service"));
   } else {
     RootBeanDefinition conversionDef =
         new RootBeanDefinition(FormattingConversionServiceFactoryBean.class);
     conversionDef.setSource(source);
     conversionDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
     String conversionName =
         parserContext.getReaderContext().registerWithGeneratedName(conversionDef);
     parserContext.registerComponent(new BeanComponentDefinition(conversionDef, conversionName));
     conversionServiceRef = new RuntimeBeanReference(conversionName);
   }
   return conversionServiceRef;
 }
  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;
  }
 @Test
 public void channelAsHeaderValue() {
   StaticApplicationContext context = new StaticApplicationContext();
   RootBeanDefinition routerBeanDefinition = new RootBeanDefinition(HeaderValueRouter.class);
   routerBeanDefinition.getConstructorArgumentValues().addGenericArgumentValue("testHeaderName");
   routerBeanDefinition.getPropertyValues().addPropertyValue("resolutionRequired", "true");
   context.registerBeanDefinition("router", routerBeanDefinition);
   context.refresh();
   MessageHandler handler = (MessageHandler) context.getBean("router");
   QueueChannel testChannel = new QueueChannel();
   Message<?> message =
       MessageBuilder.withPayload("test").setHeader("testHeaderName", testChannel).build();
   handler.handleMessage(message);
   Message<?> result = testChannel.receive(1000);
   assertNotNull(result);
   assertSame(message, result);
   context.close();
 }
 private RuntimeBeanReference getValidator(
     Element element, Object source, ParserContext parserContext) {
   if (element.hasAttribute("validator")) {
     return new RuntimeBeanReference(element.getAttribute("validator"));
   } else if (javaxValidationPresent) {
     RootBeanDefinition validatorDef =
         new RootBeanDefinition(
             "org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean");
     validatorDef.setSource(source);
     validatorDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
     String validatorName =
         parserContext.getReaderContext().registerWithGeneratedName(validatorDef);
     parserContext.registerComponent(new BeanComponentDefinition(validatorDef, validatorName));
     return new RuntimeBeanReference(validatorName);
   } else {
     return null;
   }
 }
  public Object instantiate(RootBeanDefinition beanDefinition, String beanName, BeanFactory owner) {

    // Don't override the class with CGLIB if no overrides.
    if (beanDefinition.getMethodOverrides().isEmpty()) {
      Class clazz = beanDefinition.getBeanClass();
      if (clazz.isInterface()) {
        throw new BeanInstantiationException(clazz, "Specified class is an interface");
      }
      try {
        Constructor constructor = clazz.getDeclaredConstructor((Class[]) null);
        return BeanUtils.instantiateClass(constructor, null);
      } catch (Exception ex) {
        throw new BeanInstantiationException(clazz, "No default constructor found", ex);
      }
    } else {
      // Must generate CGLIB subclass.
      return instantiateWithMethodInjection(beanDefinition, beanName, owner);
    }
  }
  @Override
  protected AbstractBeanDefinition parseConsumer(Element element, ParserContext parserContext) {
    BeanDefinitionBuilder builder =
        BeanDefinitionBuilder.genericBeanDefinition(RedisCollectionPopulatingMessageHandler.class);

    String redisTemplateRef = element.getAttribute("redis-template");
    String connectionFactory = element.getAttribute("connection-factory");
    if (StringUtils.hasText(redisTemplateRef) && StringUtils.hasText(connectionFactory)) {
      parserContext
          .getReaderContext()
          .error("Only one of 'redis-template' or 'connection-factory'" + " is allowed", element);
    }

    if (StringUtils.hasText(redisTemplateRef)) {
      builder.addConstructorArgReference(redisTemplateRef);
    } else {
      if (!StringUtils.hasText(connectionFactory)) {
        connectionFactory = "redisConnectionFactory";
      }
      builder.addConstructorArgReference(connectionFactory);
    }

    boolean atLeastOneRequired = false;
    RootBeanDefinition expressionDef =
        IntegrationNamespaceUtils.createExpressionDefinitionFromValueOrExpression(
            "key", "key-expression", parserContext, element, atLeastOneRequired);
    IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "collection-type");
    IntegrationNamespaceUtils.setValueIfAttributeDefined(
        builder, element, "extract-payload-elements");

    if (expressionDef != null) {
      builder.addConstructorArgValue(expressionDef);
    }

    String mapKeyExpression = element.getAttribute("map-key-expression");
    if (StringUtils.hasText(mapKeyExpression)) {
      RootBeanDefinition mapKeyExpressionDef = new RootBeanDefinition(ExpressionFactoryBean.class);
      mapKeyExpressionDef.getConstructorArgumentValues().addGenericArgumentValue(mapKeyExpression);
      builder.addPropertyValue("mapKeyExpression", mapKeyExpressionDef);
    }

    return builder.getBeanDefinition();
  }
 private ManagedList<Object> wrapLegacyResolvers(List<Object> list, ParserContext context) {
   ManagedList<Object> result = new ManagedList<Object>();
   for (Object object : list) {
     if (object instanceof BeanDefinitionHolder) {
       BeanDefinitionHolder beanDef = (BeanDefinitionHolder) object;
       String className = beanDef.getBeanDefinition().getBeanClassName();
       Class<?> clazz =
           ClassUtils.resolveClassName(className, context.getReaderContext().getBeanClassLoader());
       if (WebArgumentResolver.class.isAssignableFrom(clazz)) {
         RootBeanDefinition adapter =
             new RootBeanDefinition(ServletWebArgumentResolverAdapter.class);
         adapter.getConstructorArgumentValues().addIndexedArgumentValue(0, beanDef);
         result.add(new BeanDefinitionHolder(adapter, beanDef.getBeanName() + "Adapter"));
         continue;
       }
     }
     result.add(object);
   }
   return result;
 }
  @Test
  public void listenersInApplicationContext() {
    StaticApplicationContext context = new StaticApplicationContext();
    context.registerBeanDefinition("listener1", new RootBeanDefinition(MyOrderedListener1.class));
    RootBeanDefinition listener2 = new RootBeanDefinition(MyOrderedListener2.class);
    listener2
        .getConstructorArgumentValues()
        .addGenericArgumentValue(new RuntimeBeanReference("listener1"));
    listener2.setLazyInit(true);
    context.registerBeanDefinition("listener2", listener2);
    context.refresh();
    assertFalse(context.getDefaultListableBeanFactory().containsSingleton("listener2"));

    MyOrderedListener1 listener1 = context.getBean("listener1", MyOrderedListener1.class);
    MyOtherEvent event1 = new MyOtherEvent(context);
    context.publishEvent(event1);
    assertFalse(context.getDefaultListableBeanFactory().containsSingleton("listener2"));
    MyEvent event2 = new MyEvent(context);
    context.publishEvent(event2);
    assertTrue(context.getDefaultListableBeanFactory().containsSingleton("listener2"));
    MyEvent event3 = new MyEvent(context);
    context.publishEvent(event3);
    MyOtherEvent event4 = new MyOtherEvent(context);
    context.publishEvent(event4);
    assertTrue(listener1.seenEvents.contains(event1));
    assertTrue(listener1.seenEvents.contains(event2));
    assertTrue(listener1.seenEvents.contains(event3));
    assertTrue(listener1.seenEvents.contains(event4));

    listener1.seenEvents.clear();
    context.publishEvent(event1);
    context.publishEvent(event2);
    context.publishEvent(event3);
    context.publishEvent(event4);
    assertTrue(listener1.seenEvents.contains(event1));
    assertTrue(listener1.seenEvents.contains(event2));
    assertTrue(listener1.seenEvents.contains(event3));
    assertTrue(listener1.seenEvents.contains(event4));

    context.close();
  }
  public void testSerializability() throws Exception {
    MutablePropertyValues tsPvs = new MutablePropertyValues();
    tsPvs.addPropertyValue("targetBeanName", "person");
    RootBeanDefinition tsBd = new RootBeanDefinition(TestTargetSource.class, tsPvs);

    MutablePropertyValues pvs = new MutablePropertyValues();
    RootBeanDefinition bd = new RootBeanDefinition(SerializablePerson.class, pvs);
    bd.setScope(RootBeanDefinition.SCOPE_PROTOTYPE);

    DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
    bf.registerBeanDefinition("ts", tsBd);
    bf.registerBeanDefinition("person", bd);

    TestTargetSource cpts = (TestTargetSource) bf.getBean("ts");
    TargetSource serialized = (TargetSource) SerializationTestUtils.serializeAndDeserialize(cpts);
    assertTrue(
        "Changed to SingletonTargetSource on deserialization",
        serialized instanceof SingletonTargetSource);
    SingletonTargetSource sts = (SingletonTargetSource) serialized;
    assertNotNull(sts.getTarget());
  }
  private RuntimeBeanReference getContentNegotiationManager(
      Element element, Object source, ParserContext parserContext) {

    RuntimeBeanReference beanRef;
    if (element.hasAttribute("content-negotiation-manager")) {
      String name = element.getAttribute("content-negotiation-manager");
      beanRef = new RuntimeBeanReference(name);
    } else {
      RootBeanDefinition factoryBeanDef =
          new RootBeanDefinition(ContentNegotiationManagerFactoryBean.class);
      factoryBeanDef.setSource(source);
      factoryBeanDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
      factoryBeanDef.getPropertyValues().add("mediaTypes", getDefaultMediaTypes());

      String name = CONTENT_NEGOTIATION_MANAGER_BEAN_NAME;
      parserContext.getReaderContext().getRegistry().registerBeanDefinition(name, factoryBeanDef);
      parserContext.registerComponent(new BeanComponentDefinition(factoryBeanDef, name));
      beanRef = new RuntimeBeanReference(name);
    }
    return beanRef;
  }
	@Test
	public void testResourceInjectionWithResolvableDependencyType() {
		DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
		CommonAnnotationBeanPostProcessor bpp = new CommonAnnotationBeanPostProcessor();
		bpp.setBeanFactory(bf);
		bf.addBeanPostProcessor(bpp);
		RootBeanDefinition abd = new RootBeanDefinition(ExtendedResourceInjectionBean.class);
		abd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
		bf.registerBeanDefinition("annotatedBean", abd);
		RootBeanDefinition tbd = new RootBeanDefinition(TestBean.class);
		tbd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
		bf.registerBeanDefinition("testBean4", tbd);

		bf.registerResolvableDependency(BeanFactory.class, bf);
		bf.registerResolvableDependency(INestedTestBean.class, new ObjectFactory<Object>() {
			@Override
			public Object getObject() throws BeansException {
				return new NestedTestBean();
			}
		});

		PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
		Properties props = new Properties();
		props.setProperty("tb", "testBean4");
		ppc.setProperties(props);
		ppc.postProcessBeanFactory(bf);

		ExtendedResourceInjectionBean bean = (ExtendedResourceInjectionBean) bf.getBean("annotatedBean");
		INestedTestBean tb = bean.getTestBean6();
		assertNotNull(tb);

		ExtendedResourceInjectionBean anotherBean = (ExtendedResourceInjectionBean) bf.getBean("annotatedBean");
		assertNotSame(anotherBean, bean);
		assertNotSame(anotherBean.getTestBean6(), tb);

		String[] depBeans = bf.getDependenciesForBean("annotatedBean");
		assertEquals(1, depBeans.length);
		assertEquals("testBean4", depBeans[0]);
	}
  private void configurePathMatchingProperties(
      RootBeanDefinition handlerMappingDef, Element element, ParserContext parserContext) {

    Element pathMatchingElement = DomUtils.getChildElementByTagName(element, "path-matching");
    if (pathMatchingElement != null) {
      Object source = parserContext.extractSource(element);
      if (pathMatchingElement.hasAttribute("suffix-pattern")) {
        Boolean useSuffixPatternMatch =
            Boolean.valueOf(pathMatchingElement.getAttribute("suffix-pattern"));
        handlerMappingDef.getPropertyValues().add("useSuffixPatternMatch", useSuffixPatternMatch);
      }
      if (pathMatchingElement.hasAttribute("trailing-slash")) {
        Boolean useTrailingSlashMatch =
            Boolean.valueOf(pathMatchingElement.getAttribute("trailing-slash"));
        handlerMappingDef.getPropertyValues().add("useTrailingSlashMatch", useTrailingSlashMatch);
      }
      if (pathMatchingElement.hasAttribute("registered-suffixes-only")) {
        Boolean useRegisteredSuffixPatternMatch =
            Boolean.valueOf(pathMatchingElement.getAttribute("registered-suffixes-only"));
        handlerMappingDef
            .getPropertyValues()
            .add("useRegisteredSuffixPatternMatch", useRegisteredSuffixPatternMatch);
      }
      RuntimeBeanReference pathHelperRef = null;
      if (pathMatchingElement.hasAttribute("path-helper")) {
        pathHelperRef = new RuntimeBeanReference(pathMatchingElement.getAttribute("path-helper"));
      }
      pathHelperRef = MvcNamespaceUtils.registerUrlPathHelper(pathHelperRef, parserContext, source);
      handlerMappingDef.getPropertyValues().add("urlPathHelper", pathHelperRef);

      RuntimeBeanReference pathMatcherRef = null;
      if (pathMatchingElement.hasAttribute("path-matcher")) {
        pathMatcherRef = new RuntimeBeanReference(pathMatchingElement.getAttribute("path-matcher"));
      }
      pathMatcherRef = MvcNamespaceUtils.registerPathMatcher(pathMatcherRef, parserContext, source);
      handlerMappingDef.getPropertyValues().add("pathMatcher", pathMatcherRef);
    }
  }
 @Override
 public Object buildBean(String beanName, Map<String, Object> extraContext) throws Exception {
   LOG.debug("Building bean for name {}", beanName);
   if (!skipBeanNames.contains(beanName)) {
     ApplicationContext anAppContext = getApplicationContext(extraContext);
     try {
       LOG.debug(
           "Trying the application context... appContext = {},\n bean name = {}",
           anAppContext,
           beanName);
       return anAppContext.getBean(beanName);
     } catch (NoSuchBeanDefinitionException e) {
       LOG.debug(
           "Did not find bean definition for bean named {}, creating a new one...", beanName);
       if (autoWiringFactory instanceof BeanDefinitionRegistry) {
         try {
           Class clazz = Class.forName(beanName);
           BeanDefinitionRegistry registry = (BeanDefinitionRegistry) autoWiringFactory;
           RootBeanDefinition def = new RootBeanDefinition(clazz, autowireStrategy, true);
           def.setScope(BeanDefinition.SCOPE_SINGLETON);
           LOG.debug("Registering a new bean definition for class {}", beanName);
           registry.registerBeanDefinition(beanName, def);
           try {
             return anAppContext.getBean(beanName);
           } catch (NoSuchBeanDefinitionException e2) {
             LOG.warn("Could not register new bean definition for bean {}", beanName);
             skipBeanNames.add(beanName);
           }
         } catch (ClassNotFoundException e1) {
           skipBeanNames.add(beanName);
         }
       }
     }
   }
   LOG.debug("Returning autowired instance created by default ObjectFactory");
   return autoWireBean(super.buildBean(beanName, extraContext), autoWiringFactory);
 }