/** * Checks whether the result of a conversion is conform to the specified * target type. If this is the case, the passed in result object is cast to * the correct target type. Otherwise, an exception is thrown. * * @param <T> the desired result type * @param type the target class of the conversion * @param result the conversion result object * @return the result cast to the target class * @throws ConversionException if the result object is not compatible with * the target type */ private static <T> T checkConversionResult(final Class<T> type, final Object result) { if (type == null) { // in this case we cannot do much; the result object is returned @SuppressWarnings("unchecked") final T temp = (T) result; return temp; } if (result == null) { return null; } if (type.isInstance(result)) { return type.cast(result); } throw new ConversionException("Unsupported target type: " + type); }
/** * Convert the specified locale-sensitive input object into an output object of the * specified type. This method will return values of type Short. * * @param value The input object to be converted * @param pattern The pattern is used for the convertion * @return The converted value * * @throws org.apache.commons.beanutils.ConversionException if conversion cannot be performed * successfully * @throws ParseException if an error occurs parsing a String to a Number * @since 1.8.0 */ @Override protected Object parse(final Object value, final String pattern) throws ParseException { final Object result = super.parse(value, pattern); if (result == null || result instanceof Short) { return result; } final Number parsed = (Number)result; if (parsed.longValue() != parsed.shortValue()) { throw new ConversionException("Supplied number is not of type Short: " + parsed.longValue()); } // now returns property Short return new Short(parsed.shortValue()); }
/** * Convert the specified locale-sensitive input object into an output object of * BigDecimal type. * * @param value The input object to be converted * @param pattern The pattern is used for the convertion * @return The converted value * * @throws ConversionException if conversion cannot be performed * successfully * @throws ParseException if an error occurs parsing a String to a Number * @since 1.8.0 */ @Override protected Object parse(final Object value, final String pattern) throws ParseException { final Object result = super.parse(value, pattern); if (result == null || result instanceof BigDecimal) { return result; } try { return new BigDecimal(result.toString()); } catch (final NumberFormatException ex) { throw new ConversionException("Suplied number is not of type BigDecimal: " + result); } }
/** * Convert the specified locale-sensitive input object into an output object of * BigInteger type. * * @param value The input object to be converted * @param pattern The pattern is used for the convertion * @return The converted value * * @throws ConversionException if conversion cannot be performed * successfully * @throws ParseException if an error occurs parsing a String to a Number * @since 1.8.0 */ @Override protected Object parse(final Object value, final String pattern) throws ParseException { final Object result = super.parse(value, pattern); if (result == null || result instanceof BigInteger) { return result; } if (result instanceof Number) { return BigInteger.valueOf(((Number)result).longValue()); } try { return new BigInteger(result.toString()); } catch (final NumberFormatException ex) { throw new ConversionException("Suplied number is not of type BigInteger: " + result); } }
/** * Convert a String into a <code>Number</code> object. * @param sourceType the source type of the conversion * @param targetType The type to convert the value to * @param value The String date value. * @param format The NumberFormat to parse the String value. * * @return The converted Number object. * @throws ConversionException if the String cannot be converted. */ private Number parse(final Class<?> sourceType, final Class<?> targetType, final String value, final NumberFormat format) { final ParsePosition pos = new ParsePosition(0); final Number parsedNumber = format.parse(value, pos); if (pos.getErrorIndex() >= 0 || pos.getIndex() != value.length() || parsedNumber == null) { String msg = "Error converting from '" + toString(sourceType) + "' to '" + toString(targetType) + "'"; if (format instanceof DecimalFormat) { msg += " using pattern '" + ((DecimalFormat)format).toPattern() + "'"; } if (locale != null) { msg += " for locale=[" + locale + "]"; } if (log().isDebugEnabled()) { log().debug(" " + msg); } throw new ConversionException(msg); } return parsedNumber; }
/** * Parse a String date value using the set of patterns. * * @param sourceType The type of the value being converted * @param targetType The type to convert the value to. * @param value The String date value. * * @return The converted Date object. * @throws Exception if an error occurs parsing the date. */ private Calendar parse(final Class<?> sourceType, final Class<?> targetType, final String value) throws Exception { Exception firstEx = null; for (String pattern : patterns) { try { final DateFormat format = getFormat(pattern); final Calendar calendar = parse(sourceType, targetType, value, format); return calendar; } catch (final Exception ex) { if (firstEx == null) { firstEx = ex; } } } if (patterns.length > 1) { throw new ConversionException("Error converting '" + toString(sourceType) + "' to '" + toString(targetType) + "' using patterns '" + displayPatterns + "'"); } else { throw firstEx; } }
/** * Parse a String into a <code>Calendar</code> object * using the specified <code>DateFormat</code>. * * @param sourceType The type of the value being converted * @param targetType The type to convert the value to * @param value The String date value. * @param format The DateFormat to parse the String value. * * @return The converted Calendar object. * @throws ConversionException if the String cannot be converted. */ private Calendar parse(final Class<?> sourceType, final Class<?> targetType, final String value, final DateFormat format) { logFormat("Parsing", format); format.setLenient(false); final ParsePosition pos = new ParsePosition(0); final Date parsedDate = format.parse(value, pos); // ignore the result (use the Calendar) if (pos.getErrorIndex() >= 0 || pos.getIndex() != value.length() || parsedDate == null) { String msg = "Error converting '" + toString(sourceType) + "' to '" + toString(targetType) + "'"; if (format instanceof SimpleDateFormat) { msg += " using pattern '" + ((SimpleDateFormat)format).toPattern() + "'"; } if (log().isDebugEnabled()) { log().debug(" " + msg); } throw new ConversionException(msg); } final Calendar calendar = format.getCalendar(); return calendar; }
/** * <p>Set the value of a simple property with the specified name.</p> * * @param name Name of the property whose value is to be set * @param value Value to which this property is to be set * * @exception ConversionException if the specified value cannot be * converted to the type required for this property * @exception IllegalArgumentException if there is no property * of the specified name * @exception NullPointerException if the type specified for the * property is invalid * @exception NullPointerException if an attempt is made to set a * primitive property to null */ public void set(String name, Object value) { DynaProperty descriptor = getDynaProperty(name); if (descriptor.getType() == null) { throw new NullPointerException ("The type for property " + name + " is invalid"); } if (value == null) { if (descriptor.getType().isPrimitive()) { throw new NullPointerException ("Primitive value for '" + name + "'"); } } else if (!isDynaAssignable(descriptor.getType(), value.getClass())) { throw new ConversionException ("Cannot assign value of type '" + value.getClass().getName() + "' to property '" + name + "' of type '" + descriptor.getType().getName() + "'"); } dynaValues.put(name, value); }
/** * <p>Set the value of an indexed property with the specified name.</p> * * @param name Name of the property whose value is to be set * @param index Index of the property to be set * @param value Value to which this property is to be set * * @exception ConversionException if the specified value cannot be * converted to the type required for this property * @exception IllegalArgumentException if there is no property * of the specified name * @exception IllegalArgumentException if the specified property * exists, but is not indexed * @exception IndexOutOfBoundsException if the specified index * is outside the range of the underlying property */ public void set(String name, int index, Object value) { Object prop = dynaValues.get(name); if (prop == null) { throw new NullPointerException ("No indexed value for '" + name + "[" + index + "]'"); } else if (prop.getClass().isArray()) { Array.set(prop, index, value); } else if (prop instanceof List) { try { ((List) prop).set(index, value); } catch (ClassCastException e) { throw new ConversionException(e.getMessage()); } } else { throw new IllegalArgumentException ("Non-indexed property for '" + name + "[" + index + "]'"); } }
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进行转化 }
@Test public void testContextualizeConversionException() { final TestBean testBean = new TestBean(); final DefaultContext context = new DefaultContext(); context.add("val", "some string"); try { testBean.contextualize(context); fail("InvocationTargetException is expected"); } catch (CheckstyleException ex) { final String expected = "illegal value "; assertTrue("Invalid exception cause, should be: ConversionException", ex.getCause() instanceof ConversionException); assertTrue("Invalid exception message, should start with: " + expected, ex.getMessage().startsWith(expected)); } }
/** * <p>Set the value of a simple property with the specified name.</p> * * @param name Name of the property whose value is to be set * @param value Value to which this property is to be set * @throws ConversionException if the specified value cannot be * converted to the type required for * this property * @throws IllegalArgumentException if there is no property of the * specified name * @throws NullPointerException if the type specified for the property * is invalid * @throws NullPointerException if an attempt is made to set a * primitive property to null */ public void set(String name, Object value) { DynaProperty descriptor = getDynaProperty(name); if (descriptor.getType() == null) { throw new NullPointerException("The type for property " + name + " is invalid"); } if (value == null) { if (descriptor.getType().isPrimitive()) { throw new NullPointerException("Primitive value for '" + name + "'"); } } else if (!isDynaAssignable(descriptor.getType(), value.getClass())) { throw new ConversionException("Cannot assign value of type '" + value.getClass().getName() + "' to property '" + name + "' of type '" + descriptor.getType().getName() + "'"); } dynaValues.put(name, value); }
/** * <p>Set the value of an indexed property with the specified name.</p> * * @param name Name of the property whose value is to be set * @param index Index of the property to be set * @param value Value to which this property is to be set * @throws ConversionException if the specified value cannot be * converted to the type required for * this property * @throws NullPointerException if there is no property of the * specified name * @throws IllegalArgumentException if the specified property exists, but * is not indexed * @throws IndexOutOfBoundsException if the specified index is outside the * range of the underlying property */ public void set(String name, int index, Object value) { Object prop = dynaValues.get(name); if (prop == null) { throw new NullPointerException("No indexed value for '" + name + "[" + index + "]'"); } else if (prop.getClass().isArray()) { Array.set(prop, index, value); } else if (prop instanceof List) { try { ((List) prop).set(index, value); } catch (ClassCastException e) { throw new ConversionException(e.getMessage()); } } else { throw new IllegalArgumentException("Non-indexed property for '" + name + "[" + index + "]'"); } }
public Format convertToComplexType(String convertFrom) throws ConversionException { //The patterns can contain the delimiter character. int firstSeparator = convertFrom.indexOf(DELIMITER); if (firstSeparator == -1) { throw new IllegalArgumentException("Cannot find the class type for the string " + convertFrom); } String className = convertFrom.substring(0, firstSeparator); String pattern = convertFrom.substring(firstSeparator + 1); if (className.equals(DecimalFormat.class.getSimpleName())) { return new DecimalFormat(pattern); } else if (className.equals(SimpleDateFormat.class.getSimpleName())) { return new SimpleDateFormat(pattern); } else { throw new IllegalStateException("Unknown class " + className + " to create a format on based on the pattern " + pattern); } }
/** * 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); } } }
/** * 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); } }
/** * 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)); }
/** * 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)); }
/** * 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; }
/** * Convert a date to a String and a String to a Date * * @param type * String, Date or Timestamp * @param value * value to convert * @return Converted value for property population */ @SuppressWarnings("unchecked") public Object convert(Class type, Object value) { if (value == null) { return null; } else if (type == Timestamp.class) { return convertToDate(type, value, DateUtil.getDateTimePattern()); } else if (type == Date.class) { return convertToDate(type, value, DateUtil.getDatePattern()); } else if (type == String.class) { return convertToString(type, value); } throw new ConversionException("Could not convert " + value.getClass().getName() + " to " + type.getName()); }
/** * Convert a String to a Date with the specified pattern. * * @param type * String * @param value * value of String * @param pattern * date pattern to parse with * @return Converted value for property population */ @SuppressWarnings("unchecked") 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) { throw new ConversionException("Error converting String to Date"); } } throw new ConversionException("Could not convert " + value.getClass().getName() + " to " + type.getName()); }
/** * Convert a java.util.Date to a String * * @param type * Date or Timestamp * @param value * value to convert * @return Converted value for property population */ @SuppressWarnings("unchecked") protected Object convertToString(Class type, Object value) { if (value instanceof Date) { DateFormat df = new SimpleDateFormat(DateUtil.getDatePattern()); if (value instanceof Timestamp) { df = new SimpleDateFormat(DateUtil.getDateTimePattern()); } try { return df.format(value); } catch (Exception e) { throw new ConversionException("Error converting Date to String"); } } else { return value.toString(); } }
/** * Convert a String to a date * * @param type * java.util.Date * @param value * the String value * @return a converted date */ @SuppressWarnings("unchecked") protected Object convertToDate(Class type, Object value) { DateFormat df = new SimpleDateFormat(TS_FORMAT); if (value instanceof String) { try { if (StringUtils.isEmpty(value.toString())) { return null; } return df.parse((String) value); } catch (Exception pe) { throw new ConversionException( "Error converting String to Timestamp"); } } throw new ConversionException("Could not convert " + value.getClass().getName() + " to " + type.getName()); }
/** * Convert from a java.util.Date to a String * * @param type * java.lang.String * @param value * the date instance * @return string version of date using default date pattern */ @SuppressWarnings("unchecked") @Override protected Object convertToString(Class type, Object value) { DateFormat df = new SimpleDateFormat(TS_FORMAT); if (value instanceof Date) { try { return df.format(value); } catch (Exception e) { throw new ConversionException( "Error converting Timestamp to String"); } } return value.toString(); }
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()); }
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()); }
protected Object convertToString(Class type, Object value) { if (value instanceof Date) { DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); if (value instanceof Timestamp) { df = new SimpleDateFormat("HH:mm:ss"); } try { return df.format(value); } catch (Exception e) { e.printStackTrace(); throw new ConversionException("Error converting Date to String"); } } else { return value.toString(); } }
/** * Convert a String to a Date with the specified pattern. * @param type String * @param value value of String * @param pattern date pattern to parse with * @return Converted value for property population */ protected Object convertToDate(final Class<?> type, final Object value, final String pattern) { final DateFormat df = new SimpleDateFormat(pattern); if (value instanceof String) { try { if (StringUtils.isEmpty(value.toString())) { return null; } final Date date = df.parse((String) value); if (type.equals(Timestamp.class)) { return new Timestamp(date.getTime()); } return date; } catch (final Exception e) { throw new ConversionException("Error converting String to Date", e); } } throw new ConversionException("Could not convert " + value.getClass().getName() + " to " + type.getName()); }
/** * Convert a java.util.Date or a java.sql.Timestamp to a String. Or does a toString * @param value value to convert * @return Converted value for property population */ protected Object convertToString(final Object value) { if (value instanceof Date) { DateFormat df = new SimpleDateFormat(DateUtil.getDatePattern()); if (value instanceof Timestamp) { df = new SimpleDateFormat(DateUtil.getDateTimePattern()); } try { return df.format(value); } catch (final Exception e) { throw new ConversionException("Error converting Date to String", e); } } else { return value.toString(); } }
/** * Convert a String to a date * @param type java.util.Date * @param value the String value * @return a converted date */ protected Object convertToDate(Class type, Object value) { DateFormat df = new SimpleDateFormat(TS_FORMAT); if (value instanceof String) { try { if (StringUtils.isEmpty(value.toString())) { return null; } return df.parse((String) value); } catch (Exception pe) { throw new ConversionException("Error converting String to Timestamp"); } } throw new ConversionException("Could not convert " + value.getClass().getName() + " to " + type.getName()); }
public Cube convertToComplexType(String convertFrom) throws ConversionException { String[] pieces = PersisterUtils.splitByDelimiter(convertFrom, 4); Olap4jDataSource ds = dsCollection.getDataSource(pieces[0], Olap4jDataSource.class); Catalog catalog; try { catalog = mapping.createConnection(ds).getCatalogs().get(pieces[1]); } catch (Exception ex) { throw new ConversionException("Error connecting to data source " + pieces[0] + " to get cube defined by " + convertFrom, ex); } Schema schema; try { schema = catalog.getSchemas().get(pieces[2]); Cube cube = schema.getCubes().get(pieces[3]); return cube; } catch (OlapException e) { throw new ConversionException("The cube could not be retrieved from the string " + convertFrom, e); } }
public Item convertToComplexType(String convertFrom) throws ConversionException { String[] pieces = PersisterUtils.splitByDelimiter(convertFrom, 3); if (pieces[0].equals(SQLObjectItem.class.getSimpleName())) { List<QueryCache> queries = workspace.getQueries(); for (QueryCache query : queries) { for (Container table : query.getFromTableList()) { for (Item item : table.getItems()) { if (item.getUUID().equals(pieces[2])) { return item; } } } } return new SQLObjectItem(pieces[1], pieces[2]); } else if (pieces[0].equals(StringItem.class.getSimpleName())) { return new StringItem(pieces[1], pieces[2]); } else { throw new IllegalArgumentException("Unknown class of item for " + pieces[0] + " to convert " + convertFrom); } }
/** * Convert to date. * * @param type * the type * @param value * the value * @return the object */ protected Object convertToDate(Class type, Object value) { DateFormat df = new SimpleDateFormat(ConvertDateUtil.getDatePattern()); if (value instanceof String) { try { if (StringUtils.isEmpty(value.toString())) { return null; } return df.parse((String) value); } catch (Exception pe) { throw new ConversionException("Error converting String to Date"); } } throw new ConversionException("Could not convert " + value.getClass().getName() + " to " + type.getName()); }
protected Object convertToDate(Class type, Object value) { DateFormat df = new SimpleDateFormat(TS_FORMAT); if (value instanceof String) { try { if (StringUtils.isEmpty(value.toString())) { return null; } return df.parse((String) value); } catch (Exception pe) { throw new ConversionException("Error converting String to Timestamp"); } } throw new ConversionException("Could not convert " + value.getClass().getName() + " to " + type.getName()); }
public Object convert( @SuppressWarnings( "rawtypes" ) Class type, Object value ) { if ( value == null ) { throw new ConversionException( "Null values not supported in this version." ); } if ( ParamType.class == type ) { if ( value instanceof String ) { return ParamType.valueOf( ( (String) value ).toUpperCase() ); } } throw new ConversionException( format( "type %s and value %s not supported", type, value ) ); }