org.apache.commons.beanutils.ConversionException Java Examples
The following examples show how to use
org.apache.commons.beanutils.ConversionException.
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: ByteArrayConverter.java From DataLink with Apache License 2.0 | 6 votes |
public Object convert(Class type, Object value) { if (value == null) { if (useDefault) { return (defaultValue); } else { throw new ConversionException("No value specified"); } } if (value instanceof byte[]) { return (value); } // BLOB类型,canal直接存储为String("ISO-8859-1") if (value instanceof String) { try { return ((String) value).getBytes("ISO-8859-1"); } catch (Exception e) { throw new ConversionException(e); } } return converter.convert(type, value); // byteConvertor进行转化 }
Example #2
Source File: Injector.java From elepy with Apache License 2.0 | 6 votes |
private Object getProp(Class<?> returnType, Property annotation) { final Class<?> primitiveWrapper = ClassUtils.primitiveToWrapper(returnType); StringConverter stringConverter = new StringConverter(); final var configuration = elepyContext.getDependency(Configuration.class); try { final Object o = configuration.get(primitiveWrapper, annotation.key()); if (o != null) { return o; } if (isEmpty(annotation.defaultValue())) { return null; } return stringConverter.convert(primitiveWrapper, annotation.defaultValue()); } catch (ConversionException e) { logger.error(e.getMessage(), e); return null; } }
Example #3
Source File: ConversionUtils.java From red5-io with Apache License 2.0 | 6 votes |
/** * Convert map to bean * * @param source * Source map * @param target * Target class * @return Bean of that class * @throws ConversionException * on failure */ public static Object convertMapToBean(Map<String, ? extends Object> source, Class<?> target) throws ConversionException { Object bean = newInstance(target); if (bean == null) { //try with just the target name as specified in Trac #352 bean = newInstance(target.getName()); if (bean == null) { throw new ConversionException("Unable to create bean using empty constructor"); } } try { BeanUtils.populate(bean, source); } catch (Exception e) { throw new ConversionException("Error populating bean", e); } return bean; }
Example #4
Source File: ConversionUtils.java From red5-io with Apache License 2.0 | 6 votes |
/** * Convert number to primitive wrapper like Boolean or Float * * @param num * Number to conver * @param wrapper * Primitive wrapper type * @return Converted object */ public static Object convertNumberToWrapper(Number num, Class<?> wrapper) { //XXX Paul: Using valueOf will reduce object creation if (wrapper.equals(String.class)) { return num.toString(); } else if (wrapper.equals(Boolean.class)) { return Boolean.valueOf(num.intValue() == 1); } else if (wrapper.equals(Double.class)) { return Double.valueOf(num.doubleValue()); } else if (wrapper.equals(Long.class)) { return Long.valueOf(num.longValue()); } else if (wrapper.equals(Float.class)) { return Float.valueOf(num.floatValue()); } else if (wrapper.equals(Integer.class)) { return Integer.valueOf(num.intValue()); } else if (wrapper.equals(Short.class)) { return Short.valueOf(num.shortValue()); } else if (wrapper.equals(Byte.class)) { return Byte.valueOf(num.byteValue()); } throw new ConversionException(String.format("Unable to convert number to: %s", wrapper)); }
Example #5
Source File: ConversionUtils.java From red5-io with Apache License 2.0 | 6 votes |
/** * Convert string to primitive wrapper like Boolean or Float * * @param str * String to convert * @param wrapper * Primitive wrapper type * @return Converted object */ public static Object convertStringToWrapper(String str, Class<?> wrapper) { log.trace("String: {} to wrapper: {}", str, wrapper); if (wrapper.equals(String.class)) { return str; } else if (wrapper.equals(Boolean.class)) { return Boolean.valueOf(str); } else if (wrapper.equals(Double.class)) { return Double.valueOf(str); } else if (wrapper.equals(Long.class)) { return Long.valueOf(str); } else if (wrapper.equals(Float.class)) { return Float.valueOf(str); } else if (wrapper.equals(Integer.class)) { return Integer.valueOf(str); } else if (wrapper.equals(Short.class)) { return Short.valueOf(str); } else if (wrapper.equals(Byte.class)) { return Byte.valueOf(str); } throw new ConversionException(String.format("Unable to convert string to: %s", wrapper)); }
Example #6
Source File: ConversionUtils.java From red5-io with Apache License 2.0 | 6 votes |
/** * Convert to wrapped primitive * * @param source * Source object * @param wrapper * Primitive wrapper type * @return Converted object */ public static Object convertToWrappedPrimitive(Object source, Class<?> wrapper) { if (source == null || wrapper == null) { return null; } if (wrapper.isInstance(source)) { return source; } if (wrapper.isAssignableFrom(source.getClass())) { return source; } if (source instanceof Number) { return convertNumberToWrapper((Number) source, wrapper); } else { //ensure we dont try to convert text to a number, prevent NumberFormatException if (Number.class.isAssignableFrom(wrapper)) { //test for int or fp number if (!source.toString().matches(NUMERIC_TYPE)) { throw new ConversionException(String.format("Unable to convert string %s its not a number type: %s", source, wrapper)); } } return convertStringToWrapper(source.toString(), wrapper); } }
Example #7
Source File: MessageQueueForm.java From rice with Educational Community License v2.0 | 6 votes |
/** * Convert the specified input object into an output object of the * specified type. * * @param type Data type to which this value should be converted * @param value The input value to be converted * * @exception org.apache.commons.beanutils.ConversionException if conversion cannot be performed * successfully */ public Object convert(Class type, Object value) { if (value == null) { if (useDefault) { return (defaultValue); } else { throw new ConversionException("No value specified"); } } if (value instanceof Timestamp) { return (value); } try { return (Timestamp.valueOf(value.toString())); } catch (Exception e) { if (useDefault) { return (defaultValue); } else { throw new ConversionException(e); } } }
Example #8
Source File: DateConverter.java From onetwo with Apache License 2.0 | 6 votes |
public Object convert(Class type, Object value) { if (value == null) { return null; } if(type==value.getClass()) return value; if (type == Timestamp.class) { return convertToDate(type, value, "yyyy-MM-dd HH:mm:ss"); } else if (type == Date.class) { return convertToDate(type, value, "yyyy-MM-dd"); } else if (type == String.class) { return convertToString(type, value); } throw new ConversionException("Could not convert " + value.getClass().getName() + " to " + type.getName()); }
Example #9
Source File: DateConverter.java From onetwo with Apache License 2.0 | 6 votes |
protected Object convertToDate(Class type, Object value, String pattern) { DateFormat df = new SimpleDateFormat(pattern); if (value instanceof String) { try { if (StringUtils.isEmpty(value.toString())) { return null; } Date date = df.parse((String) value); if (type.equals(Timestamp.class)) { return new Timestamp(date.getTime()); } return date; } catch (Exception pe) { pe.printStackTrace(); throw new ConversionException("Error converting String to Date"); } } throw new ConversionException("Could not convert " + value.getClass().getName() + " to " + type.getName()); }
Example #10
Source File: SqlTimestampConverter.java From DataLink with Apache License 2.0 | 5 votes |
/** * Convert the specified input object into an output object of the specified type. * * @param type Data type to which this value should be converted * @param value The input value to be converted * @exception ConversionException if conversion cannot be performed successfully */ public Object convert(Class type, Object value) { if (value == null) { if (useDefault) { return (defaultValue); } else { throw new ConversionException("No value specified"); } } if (value instanceof java.sql.Date && java.sql.Date.class.equals(type)) { return value; } else if (value instanceof java.sql.Time && java.sql.Time.class.equals(type)) { return value; } else if (value instanceof Timestamp && Timestamp.class.equals(type)) { return value; } else { try { if (java.sql.Date.class.equals(type)) { return new java.sql.Date(convertTimestamp2TimeMillis(value.toString())); } else if (java.sql.Time.class.equals(type)) { return new java.sql.Time(convertTimestamp2TimeMillis(value.toString())); } else if (Timestamp.class.equals(type)) { return new Timestamp(convertTimestamp2TimeMillis(value.toString())); } else { return new Timestamp(convertTimestamp2TimeMillis(value.toString())); } } catch (Exception e) { throw new ConversionException("Value format invalid: " + e.getMessage(), e); } } }
Example #11
Source File: ConvertersTest.java From HiveRunner with Apache License 2.0 | 5 votes |
private void assertConversionException(Object value, PrimitiveTypeInfo typeInfo) { try { System.out.println(Converters.convert(value, typeInfo)); } catch (ConversionException e) { return; } fail("Expected " + ConversionException.class.getSimpleName() + " for value " + value + " (" + value.getClass().getSimpleName() + ") to " + typeInfo.getTypeName()); }
Example #12
Source File: Converters.java From HiveRunner with Apache License 2.0 | 5 votes |
@Override public Object convert(@SuppressWarnings("rawtypes") Class type, Object value) { try { return HiveDecimal.create(new BigDecimal(value.toString())); } catch (NumberFormatException e) { throw new ConversionException(e); } }
Example #13
Source File: ConvertClassTest.java From feilong-core with Apache License 2.0 | 5 votes |
/** * Test to URL. */ @Test(expected = ConversionException.class) @SuppressWarnings("static-method") public void testToURL(){ String spec = "C:\\Users\\feilong\\feilong\\train\\新员工\\warmReminder\\20160704141057.html"; convert(spec, URL.class); //异常 //MalformedURLException ConversionException }
Example #14
Source File: AbstractUsageCheck.java From contribution with GNU Lesser General Public License v2.1 | 5 votes |
/** * Set the ignore format to the specified regular expression. * @param aFormat a <code>String</code> value * @throws ConversionException unable to parse aFormat */ public void setIgnoreFormat(String aFormat) throws ConversionException { try { mRegexp = Utils.getPattern(aFormat); mIgnoreFormat = aFormat; } catch (PatternSyntaxException e) { throw new ConversionException("unable to parse " + aFormat, e); } }
Example #15
Source File: AbstractReferenceCheck.java From contribution with GNU Lesser General Public License v2.1 | 5 votes |
/** * Set the ignore name format to the specified regular expression. * @param aFormat a <code>String</code> value * @throws ConversionException unable to parse aFormat */ public void setIgnoreName(String aFormat) throws ConversionException { try { mIgnoreNameRegexp = Utils.getPattern(aFormat); } catch (PatternSyntaxException e) { throw new ConversionException("unable to parse " + aFormat, e); } }
Example #16
Source File: AbstractReferenceCheck.java From contribution with GNU Lesser General Public License v2.1 | 5 votes |
/** * Set the ignore class name to the specified regular expression. * @param aFormat a <code>String</code> value * @throws ConversionException unable to parse aFormat */ public void setIgnoreClassName(String aFormat) throws ConversionException { try { mIgnoreClassNameRegexp = Utils.getPattern(aFormat); } catch (PatternSyntaxException e) { throw new ConversionException("unable to parse " + aFormat, e); } }
Example #17
Source File: BeanUtils.java From ogham with Apache License 2.0 | 5 votes |
private static void handleConversion(Object bean, Options options, Entry<String, Object> entry, ConversionException e) throws BeanException { if (options.isSkipConversionError()) { LOG.debug("skipping property {}: can't convert value", entry.getKey(), e); } else { throw new BeanException("Failed to populate bean due to conversion error", bean, e); } }
Example #18
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 #19
Source File: AbstractUsageCheck.java From cacheonix-core with GNU Lesser General Public License v2.1 | 5 votes |
/** * Set the ignore format to the specified regular expression. * @param aFormat a <code>String</code> value * @throws ConversionException unable to parse aFormat */ public void setIgnoreFormat(String aFormat) throws ConversionException { try { mRegexp = Utils.getPattern(aFormat); mIgnoreFormat = aFormat; } catch (PatternSyntaxException e) { throw new ConversionException("unable to parse " + aFormat, e); } }
Example #20
Source File: AbstractReferenceCheck.java From cacheonix-core with GNU Lesser General Public License v2.1 | 5 votes |
/** * Set the ignore name format to the specified regular expression. * @param aFormat a <code>String</code> value * @throws ConversionException unable to parse aFormat */ public void setIgnoreName(String aFormat) throws ConversionException { try { mIgnoreNameRegexp = Utils.getPattern(aFormat); } catch (PatternSyntaxException e) { throw new ConversionException("unable to parse " + aFormat, e); } }
Example #21
Source File: AbstractReferenceCheck.java From cacheonix-core with GNU Lesser General Public License v2.1 | 5 votes |
/** * Set the ignore class name to the specified regular expression. * @param aFormat a <code>String</code> value * @throws ConversionException unable to parse aFormat */ public void setIgnoreClassName(String aFormat) throws ConversionException { try { mIgnoreClassNameRegexp = Utils.getPattern(aFormat); } catch (PatternSyntaxException e) { throw new ConversionException("unable to parse " + aFormat, e); } }
Example #22
Source File: JRFloatLocaleConverter.java From jasperreports with GNU Lesser General Public License v3.0 | 5 votes |
@Override protected Object parse(Object value, String pattern) throws ParseException { final Number parsed = (Number) super.parse(value, pattern); double doubleValue = parsed.doubleValue(); double posDouble = (doubleValue >= 0) ? doubleValue : (doubleValue * -1); if ((posDouble > 0 && posDouble < Float.MIN_VALUE) || posDouble > Float.MAX_VALUE) { throw new ConversionException("Supplied number is not of type Float: "+parsed); } return parsed.floatValue(); // unlike superclass it returns Float type }
Example #23
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 #24
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 #25
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 #26
Source File: RegexParser.java From attic-apex-malhar with Apache License 2.0 | 4 votes |
@Override public void processTuple(byte[] tuple) { if (tuple == null) { if (err.isConnected()) { err.emit(new KeyValPair<String, String>(null, "Blank/null tuple")); } errorTupleCount++; return; } String incomingString = new String(tuple); if (StringUtils.isBlank(incomingString)) { if (err.isConnected()) { err.emit(new KeyValPair<String, String>(incomingString, "Blank tuple")); } errorTupleCount++; return; } try { if (out.isConnected() && clazz != null) { Matcher matcher = pattern.matcher(incomingString); boolean patternMatched = false; Constructor<?> ctor = clazz.getConstructor(); Object object = ctor.newInstance(); if (matcher.find()) { for (int i = 0; i <= matcher.groupCount() - 1; i++) { if (delimitedParserSchema.getFields().get(i).getType() == DelimitedSchema.FieldType.DATE) { DateTimeConverter dtConverter = new DateConverter(); dtConverter.setPattern((String)delimitedParserSchema.getFields().get(i).getConstraints().get(DelimitedSchema.DATE_FORMAT)); ConvertUtils.register(dtConverter, Date.class); } BeanUtils.setProperty(object, delimitedParserSchema.getFields().get(i).getName(), matcher.group(i + 1)); } patternMatched = true; } if (!patternMatched) { throw new ConversionException("The incoming tuple do not match with the Regex pattern defined."); } out.emit(object); emittedObjectCount++; } } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException | InstantiationException | ConversionException e) { if (err.isConnected()) { err.emit(new KeyValPair<String, String>(incomingString, e.getMessage())); logger.debug("Regex Expression : {} Incoming tuple : {}", splitRegexPattern, incomingString); } errorTupleCount++; logger.error("Tuple could not be parsed. Reason {}", e.getMessage()); } }
Example #27
Source File: ConversionUtils.java From red5-io with Apache License 2.0 | 4 votes |
/** * Convert source to given class * * @param source * Source object * @param target * Target class * @return Converted object * @throws ConversionException * If object can't be converted */ @SuppressWarnings({ "unchecked", "rawtypes" }) public static Object convert(Object source, Class<?> target) throws ConversionException { if (target == null) { throw new ConversionException("Unable to perform conversion, target was null"); } if (source == null) { if (target.isPrimitive()) { throw new ConversionException(String.format("Unable to convert null to primitive value of %s", target)); } return source; } else if ((source instanceof Float && ((Float) source).isNaN()) || (source instanceof Double && ((Double) source).isNaN())) { // Don't convert NaN values return source; } if (target.isInstance(source)) { return source; } if (target.isAssignableFrom(source.getClass())) { return source; } if (target.isArray()) { return convertToArray(source, target); } if (target.equals(String.class)) { return source.toString(); } if (target.isPrimitive()) { return convertToWrappedPrimitive(source, primitiveMap.get(target)); } if (wrapperMap.containsKey(target)) { return convertToWrappedPrimitive(source, target); } if (target.equals(Map.class)) { return convertBeanToMap(source); } if (target.equals(List.class) || target.equals(Collection.class)) { if (source.getClass().equals(LinkedHashMap.class)) { return convertMapToList((LinkedHashMap<?, ?>) source); } else if (source.getClass().isArray()) { return convertArrayToList((Object[]) source); } } if (target.equals(Set.class) && source.getClass().isArray()) { return convertArrayToSet((Object[]) source); } if (target.equals(Set.class) && source instanceof List) { return new HashSet((List) source); } if (source instanceof Map) { return convertMapToBean((Map) source, target); } throw new ConversionException(String.format("Unable to preform conversion from %s to %s", source, target)); }
Example #28
Source File: ConversionUtilsTest.java From red5-io with Apache License 2.0 | 4 votes |
@Test(expected = ConversionException.class) public void testNullConvertNoClass() { // should throw exception ConversionUtils.convert(new TestJavaBean(), null); }
Example #29
Source File: ConversionUtils.java From red5-io with Apache License 2.0 | 3 votes |
/** * Convert parameters using methods of this utility class * * @param source * Array of source object * @param target * Array of target classes * @return Array of converted objects * @throws ConversionException * If object can't be converted */ public static Object[] convertParams(Object[] source, Class<?>[] target) throws ConversionException { Object[] converted = new Object[target.length]; for (int i = 0; i < target.length; i++) { converted[i] = convert(source[i], target[i]); } return converted; }
Example #30
Source File: ConversionUtils.java From red5-io with Apache License 2.0 | 3 votes |
/** * * @param source * source arra * @return list * @throws ConversionException * on failure */ public static List<?> convertArrayToList(Object[] source) throws ConversionException { List<Object> list = new ArrayList<Object>(source.length); for (Object element : source) { list.add(element); } return list; }