Пример #1
0
  /** {@inheritDoc} */
  @Override
  public void mapFrom(CamelBindingData source, Context context) throws Exception {
    Message message = source.getMessage();
    Exchange exchange = message.getExchange();

    for (Map.Entry<String, Object> header : message.getHeaders().entrySet()) {
      String name = header.getKey();
      if (matches(name) && !name.startsWith("org.switchyard.bus.camel")) {
        Object value = header.getValue();
        if (value != null) {
          context.setProperty(name, value, Scope.MESSAGE).addLabels(getCamelLabels());
        }
      }
    }
    if (exchange != null) {
      for (Map.Entry<String, Object> property : exchange.getProperties().entrySet()) {
        String name = property.getKey();
        if (matches(name) && !name.startsWith("org.switchyard.bus.camel")) {
          Object value = property.getValue();
          if (value != null) {
            context.setProperty(name, value, Scope.EXCHANGE).addLabels(getCamelLabels());
          }
        }
      }
    }
  }
Пример #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);
  }
Пример #3
0
  /**
   * Creates a JMS message from the Camel exchange and message
   *
   * @param exchange the current exchange
   * @param camelMessage the body to make a javax.jms.Message as
   * @param session the JMS session used to create the message
   * @param cause optional exception occurred that should be sent as reply instead of a regular body
   * @return a newly created JMS Message instance containing the
   * @throws JMSException if the message could not be created
   */
  public Message makeJmsMessage(
      Exchange exchange, org.apache.camel.Message camelMessage, Session session, Exception cause)
      throws JMSException {
    Message answer = null;

    boolean alwaysCopy = endpoint != null && endpoint.getConfiguration().isAlwaysCopyMessage();
    boolean force = endpoint != null && endpoint.getConfiguration().isForceSendOriginalMessage();
    if (!alwaysCopy && camelMessage instanceof JmsMessage) {
      JmsMessage jmsMessage = (JmsMessage) camelMessage;
      if (!jmsMessage.shouldCreateNewMessage() || force) {
        answer = jmsMessage.getJmsMessage();

        if (!force) {
          // answer must match endpoint type
          JmsMessageType type =
              endpoint != null ? endpoint.getConfiguration().getJmsMessageType() : null;
          if (type != null && answer != null) {
            if (type == JmsMessageType.Text) {
              answer = answer instanceof TextMessage ? answer : null;
            } else if (type == JmsMessageType.Bytes) {
              answer = answer instanceof BytesMessage ? answer : null;
            } else if (type == JmsMessageType.Map) {
              answer = answer instanceof MapMessage ? answer : null;
            } else if (type == JmsMessageType.Object) {
              answer = answer instanceof ObjectMessage ? answer : null;
            } else if (type == JmsMessageType.Stream) {
              answer = answer instanceof StreamMessage ? answer : null;
            }
          }
        }
      }
    }

    if (answer == null) {
      if (cause != null) {
        // an exception occurred so send it as response
        LOG.debug("Will create JmsMessage with caused exception: {}", cause);
        // create jms message containing the caused exception
        answer = createJmsMessage(cause, session);
      } else {
        ObjectHelper.notNull(camelMessage, "message");
        // create regular jms message using the camel message body
        answer =
            createJmsMessage(
                exchange,
                camelMessage.getBody(),
                camelMessage.getHeaders(),
                session,
                exchange.getContext());
        appendJmsProperties(answer, exchange, camelMessage);
      }
    }

    if (answer != null && messageCreatedStrategy != null) {
      messageCreatedStrategy.onMessageCreated(answer, session, exchange, null);
    }
    return answer;
  }
Пример #4
0
 /** Appends the JMS headers from the Camel {@link JmsMessage} */
 public void appendJmsProperties(
     Message jmsMessage, Exchange exchange, org.apache.camel.Message in) throws JMSException {
   Set<Map.Entry<String, Object>> entries = in.getHeaders().entrySet();
   for (Map.Entry<String, Object> entry : entries) {
     String headerName = entry.getKey();
     Object headerValue = entry.getValue();
     appendJmsProperty(jmsMessage, exchange, in, headerName, headerValue);
   }
 }
Пример #5
0
 private Map<String, Object> getServiceParameters(Message in) {
   Map<String, Object> serviceParams = new HashMap<String, Object>();
   for (Map.Entry<String, Object> entry : in.getHeaders().entrySet()) {
     if (entry.getKey().startsWith(PARAM_PREFIX)) {
       String paramName = entry.getKey().substring(PARAM_PREFIX.length());
       serviceParams.put(paramName, entry.getValue());
     }
   }
   return serviceParams;
 }
Пример #6
0
  /**
   * Copies the headers from the source to the target message.
   *
   * @param source the source message
   * @param target the target message
   * @param override whether to override existing headers
   */
  public static void copyHeaders(Message source, Message target, boolean override) {
    if (!source.hasHeaders()) {
      return;
    }

    for (Map.Entry<String, Object> entry : source.getHeaders().entrySet()) {
      String key = entry.getKey();
      Object value = entry.getValue();

      if (target.getHeader(key) == null || override) {
        target.setHeader(key, value);
      }
    }
  }
  @Converter
  public static org.springframework.integration.Message<?> toSpringMessage(
      final org.apache.camel.Message camelMessage) throws Exception {
    if (camelMessage instanceof SpringIntegrationMessage) {
      SpringIntegrationMessage siMessage = (SpringIntegrationMessage) camelMessage;
      org.springframework.integration.Message<?> message = siMessage.getMessage();
      if (message != null) {
        return message;
      }
    }

    // Create a new spring message and copy the attributes and body from the camel message
    MessageHeaders messageHeaders = new MessageHeaders(camelMessage.getHeaders());
    return new GenericMessage<Object>(camelMessage.getBody(), messageHeaders);
  }
Пример #8
0
  private void processResponse(
      Exchange exchange, Object body, SalesforceException ex, AsyncCallback callback) {
    final Message out = exchange.getOut();
    if (ex != null) {
      exchange.setException(ex);
    } else {
      out.setBody(body);
    }

    // copy headers and attachments
    out.getHeaders().putAll(exchange.getIn().getHeaders());
    out.getAttachments().putAll(exchange.getIn().getAttachments());

    // signal exchange completion
    callback.done(false);
  }
Пример #9
0
  public void testCopyFromSameHeadersInstance() {
    Exchange exchange = new DefaultExchange(context);

    Message in = exchange.getIn();
    Map<String, Object> headers = in.getHeaders();
    headers.put("foo", 123);

    Message out = new DefaultMessage();
    out.setBody("Bye World");
    out.setHeaders(headers);

    out.copyFrom(in);

    assertEquals(123, headers.get("foo"));
    assertEquals(123, in.getHeader("foo"));
    assertEquals(123, out.getHeader("foo"));
  }
  public void testUsingCustomExceptionHandlerWithNoRedeliveries() throws Exception {
    b.expectedMessageCount(1);

    sendBody("direct:start", "b");

    MockEndpoint.assertIsSatisfied(a, b);

    List<Exchange> list = b.getReceivedExchanges();
    assertTrue("List should not be empty!", !list.isEmpty());
    Exchange exchange = list.get(0);
    Message in = exchange.getIn();
    log.info("Found message with headers: " + in.getHeaders());

    assertMessageHeader(in, Exchange.REDELIVERY_COUNTER, 0);
    assertMessageHeader(in, Exchange.REDELIVERY_MAX_COUNTER, null);
    assertMessageHeader(in, Exchange.REDELIVERED, false);
  }
Пример #11
0
  public void save2DB(Exchange exchange) {

    CompositeMap header = new CompositeMap("result");

    header.put("businessModelName", businessModel.getName());
    String body = exchange.getIn().getBody(String.class);
    header.setText(body);

    try {
      CompositeMap executeProc = esbContext.executeProc("save_data", header);
      System.out.println("save2DB");
      Message inin = exchange.getIn();
      exchange.getOut().setHeaders(inin.getHeaders());
      exchange.getOut().setBody(body);

    } catch (Exception e) {
      e.printStackTrace();
      exchange.getOut().setFault(true);
    }
  }
  public void process(Exchange exchange) throws Exception {
    // System.out.println(exchange.getIn().getBody());
    Message message = exchange.getIn();
    Object payload = message.getBody();
    Map<String, Object> headers = message.getHeaders();

    String destination = endpoint.getDestination();
    String destinationSuffix =
        getHeader(headers, SpringSimpleMessagingConstants.DESTINATION_SUFFIX);
    String user = getHeader(headers, SpringSimpleMessagingConstants.USER);

    if (destinationSuffix != null) {
      destination = destination.concat(destinationSuffix);
      message.removeHeader(SpringSimpleMessagingConstants.DESTINATION_SUFFIX);
    }

    if (user != null) {
      message.removeHeader(SpringSimpleMessagingConstants.USER);
    }

    if (LOG.isDebugEnabled()) {
      try {
        LOG.debug(
            "sending message: {\"destination\":{}, \"payload\":{}, \"headers\":{}, \"user\":{}}",
            destination,
            payload,
            new JSONObject(headers),
            user);
      } catch (Exception e) {
        LOG.error("error trying to log body or header: {}", e.getMessage());
      }
    }

    if (user == null) {
      endpoint.getMessageSendingOperations().convertAndSend(destination, payload, headers);
    } else {
      endpoint
          .getMessageSendingOperations()
          .convertAndSendToUser(user, destination, payload, headers);
    }
  }
Пример #13
0
  @Test
  public void testEndpoint() throws Exception {
    mockEndpoint.reset();
    mockEndpoint.expectedBodiesReceived(expectedBody);

    template.sendBodyAndHeader(
        "https://localhost:" + port + "/test", expectedBody, "Content-Type", "application/xml");

    mockEndpoint.assertIsSatisfied();
    List<Exchange> list = mockEndpoint.getReceivedExchanges();
    Exchange exchange = list.get(0);
    TestSupport.assertNotNull("exchange", exchange);

    Message in = exchange.getIn();
    assertNotNull("in", in);

    Map<String, Object> headers = in.getHeaders();

    log.info("Headers: " + headers);

    assertTrue("Should be more than one header but was: " + headers, headers.size() > 0);
  }
Пример #14
0
  @Override
  public void copyFrom(org.apache.camel.Message that) {
    // must initialize headers before we set the JmsMessage to avoid Camel
    // populating it before we do the copy
    getHeaders().clear();

    boolean copyMessageId = true;
    if (that instanceof JmsMessage) {
      JmsMessage thatMessage = (JmsMessage) that;
      this.jmsMessage = thatMessage.jmsMessage;
      if (this.jmsMessage != null) {
        // for performance lets not copy the messageID if we are a JMS message
        copyMessageId = false;
      }
    }

    if (copyMessageId) {
      setMessageId(that.getMessageId());
    }
    setBody(that.getBody());
    getHeaders().putAll(that.getHeaders());
    getAttachments().putAll(that.getAttachments());
  }
Пример #15
0
  /**
   * Creates a JMS message from the Camel exchange and message
   *
   * @param exchange the current exchange
   * @param camelMessage the body to make a javax.jms.Message as
   * @param session the JMS session used to create the message
   * @param cause optional exception occurred that should be sent as reply instead of a regular body
   * @return a newly created JMS Message instance containing the
   * @throws JMSException if the message could not be created
   */
  public Message makeJmsMessage(
      Exchange exchange, org.apache.camel.Message camelMessage, Session session, Exception cause)
      throws JMSException {
    Message answer = null;

    boolean alwaysCopy = endpoint != null && endpoint.getConfiguration().isAlwaysCopyMessage();
    boolean force = endpoint != null && endpoint.getConfiguration().isForceSendOriginalMessage();
    if (!alwaysCopy && camelMessage instanceof JmsMessage) {
      JmsMessage jmsMessage = (JmsMessage) camelMessage;
      if (!jmsMessage.shouldCreateNewMessage() || force) {
        answer = jmsMessage.getJmsMessage();
      }
    }

    if (answer == null) {
      if (cause != null) {
        // an exception occurred so send it as response
        LOG.debug("Will create JmsMessage with caused exception: {}", cause);
        // create jms message containing the caused exception
        answer = createJmsMessage(cause, session);
      } else {
        ObjectHelper.notNull(camelMessage, "message");
        // create regular jms message using the camel message body
        answer =
            createJmsMessage(
                exchange,
                camelMessage.getBody(),
                camelMessage.getHeaders(),
                session,
                exchange.getContext());
        appendJmsProperties(answer, exchange, camelMessage);
      }
    }

    return answer;
  }
Пример #16
0
  @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;
  }
Пример #17
0
  @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;
  }
  public AMQP.BasicProperties.Builder buildProperties(Exchange exchange) {
    AMQP.BasicProperties.Builder properties = new AMQP.BasicProperties.Builder();

    Message msg;
    if (exchange.hasOut()) {
      msg = exchange.getOut();
    } else {
      msg = exchange.getIn();
    }

    final Object contentType = msg.removeHeader(RabbitMQConstants.CONTENT_TYPE);
    if (contentType != null) {
      properties.contentType(contentType.toString());
    }

    final Object priority = msg.removeHeader(RabbitMQConstants.PRIORITY);
    if (priority != null) {
      properties.priority(Integer.parseInt(priority.toString()));
    }

    final Object messageId = msg.removeHeader(RabbitMQConstants.MESSAGE_ID);
    if (messageId != null) {
      properties.messageId(messageId.toString());
    }

    final Object clusterId = msg.removeHeader(RabbitMQConstants.CLUSTERID);
    if (clusterId != null) {
      properties.clusterId(clusterId.toString());
    }

    final Object replyTo = msg.removeHeader(RabbitMQConstants.REPLY_TO);
    if (replyTo != null) {
      properties.replyTo(replyTo.toString());
    }

    final Object correlationId = msg.removeHeader(RabbitMQConstants.CORRELATIONID);
    if (correlationId != null) {
      properties.correlationId(correlationId.toString());
    }

    final Object deliveryMode = msg.removeHeader(RabbitMQConstants.DELIVERY_MODE);
    if (deliveryMode != null) {
      properties.deliveryMode(Integer.parseInt(deliveryMode.toString()));
    }

    final Object userId = msg.removeHeader(RabbitMQConstants.USERID);
    if (userId != null) {
      properties.userId(userId.toString());
    }

    final Object type = msg.removeHeader(RabbitMQConstants.TYPE);
    if (type != null) {
      properties.type(type.toString());
    }

    final Object contentEncoding = msg.removeHeader(RabbitMQConstants.CONTENT_ENCODING);
    if (contentEncoding != null) {
      properties.contentEncoding(contentEncoding.toString());
    }

    final Object expiration = msg.removeHeader(RabbitMQConstants.EXPIRATION);
    if (expiration != null) {
      properties.expiration(expiration.toString());
    }

    final Object appId = msg.removeHeader(RabbitMQConstants.APP_ID);
    if (appId != null) {
      properties.appId(appId.toString());
    }

    final Object timestamp = msg.removeHeader(RabbitMQConstants.TIMESTAMP);
    if (timestamp != null) {
      properties.timestamp(convertTimestamp(timestamp));
    }

    final Map<String, Object> headers = msg.getHeaders();
    Map<String, Object> filteredHeaders = new HashMap<>();

    // TODO: Add support for a HeaderFilterStrategy. See:
    // org.apache.camel.component.jms.JmsBinding#shouldOutputHeader
    for (Map.Entry<String, Object> header : headers.entrySet()) {
      // filter header values.
      Object value = getValidRabbitMQHeaderValue(header.getValue());
      if (value != null) {
        filteredHeaders.put(header.getKey(), header.getValue());
      } else if (LOG.isDebugEnabled()) {
        if (header.getValue() == null) {
          LOG.debug("Ignoring header: {} with null value", header.getKey());
        } else {
          LOG.debug(
              "Ignoring header: {} of class: {} with value: {}",
              header.getKey(),
              ObjectHelper.classCanonicalName(header.getValue()),
              header.getValue());
        }
      }
    }

    properties.headers(filteredHeaders);

    return properties;
  }
Пример #19
0
  /**
   * @param cxfMessage
   * @param camelMessage
   * @param exchange provides context for filtering
   */
  protected void propagateHeadersFromCxfToCamel(
      Message cxfMessage, org.apache.camel.Message camelMessage, Exchange exchange) {
    Map<String, List<String>> cxfHeaders =
        CastUtils.cast((Map<?, ?>) cxfMessage.get(Message.PROTOCOL_HEADERS));
    Map<String, Object> camelHeaders = camelMessage.getHeaders();
    camelHeaders.put(CxfConstants.CAMEL_CXF_MESSAGE, cxfMessage);

    // Copy the http header to CAMEL as we do in camel-cxfrs
    CxfUtils.copyHttpHeadersFromCxfToCamel(cxfMessage, camelMessage);

    if (cxfHeaders != null) {
      for (Map.Entry<String, List<String>> entry : cxfHeaders.entrySet()) {
        if (!headerFilterStrategy.applyFilterToExternalHeaders(
            entry.getKey(), entry.getValue(), exchange)) {
          // We need to filter the content type with multi-part,
          // as the multi-part stream is already consumed by AttachmentInInterceptor,
          // it will cause some trouble when route this message to another CXF endpoint.

          if ("Content-Type".compareToIgnoreCase(entry.getKey()) == 0
              && entry.getValue().get(0) != null
              && entry.getValue().get(0).startsWith("multipart/related")) {
            // We need to keep the Content-Type if the data format is RAW message
            DataFormat dataFormat =
                exchange.getProperty(CxfConstants.DATA_FORMAT_PROPERTY, DataFormat.class);
            if (dataFormat.equals(DataFormat.RAW)) {
              camelHeaders.put(entry.getKey(), getContentTypeString(entry.getValue()));
            } else {
              String contentType = replaceMultiPartContentType(entry.getValue().get(0));
              LOG.trace("Find the multi-part Conent-Type, and replace it with {}", contentType);
              camelHeaders.put(entry.getKey(), contentType);
            }
          } else {
            LOG.trace(
                "Populate header from CXF header={} value={}", entry.getKey(), entry.getValue());
            List<String> values = entry.getValue();
            Object evalue;
            if (values.size() > 1) {
              if (exchange.getProperty(
                  CxfConstants.CAMEL_CXF_PROTOCOL_HEADERS_MERGED, Boolean.FALSE, Boolean.class)) {
                StringBuilder sb = new StringBuilder();
                for (Iterator<String> it = values.iterator(); it.hasNext(); ) {
                  sb.append(it.next());
                  if (it.hasNext()) {
                    sb.append(',').append(' ');
                  }
                }
                evalue = sb.toString();
              } else {
                evalue = values;
              }
            } else {
              evalue = values.get(0);
            }
            camelHeaders.put(entry.getKey(), evalue);
          }
        }
      }
    }

    // propagate SOAP/protocol header list
    String key = Header.HEADER_LIST;
    Object value = cxfMessage.get(key);
    if (value != null) {
      if (!headerFilterStrategy.applyFilterToExternalHeaders(key, value, exchange)) {
        camelHeaders.put(key, value);
        LOG.trace("Populate header from CXF header={} value={}", key, value);
      } else {
        ((List<?>) value).clear();
      }
    }

    // propagate the SOAPAction header
    String soapAction = (String) camelHeaders.get(SoapBindingConstants.SOAP_ACTION);
    // Remove SOAPAction from the protocol header, as it will not be overrided
    if (ObjectHelper.isEmpty(soapAction) || "\"\"".equals(soapAction)) {
      camelHeaders.remove(SoapBindingConstants.SOAP_ACTION);
    }
    soapAction = (String) cxfMessage.get(SoapBindingConstants.SOAP_ACTION);
    if (soapAction != null) {
      if (!headerFilterStrategy.applyFilterToExternalHeaders(
          SoapBindingConstants.SOAP_ACTION, soapAction, exchange)) {
        camelHeaders.put(SoapBindingConstants.SOAP_ACTION, soapAction);
        LOG.trace(
            "Populate header from CXF header={} value={}",
            SoapBindingConstants.SOAP_ACTION,
            soapAction);
      }
    }
  }
Пример #20
0
  public void process(Exchange exchange) throws Exception {
    // 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 (getEndpoint().isBridgeEndpoint()) {
      exchange.setProperty(Exchange.SKIP_GZIP_ENCODING, Boolean.TRUE);
      String queryString = exchange.getIn().getHeader(Exchange.HTTP_QUERY, String.class);
      if (queryString != null) {
        skipRequestHeaders = URISupport.parseQuery(queryString);
      }
      // Need to remove the Host key as it should be not used
      exchange.getIn().getHeaders().remove("host");
    }
    HttpMethod method = createMethod(exchange);
    Message in = exchange.getIn();
    String httpProtocolVersion = in.getHeader(Exchange.HTTP_PROTOCOL_VERSION, String.class);
    if (httpProtocolVersion != null) {
      // set the HTTP protocol version
      HttpMethodParams params = method.getParams();
      params.setVersion(HttpVersion.parse(httpProtocolVersion));
    }

    HeaderFilterStrategy strategy = getEndpoint().getHeaderFilterStrategy();

    // propagate headers as HTTP headers
    for (Map.Entry<String, Object> entry : in.getHeaders().entrySet()) {
      String key = entry.getKey();
      Object headerValue = in.getHeader(key);

      if (headerValue != null) {
        // use an iterator as there can be multiple values. (must not use a delimiter, and allow
        // empty values)
        final Iterator<?> it = ObjectHelper.createIterator(headerValue, null, true);

        // the value to add as request header
        final List<String> values = new ArrayList<String>();

        // if its a multi value then check each value if we can add it and for multi values they
        // should be combined into a single value
        while (it.hasNext()) {
          String value =
              exchange.getContext().getTypeConverter().convertTo(String.class, it.next());

          // 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;
          }
          if (value != null
              && strategy != null
              && !strategy.applyFilterToCamelHeaders(key, value, exchange)) {
            values.add(value);
          }
        }

        // add the value(s) as a http request header
        if (values.size() > 0) {
          // use the default toString of a ArrayList to create in the form [xxx, yyy]
          // if multi valued, for a single value, then just output the value as is
          String s = values.size() > 1 ? values.toString() : values.get(0);
          method.addRequestHeader(key, s);
        }
      }
    }

    // lets store the result in the output message.
    try {
      if (LOG.isDebugEnabled()) {
        LOG.debug("Executing http {} method: {}", method.getName(), method.getURI().toString());
      }
      int responseCode = executeMethod(method);
      LOG.debug("Http responseCode: {}", responseCode);

      if (!throwException) {
        // if we do not use failed exception then populate response for all response codes
        populateResponse(exchange, method, in, strategy, responseCode);
      } else {
        if (responseCode >= 100 && responseCode < 300) {
          // only populate response for OK response
          populateResponse(exchange, method, in, strategy, responseCode);
        } else {
          // operation failed so populate exception to throw
          throw populateHttpOperationFailedException(exchange, method, responseCode);
        }
      }
    } finally {
      method.releaseConnection();
    }
  }
Пример #21
0
  /**
   * This method is called by {@link CxfConsumer} to populate a CXF response exchange from a Camel
   * exchange.
   */
  public void populateCxfResponseFromExchange(
      Exchange camelExchange, org.apache.cxf.message.Exchange cxfExchange) {

    if (cxfExchange.isOneWay()) {
      return;
    }

    // create response context
    Map<String, Object> responseContext = new HashMap<String, Object>();

    org.apache.camel.Message response;
    if (camelExchange.getPattern().isOutCapable()) {
      if (camelExchange.hasOut()) {
        response = camelExchange.getOut();
        LOG.trace("Get the response from the out message");
      } else { // Take the in message as a fall back
        response = camelExchange.getIn();
        LOG.trace("Get the response from the in message as a fallback");
      }
    } else {
      response = camelExchange.getIn();
      LOG.trace("Get the response from the in message");
    }

    // propagate response context
    Map<String, Object> camelHeaders = response.getHeaders();
    extractInvocationContextFromCamel(
        camelExchange, camelHeaders, responseContext, Client.RESPONSE_CONTEXT);

    propagateHeadersFromCamelToCxf(camelExchange, camelHeaders, cxfExchange, responseContext);
    // create out message
    Endpoint ep = cxfExchange.get(Endpoint.class);
    Message outMessage = ep.getBinding().createMessage();
    cxfExchange.setOutMessage(outMessage);

    DataFormat dataFormat =
        camelExchange.getProperty(CxfConstants.DATA_FORMAT_PROPERTY, DataFormat.class);

    // make sure the "requestor role" property does not get propagated as we do switch role
    responseContext.remove(Message.REQUESTOR_ROLE);

    outMessage.putAll(responseContext);

    // Do we still need to put the response context back like this
    outMessage.put(Client.RESPONSE_CONTEXT, responseContext);

    LOG.trace("Set out response context = {}", responseContext);

    // set body
    Object outBody = DefaultCxfBinding.getBodyFromCamel(response, dataFormat);

    if (outBody != null) {
      if (dataFormat == DataFormat.PAYLOAD) {
        CxfPayload<?> payload = (CxfPayload<?>) outBody;
        outMessage.setContent(
            List.class, getResponsePayloadList(cxfExchange, payload.getBodySources()));
        outMessage.put(Header.HEADER_LIST, payload.getHeaders());
      } else {
        if (responseContext.get(Header.HEADER_LIST) != null) {
          outMessage.put(Header.HEADER_LIST, responseContext.get(Header.HEADER_LIST));
        }

        MessageContentsList resList = null;
        // Create a new MessageContentsList to avoid OOM from the HolderOutInterceptor
        if (outBody instanceof List) {
          resList = new MessageContentsList((List<?>) outBody);
        } else if (outBody.getClass().isArray()) {
          resList = new MessageContentsList((Object[]) outBody);
        } else {
          resList = new MessageContentsList(outBody);
        }

        if (resList != null) {
          outMessage.setContent(List.class, resList);
          LOG.trace("Set Out CXF message content = {}", resList);
        }
      }
    } else if (!cxfExchange.isOneWay()
        && cxfExchange.getInMessage() != null
        && MessageUtils.isTrue(
            cxfExchange
                .getInMessage()
                .getContextualProperty("jaxws.provider.interpretNullAsOneway"))) {
      // treat this non-oneway call as oneway when the provider returns a null
      changeToOneway(cxfExchange);
      return;
    }

    // propagate attachments

    Set<Attachment> attachments = null;
    boolean isXop = Boolean.valueOf(camelExchange.getProperty(Message.MTOM_ENABLED, String.class));
    for (Map.Entry<String, DataHandler> entry :
        camelExchange.getOut().getAttachments().entrySet()) {
      if (attachments == null) {
        attachments = new HashSet<Attachment>();
      }
      AttachmentImpl attachment = new AttachmentImpl(entry.getKey(), entry.getValue());
      attachment.setXOP(isXop);
      attachments.add(attachment);
    }

    if (attachments != null) {
      outMessage.setAttachments(attachments);
    }

    BindingOperationInfo boi = cxfExchange.get(BindingOperationInfo.class);
    if (boi != null) {
      cxfExchange.put(BindingMessageInfo.class, boi.getOutput());
    }
  }
Пример #22
0
  /** Sends the body that is on the exchange */
  public void publishExchangeToChannel(Exchange camelExchange, Channel channel, String routingKey)
      throws IOException {
    Message msg;
    if (camelExchange.hasOut()) {
      msg = camelExchange.getOut();
    } else {
      msg = camelExchange.getIn();
    }

    // Remove the SERIALIZE_HEADER in case it was previously set
    if (msg.getHeaders() != null && msg.getHeaders().containsKey(SERIALIZE_HEADER)) {
      LOG.debug("Removing the {} header", SERIALIZE_HEADER);
      msg.getHeaders().remove(SERIALIZE_HEADER);
    }

    AMQP.BasicProperties properties;
    byte[] body;
    try {
      // To maintain backwards compatibility try the TypeConverter (The DefaultTypeConverter seems
      // to only work on Strings)
      body =
          camelExchange
              .getContext()
              .getTypeConverter()
              .mandatoryConvertTo(byte[].class, camelExchange, msg.getBody());

      properties = getMessageConverter().buildProperties(camelExchange).build();
    } catch (NoTypeConversionAvailableException | TypeConversionException e) {
      if (msg.getBody() instanceof Serializable) {
        // Add the header so the reply processor knows to de-serialize it
        msg.getHeaders().put(SERIALIZE_HEADER, true);

        properties = getMessageConverter().buildProperties(camelExchange).build();

        try (ByteArrayOutputStream b = new ByteArrayOutputStream();
            ObjectOutputStream o = new ObjectOutputStream(b); ) {
          o.writeObject(msg.getBody());
          body = b.toByteArray();
        }
      } else if (msg.getBody() == null) {
        properties = getMessageConverter().buildProperties(camelExchange).build();
        body = null;
      } else {
        LOG.warn("Could not convert {} to byte[]", msg.getBody());
        throw new IOException(e);
      }
    }
    String rabbitExchange = getExchangeName(msg);

    Boolean mandatory =
        camelExchange.getIn().getHeader(RabbitMQConstants.MANDATORY, isMandatory(), Boolean.class);
    Boolean immediate =
        camelExchange.getIn().getHeader(RabbitMQConstants.IMMEDIATE, isImmediate(), Boolean.class);

    LOG.debug(
        "Sending message to exchange: {} with CorrelationId = {}",
        rabbitExchange,
        properties.getCorrelationId());

    channel.basicPublish(rabbitExchange, routingKey, mandatory, immediate, properties, body);
  }
Пример #23
0
  @SuppressWarnings({"unchecked"})
  protected DataSm createDataSm(Exchange exchange) {
    Message in = exchange.getIn();
    DataSm dataSm = new DataSm();

    if (in.getHeaders().containsKey(SmppConstants.DATA_CODING)) {
      dataSm.setDataCoding(in.getHeader(SmppConstants.DATA_CODING, java.lang.Byte.class));
    } else if (in.getHeaders().containsKey(SmppConstants.ALPHABET)) {
      dataSm.setDataCoding(in.getHeader(SmppConstants.ALPHABET, java.lang.Byte.class));
    } else {
      dataSm.setDataCoding(config.getDataCoding());
    }

    if (in.getHeaders().containsKey(SmppConstants.DEST_ADDR)) {
      dataSm.setDestAddress(in.getHeader(SmppConstants.DEST_ADDR, String.class));
    } else {
      dataSm.setDestAddress(config.getDestAddr());
    }

    if (in.getHeaders().containsKey(SmppConstants.DEST_ADDR_TON)) {
      dataSm.setDestAddrTon(in.getHeader(SmppConstants.DEST_ADDR_TON, java.lang.Byte.class));
    } else {
      dataSm.setDestAddrTon(config.getDestAddrTon());
    }

    if (in.getHeaders().containsKey(SmppConstants.DEST_ADDR_NPI)) {
      dataSm.setDestAddrNpi(in.getHeader(SmppConstants.DEST_ADDR_NPI, java.lang.Byte.class));
    } else {
      dataSm.setDestAddrNpi(config.getDestAddrNpi());
    }

    if (in.getHeaders().containsKey(SmppConstants.SOURCE_ADDR)) {
      dataSm.setSourceAddr(in.getHeader(SmppConstants.SOURCE_ADDR, String.class));
    } else {
      dataSm.setSourceAddr(config.getSourceAddr());
    }

    if (in.getHeaders().containsKey(SmppConstants.SOURCE_ADDR_TON)) {
      dataSm.setSourceAddrTon(in.getHeader(SmppConstants.SOURCE_ADDR_TON, java.lang.Byte.class));
    } else {
      dataSm.setSourceAddrTon(config.getSourceAddrTon());
    }

    if (in.getHeaders().containsKey(SmppConstants.SOURCE_ADDR_NPI)) {
      dataSm.setSourceAddrNpi(in.getHeader(SmppConstants.SOURCE_ADDR_NPI, java.lang.Byte.class));
    } else {
      dataSm.setSourceAddrNpi(config.getSourceAddrNpi());
    }

    if (in.getHeaders().containsKey(SmppConstants.SERVICE_TYPE)) {
      dataSm.setServiceType(in.getHeader(SmppConstants.SERVICE_TYPE, String.class));
    } else {
      dataSm.setServiceType(config.getServiceType());
    }

    if (in.getHeaders().containsKey(SmppConstants.REGISTERED_DELIVERY)) {
      dataSm.setRegisteredDelivery(
          in.getHeader(SmppConstants.REGISTERED_DELIVERY, java.lang.Byte.class));
    } else {
      dataSm.setRegisteredDelivery(config.getRegisteredDelivery());
    }

    /*
    Map<java.lang.Short, Object> optinalParamater = in.getHeader(SmppConstants.OPTIONAL_PARAMETER, Map.class);
    if (optinalParamater != null) {
        List<OptionalParameter> optParams = createOptionalParametersByCode(optinalParamater);
        dataSm.setOptionalParameters(optParams.toArray(new OptionalParameter[optParams.size()]));
    } else {
        Map<String, String> optinalParamaters = in.getHeader(SmppConstants.OPTIONAL_PARAMETERS, Map.class);
        if (optinalParamaters != null) {
            List<OptionalParameter> optParams = createOptionalParametersByName(optinalParamaters);
            dataSm.setOptionalParameters(optParams.toArray(new OptionalParameter[optParams.size()]));
        } else {
            dataSm.setOptionalParameters();
        }
    }
    */
    List<OptionalParameter> optParams = createOptionalParametersByHeaders(in.getHeaders());
    dataSm.setOptionalParameters(optParams.toArray(new OptionalParameter[optParams.size()]));

    return dataSm;
  }
Пример #24
0
  /**
   * Dumps the message as a generic XML structure.
   *
   * @param message the message
   * @param includeBody whether or not to include the message body
   * @param indent number of spaces to indent
   * @param allowStreams whether to include message body if they are stream based
   * @param allowFiles whether to include message body if they are file based
   * @param maxChars clip body after maximum chars (to avoid very big messages). Use 0 or negative
   *     value to not limit at all.
   * @return the XML
   */
  public static String dumpAsXml(
      Message message,
      boolean includeBody,
      int indent,
      boolean allowStreams,
      boolean allowFiles,
      int maxChars) {
    StringBuilder sb = new StringBuilder();

    StringBuilder prefix = new StringBuilder();
    for (int i = 0; i < indent; i++) {
      prefix.append(" ");
    }

    // include exchangeId as attribute on the <message> tag
    sb.append(prefix);
    sb.append("<message exchangeId=\"")
        .append(message.getExchange().getExchangeId())
        .append("\">\n");

    // headers
    if (message.hasHeaders()) {
      sb.append(prefix);
      sb.append("  <headers>\n");
      // sort the headers so they are listed A..Z
      Map<String, Object> headers = new TreeMap<String, Object>(message.getHeaders());
      for (Map.Entry<String, Object> entry : headers.entrySet()) {
        Object value = entry.getValue();
        String type = ObjectHelper.classCanonicalName(value);
        sb.append(prefix);
        sb.append("    <header key=\"").append(entry.getKey()).append("\"");
        if (type != null) {
          sb.append(" type=\"").append(type).append("\"");
        }
        sb.append(">");

        // dump header value as XML, use Camel type converter to convert
        // to String
        if (value != null) {
          try {
            String xml =
                message
                    .getExchange()
                    .getContext()
                    .getTypeConverter()
                    .convertTo(String.class, message.getExchange(), value);
            if (xml != null) {
              // must always xml encode
              sb.append(StringHelper.xmlEncode(xml));
            }
          } catch (Exception e) {
            // ignore as the body is for logging purpose
          }
        }

        sb.append("</header>\n");
      }
      sb.append(prefix);
      sb.append("  </headers>\n");
    }

    if (includeBody) {
      sb.append(prefix);
      sb.append("  <body");
      String type = ObjectHelper.classCanonicalName(message.getBody());
      if (type != null) {
        sb.append(" type=\"").append(type).append("\"");
      }
      sb.append(">");

      String xml = extractBodyForLogging(message, "", allowStreams, allowFiles, maxChars);
      if (xml != null) {
        // must always xml encode
        sb.append(StringHelper.xmlEncode(xml));
      }

      sb.append("</body>\n");
    }

    sb.append(prefix);
    sb.append("</message>");
    return sb.toString();
  }