@SuppressWarnings("unchecked") private Set<Method> convertToMethodSet(Object value, TypeConverter typeConverter) { if (value instanceof Set) { return (Set<Method>) value; } Set<Method> set = new LinkedHashSet<>(); Iterator it = ObjectHelper.createIterator(value); while (it.hasNext()) { Object next = it.next(); String text = typeConverter.tryConvertTo(String.class, next); if (text != null) { Method method = Method.valueOf(text.trim()); // creates new instance only if no matching instance exists set.add(method); } } return set; }
private void doRun(final Exchange exchange, final AsyncCallback callback, IgniteCompute compute) throws Exception { Object job = exchange.getIn().getBody(); if (Collection.class.isAssignableFrom(job.getClass())) { Collection<?> col = (Collection<?>) job; TypeConverter tc = exchange.getContext().getTypeConverter(); Collection<IgniteRunnable> runnables = new ArrayList<>(col.size()); for (Object o : col) { runnables.add(tc.mandatoryConvertTo(IgniteRunnable.class, o)); } compute.run(runnables); } else if (IgniteRunnable.class.isAssignableFrom(job.getClass())) { compute.run((IgniteRunnable) job); } else { throw new RuntimeCamelException(String.format( "Ignite Compute endpoint with RUN executionType is only " + "supported for IgniteRunnable payloads, or collections of them. The payload type was: %s.", job.getClass().getName())); } }
private static Object convert(TypeConverter typeConverter, Class<?> type, Object value) throws URISyntaxException, NoTypeConversionAvailableException { if (typeConverter != null) { return typeConverter.mandatoryConvertTo(type, value); } if (type == URI.class) { return new URI(value.toString()); } PropertyEditor editor = PropertyEditorManager.findEditor(type); if (editor != null) { // property editor is not thread safe, so we need to lock Object answer; synchronized (LOCK) { editor.setAsText(value.toString()); answer = editor.getValue(); } return answer; } return null; }
@SuppressWarnings({ "unchecked", "rawtypes" }) private void doCall(final Exchange exchange, final AsyncCallback callback, IgniteCompute compute) throws Exception { Object job = exchange.getIn().getBody(); IgniteReducer<Object, Object> reducer = exchange.getIn().getHeader(IgniteConstants.IGNITE_COMPUTE_REDUCER, IgniteReducer.class); if (Collection.class.isAssignableFrom(job.getClass())) { Collection<?> col = (Collection<?>) job; TypeConverter tc = exchange.getContext().getTypeConverter(); Collection<IgniteCallable<?>> callables = new ArrayList<>(col.size()); for (Object o : col) { callables.add(tc.mandatoryConvertTo(IgniteCallable.class, o)); } if (reducer != null) { compute.call((Collection) callables, reducer); } else { compute.call((Collection) callables); } } else if (IgniteCallable.class.isAssignableFrom(job.getClass())) { compute.call((IgniteCallable<Object>) job); } else { throw new RuntimeCamelException(String.format( "Ignite Compute endpoint with CALL executionType is only " + "supported for IgniteCallable payloads, or collections of them. The payload type was: %s.", job.getClass().getName())); } }
@Override public void addFallbackTypeConverter(TypeConverter typeConverter, boolean canPromote) { log.trace("Adding fallback type converter: {} which can promote: {}", typeConverter, canPromote); // add in top of fallback as the toString() fallback will nearly always be able to convert // the last one which is add to the FallbackTypeConverter will be called at the first place fallbackConverters.add(0, new FallbackTypeConverter(typeConverter, canPromote)); if (typeConverter instanceof TypeConverterAware) { TypeConverterAware typeConverterAware = (TypeConverterAware) typeConverter; typeConverterAware.setTypeConverter(this); } if (typeConverter instanceof CamelContextAware) { CamelContextAware camelContextAware = (CamelContextAware) typeConverter; if (camelContext != null) { camelContextAware.setCamelContext(camelContext); } } }
public TypeConverter getTypeConverter() { if (typeConverter == null) { synchronized (this) { // we can synchronize on this as there is only one instance // of the camel context (its the container) typeConverter = createTypeConverter(); try { // must add service eager and force start it addService(typeConverter, true, true); } catch (Exception e) { throw ObjectHelper.wrapRuntimeCamelException(e); } } } return typeConverter; }
public <T> T getMandatoryBody(Class<T> type) throws InvalidPayloadException { // eager same instance type test to avoid the overhead of invoking the type converter // if already same type if (type.isInstance(body)) { return type.cast(body); } Exchange e = getExchange(); if (e != null) { TypeConverter converter = e.getContext().getTypeConverter(); try { return converter.mandatoryConvertTo(type, e, getBody()); } catch (Exception cause) { throw new InvalidPayloadException(e, type, this, cause); } } throw new InvalidPayloadException(e, type, this); }
public void testFallbackPromote() throws Exception { MyCoolBean cool = new MyCoolBean(); cool.setCool("Camel rocks"); TypeConverter tc = context.getTypeConverterRegistry().lookup(String.class, MyCoolBean.class); assertNull("No regular type converters", tc); String s = context.getTypeConverter().convertTo(String.class, cool); assertEquals("This is cool: Camel rocks", s); cool.setCool("It works"); s = context.getTypeConverter().convertTo(String.class, cool); assertEquals("This is cool: It works", s); tc = context.getTypeConverterRegistry().lookup(String.class, MyCoolBean.class); assertNotNull("Should have been promoted", tc); }
@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; }
private static long extractOffset(String now, TypeConverter typeConverter) throws NoTypeConversionAvailableException { Matcher matcher = NOW_PATTERN.matcher(now); if (matcher.matches()) { String op = matcher.group(1); String remainder = matcher.group(2); // convert remainder to a time millis (eg we have a String -> long converter that supports // syntax with hours, days, minutes: eg 5h30m for 5 hours and 30 minutes). long offset = typeConverter.mandatoryConvertTo(long.class, remainder); if ("+".equals(op)) { return offset; } else { return -1 * offset; } } return 0; }
@Override public Writable create(Object value, TypeConverter typeConverter, Holder<Integer> size) { InputStream is = null; try { is = typeConverter.convertTo(InputStream.class, value); ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOUtils.copyBytes(is, bos, HdfsConstants.DEFAULT_BUFFERSIZE, false); BytesWritable writable = new BytesWritable(); writable.set(bos.toByteArray(), 0, bos.toByteArray().length); size.value = bos.toByteArray().length; return writable; } catch (IOException ex) { throw new RuntimeCamelException(ex); } finally { IOHelper.close(is); } }
@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; }
@Test public void testFallbackConverterWithoutObjectFactory() throws Exception { TypeConverter converter = context.getTypeConverter(); Foo foo = converter.convertTo(Foo.class, "<foo><zot name=\"bar1\" value=\"value\" otherValue=\"otherValue\"/></foo>"); assertNotNull("foo should not be null", foo); assertEquals("value", foo.getBarRefs().get(0).getValue()); foo.getBarRefs().clear(); Bar bar = new Bar(); bar.setName("myName"); bar.setValue("myValue"); foo.getBarRefs().add(bar); Exchange exchange = new DefaultExchange(context); exchange.setProperty(Exchange.CHARSET_NAME, "UTF-8"); String value = converter.convertTo(String.class, exchange, foo); assertTrue("Should get a right marshalled string", value.indexOf("<bar name=\"myName\" value=\"myValue\"/>") > 0); }
@Test public void testConverter() throws Exception { TypeConverter converter = context.getTypeConverter(); PersonType person = converter.convertTo(PersonType.class, "<Person><firstName>FOO</firstName><lastName>BAR</lastName></Person>"); assertNotNull("Person should not be null ", person); assertEquals("Get the wrong first name ", "FOO", person.getFirstName()); assertEquals("Get the wrong second name ", "BAR", person.getLastName()); Exchange exchange = new DefaultExchange(context); exchange.setProperty(Exchange.CHARSET_NAME, "UTF-8"); String value = converter.convertTo(String.class, exchange, person); assertTrue("Should get a right marshalled string", value.indexOf("<lastName>BAR</lastName>") > 0); byte[] buffers = "<Person><firstName>FOO</firstName><lastName>BAR\u0008</lastName></Person>".getBytes("UTF-8"); InputStream is = new ByteArrayInputStream(buffers); try { converter.convertTo(PersonType.class, exchange, is); fail("Should have thrown exception"); } catch (TypeConversionException e) { // expected } }
@Test public void testFilteringConverter() throws Exception { byte[] buffers = "<Person><firstName>FOO</firstName><lastName>BAR\u0008</lastName></Person>".getBytes("UTF-8"); InputStream is = new ByteArrayInputStream(buffers); Exchange exchange = new DefaultExchange(context); exchange.setProperty(Exchange.CHARSET_NAME, "UTF-8"); exchange.setProperty(Exchange.FILTER_NON_XML_CHARS, true); TypeConverter converter = context.getTypeConverter(); PersonType person = converter.convertTo(PersonType.class, exchange, is); assertNotNull("Person should not be null ", person); assertEquals("Get the wrong first name ", "FOO", person.getFirstName()); assertEquals("Get the wrong second name ", "BAR ", person.getLastName()); person.setLastName("BAR\u0008\uD8FF"); String value = converter.convertTo(String.class, exchange, person); assertTrue("Didn't filter the non-xml chars", value.indexOf("<lastName>BAR </lastName>") > 0); exchange.setProperty(Exchange.FILTER_NON_XML_CHARS, false); value = converter.convertTo(String.class, exchange, person); assertTrue("Should not filter the non-xml chars", value.indexOf("<lastName>BAR\uD8FF</lastName>") > 0); }
private void camelFactoryProducers(@Observes ProcessAnnotatedType<CdiCamelFactory> pat, BeanManager manager) { pat.setAnnotatedType( new AnnotatedTypeDelegate<>( pat.getAnnotatedType(), pat.getAnnotatedType().getMethods().stream() .filter(am -> am.isAnnotationPresent(Produces.class)) .filter(am -> am.getTypeClosure().stream().noneMatch(isEqual(TypeConverter.class))) .peek(am -> producerQualifiers.put(am.getJavaMember(), getQualifiers(am, manager))) .map(am -> new AnnotatedMethodDelegate<>(am, am.getAnnotations().stream() .filter(annotation -> !manager.isQualifier(annotation.annotationType())) .collect(collectingAndThen(toSet(), annotations -> { annotations.add(EXCLUDED); return annotations; })))) .collect(toSet()))); }
@Override public Optional<ProcessorDefinition> handle(Function step, ProcessorDefinition route, SyndesisRouteBuilder routeBuilder) { final CamelContext context = routeBuilder.getContext(); final TypeConverter converter = context.getTypeConverter(); String method = null; String function = step.getName(); String options = null; if (ObjectHelper.isEmpty(function)) { return Optional.empty(); } int idx = function.indexOf("::"); if (idx > 0 && !function.endsWith("::")) { method = function.substring(idx + 2); function = function.substring(0, idx); } Map<String, Object> headers = step.getProperties(); if (ObjectHelper.isNotEmpty(headers)) { options = headers.entrySet().stream() .filter(entry -> Objects.nonNull(entry.getValue())) .map(entry -> asBeanParameter(converter, entry)) .collect(Collectors.joining("&")); } String uri = "class:" + function; if (method != null) { uri += "?method=" + method; if (options != null){ uri += "&" + options; } } else if (options != null){ uri += "?" + options; } return Optional.of(route.to(uri)); }
private String asBeanParameter(TypeConverter converter, Map.Entry<String, Object> entry) { try { return "bean." + entry.getKey() + "=" + converter.mandatoryConvertTo(String.class, entry.getValue()); } catch (NoTypeConversionAvailableException e) { throw new IllegalStateException(e); } }
private <T> void consumeOption(String name, Class<T> type, Consumer<T> consumer) throws NoTypeConversionAvailableException { final TypeConverter converter = getCamelContext().getTypeConverter(); final Object val = getOptions().get(name); final T result = converter.mandatoryConvertTo(type, val); consumer.accept(result); LOGGER.debug("Consume option {}", name); getOptions().remove(name); }
/** * Gather all options to use when building the delegate uri. */ private Map<String, String> buildEndpointOptions(String remaining, Map<String, Object> parameters) throws URISyntaxException, NoTypeConversionAvailableException { final TypeConverter converter = getCamelContext().getTypeConverter(); final Map<String, String> endpointOptions = new LinkedHashMap<>(); // Extract options from options that are supposed to be set at the endpoint // level, those options can be overridden and extended using by the query // parameters. Collection<String> endpointProperties = definition.getEndpointProperties().keySet(); for (String key : endpointProperties) { Object val = this.options.get(key); if (val != null) { doAddOption(endpointOptions, key, converter.mandatoryConvertTo(String.class, val)); } } // options from query parameters for (Map.Entry<String, Object> entry : parameters.entrySet()) { if (entry.getValue() != null) { doAddOption(endpointOptions, entry.getKey(), converter.mandatoryConvertTo(String.class, entry.getValue())); } } // add extra options from remaining (context-path) if (remaining != null) { String targetUri = componentScheme + ":" + remaining; Map<String, String> extra = catalog.endpointProperties(targetUri); if (extra != null && !extra.isEmpty()) { extra.forEach((key, value) -> doAddOption(endpointOptions, key, value)); } } return endpointOptions; }
@Override public ProcessorDefinition handle(Function step, ProcessorDefinition route, SyndesisRouteBuilder routeBuilder) { final CamelContext context = routeBuilder.getContext(); final TypeConverter converter = context.getTypeConverter(); String method = null; String function = step.getName(); String options = null; if (ObjectHelper.isEmpty(function)) { return route; } int idx = function.indexOf("::"); if (idx > 0 && !function.endsWith("::")) { method = function.substring(idx + 2); function = function.substring(0, idx); } Map<String, Object> headers = step.getProperties(); if (ObjectHelper.isNotEmpty(headers)) { options = headers.entrySet().stream() .map(entry -> asBeanParameter(converter, entry)) .collect(Collectors.joining("&")); } String uri = "class:" + function; if (method != null) { uri += "?method=" + method; if (options != null){ uri += "&" + options; } } else if (options != null){ uri += "?" + options; } return route.to(uri); }
/** * A helper method for comparing objects for equality in which it uses type coercion to coerce * types between the left and right values. This allows you test for equality for example with * a String and Integer type as Camel will be able to coerce the types. */ public static boolean typeCoerceEquals(TypeConverter converter, Object leftValue, Object rightValue, boolean ignoreCase) { // sanity check if (leftValue == null && rightValue == null) { // they are equal return true; } else if (leftValue == null || rightValue == null) { // only one of them is null so they are not equal return false; } // try without type coerce boolean answer = equal(leftValue, rightValue, ignoreCase); if (answer) { return true; } // are they same type, if so return false as the equals returned false if (leftValue.getClass().isInstance(rightValue)) { return false; } // convert left to right Object value = converter.tryConvertTo(rightValue.getClass(), leftValue); answer = equal(value, rightValue, ignoreCase); if (answer) { return true; } // convert right to left value = converter.tryConvertTo(leftValue.getClass(), rightValue); answer = equal(leftValue, value, ignoreCase); return answer; }
public static boolean setProperties(CamelContext context, TypeConverter typeConverter, Object target, Map<String, Object> properties) throws Exception { ObjectHelper.notNull(target, "target"); ObjectHelper.notNull(properties, "properties"); boolean rc = false; for (Iterator<Map.Entry<String, Object>> iter = properties.entrySet().iterator(); iter.hasNext();) { Map.Entry<String, Object> entry = iter.next(); if (setProperty(context, typeConverter, target, entry.getKey(), entry.getValue())) { iter.remove(); rc = true; } } return rc; }
/** * Converts the value to the given expected type or throws an exception * * @return the converted value * @throws TypeConversionException is thrown if error during type conversion * @throws NoTypeConversionAvailableException} if no type converters exists to convert to the given type */ public static <T> T convertToMandatoryType(Exchange exchange, Class<T> type, Object value) throws TypeConversionException, NoTypeConversionAvailableException { CamelContext camelContext = exchange.getContext(); ObjectHelper.notNull(camelContext, "CamelContext of Exchange"); TypeConverter converter = camelContext.getTypeConverter(); if (converter != null) { return converter.mandatoryConvertTo(type, exchange, value); } throw new NoTypeConversionAvailableException(value, type); }
/** * Converts the value to the given expected type * * @return the converted value * @throws org.apache.camel.TypeConversionException is thrown if error during type conversion */ public static <T> T convertToType(Exchange exchange, Class<T> type, Object value) throws TypeConversionException { CamelContext camelContext = exchange.getContext(); ObjectHelper.notNull(camelContext, "CamelContext of Exchange"); TypeConverter converter = camelContext.getTypeConverter(); if (converter != null) { return converter.convertTo(type, exchange, value); } return null; }
public Map<Class<?>, TypeConverter> getToClassMappings(Class<?> fromClass) { Map<Class<?>, TypeConverter> answer = new HashMap<Class<?>, TypeConverter>(); for (Map.Entry<TypeMapping, TypeConverter> entry : typeMappings.entrySet()) { TypeMapping mapping = entry.getKey(); if (mapping.isApplicable(fromClass)) { answer.put(mapping.getToType(), entry.getValue()); } } return answer; }
protected <T> TypeConverter getOrFindTypeConverter(TypeMapping key) { TypeConverter converter = typeMappings.get(key); if (converter == null) { // converter not found, try to lookup then converter = lookup(key.getToType(), key.getFromType()); if (converter != null) { typeMappings.putIfAbsent(key, converter); } } return converter; }
public void testConvert() throws Exception { TypeConverter converter = context.getTypeConverter(); Integer value = converter.convertTo(Integer.class, "1000"); assertNotNull(value); assertEquals("Converted to Integer", new Integer(1000), value); String text = converter.convertTo(String.class, value); assertEquals("Converted to String", "1000", text); }
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); }
@Override public TypeConverter getTypeConverter(Class<?> toType, Class<?> fromType) { TypeConverter answer = super.getTypeConverter(toType, fromType); if (answer == null && !loaded.get()) { // okay we could not convert, so try again, but load the converters up front ensureLoaded(); answer = super.getTypeConverter(toType, fromType); } return answer; }
@Override public Map<Class<?>, TypeConverter> getToClassMappings(Class<?> fromClass) { if (!loaded.get()) { ensureLoaded(); } return super.getToClassMappings(fromClass); }
@Override public Map<TypeMapping, TypeConverter> getTypeMappings() { if (!loaded.get()) { ensureLoaded(); } return super.getTypeMappings(); }
@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; }
public void setTypeConverter(TypeConverter typeConverter) { this.typeConverter = typeConverter; try { // must add service eager and force start it addService(typeConverter, true, true); } catch (Exception e) { throw ObjectHelper.wrapRuntimeCamelException(e); } }
/** * Lazily create a default implementation */ protected TypeConverter createTypeConverter() { BaseTypeConverterRegistry answer; if (isLazyLoadTypeConverters()) { answer = new LazyLoadingTypeConverter(packageScanClassResolver, getInjector(), getDefaultFactoryFinder()); } else { answer = new DefaultTypeConverter(packageScanClassResolver, getInjector(), getDefaultFactoryFinder()); } answer.setCamelContext(this); setTypeConverterRegistry(answer); return answer; }