private void assertExchange(Exchange exchange, boolean hasFault) {
    if (!hasFault) {
      Message out = exchange.getOut();
      assertNotNull(out);
      assertFalse(out.isFault());
      assertEquals("Goodbye!", out.getBody());
      assertEquals("cheddar", out.getHeader("cheese"));
    } else {
      Message fault = exchange.getOut();
      assertNotNull(fault);
      assertTrue(fault.isFault());
      assertNotNull(fault.getBody());
      assertTrue(
          "Should get the InterrupteException exception",
          fault.getBody() instanceof InterruptedException);
      assertEquals("nihao", fault.getHeader("hello"));
    }

    // in should stay the same
    Message in = exchange.getIn();
    assertNotNull(in);
    assertEquals("Hello!", in.getBody());
    assertEquals("feta", in.getHeader("cheese"));
    // however the shared properties have changed
    assertEquals("fresh", exchange.getProperty("salami"));
    assertNull(exchange.getProperty("Charset"));
  }
  public NCSServicePath createPath(
      @JuniperXPath("//juniper:ServicePath") NodeList pathList, Exchange exchange) {
    Message in = exchange.getIn();
    String nodeForeignSource = (String) in.getHeader("nodeForeignSource");
    String serviceForeignSource = (String) in.getHeader("foreignSource");
    Node servicePath = pathList.item(0);

    return new NCSServicePath(
        servicePath, m_dao, m_nodeDao, nodeForeignSource, serviceForeignSource);
  }
 @Test
 public void testDefault() throws Exception {
   mock.expectedBodiesReceived("test1");
   mock.expectedHeaderReceived("test", "test2");
   producerTemplate.sendBodyAndHeader("direct:input", "test1", "test", "test2");
   mock.assertIsSatisfied();
   Message received = mock.getExchanges().get(0).getIn();
   assertEquals("default", received.getHeader(GTaskBinding.GTASK_QUEUE_NAME));
   assertEquals(0, received.getHeader(GTaskBinding.GTASK_RETRY_COUNT));
 }
Beispiel #4
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"));
  }
 public void getServiceName(
     @JuniperXPath(value = "//juniper:ServiceType") String data, Exchange exchange)
     throws ParserConfigurationException, SAXException, IOException {
   Message in = exchange.getIn();
   Map<String, Object> header = new HashMap<String, Object>();
   header.put("serviceType", data);
   header.put("deviceA", in.getHeader("deviceA"));
   header.put("deviceZ", in.getHeader("deviceZ"));
   header.put("foreignId", in.getHeader("foreignId"));
   header.put("foreignSource", in.getHeader("foreignSource"));
   header.put("nodeForeignSource", in.getHeader("nodeForeignSource"));
   exchange.getOut().setHeaders(header);
 }
 private String getSoapActionFromExchange(Exchange exchange) {
   Message inMessage = exchange.getIn();
   String soapAction = inMessage.getHeader(Exchange.SOAP_ACTION, String.class);
   if (soapAction == null) {
     soapAction = inMessage.getHeader("SOAPAction", String.class);
     if (soapAction != null && soapAction.startsWith("\"")) {
       soapAction = soapAction.substring(1, soapAction.length() - 1);
     }
   }
   if (soapAction == null) {
     soapAction = exchange.getProperty(Exchange.SOAP_ACTION, String.class);
   }
   return soapAction;
 }
 private void extractHeader(String headerMame, Message camelMessage, InternetHeaders headers) {
   String h = camelMessage.getHeader(headerMame, String.class);
   if (h != null) {
     headers.addHeader(headerMame, h);
     camelMessage.removeHeader(headerMame);
   }
 }
Beispiel #8
0
 @Converter
 public static HttpServletResponse toServletResponse(Message message) {
   if (message == null) {
     return null;
   }
   return message.getHeader(Exchange.HTTP_SERVLET_RESPONSE, HttpServletResponse.class);
 }
  /**
   * You get three keys with the UserId "keyflag", a primary key and its two sub-keys. The sub-key
   * with KeyFlag {@link KeyFlags#SIGN_DATA} should be used for signing and the sub-key with KeyFlag
   * {@link KeyFlags#ENCRYPT_COMMS} or {@link KeyFlags#ENCRYPT_COMMS} or {@link
   * KeyFlags#ENCRYPT_STORAGE} should be used for decryption.
   *
   * @throws Exception
   */
  @Test
  public void testKeyFlagSelectsCorrectKey() throws Exception {
    MockEndpoint mockKeyFlag = getMockEndpoint("mock:encrypted_keyflag");
    mockKeyFlag.setExpectedMessageCount(1);
    template.sendBody("direct:keyflag", "Test Message");
    assertMockEndpointsSatisfied();

    List<Exchange> exchanges = mockKeyFlag.getExchanges();
    assertEquals(1, exchanges.size());
    Exchange exchange = exchanges.get(0);
    Message inMess = exchange.getIn();
    assertNotNull(inMess);
    // must contain exactly one encryption key and one signature
    assertEquals(1, inMess.getHeader(PGPDataFormat.NUMBER_OF_ENCRYPTION_KEYS));
    assertEquals(1, inMess.getHeader(PGPDataFormat.NUMBER_OF_SIGNING_KEYS));
  }
Beispiel #10
0
 @Converter
 public static HttpServletRequest toServletRequest(Message message) {
   if (message == null) {
     return null;
   }
   return message.getHeader(Exchange.HTTP_SERVLET_REQUEST, HttpServletRequest.class);
 }
Beispiel #11
0
 /** Extracts name of the rabbitmq exchange */
 protected String getExchangeName(Message msg) {
   String exchangeName = msg.getHeader(RabbitMQConstants.EXCHANGE_NAME, String.class);
   // If it is BridgeEndpoint we should ignore the message header of EXCHANGE_NAME
   if (exchangeName == null || isBridgeEndpoint()) {
     exchangeName = getExchangeName();
   }
   return exchangeName;
 }
Beispiel #12
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"));
  }
Beispiel #13
0
  @Override
  public void process(Exchange exchange) throws TimeoutException, NotConnectedException {
    if (endpoint.getThrowExceptions() && bricklet == null) {
      throw new IllegalStateException("The ledstrip is currently unreachable");
    }

    switch (endpoint.getModus()) {
      case LedStripModus.LedStrip:
        {
          Message message = exchange.getIn();
          LedData data = new LedData();
          data.red = message.getHeader("red", 0, Short.class);
          data.green = message.getHeader("green", 0, Short.class);
          data.blue = message.getHeader("blue", 0, Short.class);
          data.duration = message.getHeader("duration", 0, Integer.class);
          final Integer position = message.getHeader("position", Integer.class);

          if (position != null) {
            scheduleLedData(position, data);
          } else {
            for (int i = 0; i < endpoint.getAmountOfLeds(); i++) {
              scheduleLedData(i, data);
            }
          }
          break;
        }
      case LedStripModus.CharacterMatrix:
        {
          Message message = exchange.getIn();
          String body = message.getBody(String.class);
          LedLayout layout = LedLayoutFactory.createLayout(endpoint.getLayout());
          List<LedCharacter> ledCharacters = LedCharacterFactory.getCharacters(body);
          List<Integer> resolvedLedNumbers = layout.mapCharacters(ledCharacters);

          for (int i = 0; i < endpoint.getAmountOfLeds(); i++) {
            if (resolvedLedNumbers.contains(i)) {
              LedData data = new LedData();
              data.red = message.getHeader("red", 0, Short.class);
              data.green = message.getHeader("green", 0, Short.class);
              data.blue = message.getHeader("blue", 0, Short.class);
              data.duration = message.getHeader("duration", 0, Integer.class);

              scheduleLedData(i, data);
            } else {
              scheduleLedData(i, new LedData());
            }
          }
        }
    }
  }
  /**
   * Define how the message is processed.
   *
   * @param exchange the current camel message exchange
   */
  public void process(final Exchange exchange) throws IOException {

    final Message in = exchange.getIn();

    final ByteArrayOutputStream serializedGraph = new ByteArrayOutputStream();
    final String subject = ProcessorUtils.getSubjectUri(in);
    final String namedGraph = in.getHeader(FcrepoHeaders.FCREPO_NAMED_GRAPH, String.class);
    final Model model =
        createDefaultModel()
            .read(
                in.getBody(InputStream.class),
                subject,
                langFromMimeType(in.getHeader(Exchange.CONTENT_TYPE, String.class)));

    model.write(serializedGraph, "N-TRIPLE");

    /*
     * Before inserting updated triples, the Sparql update command
     * below deletes all triples with the defined subject uri
     * (coming from the FCREPO_IDENTIFIER and FCREPO_BASE_URL headers).
     * It also deletes triples that have a subject corresponding to
     * that Fcrepo URI plus the "/fcr:export?format=jcr/xml" string
     * appended to it. This makes it possible to more completely
     * remove any triples for a given resource that were added
     * earlier. If fcrepo ever stops producing triples that are
     * appended with /fcr:export?format..., then that extra line
     * can be removed. It would also be possible to recursively delete
     * triples (by removing any triple whose subject is also an object
     * of the starting (or context) URI, but that approach tends to
     * delete too many triples from the triplestore. This command does
     * not delete blank nodes.
     */
    final StringBuilder query = new StringBuilder();
    query.append(ProcessorUtils.deleteWhere(subject, namedGraph));
    query.append(";\n");
    query.append(ProcessorUtils.deleteWhere(subject + "/fcr:export?format=jcr/xml", namedGraph));
    query.append(";\n");
    query.append(ProcessorUtils.insertData(serializedGraph.toString("UTF-8"), namedGraph));

    in.setBody("update=" + encode(query.toString(), "UTF-8"));
    in.setHeader(Exchange.HTTP_METHOD, "POST");
    in.setHeader(Exchange.CONTENT_TYPE, "application/x-www-form-urlencoded");
  }
  /**
   * Creates the {@link HttpMethod} to use to call the remote server, often either its GET or POST.
   *
   * @param message the Camel message
   * @return the created method
   */
  public static HttpMethod createMethod(Message message, boolean hasPayload) {
    // use header first
    HttpMethod m = message.getHeader(Exchange.HTTP_METHOD, HttpMethod.class);
    if (m != null) {
      return m;
    }
    String name = message.getHeader(Exchange.HTTP_METHOD, String.class);
    if (name != null) {
      return HttpMethod.valueOf(name);
    }

    if (hasPayload) {
      // use POST if we have payload
      return HttpMethod.POST;
    } else {
      // fallback to GET
      return HttpMethod.GET;
    }
  }
 @Test
 public void testProcessNoAction() throws Exception {
   when(endpoint.getAction()).thenReturn(null);
   when(in.getHeader(HEADER_TIMER_ACTION, null, MetricsTimerAction.class)).thenReturn(null);
   producer.doProcess(exchange, endpoint, registry, METRICS_NAME);
   inOrder.verify(exchange, times(1)).getIn();
   inOrder.verify(endpoint, times(1)).getAction();
   inOrder.verify(in, times(1)).getHeader(HEADER_TIMER_ACTION, null, MetricsTimerAction.class);
   inOrder.verifyNoMoreInteractions();
 }
  @Test
  public void testNoFeedInHeader() throws Exception {
    MockEndpoint mock = getMockEndpoint("mock:result");
    mock.expectedMessageCount(1);
    mock.assertIsSatisfied();

    Exchange exchange = mock.getExchanges().get(0);
    Message in = exchange.getIn();
    assertNotNull(in);
    assertNull(in.getHeader(RssConstants.RSS_FEED));
  }
  /** Bad style test :( */
  @Test
  public void testThatAnnotatedMethodInvokerIsWorkingAsExpected() throws Exception {
    CamelContext context = mock(CamelContext.class);
    Plugin plugin = new Plugin();
    PluginContext pluginContext = new PluginContext();
    pluginContext.setClassLoader(getClass().getClassLoader());
    pluginContext.setInjector(new PluginContextInjectorImpl());
    pluginContext.setPluginClass(TestAggregatorImpl.class.getName());
    final BasicMessagesSerializer serializer = new BasicMessagesSerializer();
    pluginContext.setMessagesSerializer(serializer);
    plugin.setAggregator(TestAggregatorImpl.class.getName());
    plugin.setContext(pluginContext);
    AggregationRepository repo = mock(AggregationRepository.class);
    FoundMethodProcessor proc = mock(FoundMethodProcessor.class);
    TestState state = new TestState();
    Exchange exchange = mock(Exchange.class);
    Message message = spy(new JmsMessage(mock(javax.jms.Message.class), mock(JmsBinding.class)));
    message.setBody(
        serializer.processBodyAndHeadersBeforeSend(
            state, new HashMap<String, Object>(), getSystemClassLoader()));
    when(message.getHeader(BODY_CLASS)).thenReturn(TestState.class.getName());
    when(exchange.getIn()).thenReturn(message);
    when(repo.getKeys()).thenReturn(new HashSet<>(asList("key1", "key2")));
    when(repo.get(context, "key1")).thenReturn(exchange);
    when(repo.get(context, "key2")).thenReturn(exchange);
    when(proc.appliesTo(any(Method.class), any(Annotation.class))).thenReturn(true);
    pluginContext.setAggregationRepo(repo);

    AggregatorPluginAnnotatedMethodInvoker invoker =
        new AggregatorPluginAnnotatedMethodInvoker(context, plugin, OnClientMessage.class, false);
    invoker.process(proc);

    invoker.invoke("test");

    verify(proc)
        .appliesTo(
            eq(TestAggregatorImpl.class.getMethod("onBroadcast", TestState.class)),
            any(Annotation.class));
    verify(proc)
        .appliesTo(
            eq(TestAggregatorImpl.class.getMethod("onBroadcast2", TestState.class, String.class)),
            any(Annotation.class));
    verify(aggMock, times(2)).onBroadcast(any(TestState.class));
    verify(aggMock, times(2)).onBroadcast2(any(TestState.class), eq("test"));
    verify(message, atLeast(5)).setBody(any());
    verify(repo, times(2)).get(context, "key1");
    verify(repo, times(2)).get(context, "key2");
    verify(repo, times(2)).getKeys();
    verify(repo, times(2)).add(context, "key1", exchange);
    verify(repo, times(2)).add(context, "key2", exchange);
    verifyNoMoreInteractions(aggMock, repo);
  }
Beispiel #19
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();
  }
Beispiel #20
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);
      }
    }
  }
 /** Prepares the redelivery counter and boolean flag for the failure handle processor */
 private void decrementRedeliveryCounter(Exchange exchange) {
   Message in = exchange.getIn();
   Integer counter = in.getHeader(Exchange.REDELIVERY_COUNTER, Integer.class);
   if (counter != null) {
     int prev = counter - 1;
     in.setHeader(Exchange.REDELIVERY_COUNTER, prev);
     // set boolean flag according to counter
     in.setHeader(Exchange.REDELIVERED, prev > 0 ? Boolean.TRUE : Boolean.FALSE);
   } else {
     // not redelivered
     in.setHeader(Exchange.REDELIVERY_COUNTER, 0);
     in.setHeader(Exchange.REDELIVERED, Boolean.FALSE);
   }
 }
 @Test
 public void testProcessNoActionOverride() throws Exception {
   when(endpoint.getAction()).thenReturn(null);
   when(in.getHeader(HEADER_TIMER_ACTION, null, TimerAction.class)).thenReturn(TimerAction.start);
   producer.doProcess(exchange, endpoint, registry, METRICS_NAME);
   inOrder.verify(exchange, times(1)).getIn();
   inOrder.verify(endpoint, times(1)).getAction();
   inOrder.verify(in, times(1)).getHeader(HEADER_TIMER_ACTION, null, TimerAction.class);
   inOrder.verify(exchange, times(1)).getProperty(PROPERTY_NAME, Timer.Context.class);
   inOrder.verify(registry, times(1)).timer(METRICS_NAME);
   inOrder.verify(timer, times(1)).time();
   inOrder.verify(exchange, times(1)).setProperty(PROPERTY_NAME, context);
   inOrder.verifyNoMoreInteractions();
 }
 /**
  * Increments the redelivery counter and adds the redelivered flag if the message has been
  * redelivered
  */
 private int incrementRedeliveryCounter(Exchange exchange, Throwable e, RedeliveryData data) {
   Message in = exchange.getIn();
   Integer counter = in.getHeader(Exchange.REDELIVERY_COUNTER, Integer.class);
   int next = 1;
   if (counter != null) {
     next = counter + 1;
   }
   in.setHeader(Exchange.REDELIVERY_COUNTER, next);
   in.setHeader(Exchange.REDELIVERED, Boolean.TRUE);
   // if maximum redeliveries is used, then provide that information as well
   if (data.currentRedeliveryPolicy.getMaximumRedeliveries() > 0) {
     in.setHeader(
         Exchange.REDELIVERY_MAX_COUNTER, data.currentRedeliveryPolicy.getMaximumRedeliveries());
   }
   return next;
 }
 @Test
 public void testProcessStartWithOverride() throws Exception {
   when(endpoint.getAction()).thenReturn(MetricsTimerAction.start);
   when(in.getHeader(HEADER_TIMER_ACTION, MetricsTimerAction.start, MetricsTimerAction.class))
       .thenReturn(MetricsTimerAction.stop);
   when(exchange.getProperty(PROPERTY_NAME, Timer.Context.class)).thenReturn(context);
   producer.doProcess(exchange, endpoint, registry, METRICS_NAME);
   inOrder.verify(exchange, times(1)).getIn();
   inOrder.verify(endpoint, times(1)).getAction();
   inOrder
       .verify(in, times(1))
       .getHeader(HEADER_TIMER_ACTION, MetricsTimerAction.start, MetricsTimerAction.class);
   inOrder.verify(exchange, times(1)).getProperty(PROPERTY_NAME, Timer.Context.class);
   inOrder.verify(context, times(1)).stop();
   inOrder.verify(exchange, times(1)).removeProperty(PROPERTY_NAME);
   inOrder.verifyNoMoreInteractions();
 }
  @Override
  public void process(Exchange exchange) throws Exception {
    List<SimpleMeasurement> results = new ArrayList<SimpleMeasurement>();
    Message in = exchange.getIn();
    String serviceURL =
        (String)
            in.getHeader("jmxServiceUrl", "service:jmx:rmi:///jndi/rmi://localhost:1099/jmxrmi");
    String user = (String) in.getHeader("jmxUser");
    String pass = (String) in.getHeader("jmxPassword");

    JMXConnector jmxConnector = connect(serviceURL, user, pass);

    ObjectName name = new ObjectName((String) in.getHeader("jmxObjectName"));
    String[] attributeNames = ((String) in.getHeader("jmxAttributeName", "")).split(",");
    String id = (String) in.getHeader("MeasurementID");
    double scale = Double.parseDouble((String) in.getHeader("Scale", "1"));

    Number value = null;
    try {
      MBeanServerConnection mBeanServerConnection = jmxConnector.getMBeanServerConnection();

      for (String attribute : attributeNames) {
        String[] parts = attribute.split("\\.");
        Object result = mBeanServerConnection.getAttribute(name, parts[0]);
        if (result instanceof Number) value = (Number) result;
        else if (result instanceof String) {
          String s = (String) result;
          value = Double.parseDouble(s.replace(',', '.'));
        } else if (result instanceof CompositeDataSupport) {
          CompositeDataSupport cds = (CompositeDataSupport) result;
          value = (Number) ((CompositeDataSupport) result).get(parts[1]);
        } else throw new IllegalArgumentException("Unknown type: " + result);
        results.add(
            new SimpleMeasurement(id + "." + attribute, value.doubleValue() / (double) scale));
      }
    } catch (Exception e) {
      LOGGER.error("An exception occurred:", e);
    } finally {
      jmxConnector.close();
    }
    exchange.getIn().setBody(results);
  }
Beispiel #26
0
 /** Returns the MIME content type on the message or <tt>null</tt> if none defined */
 public static String getContentType(Message message) {
   return message.getHeader(Exchange.CONTENT_TYPE, String.class);
 }
  @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;
  }
 private String getServiceName(Message in) {
   return in.getHeader(SERVICE_NAME, String.class);
 }
Beispiel #30
0
 /** Returns the MIME content encoding on the message or <tt>null</tt> if none defined */
 public static String getContentEncoding(Message message) {
   return message.getHeader(Exchange.CONTENT_ENCODING, String.class);
 }