Example usage for java.beans PropertyDescriptor getReadMethod

List of usage examples for java.beans PropertyDescriptor getReadMethod

Introduction

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

Prototype

public synchronized Method getReadMethod() 

Source Link

Document

Gets the method that should be used to read the property value.

Usage

From source file:net.solarnetwork.node.support.XmlServiceSupport.java

private void writeURLEncodedBeanProperties(BeanWrapper bean, Map<String, ?> attributes, Writer out)
        throws IOException {
    PropertyDescriptor[] props = bean.getPropertyDescriptors();
    boolean propsWritten = false;
    if (attributes != null && attributes.containsKey(ATTR_NODE_ID)) {
        out.write("nodeId=" + attributes.get(ATTR_NODE_ID));
        propsWritten = true;//from   w  ww  . j  a v  a 2s . c  o  m
    }
    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;
        if (attributes != null && attributes.containsKey(propName)) {
            propValue = attributes.get(propName);
        } else {
            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 (propsWritten) {
            out.write("&");
        }
        out.write(propName);
        out.write("=");
        out.write(URLEncoder.encode(propValue.toString(), "UTF-8"));
        propsWritten = true;
    }
    out.flush();
    out.close();
}

From source file:com.datatorrent.stram.webapp.OperatorDiscoverer.java

private JSONArray getClassProperties(Class<?> clazz, int level) throws IntrospectionException {
    JSONArray arr = new JSONArray();
    TypeDiscoverer td = new TypeDiscoverer();
    try {/* w  ww  .  j a  va2  s. c o  m*/
        for (PropertyDescriptor pd : Introspector.getBeanInfo(clazz).getPropertyDescriptors()) {
            Method readMethod = pd.getReadMethod();
            if (readMethod != null) {
                if (readMethod.getDeclaringClass() == java.lang.Enum.class) {
                    // skip getDeclaringClass
                    continue;
                } else if ("class".equals(pd.getName())) {
                    // skip getClass
                    continue;
                }
            } else {
                // yields com.datatorrent.api.Context on JDK6 and com.datatorrent.api.Context.OperatorContext with JDK7
                if ("up".equals(pd.getName())
                        && com.datatorrent.api.Context.class.isAssignableFrom(pd.getPropertyType())) {
                    continue;
                }
            }
            //LOG.info("name: " + pd.getName() + " type: " + pd.getPropertyType());

            Class<?> propertyType = pd.getPropertyType();
            if (propertyType != null) {
                JSONObject propertyObj = new JSONObject();
                propertyObj.put("name", pd.getName());
                propertyObj.put("canGet", readMethod != null);
                propertyObj.put("canSet", pd.getWriteMethod() != null);
                if (readMethod != null) {
                    for (Class<?> c = clazz; c != null; c = c.getSuperclass()) {
                        OperatorClassInfo oci = classInfo.get(c.getName());
                        if (oci != null) {
                            MethodInfo getMethodInfo = oci.getMethods.get(readMethod.getName());
                            if (getMethodInfo != null) {
                                addTagsToProperties(getMethodInfo, propertyObj);
                                break;
                            }
                        }
                    }
                    // type can be a type symbol or parameterized type
                    td.setTypeArguments(clazz, readMethod.getGenericReturnType(), propertyObj);
                } else {
                    if (pd.getWriteMethod() != null) {
                        td.setTypeArguments(clazz, pd.getWriteMethod().getGenericParameterTypes()[0],
                                propertyObj);
                    }
                }
                //if (!propertyType.isPrimitive() && !propertyType.isEnum() && !propertyType.isArray() && !propertyType.getName().startsWith("java.lang") && level < MAX_PROPERTY_LEVELS) {
                //  propertyObj.put("properties", getClassProperties(propertyType, level + 1));
                //}
                arr.put(propertyObj);
            }
        }
    } catch (JSONException ex) {
        throw new RuntimeException(ex);
    }
    return arr;
}

From source file:com.sun.faces.el.impl.BeanInfoManager.java

/**
 * Initializes by mapping property names to BeanInfoProperties
 *///from w  w w. j  a va  2s. c  om
void initialize() throws ElException {
    try {
        mBeanInfo = Introspector.getBeanInfo(mBeanClass);

        mPropertyByName = new HashMap();
        mIndexedPropertyByName = new HashMap();
        PropertyDescriptor[] pds = mBeanInfo.getPropertyDescriptors();
        for (int i = 0; pds != null && i < pds.length; i++) {
            // Treat as both an indexed property and a normal property
            PropertyDescriptor pd = pds[i];
            if (pd instanceof IndexedPropertyDescriptor) {
                IndexedPropertyDescriptor ipd = (IndexedPropertyDescriptor) pd;
                Method readMethod = getPublicMethod(ipd.getIndexedReadMethod());
                Method writeMethod = getPublicMethod(ipd.getIndexedWriteMethod());
                BeanInfoIndexedProperty property = new BeanInfoIndexedProperty(readMethod, writeMethod, ipd);

                mIndexedPropertyByName.put(ipd.getName(), property);
            }

            Method readMethod = getPublicMethod(pd.getReadMethod());
            Method writeMethod = getPublicMethod(pd.getWriteMethod());
            BeanInfoProperty property = new BeanInfoProperty(readMethod, writeMethod, pd);

            mPropertyByName.put(pd.getName(), property);
        }

        mEventSetByName = new HashMap();
        EventSetDescriptor[] esds = mBeanInfo.getEventSetDescriptors();
        for (int i = 0; esds != null && i < esds.length; i++) {
            EventSetDescriptor esd = esds[i];
            mEventSetByName.put(esd.getName(), esd);
        }
    } catch (IntrospectionException exc) {
        if (log.isWarnEnabled()) {
            log.warn(MessageUtil.getMessageWithArgs(Constants.EXCEPTION_GETTING_BEANINFO, mBeanClass.getName()),
                    exc);
        }
    }
}

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

private Method findSupport(final String propertyName, final boolean setter) throws IntrospectionException {

    // If there's a support instance, use it first.

    Method m = null;/*  w  w  w .  j a  v  a  2  s  .c  o  m*/
    if (null != support) {

        final PropertyDescriptor[] propDescriptors = Introspector
                .getBeanInfo(support.getClass().getInterfaces()[0]).getPropertyDescriptors();

        for (PropertyDescriptor pd : propDescriptors) {

            if (propertyName.equalsIgnoreCase(pd.getName())) {
                if (pd instanceof MappedPropertyDescriptor) {

                    final MappedPropertyDescriptor mpd = (MappedPropertyDescriptor) pd;
                    m = setter ? mpd.getMappedWriteMethod() : mpd.getMappedReadMethod();

                } else {
                    m = setter ? pd.getWriteMethod() : pd.getReadMethod();
                }
                break;
            }
        }
    }
    return m;
}

From source file:de.xwic.appkit.core.transport.xml.XmlBeanSerializer.java

/**
 * @param doc/*from  w w w . j  av  a  2 s. co m*/
 * @param string
 * @param query
 * @throws IntrospectionException
 * @throws InvocationTargetException
 * @throws IllegalAccessException
 * @throws IllegalArgumentException
 */
public void serializeBean(Element elm, String elementName, Object bean) throws TransportException {

    Element root = elm.addElement(elementName);

    root.addAttribute("type", bean.getClass().getName());

    try {
        BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());
        for (PropertyDescriptor pd : beanInfo.getPropertyDescriptors()) {

            if (!"class".equals(pd.getName())) {
                Element pElm = root.addElement(pd.getName());
                Method mRead = pd.getReadMethod();
                if (mRead == null) {
                    log.debug(String.format("No '%s' property on '%s'.", pd.getName(), bean.getClass()));
                    continue;
                }
                Object value = mRead.invoke(bean, NO_ARGS);

                boolean addType = true;
                addType = value != null && !value.getClass().equals(pd.getPropertyType())
                        && !pd.getPropertyType().isPrimitive();
                addValue(pElm, value, addType);
            }

        }
    } catch (Exception e) {
        throw new TransportException("Error serializing bean: " + e, e);
    }

}

From source file:net.sourceforge.vulcan.web.struts.forms.PluginConfigForm.java

public void introspect(HttpServletRequest request) throws IntrospectionException, IllegalAccessException,
        InvocationTargetException, NoSuchMethodException, InstantiationException {
    Class<?> cls = null;//from  w w w  .  j a  v a  2s .c  om

    if ("pluginConfig".equals(focus)) {
        cls = pluginConfig.getClass();
        this.breadCrumbs.clear();
        this.breadCrumbs.add("Setup");

        if (isProjectPlugin()) {
            this.breadCrumbs.add("Projects");
            this.breadCrumbs.add(projectName);
            this.breadCrumbs.add(this.pluginConfig.getPluginName());
        } else {
            this.breadCrumbs.add("Plugins");
            this.breadCrumbs.add(this.pluginConfig.getPluginName());
        }
    } else {
        cls = PropertyUtils.getPropertyType(this, focus);
        if (cls.isArray()) {
            cls = cls.getComponentType();
        }
    }

    final String prefix = focus + ".";
    final PropertyDescriptor[] pds;

    if (PluginConfigDto.class.isAssignableFrom(cls)) {
        final PluginConfigDto pluginConfig = (PluginConfigDto) getFocusObject();
        final List<PropertyDescriptor> tmp = pluginConfig.getPropertyDescriptors(request.getLocale());
        pds = tmp.toArray(new PropertyDescriptor[tmp.size()]);

        if (pluginConfig instanceof PluginProfileDto) {
            ((PluginProfileDto) pluginConfig).checkPoint();
        }
    } else {
        final BeanInfo beanInfo = Introspector.getBeanInfo(cls);
        Introspector.flushFromCaches(cls);
        pds = beanInfo.getPropertyDescriptors();
    }

    if (isNested()) {
        for (PropertyDescriptor pd : propertyDescriptors) {
            if (focus.startsWith(pd.getName())) {
                breadCrumbs.add(pd.getDisplayName());
            }
        }
    }

    types.clear();
    choices.clear();
    propertyDescriptors.clear();
    hiddenPasswords.clear();

    for (PropertyDescriptor pd : pds) {
        final String name = prefix + pd.getName();
        final PropertyDescriptor cp = new PropertyDescriptor(pd.getName(), pd.getReadMethod(),
                pd.getWriteMethod());
        cp.setShortDescription(pd.getShortDescription());
        cp.setDisplayName(pd.getDisplayName());
        cp.setName(name);
        propertyDescriptors.add(cp);
        types.put(name, getTypeAndPrepare(name, pd));
    }

    putBreadCrumbsInRequest(request);
}

From source file:com.sunsprinter.diffunit.core.translators.AbstractPropertyDrivenTranslator.java

protected Collection<PropertyDescriptor> determinePropertiesEligibleForTranslation(final T object)
        throws TranslationException {
    // We don't have a map of property names to properties.  We create one now.  We use a linked hash map to
    // preserve the order of the properties.  After all, we've gone to a lot of bother to order our properties
    // so the look nice in our test output.
    final Map<String, PropertyDescriptor> allPropertiesMap = buildAllPropertiesMap(object);

    final Collection<PropertyDescriptor> properties;
    if (getPropertiesToTranslate().isEmpty()) {
        // The client hasn't specified the properties to translate so we do all of them.
        properties = allPropertiesMap.values();
    } else {//  ww  w. ja  v  a 2  s . c  om
        properties = new LinkedList<PropertyDescriptor>();

        // The client has specified the properties we have to translate.
        for (final String propertyName : getPropertiesToTranslate()) {
            final PropertyDescriptor propertyDescriptor = allPropertiesMap.get(propertyName);
            if (propertyDescriptor == null) {
                // Oops.  The client specified a property that doesn't exist.
                throw new TranslationException(object,
                        String.format(
                                "Property '%s' does not exist on object '%s'.  "
                                        + "Available properties are '%s'.",
                                propertyName, getInstanceTracker().getObjectId(object),
                                StringUtils.join(allPropertiesMap.keySet(), "', '")));
            }

            // Skip write-only properties.  Seriously, who does write-only properties?  You'd be surprised.
            if (propertyDescriptor.getReadMethod() != null) {
                properties.add(propertyDescriptor);
            }
        }
    }

    // Now build up our eligible properties collection by adding everything except the things we've been told to skip.
    final Collection<PropertyDescriptor> eligibleProperties = createEligiblePropertiesCollection();
    for (final PropertyDescriptor propertyDescriptor : properties) {
        if (!getPropertiesToSkip().contains(propertyDescriptor.getName())) {
            eligibleProperties.add(propertyDescriptor);
        }
    }

    return eligibleProperties;
}

From source file:com.bstek.dorado.idesupport.initializer.CommonRuleTemplateInitializer.java

protected Collection<AutoPropertyTemplate> getProperties(Class<?> type, XmlNodeInfo xmlNodeInfo,
        InitializerContext initializerContext) throws Exception {
    HashMap<String, AutoPropertyTemplate> properties = new LinkedHashMap<String, AutoPropertyTemplate>();
    RuleTemplateManager ruleTemplateManager = initializerContext.getRuleTemplateManager();

    if (xmlNodeInfo != null) {
        if (xmlNodeInfo.isInheritable()) {
            AutoPropertyTemplate propertyTemplate = new AutoPropertyTemplate("impl");
            propertyTemplate.setPrimitive(true);
            properties.put(propertyTemplate.getName(), propertyTemplate);

            propertyTemplate = new AutoPropertyTemplate("parent");
            propertyTemplate.setPrimitive(true);
            properties.put(propertyTemplate.getName(), propertyTemplate);
        }/*from www  .j  a  v a  2 s.c  om*/

        if (xmlNodeInfo.isScopable()) {
            AutoPropertyTemplate propertyTemplate = new AutoPropertyTemplate("scope");
            propertyTemplate.setPrimitive(true);

            Object[] ecs = Scope.class.getEnumConstants();
            String[] enumValues = new String[ecs.length];
            for (int i = 0; i < ecs.length; i++) {
                enumValues[i] = ecs[i].toString();
            }
            propertyTemplate.setEnumValues(enumValues);

            properties.put(propertyTemplate.getName(), propertyTemplate);
        }

        if (StringUtils.isNotEmpty(xmlNodeInfo.getDefinitionType())) {
            Class<?> definitionType = ClassUtils.forName(xmlNodeInfo.getDefinitionType());
            if (ListenableObjectDefinition.class.isAssignableFrom(definitionType)) {
                AutoPropertyTemplate propertyTemplate = new AutoPropertyTemplate("listener");
                propertyTemplate.setPrimitive(true);
                properties.put(propertyTemplate.getName(), propertyTemplate);
            }

            if (InterceptableDefinition.class.isAssignableFrom(definitionType)) {
                AutoPropertyTemplate propertyTemplate = new AutoPropertyTemplate("interceptor");
                propertyTemplate.setPrimitive(true);
                properties.put(propertyTemplate.getName(), propertyTemplate);
            }
        }

        for (Map.Entry<String, String> entry : xmlNodeInfo.getFixedProperties().entrySet()) {
            String propertyName = entry.getKey();
            String value = entry.getValue();

            AutoPropertyTemplate propertyTemplate = new AutoPropertyTemplate(propertyName);
            propertyTemplate.setDefaultValue(value);
            propertyTemplate.setPrimitive(true);
            propertyTemplate.setFixed(true);
            propertyTemplate.setVisible(false);
            properties.put(propertyName, propertyTemplate);
        }

        for (Map.Entry<String, XmlProperty> entry : xmlNodeInfo.getProperties().entrySet()) {
            String propertyName = entry.getKey();
            XmlProperty xmlProperty = entry.getValue();
            TypeInfo propertyTypeInfo = TypeInfo.parse(xmlProperty.propertyType());
            Class<?> propertyType = null;
            if (propertyTypeInfo != null) {
                propertyType = propertyTypeInfo.getType();
            }

            AutoPropertyTemplate propertyTemplate = new AutoPropertyTemplate(propertyName, xmlProperty);
            propertyTemplate.setPrimitive(xmlProperty.attributeOnly());
            if (propertyType != null && !propertyType.equals(String.class)) {
                propertyTemplate.setType(propertyType.getName());
            }

            if (xmlProperty.composite()) {
                initCompositeProperty(propertyTemplate, propertyType, initializerContext);
            }
            propertyTemplate.setDeprecated(xmlProperty.deprecated());

            properties.put(propertyName, propertyTemplate);
        }
    }

    PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(type);
    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        Method readMethod = propertyDescriptor.getReadMethod();
        if (readMethod != null && propertyDescriptor.getWriteMethod() != null) {
            if (readMethod.getDeclaringClass() != type) {
                try {
                    readMethod = type.getDeclaredMethod(readMethod.getName(), readMethod.getParameterTypes());
                } catch (NoSuchMethodException e) {
                    continue;
                }
            }

            String propertyName = propertyDescriptor.getName();

            XmlSubNode xmlSubNode = readMethod.getAnnotation(XmlSubNode.class);
            if (xmlSubNode != null) {
                continue;
            }

            TypeInfo propertyTypeInfo;
            Class<?> propertyType = propertyDescriptor.getPropertyType();
            if (Collection.class.isAssignableFrom(propertyType)) {
                propertyTypeInfo = TypeInfo.parse((ParameterizedType) readMethod.getGenericReturnType(), true);
                propertyType = propertyTypeInfo.getType();
            } else {
                propertyTypeInfo = new TypeInfo(propertyType, false);
            }

            AutoPropertyTemplate propertyTemplate = null;
            XmlProperty xmlProperty = readMethod.getAnnotation(XmlProperty.class);
            if (xmlProperty != null) {
                if (xmlProperty.unsupported()) {
                    continue;
                }

                propertyTemplate = properties.get(propertyName);
                if (propertyTemplate == null) {
                    propertyTemplate = new AutoPropertyTemplate(propertyName, readMethod, xmlProperty);
                    propertyTemplate.setPrimitive(xmlProperty.attributeOnly());
                }

                if (("dataSet".equals(propertyName) || "dataPath".equals(propertyName)
                        || "property".equals(propertyName)) && DataControl.class.isAssignableFrom(type)) {
                    propertyTemplate.setHighlight(1);
                }

                if (xmlProperty.composite()) {
                    initCompositeProperty(propertyTemplate, propertyType, initializerContext);
                }

                int clientTypes = ClientType.parseClientTypes(xmlProperty.clientTypes());
                if (clientTypes > 0) {
                    propertyTemplate.setClientTypes(clientTypes);
                }
                propertyTemplate.setDeprecated(xmlProperty.deprecated());
            } else if (EntityUtils.isSimpleType(propertyType) || propertyType.equals(Class.class)
                    || propertyType.isArray() && propertyType.getComponentType().equals(String.class)) {
                propertyTemplate = new AutoPropertyTemplate(propertyName, readMethod, xmlProperty);
            }

            if (propertyTemplate != null) {
                propertyTemplate.setType(propertyDescriptor.getPropertyType().getName());

                if (propertyType.isEnum()) {
                    Object[] ecs = propertyType.getEnumConstants();
                    String[] enumValues = new String[ecs.length];
                    for (int i = 0; i < ecs.length; i++) {
                        enumValues[i] = ecs[i].toString();
                    }
                    propertyTemplate.setEnumValues(enumValues);
                }

                ComponentReference componentReference = readMethod.getAnnotation(ComponentReference.class);
                if (componentReference != null) {
                    ReferenceTemplate referenceTemplate = new LazyReferenceTemplate(ruleTemplateManager,
                            componentReference.value(), "id");
                    propertyTemplate.setReference(referenceTemplate);
                }

                IdeProperty ideProperty = readMethod.getAnnotation(IdeProperty.class);
                if (ideProperty != null) {
                    propertyTemplate.setVisible(ideProperty.visible());
                    propertyTemplate.setEditor(ideProperty.editor());
                    propertyTemplate.setHighlight(ideProperty.highlight());
                    if (StringUtils.isNotEmpty(ideProperty.enumValues())) {
                        propertyTemplate.setEnumValues(StringUtils.split(ideProperty.enumValues(), ",;"));
                    }
                }

                ClientProperty clientProperty = readMethod.getAnnotation(ClientProperty.class);
                if (clientProperty != null) {
                    propertyTemplate.setDefaultValue(clientProperty.escapeValue());
                }

                properties.put(propertyName, propertyTemplate);
            }
        }
    }
    return properties.values();
}

From source file:com.cnd.greencube.server.dao.jdbc.JdbcDAO.java

@SuppressWarnings("rawtypes")
private Column2Property getIdFromObject(Class clazz) throws Exception {

    // ???//  w  w  w  . ja  v a2 s. c  om
    for (Field field : clazz.getDeclaredFields()) {
        String columnName = null;
        Annotation[] annotations = field.getDeclaredAnnotations();
        for (Annotation a : annotations) {
            if (a instanceof Id) {
                PropertyDescriptor pd = new PropertyDescriptor(field.getName(), clazz);
                Column2Property c = new Column2Property();
                c.propertyName = pd.getName();
                c.setterMethodName = pd.getWriteMethod().getName();
                c.getterMethodName = pd.getReadMethod().getName();
                c.columnName = columnName;
                return c;

            }
        }
    }
    return null;
}

From source file:com.cnd.greencube.server.dao.jdbc.JdbcDAO.java

@SuppressWarnings("rawtypes")
private List<Column2Property> getColumnsFromObj(Object obj, String[] columns) {
    Class clazz = obj.getClass();
    List<Column2Property> validColumns = new ArrayList<Column2Property>();

    // ???/*from  w  w w .ja  v  a  2 s. c o  m*/
    for (Field field : clazz.getDeclaredFields()) {
        boolean skip = true;
        String columnName = null;
        Annotation[] annotations = field.getAnnotations();
        for (Annotation a : annotations) {
            if (a instanceof Column) {
                columnName = ((Column) a).name();
                if (columns != null && !_inarray_(columns, columnName))
                    skip = true;
                else {
                    skip = false;
                }

                break;
            }
        }

        String s = field.getName();
        PropertyDescriptor pd = null;

        if (!skip) {
            // ?gettersetter
            try {
                pd = new PropertyDescriptor(s, clazz);
                if (pd == null || pd.getWriteMethod() == null || pd.getReadMethod() == null) {
                    skip = true;
                }
            } catch (Exception e) {
                skip = true;
            }
        }

        if (!skip) {
            Column2Property c = new Column2Property();
            c.propertyName = pd.getName();
            c.setterMethodName = pd.getWriteMethod().getName();
            c.getterMethodName = pd.getReadMethod().getName();
            c.columnName = columnName;
            validColumns.add(c);
        }
    }

    Column2Property c = new Column2Property();
    c.propertyName = "id";
    c.setterMethodName = "setId";
    c.getterMethodName = "getId";
    c.columnName = "C_ID";
    validColumns.add(c);

    return validColumns;
}