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

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

Introduction

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

Prototype

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

Source Link

Document

Return the Java Class representing the property type of the specified property, or null if there is no such property for the specified bean.

For more details see PropertyUtilsBean.

Usage

From source file:org.kuali.kfs.module.ar.batch.service.impl.CustomerLoadServiceImpl.java

/**
 *
 * This messy thing attempts to compare a property on the batch customer (new) and existing customer, and if
 * the new is blank, but the old is there, to overwrite the new-value with the old-value, thus preventing
 * batch uploads from blanking out certain fields.
 *
 * @param batchCustomer/*from   w  ww .j  a  v  a  2 s. c o  m*/
 * @param existingCustomer
 * @param propertyName
 */
protected void dontBlankOutFieldsOnUpdate(Customer batchCustomer, Customer existingCustomer,
        String propertyName) {
    String batchValue;
    String existingValue;
    Class<?> propertyClass = null;

    //  try to retrieve the property type to see if it exists at all
    try {
        propertyClass = PropertyUtils.getPropertyType(batchCustomer, propertyName);

        //  if the property doesnt exist, then throw an exception
        if (propertyClass == null) {
            throw new IllegalArgumentException(
                    "The propertyName specified [" + propertyName + "] doesnt exist on the Customer object.");
        }

        //  get the String values of both batch and existing, to compare
        batchValue = BeanUtils.getSimpleProperty(batchCustomer, propertyName);
        existingValue = BeanUtils.getSimpleProperty(existingCustomer, propertyName);

        //  if the existing is non-blank, and the new is blank, then over-write the new with the existing value
        if (StringUtils.isBlank(batchValue) && StringUtils.isNotBlank(existingValue)) {

            //  get the real typed value, and then try to set the property value
            Object typedValue = PropertyUtils.getProperty(existingCustomer, propertyName);
            BeanUtils.setProperty(batchCustomer, propertyName, typedValue);
        }
    } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException ex) {
        throw new RuntimeException("Could not set properties on the Customer object", ex);
    }
}

From source file:org.kuali.kfs.sys.batch.FlatFileParseTrackerImpl.java

/**
 * Called when a line has completed parsing. Throws an exception if a proper parent
 * is not found for the line being parsed
 *///  w w  w.j a  va 2 s .  c  o m
@Override
@SuppressWarnings("unchecked")
public void completeLineParse() {
    completedLineCount += 1;
    if (LOG.isDebugEnabled()) {
        LOG.debug("Completing parse of line: " + completedLineCount);
    }

    Object currentObject = parseStack.pop();
    final FlatFileChildMapEntry entry = getEntryForParsedIntoObject(currentObject);

    final Class<?> parentClass = (entry == null) ? null : entry.getParentBeanClass();
    final String propertyName = (entry == null) ? null : entry.getPropertyName();

    while (!parseStack.isEmpty()) {
        Object checkingObject = parseStack.pop();
        if (parentClass != null && parentClass.isAssignableFrom(checkingObject.getClass())) {
            try {
                if (Collection.class
                        .isAssignableFrom(PropertyUtils.getPropertyType(checkingObject, propertyName))) {
                    Collection childrenList = ((Collection) PropertyUtils.getProperty(checkingObject,
                            propertyName));
                    childrenList.add(currentObject);
                } else {
                    PropertyUtils.setProperty(checkingObject, propertyName, currentObject);
                }
                parseStack.push(checkingObject);
                parseStack.push(currentObject);
                return;
            } catch (Exception e) {
                LOG.error(
                        e.getMessage() + "occured when completing line parse; attempting to set object of type "
                                + currentObject.getClass().getName() + " to the following parent: "
                                + parentClass.getName() + "#" + propertyName,
                        e);
                throw new RuntimeException(
                        e.getMessage() + "occured when completing line parse; attempting to set object of type "
                                + currentObject.getClass().getName() + " to the following parent: "
                                + parentClass.getName() + "#" + propertyName,
                        e);
            }
        }
    }
    if (parentClass == null) {
        parseStack.push(currentObject);
        parsedParentObjects.add(currentObject);
    } else {
        throw new IllegalStateException("A line of class " + currentObject.getClass().getName()
                + " cannot exist without a proper parent");
    }
}

From source file:org.kuali.kfs.sys.dataaccess.impl.FieldMetaDataImpl.java

public Object processMetaData(DatabaseMetaData databaseMetaData) throws SQLException, MetaDataAccessException {
    Class workingBusinessObjectClass = businessObjectClass;
    String workingPropertyName = propertyName;
    while (workingPropertyName.contains(".")) {
        try {//from  w w  w. j a v  a2 s  .  c  o  m
            workingBusinessObjectClass = org.apache.ojb.broker.metadata.MetadataManager.getInstance()
                    .getGlobalRepository().getDescriptorFor(workingBusinessObjectClass)
                    .getObjectReferenceDescriptorByName(
                            workingPropertyName.substring(0, workingPropertyName.indexOf(".")))
                    .getItemClass();
        } catch (Exception e1) {
            LOG.debug(
                    new StringBuffer("Unable to get property type via reference descriptor for property ")
                            .append(workingPropertyName.substring(0, workingPropertyName.indexOf(".")))
                            .append(" of BusinessObject class ").append(workingBusinessObjectClass).toString(),
                    e1);
            try {
                workingBusinessObjectClass = org.apache.ojb.broker.metadata.MetadataManager.getInstance()
                        .getGlobalRepository().getDescriptorFor(workingBusinessObjectClass)
                        .getCollectionDescriptorByName(
                                workingPropertyName.substring(0, workingPropertyName.indexOf(".")))
                        .getItemClass();
            } catch (Exception e2) {
                LOG.debug(new StringBuffer("Unable to get property type via collection descriptor of property ")
                        .append(workingPropertyName.substring(0, workingPropertyName.indexOf(".")))
                        .append(" of BusinessObject class ").append(workingBusinessObjectClass).toString(), e2);
                BusinessObject businessObject = null;
                try {
                    businessObject = (BusinessObject) workingBusinessObjectClass.newInstance();
                } catch (Exception e3) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Unable to instantiate BusinessObject class " + workingBusinessObjectClass,
                                e3);
                    }
                    return populateAndReturnNonPersistableInstance();
                }
                try {
                    workingBusinessObjectClass = PropertyUtils.getPropertyType(businessObject,
                            workingPropertyName.substring(0, workingPropertyName.indexOf(".")));
                } catch (Exception e4) {
                    LOG.debug(new StringBuffer("Unable to get type of property ")
                            .append(workingPropertyName.substring(0, workingPropertyName.indexOf(".")))
                            .append(" for BusinessObject class ").append(workingBusinessObjectClass).toString(),
                            e4);
                    return populateAndReturnNonPersistableInstance();
                }
            }
        }
        if (workingBusinessObjectClass == null) {
            return populateAndReturnNonPersistableInstance();
        } else {
            workingPropertyName = workingPropertyName.substring(workingPropertyName.indexOf(".") + 1);
        }
    }
    if (!PersistableBusinessObject.class.isAssignableFrom(workingBusinessObjectClass)) {
        return populateAndReturnNonPersistableInstance();
    }
    ClassDescriptor classDescriptor = org.apache.ojb.broker.metadata.MetadataManager.getInstance()
            .getGlobalRepository().getDescriptorFor(workingBusinessObjectClass);
    if (classDescriptor == null) {
        return populateAndReturnNonPersistableInstance();
    }
    tableName = classDescriptor.getFullTableName();
    if (classDescriptor.getFieldDescriptorByName(workingPropertyName) == null) {
        return populateAndReturnNonPersistableInstance();
    }
    columnName = classDescriptor.getFieldDescriptorByName(workingPropertyName).getColumnName();
    ResultSet resultSet = databaseMetaData.getColumns(null, null, tableName, columnName);
    if (resultSet.next()) {
        dataType = resultSet.getString("TYPE_NAME");
        length = resultSet.getInt("COLUMN_SIZE");
        decimalPlaces = resultSet.getInt("DECIMAL_DIGITS");
        encrypted = classDescriptor.getFieldDescriptorByName(workingPropertyName)
                .getFieldConversion() instanceof OjbKualiEncryptDecryptFieldConversion;
    }
    resultSet.close();
    return this;
}

From source file:org.kuali.kfs.sys.document.service.impl.AccountingLineRenderingServiceImpl.java

/**
 * Determines if this method uses a date validation pattern, in which case, a date picker should be rendered
 * @param propertyName the property of the field being checked from the command line
 * @param accountingLineToRender the accounting line which is being rendered
 * @return true if the property does use date validation, false otherwise
 *//* w w  w  .  java 2s . co  m*/
protected boolean usesDateValidation(String propertyName, Object businessObject) {
    final org.kuali.rice.krad.datadictionary.BusinessObjectEntry entry = SpringContext
            .getBean(DataDictionaryService.class).getDataDictionary()
            .getBusinessObjectEntry(businessObject.getClass().getName());
    AttributeDefinition attributeDefinition = entry.getAttributeDefinition(propertyName);

    if (attributeDefinition == null) {
        if (!propertyName.contains("."))
            return false;
        final int firstNestingPoint = propertyName.indexOf(".");
        final String toNestingPoint = propertyName.substring(0, firstNestingPoint);
        final String fromNestingPoint = propertyName.substring(firstNestingPoint + 1);
        Object childObject = null;
        try {
            final Class childClass = PropertyUtils.getPropertyType(businessObject, toNestingPoint);
            childObject = childClass.newInstance();
        } catch (IllegalAccessException iae) {
            new UnsupportedOperationException(iae);
        } catch (InvocationTargetException ite) {
            new UnsupportedOperationException(ite);
        } catch (NoSuchMethodException nsme) {
            new UnsupportedOperationException(nsme);
        } catch (InstantiationException ie) {
            throw new UnsupportedOperationException(ie);
        }
        return usesDateValidation(fromNestingPoint, childObject);
    }

    final ValidationPattern validationPattern = attributeDefinition.getValidationPattern();
    if (validationPattern == null)
        return false; // no validation for sure means we ain't using date validation
    return validationPattern instanceof DateValidationPattern;
}

From source file:org.kuali.kfs.sys.document.validation.ParameterizedValidation.java

/**
 * Populates a single parameter field based on a field conversion, given an event to populate data from
 * @param event the event which acts as the source of data
 * @param validation the validation to populate
 * @param conversion the conversion information
 *///w  ww  .  ja v  a  2s . c  om
protected void populateParameterFromEvent(AttributedDocumentEvent event,
        ValidationFieldConvertible conversion) {
    try {
        Class propertyClass = PropertyUtils.getPropertyType(event, conversion.getSourceEventProperty());
        Object propertyValue = ObjectUtils.getPropertyValue(event, conversion.getSourceEventProperty());
        if (propertyValue != null) {
            ObjectUtils.setObjectProperty(this, conversion.getTargetValidationProperty(), propertyClass,
                    propertyValue);
        }
    } catch (FormatException fe) {
        throw new RuntimeException(fe);
    } catch (IllegalAccessException iae) {
        throw new RuntimeException(iae);
    } catch (InvocationTargetException ite) {
        throw new RuntimeException(ite);
    } catch (NoSuchMethodException nsme) {
        throw new RuntimeException(nsme);
    }
}

From source file:org.kuali.kfs.sys.service.impl.KfsBusinessObjectMetaDataServiceImpl.java

@Override
public DataMappingFieldDefinition getDataMappingFieldDefinition(
        FunctionalFieldDescription functionalFieldDescription) {
    BusinessObjectEntry businessObjectEntry = dataDictionaryService.getDataDictionary()
            .getBusinessObjectEntry(functionalFieldDescription.getComponentClass());
    String propertyType = "";
    try {//from   ww  w.j  av  a2  s. c  o m
        propertyType = PropertyUtils.getPropertyType(businessObjectEntry.getBusinessObjectClass().newInstance(),
                functionalFieldDescription.getPropertyName()).getSimpleName();
    } catch (Exception e) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("KfsBusinessObjectMetaDataServiceImpl unable to get type of property: "
                    + functionalFieldDescription.getPropertyName(), e);
        }
    }
    return new DataMappingFieldDefinition(functionalFieldDescription,
            (org.kuali.rice.kns.datadictionary.BusinessObjectEntry) businessObjectEntry,
            businessObjectEntry.getAttributeDefinition(functionalFieldDescription.getPropertyName()),
            businessObjectMetaDataDao.getFieldMetaData(businessObjectEntry.getBusinessObjectClass(),
                    functionalFieldDescription.getPropertyName()),
            propertyType, getReferenceComponentLabel(businessObjectEntry.getBusinessObjectClass(),
                    functionalFieldDescription.getPropertyName()));
}

From source file:org.kuali.ole.sys.service.impl.OleBusinessObjectMetaDataServiceImpl.java

@Override
public DataMappingFieldDefinition getDataMappingFieldDefinition(
        FunctionalFieldDescription functionalFieldDescription) {
    BusinessObjectEntry businessObjectEntry = (BusinessObjectEntry) dataDictionaryService.getDataDictionary()
            .getBusinessObjectEntry(functionalFieldDescription.getComponentClass());
    String propertyType = "";
    try {// w  ww .j a  v  a  2s  .c o  m
        propertyType = PropertyUtils.getPropertyType(businessObjectEntry.getBusinessObjectClass().newInstance(),
                functionalFieldDescription.getPropertyName()).getSimpleName();
    } catch (Exception e) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("OleBusinessObjectMetaDataServiceImpl unable to get type of property: "
                    + functionalFieldDescription.getPropertyName(), e);
        }
    }
    return new DataMappingFieldDefinition(functionalFieldDescription, businessObjectEntry,
            businessObjectEntry.getAttributeDefinition(functionalFieldDescription.getPropertyName()),
            businessObjectMetaDataDao.getFieldMetaData(businessObjectEntry.getBusinessObjectClass(),
                    functionalFieldDescription.getPropertyName()),
            propertyType, getReferenceComponentLabel(businessObjectEntry.getBusinessObjectClass(),
                    functionalFieldDescription.getPropertyName()));
}

From source file:org.kuali.rice.kim.impl.identity.PersonServiceImpl.java

private boolean isPersonProperty(Object bo, String propertyName) {
    try {//from  w  w w. ja  v a  2s.  c  om
        if (PropertyAccessorUtils.isNestedOrIndexedProperty(propertyName) // is a nested property
                && !StringUtils.contains(propertyName, "add.")) {// exclude add line properties (due to path parsing problems in PropertyUtils.getPropertyType)
            int lastIndex = PropertyAccessorUtils.getLastNestedPropertySeparatorIndex(propertyName);
            String propertyTypeName = lastIndex != -1 ? StringUtils.substring(propertyName, 0, lastIndex)
                    : StringUtils.EMPTY;
            Class<?> type = PropertyUtils.getPropertyType(bo, propertyTypeName);
            // property type indicates a Person object
            if (type != null) {
                return Person.class.isAssignableFrom(type);
            }
            LOG.warn("Unable to determine type of nested property: " + bo.getClass().getName() + " / "
                    + propertyName);
        }
    } catch (Exception ex) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Unable to determine if property on " + bo.getClass().getName() + " to a person object: "
                    + propertyName, ex);
        }
    }
    return false;
}

From source file:org.kuali.rice.kns.lookup.KualiLookupableHelperServiceImpl.java

/**
 * Check whether the given property represents a property within an EBO starting
 * with the sampleBo object given.  This is used to determine if a criteria needs
 * to be applied to the EBO first, before sending to the normal lookup DAO.
 *//* w  w w  .  java  2s  .  c o m*/
protected boolean isExternalBusinessObjectProperty(Object sampleBo, String propertyName) {
    try {
        if (propertyName.indexOf(".") > 0 && !StringUtils.contains(propertyName, "add.")) {
            Class propertyClass = PropertyUtils.getPropertyType(sampleBo,
                    StringUtils.substringBeforeLast(propertyName, "."));
            if (propertyClass != null) {
                return ExternalizableBusinessObjectUtils.isExternalizableBusinessObjectInterface(propertyClass);
            } else {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("unable to get class for " + StringUtils.substringBeforeLast(propertyName, ".")
                            + " on " + sampleBo.getClass().getName());
                }
            }
        }
    } catch (Exception e) {
        LOG.debug("Unable to determine type of property for " + sampleBo.getClass().getName() + "/"
                + propertyName, e);
    }
    return false;
}

From source file:org.kuali.rice.kns.lookup.KualiLookupableHelperServiceImpl.java

/**
 * Given an property on the main BO class, return the defined type of the ExternalizableBusinessObject.  This will be used
 * by other code to determine the correct module service to call for the lookup.
 *
 * @param boClass/*  w  w w .j a va  2  s.  com*/
 * @param propertyName
 * @return
 */
protected Class<? extends ExternalizableBusinessObject> getExternalizableBusinessObjectClass(Class boClass,
        String propertyName) {
    try {
        return PropertyUtils.getPropertyType(boClass.newInstance(),
                StringUtils.substringBeforeLast(propertyName, "."));
    } catch (Exception e) {
        LOG.debug("Unable to determine type of property for " + boClass.getName() + "/" + propertyName, e);
    }
    return null;
}