Example usage for org.apache.commons.beanutils MethodUtils invokeExactMethod

List of usage examples for org.apache.commons.beanutils MethodUtils invokeExactMethod

Introduction

In this page you can find the example usage for org.apache.commons.beanutils MethodUtils invokeExactMethod.

Prototype

public static Object invokeExactMethod(Object object, String methodName, Object[] args)
        throws NoSuchMethodException, IllegalAccessException, InvocationTargetException 

Source Link

Document

Invoke a method whose parameter types match exactly the object types.

This uses reflection to invoke the method obtained from a call to #getAccessibleMethod .

Usage

From source file:net.sf.infrared.web.util.BeanComparator.java

public int compare(Object o1, Object o2) {
    Object fieldOne = null;//from  w  w w . j  a  v a2s.  com
    Object fieldTwo = null;
    try {
        fieldOne = MethodUtils.invokeExactMethod(o1, methodName, null);
        fieldTwo = MethodUtils.invokeExactMethod(o2, methodName, null);
    } catch (NoSuchMethodException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    } catch (IllegalArgumentException e) {
        throw new RuntimeException(e);
    } catch (InvocationTargetException e) {
        throw new RuntimeException(e);
    }

    if (fieldOne != null && fieldTwo != null && fieldOne.getClass().equals(fieldTwo.getClass())
            && fieldOne instanceof Comparable && fieldTwo instanceof Comparable) {
        int retValue = ((Comparable) fieldOne).compareTo(fieldTwo);
        return (ascending ? retValue : (retValue * -1));
    } else {
        throw new IllegalArgumentException(
                "Error comparing object " + o1.toString() + " with " + o2.toString());
    }
}

From source file:fr.isima.reflexbench.architecture.ApacheReflect.java

@Override
public void invokeMethod(Object obj) {
    String methodToSearch = ((SampleSourceCode) obj).getSearchingMethod();
    try {// w ww . ja v  a 2s .  c om
        MethodUtils.invokeExactMethod(obj, methodToSearch, null);
    } catch (NoSuchMethodException ex) {
        Logger.getLogger(ApacheReflect.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        Logger.getLogger(ApacheReflect.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvocationTargetException ex) {
        Logger.getLogger(ApacheReflect.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.fengduo.bee.commons.core.lang.CollectionUtils.java

private static <K extends Number, V extends Object> Map<K, V> toNumberMap(Collection<V> values, String property,
        Number keyValue) {/*from w  ww  .jav  a2s  .  c o m*/
    if (values == null) {
        return Collections.emptyMap();
    }
    Map<K, V> valueMap = new HashMap<K, V>(values.size());
    for (V value : values) {
        try {
            String keyValueStr = BeanUtils.getProperty(value, property);
            if (NumberUtils.isNumber(keyValueStr)) {
                try {
                    // K valueTypeInstance = keyType.newInstance();
                    Object key = MethodUtils.invokeExactMethod(keyValue, "valueOf", keyValueStr);
                    valueMap.put((K) key, value);
                } catch (Exception e) {
                    throw new IllegalArgumentException("Unsupport key Type" + keyValue.getClass().getName(),
                            e);
                }
            } else {
                throw new IllegalArgumentException(
                        "Expect" + keyValue.getClass().getName() + ",Value Actul is " + keyValueStr);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new RuntimeException(e);
        }
    }
    return valueMap;
}

From source file:com.qcadoo.customTranslation.internal.CustomTranslationManagementServiceImpl.java

private Session getCurrentSession(final DataDefinition dataDefinition) {
    Object dataAccessService = FieldUtils.getProtectedFieldValue("dataAccessService", dataDefinition);
    Object hibernateService = FieldUtils.getProtectedFieldValue("hibernateService", dataAccessService);

    try {//from  w  w w  .  ja va 2 s  . co m
        return (Session) MethodUtils.invokeExactMethod(hibernateService, "getCurrentSession", new Object[0]);
    } catch (NoSuchMethodException e) {
        throw new IllegalStateException(e.getMessage(), e);
    } catch (IllegalAccessException e) {
        throw new IllegalStateException(e.getMessage(), e);
    } catch (InvocationTargetException e) {
        throw new IllegalStateException(e.getMessage(), e);
    }
}

From source file:com.qcadoo.customTranslation.internal.CustomTranslationManagementServiceImpl.java

private Object getInstanceForEntity(final DataDefinition dataDefinition) {
    try {/*from   w w w  . j a v  a  2 s .  c  o m*/
        return MethodUtils.invokeExactMethod(dataDefinition, "getInstanceForEntity", new Object[0]);
    } catch (NoSuchMethodException e) {
        throw new IllegalStateException(e.getMessage(), e);
    } catch (IllegalAccessException e) {
        throw new IllegalStateException(e.getMessage(), e);
    } catch (InvocationTargetException e) {
        throw new IllegalStateException(e.getMessage(), e);
    }
}

From source file:com.googlecode.jtiger.modules.ecside.view.html.CalcBuilder.java

public boolean defaultCalcLayout() {
    boolean hasCalc = false;
    Column calcColumn = model.getColumnHandler().getFirstCalcColumn();
    if (calcColumn == null) {
        return hasCalc;
    }//from www .  j  a v  a  2s.  c om

    String layout = model.getPreferences().getPreference(PreferencesConstants.DEFAULT_CALC_LAYOUT);

    try {
        MethodUtils.invokeExactMethod(this, layout, null);
        hasCalc = true;
        ;
    } catch (Exception e) {
        logger.error("There is no method with the layout [" + layout + "].", e);
    }
    return hasCalc;
}

From source file:com.ultrapower.eoms.common.plugin.ecside.view.html.CalcBuilder.java

public boolean defaultCalcLayout() {
   boolean hasCalc=false;
    Column calcColumn = model.getColumnHandler().getFirstCalcColumn();
    if (calcColumn == null) {
        return hasCalc;
    }/*from   w w  w. j  ava  2  s.c  o m*/

    String layout = model.getPreferences().getPreference(PreferencesConstants.DEFAULT_CALC_LAYOUT);
        
    try {
       MethodUtils.invokeExactMethod(this, layout, null);
       hasCalc=true;;
    } catch (Exception e) {
        logger.error("There is no method with the layout [" + layout + "].", e);
    }
    return hasCalc;
}

From source file:info.magnolia.content2bean.impl.Content2BeanTransformerImpl.java

/**
 * Do not set class property. In case of a map/collection try to use adder method.
 *//*from w  w  w  .  j av  a 2s . co m*/
@Override
public void setProperty(TypeMapping mapping, TransformationState state, PropertyTypeDescriptor descriptor,
        Map<String, Object> values) {
    String propertyName = descriptor.getName();
    if (propertyName.equals("class")) {
        return;
    }
    Object value = values.get(propertyName);
    Object bean = state.getCurrentBean();

    if (propertyName.equals("content") && value == null) {
        value = new SystemContentWrapper(state.getCurrentContent());
    } else if (propertyName.equals("name") && value == null) {
        value = state.getCurrentContent().getName();
    } else if (propertyName.equals("className") && value == null) {
        value = values.get("class");
    }

    // do no try to set a bean-property that has no corresponding node-property
    // else if (!values.containsKey(propertyName)) {
    if (value == null) {
        return;
    }

    log.debug("try to set {}.{} with value {}", new Object[] { bean, propertyName, value });

    // if the parent bean is a map, we can't guess the types.
    if (!(bean instanceof Map)) {
        try {
            PropertyTypeDescriptor dscr = mapping.getPropertyTypeDescriptor(bean.getClass(), propertyName);
            if (dscr.getType() != null) {

                // try to use an adder method for a Collection property of the bean
                if (dscr.isCollection() || dscr.isMap()) {
                    log.debug("{} is of type collection, map or /array", propertyName);
                    Method method = dscr.getAddMethod();

                    if (method != null) {
                        log.debug("clearing the current content of the collection/map");
                        try {
                            Object col = PropertyUtils.getProperty(bean, propertyName);
                            if (col != null) {
                                MethodUtils.invokeExactMethod(col, "clear", new Object[] {});
                            }
                        } catch (Exception e) {
                            log.debug("no clear method found on collection {}", propertyName);
                        }

                        Class<?> entryClass = dscr.getCollectionEntryType().getType();

                        log.debug("will add values by using adder method {}", method.getName());
                        for (Iterator<Object> iter = ((Map<Object, Object>) value).keySet().iterator(); iter
                                .hasNext();) {
                            Object key = iter.next();
                            Object entryValue = ((Map<Object, Object>) value).get(key);
                            entryValue = convertPropertyValue(entryClass, entryValue);
                            if (entryClass.isAssignableFrom(entryValue.getClass())) {
                                if (dscr.isCollection()) {
                                    log.debug("will add value {}", entryValue);
                                    method.invoke(bean, new Object[] { entryValue });
                                }
                                // is a map
                                else {
                                    log.debug("will add key {} with value {}", key, entryValue);
                                    method.invoke(bean, new Object[] { key, entryValue });
                                }
                            }
                        }

                        return;
                    }
                    log.debug("no add method found for property {}", propertyName);
                    if (dscr.isCollection()) {
                        log.debug("transform the values to a collection", propertyName);
                        value = ((Map<Object, Object>) value).values();
                    }
                } else {
                    value = convertPropertyValue(dscr.getType().getType(), value);
                }
            }
        } catch (Exception e) {
            // do it better
            log.error("Can't set property [{}] to value [{}] in bean [{}] for node {} due to {}",
                    new Object[] { propertyName, value, bean.getClass().getName(),
                            state.getCurrentContent().getHandle(), e.toString() });
            log.debug("stacktrace", e);
        }
    }

    try {
        // This uses the converters registered in beanUtilsBean.convertUtilsBean (see constructor of this class)
        // If a converter is registered, beanutils will convert value.toString(), not the value object as-is.
        // If no converter is registered, then the value Object is set as-is.
        // If convertPropertyValue() already converted this value, you'll probably want to unregister the beanutils
        // converter.
        // some conversions like string to class. Performance of PropertyUtils.setProperty() would be better
        beanUtilsBean.setProperty(bean, propertyName, value);

        // TODO this also does things we probably don't want/need, i.e nested and indexed properties

    } catch (Exception e) {
        // do it better
        log.error("Can't set property [{}] to value [{}] in bean [{}] for node {} due to {}",
                new Object[] { propertyName, value, bean.getClass().getName(),
                        state.getCurrentContent().getHandle(), e.toString() });
        log.debug("stacktrace", e);
    }

}

From source file:com.fengduo.bee.commons.core.lang.CollectionUtils.java

private static <T extends Number> List<T> getProperty(Collection<?> values, String property, T rawValue) {
    if (values == null || values.isEmpty()) {
        return Collections.<T>emptyList();
    }/* w ww.j  av a  2s . c  om*/
    List<T> result = new ArrayList<T>(values.size());
    for (Object value : values) {
        try {
            String propertyValue = value.toString();
            if (property != null) {
                propertyValue = BeanUtils.getProperty(value, property);
            }
            Object key = MethodUtils.invokeExactMethod(rawValue, "valueOf", propertyValue);
            result.add((T) key);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            continue;
        }
    }
    return result;
}

From source file:info.magnolia.jcr.node2bean.impl.Node2BeanTransformerImpl.java

/**
 * @param bean/*from  w w w. ja v  a  2  s.c  o m*/
 * @param propertyName
 */
private void clearCollection(Object bean, String propertyName) {
    log.debug("clearing the current content of the collection/map");
    try {
        Object col = PropertyUtils.getProperty(bean, propertyName);
        if (col != null) {
            MethodUtils.invokeExactMethod(col, "clear", new Object[] {});
        }
    } catch (Exception e) {
        log.debug("no clear method found on collection {}", propertyName);
    }
}