Example #1
0
  /**
   * Exception safe version of BeanUtils.populate()
   *
   * @param object the object to set the properties on
   * @param props the map of properties to set
   * @param logWarnings whether exception warnings should be logged
   */
  public static void populateWithoutFail(Object object, Map props, boolean logWarnings) {
    // Check to see if our object has a setProperties method where the properties
    // map should be set
    if (ClassUtils.getMethod(object.getClass(), SET_PROPERTIES_METHOD, new Class[] {Map.class})
        != null) {
      try {
        BeanUtils.setProperty(object, "properties", props);
      } catch (Exception e) {
        // this should never happen since we explicitly check for the method
        // above
        if (logWarnings) {
          logger.warn(
              "Property: "
                  + SET_PROPERTIES_METHOD
                  + "="
                  + Map.class.getName()
                  + " not found on object: "
                  + object.getClass().getName());
        }
      }
    } else {
      for (Iterator iterator = props.entrySet().iterator(); iterator.hasNext(); ) {
        Map.Entry entry = (Map.Entry) iterator.next();

        try {
          BeanUtils.setProperty(object, entry.getKey().toString(), entry.getValue());
        } catch (Exception e) {
          if (logWarnings) {
            logger.warn(
                "Property: "
                    + entry.getKey()
                    + "="
                    + entry.getValue()
                    + " not found on object: "
                    + object.getClass().getName());
          }
        }
      }
    }
  }
Example #2
0
 /**
  * This will overlay a map of properties on a bean. This method will validate that all properties
  * are available on the bean before setting the properties
  *
  * @param bean the bean on which to set the properties
  * @param props a Map of properties to set on the bean
  * @throws IllegalAccessException
  * @throws InvocationTargetException
  */
 public static void populate(Object bean, Map props)
     throws IllegalAccessException, InvocationTargetException {
   // Check to see if our object has a setProperties method where the properties
   // map should be set
   if (ClassUtils.getMethod(bean.getClass(), SET_PROPERTIES_METHOD, new Class[] {Map.class})
       != null) {
     BeanUtils.setProperty(bean, "properties", props);
   } else {
     Map master = describe(bean);
     for (Iterator iterator = props.keySet().iterator(); iterator.hasNext(); ) {
       Object o = iterator.next();
       if (!master.containsKey(o)) {
         throw new IllegalArgumentException(
             CoreMessages.propertyDoesNotExistOnObject(o.toString(), bean).getMessage());
       }
     }
     org.apache.commons.beanutils.BeanUtils.populate(bean, props);
   }
 }