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

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

Introduction

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

Prototype

public static boolean isReadable(Object bean, String name) 

Source Link

Document

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

For more details see PropertyUtilsBean.

Usage

From source file:org.openmrs.module.clinicalsummary.db.hibernate.HibernateUtilDAO.java

/**
 * @see UtilDAO#getOrderedObs(java.util.Map, java.util.Date, java.util.Date)
 *//*w  w  w .j av  a 2 s .co  m*/
@Override
@SuppressWarnings("unchecked")
public List<Object[]> aggregateOrderedObs(final Map<String, Collection<OpenmrsObject>> restrictions,
        final Collection<String> groupingProperties, final StatusType statusType, final Date startTime,
        final Date endTime) throws DAOException {

    Criteria criteria = sessionFactory.getCurrentSession().createCriteria(OrderedObs.class);

    // hack to prevent results for tests ordered concept when grouping results on concept
    if (groupingProperties.contains("concept"))
        criteria.add(Restrictions
                .not(Restrictions.eq("concept", CacheUtils.getConcept(EvaluableNameConstants.TESTS_ORDERED))));

    if (MapUtils.isNotEmpty(restrictions)) {
        OrderedObs orderedObs = new OrderedObs();
        for (String property : restrictions.keySet()) {
            Collection<OpenmrsObject> objects = restrictions.get(property);
            if (CollectionUtils.isNotEmpty(objects) && PropertyUtils.isReadable(orderedObs, property))
                criteria.add(Restrictions.in(property, objects));
        }
    }

    if (statusType != null)
        criteria.add(Restrictions.eq("status", statusType));

    if (startTime != null)
        criteria.add(Restrictions.ge("orderedDatetime", startTime));

    if (endTime != null)
        criteria.add(Restrictions.le("orderedDatetime", endTime));

    ProjectionList projectionList = Projections.projectionList();
    for (String groupingProperty : groupingProperties) {
        // group by the property and order by the same property desc and the property must not null
        criteria.add(Restrictions.isNotNull(groupingProperty));
        projectionList.add(Projections.groupProperty(groupingProperty));
        criteria.addOrder(Order.asc(groupingProperty));
    }
    // add the row count projection to the projection list
    projectionList.add(Projections.rowCount());
    criteria.setProjection(projectionList);

    return criteria.list();
}

From source file:org.openmrs.module.mohregister.db.hibernate.HibernateCoreDAO.java

@SuppressWarnings("unchecked")
public List<Encounter> getPatientEncounters(final Integer patientId,
        final Map<String, Collection<OpenmrsObject>> restrictions) throws DAOException {
    Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Obs.class);
    criteria.add(Restrictions.eq("personId", patientId));

    criteria.addOrder(Order.desc("obsDatetime"));

    Obs observation = new Obs();
    for (String property : restrictions.keySet()) {
        Collection<OpenmrsObject> propertyValues = restrictions.get(property);
        if (CollectionUtils.isNotEmpty(propertyValues) && PropertyUtils.isReadable(observation, property)) {
            criteria.add(Restrictions.in(property, propertyValues));
            criteria.addOrder(Order.asc(property));
        }//  ww  w  . j  a  v a2  s .c  o m
    }

    criteria.add(Restrictions.eq("voided", Boolean.FALSE));
    return criteria.list();
}

From source file:org.openmrs.module.mohregister.db.hibernate.HibernateCoreDAO.java

@SuppressWarnings("unchecked")
public List<Obs> getPatientObservations(final Integer patientId,
        final Map<String, Collection<OpenmrsObject>> restrictions) throws DAOException {
    // create a hibernate criteria on the encounter object
    Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Encounter.class);
    // restrict the encounter that will be returned to specific patient only
    criteria.add(Restrictions.eq("patientId", patientId));

    // default ordering for the returned encounter is descending on encounter datetime
    criteria.addOrder(Order.desc("encounterDatetime"));

    // create a dummy encounter object
    Encounter encounter = new Encounter();
    // iterate over each property in the restriction map
    for (String property : restrictions.keySet()) {
        // get the actual object that will restrict the encounter. this will contains the list of encounter type or list of location
        // or list of provider (currently not being used) passed from caller
        Collection<OpenmrsObject> propertyValues = restrictions.get(property);
        // check to make sure the list is not empty and the property is readable. example of the property for encounter are
        // encounterType or location of the encounter
        if (CollectionUtils.isNotEmpty(propertyValues) && PropertyUtils.isReadable(encounter, property)) {
            // create a restriction on the property with the above list as the value
            criteria.add(Restrictions.in(property, propertyValues));
            // add ordering on that property to prevent slowness when ordering only on encounter datetime (1.6.x only)
            criteria.addOrder(Order.asc(property));
        }// ww w.j  ava  2 s  .co m
    }

    // exclude all voided encounters
    criteria.add(Restrictions.eq("voided", Boolean.FALSE));
    return criteria.list();
}

From source file:org.openscada.da.server.spring.DataItemInputOutputProperty.java

@Override
public void afterPropertiesSet() throws Exception {
    // contract/*from  w  w  w . j a va 2  s  .c om*/
    Assert.notNull(this.bean, "'bean' must not be null");
    Assert.notNull(this.property, "'property' must not be null");
    Assert.isTrue(PropertyUtils.isReadable(this.bean, this.property));
    Assert.isTrue(PropertyUtils.isWriteable(this.bean, this.property));
    final Object value = PropertyUtils.getProperty(this.bean, this.property);
    updateData(Variant.valueOf(value), new HashMap<String, Variant>(), AttributeMode.SET);
    notifyData(Variant.valueOf(value), new HashMap<String, Variant>(), true);
}

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()));
                    }/*w  w w .  jav  a 2  s.  co 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.tinygroup.jdbctemplatedslsession.SimpleDslSession.java

private <T> Map<String, Object> convertMap(T param) throws Exception {
    Map<String, Object> description = new LinkedHashMap<String, Object>();
    PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(param);
    for (int i = 0; i < descriptors.length; i++) {
        String name = descriptors[i].getName();
        if (PropertyUtils.isReadable(param, name) && PropertyUtils.isWriteable(param, name)) {
            if (descriptors[i].getReadMethod() != null) {
                Object value = PropertyUtils.getProperty(param, name);
                description.put(name, value);
                description.put(nameStrategy.getFieldName(name), value);
            }//from w  w w .j a  va2  s. c  o  m
        }
    }
    return description;
}

From source file:psiprobe.tools.logging.DefaultAccessor.java

/**
 * Gets the property.//from   www  .  j  a v a 2 s  .c om
 *
 * @param obj the obj
 * @param name the name
 * @param defaultValue the default value
 * @return the property
 */
protected Object getProperty(Object obj, String name, Object defaultValue) {
    try {
        return PropertyUtils.isReadable(obj, name) ? PropertyUtils.getProperty(obj, name) : defaultValue;
    } catch (IllegalArgumentException | IllegalAccessException | InvocationTargetException
            | NoSuchMethodException e) {
        logger.error("", e);
    }
    logger.debug("Could not access property '{}' of object '{}'", name, obj);
    return defaultValue;
}

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

/**
 * /*from   w  w  w  .  j  a v a  2s  .  c om*/
 * @param orig
 * @return a collection with the {@link PropertyDescriptor} s that changed
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 * @throws NoSuchMethodException
 * @throws TaskNotVisibleException
 */
public Collection<String> copyPropertiesFrom(Object orig) throws IllegalAccessException,
        InvocationTargetException, NoSuchMethodException, TaskNotVisibleException {
    Set<PropertyDescriptor> propertyDescriptorsThatChanged = new HashSet<PropertyDescriptor>();

    Object dest = this;

    if (orig == null) {
        throw new IllegalArgumentException("No origin bean specified");
    }
    PropertyDescriptor origDescriptors[] = PropertyUtils.getPropertyDescriptors(orig);
    for (PropertyDescriptor origDescriptor : origDescriptors) {
        String name = origDescriptor.getName();
        if (PropertyUtils.isReadable(orig, name)) {
            if (PropertyUtils.isWriteable(dest, name)) {
                Object valueDest = PropertyUtils.getSimpleProperty(dest, name);
                Object valueOrigin = PropertyUtils.getSimpleProperty(orig, name);
                if (valueOrigin != null && valueOrigin.getClass().getPackage().getName()
                        .equalsIgnoreCase("org.eclipse.egit.github.core"))
                    continue; //let's skip the properties with egit core objects (they shall be copied from a custom overriden version of this method)
                if (valueOrigin instanceof Date)
                    valueOrigin = new DateTime(valueOrigin);
                if (Objects.equal(valueDest, valueOrigin) == false)
                    propertyDescriptorsThatChanged.add(origDescriptor);
                try {
                    //let's see if this is actually a Date, if so, let's convert it
                    PropertyUtils.setSimpleProperty(dest, name, valueOrigin);
                } catch (IllegalArgumentException ex) {
                    throw new Error("setSimpleProperty returned an exception, dest: "
                            + dest.getClass().getName() + " oid: " + ((DomainObject) dest).getExternalId()
                            + " name : " + name + " valueOrig: " + valueOrigin, ex);
                }
                LOGGER.trace("Copied property " + name + " from " + orig.getClass().getName() + " object to a "
                        + dest.getClass().getName() + " oid: " + getExternalId());
            }
        }
    }

    return Collections2.transform(propertyDescriptorsThatChanged, new Function<PropertyDescriptor, String>() {
        @Override
        public String apply(PropertyDescriptor propertyDescriptor) {
            if (propertyDescriptor == null) {
                return null;
            }
            return propertyDescriptor.getName();

        }
    });
}

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

public void copyPropertiesTo(Object dest) throws IllegalAccessException, InvocationTargetException,
        NoSuchMethodException, TaskNotVisibleException {
    Set<PropertyDescriptor> propertyDescriptorsThatChanged = new HashSet<PropertyDescriptor>();

    Object orig = this;
    checkNotNull(dest);/*from   www  .  j av a 2s.c  o  m*/

    PropertyDescriptor origDescriptors[] = PropertyUtils.getPropertyDescriptors(orig);
    for (PropertyDescriptor origDescriptor : origDescriptors) {
        String name = origDescriptor.getName();
        if (PropertyUtils.isReadable(orig, name)) {
            PropertyDescriptor destDescriptor = PropertyUtils.getPropertyDescriptor(dest,
                    origDescriptor.getName());
            if (PropertyUtils.isWriteable(dest, name) || (destDescriptor != null
                    && MiscUtils.getWriteMethodIncludingFlowStyle(destDescriptor, dest.getClass()) != null)) {
                Object valueDest = PropertyUtils.getSimpleProperty(dest, name);
                Object valueOrigin = PropertyUtils.getSimpleProperty(orig, name);

                LOGGER.debug("OrigDescriptor PropertyType: " + origDescriptor.getPropertyType().getName());
                //                    System.out.println("OrigDescriptor PropertyType: " + origDescriptor.getPropertyType().getName());
                //let's ignore the properties were the values are our domain packages
                if (valueOrigin != null && (SynchableObject.class.isAssignableFrom(valueOrigin.getClass()))) {
                    //                        System.out.println("Skipping");
                    continue; //let's skip these properties
                }
                if (SynchableObject.class.isAssignableFrom(origDescriptor.getPropertyType())) {
                    //                        System.out.println("Skipping");
                    continue;
                }
                if (origDescriptor instanceof IndexedPropertyDescriptor) {
                    IndexedPropertyDescriptor indexedPropertyDescriptor = (IndexedPropertyDescriptor) origDescriptor;
                    //                        System.out.println("OrigDescriptor IndexedPropertyDescriptor: " + indexedPropertyDescriptor.getName());
                    if (SynchableObject.class
                            .isAssignableFrom(indexedPropertyDescriptor.getIndexedPropertyType())) {
                        //                            System.out.println("Skipping");
                        continue;
                    }

                }

                //let's ignore all of the dates - as they should be filled by
                //the system
                if (valueOrigin instanceof LocalTime)
                    continue;
                if (Objects.equal(valueDest, valueOrigin) == false)
                    propertyDescriptorsThatChanged.add(origDescriptor);
                try {
                    if (PropertyUtils.isWriteable(dest, name) == false) {
                        //let's use the flow version
                        Class<?> origPropertyType = origDescriptor.getPropertyType();
                        Method writeMethodIncludingFlowStyle = MiscUtils
                                .getWriteMethodIncludingFlowStyle(destDescriptor, dest.getClass());
                        if (Arrays.asList(writeMethodIncludingFlowStyle.getParameterTypes())
                                .contains(origPropertyType)) {
                            writeMethodIncludingFlowStyle.invoke(dest, valueOrigin);
                        } else {
                            continue;
                        }

                    } else {
                        PropertyUtils.setSimpleProperty(dest, name, valueOrigin);

                    }
                } catch (IllegalArgumentException ex) {
                    throw new Error("setSimpleProperty returned an exception, dest: "
                            + dest.getClass().getName() + " name : " + name + " valueOrig: " + valueOrigin, ex);
                }
                LOGGER.trace("Copied property " + name + " from " + orig.getClass().getName() + " object to a "
                        + dest.getClass().getName() + " oid: " + getExternalId());
            }
            //                System.out.println("--");
        }
    }

}

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

/**
 * //from  w  ww  .  j  av a 2  s .co  m
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 * @throws NoSuchMethodException
 * @throws TaskNotVisibleException
 * @throws IllegalArgumentException if the property descriptors of the arguments differ
 * 
 * @return a collection of {@link PropertyDescriptor} that changed, or an empty collection
 */
public static Collection<PropertyDescriptor> propertiesEqual(Object object1, Object object2)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException,
        TaskNotVisibleException, IllegalArgumentException {

    List<PropertyDescriptor> changedDescriptors = new ArrayList<>();

    if (object1 == null || object2 == null) {
        throw new IllegalArgumentException("Both objects must be non null");
    }
    PropertyDescriptor object1Descriptors[] = PropertyUtils.getPropertyDescriptors(object1);
    PropertyDescriptor object2Descriptors[] = PropertyUtils.getPropertyDescriptors(object2);

    //let's make sure that they match
    checkArgument(ObjectUtils.equals(object1Descriptors, object2Descriptors),
            "Error, object1 : " + object1.getClass().getSimpleName() + " and object2 : "
                    + object2.getClass().getSimpleName() + " don't match");

    for (PropertyDescriptor object1Descriptor : object1Descriptors) {
        String name = object1Descriptor.getName();
        if (PropertyUtils.isReadable(object1, name) && PropertyUtils.isReadable(object2, name)) {

            //if both are readable, let's check on the values
            Object valueObject1 = PropertyUtils.getSimpleProperty(object1, name);
            Object valueObject2 = PropertyUtils.getSimpleProperty(object2, name);
            //                if (isGitHubObject(valueObject1) || isGitHubObject(valueObject2))
            //                    continue; //let's skip the GitHub properties, we won't be able to compare that

            if (!ObjectUtils.equals(valueObject1, valueObject2))
                changedDescriptors.add(object1Descriptor);
        }
    }
    return changedDescriptors;
}