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.openspotlight.graph.internal.NodeAndLinkSupport.java

@SuppressWarnings("unchecked")
public static <T extends Node> T createNode(final PartitionFactory factory, final StorageSession session,
        final String contextId, final String parentId, final Class<T> clazz, final String name,
        final boolean needsToVerifyType, final Iterable<Class<? extends Link>> linkTypesForLinkDeletion,
        final Iterable<Class<? extends Link>> linkTypesForLinkedNodeDeletion) {
    final Map<String, Class<? extends Serializable>> propertyTypes = newHashMap();
    final Map<String, Serializable> propertyValues = newHashMap();
    final PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(clazz);
    StorageNode node = null;//  w  w  w.  ja  v  a  2 s .  c  om
    if (contextId == null) {
        throw new IllegalStateException();
    }
    final Partition partition = factory.getPartition(contextId);
    NodeKey internalNodeKey;
    final Class<? extends Node> targetNodeType = findTargetClass(clazz);

    if (session != null) {
        internalNodeKey = session.withPartition(partition).createNodeKeyWithType(targetNodeType.getName())
                .withSimpleKey(NAME, name).andCreate();
        node = session.withPartition(partition).createCriteria().withUniqueKey(internalNodeKey).buildCriteria()
                .andSearchUnique(session);
    } else {
        internalNodeKey = new NodeKeyBuilderImpl(targetNodeType.getName(), partition).withSimpleKey(NAME, name)
                .andCreate();
    }

    for (final PropertyDescriptor d : descriptors) {
        if (d.getName().equals("class")) {
            continue;
        }
        propertyTypes.put(d.getName(),
                (Class<? extends Serializable>) Reflection.findClassWithoutPrimitives(d.getPropertyType()));
        final Object rawValue = node != null ? node.getPropertyValueAsString(session, d.getName()) : null;
        final Serializable value = (Serializable) (rawValue != null
                ? Conversion.convert(rawValue, d.getPropertyType())
                : null);
        propertyValues.put(d.getName(), value);
    }
    int weigthValue;
    final Set<String> stNodeProperties = node != null ? node.getPropertyNames(session)
            : Collections.<String>emptySet();
    if (stNodeProperties.contains(WEIGTH_VALUE)) {
        weigthValue = Conversion.convert(node.getPropertyValueAsString(session, WEIGTH_VALUE), Integer.class);
    } else {
        weigthValue = findInitialWeight(clazz);
    }
    Class<? extends Node> savedClass = null;
    if (stNodeProperties.contains(CORRECT_CLASS)) {
        savedClass = Conversion.convert(node.getPropertyValueAsString(session, CORRECT_CLASS), Class.class);
    }
    final BigInteger savedClassNumericType = savedClass != null ? findNumericType(savedClass) : null;
    final BigInteger proposedClassNumericType = findNumericType(clazz);
    final Class<? extends Node> classToUse = savedClassNumericType != null
            && savedClassNumericType.compareTo(proposedClassNumericType) > 0 ? savedClass : clazz;

    final NodeImpl internalNode = new NodeImpl(name, classToUse, internalNodeKey.getKeyAsString(),
            propertyTypes, propertyValues, parentId, contextId, weigthValue);
    if (node != null) {
        internalNode.cachedEntry = new WeakReference<StorageNode>(node);
        if (needsToVerifyType) {
            fixTypeData(session, classToUse, node);
        }
        final String captionAsString = node.getPropertyValueAsString(session, CAPTION);
        if (captionAsString != null) {
            internalNode.setCaption(captionAsString);
        }

    }
    final Enhancer e = new Enhancer();
    e.setSuperclass(classToUse);
    e.setInterfaces(new Class<?>[] { PropertyContainerMetadata.class });
    e.setCallback(new PropertyContainerInterceptor(internalNode));
    return (T) e.create(new Class[0], new Object[0]);
}

From source file:info.magnolia.jcr.node2bean.impl.TypeMappingImpl.java

@Override
public PropertyTypeDescriptor getPropertyTypeDescriptor(Class<?> beanClass, String propName) {
    PropertyTypeDescriptor dscr = null;//from   w  w  w  .  j  av a 2 s  .  c  o  m
    String key = beanClass.getName() + "." + propName;

    dscr = propertyTypes.get(key);

    if (dscr != null) {
        return dscr;
    }

    dscr = new PropertyTypeDescriptor();
    dscr.setName(propName);

    PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(beanClass);
    Method writeMethod = null;
    for (PropertyDescriptor descriptor : descriptors) {
        if (descriptor.getName().equals(propName)) {
            // may be null for indexed properties
            Class<?> propertyType = descriptor.getPropertyType();
            writeMethod = descriptor.getWriteMethod();
            if (propertyType != null) {
                dscr.setType(getTypeDescriptor(propertyType, writeMethod));
            }
            // set write method
            dscr.setWriteMethod(writeMethod);
            // set add method
            int numberOfParameters = dscr.isMap() ? 2 : 1;
            dscr.setAddMethod(getAddMethod(beanClass, propName, numberOfParameters));

            break;
        }
    }

    if (dscr.getType() != null) {
        // we have discovered type for property
        if (dscr.isMap() || dscr.isCollection()) {
            List<Class<?>> parameterTypes = new ArrayList<Class<?>>(); // this will contain collection types (for map key/value type, for collection value type)
            if (dscr.getWriteMethod() != null) {
                parameterTypes = inferGenericTypes(dscr.getWriteMethod());
            }
            if (dscr.getAddMethod() != null && parameterTypes.size() == 0) {
                // here we know we don't have setter or setter doesn't have parameterized type
                // but we have add method so we take parameters from it
                parameterTypes = Arrays.asList(dscr.getAddMethod().getParameterTypes());
                // rather set it to null because when we are here we will use add method
                dscr.setWriteMethod(null);
            }
            if (parameterTypes.size() > 0) {
                // we resolved types
                if (dscr.isMap()) {
                    dscr.setCollectionKeyType(getTypeDescriptor(parameterTypes.get(0)));
                    dscr.setCollectionEntryType(getTypeDescriptor(parameterTypes.get(1)));
                } else {
                    // collection
                    dscr.setCollectionEntryType(getTypeDescriptor(parameterTypes.get(0)));
                }
            }
        } else if (dscr.isArray()) {
            // for arrays we don't need to discover its parameter from set/add method
            // we just take it via Class#getComponentType() method
            dscr.setCollectionEntryType(getTypeDescriptor(dscr.getType().getType().getComponentType()));
        }
    }
    propertyTypes.put(key, dscr);

    return dscr;
}

From source file:org.ambraproject.user.service.UserServiceImpl.java

@Override
public UserProfile getProfileForDisplay(UserProfile userProfile, boolean showPrivateFields) {
    UserProfile display = new UserProfile();
    copyFields(userProfile, display);//  w w  w .  j a  v a2  s  .  c o m
    if (!showPrivateFields) {
        log.debug("Removing private fields for display on user: {}", userProfile.getDisplayName());
        display.setOrganizationName(null);
        display.setOrganizationType(null);
        display.setPostalAddress(null);
        display.setPositionType(null);
    }

    //escape html in all string fields
    BeanWrapper wrapper = new BeanWrapperImpl(display);
    for (PropertyDescriptor property : wrapper.getPropertyDescriptors()) {
        if (String.class.isAssignableFrom(property.getPropertyType())) {
            String name = property.getName();
            wrapper.setPropertyValue(name, TextUtils.escapeHtml((String) wrapper.getPropertyValue(name)));
        }
    }

    return display;
}

From source file:org.apache.tapestry.enhance.ComponentClassFactory.java

protected void checkPropertyType(PropertyDescriptor pd, Class propertyType, ILocation location) {
    if (!pd.getPropertyType().equals(propertyType))
        throw new ApplicationRuntimeException(Tapestry.format("ComponentClassFactory.property-type-mismatch",
                new Object[] { _componentClass.getName(), pd.getName(), pd.getPropertyType().getName(),
                        propertyType.getName() }),
                location, null);//from  www . j  a v a2  s.co m
}

From source file:org.openehr.adl.rm.RmBeanReflector.java

private Map<String, RmAttribute> buildAttributes(Class<?> beanClass)
        throws ReflectiveOperationException, IntrospectionException {
    Map<String, RmAttribute> properties;
    properties = new LinkedHashMap<>();
    BeanInfo info = Introspector.getBeanInfo(beanClass);

    PropertyDescriptor[] pds = info.getPropertyDescriptors();
    for (PropertyDescriptor pd : pds) {
        if (pd.getName().equals("class"))
            continue;
        ;/*from   w w w .  j ava  2 s.c o m*/

        String attribute = getAttributeForField(pd.getName());
        MultiplicityInterval occurrences = getOccurrences(beanClass, pd);
        final Class<?> targetType = List.class.isAssignableFrom(pd.getPropertyType())
                ? extractGenericType(beanClass, pd)
                : pd.getPropertyType();
        RmAttribute rp = new RmAttribute(attribute, pd, occurrences, targetType);
        properties.put(attribute, rp);
    }
    rmClassAttributeMap.put(beanClass, ImmutableMap.copyOf(properties));
    return properties;
}

From source file:com.sf.ddao.crud.param.CRUDBeanPropsParameter.java

public int bindParam(PreparedStatement preparedStatement, int idx, Context ctx) throws SQLException {
    if (descriptors == null) {
        init(ctx);//from  ww w.j  av  a  2 s .c om
    }
    int c = 0;
    final Object bean = getBean(ctx);
    DirtyPropertyAware dirtyPropertyAware = null;
    if (bean instanceof DirtyPropertyAware) {
        dirtyPropertyAware = (DirtyPropertyAware) bean;
    }
    for (PropertyDescriptor descriptor : descriptors) {
        try {
            if (dirtyPropertyAware != null && !dirtyPropertyAware.isDirty(descriptor.getName())) {
                continue;
            }
            Object v = descriptor.getReadMethod().invoke(bean);
            ParameterHelper.bind(preparedStatement, idx++, v, descriptor.getPropertyType(), ctx);
            c++;
        } catch (Exception e) {
            throw new SQLException(descriptor.getName(), e);
        }
    }
    if (dirtyPropertyAware != null) {
        dirtyPropertyAware.cleanDirtyBean();
    }
    return c;
}

From source file:com.alibaba.citrus.service.form.impl.GroupImpl.java

/**
 * group//from  w ww. j  av  a2s. c  om
 * <p>
 * <code>isValidated()</code><code>false</code>group
 * </p>
 */
public void setProperties(Object object) {
    if (!isValidated() || object == null) {
        return;
    }

    if (isValid()) {
        if (log.isDebugEnabled()) {
            log.debug("Set validated properties of group \"" + getName() + "\" to object "
                    + ObjectUtil.identityToString(object));
        }

        BeanWrapper bean = new BeanWrapperImpl(object);
        getForm().getFormConfig().getPropertyEditorRegistrar().registerCustomEditors(bean);

        for (Field field : getFields()) {
            String propertyName = field.getFieldConfig().getPropertyName();

            if (bean.isWritableProperty(propertyName)) {
                PropertyDescriptor pd = bean.getPropertyDescriptor(propertyName);
                MethodParameter mp = BeanUtils.getWriteMethodParameter(pd);
                Object value = field.getValueOfType(pd.getPropertyType(), mp, null);

                bean.setPropertyValue(propertyName, value);
            } else {
                log.debug("No writable property \"{}\" found in type {}", propertyName,
                        object.getClass().getName());
            }
        }
    } else {
        throw new InvalidGroupStateException("Attempted to call setProperties from an invalid input");
    }
}

From source file:org.apache.myfaces.el.PropertyResolverImpl.java

public Class getType(Object base, Object property) {
    try {/* www  . ja  v  a2s  .  c om*/
        if (base == null) {
            throw new PropertyNotFoundException("Base bean is null.");
        } else if (property == null) {
            throw new PropertyNotFoundException("Property name is null.");
        } else if (property instanceof String && ((String) property).length() == 0) {
            throw new PropertyNotFoundException("Property name is an empty String.");
        }

        if (base instanceof Map) {
            Object value = ((Map) base).get(property);

            // REVISIT: when generics are imlemented in JVM 1.5
            return (value == null) ? Object.class : value.getClass();
        }

        // If none of the special bean types, then process as normal Bean
        PropertyDescriptor propertyDescriptor = getPropertyDescriptor(base, property.toString());

        return propertyDescriptor.getPropertyType();
    } catch (PropertyNotFoundException e) {
        throw e;
    } catch (Exception e) {
        return null;
    }
}

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

/**
 * @param element//from  w  w  w . ja v a  2  s .c om
 * @param attributeName
 * @return Column
 */
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.apache.ojb.broker.metadata.fieldaccess.PersistentFieldIntrospectorImpl.java

private List buildPropertyGraph() {
    List result = new ArrayList();
    String[] fields = StringUtils.split(getName(), PATH_TOKEN);
    PropertyDescriptor pd = null;
    for (int i = 0; i < fields.length; i++) {
        String fieldName = fields[i];
        if (pd == null) {
            pd = findPropertyDescriptor(getDeclaringClass(), fieldName);
        } else {//from  w ww .j a v a  2 s . com
            pd = findPropertyDescriptor(pd.getPropertyType(), fieldName);
        }
        result.add(pd);
    }
    return result;
}