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:org.grails.datastore.mapping.model.config.GormMappingConfigurationStrategy.java

private boolean isNotMappedToDifferentProperty(PropertyDescriptor property, String relatedClassPropertyName,
        Map mappedBy) {//from   ww  w.jav  a2s  .co m

    String mappedByForRelation = (String) mappedBy.get(relatedClassPropertyName);
    if (mappedByForRelation == null)
        return true;
    if (!property.getName().equals(mappedByForRelation))
        return false;
    return true;
}

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

/**
 * Gets exposed property or parameter name for properties with an appropriate setter (=write) method.
 *
 * @param inputParameter/* w w  w.  jav a2s .c o m*/
 *         for exposure
 * @return property name
 */
private String getWritableExposedPropertyOrPropertyName(PropertyDescriptor inputParameter) {

    final Method writeMethod = inputParameter.getWriteMethod();
    final Expose expose = writeMethod.getAnnotation(Expose.class);
    String propertyName;
    if (expose != null) {
        propertyName = expose.value();
    } else {
        propertyName = inputParameter.getName();
    }
    return propertyName;
}

From source file:com.twinsoft.convertigo.engine.Context.java

public Object getTransactionProperty(String propertyName) {
    if (requestedObject == null) {
        return null;
    }/*from   w  w  w .j a  v a 2s  . c o m*/
    BeanInfo bi;
    try {
        bi = CachedIntrospector.getBeanInfo(requestedObject.getClass());
    } catch (IntrospectionException e) {
        Engine.logContext
                .error("getTransactionProperty : Exception while finding the bean info for transaction class '"
                        + requestedObject.getClass() + "'", e);
        return null;
    }
    PropertyDescriptor[] propertyDescriptors = bi.getPropertyDescriptors();
    int len2 = propertyDescriptors.length;
    PropertyDescriptor propertyDescriptor = null;
    Object propertyValue;
    int j;
    String propertyDescriptorName = "";
    for (j = 0; j < len2; j++) {
        propertyDescriptor = propertyDescriptors[j];
        propertyDescriptorName = propertyDescriptor.getName();
        if (propertyDescriptorName.equals(propertyName))
            break;
    }
    if (j == len2 && !propertyDescriptorName.equals(propertyName)) {
        Engine.logContext.debug("getTransactionProperty : no property descriptor found for the property '"
                + propertyName + "'");
        return null;
    }

    Method getter = propertyDescriptor.getReadMethod();
    Object args[] = {};
    try {
        propertyValue = getter.invoke(requestedObject, args);
    } catch (Exception e) {
        Engine.logContext.error("getTransactionProperty : Exception while executing the property getter '"
                + getter.getName() + "'", e);
        return null;
    }
    return propertyValue;
}

From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractConnectorController.java

private String valid(String validationJson, String fieldName, String fieldValue) throws Exception {
    if (StringUtils.isNotBlank(validationJson)) {
        JsonBean jsonObject = JSONUtils.fromJSONString(validationJson, JsonBean.class);
        PropertyDescriptor pd[] = BeanUtils.getPropertyDescriptors(JsonBean.class);
        for (PropertyDescriptor propertyDescriptor : pd) {
            String propertyname = propertyDescriptor.getName();
            if (!"class".equals(propertyname)) {
                Object propertyvalue = PropertyUtils.getProperty(jsonObject, propertyname);
                if (propertyvalue instanceof Boolean && (Boolean) propertyvalue
                        || !(propertyvalue instanceof Boolean)) {
                    String validationResult = jsonObject.validate(fieldName, fieldValue, messageSource);
                    if (!validationResult.equals(CssdkConstants.SUCCESS)) {
                        return validationResult;
                    }/* ww  w  .j  a v  a2 s . c  o m*/
                }
            }
        }
    }
    return CssdkConstants.SUCCESS;
}

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

/**
 * Turn an object into a simple XML Element, supporting custom property
 * editors.// w w 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
 */
protected 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: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;//  w w  w.j a va 2  s  . 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:org.grails.datastore.mapping.model.config.GormMappingConfigurationStrategy.java

private Association establishRelationshipForCollection(PropertyDescriptor property, PersistentEntity entity,
        MappingContext context, Map<String, Class> hasManyMap, Map mappedByMap) {
    // is it a relationship
    Class relatedClassType = hasManyMap.get(property.getName());
    if (relatedClassType == null) {
        return propertyFactory.createBasicCollection(entity, context, property);
    }/* w ww . j av a2 s. co m*/

    // set the referenced type in the property
    ClassPropertyFetcher referencedCpf = ClassPropertyFetcher.forClass(relatedClassType);
    String referencedPropertyName = null;

    // if the related type is a domain class
    // then figure out what kind of relationship it is
    if (!isPersistentEntity(relatedClassType)) {
        // otherwise set it to not persistent as you can't persist
        // relationships to non-domain classes
        return propertyFactory.createBasicCollection(entity, context, property);
    }

    // check the relationship defined in the referenced type
    // if it is also a Set/domain class etc.
    Map relatedClassRelationships = referencedCpf.getPropertyValue(HAS_MANY, Map.class);
    Class<?> relatedClassPropertyType = null;

    String relatedClassPropertyName = null;
    ClassPropertyFetcher cpf = ClassPropertyFetcher.forClass(entity.getJavaClass());
    // First check whether there is an explicit relationship
    // mapping for this property (as provided by "mappedBy").
    String mappingProperty = (String) mappedByMap.get(property.getName());
    if (StringUtils.hasText(mappingProperty)) {
        // First find the specified property on the related class, if it exists.
        PropertyDescriptor pd = findProperty(
                referencedCpf.getPropertiesAssignableFromType(entity.getJavaClass()), mappingProperty);

        // If a property of the required type does not exist, search
        // for any collection properties on the related class.
        if (pd == null) {
            pd = findProperty(referencedCpf.getPropertiesAssignableToType(Collection.class), mappingProperty);
        }

        // We've run out of options. The given "mappedBy" setting is invalid.
        if (pd == null) {
            if (entity.isExternal()) {
                return null;
            }
            throw new IllegalMappingException(
                    "Non-existent mapping property [" + mappingProperty + "] specified for property ["
                            + property.getName() + "] in class [" + entity.getJavaClass().getName() + "]");
        }

        // Tie the properties together.
        relatedClassPropertyType = pd.getPropertyType();
        referencedPropertyName = pd.getName();
    } else {

        if (!forceUnidirectional(property, mappedByMap)) {
            // if the related type has a relationships map it may be a many-to-many
            // figure out if there is a many-to-many relationship defined
            if (isRelationshipToMany(entity, relatedClassType, relatedClassRelationships)) {
                Map relatedClassMappedBy = cpf.getStaticPropertyValue(MAPPED_BY, Map.class);
                if (relatedClassMappedBy == null)
                    relatedClassMappedBy = Collections.emptyMap();
                // retrieve the relationship property
                for (Object o : relatedClassRelationships.keySet()) {
                    String currentKey = (String) o;
                    String mappedByProperty = (String) relatedClassMappedBy.get(currentKey);
                    if (mappedByProperty != null && !mappedByProperty.equals(property.getName()))
                        continue;
                    Class<?> currentClass = (Class<?>) relatedClassRelationships.get(currentKey);
                    if (currentClass.isAssignableFrom(entity.getJavaClass())) {
                        relatedClassPropertyName = currentKey;
                        break;
                    }
                }
                //            Map classRelationships = cpf.getPropertyValue(HAS_MANY, Map.class);
                //
                //            if (isRelationshipToMany(entity, relatedClassType, classRelationships)) {
                //                String relatedClassPropertyName = findManyRelatedClassPropertyName(
                //                        property.getName(), referencedCpf, classRelationships, relatedClassType);

                // if there is one defined get the type
                if (relatedClassPropertyName != null) {
                    relatedClassPropertyType = referencedCpf.getPropertyType(relatedClassPropertyName);
                }
            }

            // otherwise figure out if there is a one-to-many relationship by retrieving any properties that are of the related type
            // if there is more than one property then (for the moment) ignore the relationship
            if (relatedClassPropertyType == null
                    || Collection.class.isAssignableFrom(relatedClassPropertyType)) {
                List<PropertyDescriptor> descriptors = referencedCpf
                        .getPropertiesAssignableFromType(entity.getJavaClass());

                if (descriptors.size() == 1) {
                    final PropertyDescriptor pd = descriptors.get(0);
                    relatedClassPropertyType = pd.getPropertyType();
                    referencedPropertyName = pd.getName();
                } else if (descriptors.size() > 1) {
                    // try now to use the class name by convention
                    String classPropertyName = entity.getDecapitalizedName();
                    PropertyDescriptor pd = findProperty(descriptors, classPropertyName);
                    if (pd == null) {
                        if (entity.isExternal()) {
                            return null;
                        }
                        pd = descriptors.get(0);
                    }

                    if (pd != null) {
                        relatedClassPropertyType = pd.getPropertyType();
                        referencedPropertyName = pd.getName();
                    }
                }
            }
        }
    }

    // if its a many-to-many figure out the owning side of the relationship
    final boolean isInverseSideEntity = isPersistentEntity(relatedClassPropertyType);
    Association association = null;
    boolean many = false;
    if (relatedClassPropertyType == null || isInverseSideEntity) {
        // uni-directional one-to-many
        association = propertyFactory.createOneToMany(entity, context, property);
    } else if (Collection.class.isAssignableFrom(relatedClassPropertyType)
            || Map.class.isAssignableFrom(relatedClassPropertyType)) {
        // many-to-many
        association = propertyFactory.createManyToMany(entity, context, property);
        ((ManyToMany) association).setInversePropertyName(relatedClassPropertyName);
        many = true;
    }

    PersistentEntity associatedEntity = getOrCreateAssociatedEntity(entity, context, relatedClassType);
    if (many) {
        Map classRelationships = referencedCpf.getPropertyValue(HAS_MANY, Map.class);
        referencedPropertyName = findManyRelatedClassPropertyName(null, referencedCpf, classRelationships,
                entity.getJavaClass());
    }

    if (association != null) {
        association.setAssociatedEntity(associatedEntity);
        if (referencedPropertyName != null) {
            association.setReferencedPropertyName(referencedPropertyName);
        }
    }
    return association;
}

From source file:com.bstek.dorado.config.xml.XmlParserHelper.java

protected void doInitObjectParser(Context context, ObjectParser objectParser, XmlNodeInfo xmlNodeInfo,
        Class<?> beanType) throws Exception {
    objectParser.setAnnotationOwnerType(beanType);
    if (!Modifier.isAbstract(beanType.getModifiers())) {
        objectParser.setImpl(beanType.getName());
    }//  ww w.j a  v a 2 s.  co m

    if (xmlNodeInfo != null) {
        if (StringUtils.isNotEmpty(xmlNodeInfo.getDefinitionType())) {
            objectParser.setDefinitionType(xmlNodeInfo.getDefinitionType());
        }

        Map<String, XmlParser> propertyParsers = objectParser.getPropertyParsers();
        Map<String, XmlParser> subParsers = objectParser.getSubParsers();

        if (!(objectParser instanceof CompositePropertyParser)) {
            boolean inheritable = objectParser.isInheritable() || xmlNodeInfo.isInheritable();
            objectParser.setInheritable(inheritable);
            if (inheritable) {
                if (propertyParsers.get("parent") == null) {
                    objectParser.registerPropertyParser("parent",
                            beanFactory.getBean(IGNORE_PARSER, XmlParser.class));
                }
            }

            boolean scopable = objectParser.isScopable() || xmlNodeInfo.isScopable();
            objectParser.setScopable(scopable);
            if (scopable) {
                if (propertyParsers.get("scope") == null) {
                    objectParser.registerPropertyParser("scope",
                            beanFactory.getBean(IGNORE_PARSER, XmlParser.class));
                }
            }

            for (String fixedProperty : xmlNodeInfo.getFixedProperties().keySet()) {
                if (propertyParsers.get(fixedProperty) == null) {
                    objectParser.registerPropertyParser(fixedProperty,
                            beanFactory.getBean(IGNORE_PARSER, XmlParser.class));
                }
            }
        }

        for (XmlSubNode xmlSubNode : xmlNodeInfo.getSubNodes()) {
            if (StringUtils.isNotEmpty(xmlSubNode.propertyType())) {
                List<XmlParserInfo> xmlParserInfos = getSubNodeXmlParserInfos(context, beanType,
                        xmlSubNode.propertyName(), null, xmlSubNode);
                if (xmlParserInfos != null) {
                    for (XmlParserInfo xmlParserInfo : xmlParserInfos) {
                        objectParser.registerSubParser(xmlParserInfo.getPath(), xmlParserInfo.getParser());
                    }
                }
            } else if (StringUtils.isNotEmpty(xmlSubNode.nodeName())
                    && StringUtils.isNotEmpty(xmlSubNode.parser())) {
                BeanWrapper beanWrapper = BeanFactoryUtils.getBean(xmlSubNode.parser(), Scope.instant);
                objectParser.registerSubParser(xmlSubNode.nodeName(), (XmlParser) beanWrapper.getBean());
            }
        }

        for (Map.Entry<String, XmlProperty> entry : xmlNodeInfo.getProperties().entrySet()) {
            XmlProperty xmlProperty = entry.getValue();
            XmlParserInfo xmlParserInfo = getPropertyXmlParserInfo(context, beanType,
                    xmlProperty.propertyName(), null, xmlProperty);
            if (xmlParserInfo != null) {
                objectParser.registerPropertyParser(xmlParserInfo.getPath(), xmlParserInfo.getParser());
            }
        }

        if (ClientEventSupported.class.isAssignableFrom(beanType) && subParsers.get("ClientEvent") == null) {
            objectParser.registerSubParser("ClientEvent",
                    beanFactory.getBean(CLIENT_EVENT_PARSER, XmlParser.class));
        }
    }

    PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(beanType);
    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        String propertyName = propertyDescriptor.getName();
        if ("class".equals(propertyName)) {
            continue;
        }

        Method readMethod = propertyDescriptor.getReadMethod();
        if (readMethod == null) {
            continue;
        }
        if (readMethod.getDeclaringClass() != beanType) {
            try {
                readMethod = beanType.getMethod(readMethod.getName(), readMethod.getParameterTypes());
            } catch (NoSuchMethodException e) {
                // do nothing
            }
        }

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

        XmlSubNode xmlSubNode = readMethod.getAnnotation(XmlSubNode.class);
        if (xmlSubNode != null) {
            if (StringUtils.isNotEmpty(xmlSubNode.propertyName())) {
                throw new IllegalArgumentException("@XmlSubNode.propertyName should be empty. ["
                        + beanType.getName() + '#' + propertyName + "]");
            }

            List<XmlParserInfo> xmlParserInfos = getSubNodeXmlParserInfos(context, beanType, propertyName,
                    typeInfo, xmlSubNode);
            if (xmlParserInfos != null) {
                for (XmlParserInfo xmlParserInfo : xmlParserInfos) {
                    objectParser.registerSubParser(xmlParserInfo.getPath(), xmlParserInfo.getParser());
                }
            }
        } else {
            XmlProperty xmlProperty = readMethod.getAnnotation(XmlProperty.class);
            if (xmlProperty != null && StringUtils.isNotEmpty(xmlProperty.propertyName())) {
                throw new IllegalArgumentException("@XmlProperty.propertyName should be empty. ["
                        + beanType.getName() + '#' + propertyName + "]");
            }

            XmlParserInfo xmlParserInfo = getPropertyXmlParserInfo(context, beanType, propertyName, typeInfo,
                    xmlProperty);
            if (xmlParserInfo != null) {
                XmlParser parser = xmlParserInfo.getParser();
                if (parser instanceof TextPropertyParser) {
                    TextPropertyParser textPropertyParser = (TextPropertyParser) parser;
                    if (textPropertyParser.getTextParser() == null) {
                        TextParser textParser = textParserHelper.getTextParser(propertyType);
                        textPropertyParser.setTextParser(textParser);
                    }
                }
                objectParser.registerPropertyParser(xmlParserInfo.getPath(), parser);
            }
        }
    }

    if (objectParser instanceof ObjectParserInitializationAware) {
        ((ObjectParserInitializationAware) objectParser).postObjectParserInitialized(objectParser);
    }

    Map<String, XmlParserHelperListener> listenerMap = ((ListableBeanFactory) beanFactory)
            .getBeansOfType(XmlParserHelperListener.class);
    for (XmlParserHelperListener listener : listenerMap.values()) {
        listener.onInitParser(this, objectParser, beanType);
    }
}

From source file:com.nway.spring.jdbc.bean.AsmBeanProcessor.java

/**
 * Calls the setter method on the target object for the given property. If no setter method
 * exists for the property, this method does nothing.
 *
 * @param target The object to set the property on.
 * @param prop The property to set.//from w ww  .jav  a 2 s  . c o m
 * @param value The value to pass into the setter.
 * @throws SQLException if an error occurs setting the property.
 */
private void callSetter(Object target, PropertyDescriptor prop, Object value) throws SQLException {

    Method setter = prop.getWriteMethod();

    if (setter == null) {

        return;
    }

    try {

        // Don't call setter if the value object isn't the right type
        // if (this.isCompatibleType(value, params[0])) {
        setter.invoke(target, new Object[] { value });

    } catch (Exception e) {

        throw new SQLException("Cannot set " + prop.getName() + ": " + e.toString(), e);
    }
}

From source file:net.mojodna.searchable.AbstractBeanIndexer.java

/**
 * Add fields for each indexed/stored property.
 * //from   w w w.  j  a va2s. c o  m
 * @param doc Document to add fields to.
 * @param bean Bean to process.
 * @param descriptor Property descriptor.
 * @param stack Stack containing parent field names.
 * @param inheritedBoost Inherited boost factor.
 * @return Document with additional fields.
 * @throws IndexingException
 */
private Document addBeanFields(final Document doc, final Searchable bean, final PropertyDescriptor descriptor,
        final Stack<String> stack, final float inheritedBoost) throws IndexingException {
    final Method readMethod = descriptor.getReadMethod();
    for (final Class<? extends Annotation> annotationClass : Searchable.INDEXING_ANNOTATIONS) {
        if (null != readMethod && AnnotationUtils.isAnnotationPresent(readMethod, annotationClass)) {

            // don't index elements marked as nested=false in a nested context
            if (!stack.isEmpty() && !isNested(descriptor)) {
                continue;
            }

            for (final String fieldname : SearchableUtils.getFieldnames(descriptor)) {
                log.debug("Indexing " + descriptor.getName() + " as " + getFieldname(fieldname, stack));

                try {
                    final Object prop = PropertyUtils.getProperty(bean, descriptor.getName());
                    if (null == prop)
                        continue;

                    addFields(doc, fieldname, prop, descriptor, stack, inheritedBoost);
                } catch (final IndexingException e) {
                    throw e;
                } catch (final Exception e) {
                    throw new IndexingException("Unable to index bean.", e);
                }
            }
        }
    }

    return doc;
}