org.springframework.beans.PropertyValue Java Examples

The following examples show how to use org.springframework.beans.PropertyValue. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GrailsDataBinder.java    From AlgoTrader with GNU General Public License v2.0 6 votes vote down vote up
private void filterBlankValuesWhenTargetIsNullable(MutablePropertyValues mpvs) {
	Object target = getTarget();
	Map constrainedProperties = resolveConstrainedProperties(target, this.domainClass);
	if (constrainedProperties == null) {
		return;
	}

	PropertyValue[] valueArray = mpvs.getPropertyValues();
	for (PropertyValue propertyValue : valueArray) {
		if (BLANK.equals(propertyValue.getValue())) {
			ConstrainedProperty cp = getConstrainedPropertyForPropertyValue(constrainedProperties, propertyValue);
			if (shouldNullifyBlankString(propertyValue, cp)) {
				propertyValue.setConvertedValue(null);
			}
		}
	}
}
 
Example #2
Source File: AbstractCacheManagerAndProviderFacadeParser.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Parses the given XML element containing the properties of the cache manager
 * to register in the given registry of bean definitions.
 * 
 * @param element
 *          the XML element to parse
 * @param registry
 *          the registry of bean definitions
 * 
 * @see AbstractCacheProviderFacadeParser#doParse(String, Element,
 *      BeanDefinitionRegistry)
 */
protected final void doParse(String cacheProviderFacadeId, Element element,
    BeanDefinitionRegistry registry) {
  String id = "cacheManager";
  Class clazz = getCacheManagerClass();
  RootBeanDefinition cacheManager = new RootBeanDefinition(clazz);
  MutablePropertyValues cacheManagerProperties = new MutablePropertyValues();
  cacheManager.setPropertyValues(cacheManagerProperties);

  PropertyValue configLocation = parseConfigLocationProperty(element);
  cacheManagerProperties.addPropertyValue(configLocation);
  registry.registerBeanDefinition(id, cacheManager);

  BeanDefinition cacheProviderFacade = registry
      .getBeanDefinition(cacheProviderFacadeId);
  cacheProviderFacade.getPropertyValues().addPropertyValue("cacheManager",
      new RuntimeBeanReference(id));
}
 
Example #3
Source File: DataBinderFieldAccessTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void bindingNoErrors() throws Exception {
	FieldAccessBean rod = new FieldAccessBean();
	DataBinder binder = new DataBinder(rod, "person");
	assertTrue(binder.isIgnoreUnknownFields());
	binder.initDirectFieldAccess();
	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.addPropertyValue(new PropertyValue("name", "Rod"));
	pvs.addPropertyValue(new PropertyValue("age", new Integer(32)));
	pvs.addPropertyValue(new PropertyValue("nonExisting", "someValue"));

	binder.bind(pvs);
	binder.close();

	assertTrue("changed name correctly", rod.getName().equals("Rod"));
	assertTrue("changed age correctly", rod.getAge() == 32);

	Map<?, ?> m = binder.getBindingResult().getModel();
	assertTrue("There is one element in map", m.size() == 2);
	FieldAccessBean tb = (FieldAccessBean) m.get("person");
	assertTrue("Same object", tb.equals(rod));
}
 
Example #4
Source File: BeanDefinitionParserDelegate.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Parse a property element.
 */
public void parsePropertyElement(Element ele, BeanDefinition bd) {
	String propertyName = ele.getAttribute(NAME_ATTRIBUTE);
	if (!StringUtils.hasLength(propertyName)) {
		error("Tag 'property' must have a 'name' attribute", ele);
		return;
	}
	this.parseState.push(new PropertyEntry(propertyName));
	try {
		if (bd.getPropertyValues().contains(propertyName)) {
			error("Multiple 'property' definitions for property '" + propertyName + "'", ele);
			return;
		}
		Object val = parsePropertyValue(ele, bd, propertyName);
		PropertyValue pv = new PropertyValue(propertyName, val);
		parseMetaElements(ele, pv);
		pv.setSource(extractSource(ele));
		bd.getPropertyValues().addPropertyValue(pv);
	}
	finally {
		this.parseState.pop();
	}
}
 
Example #5
Source File: GenericFilterBean.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Create new FilterConfigPropertyValues.
 * @param config FilterConfig we'll use to take PropertyValues from
 * @param requiredProperties set of property names we need, where
 * we can't accept default values
 * @throws ServletException if any required properties are missing
 */
public FilterConfigPropertyValues(FilterConfig config, Set<String> requiredProperties)
		throws ServletException {

	Set<String> missingProps = (!CollectionUtils.isEmpty(requiredProperties) ?
			new HashSet<String>(requiredProperties) : null);

	Enumeration<String> paramNames = config.getInitParameterNames();
	while (paramNames.hasMoreElements()) {
		String property = paramNames.nextElement();
		Object value = config.getInitParameter(property);
		addPropertyValue(new PropertyValue(property, value));
		if (missingProps != null) {
			missingProps.remove(property);
		}
	}

	// Fail if we are still missing properties.
	if (!CollectionUtils.isEmpty(missingProps)) {
		throw new ServletException(
				"Initialization from FilterConfig for filter '" + config.getFilterName() +
				"' failed; the following required properties were missing: " +
				StringUtils.collectionToDelimitedString(missingProps, ", "));
	}
}
 
Example #6
Source File: AspectJAutoProxyCreatorTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testAspectsAndAdvisorAreAppliedEvenIfComingFromParentFactory() {
	ClassPathXmlApplicationContext ac = newContext("aspectsPlusAdvisor.xml");

	GenericApplicationContext childAc = new GenericApplicationContext(ac);
	// Create a child factory with a bean that should be woven
	RootBeanDefinition bd = new RootBeanDefinition(TestBean.class);
	bd.getPropertyValues().addPropertyValue(new PropertyValue("name", "Adrian"))
			.addPropertyValue(new PropertyValue("age", 34));
	childAc.registerBeanDefinition("adrian2", bd);
	// Register the advisor auto proxy creator with subclass
	childAc.registerBeanDefinition(AnnotationAwareAspectJAutoProxyCreator.class.getName(), new RootBeanDefinition(
			AnnotationAwareAspectJAutoProxyCreator.class));
	childAc.refresh();

	ITestBean beanFromChildContextThatShouldBeWeaved = (ITestBean) childAc.getBean("adrian2");
	//testAspectsAndAdvisorAreApplied(childAc, (ITestBean) ac.getBean("adrian"));
	doTestAspectsAndAdvisorAreApplied(childAc, beanFromChildContextThatShouldBeWeaved);
}
 
Example #7
Source File: HttpServletBean.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Create new ServletConfigPropertyValues.
 * @param config the ServletConfig we'll use to take PropertyValues from
 * @param requiredProperties set of property names we need, where
 * we can't accept default values
 * @throws ServletException if any required properties are missing
 */
public ServletConfigPropertyValues(ServletConfig config, Set<String> requiredProperties)
		throws ServletException {

	Set<String> missingProps = (!CollectionUtils.isEmpty(requiredProperties) ?
			new HashSet<>(requiredProperties) : null);

	Enumeration<String> paramNames = config.getInitParameterNames();
	while (paramNames.hasMoreElements()) {
		String property = paramNames.nextElement();
		Object value = config.getInitParameter(property);
		addPropertyValue(new PropertyValue(property, value));
		if (missingProps != null) {
			missingProps.remove(property);
		}
	}

	// Fail if we are still missing properties.
	if (!CollectionUtils.isEmpty(missingProps)) {
		throw new ServletException(
				"Initialization from ServletConfig for servlet '" + config.getServletName() +
				"' failed; the following required properties were missing: " +
				StringUtils.collectionToDelimitedString(missingProps, ", "));
	}
}
 
Example #8
Source File: ServletRequestDataBinderTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Must contain: forname=Tony surname=Blair age=50
 */
protected void doTestTony(PropertyValues pvs) throws Exception {
	assertTrue("Contains 3", pvs.getPropertyValues().length == 3);
	assertTrue("Contains forname", pvs.contains("forname"));
	assertTrue("Contains surname", pvs.contains("surname"));
	assertTrue("Contains age", pvs.contains("age"));
	assertTrue("Doesn't contain tory", !pvs.contains("tory"));

	PropertyValue[] ps = pvs.getPropertyValues();
	Map<String, String> m = new HashMap<String, String>();
	m.put("forname", "Tony");
	m.put("surname", "Blair");
	m.put("age", "50");
	for (int i = 0; i < ps.length; i++) {
		Object val = m.get(ps[i].getName());
		assertTrue("Can't have unexpected value", val != null);
		assertTrue("Val i string", val instanceof String);
		assertTrue("val matches expected", val.equals(ps[i].getValue()));
		m.remove(ps[i].getName());
	}
	assertTrue("Map size is 0", m.size() == 0);
}
 
Example #9
Source File: DataBinderFieldAccessTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void nestedBindingWithDefaultConversionNoErrors() throws Exception {
	FieldAccessBean rod = new FieldAccessBean();
	DataBinder binder = new DataBinder(rod, "person");
	assertTrue(binder.isIgnoreUnknownFields());
	binder.initDirectFieldAccess();
	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.addPropertyValue(new PropertyValue("spouse.name", "Kerry"));
	pvs.addPropertyValue(new PropertyValue("spouse.jedi", "on"));

	binder.bind(pvs);
	binder.close();

	assertEquals("Kerry", rod.getSpouse().getName());
	assertTrue((rod.getSpouse()).isJedi());
}
 
Example #10
Source File: DefaultListableBeanFactoryTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testExtensiveCircularReference() {
	DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
	for (int i = 0; i < 1000; i++) {
		MutablePropertyValues pvs = new MutablePropertyValues();
		pvs.addPropertyValue(new PropertyValue("spouse", new RuntimeBeanReference("bean" + (i < 99 ? i + 1 : 0))));
		RootBeanDefinition bd = new RootBeanDefinition(TestBean.class);
		bd.setPropertyValues(pvs);
		lbf.registerBeanDefinition("bean" + i, bd);
	}
	lbf.preInstantiateSingletons();
	for (int i = 0; i < 1000; i++) {
		TestBean bean = (TestBean) lbf.getBean("bean" + i);
		TestBean otherBean = (TestBean) lbf.getBean("bean" + (i < 99 ? i + 1 : 0));
		assertTrue(bean.getSpouse() == otherBean);
	}
}
 
Example #11
Source File: CustomEditorTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testComplexObject() {
	TestBean tb = new TestBean();
	String newName = "Rod";
	String tbString = "Kerry_34";

	BeanWrapper bw = new BeanWrapperImpl(tb);
	bw.registerCustomEditor(ITestBean.class, new TestBeanEditor());
	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.addPropertyValue(new PropertyValue("age", new Integer(55)));
	pvs.addPropertyValue(new PropertyValue("name", newName));
	pvs.addPropertyValue(new PropertyValue("touchy", "valid"));
	pvs.addPropertyValue(new PropertyValue("spouse", tbString));
	bw.setPropertyValues(pvs);
	assertTrue("spouse is non-null", tb.getSpouse() != null);
	assertTrue("spouse name is Kerry and age is 34",
			tb.getSpouse().getName().equals("Kerry") && tb.getSpouse().getAge() == 34);
}
 
Example #12
Source File: CustomEditorTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testComplexObjectWithOldValueAccess() {
	TestBean tb = new TestBean();
	String newName = "Rod";
	String tbString = "Kerry_34";

	BeanWrapper bw = new BeanWrapperImpl(tb);
	bw.setExtractOldValueForEditor(true);
	bw.registerCustomEditor(ITestBean.class, new OldValueAccessingTestBeanEditor());
	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.addPropertyValue(new PropertyValue("age", new Integer(55)));
	pvs.addPropertyValue(new PropertyValue("name", newName));
	pvs.addPropertyValue(new PropertyValue("touchy", "valid"));
	pvs.addPropertyValue(new PropertyValue("spouse", tbString));

	bw.setPropertyValues(pvs);
	assertTrue("spouse is non-null", tb.getSpouse() != null);
	assertTrue("spouse name is Kerry and age is 34",
			tb.getSpouse().getName().equals("Kerry") && tb.getSpouse().getAge() == 34);
	ITestBean spouse = tb.getSpouse();

	bw.setPropertyValues(pvs);
	assertSame("Should have remained same object", spouse, tb.getSpouse());
}
 
Example #13
Source File: DictionaryBeanFactoryPostProcessor.java    From rice with Educational Community License v2.0 6 votes vote down vote up
/**
 * Iterates through the properties defined for the bean definition and invokes helper methods to process
 * the property value
 *
 * @param beanDefinition bean definition whose properties will be processed
 * @param nestedBeanStack stack of beans which contain the given bean
 */
protected void processBeanProperties(BeanDefinition beanDefinition, Stack<BeanDefinitionHolder> nestedBeanStack) {
    // iterate through properties and check for any configured message keys within the value
    MutablePropertyValues pvs = beanDefinition.getPropertyValues();
    PropertyValue[] pvArray = pvs.getPropertyValues();
    for (PropertyValue pv : pvArray) {
        Object newPropertyValue = null;
        if (isStringValue(pv.getValue())) {
            newPropertyValue = processStringPropertyValue(pv.getName(), getString(pv.getValue()), nestedBeanStack);
        } else {
            newPropertyValue = visitPropertyValue(pv.getName(), pv.getValue(), nestedBeanStack);
        }

        pvs.removePropertyValue(pv.getName());
        pvs.addPropertyValue(pv.getName(), newPropertyValue);
    }
}
 
Example #14
Source File: DefaultListableBeanFactoryTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testExtensiveCircularReference() {
	DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
	for (int i = 0; i < 1000; i++) {
		MutablePropertyValues pvs = new MutablePropertyValues();
		pvs.addPropertyValue(new PropertyValue("spouse", new RuntimeBeanReference("bean" + (i < 99 ? i + 1 : 0))));
		RootBeanDefinition bd = new RootBeanDefinition(TestBean.class);
		bd.setPropertyValues(pvs);
		lbf.registerBeanDefinition("bean" + i, bd);
	}
	lbf.preInstantiateSingletons();
	for (int i = 0; i < 1000; i++) {
		TestBean bean = (TestBean) lbf.getBean("bean" + i);
		TestBean otherBean = (TestBean) lbf.getBean("bean" + (i < 99 ? i + 1 : 0));
		assertTrue(bean.getSpouse() == otherBean);
	}
}
 
Example #15
Source File: SnakeToCamelRequestDataBinder.java    From softservice with MIT License 6 votes vote down vote up
protected void addBindValues(MutablePropertyValues mpvs, ServletRequest request) {
    super.addBindValues(mpvs, request);

    //处理JsonProperty注释的对象
    Class<?> targetClass = getTarget().getClass();
    Field[] fields = targetClass.getDeclaredFields();
    for (Field field : fields) {
        JsonProperty jsonPropertyAnnotation = field.getAnnotation(JsonProperty.class);
        if (jsonPropertyAnnotation != null && mpvs.contains(jsonPropertyAnnotation.value())) {
            if (!mpvs.contains(field.getName())) {
                mpvs.add(field.getName(), mpvs.getPropertyValue(jsonPropertyAnnotation.value()).getValue());
            }
        }
    }

    List<PropertyValue> covertValues = new ArrayList<PropertyValue>();
    for (PropertyValue propertyValue : mpvs.getPropertyValueList()) {
        if(propertyValue.getName().contains("_")) {
            String camelName = SnakeToCamelRequestParameterUtil.convertSnakeToCamel(propertyValue.getName());
            if (!mpvs.contains(camelName)) {
                covertValues.add(new PropertyValue(camelName, propertyValue.getValue()));
            }
        }
    }
    mpvs.getPropertyValueList().addAll(covertValues);
}
 
Example #16
Source File: WebDataBinder.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Check the given property values for field markers,
 * i.e. for fields that start with the field marker prefix.
 * <p>The existence of a field marker indicates that the specified
 * field existed in the form. If the property values do not contain
 * a corresponding field value, the field will be considered as empty
 * and will be reset appropriately.
 * @param mpvs the property values to be bound (can be modified)
 * @see #getFieldMarkerPrefix
 * @see #getEmptyValue(String, Class)
 */
protected void checkFieldMarkers(MutablePropertyValues mpvs) {
	if (getFieldMarkerPrefix() != null) {
		String fieldMarkerPrefix = getFieldMarkerPrefix();
		PropertyValue[] pvArray = mpvs.getPropertyValues();
		for (PropertyValue pv : pvArray) {
			if (pv.getName().startsWith(fieldMarkerPrefix)) {
				String field = pv.getName().substring(fieldMarkerPrefix.length());
				if (getPropertyAccessor().isWritableProperty(field) && !mpvs.contains(field)) {
					Class<?> fieldType = getPropertyAccessor().getPropertyType(field);
					mpvs.add(field, getEmptyValue(field, fieldType));
				}
				mpvs.removePropertyValue(pv);
			}
		}
	}
}
 
Example #17
Source File: CustomEditorTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testComplexObject() {
	TestBean tb = new TestBean();
	String newName = "Rod";
	String tbString = "Kerry_34";

	BeanWrapper bw = new BeanWrapperImpl(tb);
	bw.registerCustomEditor(ITestBean.class, new TestBeanEditor());
	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.addPropertyValue(new PropertyValue("age", new Integer(55)));
	pvs.addPropertyValue(new PropertyValue("name", newName));
	pvs.addPropertyValue(new PropertyValue("touchy", "valid"));
	pvs.addPropertyValue(new PropertyValue("spouse", tbString));
	bw.setPropertyValues(pvs);
	assertTrue("spouse is non-null", tb.getSpouse() != null);
	assertTrue("spouse name is Kerry and age is 34",
			tb.getSpouse().getName().equals("Kerry") && tb.getSpouse().getAge() == 34);
}
 
Example #18
Source File: BeanComponentDefinition.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Create a new BeanComponentDefinition for the given bean.
 * @param beanDefinitionHolder the BeanDefinitionHolder encapsulating
 * the bean definition as well as the name of the bean
 */
public BeanComponentDefinition(BeanDefinitionHolder beanDefinitionHolder) {
	super(beanDefinitionHolder);

	List<BeanDefinition> innerBeans = new ArrayList<>();
	List<BeanReference> references = new ArrayList<>();
	PropertyValues propertyValues = beanDefinitionHolder.getBeanDefinition().getPropertyValues();
	for (PropertyValue propertyValue : propertyValues.getPropertyValues()) {
		Object value = propertyValue.getValue();
		if (value instanceof BeanDefinitionHolder) {
			innerBeans.add(((BeanDefinitionHolder) value).getBeanDefinition());
		}
		else if (value instanceof BeanDefinition) {
			innerBeans.add((BeanDefinition) value);
		}
		else if (value instanceof BeanReference) {
			references.add((BeanReference) value);
		}
	}
	this.innerBeanDefinitions = innerBeans.toArray(new BeanDefinition[0]);
	this.beanReferences = references.toArray(new BeanReference[0]);
}
 
Example #19
Source File: BeanDefinitionParserDelegate.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Parse a property element.
 */
public void parsePropertyElement(Element ele, BeanDefinition bd) {
	String propertyName = ele.getAttribute(NAME_ATTRIBUTE);
	if (!StringUtils.hasLength(propertyName)) {
		error("Tag 'property' must have a 'name' attribute", ele);
		return;
	}
	this.parseState.push(new PropertyEntry(propertyName));
	try {
		if (bd.getPropertyValues().contains(propertyName)) {
			error("Multiple 'property' definitions for property '" + propertyName + "'", ele);
			return;
		}
		Object val = parsePropertyValue(ele, bd, propertyName);
		PropertyValue pv = new PropertyValue(propertyName, val);
		parseMetaElements(ele, pv);
		pv.setSource(extractSource(ele));
		bd.getPropertyValues().addPropertyValue(pv);
	}
	finally {
		this.parseState.pop();
	}
}
 
Example #20
Source File: DataBinderFieldAccessTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void bindingNoErrors() throws Exception {
	FieldAccessBean rod = new FieldAccessBean();
	DataBinder binder = new DataBinder(rod, "person");
	assertTrue(binder.isIgnoreUnknownFields());
	binder.initDirectFieldAccess();
	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.addPropertyValue(new PropertyValue("name", "Rod"));
	pvs.addPropertyValue(new PropertyValue("age", new Integer(32)));
	pvs.addPropertyValue(new PropertyValue("nonExisting", "someValue"));

	binder.bind(pvs);
	binder.close();

	assertTrue("changed name correctly", rod.getName().equals("Rod"));
	assertTrue("changed age correctly", rod.getAge() == 32);

	Map<?, ?> m = binder.getBindingResult().getModel();
	assertTrue("There is one element in map", m.size() == 2);
	FieldAccessBean tb = (FieldAccessBean) m.get("person");
	assertTrue("Same object", tb.equals(rod));
}
 
Example #21
Source File: ServletRequestDataBinderTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Must contain: forname=Tony surname=Blair age=50
 */
protected void doTestTony(PropertyValues pvs) throws Exception {
	assertTrue("Contains 3", pvs.getPropertyValues().length == 3);
	assertTrue("Contains forname", pvs.contains("forname"));
	assertTrue("Contains surname", pvs.contains("surname"));
	assertTrue("Contains age", pvs.contains("age"));
	assertTrue("Doesn't contain tory", !pvs.contains("tory"));

	PropertyValue[] ps = pvs.getPropertyValues();
	Map<String, String> m = new HashMap<>();
	m.put("forname", "Tony");
	m.put("surname", "Blair");
	m.put("age", "50");
	for (int i = 0; i < ps.length; i++) {
		Object val = m.get(ps[i].getName());
		assertTrue("Can't have unexpected value", val != null);
		assertTrue("Val i string", val instanceof String);
		assertTrue("val matches expected", val.equals(ps[i].getValue()));
		m.remove(ps[i].getName());
	}
	assertTrue("Map size is 0", m.size() == 0);
}
 
Example #22
Source File: MapperScannerConfigurer.java    From Mapper with MIT License 6 votes vote down vote up
private String updatePropertyValue(String propertyName, PropertyValues values) {
    PropertyValue property = values.getPropertyValue(propertyName);

    if (property == null) {
        return null;
    }

    Object value = property.getValue();

    if (value == null) {
        return null;
    } else if (value instanceof String) {
        return value.toString();
    } else if (value instanceof TypedStringValue) {
        return ((TypedStringValue) value).getValue();
    } else {
        return null;
    }
}
 
Example #23
Source File: GenericFilterBean.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Create new FilterConfigPropertyValues.
 * @param config FilterConfig we'll use to take PropertyValues from
 * @param requiredProperties set of property names we need, where
 * we can't accept default values
 * @throws ServletException if any required properties are missing
 */
public FilterConfigPropertyValues(FilterConfig config, Set<String> requiredProperties)
	throws ServletException {

	Set<String> missingProps = (requiredProperties != null && !requiredProperties.isEmpty()) ?
			new HashSet<String>(requiredProperties) : null;

	Enumeration<?> en = config.getInitParameterNames();
	while (en.hasMoreElements()) {
		String property = (String) en.nextElement();
		Object value = config.getInitParameter(property);
		addPropertyValue(new PropertyValue(property, value));
		if (missingProps != null) {
			missingProps.remove(property);
		}
	}

	// Fail if we are still missing properties.
	if (missingProps != null && missingProps.size() > 0) {
		throw new ServletException(
			"Initialization from FilterConfig for filter '" + config.getFilterName() +
			"' failed; the following required properties were missing: " +
			StringUtils.collectionToDelimitedString(missingProps, ", "));
	}
}
 
Example #24
Source File: DataBinderFieldAccessTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void bindingNoErrors() throws Exception {
	FieldAccessBean rod = new FieldAccessBean();
	DataBinder binder = new DataBinder(rod, "person");
	assertTrue(binder.isIgnoreUnknownFields());
	binder.initDirectFieldAccess();
	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.addPropertyValue(new PropertyValue("name", "Rod"));
	pvs.addPropertyValue(new PropertyValue("age", new Integer(32)));
	pvs.addPropertyValue(new PropertyValue("nonExisting", "someValue"));

	binder.bind(pvs);
	binder.close();

	assertTrue("changed name correctly", rod.getName().equals("Rod"));
	assertTrue("changed age correctly", rod.getAge() == 32);

	Map<?, ?> m = binder.getBindingResult().getModel();
	assertTrue("There is one element in map", m.size() == 2);
	FieldAccessBean tb = (FieldAccessBean) m.get("person");
	assertTrue("Same object", tb.equals(rod));
}
 
Example #25
Source File: AspectJAutoProxyCreatorTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testAspectsAndAdvisorAreAppliedEvenIfComingFromParentFactory() {
	ClassPathXmlApplicationContext ac = newContext("aspectsPlusAdvisor.xml");

	GenericApplicationContext childAc = new GenericApplicationContext(ac);
	// Create a child factory with a bean that should be woven
	RootBeanDefinition bd = new RootBeanDefinition(TestBean.class);
	bd.getPropertyValues().addPropertyValue(new PropertyValue("name", "Adrian"))
			.addPropertyValue(new PropertyValue("age", 34));
	childAc.registerBeanDefinition("adrian2", bd);
	// Register the advisor auto proxy creator with subclass
	childAc.registerBeanDefinition(AnnotationAwareAspectJAutoProxyCreator.class.getName(), new RootBeanDefinition(
			AnnotationAwareAspectJAutoProxyCreator.class));
	childAc.refresh();

	ITestBean beanFromChildContextThatShouldBeWeaved = (ITestBean) childAc.getBean("adrian2");
	//testAspectsAndAdvisorAreApplied(childAc, (ITestBean) ac.getBean("adrian"));
	doTestAspectsAndAdvisorAreApplied(childAc, beanFromChildContextThatShouldBeWeaved);
}
 
Example #26
Source File: HttpServletBean.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Create new ServletConfigPropertyValues.
 * @param config the ServletConfig we'll use to take PropertyValues from
 * @param requiredProperties set of property names we need, where
 * we can't accept default values
 * @throws ServletException if any required properties are missing
 */
public ServletConfigPropertyValues(ServletConfig config, Set<String> requiredProperties)
		throws ServletException {

	Set<String> missingProps = (!CollectionUtils.isEmpty(requiredProperties) ?
			new HashSet<>(requiredProperties) : null);

	Enumeration<String> paramNames = config.getInitParameterNames();
	while (paramNames.hasMoreElements()) {
		String property = paramNames.nextElement();
		Object value = config.getInitParameter(property);
		addPropertyValue(new PropertyValue(property, value));
		if (missingProps != null) {
			missingProps.remove(property);
		}
	}

	// Fail if we are still missing properties.
	if (!CollectionUtils.isEmpty(missingProps)) {
		throw new ServletException(
				"Initialization from ServletConfig for servlet '" + config.getServletName() +
				"' failed; the following required properties were missing: " +
				StringUtils.collectionToDelimitedString(missingProps, ", "));
	}
}
 
Example #27
Source File: CustomEditorTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testComplexObject() {
	TestBean tb = new TestBean();
	String newName = "Rod";
	String tbString = "Kerry_34";

	BeanWrapper bw = new BeanWrapperImpl(tb);
	bw.registerCustomEditor(ITestBean.class, new TestBeanEditor());
	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.addPropertyValue(new PropertyValue("age", new Integer(55)));
	pvs.addPropertyValue(new PropertyValue("name", newName));
	pvs.addPropertyValue(new PropertyValue("touchy", "valid"));
	pvs.addPropertyValue(new PropertyValue("spouse", tbString));
	bw.setPropertyValues(pvs);
	assertTrue("spouse is non-null", tb.getSpouse() != null);
	assertTrue("spouse name is Kerry and age is 34",
			tb.getSpouse().getName().equals("Kerry") && tb.getSpouse().getAge() == 34);
}
 
Example #28
Source File: BeanDefinitionParserDelegate.java    From blog_demos with Apache License 2.0 6 votes vote down vote up
/**
 * Parse a property element.
 */
public void parsePropertyElement(Element ele, BeanDefinition bd) {
	String propertyName = ele.getAttribute(NAME_ATTRIBUTE);
	if (!StringUtils.hasLength(propertyName)) {
		error("Tag 'property' must have a 'name' attribute", ele);
		return;
	}
	this.parseState.push(new PropertyEntry(propertyName));
	try {
		if (bd.getPropertyValues().contains(propertyName)) {
			error("Multiple 'property' definitions for property '" + propertyName + "'", ele);
			return;
		}
		Object val = parsePropertyValue(ele, bd, propertyName);
		PropertyValue pv = new PropertyValue(propertyName, val);
		parseMetaElements(ele, pv);
		pv.setSource(extractSource(ele));
		bd.getPropertyValues().addPropertyValue(pv);
	}
	finally {
		this.parseState.pop();
	}
}
 
Example #29
Source File: WebDataBinder.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Check the given property values for field markers,
 * i.e. for fields that start with the field marker prefix.
 * <p>The existence of a field marker indicates that the specified
 * field existed in the form. If the property values do not contain
 * a corresponding field value, the field will be considered as empty
 * and will be reset appropriately.
 * @param mpvs the property values to be bound (can be modified)
 * @see #getFieldMarkerPrefix
 * @see #getEmptyValue(String, Class)
 */
protected void checkFieldMarkers(MutablePropertyValues mpvs) {
	String fieldMarkerPrefix = getFieldMarkerPrefix();
	if (fieldMarkerPrefix != null) {
		PropertyValue[] pvArray = mpvs.getPropertyValues();
		for (PropertyValue pv : pvArray) {
			if (pv.getName().startsWith(fieldMarkerPrefix)) {
				String field = pv.getName().substring(fieldMarkerPrefix.length());
				if (getPropertyAccessor().isWritableProperty(field) && !mpvs.contains(field)) {
					Class<?> fieldType = getPropertyAccessor().getPropertyType(field);
					mpvs.add(field, getEmptyValue(field, fieldType));
				}
				mpvs.removePropertyValue(pv);
			}
		}
	}
}
 
Example #30
Source File: BeanComponentDefinition.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
private void findInnerBeanDefinitionsAndBeanReferences(BeanDefinition beanDefinition) {
	List<BeanDefinition> innerBeans = new ArrayList<BeanDefinition>();
	List<BeanReference> references = new ArrayList<BeanReference>();
	PropertyValues propertyValues = beanDefinition.getPropertyValues();
	for (int i = 0; i < propertyValues.getPropertyValues().length; i++) {
		PropertyValue propertyValue = propertyValues.getPropertyValues()[i];
		Object value = propertyValue.getValue();
		if (value instanceof BeanDefinitionHolder) {
			innerBeans.add(((BeanDefinitionHolder) value).getBeanDefinition());
		}
		else if (value instanceof BeanDefinition) {
			innerBeans.add((BeanDefinition) value);
		}
		else if (value instanceof BeanReference) {
			references.add((BeanReference) value);
		}
	}
	this.innerBeanDefinitions = innerBeans.toArray(new BeanDefinition[innerBeans.size()]);
	this.beanReferences = references.toArray(new BeanReference[references.size()]);
}