Search in sources :

Example 1 with DataTypeAware

use of org.apache.camel.spi.DataTypeAware in project camel by apache.

the class ContractAdvice method after.

@Override
public void after(Exchange exchange, Object data) throws Exception {
    if (exchange.isFailed()) {
        // TODO can we add FAULT_TYPE processing?
        return;
    }
    Message target = exchange.hasOut() ? exchange.getOut() : exchange.getIn();
    if (!(target instanceof DataTypeAware)) {
        return;
    }
    DataTypeAware typeAwareTarget = (DataTypeAware) target;
    DataType from = typeAwareTarget.getDataType();
    DataType to = contract.getOutputType();
    if (to != null) {
        if (!to.equals(from)) {
            LOG.debug("Looking for transformer for OUTPUT: from='{}', to='{}'", from, to);
            doTransform(target, from, to);
            typeAwareTarget.setDataType(to);
        }
        if (contract.isValidateOutput()) {
            doValidate(target, to);
        }
    }
}
Also used : Message(org.apache.camel.Message) DataTypeAware(org.apache.camel.spi.DataTypeAware) DataType(org.apache.camel.spi.DataType)

Example 2 with DataTypeAware

use of org.apache.camel.spi.DataTypeAware in project camel by apache.

the class RestBindingAdvice method unmarshal.

private void unmarshal(Exchange exchange, Map<String, Object> state) throws Exception {
    boolean isXml = false;
    boolean isJson = false;
    String contentType = ExchangeHelper.getContentType(exchange);
    if (contentType != null) {
        isXml = contentType.toLowerCase(Locale.ENGLISH).contains("xml");
        isJson = contentType.toLowerCase(Locale.ENGLISH).contains("json");
    }
    // that information in the consumes
    if (!isXml && !isJson) {
        isXml = consumes != null && consumes.toLowerCase(Locale.ENGLISH).contains("xml");
        isJson = consumes != null && consumes.toLowerCase(Locale.ENGLISH).contains("json");
    }
    if (exchange.getIn() instanceof DataTypeAware && (isJson || isXml)) {
        ((DataTypeAware) exchange.getIn()).setDataType(new DataType(isJson ? "json" : "xml"));
    }
    // only allow xml/json if the binding mode allows that
    isXml &= bindingMode.equals("auto") || bindingMode.contains("xml");
    isJson &= bindingMode.equals("auto") || bindingMode.contains("json");
    // if we do not yet know if its xml or json, then use the binding mode to know the mode
    if (!isJson && !isXml) {
        isXml = bindingMode.equals("auto") || bindingMode.contains("xml");
        isJson = bindingMode.equals("auto") || bindingMode.contains("json");
    }
    state.put(STATE_KEY_ACCEPT, exchange.getIn().getHeader("Accept", String.class));
    String body = null;
    if (exchange.getIn().getBody() != null) {
        // as they assume a non-empty body
        if (isXml || isJson) {
            // we have binding enabled, so we need to know if there body is empty or not
            // so force reading the body as a String which we can work with
            body = MessageHelper.extractBodyAsString(exchange.getIn());
            if (body != null) {
                if (exchange.getIn() instanceof DataTypeAware) {
                    ((DataTypeAware) exchange.getIn()).setBody(body, new DataType(isJson ? "json" : "xml"));
                } else {
                    exchange.getIn().setBody(body);
                }
                if (isXml && isJson) {
                    // we have still not determined between xml or json, so check the body if its xml based or not
                    isXml = body.startsWith("<");
                    isJson = !isXml;
                }
            }
        }
    }
    // add missing default values which are mapped as headers
    if (queryDefaultValues != null) {
        for (Map.Entry<String, String> entry : queryDefaultValues.entrySet()) {
            if (exchange.getIn().getHeader(entry.getKey()) == null) {
                exchange.getIn().setHeader(entry.getKey(), entry.getValue());
            }
        }
    }
    // favor json over xml
    if (isJson && jsonUnmarshal != null) {
        // add reverse operation
        state.put(STATE_KEY_DO_MARSHAL, STATE_JSON);
        if (ObjectHelper.isNotEmpty(body)) {
            jsonUnmarshal.process(exchange);
            ExchangeHelper.prepareOutToIn(exchange);
        }
        return;
    } else if (isXml && xmlUnmarshal != null) {
        // add reverse operation
        state.put(STATE_KEY_DO_MARSHAL, STATE_XML);
        if (ObjectHelper.isNotEmpty(body)) {
            xmlUnmarshal.process(exchange);
            ExchangeHelper.prepareOutToIn(exchange);
        }
        return;
    }
    // we could not bind
    if ("off".equals(bindingMode) || bindingMode.equals("auto")) {
        // okay for auto we do not mind if we could not bind
        state.put(STATE_KEY_DO_MARSHAL, STATE_JSON);
    } else {
        if (bindingMode.contains("xml")) {
            exchange.setException(new BindingException("Cannot bind to xml as message body is not xml compatible", exchange));
        } else {
            exchange.setException(new BindingException("Cannot bind to json as message body is not json compatible", exchange));
        }
    }
}
Also used : DataTypeAware(org.apache.camel.spi.DataTypeAware) DataType(org.apache.camel.spi.DataType) HashMap(java.util.HashMap) Map(java.util.Map) BindingException(org.apache.camel.processor.binding.BindingException)

Example 3 with DataTypeAware

use of org.apache.camel.spi.DataTypeAware in project camel by apache.

the class TransformerContractTest method testScheme.

@Test
public void testScheme() throws Exception {
    context.addRoutes(new RouteBuilder() {

        @Override
        public void configure() throws Exception {
            transformer().scheme("xml").withDataFormat(new MyDataFormatDefinition());
            from("direct:a").inputType("xml").outputType("xml").to("mock:a").to("direct:b").to("mock:a2");
            from("direct:b").inputType("java").outputType("java").to("mock:b").process(ex -> {
                ex.getIn().setBody(new B());
            });
        }
    });
    context.start();
    MockEndpoint mocka = context.getEndpoint("mock:a", MockEndpoint.class);
    MockEndpoint mocka2 = context.getEndpoint("mock:a2", MockEndpoint.class);
    MockEndpoint mockb = context.getEndpoint("mock:b", MockEndpoint.class);
    mocka.setExpectedCount(1);
    mocka2.setExpectedCount(1);
    mockb.setExpectedCount(1);
    Exchange answer = template.send("direct:a", ex -> {
        DataTypeAware message = (DataTypeAware) ex.getIn();
        message.setBody("<foo/>", new DataType("xml"));
    });
    mocka.assertIsSatisfied();
    mocka2.assertIsSatisfied();
    mockb.assertIsSatisfied();
    Exchange exa = mocka.getExchanges().get(0);
    Exchange exa2 = mocka2.getExchanges().get(0);
    Exchange exb = mockb.getExchanges().get(0);
    assertEquals("<foo/>", exa.getIn().getBody());
    assertEquals(A.class, exb.getIn().getBody().getClass());
    assertEquals(B.class, exa2.getIn().getBody().getClass());
    assertEquals("<fooResponse/>", new String((byte[]) answer.getIn().getBody()));
}
Also used : OutputStream(java.io.OutputStream) PrintWriter(java.io.PrintWriter) TypeConverters(org.apache.camel.TypeConverters) DataType(org.apache.camel.spi.DataType) DataFormatDefinition(org.apache.camel.model.DataFormatDefinition) Exchange(org.apache.camel.Exchange) Test(org.junit.Test) InputStreamReader(java.io.InputStreamReader) Converter(org.apache.camel.Converter) DataFormat(org.apache.camel.spi.DataFormat) DataTypeAware(org.apache.camel.spi.DataTypeAware) ContextTestSupport(org.apache.camel.ContextTestSupport) RouteBuilder(org.apache.camel.builder.RouteBuilder) OutputStreamWriter(java.io.OutputStreamWriter) BufferedReader(java.io.BufferedReader) RouteContext(org.apache.camel.spi.RouteContext) InputStream(java.io.InputStream) MockEndpoint(org.apache.camel.component.mock.MockEndpoint) Exchange(org.apache.camel.Exchange) RouteBuilder(org.apache.camel.builder.RouteBuilder) MockEndpoint(org.apache.camel.component.mock.MockEndpoint) DataTypeAware(org.apache.camel.spi.DataTypeAware) DataType(org.apache.camel.spi.DataType) Test(org.junit.Test)

Example 4 with DataTypeAware

use of org.apache.camel.spi.DataTypeAware in project camel by apache.

the class TransformerRouteTest method testDataFormatTransformer.

public void testDataFormatTransformer() throws Exception {
    MockEndpoint xyzresult = getMockEndpoint("mock:xyzresult");
    xyzresult.expectedMessageCount(1);
    xyzresult.whenAnyExchangeReceived(new Processor() {

        @Override
        public void process(Exchange exchange) throws Exception {
            LOG.info("Asserting String -> XOrderResponse convertion is not yet performed");
            assertEquals("response", exchange.getIn().getBody());
        }
    });
    Exchange exchange = new DefaultExchange(context, ExchangePattern.InOut);
    ((DataTypeAware) exchange.getIn()).setBody("{name:XOrder}", new DataType("json:JsonXOrder"));
    Exchange answerEx = template.send("direct:dataFormat", exchange);
    if (answerEx.getException() != null) {
        throw answerEx.getException();
    }
    assertEquals("{name:XOrderResponse}", answerEx.getOut().getBody(String.class));
    assertMockEndpointsSatisfied();
}
Also used : Exchange(org.apache.camel.Exchange) DefaultExchange(org.apache.camel.impl.DefaultExchange) DefaultExchange(org.apache.camel.impl.DefaultExchange) Processor(org.apache.camel.Processor) MockEndpoint(org.apache.camel.component.mock.MockEndpoint) DataTypeAware(org.apache.camel.spi.DataTypeAware) DataType(org.apache.camel.spi.DataType)

Example 5 with DataTypeAware

use of org.apache.camel.spi.DataTypeAware in project camel by apache.

the class OrderRouteSpringTest method testXML.

@Test
public void testXML() throws Exception {
    mockCsv.whenAnyExchangeReceived(new Processor() {

        public void process(Exchange exchange) {
            Object mockBody = exchange.getIn().getBody();
            assertEquals(Order.class, mockBody.getClass());
            Order mockOrder = (Order) mockBody;
            assertEquals("Order-XML-0001", mockOrder.getOrderId());
            assertEquals("MIKAN", mockOrder.getItemId());
            assertEquals(365, mockOrder.getQuantity());
        }
    });
    mockCsv.setExpectedMessageCount(1);
    String order = "<order orderId=\"Order-XML-0001\" itemId=\"MIKAN\" quantity=\"365\"/>";
    String expectedAnswer = "<orderResponse orderId=\"Order-XML-0001\" accepted=\"true\" description=\"Order accepted:[item='MIKAN' quantity='365']\"/>";
    Exchange answer = xmlProducer.send("direct:xml", ex -> {
        ((DataTypeAware) ex.getIn()).setBody(order, new DataType("xml:XMLOrder"));
    });
    XMLUnit.compareXML(expectedAnswer, answer.getOut().getBody(String.class));
    mockCsv.assertIsSatisfied();
}
Also used : Exchange(org.apache.camel.Exchange) Order(org.apache.camel.example.transformer.demo.Order) Processor(org.apache.camel.Processor) DataTypeAware(org.apache.camel.spi.DataTypeAware) DataType(org.apache.camel.spi.DataType) Test(org.junit.Test)

Aggregations

DataType (org.apache.camel.spi.DataType)8 DataTypeAware (org.apache.camel.spi.DataTypeAware)8 Exchange (org.apache.camel.Exchange)5 Processor (org.apache.camel.Processor)3 Order (org.apache.camel.example.transformer.demo.Order)3 Test (org.junit.Test)3 MockEndpoint (org.apache.camel.component.mock.MockEndpoint)2 OrderResponse (org.apache.camel.example.transformer.demo.OrderResponse)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 BufferedReader (java.io.BufferedReader)1 File (java.io.File)1 InputStream (java.io.InputStream)1 InputStreamReader (java.io.InputStreamReader)1 OutputStream (java.io.OutputStream)1 OutputStreamWriter (java.io.OutputStreamWriter)1 PrintWriter (java.io.PrintWriter)1 HashMap (java.util.HashMap)1 Map (java.util.Map)1 CamelContext (org.apache.camel.CamelContext)1 ContextTestSupport (org.apache.camel.ContextTestSupport)1