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:com.maomao.framework.dao.jdbc.JdbcDAO.java

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

    // ???/* ww  w  .  j  av a2  s.  c  o m*/
    Column2Property c = null;
    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);
                c = new Column2Property();
                c.propertyName = pd.getName();
                c.setterMethodName = pd.getWriteMethod().getName();
                c.getterMethodName = pd.getReadMethod().getName();
                c.columnName = columnName;
                break;
            }
        }
    }

    if (c == null) {
        Class superClass = clazz.getSuperclass();
        for (Field field : superClass.getDeclaredFields()) {
            String columnName = null;
            Annotation[] annotations = field.getDeclaredAnnotations();
            for (Annotation a : annotations) {
                if (a instanceof Id) {
                    PropertyDescriptor pd = new PropertyDescriptor(field.getName(), superClass);
                    c = new Column2Property();
                    c.propertyName = pd.getName();
                    c.setterMethodName = pd.getWriteMethod().getName();
                    c.getterMethodName = pd.getReadMethod().getName();
                    c.columnName = columnName;
                    break;

                }
            }
        }
    }

    return c;
}

From source file:org.etudes.ambrosia.impl.UiPropertyReference.java

/**
 * Read the configured selector value from the entity.
 * //from   w  ww .j a v  a  2  s . c o  m
 * @param context
 *        The context.
 * @param entity
 *        The entity to read from.
 * @param selector
 *        The selector name.
 * @return The selector value object found, or null if not.
 */
protected Object getValue(Context context, Object entity, String property) {
    // if no selector named, just use the entity
    if (property == null)
        return entity;

    // if the property is an index reference
    if (property.startsWith("[") && property.endsWith("]")) {
        return getIndexValue(entity, decode(property.substring(1, property.length() - 1)));
    }

    // another form of index, taking the index value from the nested references
    if (property.startsWith("{") && property.endsWith("}")) {
        try {
            String propertiesIndex = property.substring(1, property.length() - 1);
            int i = Integer.parseInt(propertiesIndex);
            PropertyReference ref = this.properties.get(i);
            String index = ref.read(context, entity);

            return getIndexValue(entity, index);
        } catch (NumberFormatException e) {
        } catch (IndexOutOfBoundsException e) {
        }
    }

    // form a "getFoo()" based getter method name
    StringBuffer getter = new StringBuffer("get" + property);
    getter.setCharAt(3, getter.substring(3, 4).toUpperCase().charAt(0));

    try {
        // use this form, providing the getter name and no setter, so we can support properties that are read-only
        PropertyDescriptor pd = new PropertyDescriptor(property, entity.getClass(), getter.toString(), null);
        Method read = pd.getReadMethod();
        Object value = read.invoke(entity, (Object[]) null);
        return value;
    } catch (IntrospectionException ie) {
        M_log.warn("getValue: method: " + property + " object: " + entity.getClass(), ie);
        return null;
    } catch (IllegalAccessException ie) {
        M_log.warn("getValue: method: " + property + " object: " + entity.getClass(), ie);
        return null;
    } catch (IllegalArgumentException ie) {
        M_log.warn("getValue: method: " + property + " object: " + entity.getClass(), ie);
        return null;
    } catch (InvocationTargetException ie) {
        M_log.warn("getValue: method: " + property + " object: " + entity.getClass(), ie);
        return null;
    }
}

From source file:org.grails.datastore.mapping.model.config.GormMappingConfigurationStrategy.java

public List<PersistentProperty> getPersistentProperties(PersistentEntity entity, MappingContext context,
        ClassMapping classMapping) {//from   w  ww  .j a  v a 2s.c  o m
    final List<PersistentProperty> persistentProperties = new ArrayList<PersistentProperty>();
    ClassPropertyFetcher cpf = ClassPropertyFetcher.forClass(entity.getJavaClass());

    // owners are the classes that own this class
    Collection embedded = cpf.getStaticPropertyValue(EMBEDDED, Collection.class);
    if (embedded == null)
        embedded = Collections.emptyList();

    Collection transients = cpf.getStaticPropertyValue(TRANSIENT, Collection.class);
    if (transients == null)
        transients = Collections.emptyList();

    // hasMany associations for defining one-to-many and many-to-many
    Map hasManyMap = getAssociationMap(cpf);
    // mappedBy for defining by which property an association is mapped
    Map mappedByMap = cpf.getStaticPropertyValue(MAPPED_BY, Map.class);
    if (mappedByMap == null)
        mappedByMap = Collections.emptyMap();
    // hasOne for declaring a one-to-one association with the foreign key in the child
    Map hasOneMap = cpf.getStaticPropertyValue(HAS_ONE, Map.class);
    if (hasOneMap == null)
        hasOneMap = Collections.emptyMap();

    for (PropertyDescriptor descriptor : cpf.getPropertyDescriptors()) {
        if (descriptor.getPropertyType() == null || descriptor.getPropertyType() == Object.class) {
            // indexed property
            continue;
        }
        if (descriptor.getReadMethod() == null || descriptor.getWriteMethod() == null) {
            // non-persistent getter or setter
            continue;
        }
        if (descriptor.getName().equals(VERSION) && !entity.isVersioned()) {
            continue;
        }

        Field field = cpf.getDeclaredField(descriptor.getName());
        if (field != null && java.lang.reflect.Modifier.isTransient(field.getModifiers())) {
            continue;
        }
        final String propertyName = descriptor.getName();
        if (isExcludedProperty(propertyName, classMapping, transients))
            continue;
        Class<?> propertyType = descriptor.getPropertyType();
        Class currentPropType = propertyType;
        // establish if the property is a one-to-many
        // if it is a Set and there are relationships defined
        // and it is defined as persistent
        if (embedded.contains(propertyName)) {
            if (isCollectionType(currentPropType)) {
                Class relatedClassType = (Class) hasManyMap.get(propertyName);
                if (relatedClassType == null) {
                    Class javaClass = entity.getJavaClass();

                    Class genericClass = MappingUtils.getGenericTypeForProperty(javaClass, propertyName);

                    if (genericClass != null) {
                        relatedClassType = genericClass;
                    }
                }
                if (relatedClassType != null) {
                    if (propertyFactory.isSimpleType(relatedClassType)) {
                        Basic basicCollection = propertyFactory.createBasicCollection(entity, context,
                                descriptor);
                        persistentProperties.add(basicCollection);
                    } else {
                        EmbeddedCollection association = propertyFactory.createEmbeddedCollection(entity,
                                context, descriptor);

                        persistentProperties.add(association);
                        if (isPersistentEntity(relatedClassType)) {
                            association.setAssociatedEntity(
                                    getOrCreateAssociatedEntity(entity, context, relatedClassType));
                        } else {
                            PersistentEntity embeddedEntity = context.createEmbeddedEntity(relatedClassType);
                            embeddedEntity.initialize();
                            association.setAssociatedEntity(embeddedEntity);
                        }

                    }
                }
            } else {
                ToOne association = propertyFactory.createEmbedded(entity, context, descriptor);
                PersistentEntity associatedEntity = getOrCreateEmbeddedEntity(entity, context,
                        association.getType());
                association.setAssociatedEntity(associatedEntity);
                persistentProperties.add(association);
            }
        } else if (isCollectionType(currentPropType)) {
            final Association association = establishRelationshipForCollection(descriptor, entity, context,
                    hasManyMap, mappedByMap);
            if (association != null) {
                configureOwningSide(association);
                persistentProperties.add(association);
            }
        }
        // otherwise if the type is a domain class establish relationship
        else if (isPersistentEntity(currentPropType)) {
            final ToOne association = establishDomainClassRelationship(entity, descriptor, context, hasOneMap);
            if (association != null) {
                configureOwningSide(association);
                persistentProperties.add(association);
            }
        } else if (Enum.class.isAssignableFrom(currentPropType) || propertyFactory.isSimpleType(propertyType)) {
            persistentProperties.add(propertyFactory.createSimple(entity, context, descriptor));
        } else if (MappingFactory.isCustomType(propertyType)) {
            persistentProperties.add(propertyFactory.createCustom(entity, context, descriptor));
        }
    }
    return persistentProperties;
}

From source file:com.temenos.interaction.media.hal.HALProvider.java

/** populate a Map from a java bean
 *  TODO implement nested structures and collections
 *//*from  www.ja v a 2s .c  o  m*/
protected void buildFromBean(Map<String, Object> map, Object bean, String entityName) {
    EntityMetadata entityMetadata = metadata.getEntityMetadata(entityName);
    if (entityMetadata == null)
        throw new IllegalStateException("Entity metadata could not be found [" + entityName + "]");

    try {
        BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());
        for (PropertyDescriptor propertyDesc : beanInfo.getPropertyDescriptors()) {
            String propertyName = propertyDesc.getName();
            if (entityMetadata.getPropertyVocabulary(propertyName) != null) {
                Object value = propertyDesc.getReadMethod().invoke(bean);
                map.put(propertyName, value);
            }
        }
    } catch (IllegalArgumentException e) {
        logger.error("Error accessing bean property", e);
    } catch (IntrospectionException e) {
        logger.error("Error accessing bean property", e);
    } catch (IllegalAccessException e) {
        logger.error("Error accessing bean property", e);
    } catch (InvocationTargetException e) {
        logger.error("Error accessing bean property", e);
    }
}

From source file:com.artistech.protobuf.TuioProtoConverter.java

@Override
public Object convertFromProtobuf(final GeneratedMessage obj) {
    Object target;/*from  w w  w.  j a v a 2 s.c  o m*/

    if (TuioProtos.Blob.class.isAssignableFrom(obj.getClass())) {
        target = new TUIO.TuioBlob();
    } else if (TuioProtos.Time.class.isAssignableFrom(obj.getClass())) {
        target = new TUIO.TuioTime();
    } else if (TuioProtos.Cursor.class.isAssignableFrom(obj.getClass())) {
        target = new TUIO.TuioCursor();
    } else if (TuioProtos.Object.class.isAssignableFrom(obj.getClass())) {
        target = new TUIO.TuioObject();
    } else if (TuioProtos.Point.class.isAssignableFrom(obj.getClass())) {
        target = new TUIO.TuioPoint();
    } else {
        return null;
    }

    try {
        PropertyDescriptor[] targetProps = Introspector.getBeanInfo(target.getClass()).getPropertyDescriptors();

        BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
        PropertyDescriptor[] messageProps = beanInfo.getPropertyDescriptors();
        Method[] methods = obj.getClass().getMethods();

        for (PropertyDescriptor targetProp : targetProps) {
            for (PropertyDescriptor messageProp : messageProps) {
                if (targetProp.getName().equals(messageProp.getName())) {
                    Method writeMethod = targetProp.getWriteMethod();
                    Method readMethod = null;
                    for (Method m : methods) {
                        if (writeMethod != null
                                && m.getName().equals(writeMethod.getName().replaceFirst("set", "get"))) {
                            readMethod = m;
                            break;
                        }
                    }
                    try {
                        if (writeMethod != null && readMethod != null && targetProp.getReadMethod() != null) {
                            boolean primitiveOrWrapper = ClassUtils
                                    .isPrimitiveOrWrapper(targetProp.getReadMethod().getReturnType());

                            if (readMethod.getParameterTypes().length > 0) {
                                if (DeepCopy) {
                                    if (!Modifier.isAbstract(targetProp.getPropertyType().getModifiers())) {
                                        //basically, ArrayList
                                        Object newInstance = targetProp.getPropertyType().newInstance();
                                        Method addMethod = newInstance.getClass().getMethod("add",
                                                Object.class);
                                        Method m = obj.getClass().getMethod(readMethod.getName() + "Count");
                                        int size = (int) m.invoke(obj);
                                        for (int ii = 0; ii < size; ii++) {
                                            Object o = readMethod.invoke(obj, ii);
                                            addMethod.invoke(newInstance, o);
                                        }
                                        writeMethod.invoke(target, newInstance);
                                    } else if (Collection.class
                                            .isAssignableFrom(targetProp.getPropertyType())) {
                                        //do something if it is a collection or iterable...
                                    }
                                }
                            } else if (primitiveOrWrapper) {
                                writeMethod.invoke(target, messageProp.getReadMethod().invoke(obj));
                            } else {
                                if (GeneratedMessage.class
                                        .isAssignableFrom(messageProp.getReadMethod().getReturnType())) {

                                    GeneratedMessage invoke = (GeneratedMessage) messageProp.getReadMethod()
                                            .invoke(obj);
                                    Object val = null;
                                    for (ProtoConverter converter : services) {
                                        if (converter.supportsConversion(invoke)) {
                                            val = convertFromProtobuf(invoke);
                                            break;
                                        }
                                    }
                                    if (val != null) {
                                        writeMethod.invoke(target, val);
                                    }
                                }
                                //                                    System.out.println("Prop1 Name!: " + targetProp.getName());
                            }
                        }
                    } catch (NullPointerException ex) {
                        //Logger.getLogger(ZeroMqMouse.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (InstantiationException | NoSuchMethodException | IllegalArgumentException
                            | SecurityException | IllegalAccessException | InvocationTargetException ex) {
                        logger.error(ex);
                    }
                    break;
                }
            }
        }
    } catch (java.beans.IntrospectionException ex) {
        logger.fatal(ex);
    }
    return target;
}

From source file:io.lightlink.dao.mapping.BeanMapper.java

public BeanMapper(Class paramClass, List<String> fieldsOfLine) {

    PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(paramClass);
    descriptorMap = new CaseInsensitiveMap();
    for (PropertyDescriptor descriptor : descriptors) {
        descriptorMap.put(normalizePropertyName(descriptor.getName()), descriptor);
    }/*w ww.j a v  a  2s .  co  m*/

    List<String> ownFields = new ArrayList<String>();
    Map<String, List<String>> fieldsByChild = new CaseInsensitiveMap();

    groupFields(fieldsOfLine, ownFields, fieldsByChild);

    this.ownFields = ownFields;
    for (Map.Entry<String, List<String>> entry : fieldsByChild.entrySet()) {
        String childProperty = normalizePropertyName(entry.getKey());
        PropertyDescriptor descriptor = descriptorMap.get(childProperty);
        if (descriptor != null) {
            List<String> properties = entry.getValue();
            if (descriptor.getPropertyType().isAssignableFrom(ArrayList.class)) {
                Type[] typeArguments = ((ParameterizedType) descriptor.getReadMethod().getGenericReturnType())
                        .getActualTypeArguments();
                if (typeArguments.length == 0)
                    throw new RuntimeException("Cannot define Generic list type of " + entry.getKey()
                            + " property of " + paramClass);
                Type firstType = typeArguments[0];
                if (firstType instanceof Class) {
                    childListMappers.put(childProperty, new BeanMapper((Class) firstType, properties));
                }
            } else {
                childMappers.put(childProperty, new BeanMapper(descriptor.getPropertyType(), properties));
            }
        } else {
            throw new RuntimeException(
                    "cannot define mapping for class:" + paramClass.getName() + " property:" + childProperty);
        }
    }

    this.paramClass = paramClass;
}

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   ww  w.ja v a  2s.  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:org.force66.beantester.tests.ValuePropertyTest.java

@Override
public boolean testProperty(Object bean, PropertyDescriptor descriptor, Object value) {
    Validate.notNull(bean, "Null bean not allowed");
    Validate.notNull(descriptor, "Null PropertyDescriptor not allowed");

    boolean answer = true;
    if (descriptor.getPropertyType().isPrimitive() && value == null) {
        return answer; // Null test doesn't apply
    }/*from  w ww  .  j a  v  a 2s . c  om*/

    boolean fieldExists = FieldUtils.getField(bean.getClass(), descriptor.getName(), true) != null;

    try {
        if (descriptor.getWriteMethod() != null) {
            descriptor.getWriteMethod().invoke(bean, new Object[] { value });
            answer = testReadValue(bean, descriptor, value);
        } else if (fieldExists) {
            /*
             * Accessor exists, but no mutator.  Test the accessor by forcing the test value into the field
             * backing that accessor.
             */
            FieldUtils.writeField(bean, descriptor.getName(), value, true);
            answer = testReadValue(bean, descriptor, value);
        }
        if (descriptor.getReadMethod() != null) {
            /*
             * If an accessor exists, but has no corresponding mutator or field, all we can do
             * is execute it to make sure it doesn't except.
             */
            descriptor.getReadMethod().invoke(bean);
        }

    } catch (Exception e) {
        throw new BeanTesterException("Failed executing assignment test for accessor/mutator", e)
                .addContextValue("property", descriptor)
                .addContextValue("value class", value == null ? null : value.getClass().getName())
                .addContextValue("value", value);
    }
    return answer;
}

From source file:net.firejack.platform.core.store.AbstractStore.java

protected void findAlias(Class<?> clazz, String path, Map<String, String> aliases) {
    String[] fieldNames = path.split("\\.");
    if (fieldNames.length > 1) {
        for (int i = 0; i < fieldNames.length; i++) {
            String fieldName = fieldNames[i];
            PropertyDescriptor propertyDescriptor = ClassUtils.getPropertyDescriptor(clazz, fieldName);
            if (propertyDescriptor != null) {
                Method readMethod = propertyDescriptor.getReadMethod();
                if (readMethod != null) {
                    Class<?> returnType = readMethod.getReturnType();
                    if (Collection.class.isAssignableFrom(returnType)) {
                        returnType = (Class<?>) ((ParameterizedTypeImpl) readMethod.getGenericReturnType())
                                .getActualTypeArguments()[0];
                    }/*from w  w  w .  ja  v  a  2 s.co m*/
                    if (AbstractModel.class.isAssignableFrom(returnType)) {
                        clazz = returnType;
                        if (i == 0) {
                            aliases.put(fieldName, fieldName);
                        } else {
                            aliases.put(fieldNames[i - 1] + "." + fieldName, fieldName);
                        }
                    }
                } else {
                    throw new BusinessFunctionException(
                            "The field '" + fieldName + "' has not read method in class '" + clazz + "'");
                }
            } else {
                throw new BusinessFunctionException(
                        "The field '" + fieldName + "' does not exist in class '" + clazz + "'");
            }
        }
    }
}

From source file:org.dataconservancy.packaging.tool.impl.AnnotationDrivenPackageStateSerializer.java

/**
 * Serializes the identified stream from the package state to the supplied result.
 *
 * @param state    the package state object containing the identified stream
 * @param streamId the stream identifier for the content being serialized
 * @param result   holds the output stream for the serialization result
 *///w  w  w .  j  a  v a 2 s.  c  o  m
void serializeToResult(PackageState state, StreamId streamId, StreamResult result) {

    if (marshallerMap == null) {
        throw new IllegalStateException(ERR_MISSING_MARSHALLINGMAP);
    }

    PropertyDescriptor pd = propertyDescriptors.get(streamId);

    if (pd == null) {
        throw new IllegalArgumentException(String.format(ERR_INVALID_STREAMID, streamId.name(),
                PackageState.class.getName(),
                propertyDescriptors.keySet().stream().map(Enum::name).collect(Collectors.joining(", "))));
    }

    Object toSerialize;

    try {
        toSerialize = pd.getReadMethod().invoke(state);
        if (toSerialize == null) {
            // The field on the package state had a null value, which is OK.  We have nothing to serialize.
            return;
        }
    } catch (Exception e) {
        String err = String.format(ERR_INVOKING_METHOD, pd.getReadMethod(), state.getClass().getName(),
                e.getMessage());
        throw new RuntimeException(err, e);
    }

    try {
        StreamMarshaller streamMarshaller = marshallerMap.get(streamId);
        if (streamMarshaller == null) {
            throw new RuntimeException(String.format(ERR_MISSING_STREAMMARSHALLER, streamId));
        }

        Marshaller marshaller = streamMarshaller.getMarshaller();
        if (marshaller == null) {
            throw new RuntimeException(String.format(ERR_MISSING_SPRINGMARSHALLER, streamId, streamId));
        }

        marshaller.marshal(toSerialize, result);
    } catch (Exception e) {
        throw new RuntimeException(String.format(ERR_MARSHALLING_STREAM, streamId, e.getMessage()), e);
    }
}