public void testStringArrayProperty() throws Exception { PropsTest pt = new PropsTest(); BeanWrapper bw = new BeanWrapperImpl(pt); bw.setPropertyValue("stringArray", "foo,fi,fi,fum"); assertTrue("stringArray length = 4", pt.stringArray.length == 4); assertTrue( "correct values", pt.stringArray[0].equals("foo") && pt.stringArray[1].equals("fi") && pt.stringArray[2].equals("fi") && pt.stringArray[3].equals("fum")); bw.setPropertyValue("stringArray", new String[] {"foo", "fi", "fi", "fum"}); assertTrue("stringArray length = 4", pt.stringArray.length == 4); assertTrue( "correct values", pt.stringArray[0].equals("foo") && pt.stringArray[1].equals("fi") && pt.stringArray[2].equals("fi") && pt.stringArray[3].equals("fum")); bw.setPropertyValue("stringArray", "one"); assertTrue("stringArray length = 1", pt.stringArray.length == 1); assertTrue("stringArray elt is ok", pt.stringArray[0].equals("one")); }
/** Return the indexes available for this field (for repeated fields ad List) */ public List<Integer> indexes() { List<Integer> result = new ArrayList<Integer>(); if (form.value().isDefined()) { BeanWrapper beanWrapper = new BeanWrapperImpl(form.value().get()); beanWrapper.setAutoGrowNestedPaths(true); String objectKey = name; if (form.name() != null && name.startsWith(form.name() + ".")) { objectKey = name.substring(form.name().length() + 1); } if (beanWrapper.isReadableProperty(objectKey)) { Object value = beanWrapper.getPropertyValue(objectKey); if (value instanceof Collection) { for (int i = 0; i < ((Collection) value).size(); i++) { result.add(i); } } } } else { java.util.regex.Pattern pattern = java.util.regex.Pattern.compile( "^" + java.util.regex.Pattern.quote(name) + "\\[(\\d+)\\].*$"); for (String key : form.data().keySet()) { java.util.regex.Matcher matcher = pattern.matcher(key); if (matcher.matches()) { result.add(Integer.parseInt(matcher.group(1))); } } } return result; }
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 testPrimitiveArray() { PrimitiveArrayBean tb = new PrimitiveArrayBean(); BeanWrapper bw = new BeanWrapperImpl(tb); bw.setPropertyValue("array", new String[] {"1", "2"}); assertEquals(2, tb.getArray().length); assertEquals(1, tb.getArray()[0]); assertEquals(2, tb.getArray()[1]); }
public void testSetWrappedInstanceOfDifferentClass() throws Exception { ThrowsException tex = new ThrowsException(); BeanWrapper bw = new BeanWrapperImpl(tex); TestBean tb2 = new TestBean(); bw.setWrappedInstance(tb2); bw.setPropertyValue("age", new Integer(14)); assertTrue("2nd changed", tb2.getAge() == 14); }
public void testIsWritablePropertyNull() { NoRead nr = new NoRead(); BeanWrapper bw = new BeanWrapperImpl(nr); try { bw.isWritableProperty(null); fail("Can't inquire into writability of null property"); } catch (BeansException ex) { // expected } }
public void testNestedProperties() { String doctorCompany = ""; String lawyerCompany = "Dr. Sueem"; TestBean tb = new TestBean(); BeanWrapper bw = new BeanWrapperImpl(tb); bw.setPropertyValue("doctor.company", doctorCompany); bw.setPropertyValue("lawyer.company", lawyerCompany); assertEquals(doctorCompany, tb.getDoctor().getCompany()); assertEquals(lawyerCompany, tb.getLawyer().getCompany()); }
public void testSetWrappedInstanceOfSameClass() throws Exception { TestBean tb = new TestBean(); BeanWrapper bw = new BeanWrapperImpl(tb); tb.setAge(11); TestBean tb2 = new TestBean(); bw.setWrappedInstance(tb2); bw.setPropertyValue("age", new Integer(14)); assertTrue("2nd changed", tb2.getAge() == 14); assertTrue("1 didn't change", tb.getAge() == 11); }
public void testEmptyValueForPrimitiveProperty() { TestBean t = new TestBean(); try { BeanWrapper bw = new BeanWrapperImpl(t); bw.setPropertyValue("age", ""); fail("Should throw exception on type mismatch"); } catch (TypeMismatchException ex) { // expected } catch (Exception ex) { fail("Shouldn't throw exception other than Type mismatch"); } }
public void testSetNestedPropertyNullValue() throws Exception { ITestBean rod = new TestBean("rod", 31); BeanWrapper bw = new BeanWrapperImpl(rod); try { bw.setPropertyValue("spouse.age", new Integer(31)); fail("Shouldn't have succeded with null path"); } catch (NullValueInNestedPathException ex) { // ok assertTrue( "it was the spouse property that was null, not " + ex.getPropertyName(), ex.getPropertyName().equals("spouse")); } }
public void testArrayToStringConversion() throws PropertyVetoException { TestBean tb = new TestBean(); BeanWrapper bw = new BeanWrapperImpl(tb); bw.registerCustomEditor( String.class, new PropertyEditorSupport() { public void setAsText(String text) throws IllegalArgumentException { setValue("-" + text + "-"); } }); bw.setPropertyValue("name", new String[] {"a", "b"}); assertEquals("-a,b-", tb.getName()); }
public void testValidNullUpdate() { TestBean t = new TestBean(); t.setName("Frank"); // we need to change it back t.setSpouse(t); BeanWrapper bw = new BeanWrapperImpl(t); assertTrue("name is not null to start off", t.getName() != null); bw.setPropertyValue("name", null); assertTrue("name is now null", t.getName() == null); // Now test with non-string assertTrue("spouse is not null to start off", t.getSpouse() != null); bw.setPropertyValue("spouse", null); assertTrue("spouse is now null", t.getSpouse() == null); }
public void testGetNestedProperty() { ITestBean rod = new TestBean("rod", 31); ITestBean kerry = new TestBean("kerry", 35); rod.setSpouse(kerry); kerry.setSpouse(rod); BeanWrapper bw = new BeanWrapperImpl(rod); Integer KA = (Integer) bw.getPropertyValue("spouse.age"); assertTrue("kerry is 35", KA.intValue() == 35); Integer RA = (Integer) bw.getPropertyValue("spouse.spouse.age"); assertTrue("rod is 31, not" + RA, RA.intValue() == 31); ITestBean spousesSpouse = (ITestBean) bw.getPropertyValue("spouse.spouse"); assertTrue("spousesSpouse = initial point", rod == spousesSpouse); }
public boolean updateElement(Object element, String property) { if (!GridListEditor.this.isOn()) return false; final Integer row = (Integer) element; final int col = Integer.parseInt(property); selectedIndex = getElementIndex(row, col); final BeanWrapper bean = beans.get(selectedIndex); setSelectedBean(bean, false); gridTable.refresh(); if (listeners != null) { final BeanSelectionEvent evt = new BeanSelectionEvent(this, selectedIndex, bean.getBean()); for (BeanSelectionListener l : listeners) l.selectionChanged(evt); } return false; }
public void testBeanWrapperUpdates() { TestBean t = new TestBean(); int newAge = 33; try { BeanWrapper bw = new BeanWrapperImpl(t); t.setAge(newAge); Object bwAge = bw.getPropertyValue("age"); assertTrue("Age is an integer", bwAge instanceof Integer); int bwi = ((Integer) bwAge).intValue(); assertTrue("Bean wrapper must pick up changes", bwi == newAge); } catch (Exception ex) { fail("Shouldn't throw exception when everything is valid"); } }
public void testArrayToArrayConversion() throws PropertyVetoException { IndexedTestBean tb = new IndexedTestBean(); BeanWrapper bw = new BeanWrapperImpl(tb); bw.registerCustomEditor( TestBean.class, new PropertyEditorSupport() { public void setAsText(String text) throws IllegalArgumentException { setValue(new TestBean(text, 99)); } }); bw.setPropertyValue("array", new String[] {"a", "b"}); assertEquals(2, tb.getArray().length); assertEquals("a", tb.getArray()[0].getName()); assertEquals("b", tb.getArray()[1].getName()); }
public void testSetNestedProperty() throws Exception { ITestBean rod = new TestBean("rod", 31); ITestBean kerry = new TestBean("kerry", 0); BeanWrapper bw = new BeanWrapperImpl(rod); bw.setPropertyValue("spouse", kerry); assertTrue("nested set worked", rod.getSpouse() == kerry); assertTrue("no back relation", kerry.getSpouse() == null); bw.setPropertyValue(new PropertyValue("spouse.spouse", rod)); assertTrue("nested set worked", kerry.getSpouse() == rod); assertTrue("kerry age not set", kerry.getAge() == 0); bw.setPropertyValue(new PropertyValue("spouse.age", new Integer(35))); assertTrue("Set primitive on spouse", kerry.getAge() == 35); }
/** Test default conversion of properties */ public void testPropertiesProperty() throws Exception { PropsTest pt = new PropsTest(); BeanWrapper bw = new BeanWrapperImpl(pt); bw.setPropertyValue("name", "ptest"); // Note format... String ps = "peace=war\nfreedom=slavery"; bw.setPropertyValue("properties", ps); assertTrue("name was set", pt.name.equals("ptest")); assertTrue("props non null", pt.props != null); String freedomVal = pt.props.getProperty("freedom"); String peaceVal = pt.props.getProperty("peace"); assertTrue("peace==war", peaceVal.equals("war")); assertTrue("Freedom==slavery", freedomVal.equals("slavery")); }
public void testNewWrappedInstancePropertyValuesGet() { BeanWrapper bw = new BeanWrapperImpl(); TestBean t = new TestBean("Tony", 50); bw.setWrappedInstance(t); assertEquals( "Bean wrapper returns wrong property value", new Integer(t.getAge()), bw.getPropertyValue("age")); TestBean u = new TestBean("Udo", 30); bw.setWrappedInstance(u); assertEquals( "Bean wrapper returns cached property value", new Integer(u.getAge()), bw.getPropertyValue("age")); }
public void testIndividualAllValid() { TestBean t = new TestBean(); String newName = "tony"; int newAge = 65; String newTouchy = "valid"; try { BeanWrapper bw = new BeanWrapperImpl(t); bw.setPropertyValue("age", new Integer(newAge)); bw.setPropertyValue(new PropertyValue("name", newName)); bw.setPropertyValue(new PropertyValue("touchy", newTouchy)); 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"); } }
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?? } }
public void testEmptyPropertyValuesSet() { TestBean t = new TestBean(); int age = 50; String name = "Tony"; t.setAge(age); t.setName(name); try { BeanWrapper bw = new BeanWrapperImpl(t); assertTrue("age is OK", t.getAge() == age); assertTrue("name is OK", name.equals(t.getName())); bw.setPropertyValues(new MutablePropertyValues()); // Check its unchanged assertTrue("age is OK", t.getAge() == age); assertTrue("name is OK", name.equals(t.getName())); } catch (BeansException ex) { fail("Shouldn't throw exception when everything is valid"); } }
/** * Extract the values for all attributes in the struct. * * <p>Utilizes public setters and result set metadata. * * @see java.sql.ResultSetMetaData */ public Object fromStruct(STRUCT struct) throws SQLException { Assert.state(this.mappedClass != null, "Mapped class was not specified"); Object mappedObject = BeanUtils.instantiateClass(this.mappedClass); BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(mappedObject); initBeanWrapper(bw); ResultSetMetaData rsmd = struct.getDescriptor().getMetaData(); Object[] attr = struct.getAttributes(); int columnCount = rsmd.getColumnCount(); for (int index = 1; index <= columnCount; index++) { String column = JdbcUtils.lookupColumnName(rsmd, index).toLowerCase(); PropertyDescriptor pd = (PropertyDescriptor) this.mappedFields.get(column); if (pd != null) { Object value = attr[index - 1]; if (logger.isDebugEnabled()) { logger.debug( "Mapping column '" + column + "' to property '" + pd.getName() + "' of type " + pd.getPropertyType()); } if (bw.isWritableProperty(pd.getName())) { try { bw.setPropertyValue(pd.getName(), value); } catch (Exception e) { e.printStackTrace(); } } else { // Если нету сеттера для проперти не нужно кидать ошибку! logger.warn( "Unable to access the setter for " + pd.getName() + ". Check that " + "set" + StringUtils.capitalize(pd.getName()) + " is declared and has public access."); } } } return mappedObject; }
public void testNewWrappedInstanceNestedPropertyValuesGet() { BeanWrapper bw = new BeanWrapperImpl(); TestBean t = new TestBean("Tony", 50); t.setSpouse(new TestBean("Sue", 40)); bw.setWrappedInstance(t); assertEquals( "Bean wrapper returns wrong nested property value", new Integer(t.getSpouse().getAge()), bw.getPropertyValue("spouse.age")); TestBean u = new TestBean("Udo", 30); u.setSpouse(new TestBean("Vera", 20)); bw.setWrappedInstance(u); assertEquals( "Bean wrapper returns cached nested property value", new Integer(u.getSpouse().getAge()), bw.getPropertyValue("spouse.age")); }
@Test public void acceptAndClearClassLoader() throws Exception { BeanWrapper bw = new BeanWrapperImpl(TestBean.class); assertTrue(bw.isWritableProperty("name")); assertTrue(bw.isWritableProperty("age")); assertTrue(CachedIntrospectionResults.strongClassCache.containsKey(TestBean.class)); ClassLoader child = new OverridingClassLoader(getClass().getClassLoader()); Class<?> tbClass = child.loadClass("org.springframework.tests.sample.beans.TestBean"); assertFalse(CachedIntrospectionResults.strongClassCache.containsKey(tbClass)); CachedIntrospectionResults.acceptClassLoader(child); bw = new BeanWrapperImpl(tbClass); assertTrue(bw.isWritableProperty("name")); assertTrue(bw.isWritableProperty("age")); assertTrue(CachedIntrospectionResults.strongClassCache.containsKey(tbClass)); CachedIntrospectionResults.clearClassLoader(child); assertFalse(CachedIntrospectionResults.strongClassCache.containsKey(tbClass)); assertTrue(CachedIntrospectionResults.strongClassCache.containsKey(TestBean.class)); }
@Override public void setValue(Object value) { final List<?> obs = (List<?>) value; this.clear(); for (int i = 0; i < obs.size(); i++) { final Object bean = obs.get(i); final BeanWrapper wrapper = new BeanWrapper(bean); wrapper.setName(i + ""); beans.add(wrapper); } if (!beans.isEmpty()) { selectedIndex = 0; setSelectedBean(beans.get(0), false); } if (gridTable != null) gridTable.refresh(); updateEditingUIVisibility(); notifyValueListeners(); }
public STRUCT toStruct(Object object, Connection conn, String typeName) throws SQLException { StructDescriptor descriptor = new StructDescriptor(typeName, conn); ResultSetMetaData rsmd = descriptor.getMetaData(); int columns = rsmd.getColumnCount(); Object[] values = new Object[columns]; for (int i = 1; i <= columns; i++) { String column = JdbcUtils.lookupColumnName(rsmd, i).toLowerCase(); PropertyDescriptor fieldMeta = (PropertyDescriptor) this.mappedFields.get(column); if (fieldMeta != null) { BeanWrapper bw = new BeanWrapperImpl(object); if (bw.isReadableProperty(fieldMeta.getName())) { try { if (logger.isDebugEnabled()) { logger.debug( "Mapping column named \"" + column + "\"" + " to property \"" + fieldMeta.getName() + "\""); } values[i - 1] = bw.getPropertyValue(fieldMeta.getName()); } catch (NotReadablePropertyException ex) { throw new DataRetrievalFailureException( "Unable to map column " + column + " to property " + fieldMeta.getName(), ex); } } else { logger.warn( "Unable to access the getter for " + fieldMeta.getName() + ". Check that " + "get" + StringUtils.capitalize(fieldMeta.getName()) + " is declared and has public access."); } } } STRUCT struct = new STRUCT(descriptor, conn, values); return struct; }
public void testIntArrayProperty() { PropsTest pt = new PropsTest(); BeanWrapper bw = new BeanWrapperImpl(pt); bw.setPropertyValue("intArray", new int[] {4, 5, 2, 3}); assertTrue("intArray length = 4", pt.intArray.length == 4); assertTrue( "correct values", pt.intArray[0] == 4 && pt.intArray[1] == 5 && pt.intArray[2] == 2 && pt.intArray[3] == 3); bw.setPropertyValue("intArray", new String[] {"4", "5", "2", "3"}); assertTrue("intArray length = 4", pt.intArray.length == 4); assertTrue( "correct values", pt.intArray[0] == 4 && pt.intArray[1] == 5 && pt.intArray[2] == 2 && pt.intArray[3] == 3); bw.setPropertyValue("intArray", new Integer(1)); assertTrue("intArray length = 4", pt.intArray.length == 1); assertTrue("correct values", pt.intArray[0] == 1); bw.setPropertyValue("intArray", new String[] {"1"}); assertTrue("intArray length = 4", pt.intArray.length == 1); assertTrue("correct values", pt.intArray[0] == 1); }
public void testSetNestedPropertyPolymorphic() throws Exception { ITestBean rod = new TestBean("rod", 31); ITestBean kerry = new Employee(); BeanWrapper bw = new BeanWrapperImpl(rod); bw.setPropertyValue("spouse", kerry); bw.setPropertyValue("spouse.age", new Integer(35)); bw.setPropertyValue("spouse.name", "Kerry"); bw.setPropertyValue("spouse.company", "Lewisham"); assertTrue("kerry name is Kerry", kerry.getName().equals("Kerry")); assertTrue("nested set worked", rod.getSpouse() == kerry); assertTrue("no back relation", kerry.getSpouse() == null); bw.setPropertyValue(new PropertyValue("spouse.spouse", rod)); assertTrue("nested set worked", kerry.getSpouse() == rod); BeanWrapper kbw = new BeanWrapperImpl(kerry); assertTrue( "spouse.spouse.spouse.spouse.company=Lewisham", "Lewisham".equals(kbw.getPropertyValue("spouse.spouse.spouse.spouse.company"))); }
/** * Retrieve a field. * * @param key field name * @return the field (even if the field does not exist you get a field) */ public Field field(String key) { // Value String fieldValue = null; if (data.containsKey(key)) { fieldValue = data.get(key); } else { if (value.isPresent()) { BeanWrapper beanWrapper = new BeanWrapperImpl(value.get()); beanWrapper.setAutoGrowNestedPaths(true); String objectKey = key; if (rootName != null && key.startsWith(rootName + ".")) { objectKey = key.substring(rootName.length() + 1); } if (beanWrapper.isReadableProperty(objectKey)) { Object oValue = beanWrapper.getPropertyValue(objectKey); if (oValue != null) { final String objectKeyFinal = objectKey; fieldValue = withRequestLocale( () -> formatters.print( beanWrapper.getPropertyTypeDescriptor(objectKeyFinal), oValue)); } } } } // Error List<ValidationError> fieldErrors = errors.get(key); if (fieldErrors == null) { fieldErrors = new ArrayList<>(); } // Format Tuple<String, List<Object>> format = null; BeanWrapper beanWrapper = new BeanWrapperImpl(blankInstance()); beanWrapper.setAutoGrowNestedPaths(true); try { for (Annotation a : beanWrapper.getPropertyTypeDescriptor(key).getAnnotations()) { Class<?> annotationType = a.annotationType(); if (annotationType.isAnnotationPresent(play.data.Form.Display.class)) { play.data.Form.Display d = annotationType.getAnnotation(play.data.Form.Display.class); if (d.name().startsWith("format.")) { List<Object> attributes = new ArrayList<>(); for (String attr : d.attributes()) { Object attrValue = null; try { attrValue = a.getClass().getDeclaredMethod(attr).invoke(a); } catch (Exception e) { // do nothing } attributes.add(attrValue); } format = Tuple(d.name(), attributes); } } } } catch (NullPointerException e) { // do nothing } // Constraints List<Tuple<String, List<Object>>> constraints = new ArrayList<>(); Class<?> classType = backedType; String leafKey = key; if (rootName != null && leafKey.startsWith(rootName + ".")) { leafKey = leafKey.substring(rootName.length() + 1); } int p = leafKey.lastIndexOf('.'); if (p > 0) { classType = beanWrapper.getPropertyType(leafKey.substring(0, p)); leafKey = leafKey.substring(p + 1); } if (classType != null) { BeanDescriptor beanDescriptor = play.data.validation.Validation.getValidator().getConstraintsForClass(classType); if (beanDescriptor != null) { PropertyDescriptor property = beanDescriptor.getConstraintsForProperty(leafKey); if (property != null) { constraints = Constraints.displayableConstraint(property.getConstraintDescriptors()); } } } return new Field(this, key, constraints, format, fieldErrors, fieldValue); }