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:org.vulpe.commons.util.VulpeReflectUtil.java

/**
 * Copy transient attributes from <code>origin</code> to
 * <code>destination</code>.
 *
 * @param destination/*w w  w . j a v a2s.  c o m*/
 * @param origin
 */
public static void copyOnlyTransient(final Object destination, final Object origin) {
    final List<Field> fields = getFields(origin.getClass());
    for (final Field field : fields) {
        if (!Modifier.isTransient(field.getModifiers())) {
            continue;
        }
        try {
            final Object value = PropertyUtils.getProperty(origin, field.getName());
            if (Collection.class.isAssignableFrom(field.getType())) {
                final Collection valueDes = (Collection) PropertyUtils.getProperty(destination,
                        field.getName());
                if (value == null) {
                    if (valueDes != null) {
                        valueDes.clear();
                    }
                } else {
                    if (valueDes == null) {
                        PropertyUtils.setProperty(destination, field.getName(), value);
                    } else {
                        valueDes.clear();
                        valueDes.addAll((Collection) value);
                    }
                }
            } else {
                PropertyUtils.setProperty(destination, field.getName(), value);
            }
        } catch (NoSuchMethodException e) {
            LOG.debug("Method not found.", e);
        } catch (Exception e) {
            throw new VulpeSystemException(e);
        }
    }
}

From source file:org.vulpe.controller.AbstractVulpeBaseController.java

/**
 * Method to repair cached classes used by entity.
 *
 * @param entity//from   ww  w . j a v  a 2  s.c  o  m
 * @return Entity with cached values reloaded
 */
protected ENTITY repairCachedClasses(final ENTITY entity) {
    final List<Field> fields = VulpeReflectUtil.getFields(entity.getClass());
    for (final Field field : fields) {
        if (VulpeEntity.class.isAssignableFrom(field.getType())) {
            try {
                final VulpeEntity<ID> value = (VulpeEntity<ID>) PropertyUtils.getProperty(entity,
                        field.getName());
                if (VulpeValidationUtil.isNotEmpty(value) && !Modifier.isTransient(field.getModifiers())
                        && value.getClass().isAnnotationPresent(CachedClass.class)) {
                    final List<ENTITY> cachedList = vulpe.cache().classes()
                            .getAuto(value.getClass().getSimpleName());
                    if (VulpeValidationUtil.isNotEmpty(cachedList)) {
                        for (final ENTITY cached : cachedList) {
                            if (cached.getId().equals(value.getId())) {
                                PropertyUtils.setProperty(entity, field.getName(), cached);
                                break;
                            }
                        }
                    }
                }
            } catch (IllegalAccessException e) {
                LOG.error(e.getMessage());
            } catch (InvocationTargetException e) {
                LOG.error(e.getMessage());
            } catch (NoSuchMethodException e) {
                LOG.error(e.getMessage());
            }
        }
    }
    return entity;
}

From source file:org.vulpe.model.dao.impl.db4o.AbstractVulpeBaseDAODB4O.java

/**
 * Verified if entity property is empty and set to null;
 *
 * @param object/*from   ww  w .  ja va  2s .c o m*/
 */
public void emptyToNull(final Object object) {
    final List<Field> fields = VulpeReflectUtil.getFields(object.getClass());
    for (final Field field : fields) {
        try {
            if (field.isAnnotationPresent(SkipEmpty.class)) {
                continue;
            }
            if ((Modifier.isTransient(field.getModifiers()) || field.isAnnotationPresent(Transient.class))
                    && !field.isAnnotationPresent(QueryParameter.class) && !field.getType().isPrimitive()) {
                PropertyUtils.setProperty(object, field.getName(), null);
            } else {
                final Object value = PropertyUtils.getProperty(object, field.getName());
                if (value != null) {
                    if (String.class.isAssignableFrom(field.getType())) {
                        if (StringUtils.isEmpty(value.toString()) || "obj.id".equals(value)
                                || "null".equals(value)
                        /* || "%".equals(value) */) {
                            PropertyUtils.setProperty(object, field.getName(), null);
                        }
                    } else if (VulpeEntity.class.isAssignableFrom(value.getClass())
                            && !value.getClass().isAnnotationPresent(CreateIfNotExist.class)) {
                        emptyToNull(value);
                    }
                }
            }
        } catch (NoSuchMethodException e) {
            LOG.debug("Method not found.", e);
        } catch (Exception e) {
            throw new VulpeSystemException(e);
        }
    }
}

From source file:org.vulpe.model.dao.impl.db4o.AbstractVulpeBaseDAODB4O.java

/**
 * Repair relationship of entity./*from ww  w .  j a v  a2s .com*/
 *
 * @param <T>
 * @param entity
 */
protected <T> void repairRelationship(final T entity, final ObjectContainer container) {
    emptyToNull(entity);
    for (final Field field : VulpeReflectUtil.getFields(entity.getClass())) {
        if (!Modifier.isTransient(field.getModifiers())) {
            final Object value = VulpeReflectUtil.getFieldValue(entity, field.getName());
            if (value != null) {
                if (VulpeEntity.class.isAssignableFrom(field.getType())) {
                    try {
                        final VulpeEntity<Long> valueEntity = (VulpeEntity) value;
                        if (valueEntity.getId() != null) {
                            final VulpeEntity<Long> newEntity = (VulpeEntity<Long>) field.getType()
                                    .newInstance();
                            newEntity.setId(valueEntity.getId());
                            final ObjectSet objectSet = getObjectContainer().queryByExample(newEntity);
                            if (objectSet.hasNext()) {
                                PropertyUtils.setProperty(entity, field.getName(), objectSet.next());
                            }
                        } else {
                            if (value.getClass().isAnnotationPresent(CreateIfNotExist.class)) {
                                simpleMerge(container, value);
                            } else {
                                PropertyUtils.setProperty(entity, field.getName(), null);
                            }
                        }
                    } catch (Exception e) {
                        LOG.error(e.getMessage());
                    }
                } else if (Collection.class.isAssignableFrom(field.getType())) {
                    final Collection details = (Collection) value;
                    for (final Object object : details) {
                        if (object != null) {
                            if (VulpeEntity.class.isAssignableFrom(object.getClass())) {
                                try {
                                    final String attributeName = VulpeStringUtil
                                            .lowerCaseFirst(entity.getClass().getSimpleName());
                                    final VulpeEntity<Long> detail = (VulpeEntity<Long>) object;
                                    repair(detail, container);
                                    PropertyUtils.setProperty(detail, attributeName, entity);
                                    if (detail.getId() == null) {
                                        detail.setId(getId(detail));
                                    } else {
                                        final VulpeEntity<Long> valueEntity = (VulpeEntity) entity;
                                        final VulpeEntity<Long> newEntity = (VulpeEntity<Long>) entity
                                                .getClass().newInstance();
                                        newEntity.setId(valueEntity.getId());
                                        final VulpeEntity<Long> newDetailEntity = (VulpeEntity<Long>) object
                                                .getClass().newInstance();
                                        newDetailEntity.setId(detail.getId());
                                        PropertyUtils.setProperty(newDetailEntity, attributeName, newEntity);
                                        final ObjectSet objectSet = getObjectContainer()
                                                .queryByExample(newDetailEntity);
                                        if (objectSet.hasNext()) {
                                            final VulpeEntity<Long> persitedDetail = (VulpeEntity<Long>) objectSet
                                                    .get(0);
                                            container.ext().bind(detail, container.ext().getID(persitedDetail));
                                            container.store(detail);
                                        }
                                    }
                                } catch (Exception e) {
                                    LOG.error(e.getMessage());
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

From source file:org.vulpe.model.dao.impl.db4o.AbstractVulpeBaseDAODB4O.java

/**
 * Repair entity.//from   w ww .  j a  v  a  2s.  com
 *
 * @param <T>
 * @param entity
 * @param container
 * @throws Exception
 */
public <T> void repair(final T entity, final ObjectContainer container) {
    for (final Field field : VulpeReflectUtil.getFields(entity.getClass())) {
        if (VulpeEntity.class.isAssignableFrom(field.getType())) {
            final VulpeEntity<Long> value = VulpeReflectUtil.getFieldValue(entity, field.getName());
            if (value != null) {
                try {
                    if (value.getId() != null) {
                        final VulpeEntity<Long> newObject = (VulpeEntity<Long>) value.getClass().newInstance();
                        newObject.setId(value.getId());
                        final ObjectSet objectSet = getObjectContainer().queryByExample(newObject);
                        if (objectSet.hasNext()) {
                            final VulpeEntity<Long> objectPersisted = (VulpeEntity<Long>) objectSet.get(0);
                            PropertyUtils.setProperty(entity, field.getName(), objectPersisted);
                        }
                    } else {
                        if (value.getClass().isAnnotationPresent(CreateIfNotExist.class)) {
                            simpleMerge(container, value);
                        } else {
                            PropertyUtils.setProperty(entity, field.getName(), null);
                        }
                    }
                } catch (Exception e) {
                    throw new VulpeSystemException(e);
                }
                repair(value, container);
            }
        }
    }
}

From source file:org.vulpe.model.dao.impl.jpa.AbstractVulpeBaseDAOJPA.java

/**
 *
 * @param <T>/* w  ww . ja va2  s  .c om*/
 * @param entity
 */
protected <T> void repairRelationship(final T entity) {
    final List<Field> fields = VulpeReflectUtil.getFields(entity.getClass());
    for (final Field field : fields) {
        final OneToMany oneToMany = field.getAnnotation(OneToMany.class);
        if (oneToMany != null) {
            try {
                final List<ENTITY> entities = (List<ENTITY>) PropertyUtils.getProperty(entity, field.getName());
                if (VulpeValidationUtil.isNotEmpty(entities)) {
                    for (final ENTITY entityChild : entities) {
                        repairRelationship(entityChild);
                        PropertyUtils.setProperty(entityChild, oneToMany.mappedBy(), entity);
                    }
                }
            } catch (Exception e) {
                LOG.error(e.getMessage());
            }
        }
    }
}

From source file:org.vulpe.model.dao.impl.jpa.AbstractVulpeBaseDAOJPA.java

private void loadRelationshipsMountEntities(final Relationship relationship, final List<ENTITY> entities,
        final List<ENTITY> childs, final Map<ID, ID> relationshipIds, final String parentName,
        final OneToMany oneToMany) {
    try {//w ww .  java2  s  . c om
        for (final ENTITY parent : entities) {
            if (VulpeValidationUtil.isEmpty(childs)) {
                PropertyUtils.setProperty(parent, relationship.property(), null);
            } else {
                final List<ENTITY> loadedChilds = new ArrayList<ENTITY>();
                for (final ENTITY child : childs) {
                    if (oneToMany != null) {
                        final ID parentId = (ID) relationshipIds.get(child.getId());
                        if (parent.getId().equals(parentId)) {
                            PropertyUtils.setProperty(child, parentName, parent);
                            loadedChilds.add(child);
                        }
                        PropertyUtils.setProperty(parent, relationship.property(), loadedChilds);
                    } else {
                        final VulpeEntity<ID> parentChild = (VulpeEntity<ID>) PropertyUtils.getProperty(parent,
                                relationship.property());
                        if (VulpeValidationUtil.isNotEmpty(parentChild)
                                && child.getId().equals(parentChild.getId())) {
                            PropertyUtils.setProperty(parent, relationship.property(), child);
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        LOG.error(e.getMessage());
    }
}

From source file:pe.labtech.einvoice.api.restful.RestTools.java

public static void tryset(DocumentInfo di, Object name, Object value) {
    try {//from  w ww. j a v  a  2 s  . com
        PropertyUtils.setProperty(di, name.toString(), value);
    } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException
            | IllegalArgumentException ex) {
        //irrelevant since only valid properties will be mapped
        Logger.getLogger(RestHelper.class.getName()).log(Level.FINEST, ex,
                () -> "Invalid property " + name + " in DocumentInfo");
    }
}

From source file:ru.runa.wf.logic.bot.DatabaseTaskHandler.java

private Map<String, Object> extractResultsToProcessVariables(User user, VariableProvider variableProvider,
        Function<Integer, Object> getValueAtIndex, AbstractQuery query) throws Exception {
    Map<String, Object> outputVariables = Maps.newHashMap();
    for (int i = 0; i < query.getResultVariableCount(); i++) {
        Result result = query.getResultVariable(i);
        int resultIndex = result.getOutParameterIndex() <= 0 ? i + 1 : result.getOutParameterIndex();
        Object newValue = getValueAtIndex.apply(resultIndex);
        Object variableValue = variableProvider.getValue(result.getVariableName());
        if (result instanceof SwimlaneResult) {
            String fieldName = result.getFieldName();
            Actor actor = null;//w ww. jav a 2s .  c o m
            if ("code".equals(fieldName)) {
                actor = TypeConversionUtil.convertToExecutor(newValue, new DelegateExecutorLoader(user));
            } else if ("id".equals(fieldName)) {
                actor = Delegates.getExecutorService().getExecutor(user, (Long) newValue);
            } else {
                actor = Delegates.getExecutorService().getExecutorByName(user, (String) newValue);
            }
            newValue = Long.toString(actor.getCode());
        } else if (result.isFieldSetup()) {
            // diff with SQLActionHandler
            // if (variableValue == null) {
            // if ("name".equals(result.getFieldName()) || "data".equals(result.getFieldName()) || "contentType".equals(result.getFieldName())) {
            // variableValue = new FileVariable("file", "application/octet-stream");
            // variableProvider.add(result.getVariableName(), variableValue);
            // }
            // }
            PropertyUtils.setProperty(variableValue, result.getFieldName(), newValue);
            newValue = variableValue;
        }
        if (newValue instanceof Blob) {
            ObjectInputStream ois = new ObjectInputStream(((Blob) newValue).getBinaryStream());
            newValue = ois.readObject();
            Closeables.closeQuietly(ois);
        }
        if (newValue instanceof byte[]) {
            ByteArrayInputStream bais = new ByteArrayInputStream((byte[]) newValue);
            ObjectInputStream ois = new ObjectInputStream(bais);
            newValue = ois.readObject();
            Closeables.closeQuietly(ois);
        }
        outputVariables.put(result.getVariableName(), newValue);
    }
    return outputVariables;
}

From source file:ru.runa.wfe.extension.handler.SqlActionHandler.java

private Map<String, Object> extractResults(MapDelegableVariableProvider in, ResultSet resultSet,
        AbstractQuery query) throws Exception {
    val out = new HashMap<String, Object>();
    for (int i = 0; i < query.getResultVariableCount(); i++) {
        Result result = query.getResultVariable(i);
        String fieldName = result.getFieldName();
        Object newValue = resultSet.getObject(i + 1);
        log.debug("Obtaining result " + fieldName + " from " + newValue);
        if (result instanceof SwimlaneResult) {
            Actor actor;//from  w  w w. j  a  va 2s  .  c  o m
            if ("code".equals(fieldName)) {
                actor = executorDao.getActorByCode(((Number) newValue).longValue());
            } else if ("id".equals(fieldName)) {
                actor = executorDao.getActor(((Number) newValue).longValue());
            } else {
                actor = executorDao.getActor(newValue.toString());
            }
            newValue = Long.toString(actor.getCode());
        } else if (result.isFieldSetup()) {
            Object variableValue = in.getValue(result.getVariableName());
            if (variableValue == null) {
                if ("name".equals(result.getFieldName()) || "data".equals(result.getFieldName())
                        || "contentType".equals(result.getFieldName())) {
                    variableValue = new FileVariableImpl("file", "application/octet-stream");
                    in.add(result.getVariableName(), variableValue);
                }
            }
            PropertyUtils.setProperty(variableValue, fieldName, newValue);
            newValue = variableValue;
        }
        if (newValue instanceof Blob) {
            ObjectInputStream ois = new ObjectInputStream(((Blob) newValue).getBinaryStream());
            newValue = ois.readObject();
            Closeables.closeQuietly(ois);
        }
        if (newValue instanceof byte[]) {
            ByteArrayInputStream bais = new ByteArrayInputStream((byte[]) newValue);
            ObjectInputStream ois = new ObjectInputStream(bais);
            newValue = ois.readObject();
            Closeables.closeQuietly(ois);
        }
        in.add(result.getVariableName(), newValue);
        out.put(result.getVariableName(), newValue);
    }
    return out;
}