Search in sources :

Example 1 with DataType

use of org.apache.camel.spi.DataType 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 DataType

use of org.apache.camel.spi.DataType 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 DataType

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

the class TransformerBuilderTest method testDataFormatTransformer.

public void testDataFormatTransformer() throws Exception {
    CamelContext ctx = new DefaultCamelContext();
    RouteBuilder builder = new RouteBuilder() {

        @Override
        public void configure() throws Exception {
            transformer().fromType("xml:foo").toType("json:bar").withDataFormat(new StringDataFormat());
            from("direct:input").log("test");
        }
    };
    ctx.addRoutes(builder);
    ctx.start();
    Transformer transformer = ctx.resolveTransformer(new DataType("xml:foo"), new DataType("json:bar"));
    assertNotNull(transformer);
    assertEquals(DataFormatTransformer.class, transformer.getClass());
    DataFormatTransformer dft = (DataFormatTransformer) transformer;
    Field f = DataFormatTransformer.class.getDeclaredField("dataFormatType");
    f.setAccessible(true);
    Object dataFormatType = f.get(dft);
    assertEquals(StringDataFormat.class, dataFormatType.getClass());
}
Also used : DefaultCamelContext(org.apache.camel.impl.DefaultCamelContext) CamelContext(org.apache.camel.CamelContext) Field(java.lang.reflect.Field) ProcessorTransformer(org.apache.camel.impl.transformer.ProcessorTransformer) Transformer(org.apache.camel.spi.Transformer) DataFormatTransformer(org.apache.camel.impl.transformer.DataFormatTransformer) StringDataFormat(org.apache.camel.model.dataformat.StringDataFormat) DataType(org.apache.camel.spi.DataType) DataFormatTransformer(org.apache.camel.impl.transformer.DataFormatTransformer) DefaultCamelContext(org.apache.camel.impl.DefaultCamelContext)

Example 4 with DataType

use of org.apache.camel.spi.DataType 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 5 with DataType

use of org.apache.camel.spi.DataType 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)

Aggregations

DataType (org.apache.camel.spi.DataType)15 DataTypeAware (org.apache.camel.spi.DataTypeAware)8 Exchange (org.apache.camel.Exchange)5 Transformer (org.apache.camel.spi.Transformer)5 CamelContext (org.apache.camel.CamelContext)4 Processor (org.apache.camel.Processor)3 Order (org.apache.camel.example.transformer.demo.Order)3 Test (org.junit.Test)3 Field (java.lang.reflect.Field)2 CompositeData (javax.management.openmbean.CompositeData)2 CompositeDataSupport (javax.management.openmbean.CompositeDataSupport)2 CompositeType (javax.management.openmbean.CompositeType)2 TabularData (javax.management.openmbean.TabularData)2 TabularDataSupport (javax.management.openmbean.TabularDataSupport)2 MockEndpoint (org.apache.camel.component.mock.MockEndpoint)2 OrderResponse (org.apache.camel.example.transformer.demo.OrderResponse)2 DefaultCamelContext (org.apache.camel.impl.DefaultCamelContext)2 DataFormatTransformer (org.apache.camel.impl.transformer.DataFormatTransformer)2 ProcessorTransformer (org.apache.camel.impl.transformer.ProcessorTransformer)2 BindingException (org.apache.camel.processor.binding.BindingException)2