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"); } }
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); }
public void testIndexedProperties() { IndexedTestBean bean = new IndexedTestBean(); BeanWrapper bw = new BeanWrapperImpl(bean); TestBean tb0 = bean.getArray()[0]; TestBean tb1 = bean.getArray()[1]; TestBean tb2 = ((TestBean) bean.getList().get(0)); TestBean tb3 = ((TestBean) bean.getList().get(1)); TestBean tb6 = ((TestBean) bean.getSet().toArray()[0]); TestBean tb7 = ((TestBean) bean.getSet().toArray()[1]); TestBean tb4 = ((TestBean) bean.getMap().get("key1")); TestBean tb5 = ((TestBean) bean.getMap().get("key2")); assertEquals("name0", tb0.getName()); assertEquals("name1", tb1.getName()); assertEquals("name2", tb2.getName()); assertEquals("name3", tb3.getName()); assertEquals("name6", tb6.getName()); assertEquals("name7", tb7.getName()); assertEquals("name4", tb4.getName()); assertEquals("name5", tb5.getName()); assertEquals("name0", bw.getPropertyValue("array[0].name")); assertEquals("name1", bw.getPropertyValue("array[1].name")); assertEquals("name2", bw.getPropertyValue("list[0].name")); assertEquals("name3", bw.getPropertyValue("list[1].name")); assertEquals("name6", bw.getPropertyValue("set[0].name")); assertEquals("name7", bw.getPropertyValue("set[1].name")); assertEquals("name4", bw.getPropertyValue("map[key1].name")); assertEquals("name5", bw.getPropertyValue("map[key2].name")); assertEquals("name4", bw.getPropertyValue("map['key1'].name")); assertEquals("name5", bw.getPropertyValue("map[\"key2\"].name")); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.addPropertyValue("array[0].name", "name5"); pvs.addPropertyValue("array[1].name", "name4"); pvs.addPropertyValue("list[0].name", "name3"); pvs.addPropertyValue("list[1].name", "name2"); pvs.addPropertyValue("set[0].name", "name8"); pvs.addPropertyValue("set[1].name", "name9"); pvs.addPropertyValue("map[key1].name", "name1"); pvs.addPropertyValue("map['key2'].name", "name0"); bw.setPropertyValues(pvs); assertEquals("name5", tb0.getName()); assertEquals("name4", tb1.getName()); assertEquals("name3", tb2.getName()); assertEquals("name2", tb3.getName()); assertEquals("name1", tb4.getName()); assertEquals("name0", tb5.getName()); assertEquals("name5", bw.getPropertyValue("array[0].name")); assertEquals("name4", bw.getPropertyValue("array[1].name")); assertEquals("name3", bw.getPropertyValue("list[0].name")); assertEquals("name2", bw.getPropertyValue("list[1].name")); assertEquals("name8", bw.getPropertyValue("set[0].name")); assertEquals("name9", bw.getPropertyValue("set[1].name")); assertEquals("name1", bw.getPropertyValue("map[\"key1\"].name")); assertEquals("name0", bw.getPropertyValue("map['key2'].name")); }
public void testIndexedPropertiesWithCustomEditorForType() { IndexedTestBean bean = new IndexedTestBean(); BeanWrapper bw = new BeanWrapperImpl(bean); bw.registerCustomEditor( String.class, null, new PropertyEditorSupport() { public void setAsText(String text) throws IllegalArgumentException { setValue("prefix" + text); } }); TestBean tb0 = bean.getArray()[0]; TestBean tb1 = bean.getArray()[1]; TestBean tb2 = ((TestBean) bean.getList().get(0)); TestBean tb3 = ((TestBean) bean.getList().get(1)); TestBean tb4 = ((TestBean) bean.getMap().get("key1")); TestBean tb5 = ((TestBean) bean.getMap().get("key2")); assertEquals("name0", tb0.getName()); assertEquals("name1", tb1.getName()); assertEquals("name2", tb2.getName()); assertEquals("name3", tb3.getName()); assertEquals("name4", tb4.getName()); assertEquals("name5", tb5.getName()); assertEquals("name0", bw.getPropertyValue("array[0].name")); assertEquals("name1", bw.getPropertyValue("array[1].name")); assertEquals("name2", bw.getPropertyValue("list[0].name")); assertEquals("name3", bw.getPropertyValue("list[1].name")); assertEquals("name4", bw.getPropertyValue("map[key1].name")); assertEquals("name5", bw.getPropertyValue("map[key2].name")); assertEquals("name4", bw.getPropertyValue("map['key1'].name")); assertEquals("name5", bw.getPropertyValue("map[\"key2\"].name")); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.addPropertyValue("array[0].name", "name5"); pvs.addPropertyValue("array[1].name", "name4"); pvs.addPropertyValue("list[0].name", "name3"); pvs.addPropertyValue("list[1].name", "name2"); pvs.addPropertyValue("map[key1].name", "name1"); pvs.addPropertyValue("map['key2'].name", "name0"); bw.setPropertyValues(pvs); assertEquals("prefixname5", tb0.getName()); assertEquals("prefixname4", tb1.getName()); assertEquals("prefixname3", tb2.getName()); assertEquals("prefixname2", tb3.getName()); assertEquals("prefixname1", tb4.getName()); assertEquals("prefixname0", tb5.getName()); assertEquals("prefixname5", bw.getPropertyValue("array[0].name")); assertEquals("prefixname4", bw.getPropertyValue("array[1].name")); assertEquals("prefixname3", bw.getPropertyValue("list[0].name")); assertEquals("prefixname2", bw.getPropertyValue("list[1].name")); assertEquals("prefixname1", bw.getPropertyValue("map[\"key1\"].name")); assertEquals("prefixname0", bw.getPropertyValue("map['key2'].name")); }
/** * 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; }
@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); } }
@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 BeanDefinition parse(Element element, ParserContext parserContent) { BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(GetMentionsMessageProcessor.class.getName()); String configRef = element.getAttribute("config-ref"); if ((configRef != null) && (!StringUtils.isBlank(configRef))) { builder.addPropertyValue("moduleObject", configRef); } if ((element.getAttribute("page") != null) && (!StringUtils.isBlank(element.getAttribute("page")))) { builder.addPropertyValue("page", element.getAttribute("page")); } if ((element.getAttribute("count") != null) && (!StringUtils.isBlank(element.getAttribute("count")))) { builder.addPropertyValue("count", element.getAttribute("count")); } if ((element.getAttribute("sinceId") != null) && (!StringUtils.isBlank(element.getAttribute("sinceId")))) { builder.addPropertyValue("sinceId", element.getAttribute("sinceId")); } BeanDefinition definition = builder.getBeanDefinition(); definition.setAttribute( MuleHierarchicalBeanDefinitionParserDelegate.MULE_NO_RECURSE, Boolean.TRUE); MutablePropertyValues propertyValues = parserContent.getContainingBeanDefinition().getPropertyValues(); if (parserContent .getContainingBeanDefinition() .getBeanClassName() .equals("org.mule.config.spring.factories.PollingMessageSourceFactoryBean")) { propertyValues.addPropertyValue("messageProcessor", definition); } else { if (parserContent .getContainingBeanDefinition() .getBeanClassName() .equals("org.mule.enricher.MessageEnricher")) { propertyValues.addPropertyValue("enrichmentMessageProcessor", definition); } else { PropertyValue messageProcessors = propertyValues.getPropertyValue("messageProcessors"); if ((messageProcessors == null) || (messageProcessors.getValue() == null)) { propertyValues.addPropertyValue("messageProcessors", new ManagedList()); } List listMessageProcessors = ((List) propertyValues.getPropertyValue("messageProcessors").getValue()); listMessageProcessors.add(definition); } } return definition; }
public void testSetPropertyValuesIgnoresInvalidNestedOnRequest() { ITestBean rod = new TestBean(); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.addPropertyValue(new PropertyValue("name", "rod")); pvs.addPropertyValue(new PropertyValue("graceful.rubbish", "tony")); pvs.addPropertyValue(new PropertyValue("more.garbage", new Object())); BeanWrapper bw = new BeanWrapperImpl(rod); bw.setPropertyValues(pvs, true); assertTrue("Set valid and ignored invalid", rod.getName().equals("rod")); try { // Don't ignore: should fail bw.setPropertyValues(pvs, false); fail("Shouldn't have ignored invalid updates"); } catch (NotWritablePropertyException ex) { // OK: but which exception?? } }
/** * Copy all given PropertyValues into this object. Guarantees PropertyValue references are * independent, although it can't deep copy objects currently referenced by individual * PropertyValue objects. * * @param source the PropertyValues to copy */ public void addPropertyValues(PropertyValues source) { if (source != null) { PropertyValue[] pvs = source.getPropertyValues(); for (int i = 0; i < pvs.length; i++) { addPropertyValue(new PropertyValue(pvs[i].getName(), pvs[i].getValue())); } recache(); } }
public PropertyValues changesSince(PropertyValues old) { MutablePropertyValues changes = new MutablePropertyValues(); if (old == this) return changes; // for each property value in the new set for (int i = 0; i < this.propertyValueArray.length; i++) { PropertyValue newPv = propertyValueArray[i]; // if there wasn't an old one, add it PropertyValue pvOld = old.getPropertyValue(newPv.getName()); if (pvOld == null) { changes.addPropertyValue(newPv); } else if (!pvOld.equals(newPv)) { // it's changed changes.addPropertyValue(newPv); } } return changes; }
/** * 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 } } } } }
/** * Add all property values from the given Map. * * @param source Map with property values keyed by property name, which must be a String */ public void addPropertyValues(Map source) { if (source != null) { Iterator it = source.keySet().iterator(); while (it.hasNext()) { String key = (String) it.next(); addPropertyValue(new PropertyValue(key, source.get(key))); } recache(); } }
public void testIndexedPropertiesWithDirectAccess() { IndexedTestBean bean = new IndexedTestBean(); BeanWrapper bw = new BeanWrapperImpl(bean); TestBean tb0 = bean.getArray()[0]; TestBean tb1 = bean.getArray()[1]; TestBean tb2 = ((TestBean) bean.getList().get(0)); TestBean tb3 = ((TestBean) bean.getList().get(1)); TestBean tb6 = ((TestBean) bean.getSet().toArray()[0]); TestBean tb7 = ((TestBean) bean.getSet().toArray()[1]); TestBean tb4 = ((TestBean) bean.getMap().get("key1")); TestBean tb5 = ((TestBean) bean.getMap().get("key2")); assertEquals(tb0, bw.getPropertyValue("array[0]")); assertEquals(tb1, bw.getPropertyValue("array[1]")); assertEquals(tb2, bw.getPropertyValue("list[0]")); assertEquals(tb3, bw.getPropertyValue("list[1]")); assertEquals(tb6, bw.getPropertyValue("set[0]")); assertEquals(tb7, bw.getPropertyValue("set[1]")); assertEquals(tb4, bw.getPropertyValue("map[key1]")); assertEquals(tb5, bw.getPropertyValue("map[key2]")); assertEquals(tb4, bw.getPropertyValue("map['key1']")); assertEquals(tb5, bw.getPropertyValue("map[\"key2\"]")); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.addPropertyValue("array[0]", tb5); pvs.addPropertyValue("array[1]", tb4); pvs.addPropertyValue("list[0]", tb3); pvs.addPropertyValue("list[1]", tb2); pvs.addPropertyValue("list[2]", tb0); pvs.addPropertyValue("list[4]", tb1); pvs.addPropertyValue("map[key1]", tb1); pvs.addPropertyValue("map['key2']", tb0); pvs.addPropertyValue("map[key5]", tb4); pvs.addPropertyValue("map['key9']", tb5); bw.setPropertyValues(pvs); assertEquals(tb5, bean.getArray()[0]); assertEquals(tb4, bean.getArray()[1]); assertEquals(tb3, ((TestBean) bean.getList().get(0))); assertEquals(tb2, ((TestBean) bean.getList().get(1))); assertEquals(tb0, ((TestBean) bean.getList().get(2))); assertEquals(null, ((TestBean) bean.getList().get(3))); assertEquals(tb1, ((TestBean) bean.getList().get(4))); assertEquals(tb1, ((TestBean) bean.getMap().get("key1"))); assertEquals(tb0, ((TestBean) bean.getMap().get("key2"))); assertEquals(tb4, ((TestBean) bean.getMap().get("key5"))); assertEquals(tb5, ((TestBean) bean.getMap().get("key9"))); assertEquals(tb5, bw.getPropertyValue("array[0]")); assertEquals(tb4, bw.getPropertyValue("array[1]")); assertEquals(tb3, bw.getPropertyValue("list[0]")); assertEquals(tb2, bw.getPropertyValue("list[1]")); assertEquals(tb0, bw.getPropertyValue("list[2]")); assertEquals(null, bw.getPropertyValue("list[3]")); assertEquals(tb1, bw.getPropertyValue("list[4]")); assertEquals(tb1, bw.getPropertyValue("map[\"key1\"]")); assertEquals(tb0, bw.getPropertyValue("map['key2']")); assertEquals(tb4, bw.getPropertyValue("map[\"key5\"]")); assertEquals(tb5, bw.getPropertyValue("map['key9']")); }
public void testAllValid() { TestBean t = new TestBean(); String newName = "tony"; int newAge = 65; String newTouchy = "valid"; try { BeanWrapper bw = new BeanWrapperImpl(t); // System.out.println(bw); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.addPropertyValue(new PropertyValue("age", new Integer(newAge))); pvs.addPropertyValue(new PropertyValue("name", newName)); pvs.addPropertyValue(new PropertyValue("touchy", newTouchy)); bw.setPropertyValues(pvs); assertTrue("Validly set property must stick", t.getName().equals(newName)); assertTrue("Validly set property must stick", t.getTouchy().equals(newTouchy)); assertTrue("Validly set property must stick", t.getAge() == newAge); } catch (BeansException ex) { fail("Shouldn't throw exception when everything is valid"); } }
@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", "被修改了"); } }
public void testNoArgGetter() { StaticApplicationContext ctx = new StaticApplicationContext(); ctx.registerSingleton("testService", TestService.class, new MutablePropertyValues()); MutablePropertyValues mpv = new MutablePropertyValues(); mpv.addPropertyValue(new PropertyValue("serviceLocatorInterface", TestServiceLocator.class)); ctx.registerSingleton("factory", ServiceLocatorFactoryBean.class, mpv); ctx.refresh(); TestServiceLocator factory = (TestServiceLocator) ctx.getBean("factory"); TestService testService = factory.getTestService(); assertNotNull(testService); }
/** {@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); } } }
/** * Parse the split and turn it into a list of transitions. * * @param element the <split/gt; element to parse * @param parserContext the parser context for the bean factory * @return a collection of bean definitions for {@link * org.springframework.batch.core.job.flow.support.StateTransition} instances objects */ public Collection<BeanDefinition> parse(Element element, ParserContext parserContext) { String idAttribute = element.getAttribute("id"); BeanDefinitionBuilder stateBuilder = BeanDefinitionBuilder.genericBeanDefinition( "org.springframework.batch.core.job.flow.support.state.SplitState"); String taskExecutorBeanId = element.getAttribute("task-executor"); if (StringUtils.hasText(taskExecutorBeanId)) { RuntimeBeanReference taskExecutorRef = new RuntimeBeanReference(taskExecutorBeanId); stateBuilder.addPropertyValue("taskExecutor", taskExecutorRef); } List<Element> flowElements = DomUtils.getChildElementsByTagName(element, "flow"); if (flowElements.size() < 2) { parserContext .getReaderContext() .error("A <split/> must contain at least two 'flow' elements.", element); } Collection<BeanDefinition> flows = new ManagedList<BeanDefinition>(); int i = 0; String prefix = idAttribute; for (Element nextElement : flowElements) { String ref = nextElement.getAttribute(PARENT_ATTR); if (StringUtils.hasText(ref)) { if (nextElement.getElementsByTagName("*").getLength() > 0) { parserContext .getReaderContext() .error( "A <flow/> in a <split/> must have ref= or nested <flow/>, but not both.", nextElement); } AbstractBeanDefinition flowDefinition = new GenericBeanDefinition(); flowDefinition.setParentName(ref); MutablePropertyValues propertyValues = flowDefinition.getPropertyValues(); propertyValues.addPropertyValue("name", prefix + "." + i); flows.add(flowDefinition); } else { InlineFlowParser flowParser = new InlineFlowParser(prefix + "." + i, jobFactoryRef); flows.add(flowParser.parse(nextElement, parserContext)); } i++; } stateBuilder.addConstructorArgValue(flows); stateBuilder.addConstructorArgValue(prefix); return InlineFlowParser.getNextElements( parserContext, stateBuilder.getBeanDefinition(), element); }
/* (non-Javadoc) * @see gov.nih.nci.cabig.caaers.domain.expeditedfields.PropertyNode#addPropertyValues(java.lang.String, java.lang.Object, org.springframework.beans.MutablePropertyValues) */ @Override protected void addPropertyValues( String baseName, Object baseValue, MutablePropertyValues target) { if (baseValue == null) return; String qualifiedName = qualifyName(baseName, getPropertyName()); BeanWrapperImpl wrappedValue = new BeanWrapperImpl(baseValue); List<?> thisProp = (List<?>) wrappedValue.getPropertyValue(getPropertyName()); if (thisProp == null) return; for (int i = 0; i < thisProp.size(); i++) { Object o = thisProp.get(i); target.addPropertyValue(String.format("%s[%d]", qualifiedName, i), o); } }
private AbstractBeanDefinition parseSessionFactory( Element element, String dataSourceId, BeanDefinitionRegistry targetRegistry, ParserContext parserContext) { String sessionFactoryId = StringUtils.hasText(element.getAttribute(ID_ATTRIBUTE)) ? element.getAttribute(ID_ATTRIBUTE) : "sessionFactory"; AbstractBeanDefinition sessionFactoryBean = new GenericBeanDefinition(); sessionFactoryBean.setBeanClass(ConfigurableLocalSessionFactoryBean.class); MutablePropertyValues propertyValues = sessionFactoryBean.getPropertyValues(); final RuntimeBeanReference dataSourceRef = new RuntimeBeanReference(dataSourceId); propertyValues.addPropertyValue("dataSource", dataSourceRef); Class<?> configClass = lookupConfigClass(element, parserContext); propertyValues.addPropertyValue("configClass", configClass); final String configLocation = element.getAttribute(CONFIG_LOCATION_ATTRIBUTE); if (StringUtils.hasText(configLocation)) { propertyValues.addPropertyValue("configLocation", configLocation); } propertyValues.addPropertyValue( GrailsApplication.APPLICATION_ID, new RuntimeBeanReference(GrailsApplication.APPLICATION_ID)); targetRegistry.registerBeanDefinition(sessionFactoryId, sessionFactoryBean); final String lobHandlerRef = element.getAttribute(LOB_HANDLER_ATTRIBUTE); if (StringUtils.hasText(lobHandlerRef)) { propertyValues.addPropertyValue("lobHandler", new RuntimeBeanReference(lobHandlerRef)); } else { GenericBeanDefinition lobHandler = new GenericBeanDefinition(); lobHandler.setBeanClass(SpringLobHandlerDetectorFactoryBean.class); lobHandler.getPropertyValues().addPropertyValue("pooledConnection", true); lobHandler.getPropertyValues().addPropertyValue("dataSource", dataSourceRef); propertyValues.addPropertyValue("lobHandler", lobHandler); } String transactionManagerRef = element.getAttribute(TRANSACTION_MANAGER_ATTRIBUTE); if (StringUtils.hasText(transactionManagerRef)) { targetRegistry.registerAlias(transactionManagerRef, "transactionManager"); } else { GenericBeanDefinition transactionManagerBean = new GenericBeanDefinition(); transactionManagerBean.setBeanClass(GrailsHibernateTransactionManager.class); transactionManagerBean .getPropertyValues() .addPropertyValue("sessionFactory", new RuntimeBeanReference(sessionFactoryId)); targetRegistry.registerBeanDefinition("transactionManager", transactionManagerBean); } parserContext.getDelegate().parsePropertyElements(element, sessionFactoryBean); return sessionFactoryBean; }
public void testErrorOnTooManyOrTooFew() throws Exception { StaticApplicationContext ctx = new StaticApplicationContext(); ctx.registerSingleton("testService", TestService.class, new MutablePropertyValues()); ctx.registerSingleton("testServiceInstance2", TestService.class, new MutablePropertyValues()); MutablePropertyValues mpv = new MutablePropertyValues(); mpv.addPropertyValue(new PropertyValue("serviceLocatorInterface", TestServiceLocator.class)); ctx.registerSingleton("factory", ServiceLocatorFactoryBean.class, mpv); mpv = new MutablePropertyValues(); mpv.addPropertyValue(new PropertyValue("serviceLocatorInterface", TestServiceLocator2.class)); ctx.registerSingleton("factory2", ServiceLocatorFactoryBean.class, mpv); mpv = new MutablePropertyValues(); mpv.addPropertyValue(new PropertyValue("serviceLocatorInterface", TestService2Locator.class)); ctx.registerSingleton("factory3", ServiceLocatorFactoryBean.class, mpv); ctx.refresh(); final TestServiceLocator factory = (TestServiceLocator) ctx.getBean("factory"); new AssertThrows( NoSuchBeanDefinitionException.class, "Must fail on more than one matching type") { public void test() throws Exception { factory.getTestService(); } }.runTest(); final TestServiceLocator2 factory2 = (TestServiceLocator2) ctx.getBean("factory2"); new AssertThrows( NoSuchBeanDefinitionException.class, "Must fail on more than one matching type") { public void test() throws Exception { factory2.getTestService(null); } }.runTest(); final TestService2Locator factory3 = (TestService2Locator) ctx.getBean("factory3"); new AssertThrows(NoSuchBeanDefinitionException.class, "Must fail on no matching types") { public void test() throws Exception { factory3.getTestService(); } }.runTest(); }
private PropertyValues filterPropertyValues(PropertyValues propertyValues, String prefix) { if (prefix == null || prefix.length() == 0) return propertyValues; PropertyValue[] valueArray = propertyValues.getPropertyValues(); MutablePropertyValues newValues = new MutablePropertyValues(); for (PropertyValue propertyValue : valueArray) { String name = propertyValue.getName(); final String prefixWithDot = prefix + PREFIX_SEPERATOR; if (name.startsWith(prefixWithDot)) { name = name.substring(prefixWithDot.length(), name.length()); newValues.addPropertyValue(name, propertyValue.getValue()); } } return newValues; }
public void testStringArgGetter() throws Exception { StaticApplicationContext ctx = new StaticApplicationContext(); ctx.registerSingleton("testService", TestService.class, new MutablePropertyValues()); MutablePropertyValues mpv = new MutablePropertyValues(); mpv.addPropertyValue(new PropertyValue("serviceLocatorInterface", TestServiceLocator2.class)); ctx.registerSingleton("factory", ServiceLocatorFactoryBean.class, mpv); ctx.refresh(); // test string-arg getter with null id final TestServiceLocator2 factory = (TestServiceLocator2) ctx.getBean("factory"); TestService testBean = factory.getTestService(null); // now test with explicit id testBean = factory.getTestService("testService"); // now verify failure on bad id new AssertThrows(NoSuchBeanDefinitionException.class, "Illegal operation allowed") { public void test() throws Exception { factory.getTestService("bogusTestService"); } }.runTest(); }
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()); }
public void testCombinedLocatorInterface() { StaticApplicationContext ctx = new StaticApplicationContext(); ctx.registerPrototype("testService", TestService.class, new MutablePropertyValues()); ctx.registerAlias("testService", "1"); MutablePropertyValues mpv = new MutablePropertyValues(); mpv.addPropertyValue("serviceLocatorInterface", TestServiceLocator3.class); ctx.registerSingleton("factory", ServiceLocatorFactoryBean.class, mpv); ctx.refresh(); TestServiceLocator3 factory = (TestServiceLocator3) ctx.getBean("factory"); TestService testBean1 = factory.getTestService(); TestService testBean2 = factory.getTestService("testService"); TestService testBean3 = factory.getTestService(1); TestService testBean4 = factory.someFactoryMethod(); assertNotSame(testBean1, testBean2); assertNotSame(testBean1, testBean3); assertNotSame(testBean1, testBean4); assertNotSame(testBean2, testBean3); assertNotSame(testBean2, testBean4); assertNotSame(testBean3, testBean4); assertTrue(factory.toString().indexOf("TestServiceLocator3") != -1); }
public void testErrorOnTooManyOrTooFewWithCustomServiceLocatorException() { StaticApplicationContext ctx = new StaticApplicationContext(); ctx.registerSingleton("testService", TestService.class, new MutablePropertyValues()); ctx.registerSingleton("testServiceInstance2", TestService.class, new MutablePropertyValues()); MutablePropertyValues mpv = new MutablePropertyValues(); mpv.addPropertyValue(new PropertyValue("serviceLocatorInterface", TestServiceLocator.class)); mpv.addPropertyValue( new PropertyValue("serviceLocatorExceptionClass", CustomServiceLocatorException1.class)); ctx.registerSingleton("factory", ServiceLocatorFactoryBean.class, mpv); mpv = new MutablePropertyValues(); mpv.addPropertyValue(new PropertyValue("serviceLocatorInterface", TestServiceLocator2.class)); mpv.addPropertyValue( new PropertyValue("serviceLocatorExceptionClass", CustomServiceLocatorException2.class)); ctx.registerSingleton("factory2", ServiceLocatorFactoryBean.class, mpv); mpv = new MutablePropertyValues(); mpv.addPropertyValue(new PropertyValue("serviceLocatorInterface", TestService2Locator.class)); mpv.addPropertyValue( new PropertyValue("serviceLocatorExceptionClass", CustomServiceLocatorException3.class)); ctx.registerSingleton("factory3", ServiceLocatorFactoryBean.class, mpv); ctx.refresh(); TestServiceLocator factory = (TestServiceLocator) ctx.getBean("factory"); try { factory.getTestService(); fail("Must fail on more than one matching type"); } catch (CustomServiceLocatorException1 expected) { assertTrue(expected.getCause() instanceof NoSuchBeanDefinitionException); } TestServiceLocator2 factory2 = (TestServiceLocator2) ctx.getBean("factory2"); try { factory2.getTestService(null); fail("Must fail on more than one matching type"); } catch (CustomServiceLocatorException2 expected) { assertTrue(expected.getCause() instanceof NoSuchBeanDefinitionException); } final TestService2Locator factory3 = (TestService2Locator) ctx.getBean("factory3"); new AssertThrows(CustomServiceLocatorException3.class, "Must fail on no matching types") { public void test() throws Exception { factory3.getTestService(); } }.runTest(); }
/** * 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."); } }
/** * Get all property values, given a prefix (which will be stripped) and add the bean they define * to the factory with the given name * * @param beanName name of the bean to define * @param map Map containing string pairs * @param prefix prefix of each entry, which will be stripped * @param resourceDescription description of the resource that the Map came from (for logging * purposes) * @throws BeansException if the bean definition could not be parsed or registered */ protected void registerBeanDefinition( String beanName, Map map, String prefix, String resourceDescription) throws BeansException { String className = null; String parent = null; boolean isAbstract = false; boolean singleton = true; boolean lazyInit = false; MutablePropertyValues pvs = new MutablePropertyValues(); for (Iterator it = map.entrySet().iterator(); it.hasNext(); ) { Map.Entry entry = (Map.Entry) it.next(); String key = StringUtils.trimWhitespace((String) entry.getKey()); if (key.startsWith(prefix + SEPARATOR)) { String property = key.substring(prefix.length() + SEPARATOR.length()); if (isClassKey(property)) { className = StringUtils.trimWhitespace((String) entry.getValue()); } else if (isParentKey(property)) { parent = StringUtils.trimWhitespace((String) entry.getValue()); } else if (ABSTRACT_KEY.equals(property)) { String val = StringUtils.trimWhitespace((String) entry.getValue()); isAbstract = TRUE_VALUE.equals(val); } else if (SINGLETON_KEY.equals(property)) { String val = StringUtils.trimWhitespace((String) entry.getValue()); singleton = (val == null) || TRUE_VALUE.equals(val); } else if (LAZY_INIT_KEY.equals(property)) { String val = StringUtils.trimWhitespace((String) entry.getValue()); lazyInit = TRUE_VALUE.equals(val); } else if (property.endsWith(REF_SUFFIX)) { // This isn't a real property, but a reference to another prototype // Extract property name: property is of form dog(ref) property = property.substring(0, property.length() - REF_SUFFIX.length()); String ref = StringUtils.trimWhitespace((String) entry.getValue()); // It doesn't matter if the referenced bean hasn't yet been registered: // this will ensure that the reference is resolved at runtime. Object val = new RuntimeBeanReference(ref); pvs.addPropertyValue(new PropertyValue(property, val)); } else { // It's a normal bean property. pvs.addPropertyValue(new PropertyValue(property, readValue(entry))); } } } if (logger.isDebugEnabled()) { logger.debug("Registering bean definition for bean name '" + beanName + "' with " + pvs); } // Just use default parent if we're not dealing with the parent itself, // and if there's no class name specified. The latter has to happen for // backwards compatibility reasons. if (parent == null && className == null && !beanName.equals(this.defaultParentBean)) { parent = this.defaultParentBean; } try { AbstractBeanDefinition bd = BeanDefinitionReaderUtils.createBeanDefinition( className, parent, null, pvs, getBeanClassLoader()); bd.setAbstract(isAbstract); bd.setSingleton(singleton); bd.setLazyInit(lazyInit); getBeanFactory().registerBeanDefinition(beanName, bd); } catch (ClassNotFoundException ex) { throw new BeanDefinitionStoreException( resourceDescription, beanName, "Bean class [" + className + "] not found", ex); } catch (NoClassDefFoundError err) { throw new BeanDefinitionStoreException( resourceDescription, beanName, "Class that bean class [" + className + "] depends on not found", err); } }
/** * Get all property values, given a prefix (which will be stripped) and add the bean they define * to the factory with the given name * * @param beanName name of the bean to define * @param m Map containing string pairs * @param prefix prefix of each entry, which will be stripped * @param resourceDescription description of the resource that the Map came from (for logging * purposes) * @throws BeansException if the bean definition could not be parsed or registered */ protected void registerBeanDefinition( String beanName, Map m, String prefix, String resourceDescription) throws BeansException { String className = null; String parent = null; boolean singleton = true; boolean lazyInit = false; MutablePropertyValues pvs = new MutablePropertyValues(); Set keys = m.keySet(); Iterator itr = keys.iterator(); while (itr.hasNext()) { String key = (String) itr.next(); if (key.startsWith(prefix + SEPARATOR)) { String property = key.substring(prefix.length() + SEPARATOR.length()); if (property.equals(CLASS_KEY)) { className = (String) m.get(key); } else if (property.equals(SINGLETON_KEY)) { String val = (String) m.get(key); singleton = (val == null) || val.equals(TRUE_VALUE); } else if (property.equals(LAZY_INIT_KEY)) { String val = (String) m.get(key); lazyInit = val.equals(TRUE_VALUE); } else if (property.equals(PARENT_KEY)) { parent = (String) m.get(key); } else if (property.endsWith(REF_SUFFIX)) { // This isn't a real property, but a reference to another prototype // Extract property name: property is of form dog(ref) property = property.substring(0, property.length() - REF_SUFFIX.length()); String ref = (String) m.get(key); // It doesn't matter if the referenced bean hasn't yet been registered: // this will ensure that the reference is resolved at rungime // Default is not to use singleton Object val = new RuntimeBeanReference(ref); pvs.addPropertyValue(new PropertyValue(property, val)); } else { // normal bean property Object val = m.get(key); if (val instanceof String) { String strVal = (String) val; // if it starts with a reference prefix... if (strVal.startsWith(REF_PREFIX)) { // expand reference String targetName = strVal.substring(1); if (targetName.startsWith(REF_PREFIX)) { // escaped prefix -> use plain value val = targetName; } else { val = new RuntimeBeanReference(targetName); } } } pvs.addPropertyValue(new PropertyValue(property, val)); } } } if (logger.isDebugEnabled()) { logger.debug(pvs.toString()); } if (parent == null) { parent = this.defaultParentBean; } if (className == null && parent == null) { throw new BeanDefinitionStoreException( resourceDescription, beanName, "Either 'class' or 'parent' is required"); } try { AbstractBeanDefinition beanDefinition = null; if (className != null) { // Load the class using a special class loader if one is available. // Otherwise rely on the thread context classloader. Class clazz = Class.forName(className, true, getBeanClassLoader()); beanDefinition = new RootBeanDefinition(clazz, pvs); } else { beanDefinition = new ChildBeanDefinition(parent, pvs); } beanDefinition.setSingleton(singleton); beanDefinition.setLazyInit(lazyInit); getBeanFactory().registerBeanDefinition(beanName, beanDefinition); } catch (ClassNotFoundException ex) { throw new BeanDefinitionStoreException( resourceDescription, beanName, "Class [" + className + "] not found", ex); } }