Example usage for org.springframework.beans BeanWrapper getPropertyValue

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

Introduction

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

Prototype

@Nullable
Object getPropertyValue(String propertyName) throws BeansException;

Source Link

Document

Get the current value of the specified property.

Usage

From source file:net.solarnetwork.support.XmlSupport.java

/**
 * Turn an object into a simple XML Element, supporting custom property
 * editors.//  ww w .  j ava  2s .  c  o m
 * 
 * <p>
 * The returned XML will be a single element with all JavaBean properties
 * turned into attributes. For example:
 * <p>
 * 
 * <pre>
 * &lt;powerDatum
 *   id="123"
 *   pvVolts="123.123"
 *   ... /&gt;
 * </pre>
 * 
 * <p>
 * {@link PropertyEditor} instances can be registered with the supplied
 * {@link BeanWrapper} for custom handling of properties, e.g. dates.
 * </p>
 * 
 * @param bean
 *        the object to turn into XML
 * @param elementName
 *        the name of the XML element
 * @return the element, as an XML DOM Element
 */
public Element getElement(BeanWrapper bean, String elementName, Document dom) {
    PropertyDescriptor[] props = bean.getPropertyDescriptors();
    Element root = null;
    root = dom.createElement(elementName);
    for (int i = 0; i < props.length; i++) {
        PropertyDescriptor prop = props[i];
        if (prop.getReadMethod() == null) {
            continue;
        }
        String propName = prop.getName();
        if ("class".equals(propName)) {
            continue;
        }
        Object propValue = null;
        PropertyEditor editor = bean.findCustomEditor(prop.getPropertyType(), prop.getName());
        if (editor != null) {
            editor.setValue(bean.getPropertyValue(propName));
            propValue = editor.getAsText();
        } else {
            propValue = bean.getPropertyValue(propName);
        }
        if (propValue == null) {
            continue;
        }
        if (log.isTraceEnabled()) {
            log.trace("attribute name: " + propName + " attribute value: " + propValue);
        }
        root.setAttribute(propName, propValue.toString());
    }
    return root;
}

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);/*from  ww  w.  ja v  a 2 s.  c o m*/

    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:org.ambraproject.article.service.IngesterImpl.java

/**
 * Update an existing article by copying properties from the new one over.  Note that we can't call saveOrUpdate,
 * since the new article is not a persistent instance, but has all the properties that we want.
 * <p/>//w w  w  . j  a v  a 2 s . c  om
 * See <a href="http://stackoverflow.com/questions/4779239/update-persistent-object-with-transient-object-using-hibernate">this
 * post on stack overflow</a> for more information
 * <p/>
 * For collections, we clear the old property and add all the new entries, relying on 'delete-orphan' to delete the
 * old objects. The downside of this approach is that it results in a delete statement for each entry in the old
 * collection, and an insert statement for each entry in the new collection.  There a couple of things we could do to
 * optimize this: <ol> <li>Write a sql statement to delete the old entries in one go</li> <li>copy over collection
 * properties recursively instead of clearing the old collection.  e.g. for {@link Article#assets}, instead of
 * clearing out the old list, we would find the matching asset by DOI and Extension, and update its properties</li>
 * </ol>
 * <p/>
 * Option number 2 is messy and a lot of code (I've done it before)
 *
 * @param article         the new article, parsed from the xml
 * @param existingArticle the article pulled up from the database
 * @throws IngestException if there's a problem copying properties or updating
 */
@SuppressWarnings("unchecked")
private void updateArticle(final Article article, final Article existingArticle) throws IngestException {
    log.debug("ReIngesting (force ingest) article: {}", existingArticle.getDoi());
    //Hibernate deletes orphans after inserting the new rows, which violates a unique constraint on (doi, extension) for assets
    //this temporary change gets around the problem, before the old assets are orphaned and deleted
    hibernateTemplate.execute(new HibernateCallback() {
        @Override
        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            session.createSQLQuery("update articleAsset " + "set doi = concat('old-',doi), "
                    + "extension = concat('old-',extension) " + "where articleID = :articleID")
                    .setParameter("articleID", existingArticle.getID()).executeUpdate();
            return null;
        }
    });

    final BeanWrapper source = new BeanWrapperImpl(article);
    final BeanWrapper destination = new BeanWrapperImpl(existingArticle);

    try {
        //copy properties
        for (final PropertyDescriptor property : destination.getPropertyDescriptors()) {
            final String name = property.getName();
            if (!name.equals("ID") && !name.equals("created") && !name.equals("lastModified")
                    && !name.equals("class")) {
                //Collections shouldn't be dereferenced but have elements added
                //See http://www.onkarjoshi.com/blog/188/hibernateexception-a-collection-with-cascade-all-delete-orphan-was-no-longer-referenced-by-the-owning-entity-instance/
                if (Collection.class.isAssignableFrom(property.getPropertyType())) {
                    Collection orig = (Collection) destination.getPropertyValue(name);
                    orig.clear();
                    Collection sourcePropertyValue = (Collection) source.getPropertyValue(name);
                    if (sourcePropertyValue != null) {
                        orig.addAll((Collection) source.getPropertyValue(name));
                    }
                } else {
                    //just set the new value
                    destination.setPropertyValue(name, source.getPropertyValue(name));
                }
            }
        }
        //Circular relationship in related articles
        for (ArticleRelationship articleRelationship : existingArticle.getRelatedArticles()) {
            articleRelationship.setParentArticle(existingArticle);
        }
    } catch (Exception e) {
        throw new IngestException("Error copying properties for article " + article.getDoi(), e);
    }

    hibernateTemplate.update(existingArticle);
}

From source file:com.thesoftwarefactory.vertx.web.model.Form.java

/**
  * Creates a Bean with the given class from the from values
  * @param object Source object we're taking the values from
  * @return this object//from   ww  w .  java  2  s  . c o m
  */
public Form<T> fillFromBean(Object object) {

    BeanWrapper beanWrapper = new BeanWrapperImpl(object);
    for (Field field : fields()) {
        // if applicable, remove the fieldPrefix to get the bean field name
        String fieldName = fieldPrefix != null ? field.name().substring(fieldPrefix.length()) : field.name();
        try {
            PropertyDescriptor property = beanWrapper.getPropertyDescriptor(fieldName);
            if (property != null && property.getReadMethod() != null) {
                Object propertyValue = beanWrapper.getPropertyValue(fieldName);
                String strPropValue = propertyValue != null ? propertyValue.toString() : null;

                // If the field hasn't got a value already, clear the potential errors as they will be meaningless
                // and the set the field value
                if (field.value() == null) {
                    field.value(strPropValue);
                    field.errors().clear();
                }
            }
        } catch (InvalidPropertyException e) {
            logger.log(Level.WARNING,
                    "Could not find property " + fieldName + " for bean " + object.getClass().getName(), e);
            continue;
        }

    }
    return this;
}

From source file:net.kamhon.ieagle.dao.HibernateDao.java

private QueryParams translateExampleToQueryParams(Object example, String... orderBy) {
    Object newObj = example;/*from  ww w .j a v  a2s.co m*/
    Entity className = ((Entity) newObj.getClass().getAnnotation(Entity.class));
    if (className == null)
        throw new DataException(newObj.getClass().getSimpleName() + " class is not valid JPA annotated bean");
    String aliasName = StringUtils.isBlank(className.name()) ? "obj" : className.name();

    String hql = "SELECT " + aliasName + " FROM ";
    List<Object> params = new ArrayList<Object>();

    BeanWrapper beanO1 = new BeanWrapperImpl(newObj);
    PropertyDescriptor[] proDescriptorsO1 = beanO1.getPropertyDescriptors();
    int propertyLength = proDescriptorsO1.length;

    if (newObj != null) {
        hql += aliasName;
        hql += " IN " + example.getClass();
    }

    if (example instanceof VoBase) {
        VoBase voBase = (VoBase) example;
        for (String key : voBase.getJoinTables().keySet()) {
            if (StringUtils.isNotBlank(key)) {
                hql += " JOIN " + key + " " + voBase.getJoinTables().get(key);
            }
        }
    }

    hql += " WHERE 1=1";

    for (int i = 0; i < propertyLength; i++) {
        try {
            Object propertyValueO1 = beanO1.getPropertyValue(proDescriptorsO1[i].getName());

            if ((propertyValueO1 instanceof String && StringUtils.isNotBlank((String) propertyValueO1))
                    || propertyValueO1 instanceof Long || propertyValueO1 instanceof Double
                    || propertyValueO1 instanceof Integer || propertyValueO1 instanceof Boolean
                    || propertyValueO1 instanceof Date || propertyValueO1.getClass().isPrimitive()) {
                Field field = null;
                try {
                    field = example.getClass().getDeclaredField(proDescriptorsO1[i].getName());
                } catch (NoSuchFieldException e) {
                    if (propertyValueO1 instanceof Boolean || propertyValueO1.getClass().isPrimitive()) {
                        String fieldName = "is"
                                + StringUtils.upperCase(proDescriptorsO1[i].getName().substring(0, 1))
                                + proDescriptorsO1[i].getName().substring(1);
                        field = example.getClass().getDeclaredField(fieldName);
                    }
                }

                if (proDescriptorsO1[i].getName() != null && field != null
                        && !field.isAnnotationPresent(Transient.class)) {
                    if (!Arrays.asList(VoBase.propertiesVer).contains(proDescriptorsO1[i].getName())) {
                        hql += " AND " + aliasName + "." + field.getName() + " = ?";
                        params.add(propertyValueO1);
                    }
                }
            } else if (propertyValueO1 != null) {
                Field field = example.getClass().getDeclaredField(proDescriptorsO1[i].getName());
                if (field.isAnnotationPresent(javax.persistence.Id.class)
                        || field.isAnnotationPresent(javax.persistence.EmbeddedId.class)) {

                    BeanWrapper bean = new BeanWrapperImpl(propertyValueO1);
                    PropertyDescriptor[] proDescriptors = bean.getPropertyDescriptors();

                    for (PropertyDescriptor propertyDescriptor : proDescriptors) {
                        Object propertyValueId = bean.getPropertyValue(propertyDescriptor.getName());

                        if (propertyValueId != null && ReflectionUtil.isJavaDataType(propertyValueId)) {
                            hql += " AND " + aliasName + "." + proDescriptorsO1[i].getName() + "."
                                    + propertyDescriptor.getName() + " = ?";
                            params.add(bean.getPropertyValue(propertyDescriptor.getName()));
                        }
                    }
                }
            }
        } catch (Exception e) {
        }
    }

    // not condition
    if (example instanceof VoBase) {
        VoBase voBase = (VoBase) example;
        for (String key : voBase.getNotConditions().keySet()) {
            if (StringUtils.isNotBlank(key)) {
                hql += " AND " + aliasName + "." + key + "!=? ";
                params.add(voBase.getNotConditions().get(key));
            }
        }
    }

    // like condition
    if (example instanceof VoBase) {
        VoBase voBase = (VoBase) example;
        for (String key : voBase.getLikeConditions().keySet()) {
            if (StringUtils.isNotBlank(key)) {
                hql += " AND " + aliasName + "." + key + " LIKE ? ";
                params.add(voBase.getLikeConditions().get(key));
            }
        }
    }

    if (orderBy != null && orderBy.length != 0) {
        hql += " ORDER BY ";
        long count = 1;
        for (String orderByStr : orderBy) {
            if (count != 1)
                hql += ",";
            hql += aliasName + "." + orderByStr;
            count += 1;
        }
    }

    log.debug("hql = " + hql);

    return new QueryParams(hql, params);
}

From source file:com.thesoftwarefactory.vertx.web.model.Form.java

/**
 * bind all or only the specified properties of the object to this Form. 
 * Validation is automatically performed after the binding, validating all or only the specified properties. 
 * The result of the validation is available by calling form.hasErrors() and/or field.hasErrors() 
 * // w  w w. j a v  a 2s  . c  om
 * @param object
 * @param properties
 * @return
 */
public Form<T> bindObject(T object, String... properties) {
    if (object != null) {
        this.object = object;
        BeanWrapper beanWrapper = new BeanWrapperImpl(object);
        for (Field field : fields()) {
            // if applicable, remove the fieldPrefix to get the bean field name 
            String fieldName = fieldPrefix != null ? field.name().substring(fieldPrefix.length())
                    : field.name();
            PropertyDescriptor property = beanWrapper.getPropertyDescriptor(fieldName);
            if (property != null && property.getReadMethod() != null) {
                Object propertyValue = beanWrapper.getPropertyValue(fieldName);

                String strPropValue = propertyValue != null
                        ? (propertyValue instanceof java.time.Instant
                                ? format((java.time.Instant) propertyValue)
                                : propertyValue.toString())
                        : null;
                field.value(strPropValue);
            }
        }
    }
    return this;
}

From source file:net.kamhon.ieagle.dao.Jpa2Dao.java

private QueryParams translateExampleToQueryParams(Object example, String... orderBy) {
    Object newObj = example;//www.j a v  a  2s .c o  m
    Entity entity = ((Entity) newObj.getClass().getAnnotation(Entity.class));
    if (entity == null)
        throw new DataException(newObj.getClass().getSimpleName() + " class is not valid JPA annotated bean");

    String entityName = StringUtils.isBlank(entity.name()) ? example.getClass().getSimpleName() : entity.name();
    String aliasName = StringUtils.isBlank(entity.name()) ? "obj" : entity.name();

    String hql = "SELECT " + aliasName + " FROM ";
    List<Object> params = new ArrayList<Object>();

    BeanWrapper beanO1 = new BeanWrapperImpl(newObj);
    PropertyDescriptor[] proDescriptorsO1 = beanO1.getPropertyDescriptors();
    int propertyLength = proDescriptorsO1.length;

    if (newObj != null) {
        hql += entityName + " " + aliasName;
    }

    if (example instanceof VoBase) {
        VoBase voBase = (VoBase) example;
        for (String key : voBase.getJoinTables().keySet()) {
            if (StringUtils.isNotBlank(key)) {
                hql += " JOIN " + key + " " + voBase.getJoinTables().get(key);
            }
        }
    }

    hql += " WHERE 1=1";

    int paramCount = 0;
    for (int i = 0; i < propertyLength; i++) {
        try {
            Object propertyValueO1 = beanO1.getPropertyValue(proDescriptorsO1[i].getName());

            if ((propertyValueO1 instanceof String && StringUtils.isNotBlank((String) propertyValueO1))
                    || propertyValueO1 instanceof Long || propertyValueO1 instanceof Double
                    || propertyValueO1 instanceof Integer || propertyValueO1 instanceof Boolean
                    || propertyValueO1 instanceof Date || propertyValueO1.getClass().isPrimitive()) {

                Field field = null;
                try {
                    field = example.getClass().getDeclaredField(proDescriptorsO1[i].getName());
                } catch (NoSuchFieldException e) {
                    if (propertyValueO1 instanceof Boolean || propertyValueO1.getClass().isPrimitive()) {
                        String fieldName = "is"
                                + StringUtils.upperCase(proDescriptorsO1[i].getName().substring(0, 1))
                                + proDescriptorsO1[i].getName().substring(1);
                        field = example.getClass().getDeclaredField(fieldName);
                    }
                }

                if (proDescriptorsO1[i].getName() != null && field != null
                        && !field.isAnnotationPresent(Transient.class)) {
                    if (!Arrays.asList(VoBase.propertiesVer).contains(proDescriptorsO1[i].getName())) {
                        hql += " AND " + aliasName + "." + field.getName() + " = ?" + (++paramCount);
                        params.add(propertyValueO1);
                    }
                }
            } else if (propertyValueO1 != null) {
                Field field = example.getClass().getDeclaredField(proDescriptorsO1[i].getName());
                if (field.isAnnotationPresent(javax.persistence.Id.class)
                        || field.isAnnotationPresent(javax.persistence.EmbeddedId.class)) {

                    BeanWrapper bean = new BeanWrapperImpl(propertyValueO1);
                    PropertyDescriptor[] proDescriptors = bean.getPropertyDescriptors();

                    for (PropertyDescriptor propertyDescriptor : proDescriptors) {
                        Object propertyValueId = bean.getPropertyValue(propertyDescriptor.getName());

                        if (propertyValueId != null && ReflectionUtil.isJavaDataType(propertyValueId)) {
                            hql += " AND " + aliasName + "." + proDescriptorsO1[i].getName() + "."
                                    + propertyDescriptor.getName() + " = ?" + (++paramCount);
                            params.add(bean.getPropertyValue(propertyDescriptor.getName()));
                        }
                    }
                }
            }

        } catch (Exception e) {
        }
    }

    // not condition
    if (example instanceof VoBase) {
        VoBase voBase = (VoBase) example;
        for (String key : voBase.getNotConditions().keySet()) {
            if (StringUtils.isNotBlank(key)) {
                hql += " AND " + aliasName + "." + key + "!= ?" + (++paramCount);
                params.add(voBase.getNotConditions().get(key));
            }
        }
    }

    // like condition
    if (example instanceof VoBase) {
        VoBase voBase = (VoBase) example;
        for (String key : voBase.getLikeConditions().keySet()) {
            if (StringUtils.isNotBlank(key)) {
                hql += " AND " + aliasName + "." + key + " LIKE ?" + (++paramCount);
                params.add(voBase.getLikeConditions().get(key));
            }
        }
    }

    if (orderBy != null && orderBy.length != 0) {
        hql += " ORDER BY ";
        long count = 1;
        for (String orderByStr : orderBy) {
            if (count != 1)
                hql += ",";
            hql += aliasName + "." + orderByStr;
            count += 1;
        }
    }

    log.debug("hql = " + hql);

    return new QueryParams(hql, params);
}

From source file:com.seovic.core.DynamicObject.java

/**
 * Update specified target from this object.
 *
 * @param target  target object to update
 *///from w ww.  j a  v  a 2  s  .  c  om
public void update(Object target) {
    if (target == null) {
        throw new IllegalArgumentException("Target to update cannot be null");
    }

    BeanWrapper bw = new BeanWrapperImpl(target);
    bw.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
    for (Map.Entry<String, Object> property : m_properties.entrySet()) {
        String propertyName = property.getKey();
        Object value = property.getValue();

        if (value instanceof Map) {
            PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName);
            if (!Map.class.isAssignableFrom(pd.getPropertyType()) || pd.getWriteMethod() == null) {
                value = new DynamicObject((Map<String, Object>) value);
            }
        }

        if (value instanceof DynamicObject) {
            ((DynamicObject) value).update(bw.getPropertyValue(propertyName));
        } else {
            bw.setPropertyValue(propertyName, value);
        }
    }
}

From source file:org.codehaus.groovy.grails.web.binding.GrailsDataBinder.java

private Object getPropertyValueForPath(Object target, String[] propertyNames) {
    BeanWrapper wrapper = new BeanWrapperImpl(target);
    Object obj = target;//  www  .  ja va  2  s  .  c  o m
    for (int i = 0; i < propertyNames.length - 1; i++) {
        String propertyName = propertyNames[i];
        if (wrapper.isReadableProperty(propertyName)) {
            obj = wrapper.getPropertyValue(propertyName);
            if (obj == null)
                break;
            wrapper = new BeanWrapperImpl(obj);
        }
    }

    return obj;
}