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:org.tequila.model.JMetaPojoTest.java

/**
 * Simula como lo haria el template engine
 *//*  ww w  .ja va 2 s .c  om*/
public void testJMetaPojo() throws Exception {
    MyBean b = new MyBean();
    b.setNombre("iberck");

    //        JMetaPojo metaClass = new JMetaPojo("org.tequila.model.MyBean");
    JMetaPojo metaClass = new JMetaPojo(b);
    metaClass.injectPojoProperty("edad", 5);

    // obtener un objeto inyectado
    Object injectedObject = metaClass.createInjectedObject();

    // test de la inyeccion del objeto
    Object clazz = PropertyUtils.getNestedProperty(injectedObject, "class.simpleName");
    assertEquals("MyBean", clazz);

    Object[] declFields = (Object[]) PropertyUtils.getNestedProperty(injectedObject, "class.declaredFields");
    assertEquals("Object[]", declFields.getClass().getSimpleName());

    // test de las propiedades originales del objeto
    assertEquals("iberck", PropertyUtils.getNestedProperty(injectedObject, "nombre"));
    assertEquals("default_value", PropertyUtils.getNestedProperty(injectedObject, "cadenaConValor"));
    assertEquals("5", PropertyUtils.getNestedProperty(injectedObject, "edad").toString());

    // test con el nombre de la clase
    JMetaPojo metaClassName = new JMetaPojo("org.tequila.model.MyBean");

    metaClassName.injectPojoProperty("estatura", 23.4f);

    Object injObj = metaClassName.createInjectedObject();

    // es de tipo object ya que no se esta tomando de una instancia si no de la clase y como no tiene valor por default, es object
    assertEquals("java.lang.Object", PropertyUtils.getNestedProperty(injObj, "nombre").getClass().getName());
    assertNotNull(PropertyUtils.getNestedProperty(injObj, "nombre"));

    assertEquals("java.lang.String",
            PropertyUtils.getNestedProperty(injObj, "cadenaConValor").getClass().getName());
    assertEquals("default_value", PropertyUtils.getNestedProperty(injObj, "cadenaConValor"));

    assertEquals("java.lang.Float", PropertyUtils.getNestedProperty(injObj, "estatura").getClass().getName());
    assertEquals(23.4f, PropertyUtils.getNestedProperty(injObj, "estatura"));

    // reinjectar y probar
    metaClassName.injectPojoProperty("otraPropiedad", "val");
    injObj = metaClassName.createInjectedObject();

    // valores viejos
    assertEquals("java.lang.Object", PropertyUtils.getNestedProperty(injObj, "nombre").getClass().getName());
    assertNotNull(PropertyUtils.getNestedProperty(injObj, "nombre"));
    assertEquals("java.lang.String",
            PropertyUtils.getNestedProperty(injObj, "cadenaConValor").getClass().getName());
    assertEquals("default_value", PropertyUtils.getNestedProperty(injObj, "cadenaConValor"));
    assertEquals("java.lang.Float", PropertyUtils.getNestedProperty(injObj, "estatura").getClass().getName());
    assertEquals(23.4f, PropertyUtils.getNestedProperty(injObj, "estatura"));

    // nuevo valor inyectado
    assertEquals("java.lang.String",
            PropertyUtils.getNestedProperty(injObj, "otraPropiedad").getClass().getName());
    assertEquals("val", PropertyUtils.getNestedProperty(injObj, "otraPropiedad"));
}

From source file:org.tequila.model.JMetaPojoTest.java

public void testJMetaPojoInjectedField() throws Exception {
    JMetaPojo metaClass = new JMetaPojo("org.tequila.model.MyBean");

    metaClass.injectFieldProperty("nombre", "pref", "nom");
    Object injObj = metaClass.createInjectedObject();

    Object nombreNP = PropertyUtils.getNestedProperty(injObj, "nombre");
    // metapojo por que es un metafield
    assertEquals("JMetaPojo", nombreNP.getClass().getSimpleName());
    Object prefNp = PropertyUtils.getNestedProperty(nombreNP, "pref");
    assertEquals("nom", prefNp);

    Object nombrePreNP = PropertyUtils.getNestedProperty(injObj, "nombre.pref");
    assertEquals("java.lang.String", nombrePreNP.getClass().getName());
    assertEquals("nom", nombrePreNP);

    Object[] decFields = (Object[]) PropertyUtils.getNestedProperty(injObj, "class.declaredFields");
    assertNotNull(decFields);//from  w w  w . ja  v a2 s  .c o m
}

From source file:org.webguitoolkit.ui.controls.util.PropertyAccessor.java

/**
 * lets see if this is a we want to access a tree
 * attribute may be specified in dot notation "obj1.att2"
 * that means that we need to get the object1 first then get the attribute
 * @return//w  w w . ja  v a 2s  .c om
 */
public static Object retrieveProperty(Object data, String att) {
    if (StringUtils.isBlank(att)) {
        throw new WGTException("Trying to access empty property in Bean Class " + data.getClass().getName());
    }
    if (data instanceof IDataBag) { // dataobject wants to do retrieving itself?
        return ((IDataBag) data).getObject(att);
    }
    try {
        return PropertyUtils.getNestedProperty(data, att);
    } catch (NestedNullException nne) {
        return null; // if there is a bean null on the way to the property, just display as null.
    } catch (NoSuchMethodException e) {
        Logger.getLogger(PropertyAccessor.class).warn("Warning: The property '" + att
                + "' does not exist in Bean Class " + data.getClass().getName());
        return null; // the attribute does not exist
    } catch (Exception e) {
        throw new WGTException(
                "Exception while trying to retrieve: " + att + " from class " + data.getClass().getName(), e);
    }
}

From source file:org.yes.cart.bulkexport.csv.impl.CsvExportTupleImpl.java

private Object getObjectValue(final ExportColumn column) {
    final String property = column.getName();
    Object rawValue = null;//from ww  w . j a v  a  2 s. c o  m
    try {
        rawValue = PropertyUtils.getNestedProperty(getData(), property);
    } catch (Exception exp) {
        LOG.error("Unable to read property: " + property, exp);
    }
    return rawValue;
}

From source file:strutter.view.tag.CSelectTag.java

@Override
public void doSemanticAction() throws ParserException {
    String attname = this.getAttribute("name");

    try {/* w w w  .  ja v  a 2s .  c o  m*/
        if (attname != null && this.getAttribute("nofill") == null) {
            List sellist;

            // aktuelle Auswahl ermitteln
            // String[] sel = BeanUtils.getArrayProperty(form,
            // this.getAttribute("name"));
            String[] sel = TagHelper.getFormValues(form, attname);

            if (sel == null) {
                sellist = new ArrayList();
            } else {
                sellist = Arrays.asList(sel);
            }

            // Stringdaten beginnen mit dem value in option
            // value:optiontext
            boolean hasvalue = this.getAttribute("hasvalue") != null;
            /*
             * // ID der Liste ermitteln (Option mit id Attribut) NodeList
             * list = this.children.extractAllNodesThatMatch( new AndFilter
             * ( new NodeClassFilter (OptionTag.class), new
             * HasAttributeFilter ("id")));
             */

            // alle optionen ermitteln
            NodeList list = this.children.extractAllNodesThatMatchClass(OptionTag.class);

            // Alle bestehenden optionen lschen
            this.getChildren().removeAll();

            for (int i = 0; i < list.size(); i++) {
                OptionTag optionTag = (OptionTag) list.elementAt(i);

                String name = optionTag.getAttribute("values");

                if (name == null) {
                    name = optionTag.getAttribute("id");
                }

                if (name != null) {
                    // in Session, Request suchen
                    Object listvalues = Utils.getObject((HttpServletRequest) request, name);
                    if (listvalues == null) {
                        // in Form suchen
                        // System.out.println("options: " +
                        // ((OptionTag)list.elementAt(0)).getAttribute("id"));
                        listvalues = PropertyUtils.getNestedProperty(form, name);
                    }

                    if (listvalues instanceof ArrayList) {
                        generateOptionFrom((ArrayList) listvalues, sellist, hasvalue);
                    } else if (listvalues instanceof String[]) {
                        generateOptionFrom((String[]) listvalues, sellist, hasvalue);
                    } else if (listvalues instanceof LabelValueBean[]) {
                        generateOptionFrom((LabelValueBean[]) listvalues, sellist);
                    } else if (listvalues instanceof Map) {
                        generateOptionFrom((Map) listvalues, sellist);
                    }
                } else {
                    generateOption(optionTag.getChildrenHTML(), optionTag.getValue(),
                            optionTag.getAttribute("class"), optionTag.getAttribute("style"), sellist);
                }
            }
        }
    } catch (Exception e) {
        System.out.println(attname);
        // if anything throws an exception, stop processing and return
        // control to the caller.
        e.printStackTrace();
    }
}

From source file:us.mn.state.health.lims.taglib.OptionsCollectionTag.java

/**
 * Process the start of this tag.// www  . ja  v a 2 s. c  o  m
 * 
 * @exception JspException
 *                if a JSP exception has occurred
 */
public int doStartTag() throws JspException {
    // Acquire the select tag we are associated with
    SelectTag selectTag = (SelectTag) pageContext.getAttribute(Constants.SELECT_KEY);

    if (selectTag == null) {
        JspException e = new JspException(messages.getMessage("optionsCollectionTag.select"));
        TagUtils.getInstance().saveException(pageContext, e);
        throw e;
    }

    // Acquire the collection containing our options
    Object collection = TagUtils.getInstance().lookup(pageContext, name, property, null);

    if (collection == null) {
        JspException e = new JspException(messages.getMessage("optionsCollectionTag.collection"));
        TagUtils.getInstance().saveException(pageContext, e);
        throw e;
    }

    // Acquire an iterator over the options collection
    Iterator iter = getIterator(collection);

    //bugzilla 2154
    LogEvent.logDebug("OptionsCollectionTag", "doStartTag()", "Filter Properties = " + filterProperty);
    LogEvent.logDebug("OptionsCollectionTag", "doStartTag()", "Filter Values = " + filterValue);

    StringBuffer sb = new StringBuffer();

    if (isAllowEdits() && isShowDefault()) {
        addOption(sb, "", "", false);
    }

    boolean first = true;

    // Render the options
    while (iter.hasNext()) {

        Object bean = iter.next();
        // Get the label for this option
        Object beanLabel = getProperty(bean, label);
        // Get the value for this option
        Object beanValue = getProperty(bean, value);

        String stringLabel = beanLabel.toString();
        String stringValue = beanValue.toString();

        boolean filterOkay = true;
        boolean matchOkay = true;
        Object beanFilter;
        // We only check the filter and match properties if the current
        // option is NOT a match.
        if (!selectTag.isMatched(stringValue)) {
            if (filterProperties != null) {
                for (int i = 0; i < filterProperties.length; ++i) {
                    try {
                        //bugzilla 2154
                        LogEvent.logDebug("OptionsCollectionTag", "doStartTag()",
                                "Checking filter: " + filterValues[i]);
                        beanFilter = PropertyUtils.getNestedProperty(bean, filterProperties[i]);
                        //bugzilla 2154
                        LogEvent.logDebug("OptionsCollectionTag", "doStartTag()",
                                "Bean property: " + beanFilter.toString());
                    } catch (Exception e) {
                        //bugzilla 2154
                        LogEvent.logError("OptionsCollectionTag", "doStartTag()", e.toString());
                        throw new JspException("Failed to retrieve property from bean.", e);
                    }
                    if (beanFilter != null && beanFilter.toString().equals(filterValues[i])) {
                        //bugzilla 2154
                        LogEvent.logDebug("OptionsCollectionTag", "doStartTag()",
                                "Filter failed for " + filterProperties[i] + ".");
                        // Filter failed, so break
                        filterOkay = false;
                        break;
                    }
                }
            }

            if (matchProperties != null) {
                for (int i = 0; i < matchProperties.length; ++i) {
                    try {
                        //bugzilla 2154
                        LogEvent.logDebug("OptionsCollectionTag", "doStartTag()",
                                "Checking filter: " + matchProperties[i] + "!=" + matchValues[i]);

                        beanFilter = PropertyUtils.getNestedProperty(bean, matchProperties[i]);
                        //bugzilla 2154
                        LogEvent.logDebug("OptionsCollectionTag", "doStartTag()",
                                "Bean property: " + matchProperties[i] + "=" + beanFilter.toString());
                    } catch (Exception e) {
                        //bugzilla 2154
                        LogEvent.logError("OptionsCollectionTag", "doStartTag()", e.toString());
                        throw new JspException("Failed to retrieve property from bean.", e);
                    }

                    if (beanFilter != null && !beanFilter.toString().equals(matchValues[i])) {
                        //bugzilla 2154
                        LogEvent.logDebug("OptionsCollectionTag", "doStartTag()",
                                "Match failed for " + matchProperties[i] + ".");
                        // Match failed, so break
                        matchOkay = false;
                        break;
                    }
                }
            }
        }

        if (filterOkay && matchOkay) {
            //bugzilla 2154
            LogEvent.logDebug("OptionsCollectionTag", "doStartTag()",
                    "In OptionsTag label = " + stringLabel + " value = " + stringValue);

            if (isAllowEdits()) {
                addOption(sb, stringLabel, stringValue, selectTag.isMatched(stringValue));
            } else {
                //bugzilla 2154
                LogEvent.logDebug("OptionsCollectionTag", "doStartTag()",
                        "In OptionsTag is matched = " + selectTag.isMatched(stringValue));
                if (selectTag.isMatched(stringValue)) {
                    if (!first) {
                        stringLabel = ", " + stringLabel;
                    }
                    first = false;
                    if (getStyleClass() != null) {
                        stringLabel = "<span class=" + getStyleClass() + ">" + stringLabel + "</span>";
                    }
                    sb.append(stringLabel);
                    sb.append("\r\n<INPUT type=\"hidden\"  name=\"" + selectTag.getProperty() + "\""
                            + " value=\"" + stringValue + "\"" + ">");
                }
            }
        }
    }
    //bugzilla 2154
    LogEvent.logDebug("OptionsCollectionTag", "doStartTag()", "In OptionsTag output = " + sb.toString());

    // Render this element to our writer
    TagUtils.getInstance().write(pageContext, sb.toString());

    return SKIP_BODY;
}

From source file:us.mn.state.health.lims.taglib.SortableOptionsCollectionTag.java

/**
 * Process the start of this tag./*  ww w .  j  a  v  a 2  s.  c  om*/
 * 
 * @exception JspException
 *                if a JSP exception has occurred
 */
public int doStartTag() throws JspException {
    // Acquire the select tag we are associated with
    SelectTag selectTag = (SelectTag) pageContext.getAttribute(Constants.SELECT_KEY);

    if (selectTag == null) {
        JspException e = new JspException(messages.getMessage("optionsCollectionTag.select"));
        TagUtils.getInstance().saveException(pageContext, e);
        throw e;
    }

    // Acquire the collection containing our options
    Object collection = TagUtils.getInstance().lookup(pageContext, name, property, null);

    if (collection == null) {
        JspException e = new JspException(messages.getMessage("optionsCollectionTag.collection"));
        TagUtils.getInstance().saveException(pageContext, e);
        throw e;
    }

    // Acquire an iterator over the options collection
    Iterator iter = getIterator(collection);

    if (log.isDebugEnabled()) {
        log.debug("Filter Properties = " + filterProperty);
    }
    if (log.isDebugEnabled()) {
        log.debug("Filter Values = " + filterValue);
    }

    StringBuffer sb = new StringBuffer();

    if (isAllowEdits() && isShowDefault()) {
        addOption(sb, "", "", false, "", "", "");
    }

    boolean first = true;

    // Render the options
    while (iter.hasNext()) {

        Object bean = iter.next();
        // Get the label for this option
        Object beanLabel = getProperty(bean, label);
        // Get the value for this option
        Object beanValue = getProperty(bean, value);

        Object beanSortFieldA = getProperty(bean, sortFieldA);

        Object beanSortFieldB = getProperty(bean, sortFieldB);

        Object beanAlternateLabel = getProperty(bean, alternateLabel);

        String stringLabel = beanLabel.toString();
        String stringValue = beanValue.toString();
        String stringSortFieldA = beanSortFieldA.toString();
        String stringSortFieldB = beanSortFieldB.toString();
        String stringAlternateLabel = beanAlternateLabel.toString();

        boolean filterOkay = true;
        boolean matchOkay = true;
        Object beanFilter;
        // We only check the filter and match properties if the current
        // option is NOT a match.
        if (!selectTag.isMatched(stringValue)) {
            if (filterProperties != null) {
                for (int i = 0; i < filterProperties.length; ++i) {
                    try {
                        log.debug("Checking filter: " + filterProperties[i] + "=" + filterValues[i]);
                        beanFilter = PropertyUtils.getNestedProperty(bean, filterProperties[i]);
                        log.debug("Bean property: " + filterProperties[i] + "=" + beanFilter.toString());
                    } catch (Exception e) {
                        throw new JspException("Failed to retrieve property from bean.", e);
                    }
                    if (beanFilter != null && beanFilter.toString().equals(filterValues[i])) {
                        log.debug("Filter failed for " + filterProperties[i] + ".");
                        // Filter failed, so break
                        filterOkay = false;
                        break;
                    }
                }
            }

            if (matchProperties != null) {
                for (int i = 0; i < matchProperties.length; ++i) {
                    try {
                        log.debug("Checking filter: " + matchProperties[i] + "!=" + matchValues[i]);
                        beanFilter = PropertyUtils.getNestedProperty(bean, matchProperties[i]);
                        log.debug("Bean property: " + matchProperties[i] + "=" + beanFilter.toString());
                    } catch (Exception e) {
                        throw new JspException("Failed to retrieve property from bean.", e);
                    }

                    if (beanFilter != null && !beanFilter.toString().equals(matchValues[i])) {
                        log.debug("Match failed for " + matchProperties[i] + ".");
                        // Match failed, so break
                        matchOkay = false;
                        break;
                    }
                }
            }
        }

        if (filterOkay && matchOkay) {

            if (log.isDebugEnabled()) {
                log.debug("In OptionsTag label = " + stringLabel + " value = " + stringValue);
            }

            if (isAllowEdits()) {
                addOption(sb, stringLabel, stringValue, selectTag.isMatched(stringValue), stringSortFieldA,
                        stringSortFieldB, stringAlternateLabel);
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("In OptionsTag is matched = " + selectTag.isMatched(stringValue));
                }
                if (selectTag.isMatched(stringValue)) {
                    if (!first) {
                        stringLabel = ", " + stringLabel;
                    }
                    first = false;
                    if (getStyleClass() != null) {
                        stringLabel = "<span class=" + getStyleClass() + ">" + stringLabel + "</span>";
                    }
                    sb.append(stringLabel);
                    sb.append("\r\n<INPUT type=\"hidden\"  name=\"" + selectTag.getProperty() + "\""
                            + " value=\"" + stringValue + "\"" + ">");
                }
            }
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("In OptionsTag output = " + sb.toString());
    }

    // Render this element to our writer
    TagUtils.getInstance().write(pageContext, sb.toString());

    return SKIP_BODY;
}