Search in sources :

Example 16 with TypeConverter

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

the class BindyKeyValuePairDataFormat method marshal.

@SuppressWarnings("unchecked")
public void marshal(Exchange exchange, Object body, OutputStream outputStream) throws Exception {
    final BindyAbstractFactory factory = getFactory();
    final byte[] crlf = ConverterUtils.getByteReturn(factory.getCarriageReturn());
    final TypeConverter converter = exchange.getContext().getTypeConverter();
    // the body may not be a prepared list of map that bindy expects so help
    // a bit here and create one if needed
    final Iterator<Object> it = ObjectHelper.createIterator(body);
    while (it.hasNext()) {
        Object model = it.next();
        Map<String, Object> row;
        if (model instanceof Map) {
            row = (Map<String, Object>) model;
        } else {
            row = Collections.singletonMap(model.getClass().getName(), model);
        }
        String result = factory.unbind(row);
        outputStream.write(converter.convertTo(byte[].class, exchange, result));
        outputStream.write(crlf);
    }
}
Also used : TypeConverter(org.apache.camel.TypeConverter) BindyAbstractFactory(org.apache.camel.dataformat.bindy.BindyAbstractFactory) HashMap(java.util.HashMap) Map(java.util.Map)

Example 17 with TypeConverter

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

the class IgniteComputeProducer method doCall.

@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()));
    }
}
Also used : TypeConverter(org.apache.camel.TypeConverter) IgniteCallable(org.apache.ignite.lang.IgniteCallable) ArrayList(java.util.ArrayList) Collection(java.util.Collection) RuntimeCamelException(org.apache.camel.RuntimeCamelException)

Example 18 with TypeConverter

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

the class CamelJaxbFallbackConverterTest method testFallbackConverterWithoutObjectFactory.

@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);
}
Also used : TypeConverter(org.apache.camel.TypeConverter) DefaultExchange(org.apache.camel.impl.DefaultExchange) Exchange(org.apache.camel.Exchange) DefaultExchange(org.apache.camel.impl.DefaultExchange) Bar(org.apache.camel.example.Bar) Foo(org.apache.camel.example.Foo) Test(org.junit.Test)

Example 19 with TypeConverter

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

the class JcrProducer method process.

public void process(Exchange exchange) throws Exception {
    TypeConverter converter = exchange.getContext().getTypeConverter();
    Session session = openSession();
    Message message = exchange.getIn();
    String operation = determineOperation(message);
    try {
        if (JcrConstants.JCR_INSERT.equals(operation)) {
            Node base = findOrCreateNode(session.getRootNode(), getJcrEndpoint().getBase(), "");
            Node node = findOrCreateNode(base, getNodeName(message), getNodeType(message));
            Map<String, Object> headers = filterComponentHeaders(message.getHeaders());
            for (String key : headers.keySet()) {
                Object header = message.getHeader(key);
                if (header != null && Object[].class.isAssignableFrom(header.getClass())) {
                    Value[] value = converter.convertTo(Value[].class, exchange, header);
                    node.setProperty(key, value);
                } else {
                    Value value = converter.convertTo(Value.class, exchange, header);
                    node.setProperty(key, value);
                }
            }
            node.addMixin("mix:referenceable");
            exchange.getOut().setBody(node.getIdentifier());
            session.save();
        } else if (JcrConstants.JCR_GET_BY_ID.equals(operation)) {
            Node node = session.getNodeByIdentifier(exchange.getIn().getMandatoryBody(String.class));
            PropertyIterator properties = node.getProperties();
            while (properties.hasNext()) {
                Property property = properties.nextProperty();
                Class<?> aClass = classForJCRType(property);
                Object value;
                if (property.isMultiple()) {
                    value = converter.convertTo(aClass, exchange, property.getValues());
                } else {
                    value = converter.convertTo(aClass, exchange, property.getValue());
                }
                message.setHeader(property.getName(), value);
            }
        } else {
            throw new RuntimeException("Unsupported operation: " + operation);
        }
    } finally {
        if (session != null && session.isLive()) {
            session.logout();
        }
    }
}
Also used : Message(org.apache.camel.Message) Node(javax.jcr.Node) PropertyIterator(javax.jcr.PropertyIterator) TypeConverter(org.apache.camel.TypeConverter) Value(javax.jcr.Value) Property(javax.jcr.Property) Session(javax.jcr.Session)

Example 20 with TypeConverter

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

the class UndertowConsumer method handleRequest.

@Override
public void handleRequest(HttpServerExchange httpExchange) throws Exception {
    HttpString requestMethod = httpExchange.getRequestMethod();
    if (Methods.OPTIONS.equals(requestMethod) && !getEndpoint().isOptionsEnabled()) {
        String allowedMethods;
        if (getEndpoint().getHttpMethodRestrict() != null) {
            allowedMethods = "OPTIONS," + getEndpoint().getHttpMethodRestrict();
        } else {
            allowedMethods = "GET,HEAD,POST,PUT,DELETE,TRACE,OPTIONS,CONNECT,PATCH";
        }
        //return list of allowed methods in response headers
        httpExchange.setStatusCode(StatusCodes.OK);
        httpExchange.getResponseHeaders().put(ExchangeHeaders.CONTENT_TYPE, MimeMappings.DEFAULT_MIME_MAPPINGS.get("txt"));
        httpExchange.getResponseHeaders().put(ExchangeHeaders.CONTENT_LENGTH, 0);
        httpExchange.getResponseHeaders().put(Headers.ALLOW, allowedMethods);
        httpExchange.getResponseSender().close();
        return;
    }
    //perform blocking operation on exchange
    if (httpExchange.isInIoThread()) {
        httpExchange.dispatch(this);
        return;
    }
    //create new Exchange
    //binding is used to extract header and payload(if available)
    Exchange camelExchange = getEndpoint().createExchange(httpExchange);
    //Unit of Work to process the Exchange
    createUoW(camelExchange);
    try {
        getProcessor().process(camelExchange);
    } catch (Exception e) {
        getExceptionHandler().handleException(e);
    } finally {
        doneUoW(camelExchange);
    }
    Object body = getResponseBody(httpExchange, camelExchange);
    TypeConverter tc = getEndpoint().getCamelContext().getTypeConverter();
    if (body == null) {
        LOG.trace("No payload to send as reply for exchange: " + camelExchange);
        httpExchange.getResponseHeaders().put(ExchangeHeaders.CONTENT_TYPE, MimeMappings.DEFAULT_MIME_MAPPINGS.get("txt"));
        httpExchange.getResponseSender().send("No response available");
    } else {
        ByteBuffer bodyAsByteBuffer = tc.convertTo(ByteBuffer.class, body);
        httpExchange.getResponseSender().send(bodyAsByteBuffer);
    }
    httpExchange.getResponseSender().close();
}
Also used : HttpServerExchange(io.undertow.server.HttpServerExchange) Exchange(org.apache.camel.Exchange) TypeConverter(org.apache.camel.TypeConverter) HttpString(io.undertow.util.HttpString) ByteBuffer(java.nio.ByteBuffer) IOException(java.io.IOException) HttpString(io.undertow.util.HttpString)

Aggregations

TypeConverter (org.apache.camel.TypeConverter)48 Map (java.util.Map)13 FallbackConverter (org.apache.camel.FallbackConverter)9 InputStream (java.io.InputStream)6 HashMap (java.util.HashMap)6 Exchange (org.apache.camel.Exchange)6 RuntimeCamelException (org.apache.camel.RuntimeCamelException)6 ArrayList (java.util.ArrayList)5 NoTypeConversionAvailableException (org.apache.camel.NoTypeConversionAvailableException)5 HttpString (io.undertow.util.HttpString)4 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4 ObjectOutputStream (java.io.ObjectOutputStream)4 PrintWriter (java.io.PrintWriter)4 StringWriter (java.io.StringWriter)4 UnsupportedEncodingException (java.io.UnsupportedEncodingException)4 List (java.util.List)4 HeaderMap (io.undertow.util.HeaderMap)3 IOException (java.io.IOException)3 URI (java.net.URI)3 Message (org.apache.camel.Message)3