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:org.eclipse.smila.management.jmx.client.helpers.ConversionHelper.java

/**
 * Convert./*w  ww .  j av  a 2 s .  c o m*/
 * 
 * @param parameter
 *          the parameter
 * @param className
 *          the class name
 * 
 * @return the object
 */
public static Object convert(final String parameter, final String className) {
    final Class clazz;
    try {
        clazz = Class.forName(className);
    } catch (final ClassNotFoundException e) {
        throw new IllegalArgumentException(e);
    }
    return ConvertUtils.convert(parameter, clazz);
}

From source file:org.eiichiro.bootleg.AbstractRequest.java

/**
 * Converts the specified object to the specified type.
 * This method is overridable. You can provide your own conversion to the 
 * parameter construction by overriding this method.
 * //  w w w  .j av a  2  s  .  c om
 * @param object The object to be converted
 * @param type The type to which the specified object be converted.
 * @return The converted object.
 */
protected Object convert(Object object, Class<?> type) {
    try {
        return ConvertUtils.convert(object, type);
    } catch (Exception e) {
        logger.warn("Cannot convert [" + object + "] to [" + type + "]", e);
        return null;
    }
}

From source file:org.eiichiro.bootleg.json.ValueTypeJsonSerializer.java

/**
 * Serializes the specified user-defined value type object to 
 * <code>JsonPrimitive</code> representation.
 *///from   ww w. j  av a  2s.co  m
public JsonElement serialize(T src, Type typeOfSrc, JsonSerializationContext context) {
    Class<?> type = Types.getRawType(typeOfSrc);
    Converter converter = ConvertUtils.lookup(type);

    if ((converter != null && converter instanceof AbstractConverter)) {
        String string = (String) ConvertUtils.convert(src, String.class);

        if (string != null) {
            return new JsonPrimitive(string);
        }
    }

    return new JsonPrimitive(src.toString());
}

From source file:org.eiichiro.bootleg.xml.ValueTypeXmlAdapter.java

/**
 * Marshals the specified user-defined value type object to single XML value 
 * string representation./*from w ww. java  2  s .co  m*/
 * 
 * @throws If the specified object is not a user-defined value type.
 */
@Override
public String marshal(BoundType v) throws Exception {
    Class<? extends Object> type = v.getClass();

    if (!Types.isUserDefinedValueType(type)) {
        throw new IllegalArgumentException("Type [" + type + "] must be an user-defined value type; "
                + "@XmlJavaTypeAdapter(ValueTypeXmlAdapter.class) "
                + "can be annotated to user-defined value type and field only");
    }

    Converter converter = ConvertUtils.lookup(type);

    if ((converter != null && converter instanceof AbstractConverter)) {
        String string = (String) ConvertUtils.convert(v, String.class);

        if (string != null) {
            return string;
        }
    }

    return v.toString();
}

From source file:org.fhcrc.cpl.toolbox.datastructure.BoundMap.java

@Override
public Object put(String key, Object value) {
    try {/*from  ww  w .j  a va  2  s.  c o m*/
        BoundProperty bound = getBoundProperty(key);
        if (null != bound) {
            Object previous = null;
            if (null == bound._setter)
                throw new IllegalArgumentException("Can not set property " + key);
            if (null != value && !bound._type.isAssignableFrom(value.getClass()))
                value = ConvertUtils.convert(value.toString(), bound._type);
            if (null != bound._getter)
                previous = bound._getter.invoke(_bean);
            if (value != previous) {
                assert key != _keyDebug : "infinite recursion???";
                //noinspection ConstantConditions
                assert null != (_keyDebug = key);
                bound._setter.invoke(_bean, value);
            }
            return previous;
        }
    } catch (IllegalAccessException x) {
        throw new RuntimeException(x);
    } catch (InvocationTargetException x) {
        throw new RuntimeException(x);
    } finally {
        //noinspection ConstantConditions
        assert null == (_keyDebug = null);
    }
    return _map.put(key, value);
}

From source file:org.fhcrc.cpl.toolbox.filehandler.TabLoader.java

/**
 * Look at first 5 lines of the file and infer col names, data types.
 * Most useful if maps are being returned, otherwise use inferColumnInfo(reader, clazz) to
 * use properties of a bean instead./* w w  w .  j  ava  2s .  c o  m*/
 *
 * @param reader
 * @throws IOException
 */
private void inferColumnInfo(BufferedReader reader) throws IOException {
    reader.mark(4096 * _scanAheadLineCount);

    String[] lines = new String[_scanAheadLineCount + Math.max(_skipLines, 0)];
    int i;
    for (i = 0; i < lines.length;) {
        String line = reader.readLine();
        if (null == line)
            break;
        if (line.length() == 0 || line.charAt(0) == '#')
            continue;
        lines[i++] = line;
    }
    int nLines = i;
    reader.reset();
    if (nLines == 0) {
        _columns = new ColumnDescriptor[0];
        return;
    }

    int nCols = 0;
    String[][] lineFields = new String[nLines][];
    for (i = 0; i < nLines; i++) {
        lineFields[i] = parseLine(lines[i]);
        nCols = Math.max(nCols, lineFields[i].length);
    }

    ColumnDescriptor[] colDescs = new ColumnDescriptor[nCols];
    for (i = 0; i < nCols; i++)
        colDescs[i] = new ColumnDescriptor();

    //Try to infer types
    int inferStartLine = _skipLines == -1 ? 1 : _skipLines;
    for (int f = 0; f < nCols; f++) {
        int classIndex = -1;
        for (int line = inferStartLine; line < nLines; line++) {
            if (f >= lineFields[line].length)
                continue;
            String field = lineFields[line][f];
            if ("".equals(field))
                continue;

            for (int c = Math.max(classIndex, 0); c < convertClasses.length; c++) {
                //noinspection EmptyCatchBlock
                try {
                    Object o = ConvertUtils.convert(field, convertClasses[c]);
                    //We found a type that works. If it is more general than
                    //what we had before, we must use it.
                    if (o != null && c > classIndex)
                        classIndex = c;
                    break;
                } catch (Exception x) {
                }
            }
        }
        colDescs[f].clazz = classIndex == -1 ? String.class : convertClasses[classIndex];
    }

    //If first line is compatible type for all fields, AND all fields not Strings (dhmay adding 20100502)
    // then there is no header row
    if (_skipLines == -1) {
        boolean firstLineCompat = true;
        boolean allStrings = true;
        String[] fields = lineFields[0];
        for (int f = 0; f < nCols; f++) {
            if ("".equals(fields[f]))
                continue;
            if (colDescs[f].clazz.equals(Integer.TYPE) || colDescs[f].clazz.equals(Double.TYPE)
                    || colDescs[f].clazz.equals(Float.TYPE))
                allStrings = false;
            try {
                Object o = ConvertUtils.convert(fields[f], colDescs[f].clazz);
                if (null == o) {
                    firstLineCompat = false;
                    break;
                }
            } catch (Exception x) {
                firstLineCompat = false;
                break;
            }
        }
        if (firstLineCompat && !allStrings)
            _skipLines = 0;
        else
            _skipLines = 1;
    }

    if (_skipLines > 0) {
        String[] headers = lineFields[_skipLines - 1];
        for (int f = 0; f < nCols; f++)
            colDescs[f].name = (f >= headers.length || "".equals(headers[f])) ? "column" + f : headers[f];
    } else {
        for (int f = 0; f < colDescs.length; f++) {
            ColumnDescriptor colDesc = colDescs[f];
            colDesc.name = "column" + f;
        }
    }

    _columns = colDescs;
}

From source file:org.fhcrc.cpl.toolbox.filehandler.TabLoader.java

public Object[] loadColsAsArrays() throws IOException {
    initColNameMap();//www .j a  v  a2 s  . co  m
    ColumnDescriptor[] columns = getColumns();
    Object[] valueLists = new Object[columns.length];

    for (int i = 0; i < valueLists.length; i++) {
        if (!columns[i].load)
            continue;

        Class clazz = columns[i].clazz;
        if (clazz.isPrimitive()) {
            if (clazz.equals(Double.TYPE))
                valueLists[i] = new DoubleArray();
            else if (clazz.equals(Float.TYPE))
                valueLists[i] = new FloatArray();
            else if (clazz.equals(Integer.TYPE))
                valueLists[i] = new IntegerArray();
        } else {
            valueLists[i] = new ArrayList();
        }
    }

    BufferedReader reader = null;
    try {
        reader = getReader();
        int line = 0;

        String s;
        for (int skip = 0; skip < _skipLines; skip++) {
            //noinspection UnusedAssignment
            s = reader.readLine();
            line++;
        }

        while ((s = reader.readLine()) != null) {
            line++;
            if ("".equals(s.trim()))
                continue;

            String[] fields = parseLine(s);
            for (int i = 0; i < fields.length && i < columns.length; i++) {
                if (!columns[i].load)
                    continue;

                String value = fields[i];

                Class clazz = columns[i].clazz;
                if (clazz.isPrimitive()) {
                    if (clazz.equals(Double.TYPE))
                        ((DoubleArray) valueLists[i]).add(Double.parseDouble(value));
                    else if (clazz.equals(Float.TYPE))
                        ((FloatArray) valueLists[i]).add(Float.parseFloat(value));
                    else if (clazz.equals(Integer.TYPE))
                        ((IntegerArray) valueLists[i]).add(Integer.parseInt(value));
                } else {
                    try {
                        if ("".equals(value))
                            ((List<Object>) valueLists[i]).add(columns[i].missingValues);
                        else
                            ((List<Object>) valueLists[i]).add(ConvertUtils.convert(value, columns[i].clazz));
                    } catch (Exception x) {
                        if (_throwOnErrors)
                            throw new ConversionException(
                                    "Conversion error: line " + line + " column " + (i + 1), x);

                        ((List<Object>) valueLists[i]).add(columns[i].errorValues);
                    }
                }

            }
        }
    } finally {
        if (null != reader)
            reader.close();
    }

    Object[] returnArrays = new Object[columns.length];
    for (int i = 0; i < columns.length; i++) {
        if (!columns[i].load)
            continue;

        Class clazz = columns[i].clazz;
        if (clazz.isPrimitive()) {
            if (clazz.equals(Double.TYPE))
                returnArrays[i] = ((DoubleArray) valueLists[i]).toArray(null);
            else if (clazz.equals(Float.TYPE))
                returnArrays[i] = ((FloatArray) valueLists[i]).toArray(null);
            else if (clazz.equals(Integer.TYPE))
                returnArrays[i] = ((IntegerArray) valueLists[i]).toArray(null);
        } else {
            Object[] values = (Object[]) Array.newInstance(columns[i].clazz, ((List) valueLists[i]).size());
            returnArrays[i] = ((List<Object>) valueLists[i]).toArray(values);
        }
    }

    return returnArrays;
}

From source file:org.geomajas.layer.hibernate.HibernateFeatureModel.java

@Override
public Object newInstance(String id) throws LayerException {
    try {//from  w ww . j  ava 2s.  c om
        Serializable ser = (Serializable) ConvertUtils.convert(id,
                getEntityMetadata().getIdentifierType().getReturnedClass());
        return getEntityMetadata().instantiate(ser,
                (SessionImplementor) getSessionFactory().getCurrentSession());
    } catch (Exception e) { // NOSONAR
        throw new LayerException(e, ExceptionCode.HIBERNATE_CANNOT_CREATE_POJO,
                getFeatureInfo().getDataSourceName());
    }
}

From source file:org.geomajas.layer.hibernate.HibernateLayer.java

private Object getFeature(String featureId) throws HibernateLayerException {
    Session session = getSessionFactory().getCurrentSession();
    return session.get(getFeatureInfo().getDataSourceName(), (Serializable) ConvertUtils.convert(featureId,
            getEntityMetadata().getIdentifierType().getReturnedClass()));
}

From source file:org.gridgain.grid.util.json.GridJsonDeserializer.java

/**
 * Injects data from map to object./* w  ww  .  j av a 2s.  co m*/
 *
 * @param obj Object for injecting.
 * @param map Map with data.
 * @throws GridException If any exception occurs while data injecting.
 */
@SuppressWarnings("unchecked")
private static void mapInject(Object obj, Map map) throws GridException {
    assert obj != null;
    assert map != null;

    if (map.size() > 0) {
        Method[] mtds = obj.getClass().getMethods();

        for (String key : (Set<String>) map.keySet()) {
            boolean isFound = false;

            String mtdName = "set" + StringUtils.capitalize(key);

            for (Method mtd : mtds)
                if (mtd.getName().equals(mtdName) && mtd.getParameterTypes().length == 1
                        && mtd.getAnnotation(GridSpiConfiguration.class) != null) {
                    Object val = map.get(key);

                    Class cls = mtd.getParameterTypes()[0];

                    if (val == null || !cls.isAssignableFrom(val.getClass()))
                        val = ConvertUtils.convert(val, cls);

                    try {
                        mtd.invoke(obj, val);
                    } catch (IllegalAccessException e) {
                        throw new GridException("Can't set value " + val + " with method " + mtdName + ".", e);
                    } catch (InvocationTargetException e) {
                        throw new GridException("Can't set value " + val + " with method " + mtdName + ".", e);
                    }

                    isFound = true;

                    break;
                }

            if (!isFound)
                throw new GridException("Method " + mtdName + " not found or not annotated with @"
                        + GridSpiConfiguration.class.getSimpleName() + " in object " + obj + '.');
        }
    }
}