Search in sources :

Example 1 with TypeConversionException

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

the class ConvertingPublisher method subscribe.

@Override
public void subscribe(Subscriber<? super R> subscriber) {
    delegate.subscribe(new Subscriber<Exchange>() {

        private AtomicBoolean active = new AtomicBoolean(true);

        private Subscription subscription;

        @Override
        public void onSubscribe(Subscription newSubscription) {
            if (newSubscription == null) {
                throw new NullPointerException("subscription is null");
            } else if (newSubscription == this.subscription) {
                throw new IllegalArgumentException("already subscribed to the subscription: " + newSubscription);
            }
            if (this.subscription != null) {
                newSubscription.cancel();
            } else {
                this.subscription = newSubscription;
                subscriber.onSubscribe(newSubscription);
            }
        }

        @Override
        public void onNext(Exchange ex) {
            if (!active.get()) {
                return;
            }
            R r;
            try {
                if (ex.hasOut()) {
                    r = ex.getOut().getBody(type);
                } else {
                    r = ex.getIn().getBody(type);
                }
            } catch (TypeConversionException e) {
                LOG.warn("Unable to convert body to the specified type: " + type.getName(), e);
                r = null;
            }
            if (r == null && ex.getIn().getBody() != null) {
                this.onError(new ClassCastException("Unable to convert body to the specified type: " + type.getName()));
                active.set(false);
                subscription.cancel();
            } else {
                subscriber.onNext(r);
            }
        }

        @Override
        public void onError(Throwable throwable) {
            if (!active.get()) {
                return;
            }
            subscriber.onError(throwable);
        }

        @Override
        public void onComplete() {
            if (!active.get()) {
                return;
            }
            subscriber.onComplete();
        }
    });
}
Also used : Exchange(org.apache.camel.Exchange) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) TypeConversionException(org.apache.camel.TypeConversionException) Subscription(org.reactivestreams.Subscription)

Example 2 with TypeConversionException

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

the class SpringTypeConverter method convertTo.

@Override
public <T> T convertTo(Class<T> type, Exchange exchange, Object value) throws TypeConversionException {
    // do not attempt to convert Camel types
    if (type.getCanonicalName().startsWith("org.apache")) {
        return null;
    }
    // do not attempt to convert List -> Map. Ognl expression may use this converter as a fallback expecting null
    if (type.isAssignableFrom(Map.class) && (value.getClass().isArray() || value instanceof Collection)) {
        return null;
    }
    TypeDescriptor sourceType = types.computeIfAbsent(value.getClass(), TypeDescriptor::valueOf);
    TypeDescriptor targetType = types.computeIfAbsent(type, TypeDescriptor::valueOf);
    for (ConversionService conversionService : conversionServices) {
        if (conversionService.canConvert(sourceType, targetType)) {
            try {
                return (T) conversionService.convert(value, sourceType, targetType);
            } catch (ConversionFailedException e) {
                //
                if (e.getCause() instanceof ConverterNotFoundException && isArrayOrCollection(value)) {
                    return null;
                } else {
                    throw new TypeConversionException(value, type, e);
                }
            }
        }
    }
    return null;
}
Also used : TypeDescriptor(org.springframework.core.convert.TypeDescriptor) ConversionFailedException(org.springframework.core.convert.ConversionFailedException) TypeConversionException(org.apache.camel.TypeConversionException) ConversionService(org.springframework.core.convert.ConversionService) ConverterNotFoundException(org.springframework.core.convert.ConverterNotFoundException) Collection(java.util.Collection) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap)

Example 3 with TypeConversionException

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

the class JAXBConvertTest method testStreamShouldBeClosedEvenForException.

@Test
public void testStreamShouldBeClosedEvenForException() throws Exception {
    String data = "<errorOrder name='foo' amount='123.45' price='2.22'/>";
    InputStream is = new ByteArrayInputStream(data.getBytes());
    try {
        converter.convertTo(PurchaseOrder.class, is);
        fail("Should have thrown exception");
    } catch (TypeConversionException e) {
    // expected
    }
    assertEquals(-1, is.read());
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) TypeConversionException(org.apache.camel.TypeConversionException) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Test(org.junit.Test)

Example 4 with TypeConversionException

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

the class HttpDisableStreamCacheTest method httpDisableStreamCache.

@Test
public void httpDisableStreamCache() throws Exception {
    Exchange exchange = template.request("http4://" + localServer.getInetAddress().getHostName() + ":" + localServer.getLocalPort() + "/test/?disableStreamCache=true", new Processor() {

        public void process(Exchange exchange) throws Exception {
        }
    });
    InputStream is = assertIsInstanceOf(InputStream.class, exchange.getOut().getBody());
    assertNotNull(is);
    String name = is.getClass().getName();
    // should not be stream cache
    assertFalse(name.contains("CachedOutputStream"));
    // should be closed by http client
    try {
        assertEquals("camel rocks!", context.getTypeConverter().convertTo(String.class, exchange, is));
        fail("Should fail");
    } catch (TypeConversionException e) {
    // expected
    }
}
Also used : Exchange(org.apache.camel.Exchange) Processor(org.apache.camel.Processor) TypeConversionException(org.apache.camel.TypeConversionException) InputStream(java.io.InputStream) TypeConversionException(org.apache.camel.TypeConversionException) Test(org.junit.Test)

Example 5 with TypeConversionException

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

the class ModelHelper method dumpModelAsXml.

/**
     * Dumps the definition as XML
     *
     * @param context    the CamelContext, if <tt>null</tt> then {@link org.apache.camel.spi.ModelJAXBContextFactory} is not in use
     * @param definition the definition, such as a {@link org.apache.camel.NamedNode}
     * @return the output in XML (is formatted)
     * @throws JAXBException is throw if error marshalling to XML
     */
public static String dumpModelAsXml(CamelContext context, NamedNode definition) throws JAXBException {
    JAXBContext jaxbContext = getJAXBContext(context);
    final Map<String, String> namespaces = new LinkedHashMap<>();
    // gather all namespaces from the routes or route which is stored on the expression nodes
    if (definition instanceof RoutesDefinition) {
        List<RouteDefinition> routes = ((RoutesDefinition) definition).getRoutes();
        for (RouteDefinition route : routes) {
            extractNamespaces(route, namespaces);
        }
    } else if (definition instanceof RouteDefinition) {
        RouteDefinition route = (RouteDefinition) definition;
        extractNamespaces(route, namespaces);
    }
    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    StringWriter buffer = new StringWriter();
    marshaller.marshal(definition, buffer);
    XmlConverter xmlConverter = newXmlConverter(context);
    String xml = buffer.toString();
    Document dom;
    try {
        dom = xmlConverter.toDOMDocument(xml, null);
    } catch (Exception e) {
        throw new TypeConversionException(xml, Document.class, e);
    }
    // Add additional namespaces to the document root element
    Element documentElement = dom.getDocumentElement();
    for (String nsPrefix : namespaces.keySet()) {
        String prefix = nsPrefix.equals("xmlns") ? nsPrefix : "xmlns:" + nsPrefix;
        documentElement.setAttribute(prefix, namespaces.get(nsPrefix));
    }
    // We invoke the type converter directly because we need to pass some custom XML output options
    Properties outputProperties = new Properties();
    outputProperties.put(OutputKeys.INDENT, "yes");
    outputProperties.put(OutputKeys.STANDALONE, "yes");
    try {
        return xmlConverter.toStringFromDocument(dom, outputProperties);
    } catch (TransformerException e) {
        throw new IllegalStateException("Failed converting document object to string", e);
    }
}
Also used : Marshaller(javax.xml.bind.Marshaller) TypeConversionException(org.apache.camel.TypeConversionException) Element(org.w3c.dom.Element) JAXBContext(javax.xml.bind.JAXBContext) Document(org.w3c.dom.Document) Properties(java.util.Properties) TransformerException(javax.xml.transform.TransformerException) JAXBException(javax.xml.bind.JAXBException) TypeConversionException(org.apache.camel.TypeConversionException) LinkedHashMap(java.util.LinkedHashMap) XmlConverter(org.apache.camel.converter.jaxp.XmlConverter) StringWriter(java.io.StringWriter) TransformerException(javax.xml.transform.TransformerException)

Aggregations

TypeConversionException (org.apache.camel.TypeConversionException)13 JAXBException (javax.xml.bind.JAXBException)4 Exchange (org.apache.camel.Exchange)4 Test (org.junit.Test)4 InputStream (java.io.InputStream)3 JAXBContext (javax.xml.bind.JAXBContext)3 ByteArrayInputStream (java.io.ByteArrayInputStream)2 StringWriter (java.io.StringWriter)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 LinkedHashMap (java.util.LinkedHashMap)2 Marshaller (javax.xml.bind.Marshaller)2 XMLStreamException (javax.xml.stream.XMLStreamException)2 TransformerException (javax.xml.transform.TransformerException)2 NoTypeConversionAvailableException (org.apache.camel.NoTypeConversionAvailableException)2 Processor (org.apache.camel.Processor)2 TypeConverter (org.apache.camel.TypeConverter)2 XmlConverter (org.apache.camel.converter.jaxp.XmlConverter)2 Document (org.w3c.dom.Document)2 Metacard (ddf.catalog.data.Metacard)1 Writer (java.io.Writer)1