org.apache.camel.support.ExchangeHelper Java Examples

The following examples show how to use org.apache.camel.support.ExchangeHelper. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: KnativeHttpConsumer.java    From camel-k-runtime with Apache License 2.0 6 votes vote down vote up
private Buffer computeResponseBody(Message message) throws NoTypeConversionAvailableException {
    Object body = message.getBody();
    Exception exception = message.getExchange().getException();

    if (exception != null) {
        // we failed due an exception so print it as plain text
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        exception.printStackTrace(pw);

        // the body should then be the stacktrace
        body = sw.toString().getBytes(StandardCharsets.UTF_8);
        // force content type to be text/plain as that is what the stacktrace is
        message.setHeader(Exchange.CONTENT_TYPE, "text/plain");

        // and mark the exception as failure handled, as we handled it by returning
        // it as the response
        ExchangeHelper.setFailureHandled(message.getExchange());
    }

    return body != null
        ? Buffer.buffer(message.getExchange().getContext().getTypeConverter().mandatoryConvertTo(byte[].class, body))
        : null;
}
 
Example #2
Source File: HttpMessageToDefaultMessageProcessor.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Override
public void process(Exchange exchange) throws Exception {
    final Message message = exchange.getIn();
    if (message instanceof HttpMessage) {
        final Message replacement = new DefaultMessage(exchange.getContext());
        replacement.copyFrom(message);
        ExchangeHelper.replaceMessage(exchange, replacement, false);
    }
}
 
Example #3
Source File: ReactorIntegrationTest.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
@Test
public void testFrom() throws Exception {

    CamelContext camelctx = new DefaultCamelContext();

    CamelReactiveStreamsService crs = CamelReactiveStreams.get(camelctx);
    Publisher<Exchange> timer = crs.from("timer:reactive?period=250&repeatCount=3");

    AtomicInteger value = new AtomicInteger(0);
    CountDownLatch latch = new CountDownLatch(3);

    camelctx.start();
    try {

        // [#2936] Reactive stream has no active subscriptions
        Thread.sleep(500);

        Flux.from(timer)
            .map(exchange -> ExchangeHelper.getHeaderOrProperty(exchange, Exchange.TIMER_COUNTER, Integer.class))
            .doOnNext(res -> Assert.assertEquals(value.incrementAndGet(), res.intValue()))
            .doOnNext(res -> latch.countDown())
            .subscribe();

        Assert.assertTrue(latch.await(2, TimeUnit.SECONDS));
    } finally {
        camelctx.close();
    }
}
 
Example #4
Source File: QuteEndpoint.java    From camel-quarkus with Apache License 2.0 4 votes vote down vote up
@Override
protected void onExchange(Exchange exchange) throws Exception {
    String path = getResourceUri();
    ObjectHelper.notNull(path, "resourceUri");

    if (allowTemplateFromHeader) {
        String newResourceUri = exchange.getIn().getHeader(QuteConstants.QUTE_RESOURCE_URI, String.class);
        if (newResourceUri != null) {
            exchange.getIn().removeHeader(QuteConstants.QUTE_RESOURCE_URI);

            log.debug("{} set to {} creating new endpoint to handle exchange", QuteConstants.QUTE_RESOURCE_URI,
                    newResourceUri);
            QuteEndpoint newEndpoint = findOrCreateEndpoint(getEndpointUri(), newResourceUri);
            newEndpoint.onExchange(exchange);
            return;
        }
    }

    String content = null;
    if (allowTemplateFromHeader) {
        content = exchange.getIn().getHeader(QuteConstants.QUTE_TEMPLATE, String.class);
        if (content != null) {
            // remove the header to avoid it being propagated in the routing
            exchange.getIn().removeHeader(QuteConstants.QUTE_TEMPLATE);
        }
    }

    TemplateInstance instance = null;
    if (allowTemplateFromHeader) {
        instance = exchange.getIn().getHeader(QuteConstants.QUTE_TEMPLATE_INSTANCE, TemplateInstance.class);
    }
    if (instance != null) {
        // use template instance from header
        if (log.isDebugEnabled()) {
            log.debug("Qute template instance is from header {} for endpoint {}", QuteConstants.QUTE_TEMPLATE_INSTANCE,
                    getEndpointUri());
        }
        exchange.getIn().removeHeader(QuteConstants.QUTE_TEMPLATE_INSTANCE);
    } else {
        Template template;
        Engine engine = getQuteEngine();
        if (content == null) {
            template = engine.getTemplate(path);
        } else {
            // This is the first time to parse the content
            template = engine.parse(content);
        }
        instance = template.instance();
    }

    ExchangeHelper.createVariableMap(exchange, isAllowContextMapAll()).forEach(instance::data);

    Map<String, Object> map = exchange.getIn().getHeader(QuteConstants.QUTE_TEMPLATE_DATA, Map.class);
    if (map != null) {
        map.forEach(instance::data);
    }

    exchange.getMessage().setBody(instance.render().trim());
}
 
Example #5
Source File: QuarkusPlatformHttpConsumer.java    From camel-quarkus with Apache License 2.0 4 votes vote down vote up
static Object toHttpResponse(HttpServerResponse response, Message message, HeaderFilterStrategy headerFilterStrategy) {
    final Exchange exchange = message.getExchange();

    final int code = determineResponseCode(exchange, message.getBody());
    response.setStatusCode(code);

    final TypeConverter tc = exchange.getContext().getTypeConverter();

    // copy headers from Message to Response
    if (headerFilterStrategy != null) {
        for (Map.Entry<String, Object> entry : message.getHeaders().entrySet()) {
            final String key = entry.getKey();
            final Object value = entry.getValue();
            // use an iterator as there can be multiple values. (must not use a delimiter)
            final Iterator<?> it = ObjectHelper.createIterator(value, null);
            String firstValue = null;
            List<String> values = null;
            while (it.hasNext()) {
                final String headerValue = tc.convertTo(String.class, it.next());
                if (headerValue != null
                        && !headerFilterStrategy.applyFilterToCamelHeaders(key, headerValue, exchange)) {
                    if (firstValue == null) {
                        firstValue = headerValue;
                    } else {
                        if (values == null) {
                            values = new ArrayList<String>();
                            values.add(firstValue);
                        }
                        values.add(headerValue);
                    }
                }
            }
            if (values != null) {
                response.putHeader(key, values);
            } else if (firstValue != null) {
                response.putHeader(key, firstValue);
            }
        }
    }

    Object body = message.getBody();
    final Exception exception = exchange.getException();

    if (exception != null) {
        // we failed due an exception so print it as plain text
        final StringWriter sw = new StringWriter();
        final PrintWriter pw = new PrintWriter(sw);
        exception.printStackTrace(pw);

        // the body should then be the stacktrace
        body = ByteBuffer.wrap(sw.toString().getBytes(StandardCharsets.UTF_8));
        // force content type to be text/plain as that is what the stacktrace is
        message.setHeader(Exchange.CONTENT_TYPE, "text/plain; charset=utf-8");

        // and mark the exception as failure handled, as we handled it by returning it as the response
        ExchangeHelper.setFailureHandled(exchange);
    }

    // set the content-length if it can be determined, or chunked encoding
    final Integer length = determineContentLength(exchange, body);
    if (length != null) {
        response.putHeader("Content-Length", String.valueOf(length));
    } else {
        response.setChunked(true);
    }

    // set the content type in the response.
    final String contentType = MessageHelper.getContentType(message);
    if (contentType != null) {
        // set content-type
        response.putHeader("Content-Type", contentType);
    }
    return body;
}
 
Example #6
Source File: HttpRequestWrapperProcessor.java    From syndesis with Apache License 2.0 4 votes vote down vote up
@Override
@SuppressFBWarnings("RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE") // https://github.com/spotbugs/spotbugs/issues/259
public void process(Exchange exchange) throws Exception {
    final Message message = exchange.getIn();
    final Object body = message.getBody();

    final ObjectNode rootNode = JsonUtils.copyObjectMapperConfiguration().createObjectNode();

    if (!parameters.isEmpty()) {
        final ObjectNode parametersNode = rootNode.putObject("parameters");

        final HttpServletRequest servletRequest = message.getHeader(Exchange.HTTP_SERVLET_REQUEST, HttpServletRequest.class);
        for (String parameter : parameters) {
            final String[] values;
            final String[] headerValues = message.getHeader(parameter, String[].class);
            if (servletRequest != null && headerValues == null) {
                values = servletRequest.getParameterValues(parameter);
            } else {
                values = headerValues;
            }

            putPrameterValueTo(parametersNode, parameter, values);
        }
    }

    if (body instanceof String) {
        final String string = (String) body;
        if (ObjectHelper.isNotEmpty(string)) {
            rootNode.set("body", READER.readValue(string));
        }
    } else if (body instanceof InputStream) {
        try (InputStream stream = (InputStream) body) {
            if (stream.available() > 0) {
                rootNode.set("body", READER.readValue(stream));
            }
        }
    } else if (body != null) {
        rootNode.putPOJO("body", body);
    }

    final String newBody = JsonUtils.toString(rootNode);
    final Message replacement = new DefaultMessage(exchange.getContext());
    replacement.copyFromWithNewBody(message, newBody);

    // we rely on having the Content-Type match the body when we're
    // extracting parameters from the JSON body, otherwise we don't
    // know if the content is JSON or XML (or any future supported
    // content type)
    replacement.setHeader(Exchange.CONTENT_TYPE, "application/json");

    ExchangeHelper.replaceMessage(exchange, replacement, false);
}
 
Example #7
Source File: CamelToVertxProcessor.java    From vertx-camel-bridge with Apache License 2.0 4 votes vote down vote up
@Override
public boolean process(Exchange exchange, AsyncCallback callback) {
  Message in = exchange.getIn();

  Object body = CamelHelper.convert(inbound, in);

  DeliveryOptions delivery = CamelHelper.getDeliveryOptions(in, inbound.isHeadersCopy());
  if (inbound.getTimeout() > 0) {
    delivery.setSendTimeout(inbound.getTimeout());
  }

  try {
    if (inbound.isPublish()) {
      vertx.eventBus().publish(inbound.getAddress(), body, delivery);
    } else {
      if (ExchangeHelper.isOutCapable(exchange)) {
        vertx.eventBus().request(inbound.getAddress(), body, delivery, reply -> {
          Message out = exchange.getOut();
          if (reply.succeeded()) {
            out.setBody(reply.result().body());
            MultiMapHelper.toMap(reply.result().headers(), out.getHeaders());
          } else {
            exchange.setException(reply.cause());
          }
          // continue callback
          callback.done(false);
        });
        // being routed async so return false
        return false;
      } else {
        // No reply expected.
        vertx.eventBus().send(inbound.getAddress(), body, delivery);
      }
    }
  } catch (Throwable e) {
    // Mark the exchange as "failed".
    exchange.setException(e);
  }

  callback.done(true);
  return true;
}