Example usage for java.beans PropertyDescriptor getPropertyType

List of usage examples for java.beans PropertyDescriptor getPropertyType

Introduction

In this page you can find the example usage for java.beans PropertyDescriptor getPropertyType.

Prototype

public synchronized Class<?> getPropertyType() 

Source Link

Document

Returns the Java type info for the property.

Usage

From source file:com.nway.spring.jdbc.bean.AsmBeanProcessor.java

/**
 * Creates a new object and initializes its fields from the ResultSet.
 *
 * @param <T> The type of bean to create
 * @param rs The result set.//from w  ww  .  j av a2  s.  c  om
 * @param type The bean type (the return type of the object).
 * @param props The property descriptors.
 * @param columnToProperty The column indices in the result set.
 * @return An initialized object.
 * @throws SQLException if a database error occurs.
 */
private <T> T createBeanByASM(ResultSet rs, Class<T> mappedClass, String key) throws SQLException {

    DbBeanFactory dynamicRse = DBBEANFACTORY_CACHE.get(key);

    // 
    if (dynamicRse != null) {

        return dynamicRse.createBean(rs, mappedClass);
    }

    T bean = this.newInstance(mappedClass);

    ResultSetMetaData rsmd = rs.getMetaData();

    MethodVisitor mv = null;

    final ClassWriter cw = new ClassWriter(0);

    PropertyDescriptor[] props = BeanUtils.getPropertyDescriptors(mappedClass);

    int[] columnToProperty = this.mapColumnsToProperties(rsmd, props);

    String beanName = mappedClass.getName().replace('.', '/');

    String processorName = DynamicClassUtils.getBeanProcessorName(mappedClass);

    String internalProcessorName = processorName.replace('.', '/');

    Object[] labelArr = prepScript(cw, mv, internalProcessorName, beanName);

    mv = (MethodVisitor) labelArr[1];

    Label firstLabel = null;
    PropertyDescriptor desc = null;

    for (int i = 1; i < columnToProperty.length; i++) {

        if (columnToProperty[i] == PROPERTY_NOT_FOUND) {
            continue;
        }

        desc = props[columnToProperty[i]];
        Class<?> propType = desc.getPropertyType();

        if (null == firstLabel) {

            firstLabel = firstLabel(mv, beanName, 12);
        } else {

            visitLabel(mv, 11 + i);
        }

        //  rs.getXXX
        Object value = processColumn(rs, i, propType, desc.getWriteMethod().getName(), internalProcessorName,
                beanName, mv);

        this.callSetter(bean, desc, value);
    }

    if (firstLabel != null) {

        endScript(mv, (Label) labelArr[0], firstLabel, 12 + columnToProperty.length, internalProcessorName,
                beanName);

        cw.visitEnd();

        try {

            DynamicBeanClassLoader beanClassLoader = new DynamicBeanClassLoader(
                    ClassUtils.getDefaultClassLoader());

            Class<?> processor = beanClassLoader.defineClass(processorName, cw.toByteArray());

            DBBEANFACTORY_CACHE.put(key, (DbBeanFactory) processor.newInstance());

        } catch (Exception e) {

            throw new DynamicObjectException("ASM [ " + processorName + " ] ", e);
        }
    }

    return bean;
}

From source file:com.boylesoftware.web.impl.UserInputControllerMethodArgHandler.java

@Override
public boolean prepareUserInput(final RouterRequest request) throws ServletException {

    boolean success = false;
    final PoolableUserInput pooledUserInput = this.beanPool.getSync();
    try {/*  w  ww. j ava 2s.c  om*/
        request.setAttribute(POOLED_OBJ_ATTNAME, pooledUserInput);
        final Object bean = pooledUserInput.getBean();
        request.setAttribute(Attributes.USER_INPUT, bean);
        final UserInputErrors errors = request.getUserInputErrors();
        request.setAttribute(Attributes.USER_INPUT_ERRORS, errors);

        // bind the bean properties
        final int numProps = this.beanFields.length;
        for (int i = 0; i < numProps; i++) {
            final FieldDesc fieldDesc = this.beanFields[i];
            final PropertyDescriptor propDesc = fieldDesc.getPropDesc();
            final String propName = propDesc.getName();
            final String propValStr = (fieldDesc.isNoTrim()
                    ? StringUtils.nullIfEmpty(request.getParameter(propName))
                    : StringUtils.trimToNull(request.getParameter(propName)));
            final Method propSetter = propDesc.getWriteMethod();
            try {
                propSetter.invoke(bean, fieldDesc.getBinder().convert(request, propValStr,
                        fieldDesc.getFormat(), propDesc.getPropertyType()));
            } catch (final BindingException e) {
                if (this.log.isDebugEnabled())
                    this.log.debug("binding error", e);
                propSetter.invoke(bean, e.getDefaultValue());
                errors.add(propName, fieldDesc.getErrorMessage());
            }
        }

        // validate the bean
        final Validator validator = this.validatorFactory.usingContext()
                .messageInterpolator(request.getMessageInterpolator()).getValidator();
        Class<?>[] validationGroups = this.validationGroups;
        if ((this.validationGroups.length == 0) && (bean instanceof DynamicValidationGroups))
            validationGroups = ((DynamicValidationGroups) bean).getValidationGroups(request);
        final Set<ConstraintViolation<Object>> cvs = validator.validate(bean, validationGroups);
        final boolean valid = cvs.isEmpty();
        if (!valid) {
            for (final ConstraintViolation<Object> cv : cvs)
                errors.add(cv.getPropertyPath().toString(), cv.getMessage());
        }

        success = true;

        return valid;

    } catch (final IllegalAccessException | InvocationTargetException e) {
        throw new ServletException("Error working with user input bean.", e);
    } finally {
        if (!success)
            pooledUserInput.recycle();
    }
}

From source file:com.interface21.beans.BeanWrapperImpl.java

public PropertyEditor doFindCustomEditor(Class requiredType, String propertyName) {
    if (this.customEditors == null) {
        return null;
    }//  w ww  .  ja  v a 2s .  com
    if (propertyName != null) {
        // check property-specific editor first
        PropertyDescriptor descriptor = getPropertyDescriptor(propertyName);
        PropertyEditor editor = (PropertyEditor) this.customEditors.get(propertyName);
        if (editor != null) {
            // consistency check
            if (requiredType != null) {
                if (!descriptor.getPropertyType().isAssignableFrom(requiredType)) {
                    throw new IllegalArgumentException("Types do not match: required=" + requiredType.getName()
                            + ", found=" + descriptor.getPropertyType());
                }
            }
            return editor;
        } else {
            if (requiredType == null) {
                // try property type
                requiredType = descriptor.getPropertyType();
            }
        }
    }
    // no property-specific editor -> check type-specific editor
    return (PropertyEditor) this.customEditors.get(requiredType);
}

From source file:org.ambraproject.article.service.IngesterImpl.java

/**
 * Update an existing article by copying properties from the new one over.  Note that we can't call saveOrUpdate,
 * since the new article is not a persistent instance, but has all the properties that we want.
 * <p/>/*from w ww.j  av  a2  s.c  o  m*/
 * See <a href="http://stackoverflow.com/questions/4779239/update-persistent-object-with-transient-object-using-hibernate">this
 * post on stack overflow</a> for more information
 * <p/>
 * For collections, we clear the old property and add all the new entries, relying on 'delete-orphan' to delete the
 * old objects. The downside of this approach is that it results in a delete statement for each entry in the old
 * collection, and an insert statement for each entry in the new collection.  There a couple of things we could do to
 * optimize this: <ol> <li>Write a sql statement to delete the old entries in one go</li> <li>copy over collection
 * properties recursively instead of clearing the old collection.  e.g. for {@link Article#assets}, instead of
 * clearing out the old list, we would find the matching asset by DOI and Extension, and update its properties</li>
 * </ol>
 * <p/>
 * Option number 2 is messy and a lot of code (I've done it before)
 *
 * @param article         the new article, parsed from the xml
 * @param existingArticle the article pulled up from the database
 * @throws IngestException if there's a problem copying properties or updating
 */
@SuppressWarnings("unchecked")
private void updateArticle(final Article article, final Article existingArticle) throws IngestException {
    log.debug("ReIngesting (force ingest) article: {}", existingArticle.getDoi());
    //Hibernate deletes orphans after inserting the new rows, which violates a unique constraint on (doi, extension) for assets
    //this temporary change gets around the problem, before the old assets are orphaned and deleted
    hibernateTemplate.execute(new HibernateCallback() {
        @Override
        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            session.createSQLQuery("update articleAsset " + "set doi = concat('old-',doi), "
                    + "extension = concat('old-',extension) " + "where articleID = :articleID")
                    .setParameter("articleID", existingArticle.getID()).executeUpdate();
            return null;
        }
    });

    final BeanWrapper source = new BeanWrapperImpl(article);
    final BeanWrapper destination = new BeanWrapperImpl(existingArticle);

    try {
        //copy properties
        for (final PropertyDescriptor property : destination.getPropertyDescriptors()) {
            final String name = property.getName();
            if (!name.equals("ID") && !name.equals("created") && !name.equals("lastModified")
                    && !name.equals("class")) {
                //Collections shouldn't be dereferenced but have elements added
                //See http://www.onkarjoshi.com/blog/188/hibernateexception-a-collection-with-cascade-all-delete-orphan-was-no-longer-referenced-by-the-owning-entity-instance/
                if (Collection.class.isAssignableFrom(property.getPropertyType())) {
                    Collection orig = (Collection) destination.getPropertyValue(name);
                    orig.clear();
                    Collection sourcePropertyValue = (Collection) source.getPropertyValue(name);
                    if (sourcePropertyValue != null) {
                        orig.addAll((Collection) source.getPropertyValue(name));
                    }
                } else {
                    //just set the new value
                    destination.setPropertyValue(name, source.getPropertyValue(name));
                }
            }
        }
        //Circular relationship in related articles
        for (ArticleRelationship articleRelationship : existingArticle.getRelatedArticles()) {
            articleRelationship.setParentArticle(existingArticle);
        }
    } catch (Exception e) {
        throw new IngestException("Error copying properties for article " + article.getDoi(), e);
    }

    hibernateTemplate.update(existingArticle);
}

From source file:org.fudgemsg.mapping.JavaBeanBuilder.java

/**
 * Creates a new {@link JavaBeanBuilder} for a class.
 * //from w w  w .  j  a  v a 2  s.c o  m
 * @param <T> class the builder should process
 * @param clazz class the builder should process
 * @return the {@code JavaBeanBuilder}
 */
/* package */ static <T> JavaBeanBuilder<T> create(final Class<T> clazz) {
    // customise the properties
    final ArrayList<JBProperty> propList = new ArrayList<JBProperty>();
    for (PropertyDescriptor prop : PropertyUtils.getPropertyDescriptors(clazz)) {
        // ignore the class
        if (prop.getName().equals("class"))
            continue;
        // check for FudgeFieldName annotations on either accessor or mutator
        FudgeFieldName annoName;
        FudgeFieldOrdinal annoOrdinal;
        String name = prop.getName();
        Integer ordinal = null;
        if (prop.getWriteMethod() != null) {
            // give up if it's a transient property
            if (TransientUtil.hasTransientAnnotation(prop.getWriteMethod()))
                continue;
            if ((annoName = prop.getWriteMethod().getAnnotation(FudgeFieldName.class)) != null)
                name = annoName.value();
            if ((annoOrdinal = prop.getWriteMethod().getAnnotation(FudgeFieldOrdinal.class)) != null) {
                ordinal = (int) annoOrdinal.value();
                if (annoOrdinal.noFieldName())
                    name = null;
            }
        }
        if (prop.getReadMethod() != null) {
            // give up if it's a transient property
            if (TransientUtil.hasTransientAnnotation(prop.getReadMethod()))
                continue;
            if ((annoName = prop.getReadMethod().getAnnotation(FudgeFieldName.class)) != null)
                name = annoName.value();
            if ((annoOrdinal = prop.getReadMethod().getAnnotation(FudgeFieldOrdinal.class)) != null) {
                ordinal = (int) annoOrdinal.value();
                if (annoOrdinal.noFieldName())
                    name = null;
            }
        }
        propList.add(new JBProperty(name, ordinal, prop.getReadMethod(), prop.getWriteMethod(),
                prop.getPropertyType()));
    }
    // try and find a constructor
    try {
        return new JavaBeanBuilder<T>(propList.toArray(new JBProperty[propList.size()]),
                clazz.getConstructor());
    } catch (SecurityException e) {
        // ignore
    } catch (NoSuchMethodException e) {
        // ignore
    }
    // otherwise bean behaviour (about 5 times slower!)
    return new JavaBeanBuilder<T>(propList.toArray(new JBProperty[propList.size()]), clazz.getName());
}

From source file:org.agnitas.service.impl.NewImportWizardServiceImpl.java

protected Node createNode(Object context, String name) throws Exception {
    Class type = null;/*from   w w  w  . j av a 2  s .  c o  m*/

    // If the name represents a JavaBean property of the current context
    // then we derive the type from that...
    PropertyDescriptor propertyDescriptor = Toolkit.getPropertyDescriptor(context, name);
    if (propertyDescriptor != null) {
        type = propertyDescriptor.getPropertyType();
    } else if (context != null && !classMap.containsKey(name)) {
        return new FieldNode(context, name);
    } else {
        // ... otherwise we look for a named type alias
        type = classMap.get(name);
    }

    if (type == null) {
        throw new IllegalArgumentException(
                String.format("No type mapping could be found or derived: name=%s", name));
    }

    // If there's a format for the node's type then we go with that...
    if (type.isAssignableFrom(String.class) || type.isAssignableFrom(Map.class)) {
        return new FieldNode(context, name);
    }

    // ...otherwise we've got some sort of mutable node value.
    Object instance;
    // If the node corresponds to a JavaBean property which already has a
    // value then we mutate that...
    if (propertyDescriptor != null) {
        instance = propertyDescriptor.getReadMethod().invoke(context);
        if (instance == null) {
            instance = type.newInstance();
            propertyDescriptor.getWriteMethod().invoke(context, instance);
        }
    } else {
        // ...otherwise we're just dealing with some non-property instance
        instance = type.newInstance();
    }

    // Collections are handled in a special way - all properties are
    // basically their values
    if (instance instanceof Collection) {
        return new CollectionNode(name, (Collection) instance);
    }
    // Everything else is assumed to be a JavaBean
    return new JavaBeanNode(instance, name);
}

From source file:net.yasion.common.core.bean.wrapper.ExtendedBeanInfo.java

private PropertyDescriptor findExistingPropertyDescriptor(String propertyName, Class<?> propertyType) {
    for (PropertyDescriptor pd : this.propertyDescriptors) {
        final Class<?> candidateType;
        final String candidateName = pd.getName();
        if (pd instanceof IndexedPropertyDescriptor) {
            IndexedPropertyDescriptor ipd = (IndexedPropertyDescriptor) pd;
            candidateType = ipd.getIndexedPropertyType();
            if (candidateName.equals(propertyName) && (candidateType.equals(propertyType)
                    || candidateType.equals(propertyType.getComponentType()))) {
                return pd;
            }//from   w ww . j  a  va  2 s .  com
        } else {
            candidateType = pd.getPropertyType();
            if (candidateName.equals(propertyName) && (candidateType.equals(propertyType)
                    || propertyType.equals(candidateType.getComponentType()))) {
                return pd;
            }
        }
    }
    return null;
}

From source file:com.bstek.dorado.view.output.ClientOutputHelper.java

protected Map<String, PropertyConfig> doGetPropertyConfigs(Class<?> beanType) throws Exception {
    beanType = ProxyBeanUtils.getProxyTargetType(beanType);
    Map<String, PropertyConfig> propertyConfigs = new HashMap<String, PropertyConfig>();

    ClientObjectInfo clientObjectInfo = getClientObjectInfo(beanType);
    if (clientObjectInfo != null) {
        for (Map.Entry<String, ClientProperty> entry : clientObjectInfo.getPropertyConfigs().entrySet()) {
            String property = entry.getKey();
            ClientProperty clientProperty = entry.getValue();

            PropertyConfig propertyConfig = new PropertyConfig();
            if (clientProperty.ignored()) {
                propertyConfig.setIgnored(true);
            } else {
                if (StringUtils.isNotEmpty(clientProperty.outputter())) {
                    BeanWrapper beanWrapper = BeanFactoryUtils.getBean(clientProperty.outputter(),
                            Scope.instant);
                    propertyConfig.setOutputter(beanWrapper.getBean());
                }/*from www .j  av  a2s.co m*/

                if (clientProperty.alwaysOutput()) {
                    propertyConfig.setEscapeValue(FAKE_ESCAPE_VALUE);
                } else if (StringUtils.isNotEmpty(clientProperty.escapeValue())) {
                    propertyConfig.setEscapeValue(clientProperty.escapeValue());
                }
            }
            propertyConfigs.put(property, propertyConfig);
        }
    }

    boolean isAssembledComponent = (AssembledComponent.class.isAssignableFrom(beanType));
    Class<?> superComponentType = null;
    if (isAssembledComponent) {
        superComponentType = beanType;
        while (superComponentType != null && AssembledComponent.class.isAssignableFrom(superComponentType)) {
            superComponentType = superComponentType.getSuperclass();
            Assert.notNull(superComponentType);
        }
    }

    for (PropertyDescriptor propertyDescriptor : PropertyUtils.getPropertyDescriptors(beanType)) {
        String property = propertyDescriptor.getName();
        Method readMethod = propertyDescriptor.getReadMethod();
        if (readMethod.getDeclaringClass() != beanType) {
            try {
                readMethod = beanType.getMethod(readMethod.getName(), readMethod.getParameterTypes());
            } catch (NoSuchMethodException e) {
                // do nothing
            }
        }

        TypeInfo typeInfo;
        Class<?> propertyType = propertyDescriptor.getPropertyType();
        if (Collection.class.isAssignableFrom(propertyType)) {
            typeInfo = TypeInfo.parse((ParameterizedType) readMethod.getGenericReturnType(), true);
            if (typeInfo != null) {
                propertyType = typeInfo.getType();
            }
        } else if (propertyType.isArray()) {
            typeInfo = new TypeInfo(propertyType.getComponentType(), true);
        } else {
            typeInfo = new TypeInfo(propertyType, false);
        }

        PropertyConfig propertyConfig = null;
        ClientProperty clientProperty = readMethod.getAnnotation(ClientProperty.class);
        if (clientProperty != null) {
            propertyConfig = new PropertyConfig();
            if (clientProperty.ignored()) {
                propertyConfig.setIgnored(true);
            } else {
                if (StringUtils.isNotEmpty(clientProperty.outputter())) {
                    BeanWrapper beanWrapper = BeanFactoryUtils.getBean(clientProperty.outputter(),
                            Scope.instant);
                    propertyConfig.setOutputter(beanWrapper.getBean());
                } else if (Component.class.isAssignableFrom(propertyType)) {
                    BeanWrapper beanWrapper = BeanFactoryUtils.getBean(COMPONENT_OUTPUTTER, Scope.instant);
                    propertyConfig.setOutputter(beanWrapper.getBean());
                } else if (DataControl.class.isAssignableFrom(propertyType)
                        || FloatControl.class.isAssignableFrom(propertyType)) {
                    BeanWrapper beanWrapper = BeanFactoryUtils.getBean(COMPONENT_OUTPUTTER, Scope.instant);
                    propertyConfig.setOutputter(beanWrapper.getBean());
                } else if (DataType.class.isAssignableFrom(propertyType)) {
                    BeanWrapper beanWrapper = BeanFactoryUtils.getBean(DATA_TYPE_PROPERTY_OUTPUTTER,
                            Scope.instant);
                    propertyConfig.setOutputter(beanWrapper.getBean());
                } else if (Object.class.equals(propertyType)) {
                    BeanWrapper beanWrapper = BeanFactoryUtils.getBean(DATA_OUTPUTTER, Scope.instant);
                    propertyConfig.setOutputter(beanWrapper.getBean());
                } else if (!EntityUtils.isSimpleType(propertyType) && !propertyType.isArray()) {
                    BeanWrapper beanWrapper = BeanFactoryUtils.getBean(OBJECT_OUTPUTTER, Scope.instant);
                    propertyConfig.setOutputter(beanWrapper.getBean());
                }

                if (!clientProperty.evaluateExpression()) {
                    propertyConfig.setEvaluateExpression(false);
                }

                if (clientProperty.alwaysOutput()) {
                    propertyConfig.setEscapeValue(FAKE_ESCAPE_VALUE);
                } else if (StringUtils.isNotEmpty(clientProperty.escapeValue())) {
                    propertyConfig.setEscapeValue(clientProperty.escapeValue());
                }
            }
        } else if (isAssembledComponent && readMethod.getDeclaringClass() == beanType
                && EntityUtils.isSimpleType(propertyType)) {
            if (BeanUtils.getPropertyDescriptor(superComponentType, property) == null) {
                propertyConfig = new PropertyConfig();
                propertyConfig.setIgnored(true);
            }
        }

        ComponentReference componentReference = readMethod.getAnnotation(ComponentReference.class);
        if (componentReference != null && String.class.equals(propertyType)) {
            if (propertyConfig == null) {
                propertyConfig = new PropertyConfig();
            }
            if (propertyConfig.getOutputter() == null) {
                BeanWrapper beanWrapper = BeanFactoryUtils.getBean(COMPONENT_REFERENCE_OUTPUTTER,
                        Scope.instant);
                propertyConfig.setOutputter(beanWrapper.getBean());
            }
        }

        if (!propertyType.isPrimitive() && (Number.class.isAssignableFrom(propertyType)
                || Boolean.class.isAssignableFrom(propertyType))) {
            if (propertyConfig == null) {
                propertyConfig = new PropertyConfig();
            }
            if (propertyConfig.getEscapeValue() == PropertyConfig.NONE_VALUE) {
                propertyConfig.setEscapeValue(null);
            }
        }

        if (propertyConfig != null) {
            propertyConfigs.put(property, propertyConfig);
        }
    }
    return (propertyConfigs.isEmpty()) ? null : propertyConfigs;
}

From source file:org.ajax4jsf.builder.config.ComponentBaseBean.java

/**
 * Subclasses should extend this method to provide specifc checks
 * /* w w w  .  j a va2 s  .  co  m*/
 * Check existing and default properties
 * For properties filled from configuration, attempt to set additional parameters.
 * If base class have any bean properties, append it to configured
 * @throws ConfigurationException 
 */
public void checkProperties() throws ParsingException {
    try {
        getLog().debug("Parse properties for Component " + getName() + " with superclass " + getSuperclass());
        if (getSuperclass() != null) {
            Class<?> superClass = getLoader().loadClass(getSuperclass());

            new ClassWalkingLogic(superClass).walk(new ClassVisitor() {
                public void visit(Class<?> clazz) {
                    checkPropertiesForClass(clazz);
                }
            });
        }
    } catch (ClassNotFoundException e) {
        getLog().error("superclass not found for component " + getName(), e);
    }
    if (null != getTag()) {
        try {
            Class superClass = getLoader().loadClass(getTag().getSuperclass());
            PropertyDescriptor[] properties = PropertyUtils.getPropertyDescriptors(superClass);
            // for all properties, add it to component. If property have not abstract getter/setter ,
            // add it with exist = true . If property in list of hidden names, set hidden = true.
            for (int i = 0; i < properties.length; i++) {
                PropertyDescriptor descriptor = properties[i];
                Method writeMethod = descriptor.getWriteMethod();
                if (containProperty(descriptor.getName())) {
                    if (null != writeMethod && !Modifier.isAbstract(writeMethod.getModifiers())
                            && Modifier.isPublic(writeMethod.getModifiers())) {
                        ((PropertyBean) this.properties.get(descriptor.getName())).setExistintag(true);
                    }
                } else if (null != writeMethod && Modifier.isPublic(writeMethod.getModifiers())) {
                    if (Arrays.asList(enabledTagProperties).contains(descriptor.getName())) {
                        Class type = descriptor.getPropertyType();
                        getLog().debug("Register tag property  " + descriptor.getName() + " with type name "
                                + type.getCanonicalName());
                        PropertyBean property = new PropertyBean();
                        property.setName(descriptor.getName());
                        property.setDescription(descriptor.getShortDescription());
                        property.setDisplayname(descriptor.getDisplayName());
                        property.setClassname(descriptor.getPropertyType().getCanonicalName());
                        property.setExist(true);
                        if (!Modifier.isAbstract(writeMethod.getModifiers())) {
                            property.setExistintag(true);
                        }
                        addProperty(property);
                    }
                }
            }
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            getLog().error("superclass not found for tag " + getTag().getName(), e);
        }

    }
}

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  av  a2  s  .c om
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;
}