Search in sources :

Example 6 with TypeConverter

use of org.apache.camel.TypeConverter in project camel by apache.

the class BaseTypeConverterRegistry method removeTypeConverter.

@Override
public boolean removeTypeConverter(Class<?> toType, Class<?> fromType) {
    log.trace("Removing type converter from: {} to: {}", fromType, toType);
    TypeMapping key = new TypeMapping(toType, fromType);
    TypeConverter converter = typeMappings.remove(key);
    if (converter != null) {
        typeMappings.remove(key);
        misses.remove(key);
    }
    return converter != null;
}
Also used : TypeConverter(org.apache.camel.TypeConverter)

Example 7 with TypeConverter

use of org.apache.camel.TypeConverter in project camel by apache.

the class BaseTypeConverterRegistry method addTypeConverter.

@Override
public void addTypeConverter(Class<?> toType, Class<?> fromType, TypeConverter typeConverter) {
    log.trace("Adding type converter: {}", typeConverter);
    TypeMapping key = new TypeMapping(toType, fromType);
    TypeConverter converter = typeMappings.get(key);
    if (typeConverter != converter) {
        // add the converter unless we should ignore
        boolean add = true;
        // if converter is not null then a duplicate exists
        if (converter != null) {
            if (typeConverterExists == TypeConverterExists.Override) {
                CamelLogger logger = new CamelLogger(log, typeConverterExistsLoggingLevel);
                logger.log("Overriding type converter from: " + converter + " to: " + typeConverter);
            } else if (typeConverterExists == TypeConverterExists.Ignore) {
                CamelLogger logger = new CamelLogger(log, typeConverterExistsLoggingLevel);
                logger.log("Ignoring duplicate type converter from: " + converter + " to: " + typeConverter);
                add = false;
            } else {
                // we should fail
                throw new TypeConverterExistsException(toType, fromType);
            }
        }
        if (add) {
            typeMappings.put(key, typeConverter);
            // remove any previous misses, as we added the new type converter
            misses.remove(key);
        }
    }
}
Also used : TypeConverter(org.apache.camel.TypeConverter) CamelLogger(org.apache.camel.util.CamelLogger) TypeConverterExistsException(org.apache.camel.TypeConverterExistsException)

Example 8 with TypeConverter

use of org.apache.camel.TypeConverter in project camel by apache.

the class BaseTypeConverterRegistry method doConvertTo.

protected Object doConvertTo(final Class<?> type, final Exchange exchange, final Object value, final boolean tryConvert) {
    if (log.isTraceEnabled()) {
        log.trace("Converting {} -> {} with value: {}", new Object[] { value == null ? "null" : value.getClass().getCanonicalName(), type.getCanonicalName(), value });
    }
    if (value == null) {
        // no type conversion was needed
        if (statistics.isStatisticsEnabled()) {
            noopCounter.incrementAndGet();
        }
        // lets avoid NullPointerException when converting to boolean for null values
        if (boolean.class.isAssignableFrom(type)) {
            return Boolean.FALSE;
        }
        return null;
    }
    // same instance type
    if (type.isInstance(value)) {
        // no type conversion was needed
        if (statistics.isStatisticsEnabled()) {
            noopCounter.incrementAndGet();
        }
        return type.cast(value);
    }
    // special for NaN numbers, which we can only convert for floating numbers
    if (ObjectHelper.isNaN(value)) {
        // no type conversion was needed
        if (statistics.isStatisticsEnabled()) {
            noopCounter.incrementAndGet();
        }
        if (Float.class.isAssignableFrom(type)) {
            return Float.NaN;
        } else if (Double.class.isAssignableFrom(type)) {
            return Double.NaN;
        } else {
            // we cannot convert the NaN
            return Void.TYPE;
        }
    }
    // okay we need to attempt to convert
    if (statistics.isStatisticsEnabled()) {
        attemptCounter.incrementAndGet();
    }
    // check if we have tried it before and if its a miss
    TypeMapping key = new TypeMapping(type, value.getClass());
    if (misses.containsKey(key)) {
        // we have tried before but we cannot convert this one
        return Void.TYPE;
    }
    // try to find a suitable type converter
    TypeConverter converter = getOrFindTypeConverter(key);
    if (converter != null) {
        log.trace("Using converter: {} to convert {}", converter, key);
        Object rc;
        if (tryConvert) {
            rc = converter.tryConvertTo(type, exchange, value);
        } else {
            rc = converter.convertTo(type, exchange, value);
        }
        if (rc == null && converter.allowNull()) {
            return null;
        } else if (rc != null) {
            return rc;
        }
    }
    // not found with that type then if it was a primitive type then try again with the wrapper type
    if (type.isPrimitive()) {
        Class<?> primitiveType = ObjectHelper.convertPrimitiveTypeToWrapperType(type);
        if (primitiveType != type) {
            Class<?> fromType = value.getClass();
            TypeConverter tc = getOrFindTypeConverter(new TypeMapping(primitiveType, fromType));
            if (tc != null) {
                // add the type as a known type converter as we can convert from primitive to object converter
                addTypeConverter(type, fromType, tc);
                Object rc;
                if (tryConvert) {
                    rc = tc.tryConvertTo(primitiveType, exchange, value);
                } else {
                    rc = tc.convertTo(primitiveType, exchange, value);
                }
                if (rc == null && tc.allowNull()) {
                    return null;
                } else if (rc != null) {
                    return rc;
                }
            }
        }
    }
    // fallback converters
    for (FallbackTypeConverter fallback : fallbackConverters) {
        TypeConverter tc = fallback.getFallbackTypeConverter();
        Object rc;
        if (tryConvert) {
            rc = tc.tryConvertTo(type, exchange, value);
        } else {
            rc = tc.convertTo(type, exchange, value);
        }
        if (rc == null && tc.allowNull()) {
            return null;
        }
        if (Void.TYPE.equals(rc)) {
            // it cannot be converted so give up
            return Void.TYPE;
        }
        if (rc != null) {
            // if fallback can promote then let it be promoted to a first class type converter
            if (fallback.isCanPromote()) {
                // add it as a known type converter since we found a fallback that could do it
                if (log.isDebugEnabled()) {
                    log.debug("Promoting fallback type converter as a known type converter to convert from: {} to: {} for the fallback converter: {}", new Object[] { type.getCanonicalName(), value.getClass().getCanonicalName(), fallback.getFallbackTypeConverter() });
                }
                addTypeConverter(type, value.getClass(), fallback.getFallbackTypeConverter());
            }
            if (log.isTraceEnabled()) {
                log.trace("Fallback type converter {} converted type from: {} to: {}", new Object[] { fallback.getFallbackTypeConverter(), type.getCanonicalName(), value.getClass().getCanonicalName() });
            }
            // return converted value
            return rc;
        }
    }
    if (!tryConvert) {
        // Could not find suitable conversion, so remember it
        // do not register misses for try conversions
        misses.put(key, key);
    }
    // Could not find suitable conversion, so return Void to indicate not found
    return Void.TYPE;
}
Also used : TypeConverter(org.apache.camel.TypeConverter)

Example 9 with TypeConverter

use of org.apache.camel.TypeConverter in project camel by apache.

the class InstanceMethodTypeConverter method convertTo.

@SuppressWarnings("unchecked")
public <T> T convertTo(Class<T> type, Exchange exchange, Object value) {
    Object instance = injector.newInstance();
    if (instance == null) {
        throw new RuntimeCamelException("Could not instantiate an instance of: " + type.getCanonicalName());
    }
    // inject parent type converter
    if (instance instanceof TypeConverterAware) {
        if (registry instanceof TypeConverter) {
            TypeConverter parentTypeConverter = (TypeConverter) registry;
            ((TypeConverterAware) instance).setTypeConverter(parentTypeConverter);
        }
    }
    return useExchange ? (T) ObjectHelper.invokeMethod(method, instance, value, exchange) : (T) ObjectHelper.invokeMethod(method, instance, value);
}
Also used : TypeConverter(org.apache.camel.TypeConverter) TypeConverterAware(org.apache.camel.spi.TypeConverterAware) RuntimeCamelException(org.apache.camel.RuntimeCamelException)

Example 10 with TypeConverter

use of org.apache.camel.TypeConverter in project camel by apache.

the class LazyLoadingTypeConverter method doLookup.

@Override
protected TypeConverter doLookup(Class<?> toType, Class<?> fromType, boolean isSuper) {
    TypeConverter answer = super.doLookup(toType, fromType, isSuper);
    if (answer == null && !loaded.get()) {
        // okay we could not convert, so try again, but load the converters up front
        ensureLoaded();
        answer = super.doLookup(toType, fromType, isSuper);
    }
    return answer;
}
Also used : TypeConverter(org.apache.camel.TypeConverter)

Aggregations

TypeConverter (org.apache.camel.TypeConverter)48 Map (java.util.Map)13 FallbackConverter (org.apache.camel.FallbackConverter)9 InputStream (java.io.InputStream)6 HashMap (java.util.HashMap)6 Exchange (org.apache.camel.Exchange)6 RuntimeCamelException (org.apache.camel.RuntimeCamelException)6 ArrayList (java.util.ArrayList)5 NoTypeConversionAvailableException (org.apache.camel.NoTypeConversionAvailableException)5 HttpString (io.undertow.util.HttpString)4 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4 ObjectOutputStream (java.io.ObjectOutputStream)4 PrintWriter (java.io.PrintWriter)4 StringWriter (java.io.StringWriter)4 UnsupportedEncodingException (java.io.UnsupportedEncodingException)4 List (java.util.List)4 HeaderMap (io.undertow.util.HeaderMap)3 IOException (java.io.IOException)3 URI (java.net.URI)3 Message (org.apache.camel.Message)3