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

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

Introduction

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

Prototype

public static void setProperty(Object bean, String name, Object value)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException 

Source Link

Document

Set the value of the specified property of the specified bean, no matter which property reference format is used, with no type conversions.

For more details see PropertyUtilsBean.

Usage

From source file:com.all.shared.sync.SyncGenericConverter.java

private static <T> T fillInstance(T instance, Map<String, Object> attributes) {
    if (instance != null) {
        for (String attribute : attributes.keySet()) {
            if (PropertyUtils.isWriteable(instance, attribute)) {
                try {
                    Class<?> type = PropertyUtils.getPropertyType(instance, attribute);
                    if (instance instanceof ComplexSyncAble) {
                        ComplexSyncAble postSyncAble = (ComplexSyncAble) instance;
                        if (postSyncAble.requiresPostProcessing(attribute)) {
                            continue;
                        }//from   w  w w.ja  v a2  s  .  c o m
                    }
                    Object value = readValue(attribute, type, attributes);
                    PropertyUtils.setProperty(instance, attribute, value);
                } catch (Exception e) {
                    LOGGER.error("Could not fill attribute " + attribute + " to instance of type "
                            + instance.getClass() + ". This attribute will be ignored.", e);
                }
            }
        }
    }
    return instance;
}

From source file:com.chiralbehaviors.CoRE.phantasm.graphql.schemas.JooqSchema.java

private void initialize(UpdatableRecord<?> instance, UUID updatedBy) {
    try {/*  ww  w  .j  a  v  a2 s  .com*/
        PropertyUtils.setProperty(instance, "id", RecordsFactory.GENERATOR.generate());
        PropertyUtils.setProperty(instance, "updatedBy", updatedBy);
    } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
        throw new IllegalStateException();
    }
}

From source file:net.jofm.DefaultFixedMapper.java

private void setProperty(Object destinationObject, String fieldName, String data, Object value, boolean ignored)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    if (value != null && !ignored) {
        if (log.isDebugEnabled()) {
            log.debug("Setting field: " + fieldName + ", fixed data:" + data + ", value:" + value);
        }//  w ww  .  j  a  v  a  2  s.  co m
        PropertyUtils.setProperty(destinationObject, fieldName, value);
    }
}

From source file:com.complexible.pinto.RDFMapper.java

/**
 * Read the object from the RDF//from w  ww  . ja va  2s. c om
 *
 * @param theGraph  the RDF
 * @param theClass  the type of the object to read
 * @param theObj    the identifier of the object to create
 *
 * @return          the object
 *
 * @throws RDFMappingException if the object could not be created
 */
public <T> T readValue(final Model theGraph, final Class<T> theClass, final Resource theObj) {
    if (theClass == null) {
        return null;
    }

    final T aInst = newInstance(theClass);

    if (aInst instanceof Identifiable) {
        ((Identifiable) aInst).id(theObj);
    }

    for (PropertyDescriptor aDescriptor : PropertyUtils.getPropertyDescriptors(aInst)) {
        if (isIgnored(aDescriptor)) {
            continue;
        }

        final IRI aProperty = getProperty(aDescriptor);

        Collection<Value> aValues = theGraph.stream()
                .filter(Statements.subjectIs(theObj).and(Statements.predicateIs(aProperty)))
                .map(Statement::getObject).collect(Collectors.toList());

        Object aObj;

        if (aValues.isEmpty()) {
            continue;
        } else if (Collection.class.isAssignableFrom(aDescriptor.getPropertyType())) {
            final Collection aIterable = mCollectionFactory.create(aDescriptor);

            Collection<Value> aElems = Lists.newArrayListWithCapacity(aValues.size());

            // this will allow the mixing of RDF lists of values with single values.  in "well-formed" data that
            // kind of mixing probably won't ever happen.  but it's easier/better to be lax about what we'll accept
            // here, and this will cover one or more list assertions as well as multiple property assertions forming
            // the list as well as the mix of both
            for (Value aValue : aValues) {
                if (aValue instanceof Resource && Models2.isList(theGraph, (Resource) aValue)) {
                    aElems.addAll(Models2.asList(theGraph, (Resource) aValue));
                } else {
                    aElems.add(aValue);
                }
            }

            aElems.stream().map(toObject(theGraph, aDescriptor)::apply).forEach(aIterable::add);

            aObj = aIterable;
        } else if (Map.class.isAssignableFrom(aDescriptor.getPropertyType())) {
            if (aValues.size() > 1) {
                if (mMappingOptions.is(MappingOptions.IGNORE_CARDINALITY_VIOLATIONS)) {
                    LOGGER.warn(
                            "Property type of {} is Map, expected a single value, but {} were found.  MappingOptions is set to ignore this, so using only the first value.",
                            aDescriptor.getName(), aValues.size());
                } else {
                    throw new RDFMappingException(String.format(
                            "%s values found, but property type is Map, one value expected", aValues.size()));
                }
            }

            Value aPropValue = aValues.iterator().next();

            final Map aMap = mMapFactory.create(aDescriptor);

            for (Value aMapEntry : theGraph.filter((Resource) aPropValue, HAS_ENTRY, null).objects()) {
                final Value aKey = theGraph.stream()
                        .filter(Statements.subjectIs((Resource) aMapEntry).and(Statements.predicateIs(KEY)))
                        .map(Statement::getObject).findFirst().orElse(null);
                final Value aValue = theGraph.stream()
                        .filter(Statements.subjectIs((Resource) aMapEntry).and(Statements.predicateIs(VALUE)))
                        .map(Statement::getObject).findFirst().orElse(null);

                Object aKeyObj = null, aValueObj = null;

                if (aKey instanceof Literal) {
                    // ok to pass null here, it won't be used
                    aKeyObj = valueToObject(aKey, theGraph, null);
                } else {
                    aKeyObj = readValue(theGraph, type(theGraph, (Resource) aKey), (Resource) aKey);
                }

                if (aValue instanceof Literal) {
                    aValueObj = valueToObject(aValue, theGraph, null);
                } else {
                    aValueObj = readValue(theGraph, type(theGraph, (Resource) aValue), (Resource) aValue);
                }

                if (aKeyObj == null || aValueObj == null) {
                    LOGGER.warn("Skipping map entry, key or value could not be created.");
                    continue;
                }

                aMap.put(aKeyObj, aValueObj);
            }

            aObj = aMap;
        } else {
            if (aValues.size() > 1) {
                if (mMappingOptions.is(MappingOptions.IGNORE_CARDINALITY_VIOLATIONS)) {
                    LOGGER.warn(
                            "Property type of {} is {}, expected a single value, but {} were found.  MappingOptions is set to ignore this, so using only the first value.",
                            aDescriptor.getName(), aDescriptor.getPropertyType(), aValues.size());
                } else {
                    throw new RDFMappingException(String.format("%s values found, but property type is %s",
                            aValues.size(), aDescriptor.getPropertyType()));
                }
            }

            final Value aValue = aValues.iterator().next();

            aObj = valueToObject(aValue, theGraph, aDescriptor);
        }

        try {
            // this will fail spectacularly if there is a mismatch between the incoming RDF and what the bean
            // defines.  we can either check that eagerly and fail spectacularly then, or do it here and be
            // lazy.  we'll go with lazy
            PropertyUtils.setProperty(aInst, aDescriptor.getName(), aObj);
        } catch (Exception e) {
            Throwables.propagateIfInstanceOf(e, RDFMappingException.class);
            throw new RDFMappingException(e);
        }
    }

    return aInst;
}

From source file:com.qcadoo.model.internal.EntityServiceImpl.java

private void setField(final Object databaseEntity, final String fieldName, final Object value) {
    try {/*from  w  w  w.  j  a  va 2  s.com*/
        PropertyUtils.setProperty(databaseEntity, fieldName, value);
    } catch (Exception e) {
        throw new IllegalStateException("cannot set value of the property: "
                + databaseEntity.getClass().getSimpleName() + ", " + fieldName, e);
    }
}

From source file:com.chiralbehaviors.CoRE.phantasm.graphql.schemas.JooqSchema.java

private void set(UpdatableRecord<?> instance, Map<String, GraphQLType> types, Map<String, Object> state) {
    state.entrySet().stream().filter(entry -> !entry.getKey().equals("id")).forEach(entry -> {
        try {//  w ww.j ava2 s .co m
            PropertyUtils.setProperty(instance, entry.getKey(), entry.getValue());
        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            throw new IllegalArgumentException(String.format("Illegal property: %s", entry));
        }
    });
}

From source file:it.geosolutions.geobatch.imagemosaic.ImageMosaicCommand.java

/**
 * set this instance null properties with the passed configuration
 * @param src//w ww .  j a v a2 s.c  om
 */
public void copyConfigurationIntoCommand(final ImageMosaicConfiguration src) {

    final PropertyDescriptor[] srcProps = PropertyUtils.getPropertyDescriptors(src);
    for (PropertyDescriptor srcProp : srcProps) {
        final String name = srcProp.getName();
        if (RESERVED_PROPS.contains(name)) {
            continue;
        }
        final Object obj;
        try {
            obj = PropertyUtils.getProperty(this, name);
            if (obj == null) {
                // override
                PropertyUtils.setProperty(this, name, PropertyUtils.getProperty(src, name));
            }
        } catch (InvocationTargetException e) {
            if (LOGGER.isWarnEnabled())
                LOGGER.warn(e.getMessage());
        } catch (NoSuchMethodException e) {
            if (LOGGER.isWarnEnabled())
                LOGGER.warn(e.getMessage());
        } catch (IllegalAccessException e) {
            if (LOGGER.isWarnEnabled())
                LOGGER.warn(e.getMessage());
        }
    }

    copyDomainAttributes(src, this);
}

From source file:com.google.code.simplestuff.bean.SimpleBean.java

/**
 * //www.  j ava 2  s . c o  m
 * Returns a test object with all the {@link BusinessField} annotated fields
 * set to a test value. TODO At the moment only the String field are
 * considered and the collection are not considered.
 * 
 * @param bean The class of the bean to fill.
 * @param suffix The suffix to append in the string field.
 * @return The bean with test values.
 */
public static <T> T getTestBean(Class<T> beanClass, String suffix) {
    if (beanClass == null) {
        throw new IllegalArgumentException("The bean class passed is null!!!");
    }

    T testBean = null;
    try {
        testBean = beanClass.newInstance();
    } catch (InstantiationException e1) {
        if (log.isDebugEnabled()) {
            log.debug(e1.getMessage());
        }
    } catch (IllegalAccessException e1) {
        if (log.isDebugEnabled()) {
            log.debug(e1.getMessage());
        }
    }

    BusinessObjectDescriptor businessObjectInfo = BusinessObjectContext.getBusinessObjectDescriptor(beanClass);

    // We don't need here a not null check since by contract the
    // getBusinessObjectDescriptor method always returns an abject.
    if (businessObjectInfo.getNearestBusinessObjectClass() != null) {

        Collection<Field> annotatedField = businessObjectInfo.getAnnotatedFields();
        for (Field field : annotatedField) {
            final BusinessField fieldAnnotation = field.getAnnotation(BusinessField.class);
            if (fieldAnnotation != null) {
                try {
                    if (field.getType().equals(String.class)) {
                        String stringValue = "test" + StringUtils.capitalize(field.getName())
                                + (suffix == null ? "" : suffix);
                        PropertyUtils.setProperty(testBean, field.getName(), stringValue);

                    } else if ((field.getType().equals(boolean.class))
                            || (field.getType().equals(Boolean.class))) {
                        PropertyUtils.setProperty(testBean, field.getName(), true);
                    } else if ((field.getType().equals(int.class)) || (field.getType().equals(Integer.class))) {
                        PropertyUtils.setProperty(testBean, field.getName(), 10);
                    } else if ((field.getType().equals(char.class))
                            || (field.getType().equals(Character.class))) {
                        PropertyUtils.setProperty(testBean, field.getName(), 't');
                    } else if ((field.getType().equals(long.class)) || (field.getType().equals(Long.class))) {
                        PropertyUtils.setProperty(testBean, field.getName(), 10L);
                    } else if ((field.getType().equals(float.class)) || (field.getType().equals(Float.class))) {
                        PropertyUtils.setProperty(testBean, field.getName(), 10F);
                    } else if ((field.getType().equals(byte.class)) || (field.getType().equals(Byte.class))) {
                        PropertyUtils.setProperty(testBean, field.getName(), (byte) 10);
                    } else if (field.getType().equals(Date.class)) {
                        PropertyUtils.setProperty(testBean, field.getName(), new Date());
                    } else if (field.getType().equals(Collection.class)) {
                        // TODO: create a test object of the collection
                        // class specified (if one is specified and
                        // recursively call this method.
                    }

                } catch (IllegalAccessException e) {
                    if (log.isDebugEnabled()) {
                        log.debug(e.getMessage());
                    }
                } catch (InvocationTargetException e) {
                    if (log.isDebugEnabled()) {
                        log.debug(e.getMessage());
                    }
                } catch (NoSuchMethodException e) {
                    if (log.isDebugEnabled()) {
                        log.debug(e.getMessage());
                    }
                }
            }
        }
    }

    return testBean;
}

From source file:jp.go.nict.langrid.p2pgridbasis.data.langrid.converter.ConvertUtil.java

public static void decode(DataAttributes from, Object to) throws DataConvertException {
    setLangridConverter();//w  ww  . j  a  v  a 2  s  .  c  om
    logger.debug("##### decode #####");
    try {
        for (PropertyDescriptor descriptor : PropertyUtils.getPropertyDescriptors(to)) {
            logger.debug(
                    "Name : " + descriptor.getName() + " / PropertyType : " + descriptor.getPropertyType());
            Object value = from.getValue(descriptor.getName());
            if (PropertyUtils.isWriteable(to, descriptor.getName()) && value != null) {
                //Write OK
                try {
                    Converter converter = ConvertUtils.lookup(descriptor.getPropertyType());
                    if (!ignoreProps.contains(descriptor.getName())) {
                        if (converter == null) {
                            logger.error("no converter is registered : " + descriptor.getName() + " "
                                    + descriptor.getPropertyType());
                        } else {
                            Object obj = converter.convert(descriptor.getPropertyType(), value);
                            PropertyUtils.setProperty(to, descriptor.getName(), obj);
                        }
                    }
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                    logger.info(e.getMessage());
                } catch (NoSuchMethodException e) {
                    logger.info(e.getMessage());
                }
            } else {
                if (value != null) {
                    //Write NG
                    logger.debug("isWriteable = false");
                } else {
                    //Write NG
                    logger.debug("value = null");
                }
            }
        }
    } catch (IllegalAccessException e) {
        throw new DataConvertException(e);
    } catch (InvocationTargetException e) {
        throw new DataConvertException(e);
    }
}

From source file:com.sun.faces.config.ManagedBeanFactory.java

/**
 * <li><p> Call the property getter, if it exists.</p></li>
 * <p/>/*ww  w .ja v  a2 s . c o m*/
 * <li><p>If the getter returns null or doesn't exist, create a
 * java.util.ArrayList(), otherwise use the returned Object (an array or
 * a java.util.List).</p></li>
 * <p/>
 * <li><p>If a List was returned or created in step 2), add all
 * elements defined by nested &lt;value&gt; elements in the order
 * they are listed, converting values defined by nested
 * &lt;value&gt; elements to the type defined by
 * &lt;value-class&gt;. If a &lt;value-class&gt; is not defined, use
 * the value as-is (i.e., as a java.lang.String). Add null for each
 * &lt;null-value&gt; element.</p></li>
 * <p/>
 * <li><p> If an array was returned in step 2), create a
 * java.util.ArrayList and copy all elements from the returned array to
 * the new List, auto-boxing elements of a primitive type. Add all
 * elements defined by nested &lt;value&gt; elements as described in step
 * 3).</p></li>
 * <p/>
 * <li><p> If a new java.util.List was created in step 2) and the
 * property is of type List, set the property by calling the setter
 * method, or log an error if there is no setter method.</p></li>
 * <p/>
 * <li><p> If a new java.util.List was created in step 4), convert
 * the * List to array of the same type as the property and set the
 * property by * calling the setter method, or log an error if there
 * is no setter * method.</p></li>
 */

private void setArrayOrListPropertiesIntoBean(Object bean, ManagedPropertyBean property) throws Exception {
    Object result = null;
    boolean getterIsNull = true, getterIsArray = false;
    List valuesForBean = null;
    Class valueType = java.lang.String.class, propertyType = null;

    String propertyName = property.getPropertyName();

    try {
        // see if there is a getter
        result = PropertyUtils.getProperty(bean, propertyName);
        getterIsNull = (null == result) ? true : false;

        propertyType = PropertyUtils.getPropertyType(bean, propertyName);
        getterIsArray = propertyType.isArray();

    } catch (NoSuchMethodException nsme) {
        // it's valid to not have a getter.
    }

    // the property has to be either a List or Array
    if (!getterIsArray) {
        if (null != propertyType && !java.util.List.class.isAssignableFrom(propertyType)) {
            throw new FacesException(
                    Util.getExceptionMessageString(Util.MANAGED_BEAN_CANNOT_SET_LIST_ARRAY_PROPERTY_ID,
                            new Object[] { propertyName, managedBean.getManagedBeanName() }));
        }
    }

    //
    // Deal with the possibility of the getter returning existing
    // values.
    //

    // if the getter returned non-null
    if (!getterIsNull) {
        // if what it returned was an array
        if (getterIsArray) {
            valuesForBean = new ArrayList();
            for (int i = 0, len = Array.getLength(result); i < len; i++) {
                // add the existing values
                valuesForBean.add(Array.get(result, i));
            }
        } else {
            // if what it returned was not a List
            if (!(result instanceof List)) {
                // throw an exception                    
                throw new FacesException(
                        Util.getExceptionMessageString(Util.MANAGED_BEAN_EXISTING_VALUE_NOT_LIST_ID,
                                new Object[] { propertyName, managedBean.getManagedBeanName() }));
            }
            valuesForBean = (List) result;
        }
    } else {

        // getter returned null
        result = valuesForBean = new ArrayList();
    }

    // at this point valuesForBean contains the existing values from
    // the bean, or no values if the bean had no values.  In any
    // case, we can proceed to add values from the config file.
    valueType = copyListEntriesFromConfigToList(property.getListEntries(), valuesForBean);

    // at this point valuesForBean has the values to be set into the
    // bean.

    if (getterIsArray) {
        // convert back to Array
        result = Array.newInstance(valueType, valuesForBean.size());
        for (int i = 0, len = valuesForBean.size(); i < len; i++) {
            if (valueType == Boolean.TYPE) {
                Array.setBoolean(result, i, ((Boolean) valuesForBean.get(i)).booleanValue());
            } else if (valueType == Byte.TYPE) {
                Array.setByte(result, i, ((Byte) valuesForBean.get(i)).byteValue());
            } else if (valueType == Double.TYPE) {
                Array.setDouble(result, i, ((Double) valuesForBean.get(i)).doubleValue());
            } else if (valueType == Float.TYPE) {
                Array.setFloat(result, i, ((Float) valuesForBean.get(i)).floatValue());
            } else if (valueType == Integer.TYPE) {
                Array.setInt(result, i, ((Integer) valuesForBean.get(i)).intValue());
            } else if (valueType == Character.TYPE) {
                Array.setChar(result, i, ((Character) valuesForBean.get(i)).charValue());
            } else if (valueType == Short.TYPE) {
                Array.setShort(result, i, ((Short) valuesForBean.get(i)).shortValue());
            } else if (valueType == Long.TYPE) {
                Array.setLong(result, i, ((Long) valuesForBean.get(i)).longValue());
            } else {
                Array.set(result, i, valuesForBean.get(i));
            }
        }
    } else {
        result = valuesForBean;
    }

    if (getterIsNull || getterIsArray) {
        PropertyUtils.setProperty(bean, propertyName, result);
    }

}