Example usage for org.springframework.beans BeanUtils getPropertyDescriptors

List of usage examples for org.springframework.beans BeanUtils getPropertyDescriptors

Introduction

In this page you can find the example usage for org.springframework.beans BeanUtils getPropertyDescriptors.

Prototype

public static PropertyDescriptor[] getPropertyDescriptors(Class<?> clazz) throws BeansException 

Source Link

Document

Retrieve the JavaBeans PropertyDescriptor s of a given class.

Usage

From source file:com.ocs.dynamo.importer.impl.BaseImporter.java

/**
 * Processes a single row from the input and turns it into an object
 * /*from  www  .  ja v a 2  s.com*/
 * @param rowNum
 * @param row
 * @param clazz
 * @return
 */
public <T extends AbstractDTO> T processRow(int rowNum, R row, Class<T> clazz) {
    T t = ClassUtils.instantiateClass(clazz);
    t.setRowNum(rowNum);

    PropertyDescriptor[] descriptors = BeanUtils.getPropertyDescriptors(clazz);
    for (PropertyDescriptor d : descriptors) {
        XlsField field = ClassUtils.getAnnotation(clazz, d.getName(), XlsField.class);
        if (field != null) {
            if (isWithinRange(row, field)) {
                U unit = getUnit(row, field);

                Object obj = getFieldValue(d, unit, field);
                if (obj != null) {
                    ClassUtils.setFieldValue(t, d.getName(), obj);
                } else if (field.required()) {
                    // a required value is missing!
                    throw new OCSImportException("Required value for field '" + d.getName() + "' is missing");
                }
            } else {
                throw new OCSImportException("Row doesn't have enough columns");
            }
        }
    }

    return t;
}

From source file:com.dexcoder.dal.spring.mapper.JdbcRowMapper.java

/**
 * Initialize the mapping metadata for the given class.
 * @param mappedClass the mapped class//from  w  ww  .j  av a2s.  co  m
 */
protected void initialize(Class<T> mappedClass) {
    this.mappedClass = mappedClass;
    this.mappedFields = new HashMap<String, PropertyDescriptor>();
    this.mappedProperties = new HashSet<String>();
    PropertyDescriptor[] pds = BeanUtils.getPropertyDescriptors(mappedClass);
    for (PropertyDescriptor pd : pds) {
        if (pd.getWriteMethod() != null) {

            Method readMethod = pd.getReadMethod();
            if (readMethod != null) {
                Column aColumn = readMethod.getAnnotation(Column.class);
                if (aColumn != null) {
                    String name = NameUtils.getLegalName(aColumn.value());
                    this.mappedFields.put(lowerCaseName(name), pd);
                }
            }

            this.mappedFields.put(lowerCaseName(pd.getName()), pd);
            String underscoredName = underscoreName(pd.getName());
            if (!lowerCaseName(pd.getName()).equals(underscoredName)) {
                this.mappedFields.put(underscoredName, pd);
            }
            this.mappedProperties.add(pd.getName());
        }
    }
}

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

private <T> T createBeanByJavassist(ResultSet rs, Class<T> mappedClass, String key) throws SQLException {

    DbBeanFactory dynamicRse = DBBEANFACTORY_CACHE.get(key);

    // //from   w  w  w.j  a va  2s.co m
    if (dynamicRse != null) {

        return dynamicRse.createBean(rs, mappedClass);
    }

    T bean = this.newInstance(mappedClass);

    ResultSetMetaData rsmd = rs.getMetaData();

    PropertyDescriptor[] props = BeanUtils.getPropertyDescriptors(mappedClass);

    int[] columnToProperty = this.mapColumnsToProperties(rsmd, props);

    StringBuilder handlerScript = new StringBuilder();

    handlerScript.append("{").append(mappedClass.getName()).append(" bean = new ").append(mappedClass.getName())
            .append("();\n");

    PropertyDescriptor desc = null;
    for (int i = 1; i < columnToProperty.length; i++) {

        if (columnToProperty[i] == PROPERTY_NOT_FOUND) {
            continue;
        }

        desc = props[columnToProperty[i]];
        Class<?> propType = desc.getPropertyType();

        Object value = processColumn(rs, i, propType, desc.getWriteMethod().getName(), handlerScript);

        this.callSetter(bean, desc, value);

    }

    handlerScript.append("return bean;");

    handlerScript.append("}");

    try {

        ClassPool classPool = ClassPool.getDefault();

        classPool.appendClassPath(new LoaderClassPath(ClassUtils.getDefaultClassLoader()));

        CtClass ctHandler = classPool.makeClass(DynamicClassUtils.getBeanProcessorName(mappedClass));
        ctHandler.setSuperclass(classPool.get("com.nway.spring.jdbc.bean.DbBeanFactory"));

        CtMethod mapRow = CtNewMethod.make(
                "public Object createBean(java.sql.ResultSet rs, Class type) throws java.sql.SQLException{return null;}",
                ctHandler);

        mapRow.setGenericSignature("<T:Ljava/lang/Object;>(Ljava/sql/ResultSet;Ljava/lang/Class<TT;>;)TT;");

        mapRow.setBody(handlerScript.toString());

        ctHandler.addMethod(mapRow);

        DBBEANFACTORY_CACHE.put(key, (DbBeanFactory) ctHandler.toClass().newInstance());

    } catch (Exception e) {

        throw new DynamicObjectException("javassist [ " + mappedClass.getName() + " ] ", e);
    }

    return bean;
}

From source file:org.brushingbits.jnap.common.bean.visitor.BeanPropertyVisitor.java

protected void handleBean(Object source, Class<?> type) {
    context.nextLevel();/*w  ww  .  j a  va  2  s .  co  m*/
    visitBean(source, type);
    BeanWrapper sourceBean = PropertyAccessorFactory.forBeanPropertyAccess(source);
    PropertyDescriptor[] beanProperties = BeanUtils.getPropertyDescriptors(type);
    for (PropertyDescriptor propertyDescriptor : beanProperties) {
        String name = propertyDescriptor.getName();
        context.pushPath(name);
        if (sourceBean.isReadableProperty(name)) {
            Object value = sourceBean.getPropertyValue(name);
            visit(value);
        }
        context.popPath();
    }
    context.prevLevel();
}

From source file:org.codehaus.groovy.grails.plugins.couchdb.domain.CouchDomainClass.java

public CouchDomainClass(Class<?> clazz, Map<String, Object> defaultConstraints, boolean shouldFailOnError) {
    super(clazz, "");

    CouchEntity entityAnnotation = (CouchEntity) clazz.getAnnotation(CouchEntity.class);
    if (entityAnnotation == null) {
        throw new GrailsDomainException(
                "Class [" + clazz.getName() + "] is not annotated with grails.plugins.couchdb.CouchEntity!");
    }/*from   w  ww  .jav  a 2s  . co m*/

    this.defaultConstraints = defaultConstraints;
    this.shouldFailOnError = shouldFailOnError;

    // try to read the "designName" annotation property
    try {
        designName = entityAnnotation.designName();
        if ("".equals(designName)) {
            designName = null;
        }
    } catch (IncompleteAnnotationException ex) {
        designName = null;
    }

    // if the design wasn't set, then try to use the "type" annotation property
    if (designName == null) {
        try {
            designName = entityAnnotation.type();
        } catch (IncompleteAnnotationException ex) {
            designName = null;
        }
    }

    // if designName is still empty, then use the class name
    if (designName == null || "".equals(designName)) {
        designName = clazz.getSimpleName().toLowerCase();
    }

    if ("class".equals(designName) || "metaClass".equals(designName)) {
        throw new GrailsDomainException("The CouchEntity annotation parameter [designName] on Class ["
                + clazz.getName() + "] cannot be set to 'class' or 'metaClass'.");
    }

    // try to read the "db" annotation property
    try {
        databaseId = entityAnnotation.db();

        // if the db annotation is empty, then just use the default
        if ("".equals(databaseId)) {
            databaseId = null;
        }
    } catch (IncompleteAnnotationException ex) {
        databaseId = null;
    }

    // set the full documentType
    try {
        typeFieldName = entityAnnotation.typeFieldName();
        if (typeFieldName != null && !"".equals(typeFieldName)) {
            Method getter = clazz.getDeclaredMethod("get" + StringUtils.capitalize(typeFieldName));
            documentType = (String) getter.invoke(clazz.newInstance());
        }
    } catch (Exception e) {
        if (e instanceof NoSuchMethodException && "".equals(entityAnnotation.type())) {
            log.info("Document type is disabled for Class [" + clazz.getName() + "].");
        } else {
            log.error("Couldn't get document type for Class [" + clazz.getName() + "].", e);
        }

        documentType = "";
    }

    PropertyDescriptor[] descriptors = BeanUtils.getPropertyDescriptors(clazz);
    evaluateClassProperties(descriptors);

    // process the constraints
    try {
        initializeConstraints();
    } catch (Exception e) {
        log.error("Error reading class [" + getClazz() + "] constraints: " + e.getMessage(), e);
    }
}

From source file:com.hihsoft.baseclass.web.controller.BaseController.java

/**
 * ???(xiaojf?)//w w w  .j a  v  a2  s  .  com
 */
@Override
protected void bind(final HttpServletRequest request, final Object command) {
    final PropertyDescriptor[] pds = BeanUtils.getPropertyDescriptors(command.getClass());
    for (final PropertyDescriptor pd : pds) {
        final Class<?> clas = pd.getPropertyType();// ?class
        final boolean isSimpleProperty = BeanUtils.isSimpleProperty(clas);
        final boolean isInterface = clas.isInterface();
        final boolean hasConstruct = clas.getConstructors().length == 0 ? false : true;
        if (!isSimpleProperty && !isInterface && hasConstruct) {
            // 
            try {
                pd.getWriteMethod().invoke(command, clas.newInstance());
            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InstantiationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    try {
        super.bind(request, command);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:com.lakeside.data.sqldb.BaseDao.java

/**
 * ?/*from  w w  w.j  a  v a  2s .  co  m*/
 * @param entity
 * @return
 */
public T merge(final T entity) {
    Assert.notNull(entity, "entity?");
    Session session = getSession();
    String idName = getIdName();
    PropertyDescriptor idp = BeanUtils.getPropertyDescriptor(entityClass, idName);
    PK idvalue = null;
    try {
        idvalue = (PK) idp.getReadMethod().invoke(entity);
    } catch (Exception e) {
        throw new FatalBeanException("Could not copy properties from source to target", e);
    }
    T dest = null;
    if (idvalue != null) {
        dest = (T) session.get(entityClass, idvalue);
    }
    if (dest != null) {
        // merge the properties
        PropertyDescriptor[] descriptors = BeanUtils.getPropertyDescriptors(entityClass);
        for (PropertyDescriptor p : descriptors) {
            if (p.getWriteMethod() != null) {
                try {
                    Method readMethod = p.getReadMethod();
                    if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                        readMethod.setAccessible(true);
                    }
                    Object value = readMethod.invoke(entity);
                    if (value == null) {
                        continue;
                    }
                    Method writeMethod = p.getWriteMethod();
                    if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                        writeMethod.setAccessible(true);
                    }
                    writeMethod.invoke(dest, value);
                } catch (Throwable ex) {
                    throw new FatalBeanException("Could not copy properties from source to target", ex);
                }
            }
        }
    } else {
        // destination object is empty, save the entity object parameted
        dest = entity;
    }
    session.saveOrUpdate(dest);
    logger.debug("merge entity: {}", entity);
    return dest;
}

From source file:org.brushingbits.jnap.persistence.hsearch.FullTextDao.java

protected String[] getIndexedFields() {
    if (this.indexedFields == null) {
        PropertyDescriptor[] beanProperties = BeanUtils.getPropertyDescriptors(getEntityClass());
        List<String> fields = new ArrayList<String>();
        for (PropertyDescriptor propertyDescriptor : beanProperties) {
            Field field = ReflectionUtils.getAnnotation(Field.class, propertyDescriptor.getReadMethod());
            if (field == null) {
                java.lang.reflect.Field propertyField = FieldUtils.getField(getEntityClass(),
                        propertyDescriptor.getName());
                if (propertyField != null && propertyField.isAnnotationPresent(Field.class)) {
                    field = propertyField.getAnnotation(Field.class);
                }/*from w ww .j a v a  2  s  . c o m*/
            }
            if (field != null) {
                String fieldName = propertyDescriptor.getName();
                if (StringUtils.isNotBlank(fieldName)) {
                    fieldName = field.name();
                }
                fields.add(fieldName);
            }
        }
    }
    return this.indexedFields;
}

From source file:com.duowan.common.spring.jdbc.BeanPropertyRowMapper.java

/**
 * Initialize the mapping metadata for the given class.
 * @param mappedClass the mapped class./*from  ww  w.java  2 s  .co m*/
 */
protected void initialize(Class<T> mappedClass) {
    this.mappedClass = mappedClass;
    this.mappedFields = new HashMap<String, PropertyDescriptor>();
    this.mappedProperties = new HashSet<String>();
    PropertyDescriptor[] pds = BeanUtils.getPropertyDescriptors(mappedClass);
    for (PropertyDescriptor pd : pds) {
        if (pd.getWriteMethod() != null) {
            this.mappedFields.put(pd.getName().toLowerCase(), pd);
            String underscoredName = underscoreName(pd.getName());
            if (!pd.getName().toLowerCase().equals(underscoredName)) {
                this.mappedFields.put(underscoredName, pd);
            }
            this.mappedProperties.add(pd.getName());
        }
    }
}

From source file:com.opensymphony.able.introspect.EntityInfo.java

/**
 * Lets introspect all the properties/*w w  w .  j  a  v a 2 s  . com*/
 */
protected void introspect(Class<? extends Object> type) {
    PropertyDescriptor[] propertyDescriptors = BeanUtils.getPropertyDescriptors(entityClass);
    for (PropertyDescriptor descriptor : propertyDescriptors) {
        String name = descriptor.getName();
        if (name.equals("class")) {
            continue;
        }

        PropertyInfo propertyInfo = new PropertyInfo(this, descriptor, entityClass);
        propertyMap.put(name, propertyInfo);
        if (propertyInfo.isIdProperty()) {
            if (idProperty != null) {
                throw new IllegalStateException(
                        "Duplicate @Id properties defined for: " + idProperty + " and " + propertyInfo);
            }
            this.idProperty = propertyInfo;
        }
    }

    // now lets create the sorted properties list
    configureViewDefaults();
    configureViewTable();
    configureEditTable();
    configureViewForm();
    configureEditForm();
    configureViewField();
}