Java Code Examples for org.apache.commons.beanutils.ConvertUtils

The following examples show how to use org.apache.commons.beanutils.ConvertUtils. These examples are extracted from open source projects. 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 Project: Bats   Source File: StringCodecs.java    License: Apache License 2.0 6 votes vote down vote up
public static void check()
{
  if (classLoaders.putIfAbsent(Thread.currentThread().getContextClassLoader(), Boolean.TRUE) == null) {
    loadDefaultConverters();
    for (Map.Entry<Class<?>, Class<? extends StringCodec<?>>> entry : codecs.entrySet()) {
      try {
        final StringCodec<?> codecInstance = entry.getValue().newInstance();
        ConvertUtils.register(new Converter()
        {
          @Override
          public Object convert(Class type, Object value)
          {
            return value == null ? null : codecInstance.fromString(value.toString());
          }

        }, entry.getKey());
      } catch (Exception ex) {
        throw new RuntimeException(ex);
      }
    }
  }
}
 
Example 2
Source Project: DWSurvey   Source File: ObjectMapper.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
/**
	 * 基于Apache BeanUtils转换字符串到相应类型.
	 * 
	 * @param value 待转换的字符串.
	 * @param toType 转换目标类型.
	 */
	public static Object convertToObject(String value, Class<?> toType) {
		Object cvt_value=null;
		try {
				cvt_value=ConvertUtils.convert(value, toType);	
//			if(toType==Date.class){
//				System.out.println("0----0");
//				SimpleDateFormat dateFormat=null;
//				try{
//					dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//					cvt_value=dateFormat.parse(value);	
//				}catch(Exception e){
//					dateFormat=new SimpleDateFormat("yyyy-MM-dd");
//					cvt_value=dateFormat.parse(value);	
//				}
//			}
		} catch (Exception e) {
			throw ReflectionUtils.convertReflectionExceptionToUnchecked(e);
		}
		return cvt_value;
	}
 
Example 3
Source Project: Shop-for-JavaWeb   Source File: Variable.java    License: MIT License 6 votes vote down vote up
@JsonIgnore
public Map<String, Object> getVariableMap() {

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

	if (StringUtils.isBlank(keys)) {
		return map;
	}

	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);
		map.put(key, objectValue);
	}
	return map;
}
 
Example 4
Source Project: attic-apex-core   Source File: StringCodecs.java    License: Apache License 2.0 6 votes vote down vote up
public static void check()
{
  if (classLoaders.putIfAbsent(Thread.currentThread().getContextClassLoader(), Boolean.TRUE) == null) {
    loadDefaultConverters();
    for (Map.Entry<Class<?>, Class<? extends StringCodec<?>>> entry : codecs.entrySet()) {
      try {
        final StringCodec<?> codecInstance = entry.getValue().newInstance();
        ConvertUtils.register(new Converter()
        {
          @Override
          public Object convert(Class type, Object value)
          {
            return value == null ? null : codecInstance.fromString(value.toString());
          }

        }, entry.getKey());
      } catch (Exception ex) {
        throw new RuntimeException(ex);
      }
    }
  }
}
 
Example 5
Source Project: DataDefender   Source File: TypeConverter.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Converts the passed value to the passed type if possible.
 *
 * Conversion is performed in the following order:
 *  - Returned as-is if the value is of the same type or a sub-class of the
 *    type.
 *  - If type is java.lang.String, call toString on value and return it.
 *  - If value is a primitive, primitive wrapper, or String, and type
 *    represents one of those as well, an attempt is made to convert from/to
 *    as needed.
 *  - Otherwise, look for a constructor in the passed type that accepts a
 *    single argument of:
 *    o value itself (as its type or an interface/superclass)
 *    o A String argument, in which case toString is called on value
 *    o If value is primitive, the primitive type or it's wrapper
 *    o If value is a String, a primitive or wrapper argument
 *
 * @param value
 * @param type
 * @return
 */
public static Object convert(Object value, Class<?> type)
    throws InstantiationException,
    IllegalAccessException,
    IllegalArgumentException,
    InvocationTargetException {
    if (ClassUtils.isAssignable(value.getClass(), type)) {
        return value;
    } else if (String.class.equals(type)) {
        return value.toString();
    } else if (ClassUtils.isPrimitiveOrWrapper(type) && value instanceof String) {
        return ConvertUtils.convert(value, type);
    }
    Constructor<?> constr = getConvertibleConstructor(value.getClass(), type);
    Class<?> pt = (constr != null && constr.getParameterCount() > 0) ? constr.getParameterTypes()[0] : null;
    if (!ClassUtils.isAssignable(value.getClass(), pt)) {
        if (pt != null && ClassUtils.isAssignable(String.class, pt)) {
            return constr.newInstance(value.toString());
        } else if (pt != null && ClassUtils.isPrimitiveOrWrapper(pt) && value instanceof String) {
            return constr.newInstance(ConvertUtils.convert(value, pt));
        }
        // try anyway...
    }

    return constr.newInstance(value);
}
 
Example 6
Source Project: DataDefender   Source File: Column.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Calls all functions defined under Functions in order.
 *
 * @param rs
 * @return
 * @throws SQLException
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 */
public Object invokeFunctionChain(ResultSet rs)
    throws SQLException,
    IllegalAccessException,
    InvocationTargetException,
    InstantiationException {

    Object startingValue = null;
    Class<?> argType = getResolvedPlan().getDynamicArgumentType();
    if (argType != null && ClassUtils.isAssignable(ResultSet.class, argType)) {
        startingValue = rs;
    } else {
        startingValue = rs.getObject(name, type);
    }
    return ConvertUtils.convert(getResolvedPlan().invoke(startingValue), type);
}
 
Example 7
Source Project: maven-framework-project   Source File: Variable.java    License: 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 8
Source Project: geowave   Source File: ValueConverter.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Convert value into the specified type
 *
 * @param <X> Class to convert to
 * @param value Value to convert from
 * @param targetType Type to convert into
 * @return The converted value
 */
@SuppressWarnings("unchecked")
public static <X> X convert(final Object value, final Class<X> targetType) {
  // HP Fortify "Improper Output Neutralization" false positive
  // What Fortify considers "user input" comes only
  // from users with OS-level access anyway
  LOGGER.trace("Attempting to convert " + value + " to class type " + targetType);
  if (value != null) {
    // if object is already in intended target type, no need to convert
    // it, just return as it is
    if (value.getClass() == targetType) {
      return (X) value;
    }

    if ((value.getClass() == JSONObject.class) || (value.getClass() == JSONArray.class)) {
      return (X) value;
    }
  }

  final String strValue = String.valueOf(value);
  final Object retval = ConvertUtils.convert(strValue, targetType);
  return (X) retval;
}
 
Example 9
Source Project: minnal   Source File: ResourceUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @param parameters
 * @param request
 * @param values
 * @return
 */
private static Object[] getActionParameterValues(List<ParameterMetaData> parameters, Map<String, Object> body, Map<String, Object> values) {
	if (body != null) {
		values.putAll(body);
	}
	Object[] params = new Object[parameters.size()];
	for (int i = 0; i < parameters.size(); i++) {
		ParameterMetaData param = parameters.get(i);
		Object value = values.get(param.getName());
		if (value != null && ! value.getClass().equals(param.getType())) {
			value = ConvertUtils.convert(value, param.getType());
		}
		params[i] = value;
	}
	return params;
}
 
Example 10
Source Project: es   Source File: CollectionToStringUserType.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 从JDBC ResultSet读取数据,将其转换为自定义类型后返回
 * (此方法要求对克能出现null值进行处理)
 * names中包含了当前自定义类型的映射字段名称
 *
 * @param names
 * @param owner
 * @return
 * @throws org.hibernate.HibernateException
 * @throws java.sql.SQLException
 */
@Override
public Object nullSafeGet(ResultSet rs, String[] names, SessionImplementor session, Object owner) throws HibernateException, SQLException {
    String valueStr = rs.getString(names[0]);
    if (StringUtils.isEmpty(valueStr)) {
        return newCollection();
    }

    String[] values = StringUtils.split(valueStr, separator);

    Collection result = newCollection();

    for (String value : values) {
        if(StringUtils.isNotEmpty(value)) {
            result.add(ConvertUtils.convert(value, elementType));
        }
    }
    return result;

}
 
Example 11
Source Project: Bats   Source File: StringCodecs.java    License: Apache License 2.0 5 votes vote down vote up
public static void clear()
{
  for (Map.Entry<Class<?>, Class<? extends StringCodec<?>>> entry : codecs.entrySet()) {
    ConvertUtils.deregister(entry.getKey());
  }
  codecs.clear();
}
 
Example 12
Source Project: Bats   Source File: StringCodecs.java    License: Apache License 2.0 5 votes vote down vote up
public static <T> void register(final Class<? extends StringCodec<?>> codec, final Class<T> clazz) throws InstantiationException, IllegalAccessException
{
  check();
  final StringCodec<?> codecInstance = codec.newInstance();
  ConvertUtils.register(new Converter()
  {
    @Override
    public Object convert(Class type, Object value)
    {
      return value == null ? null : codecInstance.fromString(value.toString());
    }

  }, clazz);
  codecs.put(clazz, codec);
}
 
Example 13
Source Project: joyqueue   Source File: HandlerInvoker.java    License: 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 14
public static void setFieldValue(Object target, Field theField, Object value) {
    if (theField != null) {
        setAccess(theField);
        try {
            Object newValue = ConvertUtils.convert(value, theField.getType());
            theField.set(target, newValue);
        } catch (Exception e) {
            logger
                .error(
                    "在调用时产生错误信息,此错误信息表示该相应方法已将相关错误catch了,请尽快修复!\n以下是具体错误产生的原因:\n"
                            + e.getMessage() + " \n", e);
        }
    }
}
 
Example 15
Source Project: netstrap   Source File: DefaultWebSocketDispatcher.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 类型转换
 */
private Object convertValueType(Object baseValue, Class<?> type) {
    Object value = null;
    if (Objects.nonNull(baseValue)) {
        if (type.equals(String.class)) {
            value = baseValue;
        } else {
            value = ConvertUtils.convert(baseValue, type);
        }
    }
    return value;
}
 
Example 16
Source Project: netstrap   Source File: DefaultHttpDispatcher.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 类型转换
 */
private Object convertValueType(Object baseValue, Class<?> type) {
    Object value = null;
    if (Objects.nonNull(baseValue)) {
        if (type.equals(String.class)) {
            value = baseValue;
        } else {
            value = ConvertUtils.convert(baseValue, type);
        }
    }
    return value;
}
 
Example 17
Source Project: spring-cloud-shop   Source File: BannerServiceImpl.java    License: MIT License 5 votes vote down vote up
/**
 * Banner -> BannerResponse
 */
private BannerResponse convert(Banner banner) {
    BannerResponse response = new BannerResponse();
    BeanCopier.create(banner, response).copy();
    if (StringUtils.isNotBlank(banner.getShareChannel())) {
        response.setShareChannel(
                Stream.of((String[]) ConvertUtils.convert(banner.getShareChannel().split(Constants.COMMA), String.class))
                        .collect(Collectors.toList()));
    } else {
        response.setShareChannel(Lists.newArrayList());
    }
    return response;
}
 
Example 18
Source Project: spring-cloud-shop   Source File: ManageApplicationNoSpringTests.java    License: MIT License 5 votes vote down vote up
@Test
    public void testConvert() {

//        List<Long> collect = Stream.of().collect(Collectors.toList());
        List<Long> collect = Stream.of((Long[]) ConvertUtils.convert("32323,8888,999".split(","), Long.class)).collect(Collectors.toList());

        System.out.println(collect);
    }
 
Example 19
Source Project: easy-sync   Source File: EsSyncFull.java    License: 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 20
Source Project: easy-sync   Source File: EsSyncIncrement.java    License: Apache License 2.0 5 votes vote down vote up
private Map convertKafka2Es(Map<String, Object> 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 21
Source Project: easy-sync   Source File: ConvertTest.java    License: 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 22
Source Project: jigsaw-payment   Source File: JdbcProtobufTemplate.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 
 * @param rs
 * @param builder
 * @throws SQLException
 */
private void populate(ResultSet rs, Message.Builder builder)
		throws SQLException {
	ResultSetMetaData metaData = rs.getMetaData();
	int columnCount = metaData.getColumnCount();// 列个数
	String columnLabel = null;// 列名
	Object columnValue = null;// 列值
	Descriptors.FieldDescriptor fieldDescriptor = null;
	for (int i = 1; i <= columnCount; i++) {
		columnLabel = metaData.getColumnLabel(i);
		columnValue = rs.getObject(i);
		if (columnValue == null)
			continue;// 如果为空,继续下一个
		fieldDescriptor = descriptor.findFieldByName(columnLabel);
		if (fieldDescriptor == null)
			continue;// 如果为空,继续下一个
		// 转换为相应的类型 ,会自动将 date 类型转换为long
		if (fieldDescriptor.getType().equals(FieldDescriptor.Type.ENUM)) {
			columnValue = fieldDescriptor.getEnumType().findValueByNumber(
					(int) columnValue);
		} else {
			columnValue = ConvertUtils.convert(columnValue, fieldDescriptor
					.getDefaultValue().getClass());
		}
		builder.setField(fieldDescriptor, columnValue);
	}
}
 
Example 23
Source Project: lams   Source File: DigesterRuleParser.java    License: 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 24
/**
 * Get the first parameter value, converted to the requested type.
 * @param parameters used to extract parameter value from
 * @param parameterName name of the parameter
 * @param returnType type of object to return
 * @return the converted parameter value. Null, if the parameter 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
 */
@SuppressWarnings("unchecked")
public <T extends Object> T getParameter(Parameters parameters, String parameterName, Class<T> returnType) {
    if(returnType == null) 
    {
        throw new IllegalArgumentException("ReturnType cannot be null");
    }
    try
    {
        Object result = null;
        String stringValue = parameters.getParameter(parameterName);
        if(stringValue != null) 
        {
            result = ConvertUtils.convert(stringValue, returnType);
            if(result instanceof String)
            {
                // If a string is returned, no converter has been found
                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("Parameter value for '" + parameterName + "' should be a valid " + returnType.getSimpleName());
    }
}
 
Example 25
/**
 * 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 26
@Override
public T getParameter(String parameterName, Class<T> clazz) throws InvalidArgumentException {
	String param = getParameter(parameterName);
	if (param == null) return null;
	Object obj = ConvertUtils.convert(param, clazz);
	if (obj != null && obj.getClass().equals(clazz))
	{
		return (T) obj;
	}
	throw new InvalidArgumentException(InvalidArgumentException.DEFAULT_MESSAGE_ID, new Object[] {parameterName});
}
 
Example 27
Source Project: DWSurvey   Source File: ObjectMapper.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 定义Apache BeanUtils日期Converter的格式,可注册多个格式,以','分隔
 */
public static void registerDateConverter(String patterns) {
	DateConverter dc = new DateConverter();
	dc.setUseLocaleFormat(true);
	dc.setPatterns(StringUtils.split(patterns, ","));
	ConvertUtils.register(dc, Date.class);
}
 
Example 28
Source Project: gemfirexd-oss   Source File: DefaultValueHelper.java    License: 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 29
Source Project: spring-boot   Source File: MyBeanUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * map to bean
 * 转换过程中,由于属性的类型不同,需要分别转换。
 * java 反射机制,转换过程中属性的类型默认都是 String 类型,否则会抛出异常,而 BeanUtils 项目,做了大量转换工作,比 java 反射机制好用
 * BeanUtils 的 populate 方法,对 Date 属性转换,支持不好,需要自己编写转换器
 *
 * @param map  待转换的 map
 * @param bean 满足 bean 格式,且需要有无参的构造方法; bean 属性的名字应该和 map 的 key 相同
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 */
private static void mapToBean(Map<String, Object> map, Object bean) throws IllegalAccessException, InvocationTargetException {

    //注册几个转换器
    ConvertUtils.register(new SqlDateConverter(null), java.sql.Date.class);
    ConvertUtils.register(new SqlTimestampConverter(null), java.sql.Timestamp.class);
    //注册一个类型转换器  解决 common-beanutils 为 Date 类型赋值问题
    ConvertUtils.register(new Converter() {
        //  @Override
        public Object convert(Class type, Object value) { // type : 目前所遇到的数据类型。  value :目前参数的值。
            // System.out.println(String.format("value = %s", value));

            if (value == null || value.equals("") || value.equals("null"))
                return null;
            Date date = null;
            try {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                date = dateFormat.parse((String) value);
            } catch (Exception e) {

                e.printStackTrace();
            }

            return date;
        }

    }, Date.class);

    BeanUtils.populate(bean, map);
}
 
Example 30
Source Project: gemfirexd-oss   Source File: DefaultValueHelper.java    License: 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;
}