Example usage for org.apache.commons.beanutils PropertyUtils getSimpleProperty

List of usage examples for org.apache.commons.beanutils PropertyUtils getSimpleProperty

Introduction

In this page you can find the example usage for org.apache.commons.beanutils PropertyUtils getSimpleProperty.

Prototype

public static Object getSimpleProperty(Object bean, String name)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException 

Source Link

Document

Return the value of the specified simple property of the specified bean, with no type conversions.

For more details see PropertyUtilsBean.

Usage

From source file:com.glweb.web.struts.actions.UserAction.java

/**
 * @see org.apache.struts.action.Action#execute(ActionMapping, ActionForm, HttpServletRequest, HttpServletResponse)
 *//*from  w w  w .j  av  a  2s.c  o m*/
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    HttpSession _session = request.getSession();

    String _action = (String) PropertyUtils.getSimpleProperty(form, "action");

    if (null == _action) {
        return (mapping.getInputForward());
    }

    // Was this transaction cancelled?
    if (isCancelled(request)) {
        if (getLogger().isInfoEnabled()) {
            getLogger().info(" " + mapping.getAttribute() + " - User transaction was cancelled");
        }

        removeFormBean(mapping, request);

        _session.removeAttribute(Constants.USER_KEY);

        return (mapping.findForward("/view/user/cancel"));
    }

    User _user = null;
    String _name = (String) PropertyUtils.getSimpleProperty(form, "name");

    _user = new User();
    _user.setName(_name);

    if (getLogger().isInfoEnabled()) {
        getLogger().info("user = " + _user);
    }

    _session.setAttribute(Constants.USER_KEY, _user);

    return (mapping.findForward("/view/user/success"));
}

From source file:edu.duke.cabig.c3pr.webservice.integration.BeanUtils.java

/**
 * This methods performs deep comparison of two objects of the same class.
 * Comparison is performed only on properties exposed via the standard
 * JavaBean mechanism. Properties of primitive types, wrappers,
 * {@link String}, {@link CharSequence}, {@link Date}, {@link Enum} are
 * compared directly using {@link Object#equals(Object)}; other complex
 * properties are compared recursively. Elements of {@link Collection}
 * properties are iterated and compared.
 * /*from ww  w  . j  av  a2  s  . c  o  m*/
 * @param <T>
 * @param obj1
 * @param obj2
 * @return
 * @throws NullPointerException
 *             if any of the parameters is null.
 */
public static <T> boolean deepCompare(T obj1, T obj2) {
    if (obj1 == obj2) {
        return true;
    }
    // if it's a "simple" object, do direct comparison.
    for (Class<?> cls : DIRECTLY_COMPARABLE_TYPES) {
        if (cls.isAssignableFrom(obj1.getClass())) {
            if (!obj1.equals(obj2)) {
                log.info("Values don't match: " + obj1 + " and " + obj2);
                System.out.println();
                System.out.println("Values don't match: " + obj1 + " and " + obj2);
                return false;
            } else {
                return true;
            }
        }
    }
    try {
        PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(obj1.getClass());
        for (PropertyDescriptor pd : descriptors) {
            // ignore properties which cannot be read.
            if (pd.getReadMethod() != null) {
                Class<?> type = pd.getPropertyType();
                // this check will skip Object.getClass().
                if (SKIP_TYPES.contains(type)) {
                    continue;
                }
                String name = pd.getName();
                Object v1 = PropertyUtils.getSimpleProperty(obj1, name);
                Object v2 = PropertyUtils.getSimpleProperty(obj2, name);
                if (v1 == v2 || (v1 == null && v2 == null)) {
                    continue;
                }
                if ((v1 == null && v2 != null) || (v1 != null && v2 == null)) {
                    log.info("Values don't match: " + v1 + " and " + v2);
                    System.out.println();
                    System.out.println("Values don't match: " + v1 + " and " + v2);
                    return false;
                }
                // Collections need special handling.
                if (Collection.class.isAssignableFrom(type)) {
                    List l1 = new ArrayList((Collection) v1);
                    List l2 = new ArrayList((Collection) v2);
                    if (l1.size() != l2.size()) {
                        log.info("Collection sizes don't match:" + l1 + l2);
                        System.out.println();
                        System.out.println("Collection sizes don't match:" + l1 + ", " + l2);
                        return false;
                    }
                    for (int i = 0; i < l1.size(); i++) {
                        Object el1 = l1.get(i);
                        boolean equals = false;
                        for (int j = 0; j < l2.size(); j++) {
                            Object el2 = l2.get(j);
                            if (deepCompare(el1, el2)) {
                                if (i == j) {
                                    System.out.println("Values matched at the same index in collections");
                                } else {
                                    System.out.println("Values matched at the different index in collections");
                                }
                                equals = true;
                                break;
                            }
                        }
                        if (!equals) {
                            return false;
                        }
                    }

                } else if (!deepCompare(v1, v2)) {
                    return false;
                }
            }
        }
    } catch (Exception e) {
        throw new RuntimeException(ExceptionUtils.getFullStackTrace(e));
    }
    return true;
}

From source file:com.bacoder.parser.core.DumpVisitor.java

@Override
public void visitBefore(Node node) {
    String tag = String.format("%s<%s sl=\"%d\" sc=\"%d\" el=\"%d\" ec=\"%d\">\n",
            Strings.repeat(indent, level), node.getClass().getSimpleName(), node.getStartLine(),
            node.getStartColumn(), node.getEndLine(), node.getEndColumn());
    try {/*from  w  w  w.  j  av  a2s.  c om*/
        outputStream.write(tag.getBytes());

        Class<? extends Node> clazz = node.getClass();
        if (clazz.getAnnotation(DumpTextWithToString.class) != null) {
            String property = String.format("%s<text>%s</text>\n", Strings.repeat(indent, level + 1),
                    node.toString());
            try {
                outputStream.write(property.getBytes());
            } catch (IOException e) {
                throw new RuntimeException("Unable to write \'" + property + "\'", e);
            }
        } else {
            Field[] fields = node.getClass().getDeclaredFields();
            for (Field field : fields) {
                Class<?> type = field.getType();
                if (type.isPrimitive() || type.isEnum() || String.class.isAssignableFrom(type)) {
                    String propertyName = field.getName();
                    Object value;
                    try {
                        value = PropertyUtils.getSimpleProperty(node, propertyName);
                        String property = String.format("%s<%s>%s</%s>\n", Strings.repeat(indent, level + 1),
                                propertyName,
                                value == null ? "" : StringEscapeUtils.escapeXml(value.toString()),
                                propertyName);
                        try {
                            outputStream.write(property.getBytes());
                        } catch (IOException e) {
                            throw new RuntimeException("Unable to write \'" + property + "\'", e);
                        }
                    } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
                        // Ignore the field.
                    }
                }
            }
        }
    } catch (IOException e) {
        throw new RuntimeException("Unable to write \'" + tag + "\'", e);
    }
    level++;
}

From source file:com.sqewd.open.dal.core.persistence.db.EntityHelper.java

public static <T extends AbstractEntity> void copyToList(final T source, final T dest,
        final StructAttributeReflect attr) throws Exception {
    Object so = PropertyUtils.getSimpleProperty(source, attr.Field.getName());
    Object to = PropertyUtils.getSimpleProperty(dest, attr.Field.getName());
    if (so == null)
        return;//from w w  w  .j  a v a  2 s .c  o m
    if (to == null)
        throw new Exception("Source List has not been intiialized for Field [" + attr.Column + "]");
    if (!(so instanceof List<?>))
        throw new Exception("Source element [" + attr.Column + "] is not a List");
    if (!(to instanceof List<?>))
        throw new Exception("Target element [" + attr.Column + "] is not a List");
    MethodUtils.invokeMethod(to, "addAll", new Object[] { so });
}

From source file:com.afeng.common.utils.reflection.MyBeanUtils.java

/**
  * ?//  w  w w .j a v  a2 s .c  om
  * ???
  * 
  * @param databean
  * @param tobean
  * @throws NoSuchMethodException
  * copy
  */
public static void copyBeanNotNull2Bean(Object databean, Object tobean) throws Exception {
    PropertyDescriptor origDescriptors[] = PropertyUtils.getPropertyDescriptors(databean);
    for (int i = 0; i < origDescriptors.length; i++) {
        String name = origDescriptors[i].getName();
        //          String type = origDescriptors[i].getPropertyType().toString();
        if ("class".equals(name)) {
            continue; // No point in trying to set an object's class
        }
        if (PropertyUtils.isReadable(databean, name) && PropertyUtils.isWriteable(tobean, name)) {
            try {
                Object value = PropertyUtils.getSimpleProperty(databean, name);
                if (value != null) {
                    copyProperty(tobean, name, value);
                }
            } catch (IllegalArgumentException ie) {
                ; // Should not happen
            } catch (Exception e) {
                ; // Should not happen
            }

        }
    }
}

From source file:com.eryansky.common.utils.reflection.MyBeanUtils.java

/**
  * ?/* ww  w . j  a  v  a  2s.c o  m*/
  * ???
  * 
  * @param databean
  * @param tobean
  * @throws NoSuchMethodException
  * copy
  */
public static void copyBeanNotNull2Bean(Object databean, Object tobean) throws Exception {
    PropertyDescriptor origDescriptors[] = PropertyUtils.getPropertyDescriptors(databean);
    for (int i = 0; i < origDescriptors.length; i++) {
        String name = origDescriptors[i].getName();
        //          String type = origDescriptors[i].getPropertyType().toString();
        if ("class".equals(name)) {
            continue; // No point in trying to set an object's class
        }
        if (PropertyUtils.isReadable(databean, name) && PropertyUtils.isWriteable(tobean, name)) {
            try {
                Object value = PropertyUtils.getSimpleProperty(databean, name);
                if (value != null) {
                    copyProperty(tobean, name, value);
                }
            } catch (java.lang.IllegalArgumentException ie) {
                ; // Should not happen
            } catch (Exception e) {
                ; // Should not happen
            }

        }
    }
}

From source file:com.sqewd.open.dal.api.persistence.AbstractEntity.java

@Override
public String toString() {
    StringBuffer buff = new StringBuffer("\n");
    try {//from   ww w.  j av  a 2s.  com
        StructEntityReflect enref = ReflectionUtils.get().getEntityMetadata(this.getClass());
        buff.append("[ENTITY:").append(enref.Entity).append("(").append(enref.Class).append(")");
        for (StructAttributeReflect attr : enref.Attributes) {
            buff.append("\n\t[").append(attr.Column).append(":")
                    .append(PropertyUtils.getSimpleProperty(this, attr.Field.getName())).append("]");
        }
        buff.append("\n]");
    } catch (Exception e) {
        buff.append(e.getLocalizedMessage());
    }
    return buff.toString();
}

From source file:com.ms.commons.lang.RangeBuilder.java

public Range range() {
    for (Object obj : data) {
        try {/*  w  w  w.ja v  a  2  s. c  o m*/
            // 
            Object value = PropertyUtils.getSimpleProperty(obj, property);
            values.add(value);
        } catch (Exception e) {
            throw new RuntimeException(
                    ToStringBuilder.reflectionToString(obj) + "has not property named " + property, e);
        }
    }
    Object[] range = _range(asc, values);
    return new Range(keyName, range[0], range[1]);
}

From source file:com.bstek.dorado.config.xml.CollectionToPropertyParser.java

@SuppressWarnings({ "unchecked", "rawtypes" })
public void execute(Object object, CreationContext context) throws Exception {
    Collection collection = null;
    boolean useNativeProperty = false, isDefinition = false, shouldSetCollection = false;
    if (object instanceof Definition) {
        isDefinition = true;/*from w w  w  . j  av  a 2  s . c o m*/
        try {
            useNativeProperty = Collection.class
                    .isAssignableFrom(PropertyUtils.getPropertyType(object, property));
        } catch (Exception e) {
            // do nothing
        }

        if (!useNativeProperty) {
            collection = (Collection) ((Definition) object).getProperty(property);
            if (collection == null) {
                collection = new DefinitionSupportedList();
                shouldSetCollection = true;
            }
        }
    } else {
        useNativeProperty = true;
    }

    if (useNativeProperty) {
        collection = (Collection) PropertyUtils.getSimpleProperty(object, property);
        if (collection == null) {
            if (List.class.isAssignableFrom(PropertyUtils.getPropertyType(object, property))) {
                collection = new ArrayList();
            } else {
                collection = new HashSet();
            }
            shouldSetCollection = true;
        }
    }

    if (collection != null) {
        if (isDefinition) {
            for (Object element : elements) {
                if (element instanceof Operation) {
                    if (element instanceof DefinitionInitOperation) {
                        ((DefinitionInitOperation) element).execute(object, context);
                    } else {
                        ((Definition) object).addInitOperation((Operation) element);
                    }
                } else {
                    collection.add(element);
                }
            }
        } else {
            collection.addAll(elements);
        }

        if (shouldSetCollection && !collection.isEmpty()) {
            if (useNativeProperty) {
                PropertyUtils.setSimpleProperty(object, property, collection);
            } else {
                ((Definition) object).setProperty(property, collection);
            }
        }
    }
}

From source file:com.sqewd.open.dal.core.persistence.db.EntityHelper.java

public static <T extends AbstractEntity> Object createListInstance(final AbstractEntity entity,
        final StructAttributeReflect attr) throws Exception {
    Object vo = PropertyUtils.getSimpleProperty(entity, attr.Field.getName());
    if (vo == null) {
        vo = new ArrayList<T>();
        PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), vo);
    }/*from ww  w.j a  v a2  s . c  om*/
    return vo;
}