Java Code Examples for org.apache.commons.beanutils.ConvertUtils#convert()

The following examples show how to use org.apache.commons.beanutils.ConvertUtils#convert() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Variable.java    From maven-framework-project with MIT License 6 votes vote down vote up
public Map<String, Object> getVariableMap() {
	Map<String, Object> vars = new HashMap<String, Object>();

	ConvertUtils.register(new DateConverter(), java.util.Date.class);

	if (StringUtil.isBlank(keys)) {
		return vars;
	}

	String[] arrayKey = keys.split(",");
	String[] arrayValue = values.split(",");
	String[] arrayType = types.split(",");
	for (int i = 0; i < arrayKey.length; i++) {
		String key = arrayKey[i];
		String value = arrayValue[i];
		String type = arrayType[i];

		Class<?> targetType = Enum.valueOf(PropertyType.class, type).getValue();
		Object objectValue = ConvertUtils.convert(value, targetType);
		vars.put(key, objectValue);
	}
	return vars;
}
 
Example 2
Source File: MapBasedQueryWalker.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Get the property value, converted to the requested type.
 * 
 * @param propertyName name of the parameter
 * @param type int
 * @param returnType type of object to return
 * @return the converted parameter value. Null, if the property has no
 *         value.
 * @throws IllegalArgumentException when no conversion for the given
 *             returnType is available or if returnType is null.
 * @throws InvalidArgumentException when conversion to the given type was
 *             not possible due to an error while converting
 */
@SuppressWarnings("unchecked")
public <T extends Object> T getProperty(String propertyName, int type, Class<T> returnType)
{
    if (returnType == null) { throw new IllegalArgumentException("ReturnType cannot be null"); }
    try
    {
        Object result = null;
        String stringValue = getProperty(propertyName, type);
        if (stringValue != null)
        {
            result = ConvertUtils.convert(stringValue, returnType);
            if ((result instanceof String) && (! returnType.equals(String.class)))
            {
                // If a string is returned, no converter has been found (for non-String return type)
                throw new IllegalArgumentException("Unable to convert parameter to type: " + returnType.getName());
            }
        }
        return (T) result;
    }
    catch (ConversionException ce)
    {
        // Conversion failed, wrap in Illegal
        throw new InvalidArgumentException("Query property value for '" + propertyName + "' should be a valid "
                + returnType.getSimpleName());
    }
}
 
Example 3
Source File: DefaultValueHelper.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Converts a boolean default value to the given target type.
 * 
 * @param defaultValue   The default value
 * @param targetTypeCode The target type code
 * @return The converted value
 */
private Object convertBoolean(String defaultValue, int targetTypeCode)
{
    Boolean value  = null;
    Object  result = null;

    try
    {
        value = (Boolean)ConvertUtils.convert(defaultValue, Boolean.class);
    }
    catch (ConversionException ex)
    {
        return defaultValue;
    }
    
    if ((targetTypeCode == Types.BIT) || (targetTypeCode == Types.BOOLEAN))
    {
        result = value;
    }
    else if (TypeMap.isNumericType(targetTypeCode))
    {
        result = (value.booleanValue() ? Integer.valueOf(1) : Integer.valueOf(0));
    }
    else
    {
        result = value.toString();
    }
    return result;
}
 
Example 4
Source File: DefaultValueHelper.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Converts a boolean default value to the given target type.
 * 
 * @param defaultValue   The default value
 * @param targetTypeCode The target type code
 * @return The converted value
 */
private Object convertBoolean(String defaultValue, int targetTypeCode)
{
    Boolean value  = null;
    Object  result = null;

    try
    {
        value = (Boolean)ConvertUtils.convert(defaultValue, Boolean.class);
    }
    catch (ConversionException ex)
    {
        return defaultValue;
    }
    
    if ((targetTypeCode == Types.BIT) || (targetTypeCode == Types.BOOLEAN))
    {
        result = value;
    }
    else if (TypeMap.isNumericType(targetTypeCode))
    {
        result = (value.booleanValue() ? Integer.valueOf(1) : Integer.valueOf(0));
    }
    else
    {
        result = value.toString();
    }
    return result;
}
 
Example 5
Source File: ResultSet.java    From nextreports-server with Apache License 2.0 5 votes vote down vote up
@Override
	public int getInt(int columnIndex) throws SQLException {
//		Integer res = (Integer) getObject(columnIndex);
//		return res.intValue();
//		return ((Number) getObject(columnIndex)).intValue();
		return (Integer) ConvertUtils.convert(getObject(columnIndex), Integer.class);
	}
 
Example 6
Source File: HandlerInvoker.java    From joyqueue with Apache License 2.0 5 votes vote down vote up
protected Object convertParam(String name, Class<?> type, String value) {
    if (type.getName().startsWith("java.lang")) {
        return ConvertUtils.convert(value, type);
    } else {
        return JSON.parseObject(value, type);
    }
}
 
Example 7
Source File: DigesterRuleParser.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Object createObject(Attributes attributes) throws Exception {
    // create callparamrule
    int paramIndex = Integer.parseInt(attributes.getValue("paramnumber"));
    String attributeName = attributes.getValue("attrname");
    String type = attributes.getValue("type");
    String value = attributes.getValue("value");

    Rule objectParamRule = null;

    // type name is requried
    if (type == null) {
        throw new RuntimeException("Attribute 'type' is required.");
    }

    // create object instance
    Object param = null;
    Class<?> clazz = Class.forName(type);
    if (value == null) {
        param = clazz.newInstance();
    } else {
        param = ConvertUtils.convert(value, clazz);
    }

    if (attributeName == null) {
        objectParamRule = new ObjectParamRule(paramIndex, param);
    } else {
        objectParamRule = new ObjectParamRule(paramIndex, attributeName, param);
    }
    return objectParamRule;
}
 
Example 8
Source File: ConvertTest.java    From easy-sync with Apache License 2.0 5 votes vote down vote up
public void convert(Object[][] objects){
    for(Object[] o :objects){
        System.out.println(o[0]+","+o[1]);
        Object v= ConvertUtils.convert(o[0], o[1].getClass());
        Assert.assertEquals(v,o[1]);
    }
}
 
Example 9
Source File: HibernateFeatureModel.java    From geomajas-project-server with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public Object newInstance(String id) throws LayerException {
	try {
		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());
	}
}
 
Example 10
Source File: EsSyncFull.java    From easy-sync with Apache License 2.0 5 votes vote down vote up
private Map convertMysql2Es(DataMap dataMap) throws UnsupportedEncodingException {
    DataMap result=new DataMap();
    for(EsField esField :esFields){
        String name=esField.getSource();
        String targetType=esField.getType();
        Column column=columnMap.get(name);
        Object value=dataMap.get(name);
        if(value!=null) {
            if ("boolean".equalsIgnoreCase(targetType)) {
                value = ConvertUtils.convert(value, Boolean.class);
            } else if ("date".equalsIgnoreCase(targetType)) {
                if (value instanceof Date) {
                    value = ((Date) value).getTime();
                }
            } else if ("binary".equalsIgnoreCase(targetType)) {
                if (value instanceof byte[]) {
                    value = org.apache.commons.codec.binary.Base64.encodeBase64String((byte[]) value);
                } else {
                    value = org.apache.commons.codec.binary.Base64.encodeBase64String(value.toString().getBytes("UTF-8"));
                }
            }
        }

         result.put(esField.getTarget(),value);


    }


    return result;
}
 
Example 11
Source File: ResultSet.java    From nextreports-server with Apache License 2.0 4 votes vote down vote up
@Override
	public Time getTime(int columnIndex) throws SQLException {
//		return (Time) getObject(columnIndex);
		return (Time) ConvertUtils.convert(getObject(columnIndex), Time.class);
	}
 
Example 12
Source File: ResultSet.java    From nextreports-server with Apache License 2.0 4 votes vote down vote up
@Override
	public boolean getBoolean(int columnIndex) throws SQLException {
//		Boolean res = (Boolean) getObject(columnIndex);
//		return res.booleanValue();
		return (Boolean) ConvertUtils.convert(getObject(columnIndex), Boolean.class);
	}
 
Example 13
Source File: ConvertHelper.java    From potato-webmvc with MIT License 4 votes vote down vote up
public static Object convert(Object value,Class<?>targetType){
	return ConvertUtils.convert(value, targetType);
}
 
Example 14
Source File: ResultSet.java    From nextreports-server with Apache License 2.0 4 votes vote down vote up
@Override
	public BigDecimal getBigDecimal(int columnIndex, int scale) throws SQLException {
//		return (BigDecimal) getObject(columnIndex);
		return (BigDecimal) ConvertUtils.convert(getObject(columnIndex), BigDecimal.class);
	}
 
Example 15
Source File: ResultSet.java    From nextreports-server with Apache License 2.0 4 votes vote down vote up
@Override
	public float getFloat(int columnIndex) throws SQLException {
//		Float res = (Float) getObject(columnIndex);
//		return res.floatValue();
		return (Float) ConvertUtils.convert(getObject(columnIndex), Float.class);
	}
 
Example 16
Source File: ResultSet.java    From nextreports-server with Apache License 2.0 4 votes vote down vote up
@Override
	public Timestamp getTimestamp(int columnIndex) throws SQLException {
//		return (Timestamp) getObject(columnIndex);
		return (Timestamp) ConvertUtils.convert(getObject(columnIndex), Timestamp.class);
	}
 
Example 17
Source File: ParamConvertUtils.java    From msf4j with Apache License 2.0 3 votes vote down vote up
/**
 * Creates a converter function that converts a path segment into the given result type.
 * Current implementation doesn't follow the {@link javax.ws.rs.PathParam} specification to maintain backward
 * compatibility.
 *
 * @param resultType Result type
 * @return Function the function
 */
public static Function<String, Object> createPathParamConverter(final Type resultType) {
    if (!(resultType instanceof Class)) {
        throw new IllegalArgumentException("Unsupported @PathParam type " + resultType);
    }
    return value -> ConvertUtils.convert(value, (Class<?>) resultType);
}
 
Example 18
Source File: Plugin.java    From java-platform with Apache License 2.0 3 votes vote down vote up
/**
 * 连接Map键值对
 * 
 * @param map
 *            Map
 * @param prefix
 *            前缀
 * @param suffix
 *            后缀
 * @param separator
 *            连接符
 * @param ignoreEmptyValue
 *            忽略空值
 * @param ignoreKeys
 *            忽略Key
 * @return 字符串
 */
protected String joinKeyValue(Map<String, Object> map, String prefix, String suffix, String separator, boolean ignoreEmptyValue,
		String... ignoreKeys) {
	List<String> list = new ArrayList<String>();
	if (map != null) {
		for (Entry<String, Object> entry : map.entrySet()) {
			String key = entry.getKey();
			String value = ConvertUtils.convert(entry.getValue());
			if (StringUtils.isNotEmpty(key) && !ArrayUtils.contains(ignoreKeys, key) && (!ignoreEmptyValue || StringUtils.isNotEmpty(value))) {
				list.add(key + "=" + (value != null ? value : ""));
			}
		}
	}
	return (prefix != null ? prefix : "") + StringUtils.join(list, separator) + (suffix != null ? suffix : "");
}
 
Example 19
Source File: Plugin.java    From java-platform with Apache License 2.0 3 votes vote down vote up
/**
 * 连接Map值
 * 
 * @param map
 *            Map
 * @param prefix
 *            前缀
 * @param suffix
 *            后缀
 * @param separator
 *            连接符
 * @param ignoreEmptyValue
 *            忽略空值
 * @param ignoreKeys
 *            忽略Key
 * @return 字符串
 */
protected String joinValue(Map<String, Object> map, String prefix, String suffix, String separator, boolean ignoreEmptyValue,
		String... ignoreKeys) {
	List<String> list = new ArrayList<String>();
	if (map != null) {
		for (Entry<String, Object> entry : map.entrySet()) {
			String key = entry.getKey();
			String value = ConvertUtils.convert(entry.getValue());
			if (StringUtils.isNotEmpty(key) && !ArrayUtils.contains(ignoreKeys, key) && (!ignoreEmptyValue || StringUtils.isNotEmpty(value))) {
				list.add(value != null ? value : "");
			}
		}
	}
	return (prefix != null ? prefix : "") + StringUtils.join(list, separator) + (suffix != null ? suffix : "");
}
 
Example 20
Source File: ParamConvertUtils.java    From msf4j with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a converter function that converts cookie value into an object of the given result type.
 * It follows the supported types of {@link javax.ws.rs.CookieParam} with the following exceptions:
 * <ol>
 * <li>Does not support types registered with {@link javax.ws.rs.ext.ParamConverterProvider}</li>
 * </ol>
 *
 * @param resultType Result type
 * @return Function the function
 */
public static Function<String, Object> createCookieParamConverter(Type resultType) {
    return value -> ConvertUtils.convert(value, (Class<?>) resultType);
}