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

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

Introduction

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

Prototype

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

Source Link

Document

Return the Java Class representing the property type of the specified property, or null if there is no such property for the specified bean.

For more details see PropertyUtilsBean.

Usage

From source file:eu.europa.ec.grow.espd.domain.EspdDocument.java

private void instantiateEspdCriterion(String fieldName, Boolean value) {
    try {/*from   ww  w  .  ja va 2  s . c o m*/
        Class<?> clazz = PropertyUtils.getPropertyType(this, fieldName);
        EspdCriterion espdCriterion = (EspdCriterion) clazz.newInstance();
        espdCriterion.setExists(value);
        PropertyUtils.setSimpleProperty(this, fieldName, espdCriterion);
    } catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException
            | InstantiationException e) {
        // this is covered by tests, it should never happen so we don't care
    }
}

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

/**
 * MapkeyBean??BEAN//from   w ww  .j a v a 2  s. c  om
 * ?
 * @param bean Object
 * @param properties Map
 * @param defaultValue String
 * @throws IllegalAccessException
 * @throws java.lang.reflect.InvocationTargetException
 */
public static void copyMap2Bean(Object bean, Map properties, String defaultValue)
        throws IllegalAccessException, InvocationTargetException {
    // Do nothing unless both arguments have been specified
    if ((bean == null) || (properties == null)) {
        return;
    }
    // Loop through the property name/value pairs to be set
    Iterator names = properties.keySet().iterator();
    while (names.hasNext()) {
        String name = (String) names.next();
        // Identify the property name and value(s) to be assigned
        if (name == null) {
            continue;
        }
        Object value = properties.get(name);
        try {
            Class clazz = PropertyUtils.getPropertyType(bean, name);
            if (null == clazz) {
                continue;
            }
            String className = clazz.getName();
            if (className.equalsIgnoreCase("java.sql.Timestamp")) {
                if (value == null || value.equals("")) {
                    continue;
                }
            }
            if (className.equalsIgnoreCase("java.lang.String")) {
                if (value == null) {
                    value = defaultValue;
                }
            }
            setProperty(bean, name, value);
        } catch (NoSuchMethodException e) {
            continue;
        }
    }
}

From source file:hermes.browser.dialog.EditNamingConfigDialog.java

@SuppressWarnings("unchecked")
public void doSelectionChanged() {
    try {//from w w w.j  a  v a2s.co m
        final String selectedConfig = (String) comboBox.getSelectedItem();
        final NamingConfig config = (NamingConfig) namingConfigsByName.get(selectedConfig);
        final PropertySetConfig propertySet = config.getProperties();

        if (currentSelection == null || !currentSelection.equals(selectedConfig)) {
            currentSelection = selectedConfig;

            bean = new JNDIContextFactory();

            LoaderSupport.populateBean(bean, propertySet);

            final Map properties = PropertyUtils.describe(bean);
            final List list = new ArrayList();

            classpathIdProperty = new Property("loader", "Classpath Loader to use.", String.class) {
                /**
                * 
                */
                private static final long serialVersionUID = -3071689960943636606L;
                private String classpathId = config.getClasspathId();

                public void setValue(Object value) {
                    classpathId = value.toString();
                }

                public Object getValue() {
                    return classpathId;
                }

                public boolean hasValue() {
                    return true;
                }
            };

            classpathIdProperty.setEditorContext(ClasspathIdCellEdtitor.CONTEXT);

            list.add(classpathIdProperty);

            for (Iterator iter = properties.entrySet().iterator(); iter.hasNext();) {
                final Map.Entry entry = (Map.Entry) iter.next();
                final String propertyName = (String) entry.getKey();
                final Object propertyValue = entry.getValue() != null ? entry.getValue() : "";

                if (!propertyName.equals("class") && !propertyName.equals("name")) {
                    Property displayProperty = new Property(propertyName, propertyName,
                            PropertyUtils.getPropertyType(bean, propertyName)) {
                        /**
                        * 
                        */
                        private static final long serialVersionUID = 1751773758147906036L;

                        public void setValue(Object value) {
                            try {
                                PropertyUtils.setProperty(bean, propertyName, value);
                            } catch (Exception e) {
                                log.error(e.getMessage(), e);
                            }
                        }

                        public Object getValue() {
                            try {
                                return PropertyUtils.getProperty(bean, propertyName);
                            } catch (Exception e) {
                                log.error(e.getMessage(), e);
                            }

                            return null;
                        }

                        public boolean hasValue() {
                            return true;
                        }
                    };

                    list.add(displayProperty);
                }
            }

            final PropertyTableModel model = new PropertyTableModel(list);
            final PropertyTable table = new PropertyTable(model);

            table.setAutoResizeMode(PropertyTable.AUTO_RESIZE_ALL_COLUMNS);

            PropertyPane pane = new PropertyPane(table);

            pane.addPropertyChangeListener(new PropertyChangeListener() {
                public void propertyChange(PropertyChangeEvent evt) {

                }
            });

            model.expandAll();

            scrollPane.setViewportView(pane);
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);

        HermesBrowser.getBrowser().showErrorDialog(e);
    }
}

From source file:com.algoTrader.PropertySearch.java

/**
 * Converts the value contained within the parameter to the type which Hibernate expects.
 *
 * @param entityType the class of the entity for which the search is being performed.
 * @param parameter the parameter from which to get the value.
 * @return the appropriate value./*from  www  .j  ava  2  s  .  co  m*/
 */
private Object getValue(Class type, final SearchParameter parameter) {
    try {
        Object value = parameter.getValue();
        // - don't try to convert null values or classes
        if (value != null && !value.getClass().equals(Class.class)) {
            Class propertyType = type;
            for (final StringTokenizer tokenizer = new StringTokenizer(parameter.getName(), PERIOD); tokenizer
                    .hasMoreTokens();) {
                final String token = tokenizer.nextToken().trim();
                Class lastType = type;
                type = CriteriaSearchProperties.getPropertyType(type, token);
                if (!tokenizer.hasMoreTokens()) {
                    break;
                }
                if (type == null) {
                    throw new RuntimeException(
                            "No accessible property named '" + token + "', exists on: " + lastType.getName());
                }
                propertyType = type;
            }
            final Object object = propertyType.newInstance();
            final String name = parameter.getName().replaceAll(".*\\" + PERIOD, "");
            try {
                value = convert(value, PropertyUtils.getPropertyType(object, name));
            } catch (final NoSuchMethodException noSuchMethodException) {
                throw new RuntimeException(
                        "No accessible property named '" + name + "', exists on: " + propertyType.getName());
            }
        }
        return value;
    } catch (final Exception exception) {
        throw new RuntimeException(exception);
    }
}

From source file:net.openkoncept.vroom.VroomController.java

private void processRequestSubmit(HttpServletRequest request, HttpServletResponse response, Map paramMap)
        throws ServletException {
    // change the URI below with the actual page who invoked the request.

    String uri = request.getParameter(CALLER_URI);
    String id = request.getParameter(ID);
    String method = request.getParameter(METHOD);
    String beanClass = request.getParameter(BEAN_CLASS);
    String var = request.getParameter(VAR);
    String scope = request.getParameter(SCOPE);

    if (paramMap != null) {
        uri = (String) ((ArrayList) paramMap.get(CALLER_URI)).get(0);
        id = (String) ((ArrayList) paramMap.get(ID)).get(0);
        method = (String) ((ArrayList) paramMap.get(METHOD)).get(0);
        beanClass = (String) ((ArrayList) paramMap.get(BEAN_CLASS)).get(0);
        var = (String) ((ArrayList) paramMap.get(VAR)).get(0);
        scope = (String) ((ArrayList) paramMap.get(SCOPE)).get(0);
    }//from  ww  w .  java2  s.  c  om

    Object beanObject;
    String outcome = null;

    // call form method...

    try {
        Class clazz = Class.forName(beanClass);
        Class elemClass = clazz;
        String eId, eProperty, eBeanClass, eVar, eScope, eFormat;
        // Setting values to beans before calling the method...
        List<Element> elements = VroomConfig.getInstance().getElements(uri, id, method, beanClass, var, scope);
        for (Element e : elements) {
            eId = e.getId();
            eProperty = (e.getProperty() != null) ? e.getProperty() : eId;
            eBeanClass = (e.getBeanClass() != null) ? e.getBeanClass() : beanClass;
            eVar = (e.getVar() != null) ? e.getVar() : var;
            eScope = (e.getBeanClass() != null) ? e.getScope().value() : scope;
            eFormat = e.getFormat();
            if (!elemClass.getName().equals(eBeanClass)) {
                try {
                    elemClass = Class.forName(eBeanClass);
                } catch (ClassNotFoundException ex) {
                    throw new ServletException("Failed to load class for element [" + eId + "]", ex);
                }
            }
            if (elemClass != null) {
                try {
                    Object obj = getObjectFromScope(request, elemClass, eVar, eScope);
                    if (PropertyUtils.isWriteable(obj, eProperty)) {
                        Class propType = PropertyUtils.getPropertyType(obj, eProperty);
                        Object[] paramValues = request.getParameterValues(eId);
                        Object value = null;
                        value = getParameterValue(propType, eId, paramValues, eFormat, paramMap);
                        PropertyUtils.setProperty(obj, eProperty, value);
                    }
                } catch (InstantiationException ex) {
                    throw new ServletException("Failed to create object of type [" + eBeanClass + "]", ex);
                } catch (IllegalAccessException ex) {
                    throw new ServletException("Failed to create object of type [" + eBeanClass + "]", ex);
                }
            }
        }
        // Calling the method...
        beanObject = getObjectFromScope(request, clazz, var, scope);
        Class[] signature = new Class[] { HttpServletRequest.class, HttpServletResponse.class };
        Method m = clazz.getMethod(method, signature);
        Object object = m.invoke(beanObject, new Object[] { request, response });
        // Getting updating values from beans to pass as postback for the forward calls.
        Map<String, Object> postbackMap = new HashMap<String, Object>();
        for (Element e : elements) {
            eId = e.getId();
            eProperty = (e.getProperty() != null) ? e.getProperty() : eId;
            eBeanClass = (e.getBeanClass() != null) ? e.getBeanClass() : beanClass;
            eVar = (e.getVar() != null) ? e.getVar() : var;
            eScope = (e.getBeanClass() != null) ? e.getScope().value() : scope;
            eFormat = e.getFormat();
            if (!elemClass.getName().equals(eBeanClass)) {
                try {
                    elemClass = Class.forName(eBeanClass);
                } catch (ClassNotFoundException ex) {
                    throw new ServletException("Failed to load class for element [" + eId + "]", ex);
                }
            }
            if (elemClass != null) {
                try {
                    Object obj = getObjectFromScope(request, elemClass, eVar, eScope);
                    if (PropertyUtils.isReadable(obj, eProperty)) {
                        //                            Class propType = PropertyUtils.getPropertyType(obj, eProperty);
                        //                            Object[] paramValues = request.getParameterValues(eId);
                        //                            Object value = null;
                        //                            value = getParameterValue(propType, eId, paramValues, eFormat, paramMap);
                        //                            PropertyUtils.setProperty(obj, eProperty, value);
                        Object value = PropertyUtils.getProperty(obj, eProperty);
                        postbackMap.put(eId, value);
                    }
                } catch (InstantiationException ex) {
                    throw new ServletException("Failed to create object of type [" + eBeanClass + "]", ex);
                } catch (IllegalAccessException ex) {
                    throw new ServletException("Failed to create object of type [" + eBeanClass + "]", ex);
                }
            }
        }
        if (object == null || object instanceof String) {
            outcome = (String) object;
            Navigation n = VroomConfig.getInstance().getNavigation(uri, id, method, beanClass, var, scope,
                    outcome);
            if (n == null) {
                n = VroomConfig.getInstance().getNavigation(uri, id, method, beanClass, var, scope, "default");
            }
            if (n != null) {
                String url = n.getUrl();
                if (url == null) {
                    url = "/";
                }
                url = url.replaceAll("#\\{contextPath}", request.getContextPath());
                if (n.isForward()) {
                    String ctxPath = request.getContextPath();
                    if (url.startsWith(ctxPath)) {
                        url = url.substring(ctxPath.length());
                    }
                    PrintWriter pw = response.getWriter();
                    VroomResponseWrapper responseWrapper = new VroomResponseWrapper(response);
                    RequestDispatcher rd = request.getRequestDispatcher(url);
                    rd.forward(request, responseWrapper);
                    StringBuffer sbHtml = new StringBuffer(responseWrapper.toString());
                    VroomHtmlProcessor.addHeadMetaTags(sbHtml, uri, VroomConfig.getInstance());
                    VroomHtmlProcessor.addHeadLinks(sbHtml, uri, VroomConfig.getInstance());
                    VroomHtmlProcessor.addRequiredScripts(sbHtml, request);
                    VroomHtmlProcessor.addInitScript(sbHtml, uri, request);
                    VroomHtmlProcessor.addHeadScripts(sbHtml, uri, VroomConfig.getInstance(), request);
                    VroomHtmlProcessor.addStylesheets(sbHtml, uri, VroomConfig.getInstance(), request);
                    // Add postback values to webpage through javascript...
                    VroomHtmlProcessor.addPostbackScript(sbHtml, uri, request, postbackMap);
                    String html = sbHtml.toString().replaceAll("#\\{contextPath}", request.getContextPath());
                    response.setContentLength(html.length());
                    pw.print(html);
                } else {
                    response.sendRedirect(url);
                }
            } else {
                throw new ServletException("No navigation found for outcome [" + outcome + "]");
            }
        }

    } catch (ClassNotFoundException ex) {
        throw new ServletException("Invocation Failed for method [" + method + "]", ex);
    } catch (InstantiationException ex) {
        throw new ServletException("Invocation Failed for method [" + method + "]", ex);
    } catch (IllegalAccessException ex) {
        throw new ServletException("Invocation Failed for method [" + method + "]", ex);
    } catch (NoSuchMethodException ex) {
        throw new ServletException("Invocation Failed for method [" + method + "]", ex);
    } catch (InvocationTargetException ex) {
        throw new ServletException("Invocation Failed for method [" + method + "]", ex);
    } catch (IOException ex) {
        throw new ServletException("Navigation Failed for outcome [" + outcome + "]", ex);
    }
}

From source file:com.lzsoft.rules.core.RulesEngine.java

private Double sumFiledValuebyFieldName(List<Object> objs, Double sumD, PropertyElmt propertyElmt, String clazz)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    String fieldType;/*from www. jav  a 2 s  .co m*/
    String fieldname = propertyElmt.getField();

    if (objs.getClass().getName().toLowerCase().indexOf("list") >= 0) {
        for (Object obj : (List) objs) {
            if (obj.getClass().getName().toLowerCase().indexOf("list") >= 0) {
                for (Object object : (List) obj) {
                    if (object.getClass().getName().equals(clazz)) {
                        Object objValue = PropertyUtils.getProperty(object, fieldname);// ?mappingfieldname??
                        fieldType = PropertyUtils.getPropertyType(object, fieldname).getSimpleName();// ?mappingfieldname???
                        if ("Double".equals(fieldType)) {
                            sumD += (Double) objValue;
                        } else if ("BigDecimal".equals(fieldType)) {
                            sumD += ((BigDecimal) objValue).doubleValue();
                        }
                    }
                }
            }
        }
    } else {
        for (Object object : objs) {
            Object objValue = PropertyUtils.getProperty(object, fieldname);// ?mappingfieldname??
            fieldType = PropertyUtils.getPropertyType(object, fieldname).getSimpleName();// ?mappingfieldname???
            if ("Double".equals(fieldType)) {
                sumD += (Double) objValue;
            } else if ("BigDecimal".equals(fieldType)) {
                sumD += ((BigDecimal) objValue).doubleValue();
            }
        }
    }
    return sumD;
}

From source file:com.all.shared.sync.SyncGenericConverter.java

private static <T> T fillInstance(T instance, Map<String, Object> attributes) {
    if (instance != null) {
        for (String attribute : attributes.keySet()) {
            if (PropertyUtils.isWriteable(instance, attribute)) {
                try {
                    Class<?> type = PropertyUtils.getPropertyType(instance, attribute);
                    if (instance instanceof ComplexSyncAble) {
                        ComplexSyncAble postSyncAble = (ComplexSyncAble) instance;
                        if (postSyncAble.requiresPostProcessing(attribute)) {
                            continue;
                        }//  w  ww.ja v a 2  s  . com
                    }
                    Object value = readValue(attribute, type, attributes);
                    PropertyUtils.setProperty(instance, attribute, value);
                } catch (Exception e) {
                    LOGGER.error("Could not fill attribute " + attribute + " to instance of type "
                            + instance.getClass() + ". This attribute will be ignored.", e);
                }
            }
        }
    }
    return instance;
}

From source file:edu.arizona.kra.kim.impl.identity.PersonServiceImpl.java

private boolean isPersonProperty(BusinessObject bo, String propertyName) {
    try {/*from   w w  w.ja  va  2 s .  c om*/
        if (ObjectUtils.isNestedAttribute(propertyName) // is a nested property
                && !StringUtils.contains(propertyName, "add.")) {// exclude add line properties (due to path parsing problems in PropertyUtils.getPropertyType)
            Class<?> type = PropertyUtils.getPropertyType(bo,
                    ObjectUtils.getNestedAttributePrefix(propertyName));
            // property type indicates a Person object
            if (type != null) {
                return Person.class.isAssignableFrom(type);
            }
            LOG.warn("Unable to determine type of nested property: " + bo.getClass().getName() + " / "
                    + propertyName);
        }
    } catch (Exception ex) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Unable to determine if property on " + bo.getClass().getName() + " to a person object: "
                    + propertyName, ex);
        }
    }
    return false;
}

From source file:com.bstek.dorado.data.entity.EntityEnhancer.java

public Class<?> getPropertyType(Object entity, String property) {
    if (entity instanceof BeanMap) {
        return ((BeanMap) entity).getPropertyType(property);
    } else if (!(entity instanceof Map<?, ?>)) {
        try {/*w  ww .  j a  v a2 s . c o m*/
            return PropertyUtils.getPropertyType(entity, property);
        } catch (Exception e) {
            logger.warn(e, e);
        }
    }
    return null;
}

From source file:com.sun.faces.config.ManagedBeanFactory.java

protected void setPropertiesIntoBean(Object bean, int beanType, ManagedBeanBean managedBean) {
    Object value = null;//from   ww w  . j av a  2  s  .  c  om
    String propertyClass = null, propertyName = null, strValue = null;
    int propertyType = -1;
    Class valueClass = null;
    ManagedPropertyBean[] properties = managedBean.getManagedProperties();

    if (null == properties) {
        // a bean is allowed to have no properties
        return;
    }

    // iterate over the properties and load each into the bean
    for (int i = 0, len = properties.length; i < len; i++) {
        // skip null properties or properties without names
        if (null == properties[i] || null == (propertyName = properties[i].getPropertyName())) {
            continue;
        }
        // determine what kind of property we have
        try {
            // this switch statement sets the "value" local variable
            // and tries to set it into the bean.
            switch (propertyType = getPropertyType(properties[i])) {
            case TYPE_IS_LIST:
                setArrayOrListPropertiesIntoBean(bean, properties[i]);
                break;
            case TYPE_IS_MAP:
                setMapPropertiesIntoBean(bean, properties[i]);
                break;
            case TYPE_IS_SIMPLE:
                // if the config bean has no managed-property-class
                // defined
                if (null == (propertyClass = properties[i].getPropertyClass())) {
                    // look at the bean property
                    if (null == (valueClass = PropertyUtils.getPropertyType(bean, propertyName))) {
                        // if the bean property class can't be
                        // determined, use the fallback.
                        valueClass = getValueClassConsideringPrimitives(propertyClass);
                    }
                } else {
                    // the config has a managed-property-class
                    // defined
                    valueClass = getValueClassConsideringPrimitives(propertyClass);
                }

                strValue = properties[i].getValue();
                if (Util.isVBExpression(strValue)) {
                    value = evaluateValueBindingGet(strValue);
                } else if (null == strValue && properties[i].isNullValue()) {
                    value = null;
                } else {
                    value = strValue;
                }
                // convert the value if necessary
                value = getConvertedValueConsideringPrimitives(value, valueClass);
                PropertyUtils.setSimpleProperty(bean, propertyName, value);
                break;
            default:
                Util.doAssert(false);
            }
        } catch (FacesException fe) {
            throw fe;
        } catch (Exception ex) {
            // if the property happens to be attribute on
            // UIComponent then bean introspection set will fail.
            if (TYPE_IS_UICOMPONENT == beanType) {
                setComponentAttribute(bean, propertyName, value);
            } else {
                // then this is a real exception to rethrow
                Object[] obj = new Object[1];
                obj[0] = propertyName;
                throw new FacesException(
                        Util.getExceptionMessageString(Util.ERROR_SETTING_BEAN_PROPERTY_ERROR_MESSAGE_ID, obj),
                        ex);
            }
        }
    }
}