Example usage for org.apache.commons.beanutils PropertyUtils isWriteable

List of usage examples for org.apache.commons.beanutils PropertyUtils isWriteable

Introduction

In this page you can find the example usage for org.apache.commons.beanutils PropertyUtils isWriteable.

Prototype

public static boolean isWriteable(Object bean, String name) 

Source Link

Document

Return true if the specified property name identifies a writeable property on the specified bean; otherwise, return false.

For more details see PropertyUtilsBean.

Usage

From source file:org.beangle.model.util.EntityUtils.java

/**
 * ?/*w  ww.  j  a  v a2  s.c  o m*/
 * 
 * @param entity
 * @param ignoreDefault
 *            
 * @return
 */
@SuppressWarnings("unchecked")
public static boolean isEmpty(Entity<?> entity, boolean ignoreDefault) {
    BeanMap map = new BeanMap(entity);
    List<String> attList = CollectUtils.newArrayList();
    attList.addAll(map.keySet());
    attList.remove("class");
    try {
        for (final String attr : attList) {
            if (!PropertyUtils.isWriteable(entity, attr)) {
                continue;
            }
            Object value = map.get(attr);
            if (null == value) {
                continue;
            }
            if (ignoreDefault) {
                if (value instanceof Number) {
                    if (((Number) value).intValue() != 0) {
                        return false;
                    }
                } else if (value instanceof String) {
                    String str = (String) value;
                    if (StringUtils.isNotEmpty(str)) {
                        return false;
                    }
                } else {
                    return false;
                }
            } else {
                return false;
            }
        }
    } catch (Exception e) {
        logger.error("isEmpty error", e);
    }
    return true;
}

From source file:org.cloudifysource.dsl.internal.BaseDslScript.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private void applyPropertyToObject(final Object object, final String name, final Object value) {

    if (!isProperyExistsInBean(object, name)) {
        throw new IllegalArgumentException("Could not find property: " + name + " on Object: " + object);
    }/* ww  w.  j ava  2 s .com*/

    // Check for duplicate properties.
    if (this.usedProperties == null) {
        throw new IllegalArgumentException("used properties can not be null. Property: " + name + ", Value: "
                + value.toString() + ", Active object: " + this.activeObject);
    }
    if (this.usedProperties.contains(name)) {
        if (!isDuplicatePropertyAllowed(value)) {
            throw new IllegalArgumentException(
                    "Property duplication was found: Property " + name + " is define" + "d more than once.");
        }
    }

    this.usedProperties.add(name);
    Object convertedValue = null;
    try {
        convertedValue = convertValueToExecutableDSLEntryIfNeeded(getDSLFile().getParentFile(), object, name,
                value);
        if (logger.isLoggable(Level.FINEST)) {
            logger.finest("BeanUtils.setProperty(object=" + object + ",name=" + name + ",value="
                    + convertedValue + ",value.getClass()=" + convertedValue.getClass());
        }

        // Check if writable
        if (!PropertyUtils.isWriteable(object, name)) {
            throw new IllegalArgumentException("Field " + name + " in object of type: "
                    + object.getClass().getName() + " is not writable");
        }

        // If value is a map, merge with existing map
        final Object currentValue = PropertyUtils.getProperty(object, name);
        if (currentValue != null && currentValue instanceof Map<?, ?> && convertedValue != null
                && convertedValue instanceof Map<?, ?>) {

            final Map<Object, Object> currentMap = (Map<Object, Object>) currentValue;
            currentMap.putAll((Map<Object, Object>) convertedValue);

        } else if (PropertyUtils.getPropertyType(object, name).isEnum() && value instanceof String) {
            final Class enumClass = PropertyUtils.getPropertyType(object, name);
            final Enum enumValue = Enum.valueOf(enumClass, (String) value);
            BeanUtils.setProperty(object, name, enumValue);
        } else {
            // Then set it
            BeanUtils.setProperty(object, name, convertedValue);
        }
    } catch (final DSLValidationException e) {
        throw new DSLValidationRuntimeException(e);
    } catch (final Exception e) {
        throw new IllegalArgumentException("Failed to set property " + name + " of Object " + object
                + " to value: " + value + ". Error was: " + e.getMessage(), e);
    }

    checkForApplicationServiceBlockNameParameter(name, value);

}

From source file:org.eclipse.jubula.client.core.preferences.database.DatabaseConnectionConverter.java

/**
 * /* ww  w.  ja v a  2 s .  c o m*/
 * @param connection The connection to represent as a string. Must not be 
 *                   <code>null</code>.
 * @return a persistable String representation of the given object.
 */
private static String serialize(DatabaseConnection connection) {
    Validate.notNull(connection);

    StringBuilder sb = new StringBuilder();
    sb.append(connection.getName()).append(PROPERTY_SEPARATOR);
    for (PropertyDescriptor propDesc : PropertyUtils.getPropertyDescriptors(connection.getConnectionInfo())) {
        String propName = propDesc.getName();
        try {
            // only save writable properties, as we will not be able to 
            // set read-only properties when reading connection info back 
            // in from the preference store 
            if (PropertyUtils.isWriteable(connection.getConnectionInfo(), propName)) {
                sb.append(propName).append(PROPERTY_SEPARATOR)
                        .append(BeanUtils.getProperty(connection.getConnectionInfo(), propName))
                        .append(PROPERTY_SEPARATOR);
            }
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
    }

    sb.deleteCharAt(sb.length() - 1);
    return sb.toString();
}

From source file:org.fao.geonet.Geonetwork.java

/**
 * Init StatusActions./*from www .j ava  2 s .c  o m*/
 * 
 */
private Class setupStatusActions(ServiceConfig handlerConfig) throws ClassNotFoundException {
    // Status actions class - load it
    String statusActionsClassName = handlerConfig.getMandatoryValue(Geonet.Config.STATUS_ACTIONS_CLASS);
    Class statusActionsClass = Class.forName(statusActionsClassName);

    String useHtml5uiParam = handlerConfig.getValue(Geonet.Config.USE_HTML5_GUI);
    boolean useHtml5ui;
    if (useHtml5uiParam != null) {
        useHtml5ui = BooleanUtils.isTrue(BooleanUtils.toBooleanObject(useHtml5uiParam));
    } else {
        logger.info("Parameter " + Geonet.Config.USE_HTML5_GUI + " not found. Default to true.");
        useHtml5ui = true;
    }

    // init html5 value if possible
    try {
        final String HTML5_PROP_NAME = "useHtml5ui";

        StatusActions statusActionsImpl = (StatusActions) statusActionsClass.newInstance();

        if (PropertyUtils.isWriteable(statusActionsImpl, HTML5_PROP_NAME)) {
            BeanUtils.setProperty(statusActionsImpl, HTML5_PROP_NAME, useHtml5ui);
            logger.info(Geonet.Config.USE_HTML5_GUI + " set to " + useHtml5ui);
        } else {
            logger.warning("Could not find setter for " + Geonet.Config.USE_HTML5_GUI);
        }
    } catch (Exception ex) {
        logger.warning("Could not inject " + Geonet.Config.USE_HTML5_GUI + " value: " + ex.getMessage());
    }

    return statusActionsClass;
}

From source file:org.hx.rainbow.common.util.JavaBeanUtil.java

/**
 * bean??bean???/*from  www.jav  a2  s. co  m*/
 * zhf 2012-5-14 [] BeanUtils.copyPropertiescopy
 * @param fromBean
 * @param toBean
 */
public static void copyProperties(Object fromBean, Object toBean) {
    if (fromBean == null || toBean == null) {
        return;
    }
    try {
        //         BeanUtils.copyProperties(toBean, fromBean);
        PropertyDescriptor origDescriptors[] = PropertyUtils.getPropertyDescriptors(toBean);

        for (int i = 0; i < origDescriptors.length; i++) {
            String name = origDescriptors[i].getName();
            if (name.equals("class")) {
                continue;
            }

            //if (PropertyUtils.isReadable(fromBean, name)||PropertyUtils.isWriteable(toBean, name)) {
            if (PropertyUtils.isReadable(fromBean, name) && PropertyUtils.isWriteable(toBean, name)) {
                Object obj = PropertyUtils.getProperty(fromBean, name);
                if (obj == null) {
                    continue;
                }
                obj = convertValue(origDescriptors[i], obj);
                BeanUtils.copyProperty(toBean, name, obj);
            }
        } // for end
    } catch (Exception e) {
        e.printStackTrace();
        throw new AppException(e.getMessage());
    }
}

From source file:org.jaxygen.typeconverter.util.BeanUtil.java

/**
 * Copies bean content from one bean to another. The bean is copied using the
 * set and get methods. Method invokes all getXX methods on the from object,
 * and result pass to the corresponding setXX methods in the to object. Note
 * that it is not obvious that both object are of the same type.
 * If get and set methods do not match then it tries to use appropriate
 * converter registered in default type converter factory.
 *
 * @param from data provider object.//ww  w  .  j  av a 2 s . c  om
 * @param to data acceptor object.
 */
public static void translateBean(Object from, Object to) {
    PropertyDescriptor[] fromGetters = null;
    fromGetters = PropertyUtils.getPropertyDescriptors(from.getClass());
    for (PropertyDescriptor pd : fromGetters) {
        if (pd.getReadMethod().isAnnotationPresent(BeanTransient.class) == false) {
            if (PropertyUtils.isWriteable(to, pd.getName())) {
                try {
                    PropertyDescriptor wd = PropertyUtils.getPropertyDescriptor(to, pd.getName());
                    if (!wd.getWriteMethod().isAnnotationPresent(BeanTransient.class)) {
                        Object copyVal = PropertyUtils.getProperty(from, pd.getName());
                        if (wd.getPropertyType().isAssignableFrom(pd.getPropertyType())) {
                            PropertyUtils.setProperty(to, wd.getName(), copyVal);
                        } else {
                            try {
                                Object convertedCopyVal = TypeConverterFactory.instance().convert(copyVal,
                                        wd.getPropertyType());
                                PropertyUtils.setProperty(to, wd.getName(), convertedCopyVal);
                            } catch (ConversionError ex) {
                                Logger.getAnonymousLogger().log(Level.WARNING,
                                        "Method {0}.{1} of type {2} is not compatible to {3}.{4} of type{5}",
                                        new Object[] { from.getClass().getName(), pd.getName(),
                                                pd.getPropertyType(), to.getClass().getName(), wd.getName(),
                                                wd.getPropertyType() });
                            }
                        }
                    }
                } catch (IllegalAccessException ex) {
                    throw new java.lang.IllegalArgumentException("Could not translate bean", ex);
                } catch (InvocationTargetException ex) {
                    throw new java.lang.IllegalArgumentException("Could not translate bean", ex);
                } catch (NoSuchMethodException ex) {
                    throw new java.lang.IllegalArgumentException("Could not translate bean", ex);
                }
            }
        }
    }
}

From source file:org.jbuilt.utils.ValueClosure.java

public boolean isReadOnly(Object bean, String prop) {
    boolean result = false;
    result = !PropertyUtils.isWriteable(bean, prop);
    return result;
}

From source file:org.kuali.ext.mm.ObjectUtil.java

/**
 * 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
 *///from   w  w w .  j av a  2s .c  o m
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);
            }
        }
    }
}

From source file:org.kuali.ext.mm.ObjectUtil.java

/**
 * Populate the given fields of the target object with the values of an array
 *
 * @param targetObject the target object
 * @param sourceObject the given array//from   w  w  w  .j a  va2 s  . co  m
 * @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++;
    }
}

From source file:org.kuali.ext.mm.ObjectUtil.java

/**
 * Populate the property of the target object with the counterpart of the source object
 *
 * @param targetObject the target object
 * @param sourceObject the source object
 * @param property the specified propety of the target object
 * @param skipReferenceFields determine whether the referencing fields need to be populated
 *//*from ww  w . j  a  v a  2  s  .  co m*/
public static void setProperty(Object targetObject, Object sourceObject, DynaProperty property,
        boolean skipReferenceFields) {
    String propertyName = property.getName();

    try {
        if (skipReferenceFields) {
            Class propertyType = property.getType();
            if (propertyType == null || PersistableBusinessObjectBase.class.isAssignableFrom(propertyType)
                    || List.class.isAssignableFrom(propertyType)) {
                return;
            }
        }

        if (PropertyUtils.isReadable(sourceObject, propertyName)
                && PropertyUtils.isWriteable(targetObject, propertyName)) {
            Object propertyValue = PropertyUtils.getProperty(sourceObject, propertyName);
            PropertyUtils.setProperty(targetObject, propertyName, propertyValue);
        }
    } catch (IllegalAccessException e) {
        LOG.debug(e.getMessage() + ":" + propertyName);
    } catch (InvocationTargetException e) {
        LOG.debug(e.getMessage() + ":" + propertyName);
    } catch (NoSuchMethodException e) {
        LOG.debug(e.getMessage() + ":" + propertyName);
    } catch (IllegalArgumentException e) {
        LOG.debug(e.getMessage() + ":" + propertyName);
    } catch (Exception e) {
        LOG.debug(e.getMessage() + ":" + propertyName);
    }
}