Example usage for java.beans BeanInfo getPropertyDescriptors

List of usage examples for java.beans BeanInfo getPropertyDescriptors

Introduction

In this page you can find the example usage for java.beans BeanInfo getPropertyDescriptors.

Prototype

PropertyDescriptor[] getPropertyDescriptors();

Source Link

Document

Returns descriptors for all properties of the bean.

Usage

From source file:org.parancoe.validator.constraints.impl.NewPasswordValidator.java

@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
    String newPasswordValue = null;
    String confirmPasswordValue = null;
    boolean newPasswordFound = false;
    boolean confirmPasswordFound = false;
    try {//w  w  w  .j a  v a  2s  .c  o  m
        BeanInfo beanInfo = Introspector.getBeanInfo(value.getClass());
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
            if (constraintAnnotation.newPasswordProperty().equals(propertyDescriptor.getName())) {
                newPasswordValue = (String) propertyDescriptor.getReadMethod().invoke(value);
                newPasswordFound = true;
            }
            if (constraintAnnotation.confirmPasswordProperty().equals(propertyDescriptor.getName())) {
                confirmPasswordValue = (String) propertyDescriptor.getReadMethod().invoke(value);
                confirmPasswordFound = true;
            }
            if (newPasswordFound && confirmPasswordFound) {
                break;
            }
        }
    } catch (Exception ex) {
        throw new RuntimeException("Can't validate this bean.", ex);
    }
    if (!newPasswordFound) {
        throw new RuntimeException("Can't validate this bean: property "
                + constraintAnnotation.newPasswordProperty() + " not found.");
    }
    if (!confirmPasswordFound) {
        throw new RuntimeException("Can't validate this bean: property "
                + constraintAnnotation.confirmPasswordProperty() + " not found.");
    }
    if (constraintAnnotation.passIfBlank()) {
        if (value == null
                || (StringUtils.isBlank(newPasswordValue) && StringUtils.isBlank(confirmPasswordValue))) {
            return true;
        }
    }
    boolean result = true;
    if (StringUtils.isNotBlank(newPasswordValue) && !newPasswordValue.equals(confirmPasswordValue)) {
        context.disableDefaultConstraintViolation();
        context.buildConstraintViolationWithTemplate("{org.parancoe.validator.constraints.NewPassword.message}")
                .addNode("newPassword").addConstraintViolation().disableDefaultConstraintViolation();
        result = false;
    }
    return result;
}

From source file:org.parancoe.validator.constraints.impl.NewPasswordLengthValidator.java

@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
    String newPasswordValue = null;
    String confirmPasswordValue = null;
    boolean newPasswordFound = false;
    boolean confirmPasswordFound = false;
    try {// w w w.  j a v  a 2s .  c  o m
        BeanInfo beanInfo = Introspector.getBeanInfo(value.getClass());
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
            if (constraintAnnotation.newPasswordProperty().equals(propertyDescriptor.getName())) {
                newPasswordValue = (String) propertyDescriptor.getReadMethod().invoke(value);
                newPasswordFound = true;
            }
            if (constraintAnnotation.confirmPasswordProperty().equals(propertyDescriptor.getName())) {
                confirmPasswordValue = (String) propertyDescriptor.getReadMethod().invoke(value);
                confirmPasswordFound = true;
            }
            if (newPasswordFound && confirmPasswordFound) {
                break;
            }
        }
    } catch (Exception ex) {
        throw new RuntimeException("Can't validate this bean.", ex);
    }
    if (!newPasswordFound) {
        throw new RuntimeException("Can't validate this bean: property "
                + constraintAnnotation.newPasswordProperty() + " not found.");
    }
    if (!confirmPasswordFound) {
        throw new RuntimeException("Can't validate this bean: property "
                + constraintAnnotation.confirmPasswordProperty() + " not found.");
    }
    if (constraintAnnotation.passIfBlank()) {
        if (value == null
                || (StringUtils.isBlank(newPasswordValue) && StringUtils.isBlank(confirmPasswordValue))) {
            return true;
        }
    }
    boolean result = true;
    if (StringUtils.isNotBlank(newPasswordValue) && (newPasswordValue.length() < constraintAnnotation.min()
            || newPasswordValue.length() > constraintAnnotation.max())) {
        context.disableDefaultConstraintViolation();
        context.buildConstraintViolationWithTemplate(
                "{org.parancoe.validator.constraints.NewPasswordLength.message}").addNode("newPassword")
                .addConstraintViolation().disableDefaultConstraintViolation();
        result = false;
    }
    return result;
}

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

private PropertyDescriptor[] loadDescriptors(Class<T> cls) throws IntrospectionException {
    BeanInfo beanInfo = Introspector.getBeanInfo(cls);
    return beanInfo.getPropertyDescriptors();
}

From source file:com.orange.mmp.api.ws.jsonrpc.SimpleBeanSerializer.java

@Override
public Object marshall(SerializerState state, Object p, Object o) throws MarshallException {
    JSONObject jsonObj = new JSONObject();
    try {/*w  w  w  . j  a v a  2s .  c om*/
        BeanInfo beanInfo = Introspector.getBeanInfo(o.getClass(), Object.class);
        for (PropertyDescriptor propertyDescriptor : beanInfo.getPropertyDescriptors()) {
            Method readMethod = propertyDescriptor.getReadMethod();
            if (readMethod != null) {
                Object propValue = readMethod.invoke(o);
                Object json = ser.marshall(state, o, propValue, propertyDescriptor.getName());
                jsonObj.put(propertyDescriptor.getName(), json);
            }
        }
    } catch (JSONException jse) {
        throw new MarshallException("Failed to marshall Bean");
    } catch (IllegalAccessException iae) {
        throw new MarshallException("Failed to analyse Bean");
    } catch (InvocationTargetException ite) {
        throw new MarshallException("Failed to analyse Bean");
    } catch (IntrospectionException ie) {
        throw new MarshallException("Failed to analyse Bean");
    }
    return jsonObj;
}

From source file:ch.rasc.extclassgenerator.ModelGenerator.java

public static ModelBean createModel(final Class<?> clazz, final OutputConfig outputConfig) {

    Assert.notNull(clazz, "clazz must not be null");
    Assert.notNull(outputConfig.getIncludeValidation(), "includeValidation must not be null");

    ModelCacheKey key = new ModelCacheKey(clazz.getName(), outputConfig);
    SoftReference<ModelBean> modelReference = modelCache.get(key);
    if (modelReference != null && modelReference.get() != null) {
        return modelReference.get();
    }/*from  w  w w. j  av  a2s .  co  m*/

    Model modelAnnotation = clazz.getAnnotation(Model.class);

    final ModelBean model = new ModelBean();

    if (modelAnnotation != null && StringUtils.hasText(modelAnnotation.value())) {
        model.setName(modelAnnotation.value());
    } else {
        model.setName(clazz.getName());
    }

    if (modelAnnotation != null) {
        model.setAutodetectTypes(modelAnnotation.autodetectTypes());
    }

    if (modelAnnotation != null) {
        model.setExtend(modelAnnotation.extend());
        model.setIdProperty(modelAnnotation.idProperty());
        model.setVersionProperty(trimToNull(modelAnnotation.versionProperty()));
        model.setPaging(modelAnnotation.paging());
        model.setDisablePagingParameters(modelAnnotation.disablePagingParameters());
        model.setCreateMethod(trimToNull(modelAnnotation.createMethod()));
        model.setReadMethod(trimToNull(modelAnnotation.readMethod()));
        model.setUpdateMethod(trimToNull(modelAnnotation.updateMethod()));
        model.setDestroyMethod(trimToNull(modelAnnotation.destroyMethod()));
        model.setMessageProperty(trimToNull(modelAnnotation.messageProperty()));
        model.setWriter(trimToNull(modelAnnotation.writer()));
        model.setReader(trimToNull(modelAnnotation.reader()));
        model.setSuccessProperty(trimToNull(modelAnnotation.successProperty()));
        model.setTotalProperty(trimToNull(modelAnnotation.totalProperty()));
        model.setRootProperty(trimToNull(modelAnnotation.rootProperty()));
        model.setWriteAllFields(modelAnnotation.writeAllFields());
        model.setIdentifier(trimToNull(modelAnnotation.identifier()));
        String clientIdProperty = trimToNull(modelAnnotation.clientIdProperty());
        if (StringUtils.hasText(clientIdProperty)) {
            model.setClientIdProperty(clientIdProperty);
            model.setClientIdPropertyAddToWriter(true);
        } else {
            model.setClientIdProperty(null);
            model.setClientIdPropertyAddToWriter(false);
        }
    }

    final Set<String> hasReadMethod = new HashSet<String>();

    BeanInfo bi;
    try {
        bi = Introspector.getBeanInfo(clazz);
    } catch (IntrospectionException e) {
        throw new RuntimeException(e);
    }

    for (PropertyDescriptor pd : bi.getPropertyDescriptors()) {
        if (pd.getReadMethod() != null && pd.getReadMethod().getAnnotation(JsonIgnore.class) == null) {
            hasReadMethod.add(pd.getName());
        }
    }

    if (clazz.isInterface()) {
        final List<Method> methods = new ArrayList<Method>();

        ReflectionUtils.doWithMethods(clazz, new MethodCallback() {
            @Override
            public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
                methods.add(method);
            }
        });

        Collections.sort(methods, new Comparator<Method>() {
            @Override
            public int compare(Method o1, Method o2) {
                return o1.getName().compareTo(o2.getName());
            }
        });

        for (Method method : methods) {
            createModelBean(model, method, outputConfig);
        }
    } else {

        final Set<String> fields = new HashSet<String>();

        Set<ModelField> modelFieldsOnType = AnnotationUtils.getRepeatableAnnotation(clazz, ModelFields.class,
                ModelField.class);
        for (ModelField modelField : modelFieldsOnType) {
            if (StringUtils.hasText(modelField.value())) {
                ModelFieldBean modelFieldBean;

                if (StringUtils.hasText(modelField.customType())) {
                    modelFieldBean = new ModelFieldBean(modelField.value(), modelField.customType());
                } else {
                    modelFieldBean = new ModelFieldBean(modelField.value(), modelField.type());
                }

                updateModelFieldBean(modelFieldBean, modelField);
                model.addField(modelFieldBean);
            }
        }

        Set<ModelAssociation> modelAssociationsOnType = AnnotationUtils.getRepeatableAnnotation(clazz,
                ModelAssociations.class, ModelAssociation.class);
        for (ModelAssociation modelAssociationAnnotation : modelAssociationsOnType) {
            AbstractAssociation modelAssociation = AbstractAssociation
                    .createAssociation(modelAssociationAnnotation);
            if (modelAssociation != null) {
                model.addAssociation(modelAssociation);
            }
        }

        Set<ModelValidation> modelValidationsOnType = AnnotationUtils.getRepeatableAnnotation(clazz,
                ModelValidations.class, ModelValidation.class);
        for (ModelValidation modelValidationAnnotation : modelValidationsOnType) {
            AbstractValidation modelValidation = AbstractValidation.createValidation(
                    modelValidationAnnotation.propertyName(), modelValidationAnnotation,
                    outputConfig.getIncludeValidation());
            if (modelValidation != null) {
                model.addValidation(modelValidation);
            }
        }

        ReflectionUtils.doWithFields(clazz, new FieldCallback() {

            @Override
            public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
                if (!fields.contains(field.getName()) && (field.getAnnotation(ModelField.class) != null
                        || field.getAnnotation(ModelAssociation.class) != null
                        || (Modifier.isPublic(field.getModifiers()) || hasReadMethod.contains(field.getName()))
                                && field.getAnnotation(JsonIgnore.class) == null)) {

                    // ignore superclass declarations of fields already
                    // found in a subclass
                    fields.add(field.getName());
                    createModelBean(model, field, outputConfig);

                }
            }

        });
    }

    modelCache.put(key, new SoftReference<ModelBean>(model));
    return model;
}

From source file:com.ebay.pulsar.analytics.dao.mapper.BaseDBMapper.java

@SuppressWarnings("unchecked")
@Override/* www .j a v a 2  s. c  om*/
public T mapRow(ResultSet r, int index) throws SQLException {
    try {
        T obj = (T) clazz.newInstance();
        if (obj == null) {
            return null;
        }
        try {

            BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor property : propertyDescriptors) {
                String key = property.getName();
                if (!key.equals("class")) {
                    Object value = null;
                    try {
                        Method setter = property.getWriteMethod();
                        value = r.getObject(key.toLowerCase());
                        if (value != null && value instanceof Number) {
                            @SuppressWarnings("rawtypes")
                            Class[] types = setter.getParameterTypes();
                            value = NumberUtils.convertNumberToTargetClass((Number) value, types[0]);
                        }
                        if (value != null) {
                            if (value.getClass().equals(BigInteger.class)) {
                                setter.invoke(obj, ((BigInteger) value).longValue());
                            } else if (value.getClass().equals(byte[].class)) {
                                setter.invoke(obj, new String((byte[]) value));
                            } else if (Blob.class.isAssignableFrom(value.getClass())) {
                                Blob bv = (Blob) value;
                                byte[] b = new byte[(int) bv.length()];
                                InputStream stream = bv.getBinaryStream();
                                stream.read(b);
                                stream.close();
                                String v = new String(b);
                                setter.invoke(obj, v);
                            } else {
                                setter.invoke(obj, value);
                            }
                        }
                    } catch (Exception e) {
                        logger.error("transBean2Map Error " + e);
                        logger.error("name[" + key + "]=" + (value == null ? "NULL" : value.toString())
                                + ", class:" + (value == null ? "NULL" : value.getClass()) + ", err:"
                                + e.getMessage());
                    }

                }

            }
        } catch (Exception e) {
            logger.error("transBean2Map Error " + e);
        }
        return obj;
    } catch (Exception e) {
        logger.error("Exception:" + e);
    }

    return null;
}

From source file:java2typescript.jackson.module.visitors.TSJsonObjectFormatVisitor.java

private boolean isAccessorMethod(Method method, BeanInfo beanInfo) {
    for (PropertyDescriptor property : beanInfo.getPropertyDescriptors()) {
        if (method.equals(property.getReadMethod())) {
            return true;
        }/* w w  w .  j  ava2  s. c om*/
        if (method.equals(property.getWriteMethod())) {
            return true;
        }
    }
    return false;
}

From source file:jp.co.opentone.bsol.framework.test.dataset.bean.BeanTable.java

private ITableMetaData createTableMetaData() throws DataSetException {
    if (beans.isEmpty()) {
        return new DefaultTableMetaData(tableName, new Column[0]);
    } else {//from  w w  w. j a  v  a  2s .  co m
        try {
            List<Column> columns = new ArrayList<Column>();
            BeanInfo info = Introspector.getBeanInfo(beans.get(0).getClass());
            PropertyDescriptor[] descs = info.getPropertyDescriptors();
            for (PropertyDescriptor desc : descs) {
                if (!isIgnoreProperty(desc)) {
                    System.out.println(desc.getName());
                    columns.add(new Column(desc.getName(), DataType.UNKNOWN));
                }
            }

            Column[] c = (Column[]) columns.toArray(new Column[columns.size()]);
            return new DefaultTableMetaData(tableName, c);
        } catch (IntrospectionException e) {
            throw new DataSetException(e);
        }
    }
}

From source file:net.sf.beanlib.provider.BeanChecker.java

/** 
 * @param fBean from bean//  ww  w.  j a  v a  2  s  . c o m
 * @param tBean to bean
 * @return true if the two beans are equal in a JavaBean sense.
 * ie. if they have the same number of properties, 
 * and the properties that can be read contain the same values.
 * 
 * TODO: unit test me
 */
public boolean beanEquals(Object fBean, Object tBean) {
    if (fBean == tBean)
        return true;
    if (fBean == null || tBean == null)
        return false;
    try {
        BeanInfo bi_f = Introspector.getBeanInfo(fBean.getClass());
        PropertyDescriptor[] pda_f = bi_f.getPropertyDescriptors();

        Map<?, ?> tMap = beanGetter.getPropertyName2DescriptorMap(tBean.getClass());

        if (pda_f.length != tMap.size())
            return false;

        for (int i = pda_f.length - 1; i > -1; i--) {
            PropertyDescriptor pd_f = pda_f[i];
            PropertyDescriptor pd_t = (PropertyDescriptor) tMap.get(pd_f.getName());
            Method m_f = pd_f.getReadMethod();
            Method m_t = pd_t.getReadMethod();

            if (m_f == null) {
                if (m_t == null)
                    continue;
                return false;
            }
            if (m_t == null)
                return false;
            Object v_f = m_f.invoke(fBean);
            Object v_t = m_t.invoke(tBean);

            if (!new EqualsBuilder().append(v_f, v_t).isEquals())
                return false;
        }
        return true;
    } catch (IntrospectionException e) {
        log.error("", e);
        throw new BeanlibException(e);
    } catch (IllegalAccessException e) {
        log.error("", e);
        throw new BeanlibException(e);
    } catch (InvocationTargetException e) {
        log.error("", e.getTargetException());
        throw new BeanlibException(e.getTargetException());
    }
}

From source file:org.openehr.adl.rm.RmBeanReflector.java

private Map<String, RmAttribute> buildAttributes(Class<?> beanClass)
        throws ReflectiveOperationException, IntrospectionException {
    Map<String, RmAttribute> properties;
    properties = new LinkedHashMap<>();
    BeanInfo info = Introspector.getBeanInfo(beanClass);

    PropertyDescriptor[] pds = info.getPropertyDescriptors();
    for (PropertyDescriptor pd : pds) {
        if (pd.getName().equals("class"))
            continue;
        ;//w  w w  .  j a v  a  2 s .  c  om

        String attribute = getAttributeForField(pd.getName());
        MultiplicityInterval occurrences = getOccurrences(beanClass, pd);
        final Class<?> targetType = List.class.isAssignableFrom(pd.getPropertyType())
                ? extractGenericType(beanClass, pd)
                : pd.getPropertyType();
        RmAttribute rp = new RmAttribute(attribute, pd, occurrences, targetType);
        properties.put(attribute, rp);
    }
    rmClassAttributeMap.put(beanClass, ImmutableMap.copyOf(properties));
    return properties;
}