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

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

Introduction

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

Prototype

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

Source Link

Document

Retrieve the property descriptor for the specified property of the specified bean, or return null if there is no such descriptor.

For more details see PropertyUtilsBean.

Usage

From source file:org.kuali.rice.kns.datadictionary.validation.AttributeValidatingTypeServiceBase.java

/**
 * <p>Validates the attribute value for the given {@link TypeAttributeDefinition} having a componentName.</p>
 * <p>This implementation instantiates a component object using reflection on the class name specified in the
 * {@link TypeAttributeDefinition}s componentName, gets a {@link PropertyDescriptor} for the attribute of the
 * component object, hydrates the attribute's value from it's String form, sets that value on the component object,
 * and then delegates to//from   www  .  j  a v a 2  s . com
 * {@link #validatePrimitiveAttributeFromDescriptor(org.kuali.rice.kns.datadictionary.validation.AttributeValidatingTypeServiceBase.TypeAttributeDefinition, String, Object, java.beans.PropertyDescriptor)}.
 * </p>
 *
 * @param typeAttributeDefinition
 * @param attributeName
 * @param value
 * @return
 */
protected List<RemotableAttributeError> validateDataDictionaryAttribute(
        TypeAttributeDefinition typeAttributeDefinition, String attributeName, String value) {
    try {
        // create an object of the proper type per the component
        Object componentObject = Class.forName(typeAttributeDefinition.getComponentName()).newInstance();

        if (attributeName != null) {
            // get the bean utils descriptor for accessing the attribute on that object
            PropertyDescriptor propertyDescriptor = PropertyUtils.getPropertyDescriptor(componentObject,
                    attributeName);
            if (propertyDescriptor != null) {
                // set the value on the object so that it can be checked
                Object attributeValue = getAttributeValue(propertyDescriptor, value);
                propertyDescriptor.getWriteMethod().invoke(componentObject, attributeValue);
                return validatePrimitiveAttributeFromDescriptor(typeAttributeDefinition,
                        typeAttributeDefinition.getComponentName(), componentObject, propertyDescriptor);
            }
        }
    } catch (Exception e) {
        throw new TypeAttributeValidationException(e);
    }
    return Collections.emptyList();
}

From source file:org.kuali.rice.kns.kim.type.DataDictionaryTypeServiceBase.java

protected List<RemotableAttributeError> validateDataDictionaryAttribute(KimTypeAttribute attr, String key,
        String value) {//w  w  w .  j  a v  a 2  s  .  c  om
    try {
        // create an object of the proper type per the component
        Object componentObject = Class.forName(attr.getKimAttribute().getComponentName()).newInstance();

        if (attr.getKimAttribute().getAttributeName() != null) {
            // get the bean utils descriptor for accessing the attribute on that object
            PropertyDescriptor propertyDescriptor = PropertyUtils.getPropertyDescriptor(componentObject,
                    attr.getKimAttribute().getAttributeName());
            if (propertyDescriptor != null) {
                // set the value on the object so that it can be checked
                Object attributeValue = KRADUtils.hydrateAttributeValue(propertyDescriptor.getPropertyType(),
                        value);
                if (attributeValue == null) {
                    attributeValue = value; // not a super-awesome fallback strategy, but...
                }
                propertyDescriptor.getWriteMethod().invoke(componentObject, attributeValue);
                return validateDataDictionaryAttribute(attr.getKimTypeId(),
                        attr.getKimAttribute().getComponentName(), componentObject, propertyDescriptor);
            }
        }
    } catch (Exception e) {
        throw new KimTypeAttributeValidationException(e);
    }
    return Collections.emptyList();
}

From source file:org.kuali.rice.kns.util.BeanPropertyComparator.java

/**
 * Compare two JavaBeans by the properties given to the constructor. If no propertues
 * /* www. j av a  2 s  . c  o  m*/
 * @param o1 Object The first bean to get data from to compare against
 * @param o2 Object The second bean to get data from to compare
 * @return int negative or positive based on order
 */
public int compare(Object o1, Object o2) {
    int compared = 0;

    try {
        for (Iterator i = propertyNames.iterator(); (compared == 0) && i.hasNext();) {
            String currentProperty = i.next().toString();

            // choose appropriate comparator
            Comparator currentComparator = null;
            try {
                PropertyDescriptor propertyDescriptor = PropertyUtils.getPropertyDescriptor(o1,
                        currentProperty);
                Class propertyClass = propertyDescriptor.getPropertyType();
                if (propertyClass.equals(String.class)) {
                    currentComparator = this.stringComparator;
                } else if (TypeUtils.isBooleanClass(propertyClass)) {
                    currentComparator = this.booleanComparator;
                } else {
                    currentComparator = this.genericComparator;
                }
            } catch (NullPointerException e) {
                throw new BeanComparisonException(
                        "unable to find property '" + o1.getClass().getName() + "." + currentProperty + "'", e);
            }

            // compare the values
            Object value1 = PropertyUtils.getProperty(o1, currentProperty);
            Object value2 = PropertyUtils.getProperty(o2, currentProperty);
            /* Begin Null Support Fix */
            if (value1 == null && value2 == null)
                return 0;
            else if (value1 == null)
                return -1;
            else if (value2 == null)
                return 1;
            /* End Null Support Fix*/
            compared = currentComparator.compare(value1, value2);
        }
    } catch (IllegalAccessException e) {
        throw new BeanComparisonException("unable to compare property values", e);
    } catch (NoSuchMethodException e) {
        throw new BeanComparisonException("unable to compare property values", e);
    } catch (InvocationTargetException e) {
        throw new BeanComparisonException("unable to compare property values", e);
    }

    return compared;
}

From source file:org.kuali.rice.krad.service.impl.BusinessObjectServiceImpl.java

@Override
public BusinessObject getReferenceIfExists(BusinessObject bo, String referenceName) {
    // if either argument is null, then we have nothing to do, complain and abort
    if (ObjectUtils.isNull(bo)) {
        throw new IllegalArgumentException("Passed in BusinessObject was null.  No processing can be done.");
    }//from   ww w  . j ava2 s  .c om
    if (StringUtils.isEmpty(referenceName)) {
        throw new IllegalArgumentException(
                "Passed in referenceName was empty or null.  No processing can be done.");
    }

    // make sure the attribute exists at all, throw exception if not
    PropertyDescriptor propertyDescriptor;
    try {
        propertyDescriptor = PropertyUtils.getPropertyDescriptor(bo, referenceName);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    if (propertyDescriptor == null) {
        throw new ReferenceAttributeDoesntExistException("Requested attribute: '" + referenceName
                + "' does not exist " + "on class: '" + bo.getClass().getName() + "'. GFK");
    }

    // get the class of the attribute name
    Class referenceClass = null;
    if (bo instanceof PersistableBusinessObject) {
        referenceClass = persistenceStructureService
                .getBusinessObjectAttributeClass(((PersistableBusinessObject) bo).getClass(), referenceName);
    }
    if (referenceClass == null) {
        referenceClass = ObjectUtils.getPropertyType(bo, referenceName, persistenceStructureService);
    }
    if (referenceClass == null) {
        referenceClass = propertyDescriptor.getPropertyType();
    }

    /*
     * check for Person or EBO references in which case we can just get the reference through propertyutils
     */
    if (ExternalizableBusinessObject.class.isAssignableFrom(referenceClass)) {
        try {
            BusinessObject referenceBoExternalizable = (BusinessObject) PropertyUtils.getProperty(bo,
                    referenceName);
            if (referenceBoExternalizable != null) {
                return referenceBoExternalizable;
            }
        } catch (Exception ex) {
            //throw new RuntimeException("Unable to get property " + referenceName + " from a BO of class: " + bo.getClass().getName(),ex);
            //Proceed further - get the BO relationship using responsible module service and proceed further
        }
    }

    // make sure the class of the attribute descends from BusinessObject,
    // otherwise throw an exception
    if (!ExternalizableBusinessObject.class.isAssignableFrom(referenceClass)
            && !PersistableBusinessObject.class.isAssignableFrom(referenceClass)) {
        throw new ObjectNotABusinessObjectRuntimeException("Attribute requested (" + referenceName
                + ") is of class: " + "'" + referenceClass.getName() + "' and is not a "
                + "descendent of PersistableBusinessObject.  Only descendents of PersistableBusinessObject "
                + "can be used.");
    }

    // get the list of foreign-keys for this reference. if the reference
    // does not exist, or is not a reference-descriptor, an exception will
    // be thrown here.
    //DataObjectRelationship boRel = dataObjectMetaDataService.getBusinessObjectRelationship( bo, referenceName );
    DataObjectRelationship boRel = getDataObjectMetaDataService().getDataObjectRelationship(bo, bo.getClass(),
            referenceName, "", true, false, false);
    final Map<String, String> fkMap = boRel != null ? boRel.getParentToChildReferences()
            : Collections.<String, String>emptyMap();

    boolean allFkeysHaveValues = true;
    // walk through the foreign keys, testing each one to see if it has a value
    Map<String, Object> pkMap = new HashMap<String, Object>();
    for (Map.Entry<String, String> entry : fkMap.entrySet()) {
        String fkFieldName = entry.getKey();
        String pkFieldName = entry.getValue();

        // attempt to retrieve the value for the given field
        Object fkFieldValue;
        try {
            fkFieldValue = PropertyUtils.getProperty(bo, fkFieldName);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        // determine if there is a value for the field
        if (ObjectUtils.isNull(fkFieldValue)) {
            allFkeysHaveValues = false;
            break; // no reason to continue processing the fkeys
        } else if (String.class.isAssignableFrom(fkFieldValue.getClass())) {
            if (StringUtils.isEmpty((String) fkFieldValue)) {
                allFkeysHaveValues = false;
                break;
            } else {
                pkMap.put(pkFieldName, fkFieldValue);
            }
        }

        // if there is a value, grab it
        else {
            pkMap.put(pkFieldName, fkFieldValue);
        }
    }

    BusinessObject referenceBo = null;
    // only do the retrieval if all Foreign Keys have values
    if (allFkeysHaveValues) {
        if (ExternalizableBusinessObject.class.isAssignableFrom(referenceClass)) {
            ModuleService responsibleModuleService = KRADServiceLocatorWeb.getKualiModuleService()
                    .getResponsibleModuleService(referenceClass);
            if (responsibleModuleService != null) {
                return responsibleModuleService
                        .<ExternalizableBusinessObject>getExternalizableBusinessObject(referenceClass, pkMap);
            }
        } else
            referenceBo = this.<BusinessObject>findByPrimaryKey(referenceClass, pkMap);
    }

    // return what we have, it'll be null if it was never retrieved
    return referenceBo;
}

From source file:org.kuali.rice.krad.service.impl.PersistenceServiceJpaImpl.java

/**
 * @see org.kuali.rice.krad.service.PersistenceService#allForeignKeyValuesPopulatedForReference(org.kuali.rice.krad.bo.PersistableBusinessObject, java.lang.String)
 *///from  w  w  w  .j a  v  a  2 s .  c o m
public boolean allForeignKeyValuesPopulatedForReference(PersistableBusinessObject bo, String referenceName) {
    boolean allFkeysHaveValues = true;

    // yelp if nulls were passed in
    if (bo == null) {
        throw new IllegalArgumentException("The Class passed in for the BusinessObject argument was null.");
    }
    if (StringUtils.isBlank(referenceName)) {
        throw new IllegalArgumentException(
                "The String passed in for the referenceName argument was null or empty.");
    }

    PropertyDescriptor propertyDescriptor = null;

    // make sure the attribute exists at all, throw exception if not
    try {
        propertyDescriptor = PropertyUtils.getPropertyDescriptor(bo, referenceName);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    if (propertyDescriptor == null) {
        throw new ReferenceAttributeDoesntExistException("Requested attribute: '" + referenceName
                + "' does not exist " + "on class: '" + bo.getClass().getName() + "'.");
    }

    // get the class of the attribute name
    Class referenceClass = getBusinessObjectAttributeClass(bo.getClass(), referenceName);
    if (referenceClass == null) {
        referenceClass = propertyDescriptor.getPropertyType();
    }

    // make sure the class of the attribute descends from BusinessObject,
    // otherwise throw an exception
    if (!PersistableBusinessObject.class.isAssignableFrom(referenceClass)) {
        throw new ObjectNotABusinessObjectRuntimeException("Attribute requested (" + referenceName
                + ") is of class: " + "'" + referenceClass.getName() + "' and is not a "
                + "descendent of BusinessObject.  Only descendents of BusinessObject " + "can be used.");
    }

    EntityDescriptor descriptor = MetadataManager.getEntityDescriptor(bo.getClass());
    ObjectDescriptor objectDescriptor = descriptor.getObjectDescriptorByName(referenceName);
    if (objectDescriptor == null) {
        throw new ReferenceAttributeNotAnOjbReferenceException(
                "Attribute requested (" + referenceName + ") is not listed "
                        + "in OJB as a reference-descriptor for class: '" + bo.getClass().getName() + "'");
    }

    // get the list of the foreign-keys for this reference-descriptor
    List fkFields = objectDescriptor.getForeignKeyFields();
    Iterator fkIterator = fkFields.iterator();

    // walk through the list of the foreign keys, get their types
    while (fkIterator.hasNext()) {

        // get the field name of the fk & pk field
        String fkFieldName = (String) fkIterator.next();

        // get the value for the fk field
        Object fkFieldValue = null;
        try {
            fkFieldValue = PropertyUtils.getSimpleProperty(bo, fkFieldName);
        }

        // if we cant retrieve the field value, then
        // it doesnt have a value
        catch (IllegalAccessException e) {
            return false;
        } catch (InvocationTargetException e) {
            return false;
        } catch (NoSuchMethodException e) {
            return false;
        }

        // test the value
        if (fkFieldValue == null) {
            return false;
        } else if (String.class.isAssignableFrom(fkFieldValue.getClass())) {
            if (StringUtils.isBlank((String) fkFieldValue)) {
                return false;
            }
        }
    }

    return allFkeysHaveValues;
}

From source file:org.kuali.rice.krad.service.impl.PersistenceServiceOjbImpl.java

/**
 *
 * @see org.kuali.rice.krad.service.PersistenceService#allForeignKeyValuesPopulatedForReference(org.kuali.rice.krad.bo.BusinessObject,
 *      java.lang.String)/*w w  w.  ja va2  s  .c  om*/
 */
@Override
public boolean allForeignKeyValuesPopulatedForReference(PersistableBusinessObject bo, String referenceName) {

    boolean allFkeysHaveValues = true;

    // yelp if nulls were passed in
    if (bo == null) {
        throw new IllegalArgumentException("The Class passed in for the BusinessObject argument was null.");
    }
    if (StringUtils.isBlank(referenceName)) {
        throw new IllegalArgumentException(
                "The String passed in for the referenceName argument was null or empty.");
    }

    PropertyDescriptor propertyDescriptor = null;

    // make sure the attribute exists at all, throw exception if not
    try {
        propertyDescriptor = PropertyUtils.getPropertyDescriptor(bo, referenceName);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    if (propertyDescriptor == null) {
        throw new ReferenceAttributeDoesntExistException("Requested attribute: '" + referenceName
                + "' does not exist " + "on class: '" + bo.getClass().getName() + "'.");
    }

    // get the class of the attribute name
    Class referenceClass = getBusinessObjectAttributeClass(bo.getClass(), referenceName);
    if (referenceClass == null) {
        referenceClass = propertyDescriptor.getPropertyType();
    }

    // make sure the class of the attribute descends from BusinessObject,
    // otherwise throw an exception
    if (!PersistableBusinessObject.class.isAssignableFrom(referenceClass)) {
        throw new ObjectNotABusinessObjectRuntimeException("Attribute requested (" + referenceName
                + ") is of class: " + "'" + referenceClass.getName() + "' and is not a "
                + "descendent of BusinessObject.  Only descendents of BusinessObject " + "can be used.");
    }

    // make sure the attribute designated is listed as a
    // reference-descriptor
    // on the clazz specified, otherwise throw an exception (OJB);
    ClassDescriptor classDescriptor = getClassDescriptor(bo.getClass());
    ObjectReferenceDescriptor referenceDescriptor = classDescriptor
            .getObjectReferenceDescriptorByName(referenceName);
    if (referenceDescriptor == null) {
        throw new ReferenceAttributeNotAnOjbReferenceException(
                "Attribute requested (" + referenceName + ") is not listed "
                        + "in OJB as a reference-descriptor for class: '" + bo.getClass().getName() + "'");
    }

    // get the list of the foreign-keys for this reference-descriptor
    // (OJB)
    Vector fkFields = referenceDescriptor.getForeignKeyFields();
    Iterator fkIterator = fkFields.iterator();

    // walk through the list of the foreign keys, get their types
    while (fkIterator.hasNext()) {

        // get the field name of the fk & pk field
        String fkFieldName = (String) fkIterator.next();

        // get the value for the fk field
        Object fkFieldValue = null;
        try {
            fkFieldValue = PropertyUtils.getSimpleProperty(bo, fkFieldName);
        }

        // if we cant retrieve the field value, then
        // it doesnt have a value
        catch (IllegalAccessException e) {
            return false;
        } catch (InvocationTargetException e) {
            return false;
        } catch (NoSuchMethodException e) {
            return false;
        }

        // test the value
        if (fkFieldValue == null) {
            return false;
        } else if (String.class.isAssignableFrom(fkFieldValue.getClass())) {
            if (StringUtils.isBlank((String) fkFieldValue)) {
                return false;
            }
        }
    }

    return allFkeysHaveValues;
}

From source file:org.kuali.rice.krad.service.impl.PersistenceStructureServiceJpaImpl.java

public Map<String, String> getInverseForeignKeysForCollection(Class boClass, String collectionName) {
    // yelp if nulls were passed in
    if (boClass == null) {
        throw new IllegalArgumentException("The Class passed in for the boClass argument was null.");
    }//  ww w . j a  v a 2  s . c om
    if (collectionName == null) {
        throw new IllegalArgumentException("The String passed in for the attributeName argument was null.");
    }

    PropertyDescriptor propertyDescriptor = null;

    // make an instance of the class passed
    Object classInstance;
    try {
        classInstance = boClass.newInstance();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    // make sure the attribute exists at all, throw exception if not
    try {
        propertyDescriptor = PropertyUtils.getPropertyDescriptor(classInstance, collectionName);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    if (propertyDescriptor == null) {
        throw new ReferenceAttributeDoesntExistException("Requested attribute: '" + collectionName
                + "' does not exist " + "on class: '" + boClass.getName() + "'. GFK");
    }

    // get the class of the attribute name
    Class attributeClass = propertyDescriptor.getPropertyType();

    // make sure the class of the attribute descends from BusinessObject,
    // otherwise throw an exception
    if (!Collection.class.isAssignableFrom(attributeClass)) {
        throw new ObjectNotABusinessObjectRuntimeException(
                "Attribute requested (" + collectionName + ") is of class: " + "'" + attributeClass.getName()
                        + "' and is not a " + "descendent of Collection");
    }

    EntityDescriptor descriptor = MetadataManager.getEntityDescriptor(boClass);
    org.kuali.rice.core.framework.persistence.jpa.metadata.CollectionDescriptor cd = descriptor
            .getCollectionDescriptorByName(collectionName);
    List<String> childPrimaryKeys = cd.getForeignKeyFields();

    List parentForeignKeys = getPrimaryKeys(boClass);

    if (parentForeignKeys.size() != childPrimaryKeys.size()) {
        throw new RuntimeException(
                "The number of keys in the class descriptor and the inverse foreign key mapping for the collection descriptors do not match.");
    }

    Map<String, String> fkToPkMap = new HashMap<String, String>();
    Iterator pFKIter = parentForeignKeys.iterator();
    Iterator cPKIterator = childPrimaryKeys.iterator();

    while (pFKIter.hasNext()) {
        String parentForeignKey = (String) pFKIter.next();
        String childPrimaryKey = (String) cPKIterator.next();

        fkToPkMap.put(parentForeignKey, childPrimaryKey);
    }
    return fkToPkMap;
}

From source file:org.kuali.rice.krad.service.impl.PersistenceStructureServiceJpaImpl.java

/**
 * @see org.kuali.rice.krad.service.PersistenceService#getForeignKeyFieldsPopulationState(org.kuali.rice.krad.bo.BusinessObject,
 *      java.lang.String)/*  w  w  w  .ja  v  a 2 s  .  c o  m*/
 */
public ForeignKeyFieldsPopulationState getForeignKeyFieldsPopulationState(PersistableBusinessObject bo,
        String referenceName) {

    boolean allFieldsPopulated = true;
    boolean anyFieldsPopulated = false;
    List<String> unpopulatedFields = new ArrayList<String>();

    // yelp if nulls were passed in
    if (bo == null) {
        throw new IllegalArgumentException("The Class passed in for the BusinessObject argument was null.");
    }
    if (StringUtils.isBlank(referenceName)) {
        throw new IllegalArgumentException(
                "The String passed in for the referenceName argument was null or empty.");
    }

    PropertyDescriptor propertyDescriptor = null;

    // make sure the attribute exists at all, throw exception if not
    try {
        propertyDescriptor = PropertyUtils.getPropertyDescriptor(bo, referenceName);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    if (propertyDescriptor == null) {
        throw new ReferenceAttributeDoesntExistException("Requested attribute: '" + referenceName
                + "' does not exist " + "on class: '" + bo.getClass().getName() + "'.");
    }

    // get the class of the attribute name
    Class referenceClass = propertyDescriptor.getPropertyType();

    // make sure the class of the attribute descends from BusinessObject,
    // otherwise throw an exception
    if (!PersistableBusinessObject.class.isAssignableFrom(referenceClass)) {
        throw new ObjectNotABusinessObjectRuntimeException("Attribute requested (" + referenceName
                + ") is of class: " + "'" + referenceClass.getName() + "' and is not a "
                + "descendent of BusinessObject.  Only descendents of BusinessObject " + "can be used.");
    }

    EntityDescriptor descriptor = MetadataManager.getEntityDescriptor(bo.getClass());
    ObjectDescriptor objectDescriptor = descriptor.getObjectDescriptorByName(referenceName);

    if (objectDescriptor == null) {
        throw new ReferenceAttributeNotAnOjbReferenceException(
                "Attribute requested (" + referenceName + ") is not listed "
                        + "in OJB as a reference-descriptor for class: '" + bo.getClass().getName() + "'");
    }

    List<String> fkFields = objectDescriptor.getForeignKeyFields();
    Iterator fkIterator = fkFields.iterator();

    // walk through the list of the foreign keys, get their types
    while (fkIterator.hasNext()) {

        // get the field name of the fk & pk field
        String fkFieldName = (String) fkIterator.next();

        // get the value for the fk field
        Object fkFieldValue = null;
        try {
            fkFieldValue = PropertyUtils.getSimpleProperty(bo, fkFieldName);
        }

        // abort if the value is not retrievable
        catch (Exception e) {
            throw new RuntimeException(e);
        }

        // test the value
        if (fkFieldValue == null) {
            allFieldsPopulated = false;
            unpopulatedFields.add(fkFieldName);
        } else if (fkFieldValue instanceof String) {
            if (StringUtils.isBlank((String) fkFieldValue)) {
                allFieldsPopulated = false;
                unpopulatedFields.add(fkFieldName);
            } else {
                anyFieldsPopulated = true;
            }
        } else {
            anyFieldsPopulated = true;
        }
    }

    // sanity check. if the flag for all fields populated is set, then
    // there should be nothing in the unpopulatedFields list
    if (allFieldsPopulated) {
        if (!unpopulatedFields.isEmpty()) {
            throw new RuntimeException("The flag is set that indicates all fields are populated, but there "
                    + "are fields present in the unpopulatedFields list.  This should never happen, and indicates "
                    + "that the logic in this method is broken.");
        }
    }

    return new ForeignKeyFieldsPopulationState(allFieldsPopulated, anyFieldsPopulated, unpopulatedFields);
}

From source file:org.kuali.rice.krad.service.impl.PersistenceStructureServiceOjbImpl.java

@Override
public Map<String, String> getInverseForeignKeysForCollection(Class boClass, String collectionName) {
    // yelp if nulls were passed in
    if (boClass == null) {
        throw new IllegalArgumentException("The Class passed in for the boClass argument was null.");
    }//w  w w .ja  va 2  s  . c o  m
    if (collectionName == null) {
        throw new IllegalArgumentException("The String passed in for the attributeName argument was null.");
    }

    PropertyDescriptor propertyDescriptor = null;

    // make an instance of the class passed
    Object classInstance;
    try {
        classInstance = boClass.newInstance();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    // make sure the attribute exists at all, throw exception if not
    try {
        propertyDescriptor = PropertyUtils.getPropertyDescriptor(classInstance, collectionName);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    if (propertyDescriptor == null) {
        throw new ReferenceAttributeDoesntExistException("Requested attribute: '" + collectionName
                + "' does not exist " + "on class: '" + boClass.getName() + "'. GFK");
    }

    // get the class of the attribute name
    Class attributeClass = propertyDescriptor.getPropertyType();

    // make sure the class of the attribute descends from BusinessObject,
    // otherwise throw an exception
    if (!Collection.class.isAssignableFrom(attributeClass)) {
        throw new ObjectNotABusinessObjectRuntimeException(
                "Attribute requested (" + collectionName + ") is of class: " + "'" + attributeClass.getName()
                        + "' and is not a " + "descendent of Collection");
    }

    // make sure the collection designated is listed as a
    // collection-descriptor
    // on the boClass specified, otherwise throw an exception
    ClassDescriptor classDescriptor = getClassDescriptor(boClass);
    CollectionDescriptor collectionDescriptor = classDescriptor.getCollectionDescriptorByName(collectionName);

    // in collections, the number of keys is equal to the number of keys in
    // the parent class (the class with the collection).
    // Each of the primary keys on the parent object will be mapped to a
    // field in the element object.

    List parentForeignKeys = getPrimaryKeys(boClass);
    Vector childPrimaryKeysLegacy = collectionDescriptor.getForeignKeyFields();

    if (parentForeignKeys.size() != childPrimaryKeysLegacy.size()) {
        throw new RuntimeException(
                "The number of keys in the class descriptor and the inverse foreign key mapping for the collection descriptors do not match.");
    }

    Map<String, String> fkToPkMap = new HashMap<String, String>();

    Iterator pFKIter = parentForeignKeys.iterator();
    Iterator cPKIterator = childPrimaryKeysLegacy.iterator();

    while (pFKIter.hasNext()) {
        String parentForeignKey = (String) pFKIter.next();
        String childPrimaryKey = (String) cPKIterator.next();

        fkToPkMap.put(parentForeignKey, childPrimaryKey);
    }

    return fkToPkMap;
}

From source file:org.kuali.rice.krad.service.impl.PersistenceStructureServiceOjbImpl.java

/**
 * @see org.kuali.rice.krad.service.PersistenceService#getForeignKeyFieldsPopulationState(org.kuali.rice.krad.bo.BusinessObject,
 *      java.lang.String)//from  w  ww. j  ava2  s  .c om
 */
@Override
public ForeignKeyFieldsPopulationState getForeignKeyFieldsPopulationState(PersistableBusinessObject bo,
        String referenceName) {
    boolean allFieldsPopulated = true;
    boolean anyFieldsPopulated = false;
    List<String> unpopulatedFields = new ArrayList<String>();

    // yelp if nulls were passed in
    if (bo == null) {
        throw new IllegalArgumentException("The Class passed in for the BusinessObject argument was null.");
    }
    if (StringUtils.isBlank(referenceName)) {
        throw new IllegalArgumentException(
                "The String passed in for the referenceName argument was null or empty.");
    }

    PropertyDescriptor propertyDescriptor = null;

    // make sure the attribute exists at all, throw exception if not
    try {
        propertyDescriptor = PropertyUtils.getPropertyDescriptor(bo, referenceName);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    if (propertyDescriptor == null) {
        throw new ReferenceAttributeDoesntExistException("Requested attribute: '" + referenceName
                + "' does not exist " + "on class: '" + bo.getClass().getName() + "'.");
    }

    // get the class of the attribute name
    Class referenceClass = propertyDescriptor.getPropertyType();

    // make sure the class of the attribute descends from BusinessObject,
    // otherwise throw an exception
    if (!PersistableBusinessObject.class.isAssignableFrom(referenceClass)) {
        throw new ObjectNotABusinessObjectRuntimeException("Attribute requested (" + referenceName
                + ") is of class: " + "'" + referenceClass.getName() + "' and is not a "
                + "descendent of BusinessObject.  Only descendents of BusinessObject " + "can be used.");
    }

    // make sure the attribute designated is listed as a
    // reference-descriptor
    // on the clazz specified, otherwise throw an exception (OJB);

    ClassDescriptor classDescriptor = getClassDescriptor(bo.getClass());

    // This block is a combination of legacy and jpa
    ObjectReferenceDescriptor referenceDescriptor = classDescriptor
            .getObjectReferenceDescriptorByName(referenceName);
    if (referenceDescriptor == null) {
        throw new ReferenceAttributeNotAnOjbReferenceException(
                "Attribute requested (" + referenceName + ") is not listed "
                        + "in OJB as a reference-descriptor for class: '" + bo.getClass().getName() + "'");
    }

    // get the list of the foreign-keys for this reference-descriptor
    Vector fkFieldsLegacy = referenceDescriptor.getForeignKeyFields();
    Iterator fkIteratorLegacy = fkFieldsLegacy.iterator();

    // walk through the list of the foreign keys, get their types
    while (fkIteratorLegacy.hasNext()) {

        // get the field name of the fk & pk field
        String fkFieldName = (String) fkIteratorLegacy.next();

        // get the value for the fk field
        Object fkFieldValue = null;
        try {
            fkFieldValue = PropertyUtils.getSimpleProperty(bo, fkFieldName);
        }

        // abort if the value is not retrievable
        catch (Exception e) {
            throw new RuntimeException(e);
        }

        // test the value
        if (fkFieldValue == null) {
            allFieldsPopulated = false;
            unpopulatedFields.add(fkFieldName);
        } else if (fkFieldValue instanceof String) {
            if (StringUtils.isBlank((String) fkFieldValue)) {
                allFieldsPopulated = false;
                unpopulatedFields.add(fkFieldName);
            } else {
                anyFieldsPopulated = true;
            }
        } else {
            anyFieldsPopulated = true;
        }
    }

    // sanity check. if the flag for all fields populated is set, then
    // there should be nothing in the unpopulatedFields list
    if (allFieldsPopulated) {
        if (!unpopulatedFields.isEmpty()) {
            throw new RuntimeException("The flag is set that indicates all fields are populated, but there "
                    + "are fields present in the unpopulatedFields list.  This should never happen, and indicates "
                    + "that the logic in this method is broken.");
        }
    }

    return new ForeignKeyFieldsPopulationState(allFieldsPopulated, anyFieldsPopulated, unpopulatedFields);
}