@FallbackConverter public static <T> T convertTo(Class<T> type, Exchange exchange, Object value, TypeConverterRegistry registry) { try { if (value != null && value.getClass().equals(String.class)) { if (value.toString().startsWith("{") || value.toString().startsWith("[")) { T result = new UnirestJacksonObjectMapper().readValue(value.toString(), type); return result; } } } catch(Exception ex){ return null; } return null; }
/** * A fallback converter that allows us to easily call Java beans and use the raw Netty {@link HttpRequest} as parameter types. */ @FallbackConverter public static Object convertToHttpRequest(Class<?> type, Exchange exchange, Object value, TypeConverterRegistry registry) { // if we want to covert to HttpRequest if (value != null && HttpRequest.class.isAssignableFrom(type)) { // okay we may need to cheat a bit when we want to grab the HttpRequest as its stored on the NettyHttpMessage // so if the message instance is a NettyHttpMessage and its body is the value, then we can grab the // HttpRequest from the NettyHttpMessage NettyHttpMessage msg; if (exchange.hasOut()) { msg = exchange.getOut(NettyHttpMessage.class); } else { msg = exchange.getIn(NettyHttpMessage.class); } if (msg != null && msg.getBody() == value) { // ensure the http request content is reset so we can read all the content out-of-the-box HttpRequest request = msg.getHttpRequest(); request.getContent().resetReaderIndex(); return request; } } return null; }
/** * A fallback converter that allows us to easily call Java beans and use the raw Netty {@link HttpRequest} as parameter types. */ @FallbackConverter public static Object convertToHttpResponse(Class<?> type, Exchange exchange, Object value, TypeConverterRegistry registry) { // if we want to covert to convertToHttpResponse if (value != null && HttpResponse.class.isAssignableFrom(type)) { // okay we may need to cheat a bit when we want to grab the HttpRequest as its stored on the NettyHttpMessage // so if the message instance is a NettyHttpMessage and its body is the value, then we can grab the // HttpRequest from the NettyHttpMessage NettyHttpMessage msg; if (exchange.hasOut()) { msg = exchange.getOut(NettyHttpMessage.class); } else { msg = exchange.getIn(NettyHttpMessage.class); } if (msg != null && msg.getBody() == value) { return msg.getHttpResponse(); } } return null; }
@Converter public static InputStream toInputStream(Response response, Exchange exchange) { Object obj = response.getEntity(); if (obj == null) { return null; } if (obj instanceof InputStream) { // short circuit the lookup return (InputStream)obj; } TypeConverterRegistry registry = exchange.getContext().getTypeConverterRegistry(); TypeConverter tc = registry.lookup(InputStream.class, obj.getClass()); if (tc != null) { return tc.convertTo(InputStream.class, exchange, obj); } return null; }
/** * A fallback converter that allows us to easily call Java beans and use the raw Netty {@link HttpRequest} as parameter types. */ @FallbackConverter public static Object convertToHttpRequest(Class<?> type, Exchange exchange, Object value, TypeConverterRegistry registry) { // if we want to covert to HttpRequest if (value != null && HttpRequest.class.isAssignableFrom(type)) { // okay we may need to cheat a bit when we want to grab the HttpRequest as its stored on the NettyHttpMessage // so if the message instance is a NettyHttpMessage and its body is the value, then we can grab the // HttpRequest from the NettyHttpMessage NettyHttpMessage msg; if (exchange.hasOut()) { msg = exchange.getOut(NettyHttpMessage.class); } else { msg = exchange.getIn(NettyHttpMessage.class); } if (msg != null && msg.getBody() == value) { // ensure the http request content is reset so we can read all the content out-of-the-box FullHttpRequest request = msg.getHttpRequest(); request.content().resetReaderIndex(); return request; } } return null; }
@FallbackConverter public static Object convertTo(Class<?> type, Exchange exchange, Object value, TypeConverterRegistry registry) { // use a fallback type converter so we can convert the embedded body if the value is GenericFile if (GenericFile.class.isAssignableFrom(value.getClass())) { GenericFile<?> file = (GenericFile<?>) value; Class<?> from = file.getBody().getClass(); // maybe from is already the type we want if (from.isAssignableFrom(type)) { return file.getBody(); } // no then try to lookup a type converter TypeConverter tc = registry.lookup(type, from); if (tc != null) { Object body = file.getBody(); return tc.convertTo(type, exchange, body); } } return null; }
@FallbackConverter @SuppressWarnings("unchecked") public static <T extends Payload> T convertTo(Class<T> type, Exchange exchange, Object value, TypeConverterRegistry registry) throws IOException { Class<?> sourceType = value.getClass(); if (GenericFile.class.isAssignableFrom(sourceType)) { GenericFile<?> genericFile = (GenericFile<?>) value; if (genericFile.getFile() != null) { Class<?> genericFileType = genericFile.getFile().getClass(); TypeConverter converter = registry.lookup(Payload.class, genericFileType); if (converter != null) { return (T) converter.convertTo(Payload.class, genericFile.getFile()); } } } return null; }
/** * A fallback converter that allows us to easily call Java beans and use the raw Spark {@link Request} as parameter types. */ @FallbackConverter public static Object convertToRequest(Class<?> type, Exchange exchange, Object value, TypeConverterRegistry registry) { // if we want to covert to Request if (value != null && Request.class.isAssignableFrom(type)) { // okay we may need to cheat a bit when we want to grab the HttpRequest as its stored on the NettyHttpMessage // so if the message instance is a NettyHttpMessage and its body is the value, then we can grab the // HttpRequest from the NettyHttpMessage SparkMessage msg; if (exchange.hasOut()) { msg = exchange.getOut(SparkMessage.class); } else { msg = exchange.getIn(SparkMessage.class); } if (msg != null) { return msg.getRequest(); } } return null; }
/** * A fallback converter that allows us to easily call Java beans and use the raw Spark {@link Response} as parameter types. */ @FallbackConverter public static Object convertToResponse(Class<?> type, Exchange exchange, Object value, TypeConverterRegistry registry) { // if we want to covert to Response if (value != null && Response.class.isAssignableFrom(type)) { // okay we may need to cheat a bit when we want to grab the HttpRequest as its stored on the NettyHttpMessage // so if the message instance is a NettyHttpMessage and its body is the value, then we can grab the // HttpRequest from the NettyHttpMessage SparkMessage msg; if (exchange.hasOut()) { msg = exchange.getOut(SparkMessage.class); } else { msg = exchange.getIn(SparkMessage.class); } if (msg != null) { return msg.getResponse(); } } return null; }
@FallbackConverter @SuppressWarnings("unchecked") public static <T> T convertTo(Class<T> type, Exchange exchange, Object value, TypeConverterRegistry registry) { if (value != null) { // should not try to convert Request as its not possible if (Request.class.isAssignableFrom(value.getClass())) { return (T) Void.TYPE; } } return null; }
public InstanceMethodTypeConverter(CachingInjector<?> injector, Method method, TypeConverterRegistry registry, boolean allowNull) { this.injector = injector; this.method = method; this.useExchange = method.getParameterTypes().length == 2; this.registry = registry; this.allowNull = allowNull; }
private CachingInjector<?> handleHasConverterAnnotation(TypeConverterRegistry registry, Class<?> type, CachingInjector<?> injector, Method method, boolean allowNull) { if (isValidConverterMethod(method)) { int modifiers = method.getModifiers(); if (isAbstract(modifiers) || !isPublic(modifiers)) { LOG.warn("Ignoring bad converter on type: " + type.getCanonicalName() + " method: " + method + " as a converter method is not a public and concrete method"); } else { Class<?> toType = method.getReturnType(); if (toType.equals(Void.class)) { LOG.warn("Ignoring bad converter on type: " + type.getCanonicalName() + " method: " + method + " as a converter method returns a void method"); } else { Class<?> fromType = method.getParameterTypes()[0]; if (isStatic(modifiers)) { registerTypeConverter(registry, method, toType, fromType, new StaticMethodTypeConverter(method, allowNull)); } else { if (injector == null) { injector = new CachingInjector<Object>(registry, CastUtils.cast(type, Object.class)); } registerTypeConverter(registry, method, toType, fromType, new InstanceMethodTypeConverter(injector, method, registry, allowNull)); } } } } else { LOG.warn("Ignoring bad converter on type: " + type.getCanonicalName() + " method: " + method + " as a converter method should have one parameter"); } return injector; }
private CachingInjector<?> handleHasFallbackConverterAnnotation(TypeConverterRegistry registry, Class<?> type, CachingInjector<?> injector, Method method, boolean allowNull) { if (isValidFallbackConverterMethod(method)) { int modifiers = method.getModifiers(); if (isAbstract(modifiers) || !isPublic(modifiers)) { LOG.warn("Ignoring bad fallback converter on type: " + type.getCanonicalName() + " method: " + method + " as a fallback converter method is not a public and concrete method"); } else { Class<?> toType = method.getReturnType(); if (toType.equals(Void.class)) { LOG.warn("Ignoring bad fallback converter on type: " + type.getCanonicalName() + " method: " + method + " as a fallback converter method returns a void method"); } else { if (isStatic(modifiers)) { registerFallbackTypeConverter(registry, new StaticMethodFallbackTypeConverter(method, registry, allowNull), method); } else { if (injector == null) { injector = new CachingInjector<Object>(registry, CastUtils.cast(type, Object.class)); } registerFallbackTypeConverter(registry, new InstanceMethodFallbackTypeConverter(injector, method, registry, allowNull), method); } } } } else { LOG.warn("Ignoring bad fallback converter on type: " + type.getCanonicalName() + " method: " + method + " as a fallback converter method should have one parameter"); } return injector; }
protected void registerFallbackTypeConverter(TypeConverterRegistry registry, TypeConverter typeConverter, Method method) { boolean canPromote = false; // check whether the annotation may indicate it can promote if (method.getAnnotation(FallbackConverter.class) != null) { canPromote = method.getAnnotation(FallbackConverter.class).canPromote(); } registry.addFallbackTypeConverter(typeConverter, canPromote); }
public InstanceMethodFallbackTypeConverter(CachingInjector<?> injector, Method method, TypeConverterRegistry registry, boolean allowNull) { this.injector = injector; this.method = method; this.useExchange = method.getParameterTypes().length == 4; this.registry = registry; this.allowNull = allowNull; }
public synchronized void load(TypeConverterRegistry registry) throws TypeConverterLoaderException { // must be synchronized to ensure we don't load type converters concurrently // which cause Camel apps to fails in OSGi thereafter try { loader.load(registry); } catch (Exception e) { throw new TypeConverterLoaderException("Cannot load type converters using OSGi bundle: " + bundle.getBundleId(), e); } }
@FallbackConverter public static Object convertTo(Class<?> type, Exchange exchange, Object value, TypeConverterRegistry registry) { // use a fallback type converter so we can convert the embedded body if the value is BeanInvocation if (BeanInvocation.class.isAssignableFrom(value.getClass())) { BeanInvocation bi = (BeanInvocation) value; if (bi.getArgs() == null || bi.getArgs().length != 1) { // not possible to convert at this time as we try to convert the data passed in at first argument return Void.TYPE; } Class<?> from = bi.getArgs()[0].getClass(); Object body = bi.getArgs()[0]; // maybe from is already the type we want if (type.isAssignableFrom(from)) { return body; } // no then try to lookup a type converter TypeConverter tc = registry.lookup(type, from); if (tc != null) { return tc.convertTo(type, exchange, body); } } return null; }
@FallbackConverter public Object convertTo(Class<?> type, Exchange exchange, Object value, TypeConverterRegistry registry) { if (Currency.class.isAssignableFrom(value.getClass())) { return "Money talks says " + camelContext.getName(); } return null; }
@FallbackConverter(canPromote = true) public Object convertTo(Class<?> type, Exchange exchange, Object value, TypeConverterRegistry registry) { if (MyCoolBean.class.isAssignableFrom(value.getClass())) { return "This is cool: " + value.toString(); } return null; }
@FallbackConverter public static Object convertTo(Class<?> type, Exchange exchange, Object value, TypeConverterRegistry registry) { if (TimeZone.class.isAssignableFrom(value.getClass())) { return "Time talks"; } return null; }
public void testTypeConverterRegistry() throws Exception { getMockEndpoint("mock:a").expectedMessageCount(2); template.sendBody("direct:start", "3"); template.sendBody("direct:start", "7"); assertMockEndpointsSatisfied(); TypeConverterRegistry reg = context.getTypeConverterRegistry(); assertTrue("Should be enabled", reg.getStatistics().isStatisticsEnabled()); Long failed = reg.getStatistics().getFailedCounter(); assertEquals(0, failed.intValue()); Long miss = reg.getStatistics().getMissCounter(); assertEquals(0, miss.intValue()); try { template.sendBody("direct:start", "foo"); fail("Should have thrown exception"); } catch (Exception e) { // expected } // should now have a failed failed = reg.getStatistics().getFailedCounter(); assertEquals(1, failed.intValue()); miss = reg.getStatistics().getMissCounter(); assertEquals(0, miss.intValue()); // reset reg.getStatistics().reset(); failed = reg.getStatistics().getFailedCounter(); assertEquals(0, failed.intValue()); miss = reg.getStatistics().getMissCounter(); assertEquals(0, miss.intValue()); }
private static <T, V> CxfPayload<T> convertVia(Class<V> via, Exchange exchange, Object value, TypeConverterRegistry registry) { TypeConverter tc = registry.lookup(via, value.getClass()); if (tc != null) { TypeConverter tc1 = registry.lookup(Document.class, via); if (tc1 != null) { V is = tc.convertTo(via, exchange, value); Document document = tc1.convertTo(Document.class, exchange, is); return documentToCxfPayload(document, exchange); } } return null; }
@Test public void testTypeConverterRegistry() throws Exception { getMockEndpoint("mock:a").expectedMessageCount(2); template.sendBody("direct:start", "3"); template.sendBody("direct:start", "7"); assertMockEndpointsSatisfied(); TypeConverterRegistry reg = context.getTypeConverterRegistry(); assertTrue("Should be enabled", reg.getStatistics().isStatisticsEnabled()); Long failed = reg.getStatistics().getFailedCounter(); assertEquals(0, failed.intValue()); Long miss = reg.getStatistics().getMissCounter(); assertEquals(0, miss.intValue()); try { template.sendBody("direct:start", "foo"); fail("Should have thrown exception"); } catch (Exception e) { // expected } // should now have a failed failed = reg.getStatistics().getFailedCounter(); assertEquals(1, failed.intValue()); miss = reg.getStatistics().getMissCounter(); assertEquals(0, miss.intValue()); // reset reg.getStatistics().reset(); failed = reg.getStatistics().getFailedCounter(); assertEquals(0, failed.intValue()); miss = reg.getStatistics().getMissCounter(); assertEquals(0, miss.intValue()); }
@FallbackConverter public <T> T convertTo(Class<T> type, Exchange exchange, Object value, TypeConverterRegistry registry) { // only do this if enabled if (!init && exchange != null) { // init to see if this is enabled String text = exchange.getContext().getProperties().get(JacksonXMLConstants.ENABLE_XML_TYPE_CONVERTER); enabled = "true".equalsIgnoreCase(text); init = true; } if (enabled == null || !enabled) { return null; } if (isNotPojoType(type)) { return null; } if (exchange != null && value instanceof Map) { ObjectMapper mapper = resolveObjectMapper(exchange.getContext().getRegistry()); if (mapper.canSerialize(type)) { return mapper.convertValue(value, type); } } // Just return null to let other fallback converter to do the job return null; }
protected void registerClassMaps(TypeConverterRegistry registry, String dozerId, DozerBeanMapper dozer, List<ClassMap> all) { DozerTypeConverter converter = new DozerTypeConverter(dozer); for (ClassMap map : all) { addDozerTypeConverter(registry, converter, dozerId, map.getSrcClassToMap(), map.getDestClassToMap()); // if not one way then add the other way around also if (map.getType() != ONE_WAY) { addDozerTypeConverter(registry, converter, dozerId, map.getDestClassToMap(), map.getSrcClassToMap()); } } }
protected void addDozerTypeConverter(TypeConverterRegistry registry, DozerTypeConverter converter, String dozerId, Class<?> to, Class<?> from) { if (log.isInfoEnabled()) { if (dozerId != null) { log.info("Added Dozer: {} as Camel type converter: {} -> {}", new Object[]{dozerId, from, to}); } else { log.info("Added Dozer as Camel type converter: {} -> {}", new Object[]{from, to}); } } registry.addTypeConverter(from, to, converter); }
/** * Registers Dozer <code>BeanMappingBuilder</code> in current mapper instance. * This method should be called instead of direct <code>mapper.addMapping()</code> invocation for Camel * being able to register given type conversion. * * @param beanMappingBuilder api-based mapping builder */ public void addMapping(BeanMappingBuilder beanMappingBuilder) { if (mapper == null) { log.warn("No mapper instance provided to " + this.getClass().getSimpleName() + ". Mapping has not been registered!"); return; } mapper.addMapping(beanMappingBuilder); MappingFileData mappingFileData = beanMappingBuilder.build(); TypeConverterRegistry registry = camelContext.getTypeConverterRegistry(); List<ClassMap> classMaps = new ArrayList<ClassMap>(); classMaps.addAll(mappingFileData.getClassMaps()); registerClassMaps(registry, null, mapper, classMaps); }
public ManagedTypeConverterRegistry(CamelContext context, TypeConverterRegistry registry) { super(context, registry); this.registry = registry; }
public TypeConverterRegistry getRegistry() { return registry; }
@Deprecated public InstanceMethodTypeConverter(CachingInjector<?> injector, Method method, TypeConverterRegistry registry) { this(injector, method, registry, false); }
@Override public void load(TypeConverterRegistry registry) throws TypeConverterLoaderException { String[] packageNames; LOG.trace("Searching for {} services", META_INF_SERVICES); try { packageNames = findPackageNames(); if (packageNames == null || packageNames.length == 0) { throw new TypeConverterLoaderException("Cannot find package names to be used for classpath scanning for annotated type converters."); } } catch (Exception e) { throw new TypeConverterLoaderException("Cannot find package names to be used for classpath scanning for annotated type converters.", e); } // if we only have camel-core on the classpath then we have already pre-loaded all its type converters // but we exposed the "org.apache.camel.core" package in camel-core. This ensures there is at least one // packageName to scan, which triggers the scanning process. That allows us to ensure that we look for // META-INF/services in all the JARs. if (packageNames.length == 1 && "org.apache.camel.core".equals(packageNames[0])) { LOG.debug("No additional package names found in classpath for annotated type converters."); // no additional package names found to load type converters so break out return; } // now filter out org.apache.camel.core as its not needed anymore (it was just a dummy) packageNames = filterUnwantedPackage("org.apache.camel.core", packageNames); // filter out package names which can be loaded as a class directly so we avoid package scanning which // is much slower and does not work 100% in all runtime containers Set<Class<?>> classes = new HashSet<Class<?>>(); packageNames = filterPackageNamesOnly(resolver, packageNames, classes); if (!classes.isEmpty()) { LOG.debug("Loaded " + classes.size() + " @Converter classes"); } // if there is any packages to scan and load @Converter classes, then do it if (packageNames != null && packageNames.length > 0) { LOG.trace("Found converter packages to scan: {}", packageNames); Set<Class<?>> scannedClasses = resolver.findAnnotated(Converter.class, packageNames); if (scannedClasses.isEmpty()) { throw new TypeConverterLoaderException("Cannot find any type converter classes from the following packages: " + Arrays.asList(packageNames)); } LOG.debug("Found " + packageNames.length + " packages with " + scannedClasses.size() + " @Converter classes to load"); classes.addAll(scannedClasses); } // load all the found classes into the type converter registry for (Class<?> type : classes) { if (LOG.isTraceEnabled()) { LOG.trace("Loading converter class: {}", ObjectHelper.name(type)); } loadConverterMethods(registry, type); } // now clear the maps so we do not hold references visitedClasses.clear(); visitedURIs.clear(); }
protected void registerTypeConverter(TypeConverterRegistry registry, Method method, Class<?> toType, Class<?> fromType, TypeConverter typeConverter) { registry.addTypeConverter(toType, fromType, typeConverter); }
protected boolean isValidFallbackConverterMethod(Method method) { Class<?>[] parameterTypes = method.getParameterTypes(); return (parameterTypes != null) && (parameterTypes.length == 3 || (parameterTypes.length == 4 && Exchange.class.isAssignableFrom(parameterTypes[1])) && (TypeConverterRegistry.class.isAssignableFrom(parameterTypes[parameterTypes.length - 1]))); }
public CachingInjector(TypeConverterRegistry repository, Class<T> type) { this.repository = repository; this.type = type; }
@Deprecated public InstanceMethodFallbackTypeConverter(CachingInjector<?> injector, Method method, TypeConverterRegistry registry) { this(injector, method, registry, false); }
@Deprecated public StaticMethodFallbackTypeConverter(Method method, TypeConverterRegistry registry) { this(method, registry, false); }