Ejemplo n.º 1
0
    private void ensureHeaderContentType(
        String contentType, boolean isXml, boolean isJson, Exchange exchange) {
      // favor given content type
      if (contentType != null) {
        String type = ExchangeHelper.getContentType(exchange);
        if (type == null) {
          exchange.getIn().setHeader(Exchange.CONTENT_TYPE, contentType);
        }
      }

      // favor json over xml
      if (isJson) {
        // make sure there is a content-type with json
        String type = ExchangeHelper.getContentType(exchange);
        if (type == null) {
          exchange.getIn().setHeader(Exchange.CONTENT_TYPE, "application/json");
        }
      } else if (isXml) {
        // make sure there is a content-type with xml
        String type = ExchangeHelper.getContentType(exchange);
        if (type == null) {
          exchange.getIn().setHeader(Exchange.CONTENT_TYPE, "application/xml");
        }
      }
    }
Ejemplo n.º 2
0
  @Override
  public boolean process(Exchange exchange, AsyncCallback callback) {
    // use atomic integer to be able to pass reference and keep track on the values
    AtomicInteger index = new AtomicInteger();
    AtomicInteger count = new AtomicInteger();

    // Intermediate conversion to String is needed when direct conversion to Integer is not
    // available
    // but evaluation result is a textual representation of a numeric value.
    String text = expression.evaluate(exchange, String.class);
    try {
      int num = ExchangeHelper.convertToMandatoryType(exchange, Integer.class, text);
      count.set(num);
    } catch (NoTypeConversionAvailableException e) {
      exchange.setException(e);
      callback.done(true);
      return true;
    }

    // we hold on to the original Exchange in case it's needed for copies
    final Exchange original = exchange;

    // per-iteration exchange
    Exchange target = exchange;

    // set the size before we start
    exchange.setProperty(Exchange.LOOP_SIZE, count);

    // loop synchronously
    while (index.get() < count.get()) {

      // and prepare for next iteration
      // if (!copy) target = exchange; else copy of original
      target = prepareExchange(exchange, index.get(), original);
      boolean sync = process(target, callback, index, count, original);

      if (!sync) {
        LOG.trace(
            "Processing exchangeId: {} is continued being processed asynchronously",
            target.getExchangeId());
        // the remainder of the routing slip will be completed async
        // so we break out now, then the callback will be invoked which then continue routing from
        // where we left here
        return false;
      }

      LOG.trace(
          "Processing exchangeId: {} is continued being processed synchronously",
          target.getExchangeId());

      // increment counter before next loop
      index.getAndIncrement();
    }

    // we are done so prepare the result
    ExchangeHelper.copyResults(exchange, target);
    LOG.trace("Processing complete for exchangeId: {} >>> {}", exchange.getExchangeId(), exchange);
    callback.done(true);
    return true;
  }
Ejemplo n.º 3
0
 public void appendJmsProperty(
     Message jmsMessage,
     Exchange exchange,
     org.apache.camel.Message in,
     String headerName,
     Object headerValue)
     throws JMSException {
   if (isStandardJMSHeader(headerName)) {
     if (headerName.equals("JMSCorrelationID")) {
       jmsMessage.setJMSCorrelationID(
           ExchangeHelper.convertToType(exchange, String.class, headerValue));
     } else if (headerName.equals("JMSReplyTo") && headerValue != null) {
       if (headerValue instanceof String) {
         // if the value is a String we must normalize it first, and must include the prefix
         // as ActiveMQ requires that when converting the String to a javax.jms.Destination type
         headerValue = normalizeDestinationName((String) headerValue, true);
       }
       Destination replyTo =
           ExchangeHelper.convertToType(exchange, Destination.class, headerValue);
       JmsMessageHelper.setJMSReplyTo(jmsMessage, replyTo);
     } else if (headerName.equals("JMSType")) {
       jmsMessage.setJMSType(ExchangeHelper.convertToType(exchange, String.class, headerValue));
     } else if (headerName.equals("JMSPriority")) {
       jmsMessage.setJMSPriority(
           ExchangeHelper.convertToType(exchange, Integer.class, headerValue));
     } else if (headerName.equals("JMSDeliveryMode")) {
       JmsMessageHelper.setJMSDeliveryMode(exchange, jmsMessage, headerValue);
     } else if (headerName.equals("JMSExpiration")) {
       jmsMessage.setJMSExpiration(
           ExchangeHelper.convertToType(exchange, Long.class, headerValue));
     } else {
       // The following properties are set by the MessageProducer:
       // JMSDestination
       // The following are set on the underlying JMS provider:
       // JMSMessageID, JMSTimestamp, JMSRedelivered
       // log at trace level to not spam log
       LOG.trace("Ignoring JMS header: {} with value: {}", headerName, headerValue);
     }
   } else if (shouldOutputHeader(in, headerName, headerValue, exchange)) {
     // only primitive headers and strings is allowed as properties
     // see message properties: http://java.sun.com/j2ee/1.4/docs/api/javax/jms/Message.html
     Object value = getValidJMSHeaderValue(headerName, headerValue);
     if (value != null) {
       // must encode to safe JMS header name before setting property on jmsMessage
       String key = jmsKeyFormatStrategy.encodeKey(headerName);
       // set the property
       JmsMessageHelper.setProperty(jmsMessage, key, value);
     } else if (LOG.isDebugEnabled()) {
       // okay the value is not a primitive or string so we cannot sent it over the wire
       LOG.debug(
           "Ignoring non primitive header: {} of class: {} with value: {}",
           new Object[] {headerName, headerValue.getClass().getName(), headerValue});
     }
   }
 }
Ejemplo n.º 4
0
 /**
  * Prepares the exchange for the next iteration
  *
  * @param exchange the exchange
  * @param index the index of the next iteration
  * @return the exchange to use
  */
 protected Exchange prepareExchange(Exchange exchange, int index, Exchange original) {
   if (copy) {
     // use a copy but let it reuse the same exchange id so it appear as one exchange
     // use the original exchange rather than the looping exchange (esp. with the async routing
     // engine)
     return ExchangeHelper.createCopy(original, true);
   } else {
     ExchangeHelper.prepareOutToIn(exchange);
     return exchange;
   }
 }
 private ContentType getContentType(Exchange exchange) throws ParseException {
   String contentTypeStr = ExchangeHelper.getContentType(exchange);
   if (contentTypeStr == null) {
     contentTypeStr = DEFAULT_CONTENT_TYPE;
   }
   ContentType contentType = new ContentType(contentTypeStr);
   String contentEncoding = ExchangeHelper.getContentEncoding(exchange);
   // add a charset parameter for text subtypes
   if (contentEncoding != null && contentType.match("text/*")) {
     contentType.setParameter("charset", MimeUtility.mimeCharset(contentEncoding));
   }
   return contentType;
 }
  /** Strategy to determine if the exchange is done so we can continue */
  protected boolean isDone(Exchange exchange) {
    boolean answer = isCancelledOrInterrupted(exchange);

    // only done if the exchange hasn't failed
    // and it has not been handled by the failure processor
    // or we are exhausted
    if (!answer) {
      answer =
          exchange.getException() == null
              || ExchangeHelper.isFailureHandled(exchange)
              || ExchangeHelper.isRedeliveryExhausted(exchange);
    }

    log.trace("Is exchangeId: {} done? {}", exchange.getExchangeId(), answer);
    return answer;
  }
Ejemplo n.º 7
0
  protected Iterable<ProcessorExchangePair> createProcessorExchangePairs(Exchange exchange)
      throws Exception {
    List<ProcessorExchangePair> result = new ArrayList<ProcessorExchangePair>(processors.size());

    int index = 0;
    for (Processor processor : processors) {
      // copy exchange, and do not share the unit of work
      Exchange copy = ExchangeHelper.createCorrelatedCopy(exchange, false);

      // if we share unit of work, we need to prepare the child exchange
      if (isShareUnitOfWork()) {
        prepareSharedUnitOfWork(copy, exchange);
      }

      // and add the pair
      RouteContext routeContext =
          exchange.getUnitOfWork() != null ? exchange.getUnitOfWork().getRouteContext() : null;
      result.add(createProcessorExchangePair(index++, processor, copy, routeContext));
    }

    if (exchange.getException() != null) {
      // force any exceptions occurred during creation of exchange paris to be thrown
      // before returning the answer;
      throw exchange.getException();
    }

    return result;
  }
Ejemplo n.º 8
0
  protected void maybeDisconnectOnDone(Exchange exchange) {
    if (session == null) {
      return;
    }

    // should session be closed after complete?
    Boolean close;
    if (ExchangeHelper.isOutCapable(exchange)) {
      close =
          exchange
              .getOut()
              .getHeader(Mina2Constants.MINA_CLOSE_SESSION_WHEN_COMPLETE, Boolean.class);
    } else {
      close =
          exchange
              .getIn()
              .getHeader(Mina2Constants.MINA_CLOSE_SESSION_WHEN_COMPLETE, Boolean.class);
    }

    // should we disconnect, the header can override the configuration
    boolean disconnect = getEndpoint().getConfiguration().isDisconnect();
    if (close != null) {
      disconnect = close;
    }
    if (disconnect) {
      LOG.debug("Closing session when complete at address: {}", address);
      session.close(true);
    }
  }
Ejemplo n.º 9
0
 protected Endpoint resolveEndpoint(Exchange exchange, Object recipient) {
   // trim strings as end users might have added spaces between separators
   if (recipient instanceof String) {
     recipient = ((String) recipient).trim();
   }
   return ExchangeHelper.resolveEndpoint(exchange, recipient);
 }
Ejemplo n.º 10
0
  public void process(Exchange exchange) throws Exception {
    if (executor == null) {
      executor =
          exchange
              .getContext()
              .getExecutorServiceManager()
              .newFixedThreadPool(this, "CLAIM-CHECK", 4);
    }

    String id = tag.evaluate(exchange, String.class);
    exchange.setProperty(ClaimCheck.CLAIMCHECK_TAG_HEADER, id);

    final Producer conveyor = findDestination(exchange).createProducer();
    final Exchange baggage = ExchangeHelper.createCorrelatedCopy(exchange, false);

    LOG.info("Checking in 'baggage'");
    executor.submit(
        new Callable<Exchange>() {
          public Exchange call() throws Exception {
            try {
              LOG.debug("[claimcheck] {} {}", conveyor, baggage);
              conveyor.process(baggage);
            } catch (Throwable e) {
              LOG.warn(
                  "Error occurred during processing " + baggage + " checked in at " + conveyor, e);
            }
            return baggage;
          };
        });

    LOG.info("Continue normal flow without 'baggage'");
    Message out = exchange.getOut();
    out.setBody(value.evaluate(exchange, Object.class));
  }
  public synchronized void completedExchange(Exchange exchange, long time) {
    increment();
    exchangesCompleted.increment();
    exchangesInflight.decrement();

    if (ExchangeHelper.isFailureHandled(exchange)) {
      failuresHandled.increment();
    }
    Boolean externalRedelivered = exchange.isExternalRedelivered();
    if (externalRedelivered != null && externalRedelivered) {
      externalRedeliveries.increment();
    }

    minProcessingTime.updateValue(time);
    maxProcessingTime.updateValue(time);
    totalProcessingTime.updateValue(time);
    lastProcessingTime.updateValue(time);
    deltaProcessingTime.updateValue(time);

    long now = new Date().getTime();
    if (firstExchangeCompletedTimestamp.getUpdateCount() == 0) {
      firstExchangeCompletedTimestamp.updateValue(now);
    }

    lastExchangeCompletedTimestamp.updateValue(now);
    if (firstExchangeCompletedExchangeId == null) {
      firstExchangeCompletedExchangeId = exchange.getExchangeId();
    }
    lastExchangeCompletedExchangeId = exchange.getExchangeId();

    // update mean
    long count = exchangesCompleted.getValue();
    long mean = count > 0 ? totalProcessingTime.getValue() / count : 0;
    meanProcessingTime.updateValue(mean);
  }
Ejemplo n.º 12
0
  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);
  }
Ejemplo n.º 13
0
 /**
  * Performs a defensive copy of the exchange if needed
  *
  * @param exchange the exchange
  * @return the defensive copy, or <tt>null</tt> if not needed (redelivery is not enabled).
  */
 protected Exchange defensiveCopyExchangeIfNeeded(Exchange exchange) {
   // only do a defensive copy if redelivery is enabled
   if (redeliveryEnabled) {
     return ExchangeHelper.createCopy(exchange, true);
   } else {
     return null;
   }
 }
Ejemplo n.º 14
0
 @Override
 protected Object createBody() {
   if (mailMessage != null) {
     MailBinding binding = ExchangeHelper.getBinding(getExchange(), MailBinding.class);
     return binding != null ? binding.extractBodyFromMail(getExchange(), this) : null;
   }
   return null;
 }
Ejemplo n.º 15
0
  protected void handleException(Exchange exchange, RedeliveryData data) {
    Exception e = exchange.getException();

    // store the original caused exception in a property, so we can restore it later
    exchange.setProperty(Exchange.EXCEPTION_CAUGHT, e);

    // find the error handler to use (if any)
    OnExceptionDefinition exceptionPolicy = getExceptionPolicy(exchange, e);
    if (exceptionPolicy != null) {
      data.currentRedeliveryPolicy =
          exceptionPolicy.createRedeliveryPolicy(
              exchange.getContext(), data.currentRedeliveryPolicy);
      data.handledPredicate = exceptionPolicy.getHandledPolicy();
      data.continuedPredicate = exceptionPolicy.getContinuedPolicy();
      data.retryWhilePredicate = exceptionPolicy.getRetryWhilePolicy();
      data.useOriginalInMessage = exceptionPolicy.isUseOriginalMessage();
      data.asyncDelayedRedelivery = exceptionPolicy.isAsyncDelayedRedelivery(exchange.getContext());

      // route specific failure handler?
      Processor processor = exceptionPolicy.getErrorHandler();
      if (processor != null) {
        data.failureProcessor = processor;
      }
      // route specific on redelivery?
      processor = exceptionPolicy.getOnRedelivery();
      if (processor != null) {
        data.onRedeliveryProcessor = processor;
      }
    }

    // only log if not failure handled or not an exhausted unit of work
    if (!ExchangeHelper.isFailureHandled(exchange)
        && !ExchangeHelper.isUnitOfWorkExhausted(exchange)) {
      String msg =
          "Failed delivery for exchangeId: "
              + exchange.getExchangeId()
              + ". On delivery attempt: "
              + data.redeliveryCounter
              + " caught: "
              + e;
      logFailedDelivery(true, false, false, exchange, msg, data, e);
    }

    data.redeliveryCounter = incrementRedeliveryCounter(exchange, e, data);
  }
Ejemplo n.º 16
0
 /**
  * Aggregate the {@link Exchange} with the current result
  *
  * @param strategy the aggregation strategy to use
  * @param result the current result
  * @param exchange the exchange to be added to the result
  */
 protected synchronized void doAggregate(
     AggregationStrategy strategy, AtomicExchange result, Exchange exchange) {
   if (strategy != null) {
     // prepare the exchanges for aggregation
     Exchange oldExchange = result.get();
     ExchangeHelper.prepareAggregation(oldExchange, exchange);
     result.set(strategy.aggregate(oldExchange, exchange));
   }
 }
Ejemplo n.º 17
0
  /**
   * 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;
  }
Ejemplo n.º 18
0
 @Handler
 @Transactional
 @Override
 public void handle(Exchange exchange) throws InvalidPayloadException {
   Receipt receipt = ExchangeHelper.getMandatoryInBody(exchange, Receipt.class);
   if (!updateDatabase(receipt)) {
     LOG.warn(
         "Could not find batch for digipostBatchId='{}'. Stopping route.", receipt.getRefJobbId());
     exchange.setProperty(Exchange.ROUTE_STOP, true);
   }
 }
Ejemplo n.º 19
0
  private List<Map<String, Object>> executeQuery(Exchange exchange) throws Exception {
    String query = ExchangeHelper.getMandatoryInBody(exchange, String.class);
    boolean retrieveContent =
        exchange
            .getIn()
            .getHeader(CamelCMISConstants.CAMEL_CMIS_RETRIEVE_CONTENT, false, Boolean.class);
    int readSize =
        exchange.getIn().getHeader(CamelCMISConstants.CAMEL_CMIS_READ_SIZE, 0, Integer.class);

    ItemIterable<QueryResult> itemIterable = cmisSessionFacade.executeQuery(query);
    return cmisSessionFacade.retrieveResult(retrieveContent, readSize, itemIterable);
  }
Ejemplo n.º 20
0
 // HeaderFilterStrategyAware Methods
 // -------------------------------------------------------------------------
 protected void setCharsetWithContentType(Exchange camelExchange) {
   // setup the charset from content-type header
   String contentTypeHeader = ExchangeHelper.getContentType(camelExchange);
   if (contentTypeHeader != null) {
     String charset = HttpHeaderHelper.findCharset(contentTypeHeader);
     String normalizedEncoding =
         HttpHeaderHelper.mapCharset(charset, Charset.forName("UTF-8").name());
     if (normalizedEncoding != null) {
       camelExchange.setProperty(Exchange.CHARSET_NAME, normalizedEncoding);
     }
   }
 }
Ejemplo n.º 21
0
  public void process(Exchange exchange) throws Exception {
    notNull(getTemplate(), "template");

    if (isDeleteOutputFile()) {
      // add on completion so we can delete the file when the Exchange is done
      String fileName =
          ExchangeHelper.getMandatoryHeader(exchange, Exchange.XSLT_FILE_NAME, String.class);
      exchange.addOnCompletion(new XsltBuilderOnCompletion(fileName));
    }

    Transformer transformer = getTransformer();
    configureTransformer(transformer, exchange);

    ResultHandler resultHandler = resultHandlerFactory.createResult(exchange);
    Result result = resultHandler.getResult();
    // let's copy the headers before we invoke the transform in case they modify them
    Message out = exchange.getOut();
    out.copyFrom(exchange.getIn());

    // the underlying input stream, which we need to close to avoid locking files or other resources
    InputStream is = null;
    try {
      Source source;
      // only convert to input stream if really needed
      if (isInputStreamNeeded(exchange)) {
        is = exchange.getIn().getBody(InputStream.class);
        source = getSource(exchange, is);
      } else {
        Object body = exchange.getIn().getBody();
        source = getSource(exchange, body);
      }

      if (source instanceof StAXSource) {
        // Always convert StAXSource to SAXSource.
        // * Xalan and Saxon-B don't support StAXSource.
        // * The JDK default implementation (XSLTC) doesn't handle CDATA events
        //   (see com.sun.org.apache.xalan.internal.xsltc.trax.StAXStream2SAX).
        // * Saxon-HE/PE/EE seem to support StAXSource, but don't advertise this
        //   officially (via TransformerFactory.getFeature(StAXSource.FEATURE))
        source = new StAX2SAXSource(((StAXSource) source).getXMLStreamReader());
      }

      LOG.trace("Using {} as source", source);
      transformer.transform(source, result);
      LOG.trace("Transform complete with result {}", result);
      resultHandler.setBody(out);
    } finally {
      releaseTransformer(transformer);
      // IOHelper can handle if is is null
      IOHelper.close(is);
    }
  }
Ejemplo n.º 22
0
 @Override
 protected void populateInitialAttachments(Map<String, DataHandler> map) {
   if (mailMessage != null) {
     try {
       MailBinding binding = ExchangeHelper.getBinding(getExchange(), MailBinding.class);
       if (binding != null) {
         binding.extractAttachmentsFromMail(mailMessage, map);
       }
     } catch (Exception e) {
       throw new RuntimeCamelException("Error populating the initial mail message attachments", e);
     }
   }
 }
Ejemplo n.º 23
0
  public Object unmarshal(Exchange exchange, InputStream stream) throws Exception {
    InputStream is = ExchangeHelper.getMandatoryInBody(exchange, InputStream.class);
    GZIPInputStream unzipInput = new GZIPInputStream(is);

    // Create an expandable byte array to hold the inflated data
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try {
      IOHelper.copy(unzipInput, bos);
      return bos.toByteArray();
    } finally {
      IOHelper.close(unzipInput);
    }
  }
Ejemplo n.º 24
0
 @Override
 protected void populateInitialHeaders(Map<String, Object> map) {
   if (mailMessage != null) {
     try {
       MailBinding binding = ExchangeHelper.getBinding(getExchange(), MailBinding.class);
       if (binding != null) {
         map.putAll(binding.extractHeadersFromMail(mailMessage, getExchange()));
       }
     } catch (MessagingException e) {
       throw new RuntimeCamelException("Error accessing headers due to: " + e.getMessage(), e);
     }
   }
 }
Ejemplo n.º 25
0
  /** Strategy to determine if the exchange was cancelled or interrupted */
  protected boolean isCancelledOrInterrupted(Exchange exchange) {
    boolean answer = false;

    if (ExchangeHelper.isInterrupted(exchange)) {
      // mark the exchange to stop continue routing when interrupted
      // as we do not want to continue routing (for example a task has been cancelled)
      exchange.setProperty(Exchange.ROUTE_STOP, Boolean.TRUE);
      answer = true;
    }

    log.trace("Is exchangeId: {} interrupted? {}", exchange.getExchangeId(), answer);
    return answer;
  }
Ejemplo n.º 26
0
 @Override
 public void process(Exchange exchange) throws Exception {
   CamelExchange ex = new CamelExchange(exchange);
   if (ex.getState() != ExchangeState.FAULT) {
     Exception exception = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class);
     notifyListeners(exchange.getContext(), ex, exception);
     Throwable content = detectHandlerException(exception);
     org.switchyard.Property rollbackOnFaultProperty =
         ex.getContext().getProperty(org.switchyard.Exchange.ROLLBACK_ON_FAULT);
     if (rollbackOnFaultProperty == null || rollbackOnFaultProperty.getValue() == null) {
       ex.getContext()
           .setProperty(org.switchyard.Exchange.ROLLBACK_ON_FAULT, Boolean.TRUE, Scope.EXCHANGE);
     }
     ex.sendFault(ex.createMessage().setContent(content));
     ExchangeHelper.setFailureHandled(exchange);
   }
 }
Ejemplo n.º 27
0
 @SuppressWarnings("ThrowableResultOfMethodCallIgnored")
 @Override
 public void process(Exchange exchange) throws Exception {
   if (exchange.getIn().getBody() instanceof InputStream) {
     exchange.getIn().setBody(exchange.getContext().getStreamCachingStrategy().cache(exchange));
   }
   Exchange tempExchange = exchange.copy(true);
   try {
     for (int retry = 0; retry < endpoint.getMaxTries(); ++retry) {
       if (endpoint.getRetryDelay() > 0 && retry > 0) {
         Thread.sleep(endpoint.getRetryDelay());
       }
       endpoint.getTargetProducer().process(tempExchange);
       if (tempExchange.getException() == null) {
         onSuccess(tempExchange);
         return; // success
       }
       FailRetryException failure =
           getExceptionMatching(tempExchange.getException(), FailRetryException.class);
       if (failure != null) {
         if (!failure.isConsumed()) {
           failure.setConsumed(); // make it non-failure for surrounding retries
           return; // forward exception
         }
       }
       if (getExceptionMatching(tempExchange.getException(), endpoint.getException()) != null) {
         // retry
         LOGGER.debug("{} try {} failed", endpoint.getEndpointUri(), retry + 1);
         tempExchange = exchange.copy(true);
         if (exchange.getIn().getBody() instanceof StreamCache) {
           StreamCache is = (StreamCache) exchange.getIn().getBody();
           is.reset();
         }
       } else {
         return; // forward exception
       }
     }
     onExhausted(exchange);
     tempExchange.setException(
         new RetryExhaustedException("Retry exhausted", tempExchange.getException()));
   } finally {
     ExchangeHelper.copyResults(exchange, tempExchange);
   }
 }
Ejemplo n.º 28
0
  @SuppressWarnings("unchecked")
  public <T> T getProperty(String name, Object defaultValue, Class<T> type) {
    Object value = getProperty(name, defaultValue);
    if (value == null) {
      // lets avoid NullPointerException when converting to boolean for null values
      if (boolean.class.isAssignableFrom(type)) {
        return (T) Boolean.FALSE;
      }
      return null;
    }

    // eager same instance type test to avoid the overhead of invoking the type converter
    // if already same type
    if (type.isInstance(value)) {
      return type.cast(value);
    }

    return ExchangeHelper.convertToType(this, type, value);
  }
Ejemplo n.º 29
0
  public void process(Exchange exchange) throws Exception {
    notNull(getTemplate(), "template");

    if (isDeleteOutputFile()) {
      // add on completion so we can delete the file when the Exchange is done
      String fileName =
          ExchangeHelper.getMandatoryHeader(exchange, Exchange.XSLT_FILE_NAME, String.class);
      exchange.addOnCompletion(new XsltBuilderOnCompletion(fileName));
    }

    Transformer transformer = getTransformer();
    configureTransformer(transformer, exchange);

    ResultHandler resultHandler = resultHandlerFactory.createResult(exchange);
    Result result = resultHandler.getResult();
    exchange.setProperty("isXalanTransformer", isXalanTransformer(transformer));
    // let's copy the headers before we invoke the transform in case they modify them
    Message out = exchange.getOut();
    out.copyFrom(exchange.getIn());

    // the underlying input stream, which we need to close to avoid locking files or other resources
    InputStream is = null;
    try {
      Source source;
      // only convert to input stream if really needed
      if (isInputStreamNeeded(exchange)) {
        is = exchange.getIn().getBody(InputStream.class);
        source = getSource(exchange, is);
      } else {
        Object body = exchange.getIn().getBody();
        source = getSource(exchange, body);
      }
      LOG.trace("Using {} as source", source);
      transformer.transform(source, result);
      LOG.trace("Transform complete with result {}", result);
      resultHandler.setBody(out);
    } finally {
      releaseTransformer(transformer);
      // IOHelper can handle if is is null
      IOHelper.close(is);
    }
  }
Ejemplo n.º 30
0
  /**
   * Gets the Camel {@link Message} to use as the message to be set on the current {@link Exchange}
   * when we have received a reply message.
   *
   * <p>
   *
   * @param exchange the current exchange
   * @param messageEvent the incoming event which has the response message from Netty.
   * @return the Camel {@link Message} to set on the current {@link Exchange} as the response
   *     message.
   * @throws Exception is thrown if error getting the response message
   */
  protected Message getResponseMessage(Exchange exchange, MessageEvent messageEvent)
      throws Exception {
    Object body = messageEvent.getMessage();
    if (LOG.isDebugEnabled()) {
      LOG.debug("Channel: {} received body: {}", new Object[] {messageEvent.getChannel(), body});
    }

    // if textline enabled then covert to a String which must be used for textline
    if (producer.getConfiguration().isTextline()) {
      body =
          producer.getContext().getTypeConverter().mandatoryConvertTo(String.class, exchange, body);
    }

    // set the result on either IN or OUT on the original exchange depending on its pattern
    if (ExchangeHelper.isOutCapable(exchange)) {
      NettyPayloadHelper.setOut(exchange, body);
      return exchange.getOut();
    } else {
      NettyPayloadHelper.setIn(exchange, body);
      return exchange.getIn();
    }
  }