org.apache.commons.beanutils.ConvertUtils Java Examples
The following examples show how to use
org.apache.commons.beanutils.ConvertUtils.
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: ResourceUtil.java From minnal with Apache License 2.0 | 6 votes |
/** * @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 #2
Source File: StringCodecs.java From Bats with Apache License 2.0 | 6 votes |
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 #3
Source File: ObjectMapper.java From DWSurvey with GNU Affero General Public License v3.0 | 6 votes |
/** * 基于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 #4
Source File: Variable.java From Shop-for-JavaWeb with MIT License | 6 votes |
@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 #5
Source File: StringCodecs.java From attic-apex-core with Apache License 2.0 | 6 votes |
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 #6
Source File: CollectionToStringUserType.java From es with Apache License 2.0 | 6 votes |
/** * 从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 #7
Source File: TypeConverter.java From DataDefender with Apache License 2.0 | 6 votes |
/** * 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 #8
Source File: Column.java From DataDefender with Apache License 2.0 | 6 votes |
/** * 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 #9
Source File: Variable.java From maven-framework-project with MIT License | 6 votes |
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 #10
Source File: ValueConverter.java From geowave with Apache License 2.0 | 6 votes |
/** * 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 #11
Source File: EsSyncIncrement.java From easy-sync with Apache License 2.0 | 5 votes |
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 #12
Source File: WorkflowRestImpl.java From alfresco-remote-api with GNU Lesser General Public License v3.0 | 5 votes |
/** * 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 #13
Source File: MyBeanUtils.java From spring-boot with Apache License 2.0 | 5 votes |
/** * 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 #14
Source File: MapBasedQueryWalker.java From alfresco-remote-api with GNU Lesser General Public License v3.0 | 5 votes |
/** * 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 #15
Source File: DefaultWebSocketDispatcher.java From netstrap with Apache License 2.0 | 5 votes |
/** * 类型转换 */ 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 File: ResultSet.java From nextreports-server with Apache License 2.0 | 5 votes |
@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 #17
Source File: DefaultValueHelper.java From gemfirexd-oss with Apache License 2.0 | 5 votes |
/** * 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 #18
Source File: ResultSet.java From nextreports-server with Apache License 2.0 | 5 votes |
@Override public short getShort(int columnIndex) throws SQLException { // Short res = (Short) getObject(columnIndex); // return res.shortValue(); // return ((Number) getObject(columnIndex)).shortValue(); return (Short) ConvertUtils.convert(getObject(columnIndex), Short.class); }
Example #19
Source File: StringCodecs.java From attic-apex-core with Apache License 2.0 | 5 votes |
public static void clear() { for (Map.Entry<Class<?>, Class<? extends StringCodec<?>>> entry : codecs.entrySet()) { ConvertUtils.deregister(entry.getKey()); } codecs.clear(); }
Example #20
Source File: ReflectionUtil.java From stategen with GNU Affero General Public License v3.0 | 5 votes |
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 #21
Source File: StringCodecs.java From attic-apex-core with Apache License 2.0 | 5 votes |
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 #22
Source File: BeanUtils.java From ogham with Apache License 2.0 | 5 votes |
/** * Register the following converters: * <ul> * <li>{@link EmailAddressConverter}</li> * <li>{@link SmsSenderConverter}</li> * </ul> * * If a conversion error occurs it throws an exception. */ public static void registerDefaultConverters() { // TODO: auto-detect converters in the classpath ? // Add converter for being able to convert string address into // EmailAddress ConvertUtils.register(new EmailAddressConverter(), EmailAddress.class); // Add converter for being able to convert string into // SMS sender ConvertUtils.register(new SmsSenderConverter(), Sender.class); BeanUtilsBean.getInstance().getConvertUtils().register(true, false, 0); }
Example #23
Source File: HandlerInvoker.java From joyqueue with Apache License 2.0 | 5 votes |
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 #24
Source File: ConvertUtil.java From feilong-core with Apache License 2.0 | 5 votes |
/** * Register standard default null. * * @see ConvertUtilsBean#registerPrimitives(boolean) registerPrimitives(boolean throwException) * @see ConvertUtilsBean#registerStandard(boolean,boolean) registerStandard(boolean throwException, boolean defaultNull) * @see ConvertUtilsBean#registerOther(boolean) registerOther(boolean throwException) * @see ConvertUtilsBean#registerArrays(boolean,int) registerArrays(boolean throwException, int defaultArraySize) * @see ConvertUtilsBean#deregister(Class) ConvertUtilsBean.deregister(Class) * @since 1.11.2 */ public static void registerStandardDefaultNull(){ ConvertUtils.register(new BigDecimalConverter(null), BigDecimal.class); ConvertUtils.register(new BigIntegerConverter(null), BigInteger.class); ConvertUtils.register(new BooleanConverter(null), Boolean.class); ConvertUtils.register(new ByteConverter(null), Byte.class); ConvertUtils.register(new CharacterConverter(null), Character.class); ConvertUtils.register(new DoubleConverter(null), Double.class); ConvertUtils.register(new FloatConverter(null), Float.class); ConvertUtils.register(new IntegerConverter(null), Integer.class); ConvertUtils.register(new LongConverter(null), Long.class); ConvertUtils.register(new ShortConverter(null), Short.class); ConvertUtils.register(new StringConverter(null), String.class); }
Example #25
Source File: HibernateFeatureModel.java From geomajas-project-server with GNU Affero General Public License v3.0 | 5 votes |
@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 #26
Source File: ToAliasBeanTest.java From feilong-core with Apache License 2.0 | 5 votes |
/** * Test read properties to alias bean1. */ @Test public void testToAliasBean1(){ ArrayConverter arrayConverter = new ArrayConverter(String[].class, new StringConverter(), 2); char[] allowedChars = { ':' }; arrayConverter.setAllowedChars(allowedChars); ConvertUtils.register(arrayConverter, String[].class); DangaMemCachedConfig dangaMemCachedConfig = toAliasBean(getResourceBundle("messages.memcached"), DangaMemCachedConfig.class); assertThat( dangaMemCachedConfig, allOf(// hasProperty("serverList", arrayContaining("172.20.3-1.23:11211", "172.20.31.22:11211")), hasProperty("poolName", is("sidsock2")), hasProperty("expireTime", is(180)), hasProperty("weight", arrayContaining(2)), hasProperty("initConnection", is(10)), hasProperty("minConnection", is(5)), hasProperty("maxConnection", is(250)), hasProperty("maintSleep", is(30)), hasProperty("nagle", is(false)), hasProperty("socketTo", is(3000)), hasProperty("aliveCheck", is(false)) // )); }
Example #27
Source File: KualiActionServlet.java From rice with Educational Community License v2.0 | 5 votes |
/** * <p>Initialize other global characteristics of the controller servlet.</p> * Overridden to remove the ConvertUtils.deregister() command that caused problems * with the concurrent data dictionary load. (KULRNE-4405) * * @exception ServletException if we cannot initialize these resources */ @Override protected void initOther() throws ServletException { String value = null; value = getServletConfig().getInitParameter("config"); if (value != null) { config = value; } // Backwards compatibility for form beans of Java wrapper classes // Set to true for strict Struts 1.0 compatibility value = getServletConfig().getInitParameter("convertNull"); if ("true".equalsIgnoreCase(value) || "yes".equalsIgnoreCase(value) || "on".equalsIgnoreCase(value) || "y".equalsIgnoreCase(value) || "1".equalsIgnoreCase(value)) { convertNull = true; } if (convertNull) { ConvertUtils.register(new BigDecimalConverter(null), BigDecimal.class); ConvertUtils.register(new BigIntegerConverter(null), BigInteger.class); ConvertUtils.register(new BooleanConverter(null), Boolean.class); ConvertUtils.register(new ByteConverter(null), Byte.class); ConvertUtils.register(new CharacterConverter(null), Character.class); ConvertUtils.register(new DoubleConverter(null), Double.class); ConvertUtils.register(new FloatConverter(null), Float.class); ConvertUtils.register(new IntegerConverter(null), Integer.class); ConvertUtils.register(new LongConverter(null), Long.class); ConvertUtils.register(new ShortConverter(null), Short.class); } // KULRICE-8176: KFS Notes/Attachments Tab Functionality for Note Text Error - Visible/Special characters, spaces, or tabs parameterEncoding = getServletConfig().getInitParameter("PARAMETER_ENCODING"); }
Example #28
Source File: StringCodecs.java From Bats with Apache License 2.0 | 5 votes |
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 #29
Source File: StringCodecs.java From Bats with Apache License 2.0 | 5 votes |
public static void clear() { for (Map.Entry<Class<?>, Class<? extends StringCodec<?>>> entry : codecs.entrySet()) { ConvertUtils.deregister(entry.getKey()); } codecs.clear(); }
Example #30
Source File: ManageApplicationNoSpringTests.java From spring-cloud-shop with MIT License | 5 votes |
@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); }