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.openmobster.core.mobileObject.xml.MobileObjectSerializer.java

private Object initializeIndexedProperty(Object parentObject, String property,
        PropertyDescriptor propertyMetaData, List<ArrayMetaData> objectMetaData, String propertyPath)
        throws Exception {
    Object element = null;/* w  ww .  java 2s  . co m*/

    //ArrayUri
    String arrayUri = null;
    Integer arrayIndex = 0;
    if (propertyPath.endsWith("]")) {
        int lastIndex = propertyPath.lastIndexOf('[');
        arrayUri = propertyPath.substring(0, lastIndex);
        arrayIndex = Integer.parseInt(propertyPath.substring(lastIndex + 1, propertyPath.length() - 1).trim());
    }
    ArrayMetaData arrayMetaData = null;
    for (ArrayMetaData local : objectMetaData) {
        if (local.arrayUri.equals(arrayUri)) {
            arrayMetaData = local;
            break;
        }
    }

    //Find the Class of the elementType
    String elementTypeName = arrayMetaData.arrayClass;
    Class elementType = null;
    if (elementTypeName != null && elementTypeName.trim().length() > 0 && !elementTypeName.equals("null")) {
        elementType = Thread.currentThread().getContextClassLoader().loadClass(arrayMetaData.arrayClass);
    } else {
        //Figure out the element type from the Property Information
        //This happens when a brand new object is created on the device and is being synced
        //with the backend
        //The MobileObject Framework on the device does not know about any Class level information
        //of the remote bean
        //The Limitation of this is that:
        //
        //* Indexed Properties if Collections must be Parameterized with Concrete Types
        //* Indexed Properties if Arrays must be Arrays of Concrete Types
        if (!propertyMetaData.getPropertyType().isArray()) {
            ParameterizedType returnType = (ParameterizedType) propertyMetaData.getReadMethod()
                    .getGenericReturnType();
            Type[] actualTypes = returnType.getActualTypeArguments();
            for (Type actualType : actualTypes) {
                elementType = (Class) actualType;
            }
        } else {
            elementType = propertyMetaData.getPropertyType().getComponentType();
        }
    }

    //An IndexedProperty
    Object indexedProperty = PropertyUtils.getProperty(parentObject, propertyMetaData.getName());

    //Initialize the IndexedProperty (An Array or Collection)
    if (propertyMetaData.getPropertyType().isArray()) {
        int arraySize = arrayMetaData.arrayLength;
        if (indexedProperty == null) {
            //Initialize the Array with Size from Object Meta Data               
            PropertyUtils.setProperty(parentObject, propertyMetaData.getName(),
                    Array.newInstance(elementType, arraySize));
        } else {
            //Make sure the Array Size matches
            int actualSize = Array.getLength(indexedProperty);
            if (actualSize != arraySize) {
                //Re-set the existing Array
                PropertyUtils.setProperty(parentObject, propertyMetaData.getName(),
                        Array.newInstance(elementType, arraySize));
            }
        }
    } else {
        if (indexedProperty == null) {
            //Handle Collection Construction
            PropertyUtils.setProperty(parentObject, propertyMetaData.getName(), new ArrayList());
        }
    }

    //Check to see if the index specified by the field requires creation of new
    //element
    indexedProperty = PropertyUtils.getProperty(parentObject, propertyMetaData.getName());

    if (!propertyMetaData.getPropertyType().isArray()) {
        try {
            element = PropertyUtils.getIndexedProperty(parentObject, property);
        } catch (IndexOutOfBoundsException iae) {
            Object newlyInitialized = elementType.newInstance();
            ((Collection) indexedProperty).add(newlyInitialized);
            element = newlyInitialized;
        }
    } else {
        element = PropertyUtils.getIndexedProperty(parentObject, property);
        if (element == null) {
            Object newlyInitialized = elementType.newInstance();
            Array.set(indexedProperty, arrayIndex, newlyInitialized);
            element = newlyInitialized;
        }
    }

    return element;
}

From source file:org.openmrs.api.handler.OpenmrsObjectSaveHandler.java

/**
 * This sets the uuid property on the given OpenmrsObject if it is non-null.
 *
 * @see org.openmrs.api.handler.RequiredDataHandler#handle(org.openmrs.OpenmrsObject,
 *      org.openmrs.User, java.util.Date, java.lang.String)
 * @should set empty string properties to null
 * @should not set empty string properties to null for AllowEmptyStrings annotation
 * @should not trim empty strings for AllowLeadingOrTrailingWhitespace annotation
 * @should trim strings without AllowLeadingOrTrailingWhitespace annotation
 * @should trim empty strings for AllowEmptyStrings annotation
 *//*from   ww  w . j av  a2 s  .  com*/
public void handle(OpenmrsObject openmrsObject, User creator, Date dateCreated, String reason) {
    if (openmrsObject.getUuid() == null) {
        openmrsObject.setUuid(UUID.randomUUID().toString());
    }

    //Set all empty string properties, that do not have the AllowEmptyStrings annotation, to null.
    //And also trim leading and trailing white space for properties that do not have the
    //AllowLeadingOrTrailingWhitespace annotation.
    PropertyDescriptor[] properties = PropertyUtils.getPropertyDescriptors(openmrsObject);
    for (PropertyDescriptor property : properties) {

        if (property.getPropertyType() == null) {
            continue;
        }

        // Ignore properties that don't have a getter (e.g. GlobalProperty.valueReferenceInternal) or
        // don't have a setter (e.g. Patient.familyName)
        if (property.getWriteMethod() == null || property.getReadMethod() == null) {
            continue;
        }

        // Ignore properties that have a deprecated getter or setter
        if (property.getWriteMethod().getAnnotation(Deprecated.class) != null
                || property.getReadMethod().getAnnotation(Deprecated.class) != null) {
            continue;
        }

        //We are dealing with only strings
        if (!property.getPropertyType().equals(String.class)) {
            continue;
        }

        try {
            Object value = PropertyUtils.getProperty(openmrsObject, property.getName());
            if (value == null) {
                continue;
            }

            Object valueBeforeTrim = value;
            if (property.getWriteMethod().getAnnotation(AllowLeadingOrTrailingWhitespace.class) == null) {
                value = ((String) value).trim();

                //If we have actually trimmed any space, set the trimmed value.
                if (!valueBeforeTrim.equals(value)) {
                    PropertyUtils.setProperty(openmrsObject, property.getName(), value);
                }
            }

            //Check if user is interested in setting empty strings to null
            if (property.getWriteMethod().getAnnotation(AllowEmptyStrings.class) != null) {
                continue;
            }

            if ("".equals(value)
                    && !(openmrsObject instanceof Voidable && ((Voidable) openmrsObject).isVoided())) {
                //Set to null only if object is not already voided
                PropertyUtils.setProperty(openmrsObject, property.getName(), null);
            }
        } catch (UnsupportedOperationException ex) {
            // there is no need to log this. These should be (mostly) silently skipped over 
            if (log.isInfoEnabled()) {
                log.info(
                        "The property " + property.getName() + " is no longer supported and should be ignored.",
                        ex);
            }
        } catch (InvocationTargetException ex) {
            if (log.isWarnEnabled()) {
                log.warn("Failed to access property " + property.getName() + "; accessor threw exception.", ex);
            }
        } catch (Exception ex) {
            throw new APIException("failed.change.property.value", new Object[] { property.getName() }, ex);
        }
    }
}

From source file:org.openmrs.module.coreapps.fragment.controller.DiagnosesFragmentController.java

/**
 * This is public so that it can be used by a fragment that needs to prepopulate a diagnoses widget that is normally
 * populated with AJAX results from the #search method.
 * @param result//  ww  w . j a  va  2s.  c  o m
 * @param ui
 * @param locale
 * @return
 * @throws Exception
 */
public SimpleObject simplify(ConceptSearchResult result, UiUtils ui, Locale locale) throws Exception {
    SimpleObject simple = SimpleObject.fromObject(result, ui, "word", "conceptName.id", "conceptName.uuid",
            "conceptName.conceptNameType", "conceptName.name", "concept.id", "concept.uuid",
            "concept.conceptMappings.conceptMapType", "concept.conceptMappings.conceptReferenceTerm.code",
            "concept.conceptMappings.conceptReferenceTerm.name",
            "concept.conceptMappings.conceptReferenceTerm.conceptSource.name");

    Concept concept = result.getConcept();
    ConceptName conceptName = result.getConceptName();
    ConceptName preferredName = getPreferredName(locale, concept);
    PropertyUtils.setProperty(simple, "concept.preferredName", preferredName.getName());

    return simple;
}

From source file:org.openmrs.module.deriveddata.api.model.ArvData.java

public void resetMedications() {
    PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(this.getClass());
    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        try {//w w  w . j  a v a 2s. c om
            String name = propertyDescriptor.getName();
            if (StringUtils.startsWith(name, "on"))
                PropertyUtils.setProperty(this, name, Boolean.FALSE);
        } catch (Exception e) {
            log.error("Unable to read property: " + propertyDescriptor.getName() + "!", e);
        }
    }
}

From source file:org.openmrs.module.deriveddata.api.model.ArvData.java

public void setMedications(final Concept valueCoded, final Boolean value) {
    List<String> fieldNames = ArvDataUtils.getMappings(valueCoded);
    for (String fieldName : fieldNames) {
        try {/*from   ww w.j  a  va 2 s . c  o  m*/
            PropertyUtils.setProperty(this, fieldName, value);
        } catch (Exception e) {
            log.error("Unable to read property: " + fieldName + "!", e);
        }
    }
}

From source file:org.openmrs.module.emr.fragment.controller.DiagnosesFragmentController.java

private SimpleObject simplify(ConceptSearchResult result, UiUtils ui, Locale locale) throws Exception {
    SimpleObject simple = SimpleObject.fromObject(result, ui, "word", "conceptName.id",
            "conceptName.conceptNameType", "conceptName.name", "concept.id",
            "concept.conceptMappings.conceptMapType", "concept.conceptMappings.conceptReferenceTerm.code",
            "concept.conceptMappings.conceptReferenceTerm.name",
            "concept.conceptMappings.conceptReferenceTerm.conceptSource.name");

    Concept concept = result.getConcept();
    ConceptName conceptName = result.getConceptName();
    ConceptName preferredName = concept.getPreferredName(locale);
    PropertyUtils.setProperty(simple, "concept.preferredName", preferredName.getName());

    return simple;
}

From source file:org.openmrs.module.emrapi.descriptor.ConceptSetDescriptor.java

/**
 * @param conceptService// ww  w . j ava2s  . c  om
 * @param conceptSourceName
 * @param primaryConceptField Field for primary concept. This concept is mandatory
 * @param memberConceptFields Fields for member concepts of primary concept. These concepts can be mandatory or optional.
 */
protected void setup(ConceptService conceptService, String conceptSourceName,
        ConceptSetDescriptorField primaryConceptField, ConceptSetDescriptorField... memberConceptFields) {
    try {
        String primaryConceptCode = primaryConceptField.getConceptCode();
        Concept primaryConcept = conceptService.getConceptByMapping(primaryConceptCode, conceptSourceName);
        if (primaryConcept == null) {
            throw new MissingConceptException("Couldn't find primary concept for " + getClass().getSimpleName()
                    + " which should be mapped as " + conceptSourceName + ":" + primaryConceptCode);
        }
        PropertyUtils.setProperty(this, primaryConceptField.getName(), primaryConcept);
        for (ConceptSetDescriptorField conceptSetDescriptorField : memberConceptFields) {
            String propertyName = conceptSetDescriptorField.getName();
            String mappingCode = conceptSetDescriptorField.getConceptCode();
            Concept childConcept = conceptService.getConceptByMapping(mappingCode, conceptSourceName);
            if (conceptSetDescriptorField.isRequired()) {
                if (childConcept == null) {
                    throw new MissingConceptException(
                            "Couldn't find " + propertyName + " concept for " + getClass().getSimpleName()
                                    + " which should be mapped as " + conceptSourceName + ":" + mappingCode);
                }
                if (!primaryConcept.getSetMembers().contains(childConcept)) {
                    throw new IllegalStateException("Concept mapped as " + conceptSourceName + ":" + mappingCode
                            + " needs to be a set member of concept " + primaryConcept.getConceptId()
                            + " which is mapped as " + conceptSourceName + ":" + primaryConceptCode);
                }
            }
            PropertyUtils.setProperty(this, propertyName, childConcept);
        }
    } catch (Exception ex) {
        if (ex instanceof RuntimeException) {
            throw (RuntimeException) ex;
        } else {
            throw new IllegalStateException(ex);
        }
    }
}

From source file:org.openmrs.module.emrapi.utils.GeneralUtils.java

/**
 * Ensures that bean.propertyName is equal to newValue
 *
 * @param bean/*from ww  w . j  a  v  a  2 s  .  co  m*/
 * @param propertyName
 * @param newValue
 * @return true if we changed the value, false if we left it as-was
 */
public static boolean setPropertyIfDifferent(Object bean, String propertyName, Object newValue) {
    try {
        Object currentValue = PropertyUtils.getProperty(bean, propertyName);
        if (OpenmrsUtil.nullSafeEquals(currentValue, newValue)) {
            return false;
        } else {
            PropertyUtils.setProperty(bean, propertyName, newValue);
            return true;
        }
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:org.openmrs.module.importpatientfromws.api.impl.ImportPatientFromWebServiceImpl.java

private void copyDateProperty(Object ontoBean, JsonNode fromJson, String field) {
    String asText;/*from   w  w  w. j  a va 2s  . com*/
    try {
        asText = fromJson.get(field).getTextValue();
    } catch (Exception ex) {
        // skip fields not contained in the json
        return;
    }
    if (StringUtils.isBlank(asText)) {
        return;
    }
    Date date = parseDate(asText);
    try {
        PropertyUtils.setProperty(ontoBean, field, date);
    } catch (Exception ex) {
        throw new IllegalArgumentException(ex);
    }
}

From source file:org.openmrs.module.importpatientfromws.api.impl.ImportPatientFromWebServiceImpl.java

private void copyStringProperty(Object ontoBean, JsonNode fromJson, String field) {
    String asText;/* w  w w  .  j  av a  2  s.  c o  m*/
    try {
        asText = fromJson.get(field).getTextValue();
    } catch (Exception ex) {
        // skip fields not contained in the json
        return;
    }
    try {
        PropertyUtils.setProperty(ontoBean, field, asText);
    } catch (Exception ex) {
        throw new IllegalArgumentException(ex);
    }
}