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.bstek.dorado.config.definition.Definition.java

/**
 * ?/*w w  w.j av  a 2  s.c om*/
 * 
 * @param object
 *            ?
 * @param property
 *            ??
 * @param value
 *            @see {@link #getProperties()}
 * @param context
 *            
 * @throws Exception
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
protected void setObjectProperty(Object object, String property, Object value, CreationContext context)
        throws Exception {
    if (object instanceof Map) {
        value = DefinitionUtils.getRealValue(value, context);
        if (value instanceof DefinitionSupportedList && ((DefinitionSupportedList) value).hasDefinitions()) {
            List collection = new ArrayList();
            for (Object element : (Collection) value) {
                Object realElement = DefinitionUtils.getRealValue(element, context);
                if (realElement != ConfigUtils.IGNORE_VALUE) {
                    collection.add(realElement);
                }
            }
            value = collection;
        }
        if (value != ConfigUtils.IGNORE_VALUE) {
            ((Map) object).put(property, value);
        }
    } else {
        PropertyDescriptor propertyDescriptor = PropertyUtils.getPropertyDescriptor(object, property);
        if (propertyDescriptor != null) {
            Method readMethod = propertyDescriptor.getReadMethod();
            Method writeMethod = propertyDescriptor.getWriteMethod();

            Class<?> propertyType = propertyDescriptor.getPropertyType();
            if (writeMethod != null) {
                Class<?> oldImpl = context.getDefaultImpl();
                try {
                    context.setDefaultImpl(propertyType);
                    value = DefinitionUtils.getRealValue(value, context);
                } finally {
                    context.setDefaultImpl(oldImpl);
                }
                if (!propertyType.equals(String.class) && value instanceof String) {
                    if (propertyType.isEnum()) {
                        value = Enum.valueOf((Class) propertyType, (String) value);
                    } else if (StringUtils.isBlank((String) value)) {
                        value = null;
                    }
                } else if (value instanceof DefinitionSupportedList
                        && ((DefinitionSupportedList) value).hasDefinitions()) {
                    List collection = new ArrayList();
                    for (Object element : (Collection) value) {
                        Object realElement = DefinitionUtils.getRealValue(element, context);
                        if (realElement != ConfigUtils.IGNORE_VALUE) {
                            collection.add(realElement);
                        }
                    }
                    value = collection;
                }
                if (value != ConfigUtils.IGNORE_VALUE) {
                    writeMethod.invoke(object, new Object[] { ConvertUtils.convert(value, propertyType) });
                }
            } else if (readMethod != null && Collection.class.isAssignableFrom(propertyType)) {
                Collection collection = (Collection) readMethod.invoke(object, EMPTY_ARGS);
                if (collection != null) {
                    if (value instanceof DefinitionSupportedList
                            && ((DefinitionSupportedList) value).hasDefinitions()) {
                        for (Object element : (Collection) value) {
                            Object realElement = DefinitionUtils.getRealValue(element, context);
                            if (realElement != ConfigUtils.IGNORE_VALUE) {
                                collection.add(realElement);
                            }
                        }
                    } else {
                        collection.addAll((Collection) value);
                    }
                }
            } else {
                throw new NoSuchMethodException(
                        "Property [" + property + "] of [" + object + "] is not writable.");
            }
        } else {
            throw new NoSuchMethodException("Property [" + property + "] not found in [" + object + "].");
        }
    }
}

From source file:com.google.feedserver.util.BeanUtil.java

/**
 * Applies a collection of properties to a JavaBean. Converts String and
 * String[] values to correct property types
 * //from w  w w  . j  a  v  a  2s  .  c o  m
 * @param properties A map of the properties to set on the JavaBean
 * @param bean The JavaBean to set the properties on
 */
public void convertPropertiesToBean(Map<String, Object> properties, Object bean) throws IntrospectionException,
        IllegalArgumentException, IllegalAccessException, InvocationTargetException, ParseException {
    BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass(), Object.class);
    for (PropertyDescriptor p : beanInfo.getPropertyDescriptors()) {
        String name = p.getName();
        Object value = properties.get(name);
        Method reader = p.getReadMethod();
        Method writer = p.getWriteMethod();
        // we only care about "complete" properties
        if (reader != null && writer != null && value != null) {
            Class<?> propertyType = writer.getParameterTypes()[0];
            if (isBean(propertyType)) {
                // this is a bean
                if (propertyType.isArray()) {
                    propertyType = propertyType.getComponentType();
                    Object beanArray = Array.newInstance(propertyType, 1);

                    if (value.getClass().isArray()) {
                        Object[] valueArrary = (Object[]) value;
                        int length = valueArrary.length;
                        beanArray = Array.newInstance(propertyType, length);
                        for (int index = 0; index < valueArrary.length; ++index) {
                            Object valueObject = valueArrary[index];
                            fillBeanInArray(propertyType, beanArray, index, valueObject);
                        }
                    } else {
                        fillBeanInArray(propertyType, beanArray, 0, value);
                    }
                    value = beanArray;
                } else if (propertyType == Timestamp.class) {
                    value = new Timestamp(TIMESTAMP_FORMAT.parse((String) value).getTime());
                } else {
                    Object beanObject = createBeanObject(propertyType, value);
                    value = beanObject;
                }
            } else {
                Class<?> valueType = value.getClass();
                if (!propertyType.isAssignableFrom(valueType)) {
                    // convert string input values to property type
                    try {
                        if (valueType == String.class) {
                            value = ConvertUtils.convert((String) value, propertyType);
                        } else if (valueType == String[].class) {
                            value = ConvertUtils.convert((String[]) value, propertyType);
                        } else if (valueType == Object[].class) {
                            // best effort conversion
                            Object[] objectValues = (Object[]) value;
                            String[] stringValues = new String[objectValues.length];
                            for (int i = 0; i < objectValues.length; i++) {
                                stringValues[i] = objectValues[i] == null ? null : objectValues[i].toString();
                            }
                            value = ConvertUtils.convert(stringValues, propertyType);
                        } else {
                        }
                    } catch (ConversionException e) {
                        throw new IllegalArgumentException(
                                "Conversion failed for " + "property '" + name + "' with value '" + value + "'",
                                e);
                    }
                }
            }
            // We only write values that are present in the map. This allows
            // defaults or previously set values in the bean to be retained.
            writer.invoke(bean, value);
        }
    }
}

From source file:com.liusoft.dlog4j.search.SearchProxy.java

/**
 * ?//w w w .j av a  2  s .  c o  m
 * @param params
 * @return
 * @throws Exception 
 */
public static List search(SearchParameter params) throws Exception {
    if (params == null)
        return null;

    SearchEnabled searching = (SearchEnabled) params.getSearchObject().newInstance();

    StringBuffer path = new StringBuffer(_baseIndexPath);
    path.append(searching.name());
    File f = new File(path.toString());
    if (!f.exists())
        return null;

    IndexSearcher searcher = new IndexSearcher(path.toString());

    //?
    BooleanQuery comboQuery = new BooleanQuery();
    int _query_count = 0;
    StringTokenizer st = new StringTokenizer(params.getSearchKey());
    while (st.hasMoreElements()) {
        String q = st.nextToken();
        String[] indexFields = searching.getIndexFields();
        for (int i = 0; i < indexFields.length; i++) {
            QueryParser qp = new QueryParser(indexFields[i], analyzer);
            try {
                Query subjectQuery = qp.parse(q);
                comboQuery.add(subjectQuery, BooleanClause.Occur.SHOULD);
                _query_count++;
            } catch (Exception e) {
                log.error("Add query parameter failed. key=" + q, e);
            }
        }
    }

    if (_query_count == 0)//?
        return null;

    //??
    MultiFilter multiFilter = null;
    HashMap conds = params.getConditions();
    if (conds != null) {
        Iterator keys = conds.keySet().iterator();
        while (keys.hasNext()) {
            if (multiFilter == null)
                multiFilter = new MultiFilter(0);
            String key = (String) keys.next();
            multiFilter.add(new FieldFilter(key, conds.get(key).toString()));
        }
    }

    /*
     * Creates a sort, possibly in reverse,
     * by terms in the given field with the type of term values explicitly given.
     */
    SortField[] s_fields = new SortField[2];
    s_fields[0] = SortField.FIELD_SCORE;
    s_fields[1] = new SortField(searching.getKeywordField(), SortField.INT, true);
    Sort sort = new Sort(s_fields);

    Hits hits = searcher.search(comboQuery, multiFilter, sort);
    int numResults = hits.length();
    //System.out.println(numResults + " found............................");
    int result_count = Math.min(numResults, MAX_RESULT_COUNT);
    List results = new ArrayList(result_count);
    for (int i = 0; i < result_count; i++) {
        Document doc = (Document) hits.doc(i);
        //Java
        Object result = params.getSearchObject().newInstance();
        Enumeration fields = doc.fields();
        while (fields.hasMoreElements()) {
            Field field = (Field) fields.nextElement();
            //System.out.println(field.name()+" -- "+field.stringValue());
            if (CLASSNAME_FIELD.equals(field.name()))
                continue;
            //?
            if (!field.isStored())
                continue;
            //System.out.println("=========== begin to mapping ============");
            //String --> anything
            Class fieldType = getNestedPropertyType(result, field.name());
            //System.out.println(field.name()+", class = " + fieldType.getName());
            Object fieldValue = null;
            if (fieldType.equals(Date.class))
                fieldValue = new Date(Long.parseLong(field.stringValue()));
            else
                fieldValue = ConvertUtils.convert(field.stringValue(), fieldType);
            //System.out.println(fieldValue+", class = " + fieldValue.getClass().getName());
            setNestedProperty(result, field.name(), fieldValue);
        }
        results.add(result);
    }

    return results;
}

From source file:net.firejack.platform.core.store.registry.resource.ResourceVersionStore.java

private void copyResourceVersionProperties(RV dest, RV orig) {
    PropertyUtilsBean propertyUtils = BeanUtilsBean.getInstance().getPropertyUtils();
    PropertyDescriptor[] propertyDescriptors = propertyUtils.getPropertyDescriptors(orig);
    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        String name = propertyDescriptor.getName();
        if (ArrayUtils.contains(new String[] { "class", "id", "version", "status", "updated", "created" },
                name)) {//from w w  w .  j av a 2 s. com
            continue;
        }
        if (propertyUtils.isReadable(orig, name) && propertyUtils.isWriteable(dest, name)) {
            try {
                Object value = propertyUtils.getSimpleProperty(orig, name);
                if (value instanceof Timestamp) {
                    value = ConvertUtils.convert(value, Date.class);
                }
                BeanUtils.copyProperty(dest, name, value);
            } catch (Exception e) {
                // Should not happen
            }
        }
    }
}

From source file:com.beidou.common.util.ReflectionUtils.java

/**
 * ?.//from w  w  w . ja va 2 s .  c  o m
 * 
 * @param value ?
 * @param toType ?
 */
public static Object convertStringToObject(String value, Class<?> toType) {
    try {
        return ConvertUtils.convert(value, toType);
    } catch (Exception e) {
        throw convertReflectionExceptionToUnchecked(e);
    }
}

From source file:net.mojodna.searchable.AbstractSearcher.java

/**
 * Search the index with the specified query.
 * /*  w w  w .j a v a  2  s .c  o m*/
 * @param query Query to use.
 * @param filter Filter to use.
 * @param searcher Lucene Searcher to perform the search with.
 * @param offset Offset to begin result set at.
 * @param count Number of results to return.
 * @param sort Sort to use.
 * @return ResultSet containing results.
 * @throws SearchException 
 * @throws IOException 
 */
protected ResultSet doSearch(final Query query, final Filter filter, final Searcher searcher,
        final Integer offset, final Integer count, final Sort sort) throws SearchException, IOException {
    // execute the search
    log.debug("Searching with query: " + query.toString());
    final Hits hits = searcher.search(query, filter, sort);

    // create a container for results
    final List<Result> results = new LinkedList<Result>();

    // instantiate and initialize the ResultSet
    final ResultSetImpl rs = new ResultSetImpl(hits.length());
    rs.setQuery(query);

    final int numResults;
    if (null != count)
        numResults = Math.min(offset + count, hits.length());
    else
        numResults = hits.length();

    rs.setOffset(offset);

    // loop through results starting at offset and stopping after numResults
    for (int i = offset; i < numResults; i++) {
        final Document doc = hits.doc(i);
        Result result = null;

        // load the class name
        final String className = doc.get(TYPE_FIELD_NAME);
        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
                final String id = doc.get(ID_FIELD_NAME);
                final Field idClass = doc.getField(ID_TYPE_FIELD_NAME);
                if (null != id) {
                    log.debug("Setting id to '" + id + "' of type " + idClass.stringValue());
                    try {
                        final Object idValue = ConvertUtils.convert(id, Class.forName(idClass.stringValue()));
                        PropertyUtils.setSimpleProperty(result, idField, idValue);
                    } catch (final ClassNotFoundException e) {
                        log.warn("Id type was not a class that could be found: " + idClass.stringValue());
                    }
                } else {
                    log.warn("Id value was null.");
                }
            } else {
                final GenericResult gr = new GenericResult();
                gr.setId(doc.get(ID_FIELD_NAME));
                gr.setType(doc.get(TYPE_FIELD_NAME));
                result = gr;
            }

            // load stored fields and put them in the Result
            final Map<String, String> storedFields = new HashMap<String, String>();
            final Enumeration fields = doc.fields();
            while (fields.hasMoreElements()) {
                final Field f = (Field) fields.nextElement();
                // exclude private fields
                if (!PRIVATE_FIELD_NAMES.contains(f.name())
                        && !f.name().startsWith(IndexSupport.SORTABLE_PREFIX))
                    storedFields.put(f.name(), f.stringValue());
            }
            result.setStoredFields(storedFields);
        } catch (final Exception e) {
            throw new SearchException("Could not reconstitute resultant object.", e);
        }

        result.setRanking(i);
        result.setScore(hits.score(i));

        results.add(result);
    }

    rs.setResults(results);
    searcher.close();
    return rs;
}

From source file:com.iisigroup.cap.utils.CapBeanUtil.java

public static <T> T setField(T entry, String fieldId, Object value) {
    Field field = ReflectionUtils.findField(entry.getClass(), fieldId);
    if (field != null) {
        String setter = new StringBuffer("set").append(String.valueOf(field.getName().charAt(0)).toUpperCase())
                .append(field.getName().substring(1)).toString();
        Method method = ReflectionUtils.findMethod(entry.getClass(), setter, new Class[] { field.getType() });
        if (method != null) {
            try {
                if (field.getType() != String.class && "".equals(value)) {
                    value = null;/*  ww  w.  j ava  2 s .  c om*/
                } else if (field.getType() == BigDecimal.class) {
                    value = CapMath.getBigDecimal(String.valueOf(value));
                } else if (value instanceof String) {
                    if (field.getType() == java.util.Date.class || field.getType() == java.sql.Date.class) {
                        value = CapDate.parseDate((String) value);
                    } else if (field.getType() == Timestamp.class) {
                        value = CapDate.convertStringToTimestamp1((String) value);
                    }
                }
                if (value == null) {
                    method.invoke(entry, new Object[] { null });
                } else {
                    method.invoke(entry, ConvertUtils.convert(value, field.getType()));
                }
            } catch (Exception e) {
                if (LOGGER.isTraceEnabled()) {
                    LOGGER.trace(e.getMessage());
                } else {
                    LOGGER.warn(e.getMessage(), e);
                }
            }
        }
    }
    return entry;
}

From source file:com.hihframework.core.utils.ReflectUtil.java

/**
 * ?clazzproperty./*from  w ww.j a v  a 2s.c om*/
 * 
 * @param value ?
 * @param clazz ???Class
 * @param propertyName ???Class.
 */
public static Object convertValue(Object value, Class<?> toType) {
    try {
        DateConverter dc = new DateConverter();
        dc.setUseLocaleFormat(true);
        dc.setPatterns(new String[] { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss" });
        ConvertUtils.register(dc, Date.class);
        return ConvertUtils.convert(value, toType);
    } catch (Exception e) {
        throw convertReflectionExceptionToUnchecked(e);
    }
}

From source file:com.cartmatic.estore.common.helper.ConfigUtil.java

public int[] getProductReviewGivenPoints() {
    String temp_productReviewGivenPoints = getConfig("ProductReviewGivenPoints", "1,2,3,4,5");
    int[] productReviewGivenPoints = (int[]) ConvertUtils.convert(temp_productReviewGivenPoints.split(","),
            int.class);
    return productReviewGivenPoints;
}

From source file:com.cartmatic.estore.common.helper.ConfigUtil.java

public int[] getFeedbackGivenPoints() {
    String temp_feedbackGivenPoints = getConfig("FeedbackGivenPoints", "1,2,3,4,5");
    int[] feedbackGivenPoints = (int[]) ConvertUtils.convert(temp_feedbackGivenPoints.split(","), int.class);
    return feedbackGivenPoints;
}