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:de.xwic.appkit.webbase.toolkit.app.EditorToolkit.java

/**
 * Try some common type mappings/*from  www . ja va2  s . com*/
 * 
 * @param propInfo
 * @param controlValue
 * @return
 */
private Object autoConvertToEntityType(PropertyDescriptor propInfo, Object controlValue) {

    Class propertyType = propInfo.getPropertyType();
    Class controlType = null;
    if (controlValue == null) {
        //for primitives, null gets mapped to the default value 
        if (int.class.equals(propertyType) || long.class.equals(propertyType)
                || double.class.equals(propertyType) || float.class.equals(propertyType)
                || byte.class.equals(propertyType) || short.class.equals(propertyType)) {
            return 0;
        }
        if (boolean.class.equals(propertyType)) {
            return false;
        }
        if (char.class.equals(propertyType)) {
            return '\u0000';
        }
    } else {
        controlType = controlValue.getClass();
    }

    ITypeConverter converter = null;
    if (String.class.equals(controlType)) {
        if (Integer.class.equals(propertyType) || int.class.equals(propertyType)) {
            converter = IntegerStringConverter.INSTANCE;
        } else if (Long.class.equals(propertyType) || long.class.equals(propertyType)) {
            converter = LongStringConverter.INSTANCE;
        } else if (Float.class.equals(propertyType) || float.class.equals(propertyType)) {
            converter = FloatStringConverter.INSTANCE;
        } else if (Double.class.equals(propertyType) || double.class.equals(propertyType)) {
            converter = DoubleStringConverter.INSTANCE;
        } else if (Boolean.class.equals(propertyType) || boolean.class.equals(propertyType)) {
            converter = BooleanStringConverter.INSTANCE;
        }
        if (converter != null) {
            return converter.convertRight(controlValue);
        }
    }
    return controlValue;
}

From source file:com.linkedin.databus.core.util.TestConfigManager.java

@Test
public void testPaddedInt() throws Exception {
    ConvertUtilsBean convertUtils = new ConvertUtilsBean();
    Integer intValue = (Integer) convertUtils.convert("456", int.class);

    assertEquals("correct int value", 456, intValue.intValue());
    BeanUtilsBean beanUtils = new BeanUtilsBean();
    PropertyDescriptor propDesc = beanUtils.getPropertyUtils().getPropertyDescriptor(_configBuilder,
            "intSetting");
    assertEquals("correct setting type", int.class, propDesc.getPropertyType());

    _configManager.setSetting("com.linkedin.databus2.intSetting", " 123 ");
    DynamicConfig config = _configManager.getReadOnlyConfig();
    assertEquals("correct int value", 123, config.getIntSetting());
}

From source file:org.zkybase.cmdb.test.AbstractBeanTestCase.java

@Test
public void accessors() throws Exception {
    PropertyDescriptor[] props = BeanUtils.getPropertyDescriptors(beanClass);
    for (PropertyDescriptor prop : props) {
        String propName = prop.getName();
        if ("class".equals(propName)) {
            continue;
        }// w  w w  . j  av a2s  .  c o  m

        log.debug("Testing property accessors: {}.{}", beanClass, prop.getName());
        Method readMethod = prop.getReadMethod();
        Method writeMethod = prop.getWriteMethod();

        assertNull(readMethod.invoke(bean));
        Object dummyValue = getDummyValue(prop.getPropertyType());
        writeMethod.invoke(bean, dummyValue);
        assertSame(dummyValue, readMethod.invoke(bean));
    }
}

From source file:org.gbif.portal.registration.ResourceExtractionUtils.java

/**
 * Using the property store, a list of "registry" resources are extracted from the message 
 * @param psNamespaces That identify the message
 * @param message To extract the values from 
 * @return The resources the provider offers at the url
 * @throws MessageAccessException /*  ww  w  .  j a v a2s . c om*/
 * @throws MisconfiguredPropertyException 
 * @throws PropertyNotFoundException 
 */
@SuppressWarnings("unchecked")
public List<ResourceDetail> getResourcesFromMetadata(List<String> psNamespaces, Message message)
        throws PropertyNotFoundException, MisconfiguredPropertyException, MessageAccessException {
    List<ResourceDetail> results = new LinkedList<ResourceDetail>();
    List<Message> resourceMessages = (List<Message>) messageUtils.extractSubMessageList(message, psNamespaces,
            psPropertyPrefix, true);

    PropertyDescriptor[] pds = org.springframework.beans.BeanUtils.getPropertyDescriptors(ResourceDetail.class);

    for (Message resourceMessage : resourceMessages) {
        ResourceDetail resource = new ResourceDetail();

        for (PropertyDescriptor pd : pds) {
            String psPropertyName = psPropertyPrefix + "." + pd.getName().toUpperCase();
            String propertyValue = extractMessageProperty(resourceMessage, psNamespaces, psPropertyName);
            if (StringUtils.isNotEmpty(propertyValue)) {
                try {
                    Class propertyType = pd.getPropertyType();
                    if (propertyType.equals(Integer.class)) {
                        pd.getWriteMethod().invoke(resource, Integer.parseInt(propertyValue));
                    } else if (propertyType.equals(Long.class)) {
                        pd.getWriteMethod().invoke(resource, Long.parseLong(propertyValue));
                    } else if (propertyType.equals(Boolean.class)) {
                        pd.getWriteMethod().invoke(resource, Boolean.parseBoolean(propertyValue));
                    } else {
                        pd.getWriteMethod().invoke(resource, propertyValue);
                    }
                } catch (Exception e) {
                    logger.debug(e.getMessage(), e);
                }
            }
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Adding resource from metadata: " + resource.getName());
        }
        results.add(resource);
    }
    return results;
}

From source file:de.xwic.appkit.webbase.table.DefaultColumnLabelProvider.java

/**
 * @throws IntrospectionException //from   w w  w  . j  a v  a 2  s  .c  o m
 * 
 */
private void buildReadPath(Object element) throws IntrospectionException {
    StringTokenizer stk = new StringTokenizer(column.getPropertyId(), ".");
    readMethods = new Method[stk.countTokens()];

    int idx = 0;
    Class<?> clazz = element.getClass();
    while (stk.hasMoreTokens()) {
        String propertyName = stk.nextToken();

        PropertyDescriptor desc = new PropertyDescriptor(propertyName, clazz, makeGetterName(propertyName),
                null);
        clazz = desc.getPropertyType();
        readMethods[idx++] = desc.getReadMethod();
    }
    propertyEditor = PropertyEditorManager.findEditor(clazz);
    baseClass = element.getClass();
}

From source file:com.diversityarrays.kdxplore.editing.EntityPropertiesTable.java

@Override
public boolean editCellAt(int row, int column, EventObject e) {
    if (e instanceof MouseEvent) {
        MouseEvent me = (MouseEvent) e;
        if (SwingUtilities.isLeftMouseButton(me) && 2 != me.getClickCount()) {
            return false;
        }//from  www  . j  ava 2  s.  co m
        me.consume();
    }

    @SuppressWarnings("unchecked")
    EntityPropertiesTableModel<T> eptm = (EntityPropertiesTableModel<T>) getModel();
    if (!eptm.isCellEditable(row, column)) {
        return false;
    }

    if (handleEditCellAt(eptm, row, column)) {
        return false;
    }

    PropertyDescriptor pd = eptm.getPropertyDescriptor(row);
    if (pd == null) {
        return super.editCellAt(row, column);
    }

    Class<?> propertyClass = pd.getPropertyType();

    if (propertyChangeConfirmer != null && !propertyChangeConfirmer.isChangeAllowed(pd)) {
        return false;
    }

    if (java.util.Date.class.isAssignableFrom(propertyClass)) {
        try {
            java.util.Date dateValue = (Date) pd.getReadMethod().invoke(eptm.getEntity());

            if (propertyChangeConfirmer != null) {
                propertyChangeConfirmer.setValueBeforeChange(dateValue);
            }

            Closure<Date> onComplete = new Closure<Date>() {
                @Override
                public void execute(Date result) {
                    if (result != null) {
                        if (propertyChangeConfirmer == null
                                || propertyChangeConfirmer.valueChangeCanCommit(pd, result)) {
                            getModel().setValueAt(result, row, column);
                        }
                    }
                }
            };

            String title = pd.getDisplayName();
            DatePickerDialog datePicker = new DatePickerDialog(GuiUtil.getOwnerWindow(this), title, onComplete);
            datePicker.setDate(dateValue);
            datePicker.setVisible(true);

        } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e1) {
            e1.printStackTrace();
        }
        return false;
    }
    // else if (Enum.class.isAssignableFrom(propertyClass)) {
    // }

    Log.d(TAG, "editCellAt(" + row + "," + column + ") No Editor override provided for "
            + propertyClass.getName());
    return super.editCellAt(row, column, e);
}

From source file:org.openmobster.core.mobileObject.xml.MobileObjectSerializer.java

public Object deserialize(Class pojoClazz, String deviceXml) {
    try {//from w w  w .  j av a  2  s .  c  o m
        Object pojo = null;

        pojo = pojoClazz.newInstance();

        Document root = XMLUtilities.parse(deviceXml);

        //Parse the Object Meta Data
        List<ArrayMetaData> objectMetaData = new ArrayList<ArrayMetaData>();
        NodeList metaDataNodes = root.getElementsByTagName("array-metadata");
        if (metaDataNodes != null) {
            for (int i = 0; i < metaDataNodes.getLength(); i++) {
                Element metaDataElement = (Element) metaDataNodes.item(i);
                Element arrayUriElement = (Element) metaDataElement.getElementsByTagName("uri").item(0);
                Element arrayLengthElement = (Element) metaDataElement.getElementsByTagName("array-length")
                        .item(0);
                Element arrayClassElement = (Element) metaDataElement.getElementsByTagName("array-class")
                        .item(0);

                ArrayMetaData arrayMetaData = new ArrayMetaData();
                arrayMetaData.arrayUri = arrayUriElement.getTextContent().trim();
                arrayMetaData.arrayLength = Integer.parseInt(arrayLengthElement.getTextContent().trim());
                arrayMetaData.arrayClass = arrayClassElement.getTextContent().trim();

                objectMetaData.add(arrayMetaData);
            }
        }

        //Set the fields
        Element fieldsElement = (Element) root.getElementsByTagName("fields").item(0);
        if (fieldsElement != null) {
            NodeList fieldNodes = fieldsElement.getElementsByTagName("field");
            if (fieldNodes != null) {
                for (int i = 0; i < fieldNodes.getLength(); i++) {
                    Element fieldElement = (Element) fieldNodes.item(i);

                    String name = ((Element) fieldElement.getElementsByTagName("name").item(0))
                            .getTextContent();

                    String value = ((Element) fieldElement.getElementsByTagName("value").item(0))
                            .getTextContent();

                    String uri = ((Element) fieldElement.getElementsByTagName("uri").item(0)).getTextContent();

                    String expression = this.parseExpression(uri);

                    if (expression.indexOf('.') == -1 && expression.indexOf('[') == -1) {
                        //Simple Property
                        PropertyDescriptor metaData = PropertyUtils.getPropertyDescriptor(pojo, expression);

                        if (metaData == null || metaData.getPropertyType() == null) {
                            log.error("******************************");
                            log.error("MetaData Null For: " + expression);
                            log.error("Field Not Found on the MobileBean");
                            log.error("******************************");
                            continue;
                        }

                        if (metaData.getPropertyType().isArray()
                                && metaData.getPropertyType().getComponentType().isAssignableFrom(byte.class)) {
                            BeanUtils.setProperty(pojo, expression, Utilities.decodeBinaryData(value));
                        } else {
                            BeanUtils.setProperty(pojo, expression, value);
                        }
                    } else {
                        //Nested Property
                        this.setNestedProperty(pojo, expression, value, objectMetaData);
                    }
                }
            }
        }

        return pojo;
    } catch (Exception e) {
        log.error(this, e);
        throw new RuntimeException(e);
    }
}

From source file:org.openspotlight.graph.internal.NodeAndLinkSupport.java

@SuppressWarnings("unchecked")
public static <T extends Link> T createLink(final PartitionFactory factory, final StorageSession session,
        final Class<T> clazz, final Node rawOrigin, final Node rawTarget, final LinkDirection direction,
        final boolean createIfDontExists) {
    final Map<String, Class<? extends Serializable>> propertyTypes = newHashMap();
    final Map<String, Serializable> propertyValues = newHashMap();
    final PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(clazz);

    StorageLink linkEntry = null;/*from w  ww .j  a va 2  s .  co m*/
    Node origin, target;

    if (rawOrigin.compareTo(rawTarget) == 0) {
        throw new IllegalStateException();
    }

    if (LinkDirection.BIDIRECTIONAL.equals(direction) && rawOrigin.compareTo(rawTarget) < 0) {
        origin = rawTarget;
        target = rawOrigin;
    } else {
        origin = rawOrigin;
        target = rawTarget;
    }
    String linkId = null;
    if (session != null) {
        final StorageNode originAsSTNode = session.getNode(origin.getId());
        final StorageNode targetAsSTNode = session.getNode(target.getId());
        if (originAsSTNode == null && createIfDontExists) {
            throw new IllegalStateException();
        }
        if (originAsSTNode != null) {
            if (clazz.isAnnotationPresent(LinkAutoBidirectional.class)
                    && LinkDirection.UNIDIRECTIONAL.equals(direction)) {

                final StorageLink possibleLink = session.getLink(targetAsSTNode, originAsSTNode,
                        clazz.getName());
                final StorageLink anotherPossibleLink = session.getLink(originAsSTNode, targetAsSTNode,
                        clazz.getName());
                if (possibleLink != null && anotherPossibleLink != null) {
                    throw new IllegalStateException();
                }
                if (possibleLink != null && possibleLink.getPropertyValueAsString(session, LINK_DIRECTION)
                        .equals(LinkDirection.BIDIRECTIONAL.name())) {
                    return createLink(factory, session, clazz, rawOrigin, rawTarget,
                            LinkDirection.BIDIRECTIONAL, createIfDontExists);
                } else if (anotherPossibleLink != null
                        && anotherPossibleLink.getPropertyValueAsString(session, LINK_DIRECTION)
                                .equals(LinkDirection.BIDIRECTIONAL.name())) {
                    return createLink(factory, session, clazz, rawTarget, rawOrigin,
                            LinkDirection.BIDIRECTIONAL, createIfDontExists);
                } else if (possibleLink != null) {
                    if (createIfDontExists) {
                        session.removeLink(possibleLink);
                    }
                    return createLink(factory, session, clazz, rawOrigin, rawTarget,
                            LinkDirection.BIDIRECTIONAL, createIfDontExists);

                } else if (anotherPossibleLink != null) {
                    if (createIfDontExists) {
                        session.removeLink(anotherPossibleLink);
                    }
                    return createLink(factory, session, clazz, rawOrigin, rawTarget,
                            LinkDirection.BIDIRECTIONAL, createIfDontExists);
                }
            }
            linkEntry = session.getLink(originAsSTNode, targetAsSTNode, clazz.getName());
            if (linkEntry == null) {
                if (createIfDontExists) {
                    linkEntry = session.addLink(originAsSTNode, targetAsSTNode, clazz.getName());
                }
                if (linkEntry != null) {
                    if (LinkDirection.BIDIRECTIONAL.equals(direction)) {
                        final InputStream objectAsStream = targetAsSTNode.getPropertyValueAsStream(session,
                                BIDIRECTIONAL_LINK_IDS);
                        List<String> linkIds;
                        if (objectAsStream != null) {
                            linkIds = SerializationUtil.deserialize(objectAsStream);
                        } else {
                            linkIds = new ArrayList<String>();
                        }
                        linkIds.add(linkEntry.getKeyAsString());
                        targetAsSTNode.setSimpleProperty(session, BIDIRECTIONAL_LINK_IDS,
                                SerializationUtil.serialize(linkIds));
                        targetAsSTNode.setSimpleProperty(session, LINK_DIRECTION,
                                LinkDirection.BIDIRECTIONAL.name());
                    }
                }
            }
        }
        linkId = StringKeysSupport.buildLinkKeyAsString(clazz.getName(), origin.getId(), target.getId());
    }

    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 = linkEntry != null ? linkEntry.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 = linkEntry != null ? linkEntry.getPropertyNames(session)
            : Collections.<String>emptySet();
    if (stNodeProperties.contains(WEIGTH_VALUE)) {
        weigthValue = Conversion.convert(linkEntry.getPropertyValueAsString(session, WEIGTH_VALUE),
                Integer.class);
    } else {
        weigthValue = findInitialWeight(clazz);
    }
    final LinkImpl internalLink = new LinkImpl(linkId, clazz.getName(), clazz, propertyTypes, propertyValues,
            findInitialWeight(clazz), weigthValue, origin, target, direction);
    if (linkEntry != null) {
        internalLink.setCached(linkEntry);
        internalLink.linkDirection = direction;
    }
    final Enhancer e = new Enhancer();
    e.setSuperclass(clazz);
    e.setInterfaces(new Class<?>[] { PropertyContainerMetadata.class });
    e.setCallback(new PropertyContainerInterceptor(internalLink));
    return (T) e.create(new Class[0], new Object[0]);
}

From source file:org.mypsycho.beans.DefaultInvoker.java

public Class<?> getPropertyType(PropertyDescriptor prop, boolean collection) {
    Class<?> type = prop.getPropertyType();
    if (!collection) {
        if (type != null) {
            return type;
        }/*from  w  w  w .ja  v a2  s .c o m*/

        if (prop instanceof IndexedPropertyDescriptor) {
            type = (((IndexedPropertyDescriptor) prop).getIndexedPropertyType());
            if (type == null) { // is it possible ?
                return List.class; // Bold guess !!
            }
            return createArrayType(type);
        }
        if (prop instanceof MappedPropertyDescriptor) {
            return Map.class;
        }

        return null;
    }

    if (prop instanceof IndexedPropertyDescriptor) {
        Class<?> indexedType = (((IndexedPropertyDescriptor) prop).getIndexedPropertyType());
        if (indexedType != null) {
            return indexedType;
        }
    }
    if (prop instanceof MappedPropertyDescriptor) {
        Class<?> mappedType = (((MappedPropertyDescriptor) prop).getMappedPropertyType());
        if (mappedType != null) {
            return mappedType;
        }
    }

    return (type == null) ? null : getCollectedType(type);
}

From source file:org.apache.openejb.server.axis.assembler.HeavyweightTypeInfoBuilder.java

/**
 * Map the (nested) fields of a XML Schema Type to Java Beans properties or public fields of the specified Java Class.
 *
 * @param javaClass          the java class to map
 * @param xmlTypeInfo        the xml schema for the type
 * @param javaXmlTypeMapping the java to xml type mapping metadata
 * @param typeInfo           the JaxRpcTypeInfo for this type
 * @throws OpenEJBException if the XML Schema Type can not be mapped to the Java Class
 *//*from  www. j  av a  2 s.c o m*/
private void mapFields(Class javaClass, XmlTypeInfo xmlTypeInfo, JavaXmlTypeMapping javaXmlTypeMapping,
        JaxRpcTypeInfo typeInfo) throws OpenEJBException {
    // Skip arrays since they can't define a variable-mapping element
    if (!javaClass.isArray()) {
        // if there is a variable-mapping, log a warning
        if (!javaXmlTypeMapping.getVariableMapping().isEmpty()) {
            log.warn("Ignoring variable-mapping defined for class " + javaClass + " which is an array.");
        }
        return;
    }

    // Index Java bean properties by name
    Map<String, Class> properties = new HashMap<String, Class>();
    try {
        PropertyDescriptor[] propertyDescriptors = Introspector.getBeanInfo(javaClass).getPropertyDescriptors();
        for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
            properties.put(propertyDescriptor.getName(), propertyDescriptor.getPropertyType());
        }
    } catch (IntrospectionException e) {
        throw new OpenEJBException("Class " + javaClass + " is not a valid javabean", e);
    }

    for (VariableMapping variableMapping : javaXmlTypeMapping.getVariableMapping()) {
        String fieldName = variableMapping.getJavaVariableName();

        if (variableMapping.getXmlAttributeName() != null) {
            JaxRpcFieldInfo fieldInfo = new JaxRpcFieldInfo();
            fieldInfo.name = fieldName;

            // verify that the property exists on the java class
            Class javaType = properties.get(fieldName);
            if (javaType == null) {
                throw new OpenEJBException("field name " + fieldName + " not found in " + properties);
            }

            String attributeLocalName = variableMapping.getXmlAttributeName();
            QName xmlName = new QName("", attributeLocalName);
            fieldInfo.xmlName = xmlName;

            fieldInfo.xmlType = xmlTypeInfo.attributes.get(attributeLocalName);
            if (fieldInfo.xmlType == null) {
                throw new OpenEJBException(
                        "attribute " + xmlName + " not found in schema " + xmlTypeInfo.qname);
            }

            typeInfo.fields.add(fieldInfo);
        } else {
            JaxRpcFieldInfo fieldInfo = new JaxRpcFieldInfo();
            fieldInfo.isElement = true;
            fieldInfo.name = fieldName;

            // verify that the property exists on the java class or there is a public field
            Class javaType = properties.get(fieldName);
            if (javaType == null) {
                //see if it is a public field
                try {
                    Field field = javaClass.getField(fieldName);
                    javaType = field.getType();
                } catch (NoSuchFieldException e) {
                    throw new OpenEJBException("field name " + fieldName + " not found in " + properties, e);
                }
            }

            QName xmlName = new QName("", variableMapping.getXmlElementName());
            XmlElementInfo nestedElement = xmlTypeInfo.elements.get(xmlName);
            if (nestedElement == null) {
                String ns = xmlTypeInfo.qname.getNamespaceURI();
                xmlName = new QName(ns, variableMapping.getXmlElementName());
                nestedElement = xmlTypeInfo.elements.get(xmlName);
                if (nestedElement == null) {
                    throw new OpenEJBException(
                            "element " + xmlName + " not found in schema " + xmlTypeInfo.qname);
                }
            }
            fieldInfo.isNillable = nestedElement.nillable || hasEncoded;
            fieldInfo.xmlName = xmlName;

            // xml type
            if (nestedElement.xmlType != null) {
                fieldInfo.xmlType = nestedElement.xmlType;
            } else {
                QName anonymousName;
                if (xmlTypeInfo.anonymous) {
                    anonymousName = new QName(xmlTypeInfo.qname.getNamespaceURI(),
                            xmlTypeInfo.qname.getLocalPart() + ">" + nestedElement.qname.getLocalPart());
                } else {
                    anonymousName = new QName(xmlTypeInfo.qname.getNamespaceURI(),
                            ">" + xmlTypeInfo.qname.getLocalPart() + ">" + nestedElement.qname.getLocalPart());
                }
                fieldInfo.xmlType = anonymousName;
            }

            if (javaType.isArray()) {
                fieldInfo.minOccurs = nestedElement.minOccurs;
                fieldInfo.maxOccurs = nestedElement.maxOccurs;
            }

            typeInfo.fields.add(fieldInfo);
        }
    }
}