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.expedia.tesla.compiler.plugins.JavaTypeMapper.java

/**
 * Generate Tesla schema from Java class by reflection.
 * <p>//  w  w w  . j  a va 2 s  .  c  o  m
 * Tesla can generate schema from existing Java classes that follow the
 * JavaBeans Spec. Only properties with following attributes will be
 * included:
 * <li>public accessible.</li>
 * <li>writable (has both getter and setter).</li>
 * <li>has no {@code SkipField} annotation.</li>
 * <p>
 * Tesla will map Java type to it's closest Tesla type by default.
 * Developers can override this by either providing their own
 * {@code TypeMapper}, or with Tesla annoations.
 * <p>
 * Tesla will map all Java object types to nullable types only for class
 * properties. If you want an property to be not nullable, use annotation
 * {@code NotNullable}.
 * 
 * @param schemaBuilder
 *            All non-primitive Tesla types must be defined inside a schema.
 *            This is the schema object into which the Tesla type will be
 *            generated.
 * 
 * @param javaType
 *            The java class object.
 * 
 * @return The Tesla type created from the java class by reflection.
 * 
 * @throws TeslaSchemaException
 */
public Type fromJavaClass(Schema.SchemaBuilder schemaBuilder, java.lang.Class<?> javaType)
        throws TeslaSchemaException {
    String className = javaType.getCanonicalName();
    if (className == null) {
        throw new TeslaSchemaException(
                String.format("Tesla cannot generate schema for local class '%s'.", javaType.getName()));
    }
    String classTypeId = Class.nameToId(className);
    Class clss = (Class) schemaBuilder.findType(classTypeId);
    if (clss != null) {
        return clss;
    }

    clss = (Class) schemaBuilder.addType(classTypeId);

    Class superClass = null;
    java.lang.Class<?> base = javaType.getSuperclass();
    if (base != null && base != java.lang.Object.class) {
        superClass = (Class) fromJavaClass(schemaBuilder, javaType.getSuperclass());
    }

    List<Field> fields = new ArrayList<>();
    for (PropertyDescriptor propDesc : PropertyUtils.getPropertyDescriptors(javaType)) {
        Type fieldType = null;
        String fieldName = propDesc.getName();
        Method readMethod = propDesc.getReadMethod();
        Method writeMethod = propDesc.getWriteMethod();

        // Ignore the property it missing getter or setter method.
        if (writeMethod == null || readMethod == null) {
            continue;
        }
        if ((superClass != null && superClass.hasField(fieldName)) || clss.hasField(fieldName)) {
            continue;
        }
        // Ignore the property if it is annotated with "SkipField".
        if (readMethod.getAnnotation(com.expedia.tesla.schema.annotation.SkipField.class) != null) {
            continue;
        }
        com.expedia.tesla.schema.annotation.TypeId tidAnnotation = readMethod
                .getAnnotation(com.expedia.tesla.schema.annotation.TypeId.class);

        String typeId = null;
        if (tidAnnotation != null) {
            typeId = tidAnnotation.value();
        }
        java.lang.reflect.Type propType = readMethod.getGenericReturnType();
        fieldType = fromJava(schemaBuilder, propType);
        if (typeId != null) {
            fieldType = schemaBuilder.addType(typeId);
        } else {
            if (!(propType instanceof java.lang.Class<?> && ((java.lang.Class<?>) propType).isPrimitive())) {
                fieldType = schemaBuilder.addType(String.format("nullable<%s>", fieldType.getTypeId()));
            }
            com.expedia.tesla.schema.annotation.NotNullable anntNotNullable = readMethod
                    .getAnnotation(com.expedia.tesla.schema.annotation.NotNullable.class);
            com.expedia.tesla.schema.annotation.Nullable anntNullable = readMethod
                    .getAnnotation(com.expedia.tesla.schema.annotation.Nullable.class);
            if (anntNotNullable != null && anntNullable != null) {
                throw new TeslaSchemaException(String.format(
                        "Property '%' of class '%s' has conflict annotations." + "'NotNullable' and 'Nullable'",
                        fieldName));
            }
            if (fieldType.isNullable() && anntNotNullable != null) {
                fieldType = ((Nullable) fieldType).getElementType();
            }
            if (!fieldType.isReference()
                    && readMethod.getAnnotation(com.expedia.tesla.schema.annotation.Reference.class) != null) {
                fieldType = schemaBuilder.addType(String.format("reference<%s>", fieldType.getTypeId()));
            }
        }

        com.expedia.tesla.schema.annotation.FieldName fnAnnotation = readMethod
                .getAnnotation(com.expedia.tesla.schema.annotation.FieldName.class);
        if (fnAnnotation != null) {
            fieldName = fnAnnotation.value();
        }

        String fieldDisplayName = propDesc.getDisplayName();
        String getter = readMethod.getName();
        String setter = propDesc.getWriteMethod().getName();
        com.expedia.tesla.schema.annotation.DisplayName dnAnnotation = readMethod
                .getAnnotation(com.expedia.tesla.schema.annotation.DisplayName.class);
        if (dnAnnotation != null) {
            fieldDisplayName = dnAnnotation.value();
        }
        java.util.Map<String, String> attributes = new java.util.HashMap<String, String>();
        attributes.put("getter", getter);
        attributes.put("setter", setter);

        fields.add(new Field(fieldName, fieldDisplayName, fieldType, attributes, null));
    }

    clss.define(superClass == null ? null : Arrays.asList(new Class[] { superClass }), fields, null);
    return clss;
}

From source file:com.github.erchu.beancp.commons.NameBasedMapConvention.java

@Override
public List<Binding> getBindings(final MappingInfo mappingsInfo, final Class sourceClass,
        final Class destinationClass) {
    List<Binding> result = new LinkedList<>();
    BeanInfo sourceBeanInfo, destinationBeanInfo;

    try {/*from w w  w  .j  av  a  2  s . c om*/
        destinationBeanInfo = Introspector.getBeanInfo(destinationClass);
    } catch (IntrospectionException ex) {
        throw new MappingException(String.format("Failed to get bean info for %s", destinationClass), ex);
    }

    try {
        sourceBeanInfo = Introspector.getBeanInfo(sourceClass);
    } catch (IntrospectionException ex) {
        throw new MappingException(String.format("Failed to get bean info for %s", sourceClass), ex);
    }

    boolean allDestinationMembersMapped = true;

    for (PropertyDescriptor destinationProperty : destinationBeanInfo.getPropertyDescriptors()) {
        Method destinationMember = destinationProperty.getWriteMethod();

        if (destinationMember != null) {
            BindingSide destinationBindingSide = new PropertyBindingSide(destinationProperty);

            if (isDestinationMemberExpectedToBind(destinationBindingSide) == false) {
                continue;
            }

            List<BindingSide> sourceBindingSide = getMatchingSourceMemberByName(sourceBeanInfo, sourceClass,
                    destinationProperty.getName(), MemberAccessType.PROPERTY);

            if (sourceBindingSide != null) {
                BindingSide[] sourceBindingSideArray = sourceBindingSide.stream().toArray(BindingSide[]::new);

                Binding binding = getBindingIfAvailable(sourceClass, destinationClass, mappingsInfo,
                        sourceBindingSideArray, destinationBindingSide);

                if (binding != null) {
                    result.add(binding);
                }
            } else {
                allDestinationMembersMapped = false;
            }
        }
    }

    for (Field destinationMember : destinationClass.getFields()) {
        BindingSide destinationBindingSide = new FieldBindingSide(destinationMember);

        if (isDestinationMemberExpectedToBind(destinationBindingSide) == false) {
            continue;
        }

        List<BindingSide> sourceBindingSide = getMatchingSourceMemberByName(sourceBeanInfo, sourceClass,
                destinationMember.getName(), MemberAccessType.FIELD);

        if (sourceBindingSide != null) {

            BindingSide[] sourceBindingSideArray = sourceBindingSide.stream().toArray(BindingSide[]::new);

            Binding binding = getBindingIfAvailable(sourceClass, destinationClass, mappingsInfo,
                    sourceBindingSideArray, destinationBindingSide);

            if (binding != null) {
                result.add(binding);
            }
        } else {
            allDestinationMembersMapped = false;
        }
    }

    if (_failIfNotAllDestinationMembersMapped) {
        if (allDestinationMembersMapped == false) {
            throw new MapperConfigurationException(
                    "Not all destination members are mapped." + " This exception has been trown because "
                            + "failIfNotAllDestinationMembersMapped option is enabled.");
        }
    }

    if (_failIfNotAllSourceMembersMapped) {
        boolean allSourceMembersMapped = true;

        for (PropertyDescriptor sourceProperty : sourceBeanInfo.getPropertyDescriptors()) {
            Method sourceMember = sourceProperty.getReadMethod();

            if (sourceMember != null) {
                if (sourceMember.getDeclaringClass().equals(Object.class)) {
                    continue;
                }

                BindingSide sourceBindingSide = new PropertyBindingSide(sourceProperty);

                if (isSourceMemberMapped(result, sourceBindingSide) == false) {
                    allSourceMembersMapped = false;
                    break;
                }
            }
        }

        // if all properties are mapped we still need to check fields
        if (allSourceMembersMapped) {
            for (Field sourceMember : sourceClass.getFields()) {
                if (sourceMember.getDeclaringClass().equals(Object.class)) {
                    continue;
                }

                BindingSide sourceBindingSide = new FieldBindingSide(sourceMember);

                if (isSourceMemberMapped(result, sourceBindingSide) == false) {
                    allSourceMembersMapped = false;
                    break;
                }
            }
        }

        if (allSourceMembersMapped == false) {
            throw new MapperConfigurationException(
                    "Not all source members are mapped." + " This exception has been trown because "
                            + "failIfNotAllSourceMembersMapped option is enabled.");
        }
    }

    return result;
}

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

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

From source file:com.qcadoo.model.internal.classconverter.ModelXmlToClassConverterTest.java

private void verifyField(final PropertyDescriptor propertyDescriptor, final Class<?> type,
        final boolean readable, final boolean writable) {
    assertEquals(type, propertyDescriptor.getPropertyType());
    if (writable) {
        assertNotNull(propertyDescriptor.getWriteMethod());
    } else {/*from  w w w.j a  v  a2 s. c  o  m*/
        assertNull(propertyDescriptor.getWriteMethod());
    }
    if (readable) {
        assertNotNull(propertyDescriptor.getReadMethod());
    } else {
        assertNull(propertyDescriptor.getReadMethod());
    }
}

From source file:dhbw.ka.mwi.businesshorizon2.ui.process.period.input.AbstractInputPresenter.java

/**
 * Sorgt dafuer, dass aenderungen in das Periodenobjekt geschrieben werden.
 * ueberprueft die Benutzereingabe auf ihre Konvertierbarkeit in eine
 * Doublevariable und gibt im Fehlerfall eine Fehlermeldung an den User
 * zurueck.//  w  w  w. j ava2 s . co m
 * 
 * @param newContent
 *            Inhalt des Textfeldes das in das Periodenobjekt geschrieben
 *            werden soll
 * @param textFieldColumn
 *            Spalte des GridLayouts wo das Textfeld liegt
 * @param textFieldRow
 *            Reihe des GridLayouts wo das Textfeld liegt
 * @param destination
 *            Name der Property in welche newContent geschrieben werden soll
 */

public void validateChange(String newContent, int textFieldColumn, int textFieldRow, String destination) {
    destination = shownProperties[Arrays.asList(germanNamesProperties).indexOf(destination)];
    logger.debug("" + newContent);
    try {
        df.parse(newContent).doubleValue();
        df.parse(newContent).doubleValue();
    } catch (Exception e) {
        getView().setWrong(textFieldColumn, textFieldRow, true);
        return;
    }
    getView().setWrong(textFieldColumn, textFieldRow, false);

    for (PropertyDescriptor pd : BeanUtils.getPropertyDescriptors(period.getClass())) {
        if (Arrays.asList(shownProperties).contains(destination)) {
            if (pd.getDisplayName().equals(destination)) {
                try {
                    pd.getWriteMethod();
                    period.toString();

                    pd.getWriteMethod().invoke(period, new Object[] { df.parse(newContent).doubleValue() });
                    logger.debug("Content should be written: " + (double) pd.getReadMethod().invoke(period));
                } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException
                        | ParseException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

From source file:it.cnr.icar.eric.server.security.authorization.RegistryAttributeFinderModule.java

/**
 * Handles attributes as defined ebRIM for Any RegistryObject.
 * Used by subject, resource and action attributes handling methods.
 *//*  w  w w .  java 2  s  . c  om*/
EvaluationResult handleRegistryObjectAttribute(Object obj, Stack<?> attributeStack, URI type,
        EvaluationCtx context) {
    EvaluationResult evaluationResult = null;
    try {
        String attr = (String) attributeStack.pop();
        ServerRequestContext requestContext = AuthorizationServiceImpl.getRequestContext(context);
        log.trace("handleRegistryObjectAttribute: obj=" + obj.toString() + " attrubute = " + attr);

        if (requestContext != null && obj != null) {
            @SuppressWarnings("unused")
            RegistryRequestType registryRequest = requestContext.getCurrentRegistryRequest();

            //Now invoke a get method to get the value for attribute being sought
            Class<? extends Object> clazz = obj.getClass();
            @SuppressWarnings("unused")
            String clazzName = clazz.getName();
            PropertyDescriptor propDesc = new PropertyDescriptor(attr, clazz, getReadMethodName(attr), null);
            Method method = propDesc.getReadMethod();
            Object attrValObj = method.invoke(obj, (java.lang.Object[]) null);

            if (attrValObj instanceof Collection) {
                HashSet<AttributeValue> attrValueObjectIds = new HashSet<AttributeValue>();
                Iterator<?> iter = ((Collection<?>) attrValObj).iterator();
                while (iter.hasNext()) {
                    //??Dangerous assumption that Collection is a Collection of IdentifiableTypes
                    String attrValueObjectId = ((IdentifiableType) iter.next()).getId();
                    attrValueObjectIds.add(makeAttribute(attrValueObjectId, type));
                }
                evaluationResult = makeBag(attrValueObjectIds, type);
            } else {
                //See if more pointer chasing needs to be done or (!attributeStack.empty()) 
                if (!attributeStack.empty()) {
                    String id = (String) attrValObj;
                    RegistryObjectType ro = AuthorizationServiceImpl.getInstance()
                            .getRegistryObject(requestContext, id, false);
                    if (ro == null) {
                        throw new ObjectNotFoundException(id, "RegistryObject");
                    }
                    evaluationResult = handleRegistryObjectAttribute(ro, attributeStack, type, context);
                } else {
                    AttributeValue attrVal = makeAttribute(attrValObj, type);
                    evaluationResult = makeBag(attrVal, type);
                }
            }
        }
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (IntrospectionException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    } catch (ParsingException e) {
        e.printStackTrace();
    } catch (URISyntaxException e) {
        e.printStackTrace();
    } catch (RegistryException e) {
        e.printStackTrace();
    }

    return evaluationResult;
}

From source file:com.bstek.dorado.data.type.EntityDataTypeSupport.java

protected void doCreatePropertyDefinitons() throws Exception {
    Class<?> type = getMatchType();
    if (type == null) {
        type = getCreationType();/*from w  w  w  .  ja  va  2  s .  c o m*/
    }
    if (type == null || type.isPrimitive() || type.isArray() || Map.class.isAssignableFrom(type)) {
        return;
    }

    PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(type);
    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        String name = propertyDescriptor.getName();
        if (!BeanPropertyUtils.isValidProperty(type, name))
            continue;

        PropertyDef propertyDef = getPropertyDef(name);
        DataType dataType = null;
        Class<?> propertyType = propertyDescriptor.getPropertyType();
        if (Collection.class.isAssignableFrom(propertyType)) {
            ParameterizedType parameterizedType = (ParameterizedType) propertyDescriptor.getReadMethod()
                    .getGenericReturnType();
            if (parameterizedType != null) {
                dataType = DataUtils.getDataType(parameterizedType);
            }
        }

        if (dataType == null) {
            dataType = DataUtils.getDataType(propertyType);
        }

        if (propertyDef == null) {
            if (dataType != null) {
                propertyDef = new BasePropertyDef(name);
                propertyDef.setDataType(dataType);
                addPropertyDef(propertyDef);

                if (dataType instanceof EntityDataType || dataType instanceof AggregationDataType) {
                    propertyDef.setIgnored(true);
                }
            }
        } else if (propertyDef.getDataType() == null) {
            if (dataType != null)
                propertyDef.setDataType(dataType);
        }
    }
}

From source file:com.webpagebytes.cms.local.WPBLocalDataStoreDao.java

private int buildStatementForInsertUpdate(Object obj, Set<String> ignoreFields,
        PreparedStatement preparedStatement, Connection connection)
        throws SQLException, WPBSerializerException {
    Class<? extends Object> kind = obj.getClass();
    Field[] fields = kind.getDeclaredFields();
    int fieldIndex = 0;
    for (int i = 0; i < fields.length; i++) {
        Field field = fields[i];/*  w w w .  ja v  a2  s  .  c o  m*/
        field.setAccessible(true);
        boolean storeField = (field.getAnnotation(WPBAdminFieldKey.class) != null)
                || (field.getAnnotation(WPBAdminFieldStore.class) != null)
                || (field.getAnnotation(WPBAdminFieldTextStore.class) != null);
        if (storeField) {
            String fieldName = field.getName();
            if (ignoreFields != null && ignoreFields.contains(fieldName)) {
                continue;
            }
            fieldIndex = fieldIndex + 1;
            Object value = null;
            try {
                PropertyDescriptor pd = new PropertyDescriptor(fieldName, kind);
                value = pd.getReadMethod().invoke(obj);
            } catch (Exception e) {
                throw new WPBSerializerException("Cannot get property value", e);
            }
            if (field.getType() == Long.class) {
                Long valueLong = (Long) value;
                if (valueLong != null) {
                    preparedStatement.setLong(fieldIndex, valueLong);
                } else {
                    preparedStatement.setNull(fieldIndex, Types.BIGINT);
                }
            } else if (field.getType() == String.class) {

                String valueString = (String) value;
                if (field.getAnnotation(WPBAdminFieldStore.class) != null
                        || field.getAnnotation(WPBAdminFieldKey.class) != null) {
                    if (valueString != null) {
                        preparedStatement.setString(fieldIndex, valueString);
                    } else {
                        preparedStatement.setNull(fieldIndex, Types.VARCHAR);
                    }
                } else if (field.getAnnotation(WPBAdminFieldTextStore.class) != null) {
                    if (valueString != null) {
                        Clob clob = connection.createClob();
                        clob.setString(1, valueString);
                        preparedStatement.setClob(fieldIndex, clob);
                    } else {
                        preparedStatement.setNull(fieldIndex, Types.CLOB);
                    }
                }
            } else if (field.getType() == Integer.class) {
                Integer valueInt = (Integer) value;
                if (valueInt != null) {
                    preparedStatement.setInt(fieldIndex, valueInt);
                } else {
                    preparedStatement.setNull(fieldIndex, Types.INTEGER);
                }
            } else if (field.getType() == Date.class) {
                Date date = (Date) value;
                if (date != null) {
                    java.sql.Timestamp sqlDate = new java.sql.Timestamp(date.getTime());
                    preparedStatement.setTimestamp(fieldIndex, sqlDate);
                } else {
                    preparedStatement.setNull(fieldIndex, Types.DATE);
                }
            }
        }
    }
    return fieldIndex;
}

From source file:QueryRunner.java

/**
 * Fill the <code>PreparedStatement</code> replacement parameters with the
 * given object's bean property values./*from w  ww  .jav  a2 s.c o m*/
 * 
 * @param stmt
 *            PreparedStatement to fill
 * @param bean
 *            a JavaBean object
 * @param properties
 *            an ordered array of properties; this gives the order to insert
 *            values in the statement
 * @throws SQLException
 *             if a database access error occurs
 */
public void fillStatementWithBean(PreparedStatement stmt, Object bean, PropertyDescriptor[] properties)
        throws SQLException {
    Object[] params = new Object[properties.length];
    for (int i = 0; i < properties.length; i++) {
        PropertyDescriptor property = properties[i];
        Object value = null;
        Method method = property.getReadMethod();
        if (method == null) {
            throw new RuntimeException(
                    "No read method for bean property " + bean.getClass() + " " + property.getName());
        }
        try {
            value = method.invoke(bean, new Object[0]);
        } catch (InvocationTargetException e) {
            throw new RuntimeException("Couldn't invoke method: " + method, e);
        } catch (IllegalArgumentException e) {
            throw new RuntimeException("Couldn't invoke method with 0 arguments: " + method, e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException("Couldn't invoke method: " + method, e);
        }
        params[i] = value;
    }
    fillStatement(stmt, params);
}

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

private boolean populateListObjects(Object bean, Map<String, Object> map) {
    boolean lineAdded = false;

    for (Map.Entry<String, BeanMapper> entry : childListMappers.entrySet()) {
        String originalKey = entry.getKey();
        String key = normalizePropertyName(entry.getKey());
        PropertyDescriptor propertyDescriptor = descriptorMap.get(key);
        if (propertyDescriptor == null) {

            LOG.info("Cannot find property for " + entry.getKey() + " in class "
                    + paramClass.getCanonicalName());

        } else {/*w  w w .j a  va2s .co  m*/

            Map<String, Object> childData = prepareChildData(originalKey, map);
            try {
                Object childObject = entry.getValue().convertObject(childData, true);

                List list = (List) propertyDescriptor.getReadMethod().invoke(bean);

                if (list == null)
                    propertyDescriptor.getWriteMethod().invoke(bean, list = new ArrayList());

                if (childObject != null)
                    list.add(childObject);

                lineAdded = true;

            } catch (Exception e) {
                LOG.error(e.getMessage(), e);
            }
        }

    }
    return lineAdded;
}