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

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

Introduction

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

Prototype

public static Object getSimpleProperty(Object bean, String name)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException 

Source Link

Document

Return the value of the specified simple property of the specified bean, with no type conversions.

For more details see PropertyUtilsBean.

Usage

From source file:org.talend.commons.utils.data.sort.MultiplePropertiesBeanComparator.java

private int compare(String property, Object object1, Object object2)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    Object value1 = null;//from  w w w. j  a v  a  2s.c  o m
    Object value2 = null;
    if (property != null && !property.equals("")) { //$NON-NLS-1$
        if (object1 != null) {
            value1 = PropertyUtils.getSimpleProperty(object1, property);
        }
        if (object2 != null) {
            value2 = PropertyUtils.getSimpleProperty(object2, property);
        }
    }
    return checkNullsAndCompare(value1, value2);
}

From source file:org.tinygroup.commons.beanutil.BeanUtil.java

public static Object deepCopy(Object orig) throws Exception {
    Object dest = orig.getClass().newInstance();
    PropertyDescriptor[] origDescriptors = PropertyUtils.getPropertyDescriptors(orig);
    for (PropertyDescriptor propertyDescriptor : origDescriptors) {
        String name = propertyDescriptor.getName();
        if (PropertyUtils.isReadable(orig, name) && PropertyUtils.isWriteable(dest, name)) {
            Object value = PropertyUtils.getSimpleProperty(orig, name);
            Object valueDest = null;
            if (value != null && canDeepCopyObject(value)) {
                if (value instanceof Collection) {
                    Collection coll = (Collection) value;
                    Collection newColl = createApproximateCollection(value);
                    Iterator it = coll.iterator();
                    while (it.hasNext()) {
                        newColl.add(deepCopy(it.next()));
                    }/*ww  w.  j  a  v a  2 s  .c  o m*/
                    valueDest = newColl;
                } else if (value.getClass().isArray()) {
                    Object[] values = (Object[]) value;
                    Object[] newValues = new Object[values.length];
                    for (int i = 0; i < newValues.length; i++) {
                        newValues[i] = deepCopy(values[i]);
                    }
                    valueDest = newValues;
                } else if (value instanceof Map) {
                    Map map = (Map) value;
                    Map newMap = createApproximateMap(map);
                    for (Object key : map.keySet()) {
                        newMap.put(key, deepCopy(map.get(key)));
                    }
                    valueDest = newMap;
                } else {
                    valueDest = deepCopy(value);
                }
            } else {
                valueDest = value;
            }
            PropertyUtils.setSimpleProperty(dest, name, valueDest);
        }

    }
    return dest;

}

From source file:org.wickedsource.wickedforms.model.binding.PropertyBinding.java

@Override
@SuppressWarnings("unchecked")
public T getValue() {
    try {//from   w w  w . j  ava 2 s . c  o m
        return (T) PropertyUtils.getSimpleProperty(boundObject, property);
    } catch (Exception e) {
        throw new IllegalStateException(
                String.format("Binding error! Getting property '%s' from bound object of class %s failed!",
                        property, boundObject.getClass()),
                e);
    }
}

From source file:org.xaloon.core.jpa.audit.JpaAuditFacade.java

private void createAuditDetails(AuditEntity ae, Object auditObject, Class<?> parentClass) {
    if (parentClass == null) {
        return;// ww w  .ja  v  a 2 s . c  om
    }
    for (Field field : parentClass.getDeclaredFields()) {
        Auditable annotation = field.getAnnotation(Auditable.class);
        if (annotation != null) {
            String fieldName = field.getName();
            try {
                if (annotation.index() > -1) {
                    Object value = PropertyUtils.getIndexedProperty(auditObject, fieldName, annotation.index());
                    createAuditDetails(ae, value, value.getClass());
                } else {
                    Object value = PropertyUtils.getSimpleProperty(auditObject, fieldName);
                    AuditEntityItem details = newAuditEntityItem();
                    details.setAuditEntity(ae);
                    details.setCreateDate(new Date());
                    details.setUpdateDate(new Date());
                    details.setName(parentClass.getName() + "." + fieldName);
                    if (value != null) {
                        details.setValue(value.toString());
                    }
                    details.setKey(annotation.key());
                    ae.getAuditEntityItems().add(details);
                }
            } catch (Exception e) {
                logger.error("Exception while getting audit field value", e);
            }
        }
    }
    createAuditDetails(ae, auditObject, parentClass.getSuperclass());
}

From source file:org.xmlactions.mapping.bean_to_xml.MapperAttribute.java

public Element buildXml(BeanToXml beanToXml, Element parent, Object mapClasses) {
    try {//  w  ww.j a  v  a  2s.c o  m
        Object property = PropertyUtils.getSimpleProperty(mapClasses, getProperty());
        Object populatorObject = getPopulator(beanToXml);
        if (populatorObject != null) {
            if (populatorObject instanceof Populator) {
                Populator populator = (Populator) populatorObject;
                Element element = useAction(beanToXml, populator.getKeyvalues(), populator.getClas(), parent,
                        property, getProperty());
            } else {
                Element element = useAction(beanToXml, null, "" + populatorObject, parent, property,
                        getProperty());
            }

        } else {
            BeanToXmlUtils.addAttribute(parent, getPrefix(), getName(), property.toString());
        }
    } catch (NullPointerException ex) {
        log.error("NullPointerException:" + toString());
    } catch (Exception ex) {
        throw new IllegalArgumentException(ex.getMessage() + ":" + toString(), ex);
    }
    return parent;
}

From source file:org.xmlactions.mapping.bean_to_xml.MapperElement.java

public Element buildXml(BeanToXml beanToXml, Element parent, Object mapClasses) {
    log.debug(toString());//from  w ww.  j a  va2s.c  o  m
    Element element = null;
    try {
        Object property = PropertyUtils.getSimpleProperty(mapClasses, getProperty());
        if (property != null) {
            log.debug("property object = " + property.getClass().getName());
            // see if we have a handler for this property
            Object populatorObject = getPopulatorQuietly(beanToXml);
            if (populatorObject != null) {
                if (populatorObject instanceof Populator) {
                    Populator populator = (Populator) populatorObject;
                    element = useAction(beanToXml, populator.getKeyvalues(), populator.getClas(), parent,
                            property, getProperty());
                } else {
                    element = useAction(beanToXml, null, "" + populatorObject, parent, property, getProperty());
                }
            } else {
                if (property instanceof List) {
                    element = useAction(beanToXml, null, defaultListPopulator, parent, property, getProperty());
                } else if (property instanceof Object[]) {
                    element = useAction(beanToXml, null, defaultArrayPopulator, parent, property,
                            getProperty());
                } else {
                    Bean bean = beanToXml.findBeanByName(this.getBean_ref());
                    element = bean.processBean(beanToXml, parent, property, getPrefix(), getName());
                }
            }
        }
    } catch (NullPointerException ex) {
        log.error("NullPointerException:" + toString());
    } catch (Exception ex) {
        throw new IllegalArgumentException(ex.getMessage() + ":" + toString(), ex);
    }
    return element;
}

From source file:play.modules.resteasy.crud.RESTResource.java

/**
 * Override this method to implement your own endpoint, otherwise it will be magically bound to the
 * right path and parameters for adding an entity.
 * @param model the model type//  w  ww .ja  v  a 2  s .c  o m
 * @param elem the new entity
 * @return a response with no content
 */
public <T extends Model> Response add(Class<T> model, final T elem, UriInfo uriInfo) {
    checkPermission(elem, "insert");
    // check non-editable field
    walkProperties(model, new PropertyWalker() {
        @Override
        public void walk(Property property, Field field, CRUDField crud) {
            Object newValue;
            try {
                newValue = PropertyUtils.getSimpleProperty(elem, property.name);
            } catch (Exception e) {
                throw toThrowable(internalError(e, "Failed to get property %s", property.name));
            }
            // if that field is not editable, let us barf
            if (crud == null || !crud.editable())
                checkEmpty(newValue);
        }
    });
    elem._save();
    // now get the link to the new element
    UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
    URI uri = uriBuilder.path(getClass()).path(getClass(), "get").build(elem._key());
    return created(uri);
}

From source file:play.modules.resteasy.crud.RESTResource.java

/**
 * Override this method to implement your own endpoint, otherwise it will be magically bound to the
 * right path and parameters for editing an entity.
 * @param model the model type//from ww w  .  jav a  2s . c  o m
 * @param id the entity id to update
 * @param elem the new values for the entity
 * @return a response with no content
 */
public <T extends Model> Response edit(Class<T> model, Object id, final T elem) {
    Factory factory = Manager.factoryFor(model);
    @SuppressWarnings("unchecked")
    final T elemFromDB = (T) factory.findById(id);
    checkForUpdate(elem, elemFromDB);
    // copy every field
    walkProperties(model, new PropertyWalker() {
        @Override
        public void walk(Property property, Field field, CRUDField crud) {
            Object newValue;
            try {
                newValue = PropertyUtils.getSimpleProperty(elem, property.name);
            } catch (Exception e) {
                throw toThrowable(internalError(e, "Failed to get property %s", property.name));
            }
            // if that field is not editable, let us barf
            if (crud == null || !crud.editable())
                checkEmpty(newValue);
            else {
                // we can set it
                try {
                    PropertyUtils.setSimpleProperty(elemFromDB, property.name, newValue);
                } catch (Exception e) {
                    throw toThrowable(internalError(e, "Failed to set property %s", property.name));
                }
            }
        }
    });
    elemFromDB._save();
    return noContent();
}

From source file:pt.ist.fenix.service.services.TransferDomainObjectProperty.java

@Atomic
public static void run(DomainObject srcObject, DomainObject dstObject, String slotName)
        throws FenixServiceException {
    AccessControl.check(RolePredicates.MANAGER_PREDICATE);
    try {/*from   w w w  .  ja v a 2  s .  co m*/
        Object srcProperty = PropertyUtils.getSimpleProperty(srcObject, slotName);

        if (srcProperty != null && srcProperty instanceof Collection) {
            Collection srcCollection = (Collection) srcProperty;

            Object dstProperty = PropertyUtils.getSimpleProperty(dstObject, slotName);
            if (dstProperty instanceof Collection) {
                Collection dstCollection = (Collection) dstProperty;
                dstCollection.addAll(srcCollection);
            }

        } else {
            PropertyUtils.setSimpleProperty(dstObject, slotName, srcProperty);
        }
    } catch (InvocationTargetException e) {
        if (e.getTargetException() != null) {
            if (e.getTargetException() instanceof WriteOnReadError) {
                throw ((WriteOnReadError) e.getTargetException());
            }
            throw new FenixServiceException(e.getTargetException());
        }
        throw new FenixServiceException(e);
    } catch (IllegalAccessException e) {
        throw new FenixServiceException(e);
    } catch (NoSuchMethodException e) {
        throw new FenixServiceException(e);
    }

}

From source file:pt.ist.maidSyncher.domain.SynchableObject.java

private static void generateSyncEvent(final SynchableObject toProccessAndReturn,
        final Collection<String> changedDescriptors, final Object apiObject) throws SyncEventIllegalConflict {
    final SynchableObject originObject = toProccessAndReturn;
    SyncEvent.TypeOfChangeEvent typeOfChange = null;
    DSIObject dsiObject = toProccessAndReturn.getDSIObject();
    if (dsiObject == null || dsiObject.getLastSynchedAt() == null) {
        typeOfChange = TypeOfChangeEvent.CREATE;
    }//from w ww.j  ava  2s .  c  om
    try {
        dsiObject = toProccessAndReturn.findOrCreateDSIObject();

    } catch (UnsupportedOperationException ex) {
        LOGGER.debug(toProccessAndReturn.getClass().getName() + " doesn't support Synch");
    }
    if (dsiObject != null && dsiObject.getLastSynchedAt() != null) {
        typeOfChange = TypeOfChangeEvent.UPDATE;
    }
    if (dsiObject != null) {
        if (typeOfChange == null) {
            typeOfChange = TypeOfChangeEvent.UPDATE;
        }

        SyncUniverse syncUniverse = null;
        if (originObject instanceof pt.ist.maidSyncher.domain.activeCollab.ACObject) {
            syncUniverse = SyncUniverse.GITHUB;
        } else if (originObject instanceof GHObject) {
            syncUniverse = SyncUniverse.ACTIVE_COLLAB;
        }
        SyncEvent syncEvent = new SyncEvent(toProccessAndReturn.getUpdatedAtDate(), typeOfChange,
                changedDescriptors, dsiObject, new APIObjectWrapper() {

                    @Override
                    public void validateAPIObject() throws SyncEventOriginObjectChanged {
                        try {

                            Object currentAPIObject = null;

                            if (apiObject instanceof ACObject) {
                                //let's get the object from the repository
                                ACObject acObject = (ACObject) apiObject;
                                Constructor<? extends Object> constructor = null;
                                JSONObject jsonObject = null;

                                jsonObject = (JSONObject) acRequestProcessor.processGet(acObject.getUrl());
                                constructor = apiObject.getClass().getConstructor(JSONObject.class);
                                currentAPIObject = constructor.newInstance(jsonObject);

                            } else {
                                //if it's not an active collab one, let's assume it's a GH
                                GitHubRequest gitHubRequest = new GitHubRequest();
                                getPropertyDescriptorNameAndCheckItExists(apiObject, "url");
                                String uri = null;
                                uri = (String) PropertyUtils.getSimpleProperty(apiObject, "url");
                                gitHubRequest.setUri(uri);
                                currentAPIObject = MaidRoot.getGitHubClient().get(gitHubRequest).getBody();

                            }

                            Collection<PropertyDescriptor> changedProperties;
                            changedProperties = propertiesEqual(apiObject, currentAPIObject);
                            if (changedProperties.isEmpty() == false) {
                                String changedDescriptors = "";
                                for (PropertyDescriptor changedDescriptor : changedProperties)
                                    changedDescriptors += " " + changedDescriptor.getName();

                                throw new SyncEventOriginObjectChanged(
                                        "Origin object: " + originObject.getClass().getSimpleName()
                                                + " unequal descriptors:" + changedDescriptors);

                            }
                        } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
                                | InvocationTargetException | IOException | NoSuchMethodException
                                | SecurityException e) {
                            throw new SyncEventOriginObjectChanged(
                                    "Could not assert if Origin object changed. Origin obj: "
                                            + apiObject.getClass().getSimpleName(),
                                    e);
                        }

                    }

                    @Override
                    public Object getAPIObject() {
                        return apiObject;
                    }
                }, syncUniverse, originObject);
        addSyncEvent(syncEvent);

    }
}