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

The following examples show how to use org.apache.commons.beanutils.ConversionException. 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: DataLink   Source File: ByteArrayConverter.java    License: Apache License 2.0 6 votes vote down vote up
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 Project: elepy   Source File: Injector.java    License: Apache License 2.0 6 votes vote down vote up
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 Project: onetwo   Source File: DateConverter.java    License: Apache License 2.0 6 votes vote down vote up
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 4
Source Project: onetwo   Source File: DateConverter.java    License: Apache License 2.0 6 votes vote down vote up
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 5
Source Project: rice   Source File: MessageQueueForm.java    License: Educational Community License v2.0 6 votes vote down vote up
/**
 * 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 6
Source Project: red5-io   Source File: ConversionUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 Project: red5-io   Source File: ConversionUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 8
Source Project: red5-io   Source File: ConversionUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 9
Source Project: red5-io   Source File: ConversionUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 10
Source Project: DataLink   Source File: SqlTimestampConverter.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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
/**
 * 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 12
/**
 * 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 13
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 14
@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 15
/**
 * 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 16
/**
 * 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 17
/**
 * 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 18
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 19
Source Project: ogham   Source File: BeanUtils.java    License: Apache License 2.0 5 votes vote down vote up
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 20
/**
 * 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 21
/**
 * 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 22
/**
 * 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 23
Source Project: feilong-core   Source File: ConvertClassTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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 24
Source Project: HiveRunner   Source File: Converters.java    License: Apache License 2.0 5 votes vote down vote up
@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 25
Source Project: HiveRunner   Source File: ConvertersTest.java    License: Apache License 2.0 5 votes vote down vote up
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 26
Source Project: attic-apex-malhar   Source File: RegexParser.java    License: Apache License 2.0 4 votes vote down vote up
@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 Project: red5-io   Source File: ConversionUtils.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * 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 Project: red5-io   Source File: ConversionUtilsTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test(expected = ConversionException.class)
public void testNullConvertNoClass() {
    // should throw exception
    ConversionUtils.convert(new TestJavaBean(), null);
}
 
Example 29
Source Project: red5-io   Source File: ConversionUtils.java    License: Apache License 2.0 3 votes vote down vote up
/**
 * 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 Project: red5-io   Source File: ConversionUtils.java    License: Apache License 2.0 3 votes vote down vote up
/**
 *
 * @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;
}