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.beanfuse.struts2.action.helper.ParamHelper.java

public static Object get(Class clazz, String name) {
    String strValue = get(name);//from  w  ww. j a v a  2 s. c om
    if (StringUtils.isNotBlank(strValue)) {
        return ConvertUtils.convert(strValue, clazz);
    } else {
        return null;
    }
}

From source file:org.beanfuse.struts2.action.helper.ParamHelper.java

public static boolean getBool(String name) {
    String strValue = get(name);/*from  w  ww  .  j  a va2  s .c o  m*/
    if (StringUtils.isEmpty(strValue))
        return false;
    else
        return ((Boolean) ConvertUtils.convert(strValue, Boolean.class)).booleanValue();
}

From source file:org.beangle.commons.property.PropertyConfigBean.java

@SuppressWarnings("unchecked")
public <T> T get(Class<T> clazz, String name) {
    Object value = get(name);/*from w w w  .  java  2 s  .com*/
    if (null == value) {
        return null;
    } else {
        return (T) ConvertUtils.convert(value, clazz);
    }
}

From source file:org.beangle.ems.security.restrict.service.IdentifierDataResolver.java

@SuppressWarnings("unchecked")
public <T> List<T> unmarshal(RestrictField field, String text) {
    if (null == field.getType()) {
        return (List<T>) CollectUtils.newArrayList(StringUtils.split(text, ","));
    } else {/*www . j  a va 2s.  co m*/
        Class<?> clazz = null;
        try {
            clazz = Class.forName(field.getType());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        EntityType myType = Model.getEntityType(clazz);
        OqlBuilder<T> builder = OqlBuilder.from(myType.getEntityName(), "restrictField");

        String[] ids = StringUtils.split(text, ",");
        PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(clazz, field.getKeyName());
        Class<?> propertyType = pd.getReadMethod().getReturnType();
        List<Object> realIds = CollectUtils.newArrayList(ids.length);
        for (String id : ids) {
            Object realId = ConvertUtils.convert(id, propertyType);
            realIds.add(realId);
        }
        builder.where("restrictField." + field.getKeyName() + " in (:ids)", realIds).cacheable();
        return entityDao.search(builder);
    }
}

From source file:org.bitsofinfo.util.address.usps.ais.loader.USPSDataFileFieldHelper.java

public static Object[] extractValue(String rawRecord, Field f) throws RecordParseException {
    USPSDataFileField ann = f.getAnnotation(USPSDataFileField.class);

    // DataFileField.starts are all 1 based, so adjust back 1
    int start = ann.start() - 1;

    // get the target field name 
    String fieldName = f.getName();

    String rawValue = null;//  www  .j  a v  a 2s.  c o m
    try {
        // extract the value
        rawValue = rawRecord.substring(start, start + ann.length());

    } catch (IndexOutOfBoundsException e) {
        throw new RecordParseException("Could not extract data for field: " + fieldName
                + ". USPSDataFileField annotation specifys combination" + " of start=" + start + " length="
                + ann.length() + " which is" + " out of bounds for the raw data line being parsed..", rawRecord,
                e);
    }

    // convert blanks into nulls
    if (StringUtils.isBlank(rawValue)) {
        rawValue = null;
    }

    // the target member's data type 
    Class fieldClass = f.getType();

    // use bean utils to do any necessary conversion on the raw value
    Object trueValue = ConvertUtils.convert(rawValue, fieldClass);

    // trim it
    if (trueValue instanceof String) {
        trueValue = ((String) trueValue).trim();
    }

    Object[] toReturn = new Object[2];
    toReturn[0] = rawValue;
    toReturn[1] = trueValue;
    return toReturn;

}

From source file:org.bitsofinfo.util.address.usps.ais.store.hbase.HBaseStore.java

@Override
public USPSRecord getByIdentifier(String identifier) throws StoreException {

    Class<? extends USPSRecord> clazz = null;
    try {//from   w w  w  .j a  va 2s .com
        clazz = uspsIdGenerator.getRecordType(identifier);
    } catch (Exception e) {
        throw new StoreException("Error translating identifier into a target table type: " + identifier, e);
    }

    HTable table = getTable(clazz);
    if (table == null) {
        throw new StoreException("No target table exists for searching by identifier of " + identifier, null);
    }

    // lets create a get for the KV lookup
    Get g = new Get(Bytes.toBytes(identifier));

    Result result = null;
    try {
        // exec the get
        result = table.get(g);
    } catch (Exception e) {
        throw new StoreException("There was an unexpected error fetching by identifier: " + identifier, e);
    }

    // not found??
    if (result == null) {
        return null;
    }

    // create a dummy record
    USPSRecord record = null;
    try {
        record = clazz.newInstance();
    } catch (Exception e) {
        throw new StoreException("Error constructing target object for class: " + clazz.getName(), e);
    }

    // get all columns
    Field[] columns = getFields(clazz);

    // family as bytes
    byte[] datacols = Bytes.toBytes(DATA_COL_FAMILY);

    // map to the properties
    for (Field column : columns) {
        byte[] bc = Bytes.toBytes(column.getName());
        byte[] colVal = result.getValue(datacols, bc);
        if (colVal != null) {
            try {
                Object trueValue;

                // convert the copyright into the object
                if (column.getType() == Copyright.class) {
                    record.setCopyright(getCopyright(new String(colVal)));

                } else {
                    trueValue = ConvertUtils.convert(new String(colVal), column.getType());
                    PropertyUtils.setSimpleProperty(record, column.getName(), trueValue);
                }

            } catch (Exception e) {
                throw new StoreException("Error setting property for column: " + column.getName()
                        + " with value " + new String(colVal), e);
            }
        }
    }

    try {
        table.close();
    } catch (Exception e) {
        throw new StoreException(
                "Error closing table, when reading by identifier from target table: " + identifier, e);
    }

    return record;
}

From source file:org.deegree.db.datasource.DataSourceInitializer.java

Object getJavaArg(Argument argument) throws ClassNotFoundException {
    Class<?> parameterClass = null;
    try {/*www  .j  a  va  2  s. c  om*/
        parameterClass = getClass(argument.getJavaClass());
        final Class<?> primitiveClass = MethodUtils.getPrimitiveType(parameterClass);
        if (primitiveClass != null) {
            parameterClass = primitiveClass;
        }
    } catch (ClassNotFoundException e) {
        throw e;
    }
    return ConvertUtils.convert(argument.getValue(), parameterClass);
}

From source file:org.eclipse.eavp.viz.service.csv.CSVPlot.java

/**
 * Attempts to load the CSV series data from the specified file. This
 * operation ignores all data that is marked as comments (i.e. if the line
 * starts with #), and ignores comments after the data in a line as well.
 * This operation takes the first column of CSV data as the independent
 * series, and the rest as normal, dependent series to be added to the plot.
 * Note that only the first dependent series (the second column) will be
 * initially enabled to be drawn on the plot editor.
 * /*from   w w w. j av  a2  s  . c o m*/
 * @param file
 *            The file to load, assumed to be a valid file.
 */
private void load(File file) {
    // Initially set the name to the file name.
    String plotName = file.getName();
    setPlotTitle(plotName);

    // Configure the list
    ArrayList<String[]> lines = new ArrayList<String[]>();

    try {
        // Grab the contents of the file
        BufferedReader reader = new BufferedReader(new FileReader(file));
        String line = null;
        while ((line = reader.readLine()) != null) {
            // Skip lines that pure comments
            if (!line.startsWith("#")) {
                // Clip the line if it has a comment symbol in it to be
                // everything before the symbol
                if (line.contains("#")) {
                    int index = line.indexOf("#");
                    line = line.substring(0, index);
                }
                // Clean up any bad stuff on the line
                String[] lineArray = line.trim().split(",");
                String[] trimmedLine = new String[lineArray.length];
                // And clean up any bad stuff on each split piece
                for (int i = 0; i < lineArray.length; i++) {
                    trimmedLine[i] = lineArray[i].trim();
                }
                // Put the lines in the list
                lines.add(trimmedLine);
            }
        }

        reader.close();

    } catch (IOException e) {
        // Complain
        logger.error(
                getClass().getName() + " Exception! Could not read in data from file: " + file.getName() + ".",
                e);
    }

    if (!lines.isEmpty()) {

        // TODO- Some sort of implementation to read in the style
        // configurations for the plot, axes, and series. How to go about
        // this? A large part of the series implementation is not being
        // utilized without some sort of recognition here of the style
        // attributes!

        // Assume that the first line has information about the data
        String[] seriesNames = lines.remove(0);

        // Creates the series that contain the data loaded from the file.
        CSVSeries[] series = new CSVSeries[seriesNames.length];
        for (int i = 0; i < seriesNames.length; i++) {
            series[i] = new CSVSeries();
            series[i].setEnabled(false);
            series[i].setLabel(seriesNames[i]);
        }

        // Sets the first two series to be automatically plotted
        series[0].setEnabled(true);
        if (series.length > 1) {
            series[1].setEnabled(true);
        }

        // Load the data as doubles
        for (int i = 0; i < lines.size(); i++) {
            double[] values = (double[]) ConvertUtils.convert(lines.get(i), Double.TYPE);
            for (int j = 0; j < values.length; j++) {
                series[j].add(values[j]);
            }
        }

        // If the independent series has not been set, use the default value
        // just created
        if (getIndependentSeries() == null) {
            // Just set the first series as the independent series for now
            setIndependentSeries(series[0]);
        } else {
            // Otherwise, update the series with the new data
            for (CSVSeries s : series) {
                ISeries current = getIndependentSeries();
                if (current.getLabel().equals(s.getLabel())) {
                    setIndependentSeries(s);
                    break;
                }
            }
        }

        // Add the rest of the series as dependent series
        List<ISeries> dependentSeries = new ArrayList<ISeries>(series.length);
        for (int i = 0; i < series.length; i++) {
            dependentSeries.add(series[i]);
        }
        dataSeries.put(IPlot.DEFAULT_CATEGORY, dependentSeries);

    }

    // Loading has completed.
    loaded.set(true);

    // Notify the listeners that loading has completed.
    notifyPlotListeners("loaded", "true");

    return;
}

From source file:org.eclipse.ice.viz.service.csv.CSVPlot.java

/**
 * Attempts to load the CSV series data from the specified file. This
 * operation ignores all data that is marked as comments (i.e. if the line
 * starts with #), and ignores comments after the data in a line as well.
 * This operation takes the first column of CSV data as the independent
 * series, and the rest as normal, dependent series to be added to the plot.
 * Note that only the first dependent series (the second column) will be
 * initially enabled to be drawn on the plot editor.
 * /*from  w ww .  j  a  v a 2s  .c o m*/
 * @param file
 *            The file to load, assumed to be a valid file.
 */
private void load(File file) {
    // Initially set the name to the file name.
    String plotName = file.getName();
    setPlotTitle(plotName);

    // Configure the list
    ArrayList<String[]> lines = new ArrayList<String[]>();

    try {
        // Grab the contents of the file
        BufferedReader reader = new BufferedReader(new FileReader(file));
        String line = null;
        while ((line = reader.readLine()) != null) {
            // Skip lines that pure comments
            if (!line.startsWith("#")) {
                // Clip the line if it has a comment symbol in it to be
                // everything before the symbol
                if (line.contains("#")) {
                    int index = line.indexOf("#");
                    line = line.substring(0, index);
                }
                // Clean up any crap on the line
                String[] lineArray = line.trim().split(",");
                String[] trimmedLine = new String[lineArray.length];
                // And clean up any crap on each split piece
                for (int i = 0; i < lineArray.length; i++) {
                    trimmedLine[i] = lineArray[i].trim();
                }
                // Put the lines in the list
                lines.add(trimmedLine);
            }
        }

        reader.close();

    } catch (IOException e) {
        // Complain
        logger.error(
                getClass().getName() + " Exception! Could not read in data from file: " + file.getName() + ".",
                e);
    }

    if (!lines.isEmpty()) {

        // TODO- Some sort of implementation to read in the style
        // configurations for the plot, axes, and series. How to go about
        // this? A large part of the series implementation is not being
        // utilized without some sort of recognition here of the style
        // attributes!

        // Assume that the first line has information about the data
        String[] seriesNames = lines.remove(0);

        // Creates the series that contain the data loaded from the file.
        CSVSeries[] series = new CSVSeries[seriesNames.length];
        for (int i = 0; i < seriesNames.length; i++) {
            series[i] = new CSVSeries();
            series[i].setEnabled(false);
            series[i].setLabel(seriesNames[i]);
        }

        // Sets the first two series to be automatically plotted
        series[0].setEnabled(true);
        if (series.length > 1) {
            series[1].setEnabled(true);
        }

        // Load the data as doubles
        for (int i = 0; i < lines.size(); i++) {
            double[] values = (double[]) ConvertUtils.convert(lines.get(i), Double.TYPE);
            for (int j = 0; j < values.length; j++) {
                series[j].add(values[j]);
            }
        }

        // Just set the first series as the independent series for now
        setIndependentSeries(series[0]);

        // Add the rest of the series as dependent series
        List<ISeries> dependentSeries = new ArrayList<ISeries>(series.length - 1);
        dataSeries.put(IPlot.DEFAULT_CATEGORY, dependentSeries);
        for (int i = 1; i < series.length; i++) {
            dependentSeries.add(series[i]);
        }

    }

    // Loading has completed.
    loaded.set(true);

    // Notify the listeners that loading has completed.
    notifyPlotListeners("loaded", "true");

    return;
}

From source file:org.eclipse.jubula.rc.common.commands.MethodParams.java

/**
 * Adds the type and value of a method parameter to the internal lists.
 * @param param The parameter object that holds the type and value information in a string manner.
 * @throws MethodParamException If the parameter type cannot be found or If the parameter string value cannot be converted into an object defined by the parameter type.
 *///from   ww  w  . jav a2  s  . co m
public void add(MessageParam param) throws MethodParamException {
    try {
        Class type = null;
        try {
            type = Class.forName(param.getType(), true, Thread.currentThread().getContextClassLoader());
        } catch (ClassNotFoundException e) {
            // this happens if guidancer.datatype.Variable is used!
            type = Class.forName(String.class.getName(), true, Thread.currentThread().getContextClassLoader());
        }
        String stringValue = param.getValue() == null ? StringConstants.EMPTY : param.getValue();
        Object objectValue = ConvertUtils.convert(stringValue, type);
        if (objectValue == null || !type.isAssignableFrom(objectValue.getClass())) {
            throw new MethodParamException("Failed converting " //$NON-NLS-1$
                    + stringValue + " into an instance of " + type, param); //$NON-NLS-1$
        }
        m_types.add(type);
        m_objectValues.add(objectValue);
    } catch (ClassNotFoundException e) {
        throw new MethodParamException("Action parameter type not found: " + e, param); //$NON-NLS-1$
    }
}