private void populateRoutingInfoHeaders(final Message message, final Envelope envelope) {
   if (envelope != null) {
     message.setHeader(RabbitMQConstants.ROUTING_KEY, envelope.getRoutingKey());
     message.setHeader(RabbitMQConstants.EXCHANGE_NAME, envelope.getExchange());
     message.setHeader(RabbitMQConstants.DELIVERY_TAG, envelope.getDeliveryTag());
   }
 }
    @Override
    public void onAfterRoute(Route route, Exchange exchange) {
      // add the CORS headers after routing, but before the consumer writes the response
      Message msg = exchange.hasOut() ? exchange.getOut() : exchange.getIn();

      // use default value if none has been configured
      String allowOrigin =
          corsHeaders != null ? corsHeaders.get("Access-Control-Allow-Origin") : null;
      if (allowOrigin == null) {
        allowOrigin = RestConfiguration.CORS_ACCESS_CONTROL_ALLOW_ORIGIN;
      }
      String allowMethods =
          corsHeaders != null ? corsHeaders.get("Access-Control-Allow-Methods") : null;
      if (allowMethods == null) {
        allowMethods = RestConfiguration.CORS_ACCESS_CONTROL_ALLOW_METHODS;
      }
      String allowHeaders =
          corsHeaders != null ? corsHeaders.get("Access-Control-Allow-Headers") : null;
      if (allowHeaders == null) {
        allowHeaders = RestConfiguration.CORS_ACCESS_CONTROL_ALLOW_HEADERS;
      }
      String maxAge = corsHeaders != null ? corsHeaders.get("Access-Control-Max-Age") : null;
      if (maxAge == null) {
        maxAge = RestConfiguration.CORS_ACCESS_CONTROL_MAX_AGE;
      }

      msg.setHeader("Access-Control-Allow-Origin", allowOrigin);
      msg.setHeader("Access-Control-Allow-Methods", allowMethods);
      msg.setHeader("Access-Control-Allow-Headers", allowHeaders);
      msg.setHeader("Access-Control-Max-Age", maxAge);
    }
Beispiel #3
0
  public void populateExchangeFromCxfRsRequest(
      org.apache.cxf.message.Exchange cxfExchange,
      Exchange camelExchange,
      Method method,
      Object[] paramArray) {
    Message camelMessage = camelExchange.getIn();
    // Copy the CXF message header into the Camel inMessage
    org.apache.cxf.message.Message cxfMessage = cxfExchange.getInMessage();

    // TODO use header filter strategy and cxfToCamelHeaderMap
    CxfUtils.copyHttpHeadersFromCxfToCamel(cxfMessage, camelMessage);

    // copy the protocol header
    copyProtocolHeader(cxfMessage, camelMessage, camelMessage.getExchange());

    camelMessage.setHeader(CxfConstants.CAMEL_CXF_RS_RESPONSE_CLASS, method.getReturnType());

    camelMessage.setHeader(
        CxfConstants.CAMEL_CXF_RS_RESPONSE_GENERIC_TYPE, method.getGenericReturnType());

    copyOperationResourceInfoStack(cxfMessage, camelMessage);

    camelMessage.setHeader(CxfConstants.OPERATION_NAME, method.getName());

    camelMessage.setHeader(CxfConstants.CAMEL_CXF_MESSAGE, cxfMessage);

    camelMessage.setBody(new MessageContentsList(paramArray));
  }
 @Override
 protected void setUp() throws Exception {
   super.setUp();
   Message in = exchange.getIn();
   in.setBody("Hello there!");
   in.setHeader("name", "James");
   in.setHeader("location", "Islington,London,UK");
 }
  protected void doFindAll(Exchange exchange) throws Exception {
    DBCollection dbCol = calculateCollection(exchange);
    // do not use getMandatoryBody, because if the body is empty we want to retrieve all objects in
    // the collection
    DBObject query = null;
    // do not run around looking for a type converter unless there is a need for it
    if (exchange.getIn().getBody() != null) {
      query = exchange.getIn().getBody(DBObject.class);
    }
    DBObject fieldFilter =
        exchange.getIn().getHeader(MongoDbConstants.FIELDS_FILTER, DBObject.class);

    // get the batch size and number to skip
    Integer batchSize = exchange.getIn().getHeader(MongoDbConstants.BATCH_SIZE, Integer.class);
    Integer numToSkip = exchange.getIn().getHeader(MongoDbConstants.NUM_TO_SKIP, Integer.class);
    Integer limit = exchange.getIn().getHeader(MongoDbConstants.LIMIT, Integer.class);
    DBObject sortBy = exchange.getIn().getHeader(MongoDbConstants.SORT_BY, DBObject.class);
    DBCursor ret = null;
    try {
      if (query == null && fieldFilter == null) {
        ret = dbCol.find(new BasicDBObject());
      } else if (fieldFilter == null) {
        ret = dbCol.find(query);
      } else {
        ret = dbCol.find(query, fieldFilter);
      }

      if (sortBy != null) {
        ret.sort(sortBy);
      }

      if (batchSize != null) {
        ret.batchSize(batchSize.intValue());
      }

      if (numToSkip != null) {
        ret.skip(numToSkip.intValue());
      }

      if (limit != null) {
        ret.limit(limit.intValue());
      }

      Message resultMessage = prepareResponseMessage(exchange, MongoDbOperation.findAll);
      resultMessage.setBody(ret.toArray());
      resultMessage.setHeader(MongoDbConstants.RESULT_TOTAL_SIZE, ret.count());
      resultMessage.setHeader(MongoDbConstants.RESULT_PAGE_SIZE, ret.size());
    } finally {
      // make sure the cursor is closed
      if (ret != null) {
        ret.close();
      }
    }
  }
  // START SNIPPET: e1
  private Exchange createLetter() {
    Exchange exchange = context.getEndpoint("direct:a").createExchange();

    Message msg = exchange.getIn();
    msg.setHeader("firstName", "Claus");
    msg.setHeader("lastName", "Ibsen");
    msg.setHeader("item", "Camel in Action");
    msg.setBody("PS: Next beer is on me, James");

    return exchange;
  }
  public Exchange createMongoDbExchange(DBObject dbObj) {
    Exchange exchange = new DefaultExchange(this.getCamelContext(), getExchangePattern());
    Message message = new DefaultMessage();
    message.setHeader(MongoDbConstants.DATABASE, database);
    message.setHeader(MongoDbConstants.COLLECTION, collection);
    message.setHeader(MongoDbConstants.FROM_TAILABLE, true);

    message.setBody(dbObj);
    exchange.setIn(message);
    return exchange;
  }
    public void process(Exchange exchange) throws Exception {
      exchange.setPattern(ExchangePattern.InOut);
      Message inMessage = exchange.getIn();
      inMessage.setHeader(CxfConstants.CAMEL_CXF_RS_USING_HTTP_API, Boolean.TRUE);
      inMessage.setHeader(Exchange.HTTP_METHOD, "POST");
      inMessage.setHeader(Exchange.HTTP_PATH, "/execute");
      inMessage.setHeader(Exchange.ACCEPT_CONTENT_TYPE, "text/plain");
      inMessage.setHeader(Exchange.CONTENT_TYPE, "text/plain");

      this.processor.process(exchange);
    }
Beispiel #9
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"));
  }
 /** 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);
   }
 }
 private void populateMessageHeadersFromRabbitMQHeaders(
     final Message message, final AMQP.BasicProperties properties) {
   Map<String, Object> headers = properties.getHeaders();
   if (headers != null) {
     for (Map.Entry<String, Object> entry : headers.entrySet()) {
       // Convert LongStrings to String.
       if (entry.getValue() instanceof LongString) {
         message.setHeader(entry.getKey(), entry.getValue().toString());
       } else {
         message.setHeader(entry.getKey(), entry.getValue());
       }
     }
   }
 }
Beispiel #12
0
  public void setRabbitExchange(
      Exchange camelExchange, Envelope envelope, AMQP.BasicProperties properties, byte[] body) {
    Message message;
    if (camelExchange.getIn() != null) {
      // Use the existing message so we keep the headers
      message = camelExchange.getIn();
    } else {
      message = new DefaultMessage();
      camelExchange.setIn(message);
    }

    if (envelope != null) {
      message.setHeader(RabbitMQConstants.ROUTING_KEY, envelope.getRoutingKey());
      message.setHeader(RabbitMQConstants.EXCHANGE_NAME, envelope.getExchange());
      message.setHeader(RabbitMQConstants.DELIVERY_TAG, envelope.getDeliveryTag());
    }

    Map<String, Object> headers = properties.getHeaders();
    if (headers != null) {
      for (Map.Entry<String, Object> entry : headers.entrySet()) {
        // Convert LongStrings to String.
        if (entry.getValue() instanceof LongString) {
          message.setHeader(entry.getKey(), entry.getValue().toString());
        } else {
          message.setHeader(entry.getKey(), entry.getValue());
        }
      }
    }

    if (hasSerializeHeader(properties)) {
      Object messageBody = null;
      try (InputStream b = new ByteArrayInputStream(body);
          ObjectInputStream o = new ObjectInputStream(b); ) {
        messageBody = o.readObject();
      } catch (IOException | ClassNotFoundException e) {
        LOG.warn("Could not deserialize the object");
      }
      if (messageBody instanceof Throwable) {
        LOG.debug("Reply was an Exception. Setting the Exception on the Exchange");
        camelExchange.setException((Throwable) messageBody);
      } else {
        message.setBody(messageBody);
      }
    } else {
      // Set the body as a byte[] and let the type converter deal with it
      message.setBody(body);
    }
  }
 /**
  * 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;
 }
Beispiel #14
0
  public void testMessageDump() throws Exception {
    JAXBContext jaxb = JAXBContext.newInstance(MessageDump.class);
    Unmarshaller unmarshaller = jaxb.createUnmarshaller();

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

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

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

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

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

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

    assertEquals(1, dump.getHeaders().size());
    assertEquals("foo", dump.getHeaders().get(0).getKey());
    assertEquals("java.lang.Integer", dump.getHeaders().get(0).getType());
    assertEquals("123", dump.getHeaders().get(0).getValue());
  }
  protected void 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);
  }
  /** {@inheritDoc} */
  @Override
  public void mapTo(Context context, CamelBindingData target) throws Exception {
    Message message = target.getMessage();
    Exchange exchange = message.getExchange();

    for (Property property : context.getProperties(Scope.MESSAGE)) {
      String name = property.getName();
      if (matches(name) && !name.startsWith("org.switchyard.bus.camel")) {
        Object value = property.getValue();
        if (value != null) {
          message.setHeader(name, value);
        }
      }
    }
    if (exchange != null) {
      for (Property property : context.getProperties(Scope.EXCHANGE)) {
        String name = property.getName();
        if (matches(name) && !name.startsWith("org.switchyard.bus.camel")) {
          Object value = property.getValue();
          if (value != null) {
            exchange.setProperty(name, value);
          }
        }
      }
    }
  }
  @Test
  public void testCreateNotificationEmail() throws Exception {

    String expectedEmailBody =
        "Booking Name: Simpson, Homer<br/>Name in Parole case information: offenderName<br/>\n"
            + "SID: A9999999<br/>\n"
            + "DATE/TIME OF BOOKING: 2013-09-06<br/>\n"
            + "ARRESTING AGENCY: Honolulu PD<br/>ATTORNEY GENERAL CASE: false<br/>\n"
            + "ARREST CHARGES:<br/>\n"
            + "Description: Assault Severity: very severe, ARN: I-04679<br/>\n"
            + "<br/><br/>Positively identified by fingerprint.";

    EmailNotification email = new EmailNotification();
    email.addToAddressee("po1@localhost");
    email.setSubjectName("offenderName");
    email.setSubscribingSystemIdentifier("{http://demostate.gov/SystemNames/1.0}SystemA");
    email.setSubscriptionCategoryCode("default");
    email.setNotificationRequest(new ArrestNotificationRequest(getNotificationMessage()));

    Exchange e = new DefaultExchange((CamelContext) null);
    Message inMessage = e.getIn();
    inMessage.setHeader("notificationTopic", "arrest");
    inMessage.setBody(email);

    arrestNotificationProcessor.createNotificationEmail(e);

    Object receivedEmailBody = e.getOut().getBody();
    assertEquals(expectedEmailBody, receivedEmailBody);
    assertEquals("po1@localhost", e.getOut().getHeader(NotificationConstants.HEADER_TO));
  }
Beispiel #18
0
    public void process(Exchange exchange) throws Exception {
      exchange.getIn().getBody(String.class);

      Message output = exchange.getOut();
      output.setHeader("sample.name", "myValue");
      output.setBody(expectedBody);
    }
Beispiel #19
0
 public void processDataSet(Exchange originalExchange, DataSet dataSet, int counter)
     throws Exception {
   Exchange exchange = originalExchange.copy();
   Message in = exchange.getIn();
   in.setBody(dataSet);
   in.setHeader("CamelFlatpackCounter", counter);
   loadBalancer.process(exchange);
 }
Beispiel #20
0
 protected void copyMessageHeader(
     org.apache.cxf.message.Message cxfMessage,
     Message camelMessage,
     String cxfKey,
     String camelKey) {
   if (cxfMessage.get(cxfKey) != null) {
     camelMessage.setHeader(camelKey, cxfMessage.get(cxfKey));
   }
 }
 @Override
 public void process(Exchange exchange) throws Exception {
   exchange.setPattern(ExchangePattern.InOut);
   Message inMessage = exchange.getIn();
   setupDestinationURL(inMessage);
   // using the http central client API
   inMessage.setHeader(CxfConstants.CAMEL_CXF_RS_USING_HTTP_API, Boolean.TRUE);
   // set the Http method
   inMessage.setHeader(Exchange.HTTP_METHOD, "GET");
   // set the relative path
   inMessage.setHeader(Exchange.HTTP_PATH, "/customerservice/customers/123");
   // Specify the response class , cxfrs will use InputStream as the response object type
   inMessage.setHeader(CxfConstants.CAMEL_CXF_RS_RESPONSE_CLASS, Customer.class);
   // set a customer header
   inMessage.setHeader("key", "value");
   // since we use the Get method, so we don't need to set the message body
   inMessage.setBody(null);
 }
Beispiel #22
0
 protected void copyOperationResourceInfoStack(
     org.apache.cxf.message.Message cxfMessage, Message camelMessage) {
   OperationResourceInfoStack stack = cxfMessage.get(OperationResourceInfoStack.class);
   if (stack != null) {
     // make a copy of the operation resource info for looking up the sub resource location
     OperationResourceInfoStack copyStack = (OperationResourceInfoStack) stack.clone();
     camelMessage.setHeader(CxfConstants.CAMEL_CXF_RS_OPERATION_RESOURCE_INFO_STACK, copyStack);
   }
 }
  @SuppressWarnings("unchecked")
  protected void doUpdate(Exchange exchange) throws Exception {
    DBCollection dbCol = calculateCollection(exchange);
    List<DBObject> saveObj =
        exchange.getIn().getMandatoryBody((Class<List<DBObject>>) (Class<?>) List.class);
    if (saveObj.size() != 2) {
      throw new CamelMongoDbException(
          "MongoDB operation = insert, failed because body is not a List of DBObject objects with size = 2");
    }

    DBObject updateCriteria = saveObj.get(0);
    DBObject objNew = saveObj.get(1);

    Boolean multi = exchange.getIn().getHeader(MongoDbConstants.MULTIUPDATE, Boolean.class);
    Boolean upsert = exchange.getIn().getHeader(MongoDbConstants.UPSERT, Boolean.class);

    WriteResult result;
    WriteConcern wc = extractWriteConcern(exchange);
    // In API 2.7, the default upsert and multi values of update(DBObject, DBObject) are false,
    // false, so we unconditionally invoke the
    // full-signature method update(DBObject, DBObject, boolean, boolean). However, the default
    // behaviour may change in the future,
    // so it's safer to be explicit at this level for full determinism
    if (multi == null && upsert == null) {
      // for update with no multi nor upsert but with specific WriteConcern there is no update
      // signature without multi and upsert args,
      // so assume defaults
      result =
          wc == null
              ? dbCol.update(updateCriteria, objNew)
              : dbCol.update(updateCriteria, objNew, false, false, wc);
    } else {
      // we calculate the final boolean values so that if any of these
      // parameters is null, it is resolved to false
      result =
          wc == null
              ? dbCol.update(
                  updateCriteria,
                  objNew,
                  calculateBooleanValue(upsert),
                  calculateBooleanValue(multi))
              : dbCol.update(
                  updateCriteria,
                  objNew,
                  calculateBooleanValue(upsert),
                  calculateBooleanValue(multi),
                  wc);
    }

    Message resultMessage = prepareResponseMessage(exchange, MongoDbOperation.update);
    // we always return the WriteResult, because whether the getLastError was called or not, the
    // user will have the means to call it or
    // obtain the cached CommandResult
    processAndTransferWriteResult(result, exchange);
    resultMessage.setHeader(MongoDbConstants.RECORDS_AFFECTED, result.getN());
  }
  /**
   * 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");
  }
  protected Exchange createExchange() throws TimeoutException, NotConnectedException {
    LOG.trace("createExchange()");
    Identity info = getIdentity();
    Exchange exchange = endpoint.createExchange();

    ExchangePattern exchangePattern = exchange.getPattern();
    LOG.trace("exchangePattern=" + exchangePattern);

    // TODO CHECK InOnly. InOut, OutOnly

    // SET DEFAULT HEADER
    Message message = exchange.getIn();
    message.setHeader("uid", info.uid);
    message.setHeader("connectedUid", info.connectedUid);
    message.setHeader("deviceIdentifier", info.deviceIdentifier);
    message.setHeader("position", info.position);

    return exchange;
  }
Beispiel #26
0
  @Override
  public void execute(Exchange exchange) throws SmppException {
    DataSm dataSm = createDataSm(exchange);

    if (log.isDebugEnabled()) {
      log.debug("Sending a data short message for exchange id '{}'...", exchange.getExchangeId());
    }

    DataSmResult result;
    try {
      result =
          session.dataShortMessage(
              dataSm.getServiceType(),
              TypeOfNumber.valueOf(dataSm.getSourceAddrTon()),
              NumberingPlanIndicator.valueOf(dataSm.getSourceAddrNpi()),
              dataSm.getSourceAddr(),
              TypeOfNumber.valueOf(dataSm.getDestAddrTon()),
              NumberingPlanIndicator.valueOf(dataSm.getDestAddrNpi()),
              dataSm.getDestAddress(),
              new ESMClass(dataSm.getEsmClass()),
              new RegisteredDelivery(dataSm.getRegisteredDelivery()),
              DataCodings.newInstance(dataSm.getDataCoding()),
              dataSm.getOptionalParameters());
    } catch (Exception e) {
      throw new SmppException(e);
    }

    if (log.isDebugEnabled()) {
      log.debug(
          "Sent a data short message for exchange id '{}' and message id '{}'",
          exchange.getExchangeId(),
          result.getMessageId());
    }

    Message message = getResponseMessage(exchange);
    message.setHeader(SmppConstants.ID, result.getMessageId());
    // message.setHeader(SmppConstants.OPTIONAL_PARAMETERS,
    // createOptionalParameterByName(result.getOptionalParameters()));
    message.setHeader(SmppConstants.OPTIONAL_PARAMETERS, null);
    message.setHeader(
        SmppConstants.OPTIONAL_PARAMETER,
        createOptionalParameterByCode(result.getOptionalParameters()));
  }
  /** Configures the given message with the file which sets the body to the file object. */
  public void configureMessage(GenericFile<T> file, Message message) {
    message.setBody(file);

    if (flatten) {
      // when flatten the file name should not contain any paths
      message.setHeader(Exchange.FILE_NAME, file.getFileNameOnly());
    } else {
      // compute name to set on header that should be relative to starting directory
      String name = file.isAbsolute() ? file.getAbsoluteFilePath() : file.getRelativeFilePath();

      // skip leading endpoint configured directory
      String endpointPath = getConfiguration().getDirectory() + getFileSeparator();
      if (ObjectHelper.isNotEmpty(endpointPath) && name.startsWith(endpointPath)) {
        name = ObjectHelper.after(name, endpointPath);
      }

      // adjust filename
      message.setHeader(Exchange.FILE_NAME, name);
    }
  }
Beispiel #28
0
  public void testCopyHeadersWithHeaderFilterStrategy() throws Exception {
    CamelContext context = new DefaultCamelContext();
    context.start();

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

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

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

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

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

    assertEquals(null, target.getHeader("foo"));
    assertEquals(456, target.getHeader("bar"));
    context.stop();
  }
  protected void doRemove(Exchange exchange) throws Exception {
    DBCollection dbCol = calculateCollection(exchange);
    DBObject removeObj = exchange.getIn().getMandatoryBody(DBObject.class);

    WriteConcern wc = extractWriteConcern(exchange);
    WriteResult result = wc == null ? dbCol.remove(removeObj) : dbCol.remove(removeObj, wc);

    Message resultMessage = prepareResponseMessage(exchange, MongoDbOperation.remove);
    // we always return the WriteResult, because whether the getLastError was called or not,
    // the user will have the means to call it or obtain the cached CommandResult
    processAndTransferWriteResult(result, exchange);
    resultMessage.setHeader(MongoDbConstants.RECORDS_AFFECTED, result.getN());
  }
Beispiel #30
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);
      }
    }
  }