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

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

Introduction

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

Prototype

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

Source Link

Document

Return the value of the (possibly nested) property of the specified name, for the specified bean, with no type conversions.

For more details see PropertyUtilsBean.

Usage

From source file:com.discursive.jccook.bean.NestedPropertyExample.java

private void start() {

    // Create an author
    Author wolfe = new Author("Tom Wolfe", "Green");
    Book theRightStuff = new Book("The Right Stuff", wolfe);

    try {/*from   www . ja va 2  s  . co  m*/
        String bookName = (String) PropertyUtils.getSimpleProperty(theRightStuff, "name");
        String authorName = (String) PropertyUtils.getNestedProperty(theRightStuff, "author.name");

        System.out.println("The book is " + bookName);
        System.out.println("The author is " + authorName);
    } catch (Exception e) {
        System.out.println("There was a problem getting a bean property.");
        e.printStackTrace();
    }

}

From source file:com.conversantmedia.mapreduce.tool.FileInputOutputHandlerTest.java

@Test
public void testParseContext() {
    MyBeanA a = new MyBeanA();
    a.stringA = "IN A";
    a.p = new Path("/a/path");

    MyBeanB b = new MyBeanB();
    b.stringB = "IN B";
    b.p = new Path("/b/path");

    try {//from w  w  w  . j  av a2  s . c o m

        @SuppressWarnings("unchecked")
        Map<String, Object> ctx = PropertyUtils.describe(a);
        ctx.put("context", PropertyUtils.describe(b));

        String value = BeanUtils.getProperty(ctx, "context.stringB");
        System.out.println("VALUE = " + value);

        Object val = PropertyUtils.getNestedProperty(ctx, "stringA");
        System.out.println("Value object is: " + val);

        Object path = PropertyUtils.getNestedProperty(ctx, "path");
        if (path instanceof Path) {
            System.out.println("Got a path: " + path);
        }

        path = PropertyUtils.getNestedProperty(ctx, "context.path");
        if (path instanceof Path) {
            System.out.println("Got a path: " + path);
        }

    } catch (Exception e) {
        fail(e.getMessage());
    }
}

From source file:com.rolex.explore.beanutils.service.BeanUtilsSpecificService.java

public void exploreBeanUtil() {

    SampleBean bean = new SampleBean();

    String property1 = "name";

    String property2 = "currentAddress.city";

    String property3 = "previousAddresses[0].city";

    String property4 = "previousAddresses[3].city";

    String property5 = "vehicleLicenseModel(R60)";

    Place place1 = new Place("Sentosa", "Singapore");
    Place place2 = new Place("Colombo", "Sri Lanka");
    List<Place> places = new ArrayList<Place>();
    places.add(place1);//from   w w  w.  ja v a2s. c  om
    places.add(place2);

    String property6 = "yearlyPlacesVisited(2000)";

    String property7 = "placesVisited";

    String property8 = "placesVisited[0]";

    TourismAward award = new TourismAward("World Award Committee", "USA");

    String property9 = "yearlyPlacesVisited(2000)[0].tourismAwards[0]";

    try {
        PropertyUtils.setSimpleProperty(bean, property1, "Rolex Rolex");
        String value1 = (String) PropertyUtils.getSimpleProperty(bean, property1);
        System.out.println("###Reverse1:   " + value1);

        PropertyUtils.setNestedProperty(bean, property2, "Hoffman Estates");
        String value2 = (String) PropertyUtils.getNestedProperty(bean, property2);
        System.out.println("###Reverse2:   " + value2);

        PropertyUtils.setNestedProperty(bean, property3, "Schaumburg");
        String value3 = (String) PropertyUtils.getNestedProperty(bean, property3);
        System.out.println("###Reverse3:   " + value3);

        PropertyUtils.setNestedProperty(bean, property4, "Des Plaines");
        String value4 = (String) PropertyUtils.getNestedProperty(bean, property4);
        System.out.println("###Reverse4:   " + value4);

        Address[] arrayValue1 = (Address[]) PropertyUtils.getSimpleProperty(bean, "previousAddresses");
        System.out.println("###ReverseArray:   " + Arrays.toString(arrayValue1));

        PropertyUtils.setMappedProperty(bean, property5, "Sonata");
        String value5 = (String) PropertyUtils.getMappedProperty(bean, property5);
        System.out.println("###Reverse5:   " + value5);

        PropertyUtils.setMappedProperty(bean, property6, places);
        List<Place> value6 = (List<Place>) PropertyUtils.getMappedProperty(bean, property6);
        System.out.println("###Reverse6:   " + value6.get(0));

        PropertyUtils.setSimpleProperty(bean, property7, places);
        List<Place> value7 = (List<Place>) PropertyUtils.getSimpleProperty(bean, property7);
        System.out.println("###Reverse7:   " + value7.get(0));

        PropertyUtils.setIndexedProperty(bean, property8, place2);
        Place value8 = (Place) PropertyUtils.getIndexedProperty(bean, property8);
        System.out.println("###Reverse8:   " + value8);

        PropertyUtils.setNestedProperty(bean, property9, award);
        TourismAward value9 = (TourismAward) PropertyUtils.getNestedProperty(bean, property9);
        System.out.println("###Reverse8:   " + value8);

    } catch (IllegalAccessException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:jodtemplate.pptx.preprocessor.PicPreprocessor.java

public Document process(final Map<String, Object> context, final Document document, final Slide slide,
        final Resources resources, final Configuration configuration) throws JODTemplateException {
    final ExpressionHandler expressionHandler = configuration.getExpressionHandler();

    final IteratorIterable<Element> picElements = document
            .getDescendants(Filters.element(PPTXDocument.PIC_ELEMENT, getPresentationmlNamespace()));
    final List<Element> picElementsList = new ArrayList<>();
    while (picElements.hasNext()) {
        picElementsList.add(picElements.next());
    }/* w w  w .j a  v a 2  s  .  c o m*/

    for (Element pic : picElementsList) {
        final Attribute descr = pic.getChild(PPTXDocument.NVPICPR_ELEMENT, getPresentationmlNamespace())
                .getChild(PPTXDocument.CNVPR_ELEMENT, getPresentationmlNamespace())
                .getAttribute(PPTXDocument.DESCR_ATTR);
        if (descr != null && expressionHandler.isExpression(descr.getValue())) {
            final VariableExpression expression = expressionHandler.createVariableExpression(descr.getValue());
            Object value;
            try {
                value = PropertyUtils.getNestedProperty(context, expression.getVariable());
            } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
                throw new JODTemplateException("Unable to get value: " + expression.getVariable());
            }
            if (value instanceof ImageField) {
                final ImageField imageField = (ImageField) value;
                imageService.insertImage(imageField, slide, resources, pic);
            } else {
                throw new JODTemplateException("Field " + expression.getVariable() + " should contain image.");
            }
        }

    }

    return document;
}

From source file:jp.co.opentone.bsol.framework.core.util.PropertyGetUtil.java

public static Object getNestedProperty(Object data, String name) {
    try {/*from   w  w  w  .j a  v  a 2s  .  c o m*/
        if (!name.contains(".")) {
            return PropertyUtils.getProperty(data, name);
        }
        if (name.contains("[")) {
            String[] names = name.split("\\.", 2);
            Object obj = null;
            try {
                obj = PropertyUtils.getIndexedProperty(data, names[0]);
            } catch (NullPointerException npe) {
                // ???null??
                obj = null;
            }
            if (obj == null) {
                return null;
            }
            return getNestedProperty(obj, names[1]);
        }
        try {
            return PropertyUtils.getNestedProperty(data, name);
        } catch (NestedNullException nne) {
            // ?????null??????
            // null?
            return null;
        }
    } catch (Exception e) {
        throw new ApplicationFatalRuntimeException("invalid property : " + name, e);
    }
}

From source file:de.tudarmstadt.ukp.csniper.webapp.evaluation.SortableEvaluationResultDataProvider.java

private void updateView() {
    final SortParam<String> sp = getSort();

    if (!sp.getProperty().equals(lastSortProperty) || (lastSortOrder != sp.isAscending()) || filterChanged) {
        // Apply filter
        if (getFilter() != ResultFilter.ALL) {
            limitedResults = new ArrayList<EvaluationResult>();
            for (EvaluationResult e : results) {
                Mark emark = Mark.fromString(e.getResult());
                switch (getFilter()) {
                case ANNOTATED:
                    if (emark == Mark.CORRECT || emark == Mark.WRONG) {
                        limitedResults.add(e);
                    }//from   w w  w  .ja v  a  2 s.  c  o  m
                    break;
                case TO_CHECK:
                    if (emark == Mark.CHECK) {
                        limitedResults.add(e);
                    }
                    break;
                case TODO:
                    if (StringUtils.isBlank(e.getResult()) || emark == Mark.PRED_CORRECT
                            || emark == Mark.PRED_WRONG) {
                        limitedResults.add(e);
                    }
                    break;
                default:
                    throw new IllegalArgumentException("Unknown filter setting");
                }
            }
        } else {
            limitedResults = results;
        }

        // Apply sorting
        Collections.sort(limitedResults, new Comparator<EvaluationResult>() {
            @SuppressWarnings("rawtypes")
            @Override
            public int compare(EvaluationResult aO1, EvaluationResult aO2) {
                try {
                    Comparable v1 = (Comparable) PropertyUtils.getNestedProperty(aO1, sp.getProperty());
                    Comparable v2 = (Comparable) PropertyUtils.getNestedProperty(aO2, sp.getProperty());

                    if (v1 == null) {
                        if (v2 == null) {
                            return 0;
                        }
                        return sp.isAscending() ? -1 : 1;
                    }
                    if (v2 == null) {
                        return sp.isAscending() ? 1 : -1;
                    }
                    return sp.isAscending() ? v1.compareTo(v2) : v2.compareTo(v1);
                } catch (Exception e) {
                    throw new IllegalStateException(e);
                }
            }
        });

        lastSortProperty = sp.getProperty();
        lastSortOrder = sp.isAscending();
        filterChanged = false;
    }
}

From source file:de.tudarmstadt.ukp.csniper.webapp.statistics.SortableAggregatedEvaluationResultDataProvider.java

private void updateView() {
    final SortParam<String> sp = getSort();

    // filter/* w  ww  . j  a v a2 s  . co m*/
    if (!sp.getProperty().equals(lastSortProperty) || (lastSortOrder != sp.isAscending()) || filterChanged) {
        limitedResults = new ArrayList<AggregatedEvaluationResult>();
        for (AggregatedEvaluationResult aer : aerList) {
            if (getFilters().contains(aer.getClassification())) {
                limitedResults.add(aer);
            }
        }
    }

    // sort
    Collections.sort(limitedResults, new Comparator<AggregatedEvaluationResult>() {
        @SuppressWarnings({ "rawtypes", "unchecked" })
        @Override
        public int compare(AggregatedEvaluationResult aO1, AggregatedEvaluationResult aO2) {
            try {
                Comparable v1 = (Comparable) PropertyUtils.getNestedProperty(aO1, sp.getProperty());
                Comparable v2 = (Comparable) PropertyUtils.getNestedProperty(aO2, sp.getProperty());

                return sp.isAscending() ? v1.compareTo(v2) : v2.compareTo(v1);
            } catch (Exception e) {
                throw new IllegalStateException(e);
            }
        }
    });

    lastSortProperty = sp.getProperty();
    lastSortOrder = sp.isAscending();
    filterChanged = false;
}

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);
                    }//from   w w w .j av  a  2s. co  m
                    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.panemu.tiwulfx.table.BaseColumn.java

/**
 *
 * @param propertyName java bean property name to be used for get/set method
 * using introspection/*from   w w  w  . j a va 2  s . c o m*/
 * @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);
            }
        }
    });

}

From source file:com.agiletec.plugins.jprssaggregator.aps.system.services.converter.ContentBuilder.java

/**
 * Executes a getter method on the target object to retrieve the property
 * @param property the property to get/*from  w  w w  .ja va2  s  .  co m*/
 * @param target the object 
 * @return a string value of the property
 * @throws ApsSystemException
 */
private String extractValue(String property, Object target) throws ApsSystemException {
    String value = "";
    try {
        value = ((String) PropertyUtils.getNestedProperty(target, property)).trim();
    } catch (Throwable t) {
        _logger.error("error in extractValue", t);
    }
    return value;
}