Example usage for java.beans PropertyDescriptor getName

List of usage examples for java.beans PropertyDescriptor getName

Introduction

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

Prototype

public String getName() 

Source Link

Document

Gets the programmatic name of this feature.

Usage

From source file:com.siberhus.tdfl.mapping.BeanWrapLineMapper.java

@SuppressWarnings("unchecked")
protected Properties getBeanProperties(Object bean, Properties properties) throws IntrospectionException {

    Class<?> cls = bean.getClass();

    String[] namesCache = propertyNamesCache.get(cls);
    if (namesCache == null) {
        List<String> setterNames = new ArrayList<String>();
        BeanInfo beanInfo = Introspector.getBeanInfo(cls);
        PropertyDescriptor propDescs[] = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor propDesc : propDescs) {
            if (propDesc.getWriteMethod() != null) {
                setterNames.add(propDesc.getName());
            }//from  ww w.  jav  a2 s.  com
        }
        propertyNamesCache.put(cls, setterNames.toArray(new String[0]));
    }
    // Map from field names to property names
    Map<String, String> matches = propertiesMatched.get(cls);
    if (matches == null) {
        matches = new HashMap<String, String>();
        propertiesMatched.put(cls, matches);
    }

    @SuppressWarnings("rawtypes")
    Set<String> keys = new HashSet(properties.keySet());
    for (String key : keys) {

        if (matches.containsKey(key)) {
            switchPropertyNames(properties, key, matches.get(key));
            continue;
        }

        String name = findPropertyName(bean, key);

        if (name != null) {
            matches.put(key, name);
            switchPropertyNames(properties, key, name);
        }
    }

    return properties;
}

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

/**
 * Turn an object into a simple XML Element, supporting custom property
 * editors./*from w ww.  j  a va2s. 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;
}

From source file:at.molindo.notify.model.BeanParams.java

@Override
public Iterator<ParamValue> iterator() {
    return new Iterator<ParamValue>() {

        private final Iterator<PropertyDescriptor> _iter = getDescriptorsIter();
        private ParamValue _next = findNext();

        private ParamValue findNext() {
            while (_iter.hasNext()) {
                PropertyDescriptor pd = _iter.next();
                if (pd.getWriteMethod() == null || pd.getReadMethod() == null) {
                    continue;
                }/* w w  w .java 2s  .co m*/
                Object value = invoke(pd.getReadMethod());
                if (value == null) {
                    continue;
                }
                return Param.p(pd.getPropertyType(), pd.getName()).paramValue(value);
            }
            return null;
        }

        @Override
        public boolean hasNext() {
            return _next != null;
        }

        @Override
        public ParamValue next() {
            if (!hasNext()) {
                throw new NoSuchElementException();
            }
            ParamValue next = _next;
            _next = findNext();
            return next;
        }

        @Override
        public void remove() {
            throw new UnsupportedOperationException();
        }
    };
}

From source file:com.github.hateoas.forms.spring.xhtml.XhtmlResourceMessageConverter.java

private void writeObject(XhtmlWriter writer, Object object)
        throws IOException, IllegalAccessException, InvocationTargetException {
    if (!DataType.isSingleValueType(object.getClass())) {
        writer.beginDl();//w w  w  . j a  v  a  2s  .c o m
    }
    if (object instanceof Map) {
        Map<?, ?> map = (Map<?, ?>) object;
        for (Entry<?, ?> entry : map.entrySet()) {
            String name = entry.getKey().toString();
            Object content = entry.getValue();
            String docUrl = documentationProvider.getDocumentationUrl(name, content);
            writeObjectAttributeRecursively(writer, name, content, docUrl);
        }
    } else if (object instanceof Enum) {
        String name = ((Enum) object).name();
        String docUrl = documentationProvider.getDocumentationUrl(name, object);
        writeDdForScalarValue(writer, object);
    } else if (object instanceof Currency) {
        // TODO configurable classes which should be rendered with toString
        // or use JsonSerializer or DataType?
        String name = object.toString();
        String docUrl = documentationProvider.getDocumentationUrl(name, object);
        writeDdForScalarValue(writer, object);
    } else {
        Class<?> aClass = object.getClass();
        Map<String, PropertyDescriptor> propertyDescriptors = PropertyUtils.getPropertyDescriptors(object);
        // getFields retrieves public only
        Field[] fields = aClass.getFields();
        for (Field field : fields) {
            String name = field.getName();
            if (!propertyDescriptors.containsKey(name)) {
                Object content = field.get(object);
                String docUrl = documentationProvider.getDocumentationUrl(field, content);
                //<a href="http://schema.org/review">http://schema.org/performer</a>
                writeObjectAttributeRecursively(writer, name, content, docUrl);
            }
        }
        for (PropertyDescriptor propertyDescriptor : propertyDescriptors.values()) {
            String name = propertyDescriptor.getName();
            if (FILTER_RESOURCE_SUPPORT.contains(name)) {
                continue;
            }
            Method readMethod = propertyDescriptor.getReadMethod();
            if (readMethod != null) {
                Object content = readMethod.invoke(object);
                String docUrl = documentationProvider.getDocumentationUrl(readMethod, content);
                writeObjectAttributeRecursively(writer, name, content, docUrl);
            }
        }
    }
    if (!DataType.isSingleValueType(object.getClass())) {
        writer.endDl();
    }
}

From source file:de.escalon.hypermedia.hydra.serialize.JacksonHydraSerializer.java

private Map<String, Object> getTerms(Object bean, Class<?> mixInClass)
        throws IntrospectionException, IllegalAccessException, NoSuchFieldException {
    // define terms from package or type in context
    final Class<?> beanClass = bean.getClass();
    Map<String, Object> termsMap = getAnnotatedTerms(beanClass.getPackage(), beanClass.getPackage().getName());
    Map<String, Object> classTermsMap = getAnnotatedTerms(beanClass, beanClass.getName());
    Map<String, Object> mixinTermsMap = getAnnotatedTerms(mixInClass, beanClass.getName());

    // class terms override package terms
    termsMap.putAll(classTermsMap);/*from  w w  w.  j  av  a 2 s .  c  o m*/
    // mixin terms override class terms
    termsMap.putAll(mixinTermsMap);

    final Field[] fields = beanClass.getDeclaredFields();
    for (Field field : fields) {
        final Expose fieldExpose = field.getAnnotation(Expose.class);
        if (Enum.class.isAssignableFrom(field.getType())) {
            Map<String, String> map = new LinkedHashMap<String, String>();
            termsMap.put(field.getName(), map);
            if (fieldExpose != null) {
                map.put(AT_ID, fieldExpose.value());
            }
            map.put(AT_TYPE, AT_VOCAB);
            final Enum value = (Enum) field.get(bean);
            final Expose enumValueExpose = getAnnotation(value.getClass().getField(value.name()), Expose.class);
            // TODO redefine actual enum value to exposed on enum value definition
            if (enumValueExpose != null) {
                termsMap.put(value.toString(), enumValueExpose.value());
            } else {
                // might use upperToCamelCase if nothing is exposed
                final String camelCaseEnumValue = WordUtils
                        .capitalizeFully(value.toString(), new char[] { '_' }).replaceAll("_", "");
                termsMap.put(value.toString(), camelCaseEnumValue);
            }
        } else {
            if (fieldExpose != null) {
                termsMap.put(field.getName(), fieldExpose.value());
            }
        }
    }

    // TODO do this recursively for nested beans and collect as long as
    // nested beans have same vocab
    // expose getters in context
    final BeanInfo beanInfo = Introspector.getBeanInfo(beanClass);
    final PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        final Method method = propertyDescriptor.getReadMethod();

        final Expose expose = method.getAnnotation(Expose.class);
        if (expose != null) {
            termsMap.put(propertyDescriptor.getName(), expose.value());
        }
    }
    return termsMap;
}

From source file:com.easyget.commons.csv.bean.CsvToBean.java

/**
 * Creates a single object from a line from the csv file.
 * @param mapper - MappingStrategy//  ww w .  j a  v  a  2  s. c om
 * @param line  - array of Strings from the csv file.
 * @return - object containing the values.
 * @throws IllegalAccessException - thrown on error creating bean.
 * @throws InvocationTargetException - thrown on error calling the setters.
 * @throws InstantiationException - thrown on error creating bean.
 * @throws IntrospectionException - thrown on error getting the PropertyDescriptor.
 * @throws ParseException 
 */
protected T processLine(MappingStrategy<T> mapper, Line line, FieldFormater formater)
        throws IllegalAccessException, InvocationTargetException, InstantiationException,
        IntrospectionException, ParseException {
    T bean = mapper.createBean();
    String[] fields = line.getLine();
    for (int col = 0; col < fields.length; col++) {
        PropertyDescriptor prop = mapper.findDescriptor(col);
        String value = checkForTrim(fields[col], prop);
        // ?
        if (formater != null)
            value = formater.parse(value);
        try {
            Class<?> clazz = prop.getPropertyType();
            Object ov = ConvertUtils.convert(value, clazz);
            PropertyUtils.setProperty(bean, prop.getName(), ov);
        } catch (NoSuchMethodException e) {
            // 
        }
    }
    return bean;
}

From source file:org.archive.crawler.restlet.JobRelatedResource.java

protected void defaultUpdateDescriptor(PropertyDescriptor pd) {
    // make non-editable
    try {/*from   ww w .j  a va 2 s.c om*/
        pd.setWriteMethod(null);
    } catch (IntrospectionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    if (HIDDEN_PROPS.contains(pd.getName())) {
        pd.setHidden(true);
    }
}

From source file:com.clican.pluto.common.support.spring.BeanPropertyRowMapper.java

/**
 * Extract the values for all columns in the current row.
 * <p>//from ww w . java  2s . c o  m
 * Utilizes public setters and result set metadata.
 * 
 * @see java.sql.ResultSetMetaData
 */
public Object mapRow(ResultSet rs, int rowNumber) throws SQLException {
    Assert.state(this.mappedClass != null, "Mapped class was not specified");
    Object mappedObject = BeanUtils.instantiateClass(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).toLowerCase();
        PropertyDescriptor pd = (PropertyDescriptor) this.mappedFields.get(column);
        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());
                }
                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);
            }
        }
    }

    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.googlecode.jsonplugin.JSONWriter.java

/**
 * Ignore "class" field/*w w  w.  ja  v a2s . com*/
 */
private boolean shouldExcludeProperty(Class clazz, PropertyDescriptor prop)
        throws SecurityException, NoSuchFieldException {
    String name = prop.getName();

    if (name.equals("class") || name.equals("declaringClass") || name.equals("cachedSuperClass")
            || name.equals("metaClass")) {
        return true;
    }

    return false;
}