@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();
   }
 }
 public void test2Invalid() {
   TestBean t = new TestBean();
   String newName = "tony";
   String invalidTouchy = ".valid";
   try {
     BeanWrapper bw = new BeanWrapperImpl(t);
     // System.out.println(bw);
     MutablePropertyValues pvs = new MutablePropertyValues();
     pvs.addPropertyValue(new PropertyValue("age", "foobar"));
     pvs.addPropertyValue(new PropertyValue("name", newName));
     pvs.addPropertyValue(new PropertyValue("touchy", invalidTouchy));
     bw.setPropertyValues(pvs);
     fail("Should throw exception when everything is valid");
   } catch (PropertyAccessExceptionsException ex) {
     assertTrue("Must contain 2 exceptions", ex.getExceptionCount() == 2);
     // Test validly set property matches
     assertTrue("Validly set property must stick", t.getName().equals(newName));
     assertTrue("Invalidly set property must retain old value", t.getAge() == 0);
     assertTrue(
         "New value of dodgy setter must be available through exception",
         ex.getPropertyAccessException("touchy")
             .getPropertyChangeEvent()
             .getNewValue()
             .equals(invalidTouchy));
   } catch (Exception ex) {
     fail("Shouldn't throw exception other than pvee");
   }
 }
  /**
   * 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;
  }
 @Test
 public void testBindLocalDateArray() {
   MutablePropertyValues propertyValues = new MutablePropertyValues();
   propertyValues.add("localDate", new String[] {"10/31/09"});
   binder.bind(propertyValues);
   assertEquals(0, binder.getBindingResult().getErrorCount());
 }
 @Test
 public void testBindDateTimeOverflow() {
   MutablePropertyValues propertyValues = new MutablePropertyValues();
   propertyValues.add("dateTimeAnnotatedPattern", "02/29/09 12:00 PM");
   binder.bind(propertyValues);
   assertEquals(1, binder.getBindingResult().getErrorCount());
 }
  public void testServiceMappings() {
    StaticApplicationContext ctx = new StaticApplicationContext();
    ctx.registerPrototype("testService1", TestService.class, new MutablePropertyValues());
    ctx.registerPrototype("testService2", ExtendedTestService.class, new MutablePropertyValues());
    MutablePropertyValues mpv = new MutablePropertyValues();
    mpv.addPropertyValue("serviceLocatorInterface", TestServiceLocator3.class);
    mpv.addPropertyValue("serviceMappings", "=testService1\n1=testService1\n2=testService2");
    ctx.registerSingleton("factory", ServiceLocatorFactoryBean.class, mpv);
    ctx.refresh();

    TestServiceLocator3 factory = (TestServiceLocator3) ctx.getBean("factory");
    TestService testBean1 = factory.getTestService();
    TestService testBean2 = factory.getTestService("testService1");
    TestService testBean3 = factory.getTestService(1);
    TestService testBean4 = factory.getTestService(2);
    assertNotSame(testBean1, testBean2);
    assertNotSame(testBean1, testBean3);
    assertNotSame(testBean1, testBean4);
    assertNotSame(testBean2, testBean3);
    assertNotSame(testBean2, testBean4);
    assertNotSame(testBean3, testBean4);
    assertFalse(testBean1 instanceof ExtendedTestService);
    assertFalse(testBean2 instanceof ExtendedTestService);
    assertFalse(testBean3 instanceof ExtendedTestService);
    assertTrue(testBean4 instanceof ExtendedTestService);
  }
 @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);
   }
 }
 /**
  * Check the given property values against the required fields, generating missing field errors
  * where appropriate.
  *
  * @param mpvs the property values to be bound (can be modified)
  * @see #getRequiredFields
  * @see #getBindingErrorProcessor
  * @see BindingErrorProcessor#processMissingFieldError
  */
 protected void checkRequiredFields(MutablePropertyValues mpvs) {
   String[] requiredFields = getRequiredFields();
   if (!ObjectUtils.isEmpty(requiredFields)) {
     Map<String, PropertyValue> propertyValues = new HashMap<String, PropertyValue>();
     PropertyValue[] pvs = mpvs.getPropertyValues();
     for (PropertyValue pv : pvs) {
       String canonicalName = PropertyAccessorUtils.canonicalPropertyName(pv.getName());
       propertyValues.put(canonicalName, pv);
     }
     for (String field : requiredFields) {
       PropertyValue pv = propertyValues.get(field);
       boolean empty = (pv == null || pv.getValue() == null);
       if (!empty) {
         if (pv.getValue() instanceof String) {
           empty = !StringUtils.hasText((String) pv.getValue());
         } else if (pv.getValue() instanceof String[]) {
           String[] values = (String[]) pv.getValue();
           empty = (values.length == 0 || !StringUtils.hasText(values[0]));
         }
       }
       if (empty) {
         // Use bind error processor to create FieldError.
         getBindingErrorProcessor().processMissingFieldError(field, getInternalBindingResult());
         // Remove property from property values to bind:
         // It has already caused a field error with a rejected value.
         if (pv != null) {
           mpvs.removePropertyValue(pv);
           propertyValues.remove(field);
         }
       }
     }
   }
 }
  @Test
  public void testAutoProxyCreatorWithFactoryBeanAndProxyFactoryBeanOnly() {
    StaticApplicationContext sac = new StaticApplicationContext();

    MutablePropertyValues pvs = new MutablePropertyValues();
    pvs.add("proxyObject", "false");
    sac.registerSingleton("testAutoProxyCreator", TestAutoProxyCreator.class, pvs);

    pvs = new MutablePropertyValues();
    pvs.add("singleton", "false");
    sac.registerSingleton("prototypeFactoryToBeProxied", DummyFactory.class, pvs);

    sac.refresh();

    TestAutoProxyCreator tapc = (TestAutoProxyCreator) sac.getBean("testAutoProxyCreator");
    tapc.testInterceptor.nrOfInvocations = 0;

    FactoryBean<?> prototypeFactory = (FactoryBean<?>) sac.getBean("&prototypeFactoryToBeProxied");
    assertTrue(AopUtils.isCglibProxy(prototypeFactory));
    TestBean tb = (TestBean) sac.getBean("prototypeFactoryToBeProxied");
    assertFalse(AopUtils.isCglibProxy(tb));

    assertEquals(2, tapc.testInterceptor.nrOfInvocations);
    tb.getAge();
    assertEquals(2, tapc.testInterceptor.nrOfInvocations);
  }
 @Test
 public void testBindMonthDay() {
   MutablePropertyValues propertyValues = new MutablePropertyValues();
   propertyValues.add("monthDay", "--12-03");
   binder.bind(propertyValues);
   assertEquals(0, binder.getBindingResult().getErrorCount());
   assertTrue(binder.getBindingResult().getFieldValue("monthDay").toString().equals("--12-03"));
 }
 @Test
 public void testBindLocalDateAnnotatedWithError() {
   MutablePropertyValues propertyValues = new MutablePropertyValues();
   propertyValues.add("localDateAnnotated", "Oct -31, 2009");
   binder.bind(propertyValues);
   assertEquals(1, binder.getBindingResult().getFieldErrorCount("localDateAnnotated"));
   assertEquals("Oct -31, 2009", binder.getBindingResult().getFieldValue("localDateAnnotated"));
 }
 @Test
 public void testBindPeriod() {
   MutablePropertyValues propertyValues = new MutablePropertyValues();
   propertyValues.add("period", "P6Y3M1D");
   binder.bind(propertyValues);
   assertEquals(0, binder.getBindingResult().getErrorCount());
   assertTrue(binder.getBindingResult().getFieldValue("period").toString().equals("P6Y3M1D"));
 }
 @Test
 public void testBindISODateTimeWithZone() {
   MutablePropertyValues propertyValues = new MutablePropertyValues();
   propertyValues.add("isoDateTime", "2009-10-31T12:00:00.000Z");
   binder.bind(propertyValues);
   assertEquals(0, binder.getBindingResult().getErrorCount());
   assertEquals("2009-10-31T12:00:00", binder.getBindingResult().getFieldValue("isoDateTime"));
 }
 @Test
 public void testBindISOTime() {
   MutablePropertyValues propertyValues = new MutablePropertyValues();
   propertyValues.add("isoTime", "12:00:00");
   binder.bind(propertyValues);
   assertEquals(0, binder.getBindingResult().getErrorCount());
   assertEquals("12:00:00", binder.getBindingResult().getFieldValue("isoTime"));
 }
 @Test
 public void testBindLocalDate() {
   MutablePropertyValues propertyValues = new MutablePropertyValues();
   propertyValues.add("localDate", "10/31/09");
   binder.bind(propertyValues);
   assertEquals(0, binder.getBindingResult().getErrorCount());
   assertEquals("10/31/09", binder.getBindingResult().getFieldValue("localDate"));
 }
 @Test
 public void testBindLocalTimeFromJavaUtilCalendar() throws Exception {
   MutablePropertyValues propertyValues = new MutablePropertyValues();
   propertyValues.add("localTime", new GregorianCalendar(1970, 0, 0, 12, 0));
   binder.bind(propertyValues);
   assertEquals(0, binder.getBindingResult().getErrorCount());
   assertEquals("12:00 PM", binder.getBindingResult().getFieldValue("localTime"));
 }
 @Test
 public void testBindLocalTimeAnnotated() {
   MutablePropertyValues propertyValues = new MutablePropertyValues();
   propertyValues.add("localTimeAnnotated", "12:00:00 PM");
   binder.bind(propertyValues);
   assertEquals(0, binder.getBindingResult().getErrorCount());
   assertEquals("12:00:00 PM", binder.getBindingResult().getFieldValue("localTimeAnnotated"));
 }
 @Test
 public void testBindYearMonth() {
   MutablePropertyValues propertyValues = new MutablePropertyValues();
   propertyValues.add("yearMonth", "2007-12");
   binder.bind(propertyValues);
   assertEquals(0, binder.getBindingResult().getErrorCount());
   assertTrue(binder.getBindingResult().getFieldValue("yearMonth").toString().equals("2007-12"));
 }
 private void filterNestedParameterMaps(MutablePropertyValues mpvs) {
   for (PropertyValue pv : mpvs.getPropertyValues()) {
     final Object value = pv.getValue();
     if (isNotCandidateForBinding(value)) {
       mpvs.removePropertyValue(pv);
     }
   }
 }
 @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");
 }
 @Test
 public void testBindNestedLocalDateAnnotated() {
   MutablePropertyValues propertyValues = new MutablePropertyValues();
   propertyValues.add("children[0].localDateAnnotated", "Oct 31, 2009");
   binder.bind(propertyValues);
   assertEquals(0, binder.getBindingResult().getErrorCount());
   assertEquals(
       "Oct 31, 2009", binder.getBindingResult().getFieldValue("children[0].localDateAnnotated"));
 }
 @Test
 public void testBindDateTimeAnnotatedPattern() {
   MutablePropertyValues propertyValues = new MutablePropertyValues();
   propertyValues.add("dateTimeAnnotatedPattern", "10/31/09 12:00 PM");
   binder.bind(propertyValues);
   assertEquals(0, binder.getBindingResult().getErrorCount());
   assertEquals(
       "10/31/09 12:00 PM", binder.getBindingResult().getFieldValue("dateTimeAnnotatedPattern"));
 }
 @Test
 public void testBindLocalDateAnnotatedWithDirectFieldAccess() {
   binder.initDirectFieldAccess();
   MutablePropertyValues propertyValues = new MutablePropertyValues();
   propertyValues.add("localDateAnnotated", "Oct 31, 2009");
   binder.bind(propertyValues);
   assertEquals(0, binder.getBindingResult().getErrorCount());
   assertEquals("Oct 31, 2009", binder.getBindingResult().getFieldValue("localDateAnnotated"));
 }
 @Test
 public void testBindInstantFromJavaUtilDate() throws Exception {
   MutablePropertyValues propertyValues = new MutablePropertyValues();
   propertyValues.add("instant", new Date(109, 9, 31, 12, 0));
   binder.bind(propertyValues);
   assertEquals(0, binder.getBindingResult().getErrorCount());
   assertTrue(
       binder.getBindingResult().getFieldValue("instant").toString().startsWith("2009-10-31"));
 }
 @Test
 public void testBindDuration() {
   MutablePropertyValues propertyValues = new MutablePropertyValues();
   propertyValues.add("duration", "PT8H6M12.345S");
   binder.bind(propertyValues);
   assertEquals(0, binder.getBindingResult().getErrorCount());
   assertTrue(
       binder.getBindingResult().getFieldValue("duration").toString().equals("PT8H6M12.345S"));
 }
 /**
  * Checks for structured properties. Structured properties are properties with a name containg a
  * "_"
  *
  * @param propertyValues
  */
 @SuppressWarnings("unchecked")
 private void checkStructuredProperties(MutablePropertyValues propertyValues) {
   PropertyValue[] pvs = propertyValues.getPropertyValues();
   for (PropertyValue propertyValue : pvs) {
     if (!isStructured(propertyValue)) {
       continue;
     }
     String propertyName = getNameOf(propertyValue);
     Class<?> type = bean.getPropertyType(propertyName);
     if (type != null) {
       PropertyEditor editor = findCustomEditor(type, propertyName);
       if (null != editor && StructuredPropertyEditor.class.isAssignableFrom(editor.getClass())) {
         StructuredPropertyEditor structuredEditor = (StructuredPropertyEditor) editor;
         List fields = new ArrayList();
         fields.addAll(structuredEditor.getRequiredFields());
         fields.addAll(structuredEditor.getOptionalFields());
         Map<String, String> fieldValues = new HashMap<String, String>();
         try {
           for (Object fld : fields) {
             String field = (String) fld;
             PropertyValue partialStructValue =
                 propertyValues.getPropertyValue(
                     propertyName + STRUCTURED_PROPERTY_SEPERATOR + field);
             if (partialStructValue == null
                 && structuredEditor.getRequiredFields().contains(field)) {
               throw new MissingPropertyException(
                   "Required structured property is missing [" + field + "]");
             } else if (partialStructValue == null) {
               continue;
             }
             fieldValues.put(field, getStringValue(partialStructValue));
           }
           try {
             Object value = structuredEditor.assemble(type, fieldValues);
             for (Object fld : fields) {
               String field = (String) fld;
               PropertyValue partialStructValue =
                   propertyValues.getPropertyValue(
                       propertyName + STRUCTURED_PROPERTY_SEPERATOR + field);
               if (null != partialStructValue) {
                 partialStructValue.setConvertedValue(getStringValue(partialStructValue));
               }
             }
             propertyValues.addPropertyValue(new PropertyValue(propertyName, value));
           } catch (IllegalArgumentException iae) {
             LOG.warn(
                 "Unable to parse structured date from request for date [" + propertyName + "]",
                 iae);
           }
         } catch (InvalidPropertyException ipe) {
           // ignore
         }
       }
     }
   }
 }
 @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");
 }
 @Test
 public void testBindWithAlias() throws Exception {
   VanillaTarget target = new VanillaTarget();
   MutablePropertyValues properties = new MutablePropertyValues();
   properties.add("flub", "a");
   properties.add("foo", "b");
   new RelaxedDataBinder(target).withAlias("flub", "fooBaz").bind(properties);
   assertThat(target.getFooBaz(), equalTo("a"));
   assertThat(target.getFoo(), equalTo("b"));
 }
 @Test
 public void testBindLocalDateTimeAnnotated() {
   MutablePropertyValues propertyValues = new MutablePropertyValues();
   propertyValues.add("localDateTimeAnnotated", LocalDateTime.of(2009, 10, 31, 12, 0));
   binder.bind(propertyValues);
   assertEquals(0, binder.getBindingResult().getErrorCount());
   String value = binder.getBindingResult().getFieldValue("localDateTimeAnnotated").toString();
   assertTrue(value.startsWith("Oct 31, 2009"));
   assertTrue(value.endsWith("12:00:00 PM"));
 }
 @Test
 public void testBindLocalDateTimeFromJavaUtilCalendar() throws Exception {
   MutablePropertyValues propertyValues = new MutablePropertyValues();
   propertyValues.add("localDateTime", new GregorianCalendar(2009, 9, 31, 12, 0));
   binder.bind(propertyValues);
   assertEquals(0, binder.getBindingResult().getErrorCount());
   String value = binder.getBindingResult().getFieldValue("localDateTime").toString();
   assertTrue(value.startsWith("10/31/09"));
   assertTrue(value.endsWith("12:00 PM"));
 }