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"));
  }
  /**
   * Creates a holder object for the data to send to the remote server.
   *
   * @param exchange the exchange with the IN message with data to send
   * @return the data holder
   * @throws CamelExchangeException is thrown if error creating RequestEntity
   */
  protected RequestEntity createRequestEntity(Exchange exchange) throws CamelExchangeException {
    Message in = exchange.getIn();
    if (in.getBody() == null) {
      return null;
    }

    RequestEntity answer = in.getBody(RequestEntity.class);
    if (answer == null) {
      try {
        Object data = in.getBody();
        if (data != null) {
          String contentType = ExchangeHelper.getContentType(exchange);

          if (contentType != null
              && HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT.equals(contentType)) {
            // serialized java object
            Serializable obj = in.getMandatoryBody(Serializable.class);
            // write object to output stream
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            HttpHelper.writeObjectToStream(bos, obj);
            answer =
                new ByteArrayRequestEntity(
                    bos.toByteArray(), HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT);
            IOHelper.close(bos);
          } else if (data instanceof File || data instanceof GenericFile) {
            // file based (could potentially also be a FTP file etc)
            File file = in.getBody(File.class);
            if (file != null) {
              answer = new FileRequestEntity(file, contentType);
            }
          } else if (data instanceof String) {
            // be a bit careful with String as any type can most likely be converted to String
            // so we only do an instanceof check and accept String if the body is really a String
            // do not fallback to use the default charset as it can influence the request
            // (for example application/x-www-form-urlencoded forms being sent)
            String charset = IOHelper.getCharsetName(exchange, false);
            answer = new StringRequestEntity((String) data, contentType, charset);
          }
          // fallback as input stream
          if (answer == null) {
            // force the body as an input stream since this is the fallback
            InputStream is = in.getMandatoryBody(InputStream.class);
            answer = new InputStreamRequestEntity(is, contentType);
          }
        }
      } catch (UnsupportedEncodingException e) {
        throw new CamelExchangeException(
            "Error creating RequestEntity from message body", exchange, e);
      } catch (IOException e) {
        throw new CamelExchangeException("Error serializing message body", exchange, e);
      }
    }
    return answer;
  }
  public static Object getBodyFromCamel(org.apache.camel.Message out, DataFormat dataFormat) {
    Object answer = null;

    if (dataFormat == DataFormat.POJO) {
      answer = out.getBody();
    } else if (dataFormat == DataFormat.PAYLOAD) {
      answer = out.getBody(CxfPayload.class);
    } else if (dataFormat.dealias() == DataFormat.RAW) {
      answer = out.getBody(InputStream.class);
    } else if (dataFormat.dealias() == DataFormat.CXF_MESSAGE) {
      answer = out.getBody();
    }
    return answer;
  }
  public void testSendingAMessageUsingMulticastReceivesItsOwnExchangeParallel() throws Exception {
    MockEndpoint resultEndpoint = getMockEndpoint("mock:result");

    resultEndpoint.expectsNoDuplicates(body());
    resultEndpoint.expectedMessageCount(4);

    // InOnly
    template.send(
        "direct:parallel",
        new Processor() {
          public void process(Exchange exchange) {
            Message in = exchange.getIn();
            in.setBody("James,Guillaume,Hiram,Rob");
            in.setHeader("foo", "bar");
          }
        });

    assertMockEndpointsSatisfied();

    List<Exchange> list = resultEndpoint.getReceivedExchanges();
    Set<Integer> numbersFound = new TreeSet<Integer>();
    final String[] names = {"James", "Guillaume", "Hiram", "Rob"};

    for (int i = 0; i < 4; i++) {
      Exchange exchange = list.get(i);
      Message in = exchange.getIn();
      Integer splitCounter = exchange.getProperty(Exchange.SPLIT_INDEX, Integer.class);
      numbersFound.add(splitCounter);
      assertEquals(names[splitCounter], in.getBody());
      assertProperty(exchange, Exchange.SPLIT_SIZE, 4);
    }

    assertEquals(4, numbersFound.size());
  }
 @Override
 public void process(Exchange exchange) throws Exception {
   Message in = exchange.getIn();
   String filename = in.getBody(String.class);
   List<String> lines = Files.readAllLines(Paths.get(filename), Charset.defaultCharset());
   in.setBody(lines);
 }
  public void testSetBodyType() throws Exception {
    Exchange exchange = new DefaultExchange(context);
    Message in = exchange.getIn();
    in.setBody("123", Integer.class);

    assertIsInstanceOf(Integer.class, in.getBody());
  }
    @Override
    public Source respond(SoapOperation invokedOperation, SoapMessage message) {
      Exchange exchange = new DefaultExchange(getCamelContext(), ExchangePattern.InOut);

      Document messageDocument = message.getDocument();
      String requestBody = envelopeWrapper.unwrap(messageDocument, getCamelContext());

      exchange.getIn().setBody(requestBody);
      exchange.getIn().setHeader(OPERATION, invokedOperation.getOperationName());

      try {
        getProcessor().process(exchange);
        if (exchange.getException() != null) {
          throw exchange.getException();
        }
        Message responseMessage = exchange.getOut(Message.class);
        if (responseMessage != null) {
          String responseBody = responseMessage.getBody(String.class);
          return envelopeWrapper.wrapToSource(responseBody, getCamelContext());
        } else {
          throw new IllegalArgumentException(
              "Could not find output message, exchange: " + exchange);
        }
      } catch (Exception ex) {
        throw new SoapServerException(ex);
      }
    }
  public void process(Exchange exchange) throws Exception {
    Jaxp11XMLReaderCreator xmlCreator = new Jaxp11XMLReaderCreator();
    DefaultValidationErrorHandler errorHandler = new DefaultValidationErrorHandler();

    PropertyMapBuilder mapBuilder = new PropertyMapBuilder();
    mapBuilder.put(ValidateProperty.XML_READER_CREATOR, xmlCreator);
    mapBuilder.put(ValidateProperty.ERROR_HANDLER, errorHandler);
    PropertyMap propertyMap = mapBuilder.toPropertyMap();

    Validator validator = getSchema().createValidator(propertyMap);

    Message in = exchange.getIn();
    SAXSource saxSource = in.getBody(SAXSource.class);
    if (saxSource == null) {
      Source source = exchange.getIn().getMandatoryBody(Source.class);
      saxSource = ExchangeHelper.convertToMandatoryType(exchange, SAXSource.class, source);
    }
    InputSource bodyInput = saxSource.getInputSource();

    // now lets parse the body using the validator
    XMLReader reader = xmlCreator.createXMLReader();
    reader.setContentHandler(validator.getContentHandler());
    reader.setDTDHandler(validator.getDTDHandler());
    reader.setErrorHandler(errorHandler);
    reader.parse(bodyInput);

    errorHandler.handleErrors(exchange, schema);
  }
  /* (non-Javadoc)
   * @see com.netflexity.qflex.agent.CallProcessor#processCall(java.lang.Object)
   */
  @Override
  public OperationType processCall(final OperationType operation) {
    ProducerTemplate template = camelContext.createProducerTemplate();
    Exchange exchange =
        template.request(
            route,
            new Processor() {

              /* (non-Javadoc)
               * @see org.apache.camel.Processor#process(org.apache.camel.Exchange)
               */
              public void process(Exchange exchange) throws Exception {
                Request operationRequest = operation.getRequest();
                Object obj = operationRequest.getAny();
                exchange.getIn().setBody(obj);
              }
            });

    OperationType.Result result = new OperationType.Result();
    operation.setResult(result);

    Message message = exchange.getOut();
    if (message != null) {
      logger.debug("Response:" + message.getBody());
      if (exchange.getException() != null) {
        logger.error("Fault processing operation:", exchange.getException());
        ErrorType error = new ErrorType();
        operation.setError(error);
        if (exchange.getException() instanceof WMQFaultMessage) {
          WMQFaultMessage exc = (WMQFaultMessage) exchange.getException();
          if (exc.getFaultInfo() != null) {
            error.setCode(exc.getFaultInfo().getReasonCode());
            error.setDescription(exc.getFaultInfo().getDescription());
          } else {
            error.setDescription(exc.getMessage());
          }
        } else {
          error.setDescription(exchange.getException().getMessage());
        }
      } else {
        result.setAny(message.getBody());
      }
      message.setBody(operation);
    }

    return operation;
  }
  @Override
  public void process(Exchange exchange) throws Exception {
    Message in = exchange.getIn();
    HttpServletRequest request = in.getBody(HttpServletRequest.class);
    // Get Exchange body
    byte[] rawBody = in.getBody(byte[].class);

    if (request.getParameter("hub.verify_token") != null) {
      if (this.verifyToken.equalsIgnoreCase(request.getParameter("hub.verify_token"))) {
        if (request.getParameter("hub.challenge") != null) {
          Object body = request.getParameter("hub.challenge");
          exchange.getOut().setBody(body);
          log.trace(" Challenge is posted,  his value  :" + request.getParameter("hub.challenge"));
        }
      }
    }
    if (in.getBody() != null) {
      String instagramBody = new String(rawBody);
      log.debug("Received body value is  :  " + instagramBody);

      if (instagramBody.startsWith("{")) {
        log.info("Instagram response  :" + new JSONObject(instagramBody));

      } else if (instagramBody.startsWith("[{")) {
        // Get the first pagination order by the recent element
        JSONArray instagramJSArray = new JSONArray(instagramBody);
        long subscriptionID = instagramJSArray.getJSONObject(0).getLong("subscription_id");
        String tag = instagramJSArray.getJSONObject(0).getString("object_id");

        JSONArray data = getInstagramTag(tag);
        if (data != null) {
          JSONArray pileTags = empileTag(data);

          if (pileTags != null) {
            for (int i = (pileTags.length() - 1); i >= 0; i--) {
              HMessage msg = new HMessage();
              msg = transformInstagramToHMessage(pileTags.getJSONObject(i));
              JSONObject header = new JSONObject();
              header.put("subscription_id", subscriptionID);
              msg.setHeaders(header);
              put(msg);
            }
          }
        }
      }
    }
  }
  /**
   * This method call Message.getBody({@link MessageContentsList}) to allow an appropriate converter
   * to kick in even through we only read the first element off the MessageContextList. If that
   * returns null, we check the body to see if it is a List or an array and then return the first
   * element. If that fails, we will simply return the object.
   */
  public Object bindCamelMessageBodyToRequestBody(Message camelMessage, Exchange camelExchange)
      throws Exception {

    Object request = camelMessage.getBody(MessageContentsList.class);
    if (request != null) {
      return ((MessageContentsList) request).get(0);
    }

    request = camelMessage.getBody();
    if (request instanceof List) {
      request = ((List<?>) request).get(0);
    } else if (request != null && request.getClass().isArray()) {
      request = ((Object[]) request)[0];
    }

    return request;
  }
Exemple #12
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;
  }
Exemple #13
0
 /**
  * If the message body contains a {@link StreamCache} instance, reset the cache to enable reading
  * from it again.
  *
  * @param message the message for which to reset the body
  */
 public static void resetStreamCache(Message message) {
   if (message == null) {
     return;
   }
   Object body = message.getBody();
   if (body != null && body instanceof StreamCache) {
     ((StreamCache) body).reset();
   }
 }
  /** Marshals the request, sends it to the route, and unmarshals the response. */
  @Override
  public void process(Exchange exchange) throws Exception {
    Message message;

    // marshal
    message = exchange.getIn();
    MessageAdapter request = message.getBody(MessageAdapter.class);
    message.setBody(request.toString());

    // run the route
    getWrappedProcessor().process(exchange);

    // unmarshal
    message = Exchanges.resultMessage(exchange);
    String responseString = message.getBody(String.class);
    message.setBody(MessageAdapters.make(getMllpEndpoint().getParser(), responseString));
    exchange.setProperty(
        Exchange.CHARSET_NAME, getMllpEndpoint().getConfiguration().getCharsetName());
  }
Exemple #15
0
 /**
  * Gets the given body class type name as a String.
  *
  * <p>Will skip java.lang. for the build in Java types.
  *
  * @param message the message with the body
  * @return the body type name as String, can return <tt>null</null> if no body
  */
 public static String getBodyTypeName(Message message) {
   if (message == null) {
     return null;
   }
   String answer = ObjectHelper.classCanonicalName(message.getBody());
   if (answer != null && answer.startsWith("java.lang.")) {
     return answer.substring(10);
   }
   return answer;
 }
 @Override
 public void process(Exchange exchange) {
   final Message in = exchange.getIn();
   final Collection<?> list = in.getBody(AbstractCollection.class);
   BigDecimal total = BigDecimal.ZERO;
   for (Object value : list) {
     total = total.add(BigDecimal.valueOf((Integer) value));
   }
   in.setBody(total.divide(new BigDecimal(list.size()), RoundingMode.HALF_UP));
 }
Exemple #17
0
  public void pollCurrentLog() {
    try {
      CamelContext camelContext = new DefaultCamelContext();
      camelContext.addComponent(
          "jms",
          org.apache.activemq.camel.component.ActiveMQComponent.activeMQComponent(
              "tcp://localhost:61616"));
      ConsumerTemplate consumerTemplate = camelContext.createConsumerTemplate();
      Message message = consumerTemplate.receive("jms:queue:maven-logs").getIn();

      if (message != null && message.getBody() != null) {
        if (currentLog == null) {
          currentLog = message.getBody().toString();
        } else {
          currentLog += "\n" + message.getBody();
        }
      }
    } catch (Exception e) {
      logger.error("Error:", e);
    }
  }
Exemple #18
0
  private MethodInfo chooseMethodWithMatchingBody(
      Exchange exchange,
      Collection<MethodInfo> operationList,
      List<MethodInfo> operationsWithCustomAnnotation)
      throws AmbiguousMethodCallException {
    // see if we can find a method whose body param type matches the message body
    Message in = exchange.getIn();
    Object body = in.getBody();
    if (body != null) {
      Class<?> bodyType = body.getClass();
      if (LOG.isTraceEnabled()) {
        LOG.trace(
            "Matching for method with a single parameter that matches type: {}",
            bodyType.getCanonicalName());
      }

      List<MethodInfo> possibles = new ArrayList<MethodInfo>();
      List<MethodInfo> possiblesWithException = new ArrayList<MethodInfo>();
      for (MethodInfo methodInfo : operationList) {
        // test for MEP pattern matching
        boolean out = exchange.getPattern().isOutCapable();
        if (out && methodInfo.isReturnTypeVoid()) {
          // skip this method as the MEP is Out so the method must return something
          continue;
        }

        // try to match the arguments
        if (methodInfo.bodyParameterMatches(bodyType)) {
          LOG.trace("Found a possible method: {}", methodInfo);
          if (methodInfo.hasExceptionParameter()) {
            // methods with accepts exceptions
            possiblesWithException.add(methodInfo);
          } else {
            // regular methods with no exceptions
            possibles.add(methodInfo);
          }
        }
      }

      // find best suited method to use
      return chooseBestPossibleMethodInfo(
          exchange,
          operationList,
          body,
          possibles,
          possiblesWithException,
          operationsWithCustomAnnotation);
    }

    // no match so return null
    return null;
  }
  public void testTransform() throws Exception {
    MockEndpoint resultEndpoint = resolveMandatoryEndpoint("mock:result", MockEndpoint.class);
    resultEndpoint.expectedMessageCount(1);

    resultEndpoint.assertIsSatisfied();

    List<Exchange> list = resultEndpoint.getReceivedExchanges();
    Exchange exchange = list.get(0);
    Message in = exchange.getIn();

    String text = in.getBody(String.class);
    log.info("Received: " + text);
  }
Exemple #20
0
 @Override
 public void process(Exchange exchange) throws Exception {
   Message in = exchange.getIn();
   RepositoryCommit commit = (RepositoryCommit) in.getBody();
   User author = commit.getAuthor();
   log.debug(
       "Got commit with author: "
           + author.getLogin()
           + ": "
           + author.getHtmlUrl()
           + " SHA "
           + commit.getSha());
 }
Exemple #21
0
  /**
   * Extracts the given body and returns it as a String, that can be used for logging etc.
   *
   * <p>Will handle stream based bodies wrapped in StreamCache.
   *
   * @param message the message with the body
   * @return the body as String, can return <tt>null</null> if no body
   */
  public static String extractBodyAsString(Message message) {
    if (message == null) {
      return null;
    }

    StreamCache newBody = message.getBody(StreamCache.class);
    if (newBody != null) {
      message.setBody(newBody);
    }

    Object answer = message.getBody(String.class);
    if (answer == null) {
      answer = message.getBody();
    }

    if (newBody != null) {
      // Reset the InputStreamCache
      newBody.reset();
    }

    return answer != null ? answer.toString() : null;
  }
  @Override
  protected void populateVelocityContext(
      final VelocityContext velocityContext, final Message message, final JobInstance configuration)
      throws UnableToProceedWithConversionException {
    final FrbrDocument data = message.getBody(FrbrDocument.class);

    if (data != null) {
      final Document document = data.getDocument();
      final Element root = document.getDocumentElement();
      velocityContext.put(Constants.ROOT_ELEMENT_ATTRIBUTE_NAME, root);
      velocityContext.put(Constants.FRBR_DATA_ATTRIBUTE_NAME, data);
    }
  }
Exemple #23
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());
            }
          }
        }
    }
  }
  @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);
  }
  @Test
  public void testUnMarshallingJsonComplete() throws InterruptedException, IOException {
    out.setExpectedMessageCount(1);
    String s = readFile(NOTIFICATION_JSON, Charset.defaultCharset());
    in.sendBody(s);
    out.await(5, TimeUnit.SECONDS);
    out.assertIsSatisfied();
    List<Exchange> exchanges = out.getExchanges();

    for (Exchange exchange : exchanges) {
      Message message = exchange.getIn();
      Notification notif = message.getBody(Notification.class);
      validateNotification(notif);
    }
  }
 @Test
 public void testTranslatedEvent() throws Exception {
   out.expectedMinimumMessageCount(1);
   trap.send();
   out.assertIsSatisfied();
   List<Exchange> exchanges = out.getExchanges();
   Exchange exchange = exchanges.get(0);
   Message message = exchange.getIn();
   RawEvent event = message.getBody(RawEvent.class);
   assertNotNull("check for not null", event);
   assertEquals("check event title", "linkDown trap received from 127.0.0.1", event.getTitle());
   assertEquals("check event message", "Received linkDown trap", event.getMessage());
   Map<String, Object> properties = event.getProperties();
   assertEquals("check trap property", "Host has been restarted", properties.get("linkDown"));
   assertEquals("check uptime property", "7:12:00.00", properties.get("sysUpTimeInstance"));
   assertEquals("check description property", "Test Trap!", properties.get("sysDescr.0"));
 }
  private void sendOutMessage(Exchange exchange) throws QFJException {
    Message camelMessage = exchange.getOut();
    quickfix.Message quickfixjMessage = camelMessage.getBody(quickfix.Message.class);

    log.debug("Sending FIX message reply: {}", quickfixjMessage);

    SessionID messageSessionID = exchange.getIn().getHeader("SessionID", SessionID.class);

    Session session = getSession(messageSessionID);
    if (session == null) {
      throw new IllegalStateException("Unknown session: " + messageSessionID);
    }

    if (!session.send(quickfixjMessage)) {
      throw new CannotSendException(
          "Could not send FIX message reply: " + quickfixjMessage.toString());
    }
  }
  /**
   * 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");
  }
  public void greetMe(Exchange exchange) {
    Bus oldbus = BusFactory.getThreadDefaultBus();
    BusFactory.setThreadDefaultBus(bus);
    try {
      synchronized (greeter) {
        Message message = exchange.getIn();
        String name = message.getBody(String.class);
        System.out.println("Greeting " + name + " at address " + address);

        String result = greeter.greetMe(name);
        System.out.println("Greeter response: " + result);
        exchange.getOut().setBody(result);
      }
    } catch (RuntimeException e) {
      e.printStackTrace();
      throw e;
    } finally {
      BusFactory.setThreadDefaultBus(oldbus);
    }
  }
  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);
    }
  }