Example usage for org.springframework.beans BeanWrapper getPropertyDescriptors

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

Introduction

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

Prototype

PropertyDescriptor[] getPropertyDescriptors();

Source Link

Document

Obtain the PropertyDescriptors for the wrapped object (as determined by standard JavaBeans introspection).

Usage

From source file:de.tudarmstadt.ukp.csniper.webapp.security.dao.AbstractDao.java

/**
 * Finds all entities that have the same type as the given example and all fields are equal to
 * non-null fields in the example.// w ww.  j  a  v  a2 s.c o m
 */
protected <TT> CriteriaQuery<TT> queryByExample(TT aExample, String aOrderBy, boolean aAscending) {
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    @SuppressWarnings("unchecked")
    CriteriaQuery<TT> query = cb.createQuery((Class<TT>) aExample.getClass());
    @SuppressWarnings("unchecked")
    Root<TT> root = query.from((Class<TT>) aExample.getClass());
    query.select(root);

    List<Predicate> predicates = new ArrayList<Predicate>();
    BeanWrapper a = PropertyAccessorFactory.forBeanPropertyAccess(aExample);

    // Iterate over all properties
    for (PropertyDescriptor d : a.getPropertyDescriptors()) {
        Object value = a.getPropertyValue(d.getName());

        // Only consider writeable properties. This filters out e.g. the "class" (getClass())
        // property.
        if (value != null && a.isWritableProperty(d.getName())) {
            predicates.add(cb.equal(root.get(d.getName()), value));
        }
    }

    if (!predicates.isEmpty()) {
        query.where(predicates.toArray(new Predicate[predicates.size()]));
    }

    if (aOrderBy != null) {
        if (aAscending) {
            query.orderBy(cb.asc(root.get(aOrderBy)));
        } else {
            query.orderBy(cb.desc(root.get(aOrderBy)));
        }
    }

    return query;
}

From source file:net.urosk.reportEngine.BirtConfigs.java

public void printOutProperties() throws Exception {

    final BeanWrapper wrapper = new BeanWrapperImpl(this);
    for (final PropertyDescriptor descriptor : wrapper.getPropertyDescriptors()) {
        logger.info(descriptor.getName() + ":" + descriptor.getReadMethod().invoke(this));
    }//from   w ww.  j a  v a2  s. co m
}

From source file:org.ambraproject.testutils.DummyHibernateDataStore.java

@Override
@SuppressWarnings("unchecked")
public <T> T get(final Class<T> clazz, final Serializable id) {
    return (T) hibernateTemplate.execute(new HibernateCallback() {
        @Override//from   ww w  .  j  ava2s  .  com
        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            T object = (T) session.get(clazz, id);
            if (object == null) {
                return null;
            } else {
                //Load up all the object's collection attributes in a session to make sure they aren't lazy-loaded
                BeanWrapper wrapper = new BeanWrapperImpl(object);
                for (PropertyDescriptor propertyDescriptor : wrapper.getPropertyDescriptors()) {
                    if (Collection.class.isAssignableFrom(propertyDescriptor.getPropertyType())) {
                        Iterator iterator = ((Collection) wrapper
                                .getPropertyValue(propertyDescriptor.getName())).iterator();
                        while (iterator.hasNext()) {
                            iterator.next();
                        }
                    }
                }
            }
            return object;
        }
    });
}

From source file:com.fmguler.ven.QueryGenerator.java

private void generateRecursively(int level, String tableName, String objectPath, Class objectClass, Set joins,
        StringBuffer selectClause, StringBuffer fromClause) {
    BeanWrapper wr = new BeanWrapperImpl(objectClass);
    PropertyDescriptor[] pdArr = wr.getPropertyDescriptors();

    for (int i = 0; i < pdArr.length; i++) {
        Class fieldClass = pdArr[i].getPropertyType(); //field class
        String fieldName = pdArr[i].getName(); //field name
        Object fieldValue = wr.getPropertyValue(fieldName);
        String columnName = Convert.toDB(pdArr[i].getName()); //column name

        //direct database class (Integer, String, Date, etc)
        if (dbClasses.contains(fieldClass)) {
            selectClause.append(tableName).append(".").append(columnName).append(" as ").append(tableName)
                    .append("_").append(columnName); //column
            selectClause.append(", ");
        }/*from  w  ww .j a v  a 2 s. c  o  m*/

        //many to one association (object property)
        if (fieldClass.getPackage() != null && domainPackages.contains(fieldClass.getPackage().getName())
                && joinsContain(joins, objectPath + "." + fieldName)) {
            String joinTableAlias = tableName + "_" + columnName; //alias for table to join since there can be multiple joins to the same table
            String joinTable = Convert.toDB(Convert.toSimpleName(fieldClass.getName())); //table to join
            fromClause.append(" left join ").append(joinTable).append(" ").append(joinTableAlias);
            fromClause.append(" on ").append(joinTableAlias).append(".id = ").append(tableName).append(".")
                    .append(columnName).append("_id");
            generateRecursively(++level, joinTableAlias, objectPath + "." + fieldName, fieldClass, joins,
                    selectClause, fromClause);
        }

        //one to many association (list property)
        if (fieldValue instanceof List && joinsContain(joins, objectPath + "." + fieldName)) {
            Class elementClass = VenList.findElementClass((List) fieldValue);
            String joinTableAlias = tableName + "_" + columnName; //alias for table to join since there can be multiple joins to the same table
            String joinTable = Convert.toDB(Convert.toSimpleName(elementClass.getName())); //table to join
            String joinField = Convert.toDB(findJoinField((List) fieldValue)); //field to join
            fromClause.append(" left join ").append(joinTable).append(" ").append(joinTableAlias);
            fromClause.append(" on ").append(joinTableAlias).append(".").append(joinField).append("_id = ")
                    .append(tableName).append(".id");
            generateRecursively(++level, joinTableAlias, objectPath + "." + fieldName, elementClass, joins,
                    selectClause, fromClause);
        }
    }
}

From source file:org.springjutsu.validation.rules.ValidationRulesContainer.java

/**
 * Read from exclude annotations to further 
 * populate exclude paths already parsed from XML.
 *///from   ww w. j av  a 2  s.  com
@SuppressWarnings({ "unchecked", "rawtypes" })
private void initExcludePaths() {
    for (ValidationEntity entity : validationEntityMap.values()) {
        // no paths to check on an interface.
        if (entity.getValidationClass().isInterface()) {
            continue;
        }
        BeanWrapper entityWrapper = new BeanWrapperImpl(entity.getValidationClass());
        for (PropertyDescriptor descriptor : entityWrapper.getPropertyDescriptors()) {
            if (!entityWrapper.isReadableProperty(descriptor.getName())
                    || !entityWrapper.isWritableProperty(descriptor.getName())) {
                continue;
            }
            for (Class excludeAnnotation : excludeAnnotations) {
                try {
                    if (ReflectionUtils.findField(entity.getValidationClass(), descriptor.getName())
                            .getAnnotation(excludeAnnotation) != null) {
                        entity.getExcludedPaths().add(descriptor.getName());
                    }
                } catch (SecurityException se) {
                    throw new IllegalStateException("Unexpected error while checking for excluded properties",
                            se);
                }
            }
        }
    }
}

From source file:org.springjutsu.validation.rules.ValidationRulesContainer.java

/**
 * Read from include annotations to further 
 * populate include paths already parsed from XML.
 */// www  . j a v a  2s.c om
@SuppressWarnings({ "unchecked", "rawtypes" })
private void initIncludePaths() {
    for (ValidationEntity entity : validationEntityMap.values()) {
        // no paths to check on an interface.
        if (entity.getValidationClass().isInterface()) {
            continue;
        }
        BeanWrapper entityWrapper = new BeanWrapperImpl(entity.getValidationClass());
        for (PropertyDescriptor descriptor : entityWrapper.getPropertyDescriptors()) {
            if (!entityWrapper.isReadableProperty(descriptor.getName())
                    || !entityWrapper.isWritableProperty(descriptor.getName())) {
                continue;
            }
            for (Class includeAnnotation : includeAnnotations) {
                try {
                    if (ReflectionUtils.findField(entity.getValidationClass(), descriptor.getName())
                            .getAnnotation(includeAnnotation) != null) {
                        entity.getIncludedPaths().add(descriptor.getName());
                    }
                } catch (SecurityException se) {
                    throw new IllegalStateException("Unexpected error while checking for included properties",
                            se);
                }
            }
        }
    }
}

From source file:net.sourceforge.vulcan.spring.SpringBeanXmlEncoder.java

void encodeBean(Element root, String beanName, Object bean) {
    final BeanWrapper bw = new BeanWrapperImpl(bean);

    final PropertyDescriptor[] pds = bw.getPropertyDescriptors();
    final Element beanNode = new Element("bean");

    root.addContent(beanNode);// w w  w  .j a  v  a  2  s .com

    if (beanName != null) {
        beanNode.setAttribute("name", beanName);
    }

    if (factoryExpert.needsFactory(bean)) {
        encodeBeanByFactory(beanNode, bean);
    } else {
        beanNode.setAttribute("class", bean.getClass().getName());
    }

    for (PropertyDescriptor pd : pds) {
        if (pd.getWriteMethod() == null)
            continue;

        final Method readMethod = pd.getReadMethod();

        if (readMethod == null)
            continue;

        if (readMethod.getAnnotation(Transient.class) != null) {
            continue;
        }
        final String name = pd.getName();

        final Object value = bw.getPropertyValue(name);
        if (value == null)
            continue;

        final Element propertyNode = new Element("property");
        propertyNode.setAttribute("name", name);
        beanNode.addContent(propertyNode);

        encodeObject(propertyNode, value);
    }
}

From source file:com.fmguler.ven.support.LiquibaseConverter.java

private void convertClass(StringBuffer liquibaseXml, Class domainClass) {
    String objectName = Convert.toSimpleName(domainClass.getName());
    String tableName = Convert.toDB(objectName);
    startTagChangeSet(liquibaseXml, author, "" + (changeSetId++));
    startTagCreateTable(liquibaseXml, schema, tableName);
    addIdColumn(liquibaseXml, tableName);
    List foreignKeyConstraints = new LinkedList();

    BeanWrapper wr = new BeanWrapperImpl(domainClass);
    PropertyDescriptor[] pdArr = wr.getPropertyDescriptors();

    for (int i = 0; i < pdArr.length; i++) {
        Class fieldClass = pdArr[i].getPropertyType(); //field class
        String fieldName = pdArr[i].getName(); //field name
        String columnName = Convert.toDB(pdArr[i].getName()); //column name

        if (fieldName.equals("id")) {
            continue;
        }//  w  w  w .j  av  a2 s .  c  o m

        //direct database class (Integer, String, Date, etc)
        if (dbClasses.keySet().contains(fieldClass)) {
            addPrimitiveColumn(liquibaseXml, columnName, ((Integer) dbClasses.get(fieldClass)).intValue());

        }

        //many to one association (object property)
        if (fieldClass.getPackage() != null && domainPackages.contains(fieldClass.getPackage().getName())) {
            addPrimitiveColumn(liquibaseXml, columnName + "_id", COLUMN_TYPE_INT);

            //handle foreign key
            String referencedTableName = Convert.toDB(Convert.toSimpleName(fieldClass.getName()));
            Map fkey = new HashMap();
            fkey.put("baseTableName", tableName);
            fkey.put("baseColumnNames", columnName + "_id");
            fkey.put("referencedTableName", referencedTableName);
            if (processedTables.contains(referencedTableName))
                foreignKeyConstraints.add(fkey);
            else
                unhandledForeignKeyConstraints.add(fkey);
        }

    }
    endTagCreateTable(liquibaseXml);
    endTagChangeSet(liquibaseXml);

    //mark table as processed
    processedTables.add(tableName);
    //add fkeys waiting for this table
    notifyUnhandledForeignKeyConstraints(liquibaseXml, tableName);
    //add fkeys not waiting for this table
    Iterator it = foreignKeyConstraints.iterator();
    while (it.hasNext()) {
        Map fkey = (Map) it.next();
        addForeignKeyConstraint(liquibaseXml, fkey);
    }
}

From source file:net.solarnetwork.web.support.SimpleCsvView.java

private List<String> getCSVFields(Object row, final Collection<String> fieldOrder) {
    assert row != null;
    List<String> result = new ArrayList<String>();
    if (row instanceof Map) {
        Map<?, ?> map = (Map<?, ?>) row;
        if (fieldOrder != null) {
            for (String key : fieldOrder) {
                result.add(key);/*w  w  w. ja  v a 2s. com*/
            }
        } else {
            for (Object key : map.keySet()) {
                result.add(key.toString());
            }
        }
    } else {
        // use bean properties
        if (getPropertySerializerRegistrar() != null) {
            // try whole-bean serialization first
            Object o = getPropertySerializerRegistrar().serializeProperty("row", row.getClass(), row, row);
            if (o != row) {
                if (o != null) {
                    result = getCSVFields(o, fieldOrder);
                    return result;
                }
            }
        }
        BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(row);
        PropertyDescriptor[] props = wrapper.getPropertyDescriptors();
        Set<String> resultSet = new LinkedHashSet<String>();
        for (PropertyDescriptor prop : props) {
            String name = prop.getName();
            if (getJavaBeanIgnoreProperties() != null && getJavaBeanIgnoreProperties().contains(name)) {
                continue;
            }
            if (wrapper.isReadableProperty(name)) {
                // test for SerializeIgnore
                Method getter = prop.getReadMethod();
                if (getter != null && getter.isAnnotationPresent(SerializeIgnore.class)) {
                    continue;
                }
                resultSet.add(name);
            }
        }
        if (fieldOrder != null && fieldOrder.size() > 0) {
            for (String key : fieldOrder) {
                if (resultSet.contains(key)) {
                    result.add(key);
                }
            }
        } else {
            result.addAll(resultSet);
        }

    }
    return result;
}

From source file:net.solarnetwork.web.support.JSONView.java

private void generateJavaBeanObject(JsonGenerator json, String key, Object bean,
        PropertyEditorRegistrar registrar) throws JsonGenerationException, IOException {
    if (key != null) {
        json.writeFieldName(key);/*from  ww  w . ja v a  2 s  . c o  m*/
    }
    if (bean == null) {
        json.writeNull();
        return;
    }
    BeanWrapper wrapper = getPropertyAccessor(bean, registrar);
    PropertyDescriptor[] props = wrapper.getPropertyDescriptors();
    json.writeStartObject();
    for (PropertyDescriptor prop : props) {
        String name = prop.getName();
        if (this.getJavaBeanIgnoreProperties() != null && this.getJavaBeanIgnoreProperties().contains(name)) {
            continue;
        }
        if (wrapper.isReadableProperty(name)) {
            Object propVal = wrapper.getPropertyValue(name);
            if (propVal != null) {

                // test for SerializeIgnore
                Method getter = prop.getReadMethod();
                if (getter != null && getter.isAnnotationPresent(SerializeIgnore.class)) {
                    continue;
                }

                if (getPropertySerializerRegistrar() != null) {
                    propVal = getPropertySerializerRegistrar().serializeProperty(name, propVal.getClass(), bean,
                            propVal);
                } else {
                    // Spring does not apply PropertyEditors on read methods, so manually handle
                    PropertyEditor editor = wrapper.findCustomEditor(null, name);
                    if (editor != null) {
                        editor.setValue(propVal);
                        propVal = editor.getAsText();
                    }
                }
                if (propVal instanceof Enum<?> || getJavaBeanTreatAsStringValues() != null
                        && getJavaBeanTreatAsStringValues().contains(propVal.getClass())) {
                    propVal = propVal.toString();
                }
                writeJsonValue(json, name, propVal, registrar);
            }
        }
    }
    json.writeEndObject();
}