Esempio n. 1
0
  /*
   * Tests the {@link MessageHelper#resetStreamCache(Message)} method
   */
  public void testResetStreamCache() throws Exception {
    // should not throw exceptions when Message or message body is null
    MessageHelper.resetStreamCache(null);
    MessageHelper.resetStreamCache(message);

    // handle StreamCache
    final ValueHolder<Boolean> reset = new ValueHolder<Boolean>(Boolean.FALSE);
    message.setBody(
        new StreamCache() {
          @SuppressWarnings("deprecation")
          public void reset() {
            reset.set(Boolean.TRUE);
          }

          public void writeTo(OutputStream os) throws IOException {
            // noop
          }

          public StreamCache copy(Exchange exchange) throws IOException {
            return null;
          }

          public boolean inMemory() {
            return true;
          }

          @Override
          public long length() {
            return 0;
          }
        });
    MessageHelper.resetStreamCache(message);
    assertTrue("Should have reset the stream cache", reset.get());
  }
Esempio n. 2
0
  protected void populateResponse(
      Exchange exchange,
      HttpMethod method,
      Message in,
      HeaderFilterStrategy strategy,
      int responseCode)
      throws IOException, ClassNotFoundException {
    // We just make the out message is not create when extractResponseBody throws exception,
    Object response = extractResponseBody(method, exchange);
    Message answer = exchange.getOut();

    answer.setHeader(Exchange.HTTP_RESPONSE_CODE, responseCode);
    answer.setBody(response);

    // propagate HTTP response headers
    Header[] headers = method.getResponseHeaders();
    for (Header header : headers) {
      String name = header.getName();
      String value = header.getValue();
      if (name.toLowerCase().equals("content-type")) {
        name = Exchange.CONTENT_TYPE;
        exchange.setProperty(Exchange.CHARSET_NAME, IOHelper.getCharsetNameFromContentType(value));
      }

      // use http helper to extract parameter value as it may contain multiple values
      Object extracted = HttpHelper.extractHttpParameterValue(value);
      if (strategy != null && !strategy.applyFilterToExternalHeaders(name, extracted, exchange)) {
        HttpHelper.appendHeader(answer.getHeaders(), name, extracted);
      }
    }

    // preserve headers from in by copying any non existing headers
    // to avoid overriding existing headers with old values
    MessageHelper.copyHeaders(exchange.getIn(), answer, false);
  }
  protected void prepareExchangeForContinue(Exchange exchange, RedeliveryData data) {
    Exception caught = exchange.getException();

    // we continue so clear any exceptions
    exchange.setException(null);
    // clear rollback flags
    exchange.setProperty(Exchange.ROLLBACK_ONLY, null);
    // reset cached streams so they can be read again
    MessageHelper.resetStreamCache(exchange.getIn());

    // its continued then remove traces of redelivery attempted and caught exception
    exchange.getIn().removeHeader(Exchange.REDELIVERED);
    exchange.getIn().removeHeader(Exchange.REDELIVERY_COUNTER);
    exchange.getIn().removeHeader(Exchange.REDELIVERY_MAX_COUNTER);
    exchange.removeProperty(Exchange.FAILURE_HANDLED);
    // keep the Exchange.EXCEPTION_CAUGHT as property so end user knows the caused exception

    // create log message
    String msg = "Failed delivery for exchangeId: " + exchange.getExchangeId();
    msg =
        msg
            + ". Exhausted after delivery attempt: "
            + data.redeliveryCounter
            + " caught: "
            + caught;
    msg = msg + ". Handled and continue routing.";

    // log that we failed but want to continue
    logFailedDelivery(false, false, true, exchange, msg, data, null);
  }
Esempio n. 4
0
  public void testMessageDump() throws Exception {
    JAXBContext jaxb = JAXBContext.newInstance(MessageDump.class);
    Unmarshaller unmarshaller = jaxb.createUnmarshaller();

    CamelContext context = new DefaultCamelContext();
    context.start();

    message = new DefaultExchange(context).getIn();

    // xml message body
    message.setBody("Hello World");
    message.setHeader("foo", 123);

    String out = MessageHelper.dumpAsXml(message, true);

    MessageDump dump = (MessageDump) unmarshaller.unmarshal(new StringReader(out));
    assertNotNull(dump);

    assertEquals("java.lang.String", dump.getBody().getType());
    assertEquals("Hello World", dump.getBody().getValue());

    assertEquals(1, dump.getHeaders().size());
    assertEquals("foo", dump.getHeaders().get(0).getKey());
    assertEquals("java.lang.Integer", dump.getHeaders().get(0).getType());
    assertEquals("123", dump.getHeaders().get(0).getValue());
  }
  protected void doGetBuild(Exchange exchange, String operation) throws Exception {
    Build build = null;
    String buildName =
        exchange.getIn().getHeader(KubernetesConstants.KUBERNETES_BUILD_NAME, String.class);
    String namespaceName =
        exchange.getIn().getHeader(KubernetesConstants.KUBERNETES_NAMESPACE_NAME, String.class);
    if (ObjectHelper.isEmpty(buildName)) {
      LOG.error("Get a specific Build require specify a Build name");
      throw new IllegalArgumentException("Get a specific Build require specify a Build name");
    }
    if (ObjectHelper.isEmpty(namespaceName)) {
      LOG.error("Get a specific Build require specify a namespace name");
      throw new IllegalArgumentException("Get a specific Build require specify a namespace name");
    }
    build =
        getEndpoint()
            .getKubernetesClient()
            .adapt(OpenShiftClient.class)
            .builds()
            .inNamespace(namespaceName)
            .withName(buildName)
            .get();

    MessageHelper.copyHeaders(exchange.getIn(), exchange.getOut(), true);
    exchange.getOut().setBody(build);
  }
 private Message prepareResponseMessage(Exchange exchange, MongoDbOperation operation) {
   Message answer = exchange.getOut();
   MessageHelper.copyHeaders(exchange.getIn(), answer, false);
   if (isWriteOperation(operation) && endpoint.isWriteResultAsHeader()) {
     answer.setBody(exchange.getIn().getBody());
   }
   return answer;
 }
Esempio n. 7
0
  public void testCopyHeaders() throws Exception {
    Message source = message;
    Message target = new DefaultMessage();

    source.setHeader("foo", 123);
    source.setHeader("bar", 456);
    target.setHeader("bar", "yes");

    MessageHelper.copyHeaders(source, target, false);

    assertEquals(123, target.getHeader("foo"));
    assertEquals("yes", target.getHeader("bar"));
  }
Esempio n. 8
0
  public void testDumpAsXmlPlainBody() throws Exception {
    CamelContext context = new DefaultCamelContext();
    context.start();

    message = new DefaultExchange(context).getIn();

    // xml message body
    message.setBody("Hello World");
    message.setHeader("foo", 123);

    String out = MessageHelper.dumpAsXml(message);
    assertTrue(
        "Should contain body", out.contains("<body type=\"java.lang.String\">Hello World</body>"));

    context.stop();
  }
Esempio n. 9
0
  public void testDumpAsXmlBody() throws Exception {
    CamelContext context = new DefaultCamelContext();
    context.start();

    message = new DefaultExchange(context).getIn();

    // xml message body
    message.setBody("<?xml version=\"1.0\"?><hi>Hello World</hi>");
    message.setHeader("foo", 123);

    String out = MessageHelper.dumpAsXml(message);
    assertTrue(
        "Should contain body",
        out.contains(
            "<body type=\"java.lang.String\">&lt;?xml version=&quot;1.0&quot;?&gt;&lt;hi&gt;Hello World&lt;/hi&gt;</body>"));
    assertTrue("Should contain exchangeId", out.contains(message.getExchange().getExchangeId()));

    context.stop();
  }
Esempio n. 10
0
  public void testDumpAsXmlNoBodyIndent() throws Exception {
    CamelContext context = new DefaultCamelContext();
    context.start();

    message = new DefaultExchange(context).getIn();

    // xml message body
    message.setBody("Hello World");
    message.setHeader("foo", 123);

    String out = MessageHelper.dumpAsXml(message, false, 2);

    assertEquals(
        "  <message exchangeId=\""
            + message.getExchange().getExchangeId()
            + "\">"
            + "\n    <headers>\n      <header key=\"foo\" type=\"java.lang.Integer\">123</header>\n    </headers>\n  </message>",
        out);

    context.stop();
  }
Esempio n. 11
0
  public void testCopyHeadersWithHeaderFilterStrategy() throws Exception {
    CamelContext context = new DefaultCamelContext();
    context.start();

    message = new DefaultExchange(context).getIn();

    Message source = message;
    Message target = message.getExchange().getOut();

    DefaultHeaderFilterStrategy headerFilterStrategy = new DefaultHeaderFilterStrategy();
    headerFilterStrategy.setOutFilterPattern("foo");

    source.setHeader("foo", 123);
    source.setHeader("bar", 456);
    target.setHeader("bar", "yes");

    MessageHelper.copyHeaders(source, target, headerFilterStrategy, true);

    assertEquals(null, target.getHeader("foo"));
    assertEquals(456, target.getHeader("bar"));
    context.stop();
  }
  protected void prepareExchangeForRedelivery(Exchange exchange, RedeliveryData data) {
    // there must be a defensive copy of the exchange
    ObjectHelper.notNull(data.original, "Defensive copy of Exchange is null", this);

    // okay we will give it another go so clear the exception so we can try again
    exchange.setException(null);

    // clear rollback flags
    exchange.setProperty(Exchange.ROLLBACK_ONLY, null);

    // TODO: We may want to store these as state on RedelieryData so we keep them in case end user
    // messes with Exchange
    // and then put these on the exchange when doing a redelivery / fault processor

    // preserve these headers
    Integer redeliveryCounter =
        exchange.getIn().getHeader(Exchange.REDELIVERY_COUNTER, Integer.class);
    Integer redeliveryMaxCounter =
        exchange.getIn().getHeader(Exchange.REDELIVERY_MAX_COUNTER, Integer.class);
    Boolean redelivered = exchange.getIn().getHeader(Exchange.REDELIVERED, Boolean.class);

    // we are redelivering so copy from original back to exchange
    exchange.getIn().copyFrom(data.original.getIn());
    exchange.setOut(null);
    // reset cached streams so they can be read again
    MessageHelper.resetStreamCache(exchange.getIn());

    // put back headers
    if (redeliveryCounter != null) {
      exchange.getIn().setHeader(Exchange.REDELIVERY_COUNTER, redeliveryCounter);
    }
    if (redeliveryMaxCounter != null) {
      exchange.getIn().setHeader(Exchange.REDELIVERY_MAX_COUNTER, redeliveryMaxCounter);
    }
    if (redelivered != null) {
      exchange.getIn().setHeader(Exchange.REDELIVERED, redelivered);
    }
  }
Esempio n. 13
0
 protected void doListBuildByLabels(Exchange exchange, String operation) throws Exception {
   BuildList buildList = null;
   Map<String, String> labels =
       exchange.getIn().getHeader(KubernetesConstants.KUBERNETES_BUILDS_LABELS, Map.class);
   String namespaceName =
       exchange.getIn().getHeader(KubernetesConstants.KUBERNETES_NAMESPACE_NAME, String.class);
   if (!ObjectHelper.isEmpty(namespaceName)) {
     ClientNonNamespaceOperation<
             Build,
             BuildList,
             DoneableBuild,
             ClientBuildResource<Build, DoneableBuild, String, LogWatch>>
         builds =
             getEndpoint()
                 .getKubernetesClient()
                 .adapt(OpenShiftClient.class)
                 .builds()
                 .inNamespace(namespaceName);
     for (Map.Entry<String, String> entry : labels.entrySet()) {
       builds.withLabel(entry.getKey(), entry.getValue());
     }
     buildList = builds.list();
   } else {
     ClientMixedOperation<
             Build,
             BuildList,
             DoneableBuild,
             ClientBuildResource<Build, DoneableBuild, String, LogWatch>>
         builds = getEndpoint().getKubernetesClient().adapt(OpenShiftClient.class).builds();
     for (Map.Entry<String, String> entry : labels.entrySet()) {
       builds.withLabel(entry.getKey(), entry.getValue());
     }
     buildList = builds.list();
   }
   MessageHelper.copyHeaders(exchange.getIn(), exchange.getOut(), true);
   exchange.getOut().setBody(buildList.getItems());
 }
 @Override
 public Object unmarshal(Exchange exchange, InputStream stream)
     throws IOException, MessagingException {
   MimeBodyPart mimeMessage;
   String contentType;
   Message camelMessage;
   Object content = null;
   if (headersInline) {
     mimeMessage = new MimeBodyPart(stream);
     camelMessage = exchange.getOut();
     MessageHelper.copyHeaders(exchange.getIn(), camelMessage, true);
     contentType = mimeMessage.getHeader(CONTENT_TYPE, null);
     // write the MIME headers not generated by javamail as Camel headers
     Enumeration<?> headersEnum = mimeMessage.getNonMatchingHeaders(STANDARD_HEADERS);
     while (headersEnum.hasMoreElements()) {
       Object ho = headersEnum.nextElement();
       if (ho instanceof Header) {
         Header header = (Header) ho;
         camelMessage.setHeader(header.getName(), header.getValue());
       }
     }
   } else {
     // check if this a multipart at all. Otherwise do nothing
     contentType = exchange.getIn().getHeader(CONTENT_TYPE, String.class);
     if (contentType == null) {
       return stream;
     }
     try {
       ContentType ct = new ContentType(contentType);
       if (!ct.match("multipart/*")) {
         return stream;
       }
     } catch (ParseException e) {
       LOG.warn("Invalid Content-Type " + contentType + " ignored");
       return stream;
     }
     camelMessage = exchange.getOut();
     MessageHelper.copyHeaders(exchange.getIn(), camelMessage, true);
     ByteArrayOutputStream bos = new ByteArrayOutputStream();
     IOHelper.copyAndCloseInput(stream, bos);
     InternetHeaders headers = new InternetHeaders();
     extractHeader(CONTENT_TYPE, camelMessage, headers);
     extractHeader(MIME_VERSION, camelMessage, headers);
     mimeMessage = new MimeBodyPart(headers, bos.toByteArray());
     bos.close();
   }
   DataHandler dh;
   try {
     dh = mimeMessage.getDataHandler();
     if (dh != null) {
       content = dh.getContent();
       contentType = dh.getContentType();
     }
   } catch (MessagingException e) {
     LOG.warn("cannot parse message, no unmarshalling done");
   }
   if (content instanceof MimeMultipart) {
     MimeMultipart mp = (MimeMultipart) content;
     content = mp.getBodyPart(0);
     for (int i = 1; i < mp.getCount(); i++) {
       BodyPart bp = mp.getBodyPart(i);
       DefaultAttachment camelAttachment = new DefaultAttachment(bp.getDataHandler());
       @SuppressWarnings("unchecked")
       Enumeration<Header> headers = bp.getAllHeaders();
       while (headers.hasMoreElements()) {
         Header header = headers.nextElement();
         camelAttachment.addHeader(header.getName(), header.getValue());
       }
       camelMessage.addAttachmentObject(getAttachmentKey(bp), camelAttachment);
     }
   }
   if (content instanceof BodyPart) {
     BodyPart bp = (BodyPart) content;
     camelMessage.setBody(bp.getInputStream());
     contentType = bp.getContentType();
     if (contentType != null && !DEFAULT_CONTENT_TYPE.equals(contentType)) {
       camelMessage.setHeader(CONTENT_TYPE, contentType);
       ContentType ct = new ContentType(contentType);
       String charset = ct.getParameter("charset");
       if (charset != null) {
         camelMessage.setHeader(Exchange.CONTENT_ENCODING, MimeUtility.javaCharset(charset));
       }
     }
   } else {
     // If we find no body part, try to leave the message alone
     LOG.info("no MIME part found");
   }
   return camelMessage;
 }
  @Override
  public HttpRequest toNettyRequest(
      Message message, String uri, NettyHttpConfiguration configuration) throws Exception {
    LOG.trace("toNettyRequest: {}", message);

    // the message body may already be a Netty HTTP response
    if (message.getBody() instanceof HttpRequest) {
      return (HttpRequest) message.getBody();
    }

    // just assume GET for now, we will later change that to the actual method to use
    HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri);

    TypeConverter tc = message.getExchange().getContext().getTypeConverter();

    // if we bridge endpoint then we need to skip matching headers with the HTTP_QUERY to avoid
    // sending
    // duplicated headers to the receiver, so use this skipRequestHeaders as the list of headers to
    // skip
    Map<String, Object> skipRequestHeaders = null;
    if (configuration.isBridgeEndpoint()) {
      String queryString = message.getHeader(Exchange.HTTP_QUERY, String.class);
      if (queryString != null) {
        skipRequestHeaders = URISupport.parseQuery(queryString, false, true);
      }
      // Need to remove the Host key as it should be not used
      message.getHeaders().remove("host");
    }

    // append headers
    // must use entrySet to ensure case of keys is preserved
    for (Map.Entry<String, Object> entry : message.getHeaders().entrySet()) {
      String key = entry.getKey();
      Object value = entry.getValue();

      // we should not add headers for the parameters in the uri if we bridge the endpoint
      // as then we would duplicate headers on both the endpoint uri, and in HTTP headers as well
      if (skipRequestHeaders != null && skipRequestHeaders.containsKey(key)) {
        continue;
      }

      // use an iterator as there can be multiple values. (must not use a delimiter)
      final Iterator<?> it = ObjectHelper.createIterator(value, null, true);
      while (it.hasNext()) {
        String headerValue = tc.convertTo(String.class, it.next());

        if (headerValue != null
            && headerFilterStrategy != null
            && !headerFilterStrategy.applyFilterToCamelHeaders(
                key, headerValue, message.getExchange())) {
          LOG.trace("HTTP-Header: {}={}", key, headerValue);
          request.headers().add(key, headerValue);
        }
      }
    }

    Object body = message.getBody();
    if (body != null) {
      // support bodies as native Netty
      ChannelBuffer buffer;
      if (body instanceof ChannelBuffer) {
        buffer = (ChannelBuffer) body;
      } else {
        // try to convert to buffer first
        buffer = message.getBody(ChannelBuffer.class);
        if (buffer == null) {
          // fallback to byte array as last resort
          byte[] data = message.getMandatoryBody(byte[].class);
          buffer = ChannelBuffers.copiedBuffer(data);
        }
      }
      if (buffer != null) {
        request.setContent(buffer);
        int len = buffer.readableBytes();
        // set content-length
        request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, len);
        LOG.trace("Content-Length: {}", len);
      } else {
        // we do not support this kind of body
        throw new NoTypeConversionAvailableException(body, ChannelBuffer.class);
      }
    }

    // update HTTP method accordingly as we know if we have a body or not
    HttpMethod method = NettyHttpHelper.createMethod(message, body != null);
    request.setMethod(method);

    // set the content type in the response.
    String contentType = MessageHelper.getContentType(message);
    if (contentType != null) {
      // set content-type
      request.headers().set(HttpHeaders.Names.CONTENT_TYPE, contentType);
      LOG.trace("Content-Type: {}", contentType);
    }

    // must include HOST header as required by HTTP 1.1
    // use URI as its faster than URL (no DNS lookup)
    URI u = new URI(uri);
    String host = u.getHost();
    request.headers().set(HttpHeaders.Names.HOST, host);
    LOG.trace("Host: {}", host);

    // configure connection to accordingly to keep alive configuration
    // favor using the header from the message
    String connection = message.getHeader(HttpHeaders.Names.CONNECTION, String.class);
    if (connection == null) {
      // fallback and use the keep alive from the configuration
      if (configuration.isKeepAlive()) {
        connection = HttpHeaders.Values.KEEP_ALIVE;
      } else {
        connection = HttpHeaders.Values.CLOSE;
      }
    }
    request.headers().set(HttpHeaders.Names.CONNECTION, connection);
    LOG.trace("Connection: {}", connection);
    return request;
  }
  @Override
  public HttpResponse toNettyResponse(Message message, NettyHttpConfiguration configuration)
      throws Exception {
    LOG.trace("toNettyResponse: {}", message);

    // the message body may already be a Netty HTTP response
    if (message.getBody() instanceof HttpResponse) {
      return (HttpResponse) message.getBody();
    }

    // the response code is 200 for OK and 500 for failed
    boolean failed = message.getExchange().isFailed();
    int defaultCode = failed ? 500 : 200;

    int code = message.getHeader(Exchange.HTTP_RESPONSE_CODE, defaultCode, int.class);
    HttpResponse response =
        new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(code));
    LOG.trace("HTTP Status Code: {}", code);

    TypeConverter tc = message.getExchange().getContext().getTypeConverter();

    // append headers
    // must use entrySet to ensure case of keys is preserved
    for (Map.Entry<String, Object> entry : message.getHeaders().entrySet()) {
      String key = entry.getKey();
      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);
      while (it.hasNext()) {
        String headerValue = tc.convertTo(String.class, it.next());
        if (headerValue != null
            && headerFilterStrategy != null
            && !headerFilterStrategy.applyFilterToCamelHeaders(
                key, headerValue, message.getExchange())) {
          LOG.trace("HTTP-Header: {}={}", key, headerValue);
          response.headers().add(key, headerValue);
        }
      }
    }

    Object body = message.getBody();
    Exception cause = message.getExchange().getException();
    // support bodies as native Netty
    ChannelBuffer buffer;

    // if there was an exception then use that as body
    if (cause != null) {
      if (configuration.isTransferException()) {
        // we failed due an exception, and transfer it as java serialized object
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(cause);
        oos.flush();
        IOHelper.close(oos, bos);

        // the body should be the serialized java object of the exception
        body = ChannelBuffers.copiedBuffer(bos.toByteArray());
        // force content type to be serialized java object
        message.setHeader(
            Exchange.CONTENT_TYPE, NettyHttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT);
      } else {
        // we failed due an exception so print it as plain text
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        cause.printStackTrace(pw);

        // the body should then be the stacktrace
        body = ChannelBuffers.copiedBuffer(sw.toString().getBytes());
        // 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());
    }

    if (body instanceof ChannelBuffer) {
      buffer = (ChannelBuffer) body;
    } else {
      // try to convert to buffer first
      buffer = message.getBody(ChannelBuffer.class);
      if (buffer == null) {
        // fallback to byte array as last resort
        byte[] data = message.getBody(byte[].class);
        if (data != null) {
          buffer = ChannelBuffers.copiedBuffer(data);
        } else {
          // and if byte array fails then try String
          String str;
          if (body != null) {
            str = message.getMandatoryBody(String.class);
          } else {
            str = "";
          }
          buffer = ChannelBuffers.copiedBuffer(str.getBytes());
        }
      }
    }
    if (buffer != null) {
      response.setContent(buffer);
      // We just need to reset the readerIndex this time
      if (buffer.readerIndex() == buffer.writerIndex()) {
        buffer.setIndex(0, buffer.writerIndex());
      }
      // TODO How to enable the chunk transport
      int len = buffer.readableBytes();
      // set content-length
      response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, len);
      LOG.trace("Content-Length: {}", len);
    }

    // set the content type in the response.
    String contentType = MessageHelper.getContentType(message);
    if (contentType != null) {
      // set content-type
      response.headers().set(HttpHeaders.Names.CONTENT_TYPE, contentType);
      LOG.trace("Content-Type: {}", contentType);
    }

    // configure connection to accordingly to keep alive configuration
    // favor using the header from the message
    String connection = message.getHeader(HttpHeaders.Names.CONNECTION, String.class);
    // Read the connection header from the exchange property
    if (connection == null) {
      connection = message.getExchange().getProperty(HttpHeaders.Names.CONNECTION, String.class);
    }
    if (connection == null) {
      // fallback and use the keep alive from the configuration
      if (configuration.isKeepAlive()) {
        connection = HttpHeaders.Values.KEEP_ALIVE;
      } else {
        connection = HttpHeaders.Values.CLOSE;
      }
    }
    response.headers().set(HttpHeaders.Names.CONNECTION, connection);
    // Just make sure we close the channel when the connection value is close
    if (connection.equalsIgnoreCase(HttpHeaders.Values.CLOSE)) {
      message.setHeader(NettyConstants.NETTY_CLOSE_CHANNEL_WHEN_COMPLETE, true);
    }
    LOG.trace("Connection: {}", connection);

    return response;
  }
Esempio n. 17
0
 public void testGetContentType() throws Exception {
   message.setHeader(Exchange.CONTENT_TYPE, "text/xml");
   assertEquals("text/xml", MessageHelper.getContentType(message));
 }
  /** All redelivery attempts failed so move the exchange to the dead letter queue */
  protected boolean deliverToFailureProcessor(
      final Processor processor,
      final Exchange exchange,
      final RedeliveryData data,
      final AsyncCallback callback) {
    boolean sync = true;

    Exception caught = exchange.getException();

    // we did not success with the redelivery so now we let the failure processor handle it
    // clear exception as we let the failure processor handle it
    exchange.setException(null);

    boolean handled = false;
    // regard both handled or continued as being handled
    if (shouldHandled(exchange, data) || shouldContinue(exchange, data)) {
      // its handled then remove traces of redelivery attempted
      exchange.getIn().removeHeader(Exchange.REDELIVERED);
      exchange.getIn().removeHeader(Exchange.REDELIVERY_COUNTER);
      exchange.getIn().removeHeader(Exchange.REDELIVERY_MAX_COUNTER);
      handled = true;
    } else {
      // must decrement the redelivery counter as we didn't process the redelivery but is
      // handling by the failure handler. So we must -1 to not let the counter be out-of-sync
      decrementRedeliveryCounter(exchange);
    }

    // is the a failure processor to process the Exchange
    if (processor != null) {

      // prepare original IN body if it should be moved instead of current body
      if (data.useOriginalInMessage) {
        log.trace("Using the original IN message instead of current");
        Message original = exchange.getUnitOfWork().getOriginalInMessage();
        exchange.setIn(original);
        if (exchange.hasOut()) {
          log.trace("Removing the out message to avoid some uncertain behavior");
          exchange.setOut(null);
        }
      }

      // reset cached streams so they can be read again
      MessageHelper.resetStreamCache(exchange.getIn());

      log.trace("Failure processor {} is processing Exchange: {}", processor, exchange);

      // store the last to endpoint as the failure endpoint
      exchange.setProperty(Exchange.FAILURE_ENDPOINT, exchange.getProperty(Exchange.TO_ENDPOINT));

      // the failure processor could also be asynchronous
      AsyncProcessor afp = AsyncProcessorTypeConverter.convert(processor);
      sync =
          AsyncProcessorHelper.process(
              afp,
              exchange,
              new AsyncCallback() {
                public void done(boolean sync) {
                  log.trace(
                      "Failure processor done: {} processing Exchange: {}", processor, exchange);
                  try {
                    prepareExchangeAfterFailure(exchange, data);
                    // fire event as we had a failure processor to handle it, which there is a event
                    // for
                    boolean deadLetterChannel =
                        processor == data.deadLetterProcessor && data.deadLetterProcessor != null;
                    EventHelper.notifyExchangeFailureHandled(
                        exchange.getContext(), exchange, processor, deadLetterChannel);
                  } finally {
                    // if the fault was handled asynchronously, this should be reflected in the
                    // callback as well
                    data.sync &= sync;
                    callback.done(data.sync);
                  }
                }
              });
    } else {
      try {
        // no processor but we need to prepare after failure as well
        prepareExchangeAfterFailure(exchange, data);
      } finally {
        // callback we are done
        callback.done(data.sync);
      }
    }

    // create log message
    String msg = "Failed delivery for exchangeId: " + exchange.getExchangeId();
    msg =
        msg
            + ". Exhausted after delivery attempt: "
            + data.redeliveryCounter
            + " caught: "
            + caught;
    if (processor != null) {
      msg = msg + ". Processed by failure processor: " + processor;
    }

    // log that we failed delivery as we are exhausted
    logFailedDelivery(false, handled, false, exchange, msg, data, null);

    return sync;
  }
Esempio n. 19
0
 public void testGetContentEncpding() throws Exception {
   message.setHeader(Exchange.CONTENT_ENCODING, "iso-8859-1");
   assertEquals("iso-8859-1", MessageHelper.getContentEncoding(message));
 }
  @Override
  public boolean process(Exchange exchange, final AsyncCallback callback) {
    if (enableCORS) {
      exchange.addOnCompletion(new RestBindingCORSOnCompletion(corsHeaders));
    }

    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");
    }
    // if content type could not tell us if it was json or xml, then fallback to if the binding was
    // configured with
    // 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");
    }

    // 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");
    }

    String accept = exchange.getIn().getHeader("Accept", String.class);

    String body = null;
    if (exchange.getIn().getBody() != null) {

      // okay we have a binding mode, so need to check for empty body as that can cause the
      // marshaller to fail
      // 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) {
          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;
          }
        }
      }
    }

    // favor json over xml
    if (isJson && jsonUnmarshal != null) {
      // add reverse operation
      exchange.addOnCompletion(
          new RestBindingMarshalOnCompletion(
              exchange.getFromRouteId(), jsonMarshal, xmlMarshal, false, accept));
      if (ObjectHelper.isNotEmpty(body)) {
        return jsonUnmarshal.process(exchange, callback);
      } else {
        callback.done(true);
        return true;
      }
    } else if (isXml && xmlUnmarshal != null) {
      // add reverse operation
      exchange.addOnCompletion(
          new RestBindingMarshalOnCompletion(
              exchange.getFromRouteId(), jsonMarshal, xmlMarshal, true, accept));
      if (ObjectHelper.isNotEmpty(body)) {
        return xmlUnmarshal.process(exchange, callback);
      } else {
        callback.done(true);
        return true;
      }
    }

    // we could not bind
    if (bindingMode == null || "off".equals(bindingMode) || bindingMode.equals("auto")) {
      // okay for auto we do not mind if we could not bind
      exchange.addOnCompletion(
          new RestBindingMarshalOnCompletion(
              exchange.getFromRouteId(), jsonMarshal, xmlMarshal, false, accept));
      callback.done(true);
      return true;
    } 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));
      }
      callback.done(true);
      return true;
    }
  }