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 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"));
  }
Пример #3
0
 /** 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 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 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"));
  }
 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 testGetNestedPropertyNullValue() throws Exception {
    ITestBean rod = new TestBean("rod", 31);
    ITestBean kerry = new TestBean("kerry", 35);
    rod.setSpouse(kerry);

    BeanWrapper bw = new BeanWrapperImpl(rod);
    try {
      bw.getPropertyValue("spouse.spouse.age");
      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 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")));
  }
 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;
 }
Пример #10
0
  /**
   * 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);
  }
  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 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"));
  }