Example usage for org.apache.commons.beanutils ConvertUtils convert

List of usage examples for org.apache.commons.beanutils ConvertUtils convert

Introduction

In this page you can find the example usage for org.apache.commons.beanutils ConvertUtils convert.

Prototype

public static Object convert(String values[], Class clazz) 

Source Link

Document

Convert an array of specified values to an array of objects of the specified class (if possible).

For more details see ConvertUtilsBean.

Usage

From source file:com.projity.field.FieldConverter.java

/**
 * /*from w ww .  java 2 s . com*/
 * @param value.  Convert from this value
 * @param clazz. Convert to this clazz type.
 * @return object of type clazz.
 * @throws FieldParseException
 */
private Object _convert(Object value, Class clazz, FieldContext context) throws FieldParseException {
    try {
        if (value instanceof String) {
            Object result = null;
            if (context == null)
                result = ConvertUtils.convert((String) value, clazz);
            else {
                Converter contextConverter = null;
                HashMap<Class, Converter> contextMap = contextMaps.get(context);
                if (contextMap != null)
                    contextConverter = contextMap.get(clazz);
                if (contextConverter != null) {
                    contextConverter.convert(clazz, value);
                } else {
                    System.out.println("no context converter found ");
                    result = ConvertUtils.convert((String) value, clazz);
                }
            }
            //         if (result instanceof java.util.Date) { //  dates need to be normalized
            //            result = new Date(DateTime.gmt((Date) result));
            //         }
            if (result == null) {
                throw new FieldParseException("Invalid type");
            }
            return result;
        }

        // Because of stupidity of beanutils which assumes type string, I implement this by hand
        Converter converter = ConvertUtils.lookup(clazz);
        if (converter == null) {
            System.out.println(
                    "converter is null for class " + clazz + " instance " + instance.hashCode() + " resetting");
            instance = new FieldConverter();
            converter = ConvertUtils.lookup(String.class);
        }
        return converter.convert(clazz, value);
    } catch (ConversionException conversionException) {
        throw new FieldParseException(conversionException);
    }
}

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

public ResultSet search(final String query, final Integer start, final Integer count) throws IndexException {
    try {/*from   www. ja  v  a  2  s.  c o  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.mawujun.utils.BeanUtils.java

public static <T> T convert(Object value, Class<T> toType) {
    //???/*from w ww.  ja  v a2  s. c  om*/
    if (value.getClass() == toType) {
        return (T) value;
    }

    try {
        return (T) ConvertUtils.convert(value, toType);
    } catch (Exception e) {
        throw ReflectUtils.convertReflectionExceptionToUnchecked(e);
    }
}

From source file:com.mawujun.utils.bean.BeanUtils.java

public static <T> T convert(Object value, Class<T> toType) {
    //      //???
    //      if(value.getClass()==toType){
    //         return (T)value;
    //      }/* w  w w.  j  av  a  2 s .  co  m*/

    try {
        return (T) ConvertUtils.convert(value, toType);
    } catch (Exception e) {
        throw ReflectUtils.convertReflectionExceptionToUnchecked(e);
    }
}

From source file:jp.terasoluna.fw.util.ConvertUtil.java

/**
 * <code>T</code>???//from   w ww  .jav  a  2 s .c  o m
 * <p>
 * <ul>
 *  <li><code>allowsNull</code>?<code>false</code>??
 *        <code>obj</code>?<code>null</code> - 
 *  <li><code>allowsNull</code>?<code>true</code>??
 *        <code>obj</code>?<code>null</code> - <code>null</code>?
 *  <li><code>obj</code>?<code>clazz</code> - ??????
 *  <li><code>obj</code>?<code>clazz</code>????
 *        - <code>ConvertUtils</code>?????????
 * </ul>
 * </p>
 * 
 * @param <T> ??
 * @param obj 
 * @param clazz ??
 * @param allowsNull <code>obj</code>?<code>null</code>?
 *      ??????
 * @return ??
 * @throws IllegalArgumentException <code>clazz</code>?
 *      <code>null</code>??
 *      <code>allowsNull</code>?<code>false</code>??
 *        <code>obj</code>?<code>null</code>??
 *      ?????
 */
@SuppressWarnings("unchecked")
public static <T> T convert(Object obj, Class<T> clazz, boolean allowsNull) throws IllegalArgumentException {

    if (clazz == null) {
        throw new IllegalArgumentException("Argument 'clazz' (" + Object.class.getName() + ") is null");
    }

    if (obj == null) {
        if (!allowsNull) {
            String message = "Unable to cast 'null' to '" + clazz.getName() + "'";
            throw new IllegalArgumentException(message, new ClassCastException(message));
        }
        return null;
    }

    if (clazz.isAssignableFrom(obj.getClass())) {
        return (T) obj;
    }

    Object result = null;
    try {
        result = ConvertUtils.convert(obj.toString(), clazz);
    } catch (ConversionException e) {
        throw new IllegalArgumentException(e);
    }
    return (T) result;
}

From source file:com.mawujun.utils.bean.BeanUtils.java

/**
 * ??/* w w w . j  a  v  a2  s .  c om*/
 * @param values
 * @param toType
 * @return
 */
public static <T> T convert(String[] values, Class<T> toType) {
    return (T) ConvertUtils.convert(values, toType);
}

From source file:com.hongqiang.shop.modules.cms.service.CategoryService.java

/**
 * ???/*from   www .j a v a2 s .  co m*/
 */
public List<Category> findByIds(String ids) {
    List<Category> list = Lists.newArrayList();
    Long[] idss = (Long[]) ConvertUtils.convert(StringUtils.split(ids, ","), Long.class);
    if (idss.length > 0) {
        List<Category> l = categoryDao.findByIdIn(idss);
        for (Long id : idss) {
            for (Category e : l) {
                if (e.getId().longValue() == id) {
                    list.add(e);
                    break;
                }
            }
        }
    }
    return list;
}

From source file:com.jdon.strutsutil.util.EditeViewPageUtil.java

/**
 * ?key  /admin/productAction.do?action=edit&productId=1721
 * ?:productIdproductmodelmapping.xmlkey
 * /*w ww .j  a va  2 s .  co m*/
 *  /admin/productAction.do?action=edit&userId=16
 * userId?modelmapping.xmlkey?override
 * 
 * 
 * @param actionMapping
 * @param request
 * @return ?key
 * @throws java.lang.Exception
 */
public Object getParamKeyValue(HttpServletRequest request, ModelHandler modelHandler) {

    Object keyValue = null;
    try {
        ModelMapping modelMapping = modelHandler.getModelMapping();
        String keyName = modelMapping.getKeyName();
        Debug.logVerbose("[JdonFramework] the keyName is  " + keyName, module);
        String keyValueS = request.getParameter(keyName);
        Debug.logVerbose("[JdonFramework] got the keyValue is  " + keyValueS, module);
        if (keyValueS == null) {
            Debug.logVerbose("[JdonFramework]the keyValue is null", module);
        }
        Class keyClassType = modelMapping.getKeyClassType();
        if (keyClassType.isAssignableFrom(String.class)) {
            keyValue = keyValueS;
        } else {
            Debug.logVerbose("[JdonFramework] convert String keyValue to" + keyClassType.getName(), module);
            keyValue = ConvertUtils.convert(keyValueS, keyClassType);
        }
    } catch (Exception e) {
        Debug.logError("[JdonFramework] getParamKeyValue error: " + e);
    }
    return keyValue;
}

From source file:jp.co.acroquest.endosnipe.perfdoctor.rule.RuleInstanceUtil.java

/**
 * ??/*from  w  w  w  . j  a v a2s .co  m*/
 * @param obj ?
 * @param fieldName ??
 * @param value 
 * @throws RuleCreateException ???????
 */
protected static void setValue(final Object obj, final String fieldName, final String value)
        throws RuleCreateException {
    Class<? extends Object> clazz = obj.getClass();
    Object[] args = new Object[] { clazz.getCanonicalName(), fieldName, value };

    try {
        Field field = clazz.getField(fieldName);

        Object convertedValue = ConvertUtils.convert(value, field.getType());
        field.set(obj, convertedValue);
    } catch (NoSuchFieldException ex) {
        throw new RuleCreateException(PerfConstants.PROPERTY_NOT_FOUND, args);
    } catch (SecurityException ex) {
        throw new RuleCreateException(PerfConstants.PROPERTY_ERROR, args);
    } catch (IllegalArgumentException ex) {
        throw new RuleCreateException(PerfConstants.PROPERTY_TYPE_ERROR, args);
    } catch (IllegalAccessException ex) {
        throw new RuleCreateException(PerfConstants.PROPERTY_ACCESS_ERROR, args);
    }
}

From source file:info.magnolia.importexport.PropertiesImportExport.java

protected Object convertNodeDataStringToObject(String valueStr) {
    if (contains(valueStr, ':')) {
        final String type = StringUtils.substringBefore(valueStr, ":");
        final String value = StringUtils.substringAfter(valueStr, ":");

        // there is no beanUtils converter for Calendar
        if (type.equalsIgnoreCase("date")) {
            return ISO8601.parse(value);
        } else if (type.equalsIgnoreCase("binary")) {
            return new ByteArrayInputStream(value.getBytes());
        } else {/*from   ww  w. ja  v  a 2s  .co  m*/
            try {
                final Class<?> typeCl;
                if (type.equals("int")) {
                    typeCl = Integer.class;
                } else {
                    typeCl = Class.forName("java.lang." + StringUtils.capitalize(type));
                }
                return ConvertUtils.convert(value, typeCl);
            } catch (ClassNotFoundException e) {
                // possibly a stray :, let's ignore it for now
                return valueStr;
            }
        }
    }
    // no type specified, we assume it's a string, no conversion
    return valueStr;
}