Java Code Examples for org.apache.commons.beanutils.PropertyUtils#isWriteable()

The following examples show how to use org.apache.commons.beanutils.PropertyUtils#isWriteable() . 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: KualiMaintenanceDocumentAction.java    From rice with Educational Community License v2.0 6 votes vote down vote up
protected void copyParametersToBO(Map<String, String> parameters, PersistableBusinessObject newBO) throws Exception{
	for (String parmName : parameters.keySet()) {
		String propertyValue = parameters.get(parmName);

		if (StringUtils.isNotBlank(propertyValue)) {
			String propertyName = parmName;
			// set value of property in bo
			if (PropertyUtils.isWriteable(newBO, propertyName)) {
				Class type = ObjectUtils.easyGetPropertyType(newBO, propertyName);
				if (type != null && Formatter.getFormatter(type) != null) {
					Formatter formatter = Formatter.getFormatter(type);
					Object obj = formatter.convertFromPresentationFormat(propertyValue);
					ObjectUtils.setObjectProperty(newBO, propertyName, obj.getClass(), obj);
				}
				else {
					ObjectUtils.setObjectProperty(newBO, propertyName, String.class, propertyValue);
				}
			}
		}
	}
}
 
Example 2
Source File: ObjectUtils.java    From rice with Educational Community License v2.0 6 votes vote down vote up
/**
 * Return whether or not an attribute is writeable. This method is aware that that Collections may be involved and
 * handles them
 * consistently with the way in which OJB handles specifying the attributes of elements of a Collection.
 *
 * @param object
 * @param property
 * @return
 * @throws IllegalArgumentException
 */
public static boolean isWriteable(Object object, String property,
        PersistenceStructureService persistenceStructureService) throws IllegalArgumentException {
    if (null == object || null == property) {
        throw new IllegalArgumentException("Cannot check writeable status with null arguments.");
    }

	// Try the easy way.
	try {
		if (!(PropertyUtils.isWriteable(object, property))) {
			// If that fails lets try to be a bit smarter, understanding that Collections may be involved.
			return isWriteableHelper(object, property, persistenceStructureService);
		} else {
			return true;
		}
	} catch (NestedNullException nestedNullException) {
		// If a NestedNullException is thrown then the property has a null
		// value.  Call the helper to find the class of the property and
		// get a newInstance of it.
		return isWriteableHelper(object, property, persistenceStructureService);
	}
}
 
Example 3
Source File: TestDataGenerator.java    From kfs with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Generates transaction data for a business object from properties
 * 
 * @param businessObject the transction business object
 * @return the transction business object with data
 * @throws Exception thrown if an exception is encountered for any reason
 */
public Transaction generateTransactionData(Transaction businessObject) throws Exception {
    Iterator propsIter = properties.keySet().iterator();
    while (propsIter.hasNext()) {
        String propertyName = (String) propsIter.next();
        String propertyValue = (String) properties.get(propertyName);

        // if searchValue is empty and the key is not a valid property ignore
        if (StringUtils.isBlank(propertyValue) || !(PropertyUtils.isWriteable(businessObject, propertyName))) {
            continue;
        }

        Object finalPropertyValue = getPropertyValue(businessObject, propertyName, propertyValue);
        if (finalPropertyValue != null) {
            PropertyUtils.setProperty(businessObject, propertyName, finalPropertyValue);
        }
    }
    setFiscalYear(businessObject);
    return businessObject;
}
 
Example 4
Source File: ObjectUtil.java    From kfs with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Populate the given fields of the target object with the values of an array
 * 
 * @param targetObject the target object
 * @param sourceObject the given array
 * @param keyFields the given fields of the target object that need to be popluated
 */
public static void buildObject(Object targetObject, Object[] sourceObject, List<String> keyFields) {
    int indexOfArray = 0;
    for (String propertyName : keyFields) {
        if (PropertyUtils.isWriteable(targetObject, propertyName) && indexOfArray < sourceObject.length) {
            try {
                Object value = sourceObject[indexOfArray];
                String propertyValue = value != null ? value.toString() : StringUtils.EMPTY;

                String type = getSimpleTypeName(targetObject, propertyName);
                Object realPropertyValue = valueOf(type, propertyValue);

                if (realPropertyValue != null && !StringUtils.isEmpty(realPropertyValue.toString())) {
                    PropertyUtils.setProperty(targetObject, propertyName, realPropertyValue);
                }
                else {
                    PropertyUtils.setProperty(targetObject, propertyName, null);
                }
            }
            catch (Exception e) {
                LOG.debug(e);
            }
        }
        indexOfArray++;
    }
}
 
Example 5
Source File: ObjectUtil.java    From kfs with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Populate the given fields of the target object with the corresponding field values of source object
 * 
 * @param targetObject the target object
 * @param sourceObject the source object
 * @param keyFields the given fields of the target object that need to be popluated
 */
public static void buildObject(Object targetObject, Object sourceObject, List<String> keyFields) {
    if (sourceObject.getClass().isArray()) {
        buildObject(targetObject, sourceObject, keyFields);
        return;
    }

    for (String propertyName : keyFields) {
        if (PropertyUtils.isReadable(sourceObject, propertyName) && PropertyUtils.isWriteable(targetObject, propertyName)) {
            try {
                Object propertyValue = PropertyUtils.getProperty(sourceObject, propertyName);
                PropertyUtils.setProperty(targetObject, propertyName, propertyValue);
            }
            catch (Exception e) {
                LOG.debug(e);
            }
        }
    }
}
 
Example 6
Source File: MailingServiceImpl.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
private <T> T cloneBean(T dest, T orig) throws IllegalAccessException, InvocationTargetException {
	PropertyDescriptor[] origDescriptors = PropertyUtils.getPropertyDescriptors(orig);
	for (PropertyDescriptor descriptor : origDescriptors) {
		String name = descriptor.getName();
		if (PropertyUtils.isReadable(orig, name) && PropertyUtils.isWriteable(dest, name)) {
			try {
				Object value = PropertyUtils.getSimpleProperty(orig, name);
				if (!(value instanceof Collection<?>) && !(value instanceof Map<?, ?>)) {
					PropertyUtils.setSimpleProperty(dest, name, value);
				}
			} catch (NoSuchMethodException e) {
				logger.debug("Error writing to '" + name + "' on class '" + dest.getClass() + "'", e);
			}
		}
	}
	return dest;
}
 
Example 7
Source File: ObjectUtil.java    From springdream with Apache License 2.0 5 votes vote down vote up
/**
 * 设置成员变量
 */
public static void setField(Object obj, String fieldName, Object fieldValue) {
    try {
        if (PropertyUtils.isWriteable(obj, fieldName)) {
            PropertyUtils.setProperty(obj, fieldName, fieldValue);
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 8
Source File: ToolInfo.java    From velocity-tools with Apache License 2.0 5 votes vote down vote up
/**
 * Set a property on a tool instance
 * @param tool tool instance
 * @param name property name
 * @param value property value
 * @throws Exception if setting the property throwed
 */
protected void setProperty(Object tool, String name, Object value) throws Exception
{
    if (PropertyUtils.isWriteable(tool, name))
    {
        //TODO? support property conversion here?
        //      heavy-handed way is BeanUtils.copyProperty(...)
        PropertyUtils.setProperty(tool, name, value);
    }
}
 
Example 9
Source File: LookupCriteriaGeneratorImpl.java    From rice with Educational Community License v2.0 5 votes vote down vote up
@Override
public QueryByCriteria.Builder createObjectCriteriaFromMap(Object example, Map<String, String> formProps) {
    Predicates criteria = new Predicates();

    // iterate through the parameter map for search criteria
    for (Map.Entry<String, String> formProp : formProps.entrySet()) {

        String propertyName = formProp.getKey();
        String searchValue = "";
        if (formProp.getValue() != null) {
            searchValue = formProp.getValue();
        }

        Object instanObject = instantiateLookupDataObject((Class<?>)example);
        if (StringUtils.isNotBlank(searchValue) & PropertyUtils.isWriteable(instanObject, propertyName)) {
            Class<?> propertyType = getPropertyType(instanObject, propertyName);
            if (TypeUtils.isIntegralClass(propertyType) || TypeUtils.isDecimalClass(propertyType) ) {
                addEqualNumeric(criteria, propertyName, propertyType, searchValue);
            } else if (TypeUtils.isTemporalClass(propertyType)) {
                addEqualTemporal(criteria, propertyName, searchValue);
            } else {
                addEqual(criteria, propertyName, searchValue);
            }
        }
    }

    return criteria.toQueryBuilder();
}
 
Example 10
Source File: TestDataPreparator.java    From kfs with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Generates transaction data for a business object from properties
 * 
 * @param businessObject the transction business object
 * @return the transction business object with data
 * @throws Exception thrown if an exception is encountered for any reason
 */
public static <T> T buildTestDataObject(Class<? extends T> clazz, Properties properties) {
    T testData = null;

    try {
        testData = clazz.newInstance();

        Iterator propsIter = properties.keySet().iterator();
        while (propsIter.hasNext()) {
            String propertyName = (String) propsIter.next();
            String propertyValue = (String) properties.get(propertyName);

            // if searchValue is empty and the key is not a valid property ignore
            if (StringUtils.isBlank(propertyValue) || !(PropertyUtils.isWriteable(testData, propertyName))) {
                continue;
            }

            String propertyType = PropertyUtils.getPropertyType(testData, propertyName).getSimpleName();
            Object finalPropertyValue = ObjectUtil.valueOf(propertyType, propertyValue);
            
            if (finalPropertyValue != null) {
                PropertyUtils.setProperty(testData, propertyName, finalPropertyValue);
            }
        }
    }
    catch (Exception e) {
        throw new RuntimeException("Cannot build a test data object with the given data. " + e);
    }

    return testData;
}
 
Example 11
Source File: MyBeanUtils.java    From jeecg with Apache License 2.0 5 votes vote down vote up
/**
	 * 对象拷贝
	 * 数据对象空值不拷贝到目标对象
	 * 
	 * @param dataObject
	 * @param toObject
	 * @throws NoSuchMethodException
	 * copy
	 */
  public static void copyBeanNotNull2Bean(Object databean,Object tobean)throws Exception
  {
	  PropertyDescriptor origDescriptors[] = PropertyUtils.getPropertyDescriptors(databean);
      for (int i = 0; i < origDescriptors.length; i++) {
          String name = origDescriptors[i].getName();
//          String type = origDescriptors[i].getPropertyType().toString();
          if ("class".equals(name)) {
              continue; // No point in trying to set an object's class
          }
          if (PropertyUtils.isReadable(databean, name) &&PropertyUtils.isWriteable(tobean, name)) {
              try {
                  Object value = PropertyUtils.getSimpleProperty(databean, name);
                  if(value!=null){
                	  getInstance().setSimpleProperty(tobean, name, value);
                  }
              }
              catch (java.lang.IllegalArgumentException ie) {
                  ; // Should not happen
              }
              catch (Exception e) {
                  ; // Should not happen
              }

          }
      }
  }
 
Example 12
Source File: ObjectUtil.java    From smart-framework with Apache License 2.0 5 votes vote down vote up
/**
 * 设置成员变量
 */
public static void setField(Object obj, String fieldName, Object fieldValue) {
    try {
        if (PropertyUtils.isWriteable(obj, fieldName)) {
            PropertyUtils.setProperty(obj, fieldName, fieldValue);
        }
    } catch (Exception e) {
        logger.error("设置成员变量出错!", e);
        throw new RuntimeException(e);
    }
}
 
Example 13
Source File: KubernetesCloudTest.java    From kubernetes-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void copyConstructor() throws Exception {
    PodTemplate pt = new PodTemplate();
    pt.setName("podTemplate");

    KubernetesCloud cloud = new KubernetesCloud("name");
    ArrayList<String> objectProperties = Lists.newArrayList("templates", "podRetention", "podLabels", "labels", "serverCertificate");
    for (String property: PropertyUtils.describe(cloud).keySet()) {
        if (PropertyUtils.isWriteable(cloud, property)) {
            Class<?> propertyType = PropertyUtils.getPropertyType(cloud, property);
            if (propertyType == String.class) {
                if (property.endsWith("Str")) {
                    // setContainerCapStr
                    // setMaxRequestsPerHostStr
                    PropertyUtils.setProperty(cloud, property, RandomStringUtils.randomNumeric(3));
                } else {
                    PropertyUtils.setProperty(cloud, property, RandomStringUtils.randomAlphabetic(10));
                }
            } else if (propertyType == int.class) {
                PropertyUtils.setProperty(cloud, property, RandomUtils.nextInt());
            } else if (propertyType == Integer.class) {
                PropertyUtils.setProperty(cloud, property, Integer.valueOf(RandomUtils.nextInt()));
            } else if (propertyType == boolean.class) {
                PropertyUtils.setProperty(cloud, property, RandomUtils.nextBoolean());
            } else if (!objectProperties.contains(property)) {
                fail("Unhandled field in copy constructor: " + property);
            }
        }
    }
    cloud.setServerCertificate("-----BEGIN CERTIFICATE-----");
    cloud.setTemplates(Collections.singletonList(pt));
    cloud.setPodRetention(new Always());
    cloud.setPodLabels(PodLabel.listOf("foo", "bar", "cat", "dog"));
    cloud.setLabels(ImmutableMap.of("foo", "bar"));

    KubernetesCloud copy = new KubernetesCloud("copy", cloud);
    assertEquals("copy", copy.name);
    assertEquals("Expected cloud from copy constructor to be equal to the source except for name", cloud, copy);
}
 
Example 14
Source File: ObjectUtil.java    From smart-framework with Apache License 2.0 5 votes vote down vote up
/**
 * 设置成员变量
 */
public static void setField(Object obj, String fieldName, Object fieldValue) {
    try {
        if (PropertyUtils.isWriteable(obj, fieldName)) {
            PropertyUtils.setProperty(obj, fieldName, fieldValue);
        }
    } catch (Exception e) {
        logger.error("设置成员变量出错!", e);
        throw new RuntimeException(e);
    }
}
 
Example 15
Source File: MyBeanUtils.java    From jeewx with Apache License 2.0 5 votes vote down vote up
/**
	 * 对象拷贝
	 * 数据对象空值不拷贝到目标对象
	 * 
	 * @param dataObject
	 * @param toObject
	 * @throws NoSuchMethodException
	 * copy
	 */
  public static void copyBeanNotNull2Bean(Object databean,Object tobean)
  {
	  PropertyDescriptor origDescriptors[] =
          PropertyUtils.getPropertyDescriptors(databean);
      for (int i = 0; i < origDescriptors.length; i++) {
          String name = origDescriptors[i].getName();
//          String type = origDescriptors[i].getPropertyType().toString();
          if ("class".equals(name)) {
              continue; // No point in trying to set an object's class
          }
          if (PropertyUtils.isReadable(databean, name) &&
              PropertyUtils.isWriteable(tobean, name)) {
              try {
                  Object value = PropertyUtils.getSimpleProperty(databean, name);
                  if(value!=null){
                	    copyProperty(tobean, name, value);
                  }
              }
              catch (java.lang.IllegalArgumentException ie) {
                  ; // Should not happen
              }
              catch (Exception e) {
                  ; // Should not happen
              }

          }
      }
  }
 
Example 16
Source File: MyBeanUtils.java    From jeewx with Apache License 2.0 5 votes vote down vote up
/**
	 * 对象拷贝
	 * 数据对象空值不拷贝到目标对象
	 * 
	 * @param dataObject
	 * @param toObject
	 * @throws NoSuchMethodException
	 * copy
	 */
  public static void copyBeanNotNull2Bean(Object databean,Object tobean)
  {
	  PropertyDescriptor origDescriptors[] =
          PropertyUtils.getPropertyDescriptors(databean);
      for (int i = 0; i < origDescriptors.length; i++) {
          String name = origDescriptors[i].getName();
//          String type = origDescriptors[i].getPropertyType().toString();
          if ("class".equals(name)) {
              continue; // No point in trying to set an object's class
          }
          if (PropertyUtils.isReadable(databean, name) &&
              PropertyUtils.isWriteable(tobean, name)) {
              try {
                  Object value = PropertyUtils.getSimpleProperty(databean, name);
                  if(value!=null){
                	    copyProperty(tobean, name, value);
                  }
              }
              catch (java.lang.IllegalArgumentException ie) {
                  ; // Should not happen
              }
              catch (Exception e) {
                  ; // Should not happen
              }

          }
      }
  }
 
Example 17
Source File: MyBeanUtils.java    From jeewx with Apache License 2.0 5 votes vote down vote up
/**
	 * 对象拷贝
	 * 数据对象空值不拷贝到目标对象
	 * 
	 * @param dataObject
	 * @param toObject
	 * @throws NoSuchMethodException
	 * copy
	 */
  public static void copyBeanNotNull2Bean(Object databean,Object tobean)throws Exception
  {
	  PropertyDescriptor origDescriptors[] = PropertyUtils.getPropertyDescriptors(databean);
      for (int i = 0; i < origDescriptors.length; i++) {
          String name = origDescriptors[i].getName();
//          String type = origDescriptors[i].getPropertyType().toString();
          if ("class".equals(name)) {
              continue; // No point in trying to set an object's class
          }
          if (PropertyUtils.isReadable(databean, name) &&PropertyUtils.isWriteable(tobean, name)) {
              try {
                  Object value = PropertyUtils.getSimpleProperty(databean, name);
                  if(value!=null){
                	    copyProperty(tobean, name, value);
                  }
              }
              catch (java.lang.IllegalArgumentException ie) {
                  ; // Should not happen
              }
              catch (Exception e) {
                  ; // Should not happen
              }

          }
      }
  }
 
Example 18
Source File: FieldUtils.java    From rice with Educational Community License v2.0 5 votes vote down vote up
private static boolean isPropertyWritable(Object bean, String name) {
    try {
        return PropertyUtils.isWriteable(bean, name);
    } catch (NestedNullException e) {
        return false;
    }
}
 
Example 19
Source File: ObjectUtil.java    From PeonyFramwork with Apache License 2.0 5 votes vote down vote up
/**
 * 设置成员变量
 */
public static void setField(Object obj, String fieldName, Object fieldValue) {
    try {
        if (PropertyUtils.isWriteable(obj, fieldName)) {
            PropertyUtils.setProperty(obj, fieldName, fieldValue);
        }
    } catch (Exception e) {
        logger.error("设置成员变量出错!", e);
        throw new RuntimeException(e);
    }
}
 
Example 20
Source File: ComplexContentTransformer.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Sets any transformation option overrides it can.
 */
private void overrideTransformationOptions(TransformationOptions options)
{
    // Set any transformation options overrides if we can
    if(options != null && transformationOptionOverrides != null)
    {
       for(String key : transformationOptionOverrides.keySet())
       {
          if(PropertyUtils.isWriteable(options, key))
          {
             try 
             {
                PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(options, key);
                Class<?> propertyClass = pd.getPropertyType();
                
                Object value = transformationOptionOverrides.get(key);
                if(value != null)
                {
                    if(propertyClass.isInstance(value))
                    {
                        // Nothing to do
                    }
                    else if(value instanceof String && propertyClass.isInstance(Boolean.TRUE))
                    {
                        // Use relaxed converter
                        value = TransformationOptions.relaxedBooleanTypeConverter.convert((String)value);
                    }
                    else
                    {
                        value = DefaultTypeConverter.INSTANCE.convert(propertyClass, value);
                    }
                }
                PropertyUtils.setProperty(options, key, value);
             } 
             catch(NoSuchMethodException nsme) {}
             catch(InvocationTargetException ite) {}
             catch(IllegalAccessException iae) {}
          }
          else
          {
             logger.warn("Unable to set override Transformation Option " + key + " on " + options);
          }
       }
    }
}