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.openengsb.core.ekb.persistence.edb.internal.EDBConverter.java

/**
 * Converts an EDBObject to a model by analyzing the object and trying to call the corresponding setters of the
 * model.//from ww w  .  jav  a2s .  co  m
 */
private Object convertEDBObjectToUncheckedModel(Class<?> model, EDBObject object) {
    if (!checkEDBObjectModelType(object, model)) {
        return null;
    }
    List<OpenEngSBModelEntry> entries = new ArrayList<OpenEngSBModelEntry>();
    for (PropertyDescriptor propertyDescriptor : ModelUtils.getPropertyDescriptorsForClass(model)) {
        if (propertyDescriptor.getWriteMethod() == null
                || propertyDescriptor.getName().equals("openEngSBModelTail")) {
            continue;
        }
        Object value = getValueForProperty(propertyDescriptor, object);
        Class<?> propertyClass = propertyDescriptor.getPropertyType();
        if (propertyClass.isPrimitive()) {
            entries.add(new OpenEngSBModelEntry(propertyDescriptor.getName(), value,
                    ClassUtils.primitiveToWrapper(propertyClass)));
        } else {
            entries.add(new OpenEngSBModelEntry(propertyDescriptor.getName(), value, propertyClass));
        }
    }

    for (Map.Entry<String, EDBObjectEntry> objectEntry : object.entrySet()) {
        EDBObjectEntry entry = objectEntry.getValue();
        Class<?> entryType;
        try {
            entryType = model.getClassLoader().loadClass(entry.getType());
            entries.add(new OpenEngSBModelEntry(entry.getKey(), entry.getValue(), entryType));
        } catch (ClassNotFoundException e) {
            LOGGER.error("Unable to load class {} of the model tail", entry.getType());
        }
    }
    return ModelUtils.createModel(model, entries);
}

From source file:de.xwic.sandbox.server.installer.modules.config.ConfigUpgradeScriptHelper.java

/**
 * Generic method to apply property/attribute values from a map to an object.
 * //www .  j  a  va2 s  .  c om
 * @param area
 * @param args
 * @throws IntrospectionException
 * @throws InvocationTargetException
 * @throws IllegalAccessException
 * @throws IllegalArgumentException
 */
private void applyAttributes(Object bean, Map<String, Object> args) throws Exception {

    for (String propertyName : args.keySet()) {

        Object value = args.get(propertyName);

        PropertyDescriptor pd = new PropertyDescriptor(propertyName, bean.getClass());
        Method mWrite = pd.getWriteMethod();
        if (mWrite == null) {
            throw new RuntimeException(
                    "Property '" + propertyName + "' does not exist or does not have a write method in class '"
                            + bean.getClass().getName() + "'");
        }

        // convert arguments
        Class<?> propertyType = pd.getPropertyType();
        if (propertyType.equals(IPicklistEntry.class)) {

        }
        mWrite.invoke(bean, value);

    }

}

From source file:com.hihsoft.baseclass.web.controller.BaseController.java

/**
 * ???(xiaojf?)/*from  www .j  a v a  2  s .  c o  m*/
 */
@Override
protected void bind(final HttpServletRequest request, final Object command) {
    final PropertyDescriptor[] pds = BeanUtils.getPropertyDescriptors(command.getClass());
    for (final PropertyDescriptor pd : pds) {
        final Class<?> clas = pd.getPropertyType();// ?class
        final boolean isSimpleProperty = BeanUtils.isSimpleProperty(clas);
        final boolean isInterface = clas.isInterface();
        final boolean hasConstruct = clas.getConstructors().length == 0 ? false : true;
        if (!isSimpleProperty && !isInterface && hasConstruct) {
            // 
            try {
                pd.getWriteMethod().invoke(command, clas.newInstance());
            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InstantiationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    try {
        super.bind(request, command);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:org.fhcrc.cpl.toolbox.datastructure.BoundMap.java

private void initialize(Class beanClass) {
    synchronized (_savedPropertyMaps) {
        HashMap<String, BoundProperty> props = _savedPropertyMaps.get(beanClass);
        if (props == null) {
            try {
                props = new HashMap<String, BoundProperty>();
                BeanInfo beanInfo = Introspector.getBeanInfo(beanClass);
                PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
                if (propertyDescriptors != null) {
                    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
                        if (propertyDescriptor != null) {
                            String name = propertyDescriptor.getName();
                            if ("class".equals(name))
                                continue;
                            Method readMethod = propertyDescriptor.getReadMethod();
                            Method writeMethod = propertyDescriptor.getWriteMethod();
                            Class aType = propertyDescriptor.getPropertyType();
                            props.put(name, new BoundProperty(readMethod, writeMethod, aType));
                        }//w ww .j a va2  s. c o m
                    }
                }
            } catch (IntrospectionException e) {
                Logger.getLogger(this.getClass()).error("error creating BoundMap", e);
                throw new RuntimeException(e);
            }
            _savedPropertyMaps.put(beanClass, props);
        }
        _properties = props;
    }
}

From source file:com.github.venkateshamurthy.designpatterns.builders.FluentBuilders.java

/**
 * Gets class type of field parameters in a class for which setters are to
 * be found/*from   w ww. jav  a2 s .  c o  m*/
 * 
 * @param thisPojoClass
 * @param ctClass
 * @param ctMethodSet
 *            can be a subset of setters for fields in this class
 * @return set of classes representing field types
 * @throws NotFoundException
 */
@SuppressWarnings("serial")
private Set<Class<?>> getPropertyClassTypes(final Class<?> thisPojoClass, final CtClass ctClass,
        final Set<CtMethod> ctMethodSet) throws NotFoundException {
    Set<Class<?>> set = new LinkedHashSet<>();
    try {
        final Object bean = thisPojoClass.newInstance(); // create an
                                                         // instance
        for (Field field : thisPojoClass.getDeclaredFields()) {
            if (field.isSynthetic()) {
                LOGGER.warning(field.getName() + " is syntheticlly added, so ignoring");
                continue;
            }
            PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(bean, field.getName());

            assert pd != null;
            if (pd != null) {
                if (pd.getPropertyType() != null) {
                    set.add(pd.getPropertyType()); // irrespective of
                                                   // CtMethod just add
                    final Method mutator = pd.getWriteMethod();
                    if (mutator != null && ctMethodSet.add(ctClass.getDeclaredMethod(mutator.getName()))) {
                        LOGGER.info(mutator.getName() + " is ADDED");
                    }
                }
            } else {
                LOGGER.warning("Unable to get Proprty (Field's class) Type for:" + field.getName());
            }

        }
    } catch (InstantiationException | IllegalAccessException | InvocationTargetException
            | NoSuchMethodException e) {
        throw new NotFoundException("Exception Not Found:", e);
    }
    return set;
}

From source file:com.duowan.common.spring.jdbc.BeanPropertyRowMapper.java

/**
 * Extract the values for all columns in the current row.
 * <p>Utilizes public setters and result set metadata.
 * @see java.sql.ResultSetMetaData//from w ww.j a va  2  s  . c  o m
 */
public T mapRow(ResultSet rs, int rowNumber) throws SQLException {
    Assert.state(this.mappedClass != null, "Mapped class was not specified");
    T mappedObject = BeanUtils.instantiate(this.mappedClass);
    BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(mappedObject);
    initBeanWrapper(bw);

    ResultSetMetaData rsmd = rs.getMetaData();
    int columnCount = rsmd.getColumnCount();
    Set<String> populatedProperties = (isCheckFullyPopulated() ? new HashSet<String>() : null);

    for (int index = 1; index <= columnCount; index++) {
        String column = JdbcUtils.lookupColumnName(rsmd, index);
        PropertyDescriptor pd = this.mappedFields.get(column.replaceAll(" ", "").toLowerCase());
        if (pd != null) {
            try {
                Object value = getColumnValue(rs, index, pd);
                if (logger.isDebugEnabled() && rowNumber == 0) {
                    logger.debug("Mapping column '" + column + "' to property '" + pd.getName() + "' of type "
                            + pd.getPropertyType());
                }
                try {
                    bw.setPropertyValue(pd.getName(), value);
                } catch (TypeMismatchException e) {
                    if (value == null && primitivesDefaultedForNullValue) {
                        logger.debug("Intercepted TypeMismatchException for row " + rowNumber + " and column '"
                                + column + "' with value " + value + " when setting property '" + pd.getName()
                                + "' of type " + pd.getPropertyType() + " on object: " + mappedObject);
                    } else {
                        throw e;
                    }
                }
                if (populatedProperties != null) {
                    populatedProperties.add(pd.getName());
                }
            } catch (NotWritablePropertyException ex) {
                throw new DataRetrievalFailureException(
                        "Unable to map column " + column + " to property " + pd.getName(), ex);
            }
        }
    }

    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:org.kuali.rice.krad.datadictionary.DataDictionary.java

/**
 * @param propertyClass//from   w w  w. j  a  v a2 s . c o m
 * @param propertyName
 * @return PropertyDescriptor for the getter for the named property of the given class, if one exists.
 */
public static PropertyDescriptor buildReadDescriptor(Class propertyClass, String propertyName) {
    if (propertyClass == null) {
        throw new IllegalArgumentException("invalid (null) propertyClass");
    }
    if (StringUtils.isBlank(propertyName)) {
        throw new IllegalArgumentException("invalid (blank) propertyName");
    }

    PropertyDescriptor propertyDescriptor = null;

    String[] intermediateProperties = propertyName.split("\\.");
    int lastLevel = intermediateProperties.length - 1;
    Class currentClass = propertyClass;

    for (int i = 0; i <= lastLevel; ++i) {

        String currentPropertyName = intermediateProperties[i];
        propertyDescriptor = buildSimpleReadDescriptor(currentClass, currentPropertyName);

        if (i < lastLevel) {

            if (propertyDescriptor != null) {

                Class propertyType = propertyDescriptor.getPropertyType();
                if (getLegacyDataAdapter().isExtensionAttribute(currentClass, currentPropertyName,
                        propertyType)) {
                    propertyType = getLegacyDataAdapter().getExtensionAttributeClass(currentClass,
                            currentPropertyName);
                }
                if (Collection.class.isAssignableFrom(propertyType)) {
                    currentClass = getLegacyDataAdapter().determineCollectionObjectType(currentClass,
                            currentPropertyName);
                } else {
                    currentClass = propertyType;
                }

            }

        }

    }

    return propertyDescriptor;
}

From source file:org.apache.activemq.artemis.uri.ConnectionFactoryURITest.java

private void populate(StringBuilder sb, BeanUtilsBean bean, ActiveMQConnectionFactory factory)
        throws IllegalAccessException, InvocationTargetException {
    PropertyDescriptor[] descriptors = bean.getPropertyUtils().getPropertyDescriptors(factory);
    for (PropertyDescriptor descriptor : descriptors) {
        if (ignoreList.contains(descriptor.getName())) {
            continue;
        }// ww w  .j av a  2s. com
        System.err.println("name::" + descriptor.getName());
        if (descriptor.getWriteMethod() != null && descriptor.getReadMethod() != null) {
            if (descriptor.getPropertyType() == String.class) {
                String value = RandomUtil.randomString();
                bean.setProperty(factory, descriptor.getName(), value);
                sb.append("&").append(descriptor.getName()).append("=").append(value);
            } else if (descriptor.getPropertyType() == int.class) {
                int value = RandomUtil.randomPositiveInt();
                bean.setProperty(factory, descriptor.getName(), value);
                sb.append("&").append(descriptor.getName()).append("=").append(value);
            } else if (descriptor.getPropertyType() == long.class) {
                long value = RandomUtil.randomPositiveLong();
                bean.setProperty(factory, descriptor.getName(), value);
                sb.append("&").append(descriptor.getName()).append("=").append(value);
            } else if (descriptor.getPropertyType() == double.class) {
                double value = RandomUtil.randomDouble();
                bean.setProperty(factory, descriptor.getName(), value);
                sb.append("&").append(descriptor.getName()).append("=").append(value);
            }
        }
    }
}

From source file:de.escalon.hypermedia.spring.de.escalon.hypermedia.spring.jackson.LinkListSerializer.java

private void recurseSupportedProperties(JsonGenerator jgen, String currentVocab, Class<?> beanType,
        ActionDescriptor actionDescriptor, ActionInputParameter actionInputParameter, Object currentCallValue)
        throws IntrospectionException, IOException {
    // TODO support Option provider by other method args?
    final BeanInfo beanInfo = Introspector.getBeanInfo(beanType);
    final PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
    // TODO collection and map

    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        final Method writeMethod = propertyDescriptor.getWriteMethod();
        if (writeMethod == null) {
            continue;
        }/*from   w w w . ja  v  a 2  s.c  o m*/
        final Class<?> propertyType = propertyDescriptor.getPropertyType();
        // TODO: the property name must be a valid URI - need to check context for terms?
        String propertyName = getWritableExposedPropertyOrPropertyName(propertyDescriptor);
        if (DataType.isScalar(propertyType)) {

            final Property property = new Property(beanType, propertyDescriptor.getReadMethod(),
                    propertyDescriptor.getWriteMethod(), propertyDescriptor.getName());

            Object propertyValue = getPropertyValue(currentCallValue, propertyDescriptor);

            ActionInputParameter propertySetterInputParameter = new ActionInputParameter(
                    new MethodParameter(propertyDescriptor.getWriteMethod(), 0), propertyValue);
            final Object[] possiblePropertyValues = actionInputParameter.getPossibleValues(property,
                    actionDescriptor);

            writeSupportedProperty(jgen, currentVocab, propertySetterInputParameter, propertyName, property,
                    possiblePropertyValues);
        } else {
            jgen.writeStartObject();
            jgen.writeStringField("hydra:property", propertyName);
            // TODO: is the property required -> for bean props we need the Access annotation to express that
            jgen.writeObjectFieldStart(getPropertyOrClassNameInVocab(currentVocab, "rangeIncludes",
                    JacksonHydraSerializer.HTTP_SCHEMA_ORG, "schema:"));
            Expose expose = AnnotationUtils.getAnnotation(propertyType, Expose.class);
            String subClass;
            if (expose != null) {
                subClass = expose.value();
            } else {
                subClass = propertyType.getSimpleName();
            }
            jgen.writeStringField(getPropertyOrClassNameInVocab(currentVocab, "subClassOf",
                    "http://www.w3.org/2000/01/rdf-schema#", "rdfs:"), subClass);

            jgen.writeArrayFieldStart("hydra:supportedProperty");

            Object propertyValue = getPropertyValue(currentCallValue, propertyDescriptor);

            recurseSupportedProperties(jgen, currentVocab, propertyType, actionDescriptor, actionInputParameter,
                    propertyValue);
            jgen.writeEndArray();

            jgen.writeEndObject();
            jgen.writeEndObject();
        }
    }
}

From source file:net.solarnetwork.support.XmlSupport.java

/**
 * Turn an object into a simple XML Element, supporting custom property
 * editors./*from   ww  w. j a  v a  2  s  .  c  o m*/
 * 
 * <p>
 * The returned XML will be a single element with all JavaBean properties
 * turned into attributes. For example:
 * <p>
 * 
 * <pre>
 * &lt;powerDatum
 *   id="123"
 *   pvVolts="123.123"
 *   ... /&gt;
 * </pre>
 * 
 * <p>
 * {@link PropertyEditor} instances can be registered with the supplied
 * {@link BeanWrapper} for custom handling of properties, e.g. dates.
 * </p>
 * 
 * @param bean
 *        the object to turn into XML
 * @param elementName
 *        the name of the XML element
 * @return the element, as an XML DOM Element
 */
public Element getElement(BeanWrapper bean, String elementName, Document dom) {
    PropertyDescriptor[] props = bean.getPropertyDescriptors();
    Element root = null;
    root = dom.createElement(elementName);
    for (int i = 0; i < props.length; i++) {
        PropertyDescriptor prop = props[i];
        if (prop.getReadMethod() == null) {
            continue;
        }
        String propName = prop.getName();
        if ("class".equals(propName)) {
            continue;
        }
        Object propValue = null;
        PropertyEditor editor = bean.findCustomEditor(prop.getPropertyType(), prop.getName());
        if (editor != null) {
            editor.setValue(bean.getPropertyValue(propName));
            propValue = editor.getAsText();
        } else {
            propValue = bean.getPropertyValue(propName);
        }
        if (propValue == null) {
            continue;
        }
        if (log.isTraceEnabled()) {
            log.trace("attribute name: " + propName + " attribute value: " + propValue);
        }
        root.setAttribute(propName, propValue.toString());
    }
    return root;
}