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:org.kuali.rice.krad.util.ObjectUtils.java

/**
 * Recursive; sets all occurences of the property in the object, its nested objects and its object lists with the
 * given value.//from   ww w . j  ava  2 s .  c o  m
 *
 * @param bo
 * @param propertyName
 * @param type
 * @param propertyValue
 * @throws NoSuchMethodException
 * @throws InvocationTargetException
 * @throws IllegalAccessException
 */
public static void setObjectPropertyDeep(Object bo, String propertyName, Class type, Object propertyValue)
        throws FormatException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {

    // Base return cases to avoid null pointers & infinite loops
    if (isNull(bo) || !PropertyUtils.isReadable(bo, propertyName)
            || (propertyValue != null && propertyValue.equals(getPropertyValue(bo, propertyName)))
            || (type != null && !type.equals(easyGetPropertyType(bo, propertyName)))) {
        return;
    }

    // need to materialize the updateable collections before resetting the property, because it may be used in the retrieval
    materializeUpdateableCollections(bo);

    // Set the property in the BO
    setObjectProperty(bo, propertyName, type, propertyValue);

    // Now drill down and check nested BOs and BO lists
    PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(bo.getClass());
    for (int i = 0; i < propertyDescriptors.length; i++) {

        PropertyDescriptor propertyDescriptor = propertyDescriptors[i];

        // Business Objects
        if (propertyDescriptor.getPropertyType() != null
                && (BusinessObject.class).isAssignableFrom(propertyDescriptor.getPropertyType())
                && PropertyUtils.isReadable(bo, propertyDescriptor.getName())) {
            Object nestedBo = getPropertyValue(bo, propertyDescriptor.getName());
            if (nestedBo instanceof BusinessObject) {
                setObjectPropertyDeep(nestedBo, propertyName, type, propertyValue);
            }
        }

        // Lists
        else if (propertyDescriptor.getPropertyType() != null
                && (List.class).isAssignableFrom(propertyDescriptor.getPropertyType())
                && getPropertyValue(bo, propertyDescriptor.getName()) != null) {

            List propertyList = (List) getPropertyValue(bo, propertyDescriptor.getName());
            for (Object listedBo : propertyList) {
                if (listedBo != null && listedBo instanceof BusinessObject) {
                    setObjectPropertyDeep(listedBo, propertyName, type, propertyValue);
                }
            } // end for
        }
    } // end for
}

From source file:io.github.moosbusch.lumpi.gui.form.spi.AbstractDynamicForm.java

protected final Form.Section createSection(Class<?> beanClass, PropertyDescriptor[] propDescs)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    Form.Section result = new Form.Section();
    String sectHeading = getSectionHeading();
    Map<String, Class<?>> propertyMap = new HashMap<>();
    propertyMap.setComparator(Comparator.naturalOrder());

    if ((isShowSectionHeading()) && (StringUtils.isNotBlank(sectHeading))) {
        result.setHeading(sectHeading);//from   w  w w  .  java 2  s.c om
    }

    for (PropertyDescriptor propDesc : propDescs) {
        propertyMap.put(propDesc.getName(), propDesc.getPropertyType());
    }

    for (String propertyName : propertyMap) {
        Class<?> propertyClass = ClassUtils.primitiveToWrapper(propertyMap.get(propertyName));

        FormEditor<? extends Component> editor;

        if (!isExcludedProperty(beanClass, propertyName)) {
            editor = getEditor(beanClass.getName(), propertyClass.getName(), propertyName);

            if (editor != null) {
                Component cmp = editor.getComponent();
                PropertyUtils.setProperty(cmp, editor.getDataBindingKeyPropertyName(), propertyName);
                setLabel(cmp, StringUtils.capitalize(propertyName));

                if (editor.isScrollable()) {
                    ScrollPane scroll = Objects.requireNonNull(createScrollPane());
                    scroll.setView(cmp);
                    result.add(scroll);
                } else {
                    result.add(cmp);
                }
            }
        }
    }

    return result;
}

From source file:org.kuali.kfs.module.ar.businessobject.lookup.CustomerInvoiceWriteoffLookupResultLookupableHelperServiceImpl.java

/**
 * @param element// w  w  w. j a v a 2s.  co  m
 * @param attributeName
 * @return Column
 *
 * KRAD Conversion: setup up the results column in the display results set.
 *
 * No use of data dictionary.
 */
protected Column setupResultsColumn(BusinessObject element, String attributeName,
        BusinessObjectRestrictions businessObjectRestrictions) {
    Column col = new Column();

    col.setPropertyName(attributeName);

    String columnTitle = getDataDictionaryService().getAttributeLabel(element.getClass(), attributeName);
    if (StringUtils.isBlank(columnTitle)) {
        columnTitle = getDataDictionaryService().getCollectionLabel(element.getClass(), attributeName);
    }
    col.setColumnTitle(columnTitle);
    col.setMaxLength(getDataDictionaryService().getAttributeMaxLength(element.getClass(), attributeName));

    try {
        Class formatterClass = getDataDictionaryService().getAttributeFormatter(element.getClass(),
                attributeName);
        Formatter formatter = null;
        if (formatterClass != null) {
            formatter = (Formatter) formatterClass.newInstance();
            col.setFormatter(formatter);
        }

        // pick off result column from result list, do formatting
        String propValue = KFSConstants.EMPTY_STRING;
        Object prop = ObjectUtils.getPropertyValue(element, attributeName);

        // set comparator and formatter based on property type
        Class propClass = null;
        PropertyDescriptor propDescriptor = PropertyUtils.getPropertyDescriptor(element, col.getPropertyName());
        if (propDescriptor != null) {
            propClass = propDescriptor.getPropertyType();
        }

        // formatters
        if (prop != null) {
            propValue = getContractsGrantsReportHelperService().formatByType(prop, formatter);
        }

        // comparator
        col.setComparator(CellComparatorHelper.getAppropriateComparatorForPropertyClass(propClass));
        col.setValueComparator(CellComparatorHelper.getAppropriateValueComparatorForPropertyClass(propClass));
        propValue = super.maskValueIfNecessary(element.getClass(), col.getPropertyName(), propValue,
                businessObjectRestrictions);
        col.setPropertyValue(propValue);

        if (StringUtils.isNotBlank(propValue)) {
            col.setColumnAnchor(getInquiryUrl(element, col.getPropertyName()));
        }
    } catch (InstantiationException ie) {
        throw new RuntimeException(
                "Unable to get new instance of formatter class for property " + col.getPropertyName(), ie);
    } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException ex) {
        throw new RuntimeException("Cannot access PropertyType for property " + "'" + col.getPropertyName()
                + "' " + " on an instance of '" + element.getClass().getName() + "'.", ex);
    }
    return col;
}

From source file:org.kuali.rice.krad.util.ObjectUtils.java

public static void setObjectPropertyDeep(Object bo, String propertyName, Class type, Object propertyValue,
        int depth)
        throws FormatException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    // Base return cases to avoid null pointers & infinite loops
    if (depth == 0 || isNull(bo) || !PropertyUtils.isReadable(bo, propertyName)) {
        return;/*from  w  w w  . ja va  2 s  . c o  m*/
    }

    // need to materialize the updateable collections before resetting the property, because it may be used in the retrieval
    try {
        materializeUpdateableCollections(bo);
    } catch (ClassNotPersistableException ex) {
        //Not all classes will be persistable in a collection. For e.g. externalizable business objects.
        LOG.info("Not persistable dataObjectClass: " + bo.getClass().getName() + ", field: " + propertyName);
    }

    // Set the property in the BO
    setObjectProperty(bo, propertyName, type, propertyValue);

    // Now drill down and check nested BOs and BO lists
    PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(bo.getClass());
    for (int i = 0; i < propertyDescriptors.length; i++) {
        PropertyDescriptor propertyDescriptor = propertyDescriptors[i];

        // Business Objects
        if (propertyDescriptor.getPropertyType() != null
                && (BusinessObject.class).isAssignableFrom(propertyDescriptor.getPropertyType())
                && PropertyUtils.isReadable(bo, propertyDescriptor.getName())) {
            Object nestedBo = getPropertyValue(bo, propertyDescriptor.getName());
            if (nestedBo instanceof BusinessObject) {
                setObjectPropertyDeep(nestedBo, propertyName, type, propertyValue, depth - 1);
            }
        }

        // Lists
        else if (propertyDescriptor.getPropertyType() != null
                && (List.class).isAssignableFrom(propertyDescriptor.getPropertyType())
                && getPropertyValue(bo, propertyDescriptor.getName()) != null) {

            List propertyList = (List) getPropertyValue(bo, propertyDescriptor.getName());

            // Complete Hibernate Hack - fetches the proxied List into the PersistenceContext and sets it on the BO Copy.
            //                if (propertyList instanceof PersistentBag) {
            //                    try {
            //                        PersistentBag bag = (PersistentBag) propertyList;
            //                        PersistableBusinessObject pbo =
            //                                (PersistableBusinessObject) KRADServiceLocator.getEntityManagerFactory()
            //                                        .createEntityManager().find(bo.getClass(), bag.getKey());
            //                        Field field1 = pbo.getClass().getDeclaredField(propertyDescriptor.getName());
            //                        Field field2 = bo.getClass().getDeclaredField(propertyDescriptor.getName());
            //                        field1.setAccessible(true);
            //                        field2.setAccessible(true);
            //                        field2.set(bo, field1.get(pbo));
            //                        propertyList = (List) getPropertyValue(bo, propertyDescriptor.getName());
            //                        ;
            //                    } catch (Exception e) {
            //                        LOG.error(e.getMessage(), e);
            //                    }
            //                }
            // End Complete Hibernate Hack

            for (Object listedBo : propertyList) {
                if (listedBo != null && listedBo instanceof BusinessObject) {
                    setObjectPropertyDeep(listedBo, propertyName, type, propertyValue, depth - 1);
                }
            } // end for
        }
    } // end for
}

From source file:de.erdesignerng.dialect.ModelItemProperties.java

public void initializeFrom(T aObject) {
    ModelProperties theProperties = aObject.getProperties();

    try {/*from  w  w w  .  j  av a2  s .c  o  m*/
        for (PropertyDescriptor theDescriptor : PropertyUtils.getPropertyDescriptors(this)) {
            if (theDescriptor.getReadMethod() != null && theDescriptor.getWriteMethod() != null) {
                String theValue = theProperties.getProperty(theDescriptor.getName());
                if (!StringUtils.isEmpty(theValue)) {
                    Class theType = theDescriptor.getPropertyType();

                    if (theType.isEnum()) {
                        PropertyUtils.setProperty(this, theDescriptor.getName(),
                                Enum.valueOf(theType, theValue));
                    }
                    if (String.class.equals(theType)) {
                        PropertyUtils.setProperty(this, theDescriptor.getName(), theValue);
                    }
                    if (Long.class.equals(theType) || long.class.equals(theType)) {
                        PropertyUtils.setProperty(this, theDescriptor.getName(), Long.parseLong(theValue));
                    }
                    if (Integer.class.equals(theType) || int.class.equals(theType)) {
                        PropertyUtils.setProperty(this, theDescriptor.getName(), Integer.parseInt(theValue));
                    }
                    if (Boolean.class.equals(theType) || boolean.class.equals(theType)) {
                        PropertyUtils.setProperty(this, theDescriptor.getName(),
                                Boolean.parseBoolean(theValue));
                    }
                }
            }
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

}

From source file:com.gzj.tulip.jade.rowmapper.BeanPropertyRowMapper.java

/**
 * Extract the values for all columns in the current row.
 * <p>/*from w w w.j ava2  s  . c  o  m*/
 * Utilizes public setters and result set metadata.
 * 
 * @see java.sql.ResultSetMetaData
 */
public Object mapRow(ResultSet rs, int rowNumber) throws SQLException {
    // spring's : Object mappedObject = BeanUtils.instantiateClass(this.mappedClass);
    // jade's : private Object instantiateClass(this.mappedClass);
    // why: ??mappedClass.newInstranceBeanUtils.instantiateClass(mappedClass)1?
    Object mappedObject = instantiateClass(this.mappedClass);
    BeanWrapper bw = new BeanWrapperImpl(mappedObject);

    ResultSetMetaData rsmd = rs.getMetaData();
    int columnCount = rsmd.getColumnCount();

    boolean warnEnabled = logger.isWarnEnabled();
    boolean debugEnabled = logger.isDebugEnabled();
    Set<String> populatedProperties = (checkProperties ? new HashSet<String>() : null);

    for (int index = 1; index <= columnCount; index++) {
        String column = JdbcUtils.lookupColumnName(rsmd, index).toLowerCase();
        PropertyDescriptor pd = this.mappedFields.get(column);
        if (pd != null) {
            try {
                Object value = JdbcUtils.getResultSetValue(rs, index, pd.getPropertyType());
                if (debugEnabled && rowNumber == 0) {
                    logger.debug("Mapping column '" + column + "' to property '" + pd.getName() + "' of type "
                            + pd.getPropertyType());
                }
                bw.setPropertyValue(pd.getName(), value);
                if (populatedProperties != null) {
                    populatedProperties.add(pd.getName());
                }
            } catch (NotWritablePropertyException ex) {
                throw new DataRetrievalFailureException(
                        "Unable to map column " + column + " to property " + pd.getName(), ex);
            }
        } else {
            if (checkColumns) {
                throw new InvalidDataAccessApiUsageException("Unable to map column '" + column
                        + "' to any properties of bean " + this.mappedClass.getName());
            }
            if (warnEnabled && rowNumber == 0) {
                logger.warn("Unable to map column '" + column + "' to any properties of bean "
                        + this.mappedClass.getName());
            }
        }
    }

    if (populatedProperties != null && !populatedProperties.equals(this.mappedProperties)) {
        throw new InvalidDataAccessApiUsageException("Given ResultSet does not contain all fields "
                + "necessary to populate object of class [" + this.mappedClass + "]: " + this.mappedProperties);
    }

    return mappedObject;
}

From source file:no.sesat.search.datamodel.DataModelFactoryImplTest.java

private void scan(final Class<? extends Annotation> type, final Class<?> cls, final Command command)
        throws IntrospectionException {

    LOG.info("scanning " + cls.getSimpleName());
    final PropertyDescriptor[] properties = Introspector.getBeanInfo(cls).getPropertyDescriptors();
    for (PropertyDescriptor property : properties) {

        final Class<?> propCls = property instanceof MappedPropertyDescriptor
                ? ((MappedPropertyDescriptor) property).getMappedPropertyType()
                : property.getPropertyType();

        LOG.info("  checking property " + property.getName() + " [" + propCls.getSimpleName() + ']');

        if (null != propCls.getAnnotation(type)) {
            command.execute(propCls);/*from  w w w.j a v a2 s .  com*/
        }

        if (null != propCls.getAnnotation(DataNode.class)) {
            // also descend down dataNodes in the datamodel
            scan(type, propCls, command);
        }
    }

    // repeat again on all implemented interfaces
    for (Class<?> c : cls.getInterfaces()) {
        scan(type, c, command);
    }
}

From source file:com.sinosoft.one.data.jade.rowmapper.BeanPropertyRowMapper.java

/**
 * Extract the values for all columns in the current row.
 * <p>/*from w w  w .j a va  2  s.  co  m*/
 * Utilizes public setters and result set metadata.
 * 
 * @see java.sql.ResultSetMetaData
 */
public Object mapRow(ResultSet rs, int rowNumber) throws SQLException {
    // spring's : Object mappedObject = BeanUtils.instantiateClass(this.mappedClass);
    // jade's : private Object instantiateClass(this.mappedClass);
    // why: ??mappedClass.newInstranceBeanUtils.instantiateClass(mappedClass)1?
    Object mappedObject = instantiateClass(this.mappedClass);
    BeanWrapper bw = new BeanWrapperImpl(mappedObject);
    bw.setConversionService(this.conversionService);
    ResultSetMetaData rsmd = rs.getMetaData();
    int columnCount = rsmd.getColumnCount();

    boolean warnEnabled = logger.isWarnEnabled();
    boolean debugEnabled = logger.isDebugEnabled();
    Set<String> populatedProperties = (checkProperties ? new HashSet<String>() : null);

    for (int index = 1; index <= columnCount; index++) {
        String column = JdbcUtils.lookupColumnName(rsmd, index).toLowerCase();
        PropertyDescriptor pd = this.mappedFields.get(column);
        if (pd != null) {
            try {
                Object value = JdbcUtils.getResultSetValue(rs, index, pd.getPropertyType());
                if (debugEnabled && rowNumber == 0) {
                    logger.debug("Mapping column '" + column + "' to property '" + pd.getName() + "' of type "
                            + pd.getPropertyType());
                }
                bw.setPropertyValue(pd.getName(), value);
                if (populatedProperties != null) {
                    populatedProperties.add(pd.getName());
                }
            } catch (NotWritablePropertyException ex) {
                throw new DataRetrievalFailureException(
                        "Unable to map column " + column + " to property " + pd.getName(), ex);
            }
        } else {
            if (checkColumns) {
                throw new InvalidDataAccessApiUsageException("Unable to map column '" + column
                        + "' to any properties of bean " + this.mappedClass.getName());
            }
            if (warnEnabled && rowNumber == 0) {
                logger.warn("Unable to map column '" + column + "' to any properties of bean "
                        + this.mappedClass.getName());
            }
        }
    }

    if (populatedProperties != null && !populatedProperties.equals(this.mappedProperties)) {
        throw new InvalidDataAccessApiUsageException("Given ResultSet does not contain all fields "
                + "necessary to populate object of class [" + this.mappedClass + "]: " + this.mappedProperties);
    }

    return mappedObject;
}

From source file:com.qcadoo.model.internal.classconverter.ModelXmlToClassConverterTest.java

private void verifyField(final PropertyDescriptor propertyDescriptor, final Class<?> type,
        final boolean readable, final boolean writable) {
    assertEquals(type, propertyDescriptor.getPropertyType());
    if (writable) {
        assertNotNull(propertyDescriptor.getWriteMethod());
    } else {//from  ww w . j  ava2 s .c  om
        assertNull(propertyDescriptor.getWriteMethod());
    }
    if (readable) {
        assertNotNull(propertyDescriptor.getReadMethod());
    } else {
        assertNull(propertyDescriptor.getReadMethod());
    }
}