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

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

Introduction

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

Prototype

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

Source Link

Document

Return the value of the specified property of the specified bean, no matter which property reference format is used, with no type conversions.

For more details see PropertyUtilsBean.

Usage

From source file:com.wavemaker.runtime.service.RuntimeService.java

/**
 * getProperty() is a legacy interface. This retrieves (and allows lazy-loading) of a single attribute of an object.
 * // www .  ja v a 2 s .  c  o m
 * @param instance An instance of type type.
 * @param type The type of the object instance.
 * @param propertyName The name of the property to load.
 * @return The attribute specified by the propertyName parameter is returned, not the whole object.
 * @throws Exception
 */
@SuppressWarnings("rawtypes")
public Object getProperty(@JSONParameterTypeField(typeParameter = 1) Object instance, String type,
        String propertyName) throws Exception {

    ServiceWire serviceWire = this.typeManager.getServiceWireForType(type);

    if (serviceWire.isLiveDataService()) {

        PropertyOptions po = new PropertyOptions();
        po.getProperties().add(propertyName);

        TypedServiceReturn resp = read(this.typeManager.getServiceIdForType(type), type, instance, po, null);

        Object o = ((SuccessResponse) resp.getReturnValue()).getResult();

        if (o instanceof Collection) {
            Collection c = (Collection) o;
            if (c.isEmpty()) {
                o = null;
            } else {
                o = c.iterator().next();
            }
        }

        if (o == null) {
            return null;
        } else {
            Object ret = PropertyUtils.getProperty(o, propertyName);
            return ret;
        }
    } else {
        throw new NotYetImplementedException();
    }
}

From source file:com.khubla.cbean.serializer.impl.json.JSONListFieldSerializer.java

@Override
public void deserialize(Object o, Field field, String value) throws SerializerException {
    try {//from  w w  w  . ja  v a 2  s .c o m
        /*
         * get the parameterized type
         */
        final ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType();
        final Class<?> containedType = (Class<?>) parameterizedType.getActualTypeArguments()[0];
        /*
         * get cBean
         */
        final CBean<?> cBean = CBeanServer.getInstance().getCBean(containedType);
        /*
         * get the array object
         */
        @SuppressWarnings("unchecked")
        final List<Object> list = (List<Object>) PropertyUtils.getProperty(o, field.getName());
        /*
         * iterate
         */
        final JSONArray jsonArray = new JSONArray(value);
        for (int i = 0; i < jsonArray.length(); i++) {
            final String key = jsonArray.getString(i);
            final Object oo = cBean.load(new CBeanKey(key));
            /*
             * oo could be null. if that happens, it can be because the underlying object has been deleted. this is ok. We add the null into the the list so that we preserve the list LENGTH
             */
            list.add(oo);
        }
    } catch (final Exception e) {
        throw new SerializerException(e);
    }
}

From source file:com.evolveum.midpoint.web.component.util.ListDataProvider2.java

@SuppressWarnings("unchecked")
protected <V extends Comparable<V>> void sort(List<T> list) {
    Collections.sort(list, new Comparator<T>() {
        @Override// www.j av a 2 s  .c  o  m
        public int compare(T o1, T o2) {
            SortParam<String> sortParam = getSort();
            String propertyName = sortParam.getProperty();
            V prop1, prop2;
            try {
                prop1 = (V) PropertyUtils.getProperty(o1, propertyName);
                prop2 = (V) PropertyUtils.getProperty(o2, propertyName);
            } catch (RuntimeException | IllegalAccessException | InvocationTargetException
                    | NoSuchMethodException e) {
                throw new SystemException("Couldn't sort the object list: " + e.getMessage(), e);
            }
            int comparison = ObjectUtils.compare(prop1, prop2, true);
            return sortParam.isAscending() ? comparison : -comparison;
        }
    });
}

From source file:com.gisgraphy.helper.BeanHelper.java

public static String toString(Object current) {
    if (current == null) {
        return "null";
    }/* ww w .j a  v a 2 s .  com*/
    final StringBuffer buffer = new StringBuffer();
    final String beanName = current.getClass().getSimpleName();
    buffer.append(beanName);
    buffer.append(" { ");
    String propertyName;
    Object propertyValue = null;
    boolean first = true;
    Exception exception;
    try {
        for (final PropertyDescriptor propertyDescriptor : Introspector
                .getBeanInfo(current.getClass(), Object.class).getPropertyDescriptors()) {
            exception = null;
            propertyName = propertyDescriptor.getName();
            logger.debug("propertyName=" + propertyName);
            try {
                propertyValue = PropertyUtils.getProperty(current, propertyName);
            } catch (final IllegalAccessException e) {
                exception = e;
            } catch (final InvocationTargetException e) {
                exception = e;
            } catch (final NoSuchMethodException e) {
                exception = e;
            }
            if (exception != null) {
                logger.debug("impossible to get value of property " + propertyName + " of bean " + beanName,
                        exception);
                continue;
            }
            if (first) {
                first = false;
            } else {
                buffer.append(", ");
            }
            buffer.append(propertyName);
            buffer.append(':');
            buffer.append(propertyValue);
        }
    } catch (final IntrospectionException e) {
        logger.error("impossible to get properties of bean " + beanName, e);
    }
    buffer.append(" }");
    return buffer.toString();
}

From source file:com.github.richardwilly98.esdms.services.ParameterProvider.java

@Override
public Object getParameterValue(String name) throws ServiceException {
    checkNotNull(name);/*  ww w.  jav a2  s  .  c  om*/
    if (name.contains(".")) {
        String id = name.substring(0, name.indexOf("."));
        String propertyName = name.substring(name.indexOf(".") + 1);
        Parameter parameter = super.get(id);
        try {
            return PropertyUtils.getProperty(parameter, propertyName);
        } catch (Exception ex) {
            log.error(String.format("getParameterValue %s failed", name), ex);
            throw new ServiceException(ex.getLocalizedMessage());
        }
    } else
        return super.get(name);
}

From source file:de.micromata.genome.gwiki.web.tags.GWikiHtmlOptionsCollectionTag.java

@Override
public int doStartTag() throws JspException {
    GWikiHtmlSelectTag selTag = (GWikiHtmlSelectTag) pageContext
            .getAttribute(GWikiHtmlSelectTag.GWikiHtmlSelectTag_KEY);
    if (selTag == null) {
        throw new JspException("cann use optionsCollection only inside a select tag");
    }/*w w  w. ja v a 2s .c  om*/
    Object collection = GWikiTagRenderUtils.readFormValue(pageContext, property);
    if (collection == null) {
        throw new JspException("Jsp: form." + property + " is a null value");
    }

    Iterator<?> iter = getIterator(collection);

    StringBuilder sb = new StringBuilder();

    while (iter.hasNext()) {

        Object bean = iter.next();
        Object beanLabel = null;
        Object beanValue = null;

        // Get the label for this option
        try {
            beanLabel = PropertyUtils.getProperty(bean, label);
            if (beanLabel == null) {
                beanLabel = "";
            }
        } catch (Exception ex) {
            throw new JspException("Cannot access label ' " + label + " from collection form." + property + ": "
                    + ex.getMessage(), ex);
        }

        // Get the value for this option
        try {
            beanValue = PropertyUtils.getProperty(bean, value);
            if (beanValue == null) {
                beanValue = "";
            }
        } catch (Exception ex) {
            throw new JspException("Cannot access value ' " + value + " from collection form." + property + ": "
                    + ex.getMessage(), ex);
        }
        String stringLabel = beanLabel.toString();
        String stringValue = beanValue.toString();
        sb.append("<option value=\"").append(escapeHtml ? WebUtils.escapeHtml(stringValue) : stringValue)
                .append("\"");
        if (selTag.hasValue(stringValue) == true) {
            sb.append(" selected=\"selected\"");
        }
        sb.append(" ");
        GWikiTagRenderUtils.renderTagAttributes(this, sb);
        sb.append(">").append(escapeHtml ? WebUtils.escapeHtml(stringLabel) : stringLabel);
        sb.append("</option>");
    }
    GWikiTagRenderUtils.write(pageContext, sb.toString());
    return SKIP_BODY;
}

From source file:com.mycollab.module.crm.ui.components.CrmFollowersComp.java

public void displayFollowers(final V bean) {
    this.bean = bean;
    try {/*from   ww  w  .  j  a va 2s .c o m*/
        typeId = (Integer) PropertyUtils.getProperty(bean, "id");
    } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
        LOG.error("Error", e);
        return;
    }
    this.removeAllComponents();

    MHorizontalLayout header = new MHorizontalLayout().withStyleName("info-hdr");
    header.setDefaultComponentAlignment(Alignment.MIDDLE_LEFT);
    Label followerHeader = new Label(
            FontAwesome.EYE.getHtml() + " " + UserUIContext.getMessage(FollowerI18nEnum.OPT_SUB_INFO_WATCHERS),
            ContentMode.HTML);
    header.addComponent(followerHeader);

    if (hasEditPermission()) {
        final PopupView addPopupView = new PopupView(UserUIContext.getMessage(GenericI18Enum.ACTION_MODIFY),
                new MVerticalLayout());
        addPopupView.addPopupVisibilityListener(popupVisibilityEvent -> {
            PopupView.Content content = addPopupView.getContent();
            if (popupVisibilityEvent.isPopupVisible()) {
                MVerticalLayout popupComponent = (MVerticalLayout) content.getPopupComponent();
                popupComponent.removeAllComponents();
                popupComponent.with(new ELabel(UserUIContext.getMessage(FollowerI18nEnum.OPT_SUB_INFO_WATCHERS))
                        .withStyleName(ValoTheme.LABEL_H3), new ModifyWatcherPopup());
            } else {
                MVerticalLayout popupComponent = (MVerticalLayout) content.getPopupComponent();
                ModifyWatcherPopup popup = (ModifyWatcherPopup) popupComponent.getComponent(1);
                List<MonitorItem> unsavedItems = popup.getUnsavedItems();
                monitorItemService.saveMonitorItems(unsavedItems);
                loadWatchers();
            }
        });
        header.addComponent(addPopupView);
    }
    header.addComponent(ELabel.fontIcon(FontAwesome.QUESTION_CIRCLE).withStyleName(WebThemes.INLINE_HELP)
            .withDescription(UserUIContext.getMessage(FollowerI18nEnum.FOLLOWER_EXPLAIN_HELP)));

    this.addComponent(header);
    watcherLayout = new MCssLayout().withFullWidth().withStyleName(WebThemes.FLEX_DISPLAY);
    this.addComponent(watcherLayout);
    loadWatchers();
}

From source file:com.google.api.ads.dfp.appengine.fetcher.AllNestedFetcher.java

/**
 * Method used to fetch all of an entity and it's nested child. Exceptions are handled by logging
 * and sending error messages back to the user through the channel.
 *
 * @param filterText the filter that should be used to filter for the parent ID in the child
 *//*from   w ww  .j a  v  a  2  s .  com*/
@VisibleForTesting
void fetchAll(String filterText) {
    try {
        StatementBuilder statementBuilder = new StatementBuilder().limit(StatementBuilder.SUGGESTED_PAGE_LIMIT);
        int totalResultSetSize = 0;
        do {
            Object page = parentPageFetcher.getByStatement(statementBuilder.toStatement());
            totalResultSetSize = (Integer) PropertyUtils.getProperty(page, "totalResultSetSize");
            if (totalResultSetSize == 0) {
                channels.sendNoResultMessage(channelKey, tag, requestId);
            }
            List<?> objects = (List<?>) PropertyUtils.getProperty(page, "results");
            for (Object object : objects) {
                channels.sendSingleObject(channelKey, object, tag, requestId);
                childAllFetcher.fetchAll(filterText + PropertyUtils.getProperty(object, "id"));
            }
            statementBuilder.increaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
        } while (statementBuilder.getOffset() < totalResultSetSize);
    } catch (ApiException_Exception e) {
        channels.sendErrorChannelMessage(channelKey, tag, requestId, e.getMessage());
    } catch (Exception e) {
        channels.sendErrorChannelMessage(channelKey, tag, requestId, e.getMessage());
        log.log(Level.SEVERE, "Error fetching objects.", e);
    }
}

From source file:com.nec.nsgui.taglib.nssorttab.ListSTModel.java

public int compare(Object o1, Object o2) {

    if (o1 == null && o2 == null)
        return 0;

    if (o1 == null) {
        return isAscend ? -1 : 1;
    } else if (o2 == null) {
        return isAscend ? 1 : -1;
    }/*from  w w  w . j a v a 2  s  .  co  m*/

    int result = 0; //the result of compare
    int size = sortData.size(); //the size of sortData 

    for (int i = 0; i < size && result == 0; i += 2) {
        String colName = (String) sortData.get(i);
        Object prop1 = null, prop2 = null;
        try {
            prop1 = PropertyUtils.getProperty(o1, colName);
            prop2 = PropertyUtils.getProperty(o2, colName);
        } catch (Exception e) {
        }

        if (prop1 == null && prop2 == null) {
            return 0;
        }
        if (prop1 == null) {
            result = -1;
        } else if (prop2 == null) {
            result = 1;
        } else {
            Comparator comparator = (Comparator) sortData.get(i + 1);
            BeanComparator beanComp;

            if (comparator != null) {
                beanComp = new BeanComparator(colName, comparator);
            } else {
                beanComp = new BeanComparator(colName);
            }

            result = beanComp.compare(o1, o2);
        }
        if (i == 0 && !isAscend) {
            result = -result;
        }
    }

    return result;
}

From source file:jp.co.opentone.bsol.linkbinder.view.admin.attachment.MasterSettingFileUploadAction.java

private UploadedFile getUploadedFile() {
    try {//w w w  .j  av  a 2 s . com
        UploadedFile f = (UploadedFile) PropertyUtils.getProperty(page, PROP_UPLOADED);
        return (f != null && f.getFileSize() != null) ? f : null;
    } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
        throw new ApplicationFatalRuntimeException(e);
    }
}