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:ca.sqlpower.matchmaker.swingui.SaveAndOpenWorkspaceActionTest.java

/**
 * Takes two SPObjects and recursively determines if all persistable properties
 * are equal. This is used in testing before-states and after-states for
 * persistence tests./*ww  w  .  j  av  a  2  s.  c  om*/
 */
private boolean checkEquality(SPObject spo1, SPObject spo2) {

    try {
        Set<String> s = TestUtils.findPersistableBeanProperties(spo1, false, false);
        List<PropertyDescriptor> settableProperties = Arrays
                .asList(PropertyUtils.getPropertyDescriptors(spo1.getClass()));

        for (PropertyDescriptor property : settableProperties) {
            @SuppressWarnings("unused")
            Object oldVal;
            if (!s.contains(property.getName()))
                continue;
            if (property.getName().equals("parent"))
                continue; //Changing the parent causes headaches.
            if (property.getName().equals("session"))
                continue;
            if (property.getName().equals("type"))
                continue;
            try {
                oldVal = PropertyUtils.getSimpleProperty(spo1, property.getName());
                // check for a getter
                if (property.getReadMethod() == null)
                    continue;

            } catch (NoSuchMethodException e) {
                logger.debug("Skipping non-settable property " + property.getName() + " on "
                        + spo1.getClass().getName());
                continue;
            }
            Object spo1Property = PropertyUtils.getSimpleProperty(spo1, property.getName());
            Object spo2Property = PropertyUtils.getSimpleProperty(spo2, property.getName());

            assertEquals("Failed to equate " + property.getName() + " on object of type " + spo1.getClass(),
                    spo1Property, spo2Property);
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    // look at children
    Iterator<? extends SPObject> i = (spo1.getChildren().iterator());
    Iterator<? extends SPObject> j = (spo2.getChildren().iterator());
    while (i.hasNext() && j.hasNext()) {
        SPObject ii = i.next();
        SPObject jj = j.next();
        logger.debug("Comparing: " + ii.getClass().getSimpleName() + "," + jj.getClass().getSimpleName());
        checkEquality(ii, jj);
    }
    return (!(i.hasNext() || j.hasNext()));
}

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

public Range range() {
    for (Object obj : data) {
        try {/*from  w ww .  j a v a2  s.  co  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(asc, keyName, range[0], range[1]);
}

From source file:com.roadmap.common.util.ObjectUtil.java

/**
 * Return the value of the specified simple property of the 
 * specified bean, with no type conversions.
 *
 * @param Object object whose property is to be extracted
 * @param String name of the property to be extracted
 * //from   w w  w .  j a  v a  2s  .  co  m
 * @return Object The property value 
 */
@SuppressWarnings("rawtypes")
public static Object getConcatenatedPropertyStringValues(Object vo, String[] props, String sep) {
    Object retVal = null;
    ArrayList<String> stringList = new ArrayList<String>();
    try {
        if (vo instanceof Map) {
            if (vo != null) {
                for (String prop : props) {
                    retVal = ((Map) vo).get(prop);
                    stringList.add(retVal.toString());
                }
            }
        } else {
            for (String prop : props) {
                retVal = PropertyUtils.getSimpleProperty(vo, prop);
                stringList.add(retVal.toString());
            }

        }
    } catch (Exception e) {
        //No need to handle
    }
    return StringUtils.join(stringList, sep);
}

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

public static void copyBean2Map(Map map, Object bean) {
    PropertyDescriptor[] pds = PropertyUtils.getPropertyDescriptors(bean);
    for (int i = 0; i < pds.length; i++) {
        PropertyDescriptor pd = pds[i];
        String propname = pd.getName();
        try {//from ww w.j  av  a2s.  c o m
            Object propvalue = PropertyUtils.getSimpleProperty(bean, propname);
            map.put(propname, propvalue);
        } catch (IllegalAccessException e) {
            //e.printStackTrace();
        } catch (InvocationTargetException e) {
            //e.printStackTrace();
        } catch (NoSuchMethodException e) {
            //e.printStackTrace();
        }
    }
}

From source file:com.feilong.commons.core.bean.BeanUtilTest.java

/**
 * Demo normal java beans.//w w  w  .j a v a 2  s.  c om
 *
 * @throws Exception
 *             the exception
 */
@Test
public void testDemoNormalJavaBeans() throws Exception {

    log.debug(StringUtils.center(" demoNormalJavaBeans ", 40, "="));

    // data setup  
    Address addr1 = new Address("CA1234", "xxx", "Los Angeles", "USA");
    Address addr2 = new Address("100000", "xxx", "Beijing", "China");
    Address[] addrs = new Address[2];
    addrs[0] = addr1;
    addrs[1] = addr2;
    Customer cust = new Customer(123, "John Smith", addrs);

    // accessing the city of first address  
    String cityPattern = "addresses[0].city";
    String name = (String) PropertyUtils.getSimpleProperty(cust, "name");
    String city = (String) PropertyUtils.getProperty(cust, cityPattern);
    Object[] rawOutput1 = new Object[] { "The city of customer ", name, "'s first address is ", city, "." };
    log.debug(StringUtils.join(rawOutput1));

    // setting the zipcode of customer's second address  
    String zipPattern = "addresses[1].zipCode";
    if (PropertyUtils.isWriteable(cust, zipPattern)) {//PropertyUtils  
        log.debug("Setting zipcode ...");
        PropertyUtils.setProperty(cust, zipPattern, "200000");//PropertyUtils  
    }
    String zip = (String) PropertyUtils.getProperty(cust, zipPattern);//PropertyUtils  
    Object[] rawOutput2 = new Object[] { "The zipcode of customer ", name, "'s second address is now ", zip,
            "." };
    log.debug(StringUtils.join(rawOutput2));
}

From source file:it.sample.parser.util.CommonsUtil.java

/**
 * Metodo di utilita' che copia i campi non nulli della classe sorgente in quelli della classe di destinazione
 * /*from w ww.  ja  v  a  2  s. co  m*/
 * @param source
 * @param destination
 */
public static <K, T> void copyNotNullProperties(K source, T destination) {
    PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(source);
    if (descriptors != null) {
        for (PropertyDescriptor descriptor : descriptors) {
            try {
                String propertyName = descriptor.getName();
                Field field = getDeclaredField(propertyName, source.getClass());

                if (field != null && field.getAnnotation(IgnoreField.class) == null) {
                    boolean wasAccessible = field.isAccessible();
                    field.setAccessible(true);

                    if (PropertyUtils.getReadMethod(descriptor) != null) {
                        Object val = PropertyUtils.getSimpleProperty(source, propertyName);
                        if (val != null && descriptor.getWriteMethod() != null) {
                            PropertyUtils.setProperty(destination, propertyName, val);
                        }
                    }
                    field.setAccessible(wasAccessible);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:com.feilong.core.bean.BeanUtilTest.java

/**
 * Demo normal java beans./*from w w  w  .java2s  . c om*/
 *
 * @throws Exception
 *             the exception
 */
@Test
public void testDemoNormalJavaBeans() throws Exception {
    LOGGER.debug(StringUtils.center(" demoNormalJavaBeans ", 40, "="));

    // data setup  
    Customer customer = new Customer(123, "John Smith",
            toArray(new Address("CA1234", "xxx", "Los Angeles", "USA"),
                    new Address("100000", "xxx", "Beijing", "China")));

    // accessing the city of first address  
    String name = (String) PropertyUtils.getSimpleProperty(customer, "name");
    String city = (String) PropertyUtils.getProperty(customer, "addresses[0].city");

    LOGGER.debug(StringUtils
            .join(new Object[] { "The city of customer ", name, "'s first address is ", city, "." }));

    // setting the zipcode of customer's second address  
    String zipPattern = "addresses[1].zipCode";
    if (PropertyUtils.isWriteable(customer, zipPattern)) {//PropertyUtils  
        LOGGER.debug("Setting zipcode ...");
        PropertyUtils.setProperty(customer, zipPattern, "200000");//PropertyUtils  
    }
    String zip = (String) PropertyUtils.getProperty(customer, zipPattern);//PropertyUtils  

    LOGGER.debug(StringUtils
            .join(new Object[] { "The zipcode of customer ", name, "'s second address is now ", zip, "." }));
}

From source file:com.panemu.tiwulfx.form.Form.java

private void updateNestedObject(String joinPropertyName, Object newValue) {
    for (BaseControl control : lstInputControl) {
        if (control.getPropertyName().startsWith(joinPropertyName)
                && !(control.getPropertyName().equals(joinPropertyName))) {
            String childPropertyName = control.getPropertyName().substring(joinPropertyName.length() + 1,
                    control.getPropertyName().length());
            if (newValue != null) {
                try {
                    Object childValue = null;
                    if (!childPropertyName.contains(".")) {
                        childValue = PropertyUtils.getSimpleProperty(newValue, childPropertyName);
                    } else {
                        childValue = PropertyUtils.getNestedProperty(newValue, childPropertyName);
                    }/*  w  w  w. j  a va 2s. c om*/
                    control.setValue(childValue);
                } catch (IllegalArgumentException | IllegalAccessException | InvocationTargetException
                        | NoSuchMethodException ex) {
                    if (ex instanceof IllegalArgumentException) {
                        /**
                         * The actual exception needed to be caught is
                         * org.apache.commons.beanutils.NestedNullException.
                         * But Scene Builder throw
                         * java.lang.ClassNotFoundException:
                         * org.apache.commons.beanutils.NestedNullException
                         * if NestedNullException is referenced in this
                         * class. So I catch its parent instead.
                         */
                        control.setValue(null);
                    } else {
                        throw new RuntimeException(ex);
                    }
                }
            } else {
                control.setValue(null);
            }
        }
    }
}

From source file:com.sun.faces.mock.MockPropertyResolver.java

public Object getValue(Object base, Object property) throws EvaluationException, PropertyNotFoundException {

    if (base == null) {
        throw new NullPointerException();
    }/*from  w  w  w .java  2s  . c  o m*/
    String name = property.toString();
    try {
        if (base instanceof Map) {
            Map map = (Map) base;
            if (map.containsKey(name)) {
                return (map.get(name));
            } else {
                throw new PropertyNotFoundException(name);
            }
        } else {
            return (PropertyUtils.getSimpleProperty(base, name));
        }
    } catch (IllegalAccessException e) {
        throw new EvaluationException(e);
    } catch (InvocationTargetException e) {
        throw new EvaluationException(e.getTargetException());
    } catch (NoSuchMethodException e) {
        throw new PropertyNotFoundException(name);
    }

}

From source file:com.panemu.tiwulfx.table.BaseColumn.java

/**
 *
 * @param propertyName java bean property name to be used for get/set method
 * using introspection//  w ww.j  a v  a2  s . c om
 * @param prefWidth preferred collumn width
 * @param columnHeader column header text. Default equals propertyName. This
 * text is localized
 */
public BaseColumn(String propertyName, double prefWidth, String columnHeader) {
    super(columnHeader);
    setPrefWidth(prefWidth);
    this.propertyName = propertyName;
    //        setCellValueFactory(new PropertyValueFactory<S, T>(propertyName));
    tableCriteria.addListener(new InvalidationListener() {
        @Override
        public void invalidated(Observable observable) {
            if (tableCriteria.get() != null) {
                BaseColumn.this.setGraphic(filterImage);
            } else {
                BaseColumn.this.setGraphic(null);
            }
        }
    });
    setCellValueFactory(new Callback<CellDataFeatures<R, C>, ObservableValue<C>>() {
        private SimpleObjectProperty<C> propertyValue;

        @Override
        public ObservableValue<C> call(CellDataFeatures<R, C> param) {
            /**
             * This code is adapted from {@link PropertyValueFactory#getCellDataReflectively(T)
             */
            try {
                Object cellValue;
                if (getPropertyName().contains(".")) {
                    cellValue = PropertyUtils.getNestedProperty(param.getValue(), getPropertyName());
                } else {
                    cellValue = PropertyUtils.getSimpleProperty(param.getValue(), getPropertyName());
                }
                propertyValue = new SimpleObjectProperty<>((C) cellValue);
                return propertyValue;
            } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException ex) {
                throw new RuntimeException(ex);
            } catch (Exception ex) {
                /**
                 * Ideally it catches
                 * org.apache.commons.beanutils.NestedNullException. However
                 * we need to import apachec bean utils library in FXML file
                 * to be able to display it in Scene Builder. So, I decided
                 * to catch Exception to avoid the import.
                 */
                return new SimpleObjectProperty<>(null);
            }
        }
    });

}