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

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

Introduction

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

Prototype

public static void setSimpleProperty(Object bean, String name, Object value)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException 

Source Link

Document

Set the value of the specified simple property of the specified bean, with no type conversions.

For more details see PropertyUtilsBean.

Usage

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

@Override
protected void internalWriteProperty(Object entity, String property, Object value) throws Exception {
    BeanMap beanMap = getBeanMap(entity);
    Class<?> propertyType = beanMap.getPropertyType(property);
    if (!propertyType.isInstance(value)) {
        value = tryConvertValue(propertyType, value);
    }/*from  w  w  w  .  j a  va  2s. c o m*/
    PropertyUtils.setSimpleProperty(entity, property, value);
}

From source file:net.sf.qooxdoo.rpc.RemoteCallUtils.java

/**
 * Converts JSON types to "normal" java types.
 *
 * @param       obj                 the object to convert (must not be
 *                                  <code>null</code>, but can be
 *                                  <code>JSONObject.NULL</code>).
 * @param       targetType          the desired target type (must not be
 *                                  <code>null</code>).
 *
 * @return      the converted object.// w w w .  j a va2  s  .c o  m
 *
 * @exception   IllegalArgumentException    thrown if the desired
 *                                          conversion is not possible.
 */

public Object toJava(Object obj, Class targetType) {
    try {
        if (obj == JSONObject.NULL) {
            if (targetType == Integer.TYPE || targetType == Double.TYPE || targetType == Boolean.TYPE
                    || targetType == Long.TYPE || targetType == Float.TYPE) {
                // null does not work for primitive types
                throw new Exception();
            }
            return null;
        }
        if (obj instanceof JSONArray) {
            Class componentType;
            if (targetType == null || targetType == Object.class) {
                componentType = null;
            } else {
                componentType = targetType.getComponentType();
            }
            JSONArray jsonArray = (JSONArray) obj;
            int length = jsonArray.length();
            Object retVal = Array.newInstance((componentType == null ? Object.class : componentType), length);
            for (int i = 0; i < length; ++i) {
                Array.set(retVal, i, toJava(jsonArray.get(i), componentType));
            }
            return retVal;
        }
        if (obj instanceof JSONObject) {
            JSONObject jsonObject = (JSONObject) obj;
            JSONArray names = jsonObject.names();
            if (targetType == Map.class || targetType == HashMap.class || targetType == null
                    || targetType == Object.class) {
                HashMap retVal = new HashMap();
                if (names != null) {
                    int length = names.length();
                    String name;
                    for (int i = 0; i < length; ++i) {
                        name = names.getString(i);
                        retVal.put(name, toJava(jsonObject.get(name), null));
                    }
                }
                return retVal;
            }
            Object bean;
            String requestedTypeName = jsonObject.optString("class", null);
            if (requestedTypeName != null) {
                Class clazz = resolveClassHint(requestedTypeName, targetType);
                if (clazz == null || !targetType.isAssignableFrom(clazz)) {
                    throw new Exception();
                }
                bean = clazz.newInstance();
                // TODO: support constructor parameters
            } else {
                bean = targetType.newInstance();
            }
            if (names != null) {
                int length = names.length();
                String name;
                PropertyDescriptor desc;
                for (int i = 0; i < length; ++i) {
                    name = names.getString(i);
                    if (!"class".equals(name)) {
                        desc = PropertyUtils.getPropertyDescriptor(bean, name);
                        if (desc != null && desc.getWriteMethod() != null) {
                            PropertyUtils.setSimpleProperty(bean, name,
                                    toJava(jsonObject.get(name), desc.getPropertyType()));
                        }
                    }
                }
            }
            return bean;
        }
        if (targetType == null || targetType == Object.class) {
            return obj;
        }
        Class actualTargetType;
        Class sourceType = obj.getClass();
        if (targetType == Integer.TYPE) {
            actualTargetType = Integer.class;
        } else if (targetType == Boolean.TYPE) {
            actualTargetType = Boolean.class;
        } else if ((targetType == Double.TYPE || targetType == Double.class)
                && Number.class.isAssignableFrom(sourceType)) {
            return new Double(((Number) obj).doubleValue());
            // TODO: maybe return obj directly if it's a Double 
        } else if ((targetType == Float.TYPE || targetType == Float.class)
                && Number.class.isAssignableFrom(sourceType)) {
            return new Float(((Number) obj).floatValue());
        } else if ((targetType == Long.TYPE || targetType == Long.class)
                && Number.class.isAssignableFrom(sourceType)) {
            return new Long(((Number) obj).longValue());
        } else {
            actualTargetType = targetType;
        }
        if (!actualTargetType.isAssignableFrom(sourceType)) {
            throw new Exception();
        }
        return obj;
    } catch (IllegalArgumentException e) {
        throw e;
    } catch (Exception e) {
        throw new IllegalArgumentException("Cannot convert " + (obj == null ? null : obj.getClass().getName())
                + " to " + (targetType == null ? null : targetType.getName()));
    }
}

From source file:com.sqewd.open.dal.core.persistence.db.EntityHelper.java

@SuppressWarnings({ "unchecked", "rawtypes" })
public static void setColumnValue(final ResultSet rs, final StructAttributeReflect attr,
        final AbstractEntity entity, final AbstractJoinGraph gr, final Stack<KeyValuePair<Class<?>>> path)
        throws Exception {

    KeyValuePair<String> alias = gr.getAliasFor(path, attr.Column, 0);
    String tabprefix = alias.getKey();

    if (EnumPrimitives.isPrimitiveType(attr.Field.getType())) {
        EnumPrimitives prim = EnumPrimitives.type(attr.Field.getType());
        switch (prim) {
        case ECharacter:
            String sv = rs.getString(tabprefix + "." + attr.Column);
            if (!rs.wasNull()) {
                PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), sv.charAt(0));
            }/* w  w w  . ja va2  s. com*/
            break;
        case EShort:
            short shv = rs.getShort(tabprefix + "." + attr.Column);
            if (!rs.wasNull()) {
                PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), shv);
            }
            break;
        case EInteger:
            int iv = rs.getInt(tabprefix + "." + attr.Column);
            if (!rs.wasNull()) {
                PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), iv);
            }
            break;
        case ELong:
            long lv = rs.getLong(tabprefix + "." + attr.Column);
            if (!rs.wasNull()) {
                PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), lv);
            }
            break;
        case EFloat:
            float fv = rs.getFloat(tabprefix + "." + attr.Column);
            if (!rs.wasNull()) {
                PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), fv);
            }
            break;
        case EDouble:
            double dv = rs.getDouble(tabprefix + "." + attr.Column);
            if (!rs.wasNull()) {
                PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), dv);
            }
            break;
        default:
            throw new Exception("Unsupported Data type [" + prim.name() + "]");
        }
    } else if (attr.Convertor != null) {
        String value = rs.getString(tabprefix + "." + attr.Column);
        if (!rs.wasNull()) {
            attr.Convertor.load(entity, attr.Column, value);
        }
    } else if (attr.Field.getType().equals(String.class)) {
        String value = rs.getString(tabprefix + "." + attr.Column);
        if (!rs.wasNull()) {
            PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), value);
        }
    } else if (attr.Field.getType().equals(Date.class)) {
        long value = rs.getLong(tabprefix + "." + attr.Column);
        if (!rs.wasNull()) {
            Date dt = new Date(value);
            PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), dt);
        }
    } else if (attr.Field.getType().isEnum()) {
        String value = rs.getString(tabprefix + "." + attr.Column);
        if (!rs.wasNull()) {
            Class ecls = attr.Field.getType();
            Object evalue = Enum.valueOf(ecls, value);
            PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), evalue);
        }
    } else if (attr.Reference != null) {
        Class<?> rt = Class.forName(attr.Reference.Class);
        Object obj = rt.newInstance();
        if (!(obj instanceof AbstractEntity))
            throw new Exception("Unsupported Entity type [" + rt.getCanonicalName() + "]");
        AbstractEntity rentity = (AbstractEntity) obj;
        if (path.size() > 0) {
            path.peek().setKey(attr.Column);
        }

        KeyValuePair<Class<?>> cls = new KeyValuePair<Class<?>>();
        cls.setValue(rentity.getClass());
        path.push(cls);
        setEntity(rentity, rs, gr, path);
        PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), rentity);
        path.pop();
    }
}

From source file:net.mojodna.searchable.solr.SolrSearcher.java

public ResultSet search(final String query, final Integer start, final Integer count) throws IndexException {
    try {//  ww  w . j  a va2s.  co  m
        final GetMethod get = new GetMethod(solrPath);
        final List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new NameValuePair("q", query));
        if (null != start) {
            params.add(new NameValuePair("start", start.toString()));
        }
        if (null != count) {
            params.add(new NameValuePair("rows", count.toString()));
        }
        params.add(new NameValuePair("version", "2.1"));
        params.add(new NameValuePair("indent", "on"));
        get.setQueryString(params.toArray(new NameValuePair[] {}));
        final int responseCode = getHttpClient().executeMethod(get);

        final SAXBuilder builder = new SAXBuilder();
        final Document response = builder.build(get.getResponseBodyAsStream());
        final Element resultNode = response.getRootElement().getChild("result");

        final ResultSetImpl resultSet = new ResultSetImpl(
                new Integer(resultNode.getAttributeValue("numFound")));
        resultSet.setOffset(new Integer(resultNode.getAttributeValue("start")));
        List<Element> docs = resultNode.getChildren("doc");
        for (int i = 0; i < docs.size(); i++) {
            final Element doc = docs.get(i);
            Result result = null;

            // load the class name
            String className = null;
            String id = null;
            String idType = null;
            for (final Iterator it = doc.getChildren("str").iterator(); it.hasNext();) {
                final Element str = (Element) it.next();
                final String name = str.getAttributeValue("name");
                if (IndexSupport.TYPE_FIELD_NAME.equals(name)) {
                    className = str.getTextTrim();
                } else if (IndexSupport.ID_FIELD_NAME.equals(name)) {
                    id = str.getTextTrim();
                } else if (IndexSupport.ID_TYPE_FIELD_NAME.equals(name)) {
                    idType = str.getTextTrim();
                }
            }

            try {
                // attempt to instantiate an instance of the specified class
                try {
                    if (null != className) {
                        final Object o = Class.forName(className).newInstance();
                        if (o instanceof Result) {
                            log.debug("Created new instance of: " + className);
                            result = (Result) o;
                        }
                    }
                } catch (final ClassNotFoundException e) {
                    // class was invalid, or something
                }

                // fall back to a GenericResult as a container
                if (null == result)
                    result = new GenericResult();

                if (result instanceof Searchable) {
                    // special handling for searchables
                    final String idField = SearchableBeanUtils
                            .getIdPropertyName(((Searchable) result).getClass());

                    // attempt to load the id and set the id property on the Searchable appropriately
                    if (null != id) {
                        log.debug("Setting id to '" + id + "' of type " + idType);
                        try {
                            final Object idValue = ConvertUtils.convert(id, Class.forName(idType));
                            PropertyUtils.setSimpleProperty(result, idField, idValue);
                        } catch (final ClassNotFoundException e) {
                            log.warn("Id type was not a class that could be found: " + idType);
                        }
                    } else {
                        log.warn("Id value was null.");
                    }
                } else {
                    final GenericResult gr = new GenericResult();
                    gr.setId(id);
                    gr.setType(className);
                    result = gr;
                }

            } catch (final Exception e) {
                throw new SearchException("Could not reconstitute resultant object.", e);
            }

            result.setRanking(i);

            resultSet.add(result);
        }

        return resultSet;
    } catch (final JDOMException e) {
        throw new IndexingException(e);
    } catch (final IOException e) {
        throw new IndexingException(e);
    }
}

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

public void setValue(Object base, Object property, Object value) throws PropertyNotFoundException {

    if (base == null) {
        throw new NullPointerException();
    }/*from   w w w.j  ava  2  s.  com*/
    String name = property.toString();
    try {
        if (base instanceof Map) {
            ((Map) base).put(name, value);
        } else {
            PropertyUtils.setSimpleProperty(base, name, value);
        }
    } 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.myjeeva.poi.ExcelWorkSheetHandler.java

private void assignValue(Object targetObj, String cellReference, String value) {
    if (null == targetObj || StringUtils.isEmpty(cellReference) || StringUtils.isEmpty(value)) {
        return;//from   w  w  w.j a v a 2s.c  o  m
    }

    try {
        String propertyName = this.cellMapping.get(cellReference);
        if (null == propertyName) {
            LOG.error("Cell mapping doesn't exists!");
        } else {
            PropertyUtils.setSimpleProperty(targetObj, propertyName, value);
        }
    } catch (IllegalAccessException iae) {
        LOG.error(iae.getMessage());
    } catch (InvocationTargetException ite) {
        LOG.error(ite.getMessage());
    } catch (NoSuchMethodException nsme) {
        LOG.error(nsme.getMessage());
    }
}

From source file:com.bstek.dorado.config.ExpressionMethodInterceptor.java

@SuppressWarnings({ "unchecked", "rawtypes" })
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
    if (!disabled) {
        Object object = methodInvocation.getThis();
        if (object instanceof Map<?, ?>) {
            final String methodName = methodInvocation.getMethod().getName();
            if (GET.equals(methodName)) {
                String property = (String) methodInvocation.getArguments()[0];
                Expression expression = getExpressionProperties().get(property);
                if (expression != null) {
                    Object value = expression.evaluate();
                    if (expression.getEvaluateMode() == EvaluateMode.onInstantiate) {
                        Map map = (Map) object;
                        map.put(property, value);
                    }/* ww w . j a  v a2  s.c  o m*/
                    return value;
                }
            } else if (PUT.equals(methodName)) {
                String property = (String) methodInvocation.getArguments()[0];
                getExpressionProperties().remove(property);
            } else if (ENTRY_SET.equals(methodName)) {
                Map map = (Map) object;
                Set<Map.Entry> entrySet = (Set<Map.Entry>) methodInvocation.proceed();
                Set newEntrySet = new HashSet();
                for (Map.Entry entry : entrySet) {
                    newEntrySet.add(new MapEntry(map, entry.getKey()));
                }
                return newEntrySet;
            }
        } else {
            if (interceptingReadMethods == null) {
                discoverInterceptingMethods(object.getClass().getSuperclass());
            }

            Method method = methodInvocation.getMethod();
            if (methodInvocation.getArguments().length == 0) {
                ReadMethodDescriptor methodDescriptor = interceptingReadMethods.get(method);
                if (methodDescriptor != null) {
                    Expression expression = getExpressionProperties().get(methodDescriptor.getProperty());
                    Object value = evaluateExpression(methodDescriptor);
                    if (expression.getEvaluateMode() != EvaluateMode.onRead) {
                        PropertyUtils.setSimpleProperty(object, methodDescriptor.getProperty(), value);
                    }
                    return value;
                }
            } else {
                Method readMethod = interceptingWriteMethods.get(method);
                if (readMethod != null) {
                    interceptingReadMethods.remove(readMethod);
                    interceptingWriteMethods.remove(method);
                }
            }
        }
    }
    return methodInvocation.proceed();
}

From source file:net.sf.qooxdoo.rpc.RpcServlet.java

/**
 * Looks up an instance of a service and creates one if necessary.
 *
 * @param   session             the current session (for storing
 *                              instances).
 * @param   serviceClassName    the fully qualified name of the class
 *                              to instantiate.
 * @param   name                the name to use for the instance.
 * @param   requiredType        The type the service must have. May be
 *                              null. //from w w w  .  j  a  v  a2  s .  co  m
 */

public synchronized Service getServiceInstance(HttpSession session, String serviceClassName, Object name,
        Class requiredType) throws ClassNotFoundException, IllegalAccessException, InstantiationException,
        InvocationTargetException, NoSuchMethodException {

    if (requiredType == null) {
        requiredType = Service.class;
    }

    String lookFor = serviceClassName;
    if (name != null) {
        lookFor += "/" + name;
    }
    Service inst = (Service) session.getAttribute(lookFor);
    if (inst == null) {
        Class clazz = Class.forName(serviceClassName);
        if (!requiredType.isAssignableFrom(clazz)) {
            throw new ClassCastException("The requested service class " + clazz.getName()
                    + " is not from the required type " + requiredType.getName() + "");
        }
        inst = (Service) clazz.newInstance();
        Class[] paramTypes = new Class[1];
        Object[] params = new Object[1];
        paramTypes[0] = Environment.class;
        Method method = MethodUtils.getMatchingAccessibleMethod(clazz, "setWebcomponentEnvironment",
                paramTypes);
        if (method == null) {
            method = MethodUtils.getMatchingAccessibleMethod(clazz, "setQooxdooEnvironment", paramTypes);
        }
        if (method != null) {
            params[0] = new Environment();
            method.invoke(inst, params);
        }
        if (name != null) {
            paramTypes[0] = String.class;
            method = MethodUtils.getMatchingAccessibleMethod(clazz, "setWebcomponentName", paramTypes);
            if (method != null) {
                params[0] = name;
                method.invoke(inst, params);
            }
        }
        session.setAttribute(lookFor, inst);

        // initialize the service properties
        ServletConfig servletConfig = getServletConfig();
        Enumeration initParamNames = servletConfig.getInitParameterNames();
        String initParamName;
        String initParamValue;
        int pos;
        String packageName;
        String propertyName;
        HashMap candidates = new HashMap();
        while (initParamNames.hasMoreElements()) {
            initParamName = (String) initParamNames.nextElement();
            pos = initParamName.lastIndexOf('.');
            if (pos == -1) {
                packageName = "";
                propertyName = initParamName;
            } else {
                packageName = initParamName.substring(0, pos);
                propertyName = initParamName.substring(pos + 1);
            }
            String candidateName;
            if (serviceClassName.startsWith(packageName)) {
                candidateName = (String) candidates.get(propertyName);
                if (candidateName == null) {
                    candidates.put(propertyName, initParamName);
                } else if (candidateName.length() < initParamName.length()) {
                    candidates.put(propertyName, initParamName);
                }
            }
        }
        Iterator candidatesIterator = candidates.keySet().iterator();
        Class propertyType;
        while (candidatesIterator.hasNext()) {
            propertyName = (String) candidatesIterator.next();
            initParamName = (String) candidates.get(propertyName);
            initParamValue = servletConfig.getInitParameter(initParamName);
            propertyType = PropertyUtils.getPropertyType(inst, propertyName);
            if (propertyType != null) {
                if (propertyType.getComponentType() == String.class) {
                    PropertyUtils.setSimpleProperty(inst, propertyName,
                            StringUtils.tokenize(initParamValue, ';'));
                } else {
                    try {
                        PropertyUtils.setSimpleProperty(inst, propertyName,
                                ConvertUtils.convert(initParamValue, propertyType));
                    } catch (Exception e) {
                        // try to instatiate a class of the supplied parameter
                        //System.out.println("***** setting '" + propertyName + "' to an instance of '" + initParamValue + "'");
                        PropertyUtils.setSimpleProperty(inst, propertyName,
                                getServiceInstance(session, initParamValue, null, null));
                    }
                }
            } else {
                //System.out.println("***** property '" + propertyName + "' not matched");
            }
        }

        // tell the instance that we're done
        paramTypes = new Class[0];
        method = MethodUtils.getMatchingAccessibleMethod(clazz, "webcomponentInit", paramTypes);
        if (method != null) {
            params = new Object[0];
            method.invoke(inst, params);
        }
    }
    return inst;
}

From source file:com.bstek.dorado.view.config.definition.ViewConfigDefinition.java

protected void injectResourceString(ViewConfig viewConfig, String key, String resourceString) throws Exception {
    Object object = viewConfig;/*  www.  ja  v  a 2s. c  om*/
    ResourceInjection resourceInjection = object.getClass().getAnnotation(ResourceInjection.class);

    String[] sections = StringUtils.split(key, ".");
    int len = sections.length;
    for (int i = 0; i < len; i++) {
        String section = sections[i];
        boolean isObject = section.charAt(0) == '#';
        if (isObject) {
            section = section.substring(1);
        }

        if (i == 0 && section.equals("view")) {
            object = viewConfig.getView();
        } else if (isObject) {
            if (object == viewConfig) {
                object = viewConfig.getDataType(section);
                if (object == null && viewConfig.getView() != null) {
                    object = viewConfig.getView().getViewElement(section);
                }
            } else {
                if (resourceInjection == null) {
                    throwInvalidResourceKey(key);
                }
                String methodName = resourceInjection.subObjectMethod();
                if (StringUtils.isEmpty(methodName)) {
                    throwInvalidResourceKey(key);
                }
                object = MethodUtils.invokeExactMethod(object, methodName, new String[] { section });
            }
            if (object == null) {
                break;
            }
            resourceInjection = object.getClass().getAnnotation(ResourceInjection.class);

            if (i == len - 1) {
                String[] defaultProperties;
                if (resourceInjection == null) {
                    defaultProperties = DEFAULT_PROPERTIES;
                } else {
                    defaultProperties = resourceInjection.defaultProperty();
                }

                boolean found = false;
                for (String property : defaultProperties) {
                    if (PropertyUtils.isWriteable(object, property)) {
                        if (PropertyUtils.getSimpleProperty(object, property) == null) {
                            PropertyUtils.setSimpleProperty(object, property, resourceString);
                        }
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    throwInvalidResourceKey(key);
                }
            }
        } else {
            if (i == len - 1) {
                if (PropertyUtils.getSimpleProperty(object, section) == null) {
                    PropertyUtils.setSimpleProperty(object, section, resourceString);
                }
            } else {
                object = PropertyUtils.getSimpleProperty(object, section);
            }
        }
    }
}

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

private void instantiateEspdCriterion(String fieldName, Boolean value) {
    try {//from  w  ww  .j  a v a 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
    }
}