id
stringlengths
33
40
content
stringlengths
662
61.5k
max_stars_repo_path
stringlengths
85
97
bugs-dot-jar_data_CAMEL-3498_b4606700
--- BugID: CAMEL-3498 Summary: 'Splitter Component: Setting ''streaming = "true"'' breaks error handling' Description: | Setting 'streaming = "true"' breaks error handling: If an exception is thrown in a processor, the exception in the subExchange is copied to the original exchange in MulticastProcessor line 554. In Splitter line 140 the original exchange is copied, including the exception that was thrown while processing the previous exchange. This prevents all subsequent exchanges from being processed successfully. diff --git a/camel-core/src/main/java/org/apache/camel/processor/Splitter.java b/camel-core/src/main/java/org/apache/camel/processor/Splitter.java index 97e5178..6d585fb 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/Splitter.java +++ b/camel-core/src/main/java/org/apache/camel/processor/Splitter.java @@ -109,6 +109,9 @@ public class Splitter extends MulticastProcessor implements AsyncProcessor, Trac private Iterable<ProcessorExchangePair> createProcessorExchangePairsIterable(final Exchange exchange, final Object value) { final Iterator iterator = ObjectHelper.createIterator(value); return new Iterable() { + // create a copy which we use as master to copy during splitting + // this avoids any side effect reflected upon the incoming exchange + private final Exchange copy = ExchangeHelper.createCopy(exchange, true); public Iterator iterator() { return new Iterator() { @@ -137,7 +140,8 @@ public class Splitter extends MulticastProcessor implements AsyncProcessor, Trac public Object next() { Object part = iterator.next(); - Exchange newExchange = ExchangeHelper.createCopy(exchange, true); + // create a copy as the new exchange to be routed in the splitter from the copy + Exchange newExchange = ExchangeHelper.createCopy(copy, true); if (part instanceof Message) { newExchange.setIn((Message)part); } else {
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-3498_b4606700.diff
bugs-dot-jar_data_CAMEL-5140_8898d491
--- BugID: CAMEL-5140 Summary: bean component - @Handler should take precedence in a bean that implements Predicate Description: If you use a bean in a Camel route, and have not specified the method name to invoke. Then Camel has to scan for suitable methods to use. And for that we have the @Handler annotation which should take precedence in this process. However if the bean implements Predicate, or Processor, then Camel will use that. However the @Handler should be used instead, as this is what the end-user expects. And also what we tell in the docs. diff --git a/camel-core/src/main/java/org/apache/camel/component/bean/BeanProcessor.java b/camel-core/src/main/java/org/apache/camel/component/bean/BeanProcessor.java index 536a07f..f3e5485 100644 --- a/camel-core/src/main/java/org/apache/camel/component/bean/BeanProcessor.java +++ b/camel-core/src/main/java/org/apache/camel/component/bean/BeanProcessor.java @@ -89,17 +89,19 @@ public class BeanProcessor extends ServiceSupport implements AsyncProcessor { } // do we have a custom adapter for this POJO to a Processor - // should not be invoked if an explicit method has been set - Processor processor = getProcessor(); - if (explicitMethodName == null && processor != null) { - LOG.trace("Using a custom adapter as bean invocation: {}", processor); - try { - processor.process(exchange); - } catch (Throwable e) { - exchange.setException(e); + // but only do this if allowed + if (allowProcessor(explicitMethodName, beanInfo)) { + Processor processor = getProcessor(); + if (processor != null) { + LOG.trace("Using a custom adapter as bean invocation: {}", processor); + try { + processor.process(exchange); + } catch (Throwable e) { + exchange.setException(e); + } + callback.done(true); + return true; } - callback.done(true); - return true; } Message in = exchange.getIn(); @@ -253,4 +255,23 @@ public class BeanProcessor extends ServiceSupport implements AsyncProcessor { protected void doStop() throws Exception { ServiceHelper.stopService(getProcessor()); } + + private boolean allowProcessor(String explicitMethodName, BeanInfo info) { + if (explicitMethodName != null) { + // don't allow if explicit method name is given, as we then must invoke this method + return false; + } + + // don't allow if any of the methods has a @Handler annotation + // as the @Handler annotation takes precedence and is supposed to trigger invocation + // of the given method + for (MethodInfo method : info.getMethods()) { + if (method.hasHandlerAnnotation()) { + return false; + } + } + + // fallback and allow using the processor + return true; + } }
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-5140_8898d491.diff
bugs-dot-jar_data_CAMEL-8592_57f72cd9
--- BugID: CAMEL-8592 Summary: NPE in AbstractListAggregationStrategy if empty list Description: |- See nabble http://camel.465427.n5.nabble.com/NullPointerException-on-empty-List-in-AbstractListAggregationStrategy-tp5764965.html diff --git a/camel-core/src/main/java/org/apache/camel/processor/aggregate/AbstractListAggregationStrategy.java b/camel-core/src/main/java/org/apache/camel/processor/aggregate/AbstractListAggregationStrategy.java index ad2ec8e..d4ff93f 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/aggregate/AbstractListAggregationStrategy.java +++ b/camel-core/src/main/java/org/apache/camel/processor/aggregate/AbstractListAggregationStrategy.java @@ -62,7 +62,7 @@ public abstract class AbstractListAggregationStrategy<V> implements CompletionAw @SuppressWarnings("unchecked") public void onCompletion(Exchange exchange) { - if (isStoreAsBodyOnCompletion()) { + if (exchange != null && isStoreAsBodyOnCompletion()) { List<V> list = (List<V>) exchange.removeProperty(Exchange.GROUPED_EXCHANGE); if (list != null) { exchange.getIn().setBody(list);
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-8592_57f72cd9.diff
bugs-dot-jar_data_CAMEL-6948_f744afd9
--- BugID: CAMEL-6948 Summary: ProducerCache should not only stop non-singelton Producers but also shutdown them afterwards as well if the given Producer is a ShutdownableService Description: |- Currently because of this bug the {{doShutdown}} hook of the following non-singleton Producers doesn't kick in at all: - {{JpaProducer}} - {{Mina2Producer}} Which could cause resources leaking. diff --git a/camel-core/src/main/java/org/apache/camel/impl/ProducerCache.java b/camel-core/src/main/java/org/apache/camel/impl/ProducerCache.java index 6b292c0..b35eca5 100644 --- a/camel-core/src/main/java/org/apache/camel/impl/ProducerCache.java +++ b/camel-core/src/main/java/org/apache/camel/impl/ProducerCache.java @@ -30,6 +30,7 @@ import org.apache.camel.Processor; import org.apache.camel.Producer; import org.apache.camel.ProducerCallback; import org.apache.camel.ServicePoolAware; +import org.apache.camel.ShutdownableService; import org.apache.camel.processor.UnitOfWorkProducer; import org.apache.camel.spi.ServicePool; import org.apache.camel.support.ServiceSupport; @@ -137,6 +138,11 @@ public class ProducerCache extends ServiceSupport { } else if (!producer.isSingleton()) { // stop non singleton producers as we should not leak resources producer.stop(); + + // shutdown as well in case the producer is shutdownable + if (producer instanceof ShutdownableService) { + ShutdownableService.class.cast(producer).shutdown(); + } } }
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-6948_f744afd9.diff
bugs-dot-jar_data_CAMEL-6667_1fc7bd7a
--- BugID: CAMEL-6667 Summary: Loop EIP doesn't honour copy option in some circumstances Description: "Happens when the Async Routing Engine variant of the Loop logic kicks in, and there are more than two processors in the loop body, e.g. \n\\\\\n\\\\\n{code:java}\n.loop(3)\n \ .to(\"activemq:queue:abc?exchangePattern=InOut\")\n .to(\"activemq:queue:def?exchangePattern=InOut\")\n.end()\n{code}\n\nThe wrong inflight Exchange is copied (instead of the original one), and since the implicit Pipeline has copied the OUT message from the 1st endpoint to the IN message, the original IN message is lost fully." diff --git a/camel-core/src/main/java/org/apache/camel/processor/LoopProcessor.java b/camel-core/src/main/java/org/apache/camel/processor/LoopProcessor.java index df2baed..89649b1 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/LoopProcessor.java +++ b/camel-core/src/main/java/org/apache/camel/processor/LoopProcessor.java @@ -60,7 +60,11 @@ public class LoopProcessor extends DelegateAsyncProcessor implements Traceable { 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 @@ -70,8 +74,9 @@ public class LoopProcessor extends DelegateAsyncProcessor implements Traceable { while (index.get() < count.get()) { // and prepare for next iteration - target = prepareExchange(exchange, index.get()); - boolean sync = process(target, callback, index, count); + // 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()); @@ -94,12 +99,13 @@ public class LoopProcessor extends DelegateAsyncProcessor implements Traceable { } protected boolean process(final Exchange exchange, final AsyncCallback callback, - final AtomicInteger index, final AtomicInteger count) { + final AtomicInteger index, final AtomicInteger count, + final Exchange original) { // set current index as property LOG.debug("LoopProcessor: iteration #{}", index.get()); exchange.setProperty(Exchange.LOOP_INDEX, index.get()); - + boolean sync = processor.process(exchange, new AsyncCallback() { public void done(boolean doneSync) { // we only have to handle async completion of the routing slip @@ -116,10 +122,10 @@ public class LoopProcessor extends DelegateAsyncProcessor implements Traceable { while (index.get() < count.get()) { // and prepare for next iteration - target = prepareExchange(exchange, index.get()); + target = prepareExchange(exchange, index.get(), original); // process again - boolean sync = process(target, callback, index, count); + 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 @@ -148,10 +154,11 @@ public class LoopProcessor extends DelegateAsyncProcessor implements Traceable { * @param index the index of the next iteration * @return the exchange to use */ - protected Exchange prepareExchange(Exchange exchange, int index) { + 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 - return ExchangeHelper.createCopy(exchange, true); + // 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;
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-6667_1fc7bd7a.diff
bugs-dot-jar_data_CAMEL-6810_6b210169
--- BugID: CAMEL-6810 Summary: 'Bean Component/BeanBinding: Body as InputStream parametr (specified as ${body} in route)' Description: "I discovered following problem (which was already shortly discussed in [Camel user forum|http://camel.465427.n5.nabble.com/Bean-component-Bean-Binding-Body-as-InputStream-parametr-specified-as-body-in-route-td5740656.ht]).\n\nI have a \"streamBodyBindingBean\" bean with this method:\n{code}\npublic void bodyBinding(InputStream in) throws IOException {\n int byteCount = 0;\n int c;\n while((c = in.read()) != -1)\n byteCount++;\n System.out.println(\"ByteCount: \" + byteCount);\n}\n{code}\n\nAnd this route:\n{code}\n<route id=\"\" trace=\"true\">\n <from uri=\"direct://body-input-stream-binding-in\"/>\n \ <to uri=\"bean://streamBodyBindingBean?method=bodyBinding(${body})\"/>\n <!-- to uri=\"bean://isBodyBindingBean\"/--> \n <to uri=\"mock://body-input-stream-binding-out\"/>\n</route>\n{code}\n\nAnd here is a way how I send exchange from test stuff:\n{code}\nByteArrayInputStream in = new ByteArrayInputStream(\n \"Small body, which I want to bind as InputStream\".getBytes(\"UTF-8\")\n);\nExchange exchange = createExchangeWithBody(in);\nexchange.setPattern(ExchangePattern.InOnly);\ntemplate.send(\"direct://body-input-stream-binding-in\", exchange); \n{code}\n\nIn this case I got a sysout message: {{ByteCount: 0}}, but when I used the commented variant in the route, I got expected result: {{ByteCount: 47\"}}.\n\nWhen I change the route and use bean component 2 times (both variant of bean method invocation), then I got:\n\n{noformat}\n2013-10-01 12:26:37.259 DEBUG {main} [SendProcessor] >>>> Endpoint[bean://isBodyBindingBean?method=bodyBinding%28%24%7Bbody%7D%29] Exchange[Message: [Body is instance of org.apache.camel.StreamCache]]\nByteCount: 0\n2013-10-01 12:26:37.289 DEBUG {main} [SendProcessor] >>>> Endpoint[bean://isBodyBindingBean] Exchange[Message: [Body is instance of org.apache.camel.StreamCache]]\nByteCount: 47\n2013-10-01 12:26:37.307 DEBUG {main} [SendProcessor] >>>> Endpoint[mock://body-input-stream-binding-out] Exchange[Message: [Body is instance of org.apache.camel.StreamCache]] \n{noformat}\n\nThe strange for me is {{MethodInfo}} class, line 526:\n{code}\n// the parameter value was not already valid, but since the simple language have evaluated the expression\n// which may change the parameterValue, so we have to check it again to see if its now valid\nexp = exchange.getContext().getTypeConverter().convertTo(String.class, parameterValue);\n// String values from the simple language is always valid\nif (!valid) {\n ...\n}\n{code}\n\nThe line after comment caused that my \"InputStream\" is transformed into String, what can be a problem in case of \"big\" InputStream.\n\nI know that I can use only second variant of \"bean method invocation\", which is enough for my need, but I only want to point out to this situation." diff --git a/camel-core/src/main/java/org/apache/camel/component/bean/MethodInfo.java b/camel-core/src/main/java/org/apache/camel/component/bean/MethodInfo.java index a4dd2e0..0c22e75 100644 --- a/camel-core/src/main/java/org/apache/camel/component/bean/MethodInfo.java +++ b/camel-core/src/main/java/org/apache/camel/component/bean/MethodInfo.java @@ -393,8 +393,6 @@ public class MethodInfo { /** * Returns true if this method is covariant with the specified method * (this method may above or below the specified method in the class hierarchy) - * @param method - * @return */ public boolean isCovariantWith(MethodInfo method) { return @@ -541,13 +539,18 @@ public class MethodInfo { return Void.TYPE; } - // the parameter value was not already valid, but since the simple language have evaluated the expression - // which may change the parameterValue, so we have to check it again to see if its now valid - exp = exchange.getContext().getTypeConverter().convertTo(String.class, parameterValue); - // String values from the simple language is always valid - if (!valid) { - // re validate if the parameter was not valid the first time (String values should be accepted) - valid = parameterValue instanceof String || BeanHelper.isValidParameterValue(exp); + // the parameter value may match the expected type, then we use it as-is + if (parameterType.isAssignableFrom(parameterValue.getClass())) { + valid = true; + } else { + // the parameter value was not already valid, but since the simple language have evaluated the expression + // which may change the parameterValue, so we have to check it again to see if its now valid + exp = exchange.getContext().getTypeConverter().tryConvertTo(String.class, parameterValue); + // String values from the simple language is always valid + if (!valid) { + // re validate if the parameter was not valid the first time (String values should be accepted) + valid = parameterValue instanceof String || BeanHelper.isValidParameterValue(exp); + } } if (valid) {
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-6810_6b210169.diff
bugs-dot-jar_data_CAMEL-5683_0c3c7d1b
--- BugID: CAMEL-5683 Summary: JMS connection leak with request/reply producer on temporary queues Description: |+ Over time I see the number of temporary queues in ActiveMQ slowly climb. Using JMX information and memory dumps in MAT, I believe the cause is a connection leak in Apache Camel. My environment contains 2 ActiveMQ brokers in a network of brokers configuration. There are about 15 separate applications which use Apache Camel to connect to the broker using the ActiveMQ/JMS component. The various applications have different load profiles and route configurations. In the more active client applications, I found that ActiveMQ was listing 300+ consumers when, based on my configuration, I would expect no more than 75. The vast majority of the consumers are sitting on a temporary queue. Over time, the 300 number increments by one or two over about a 4 hour period. I did a memory dump on one of the more active client applications and found about 275 DefaultMessageListenerContainers. Using MAT, I can see that some of the containers are referenced by JmsProducers in the ProducerCache; however I can also see a large number of listener containers that are no longer being referenced at all. I was also able to match up a soft-references producer/listener endpoint with an unreferenced listener which means a second producer was created at some point. Looking through the ProducerCache code, it looks like the LRU cache uses soft-references to producers, in my case a JmsProducer. This seems problematic for two reasons: - If memory gets constrained and the GC cleans up a producer, it is never properly stopped. - If the cache gets full and the map removes the LRU producer, it is never properly stopped. What I believe is happening, is that my application is sending a few request/reply messages to a JmsProducer. The producer creates a TemporaryReplyManager which creates a DefaultMessageListenerContainer. At some point, the JmsProducer is claimed by the GC (either via the soft-reference or because the cache is full) and the reply manager is never stopped. This causes the listener container to continue to listen on the temporary queue, consuming local resources and more importantly, consuming resources on the JMS broker. I haven't had a chance to write an application to reproduce this behavior, but I will attach one of my route configurations and a screenshot of the MAT analysis looking at DefaultMessageListenerContainers. If needed, I could provide the entire memory dump for analysis (although I rather not post it publicly). The leak depends on memory usage or producer count in the client application because the ProducerCache must have some churn. Like I said, in our production system we see about 12 temporary queues abandoned per client per day. Unless I'm missing something, it looks like the producer cache would need to be much smarter to support stopping a producer when the soft-reference is reclaimed or a member of the cache is ejected from the LRU list. diff --git a/camel-core/src/main/java/org/apache/camel/impl/ConsumerCache.java b/camel-core/src/main/java/org/apache/camel/impl/ConsumerCache.java index 16be6ab..cadb98a 100644 --- a/camel-core/src/main/java/org/apache/camel/impl/ConsumerCache.java +++ b/camel-core/src/main/java/org/apache/camel/impl/ConsumerCache.java @@ -27,7 +27,6 @@ import org.apache.camel.PollingConsumer; import org.apache.camel.support.ServiceSupport; import org.apache.camel.util.CamelContextHelper; import org.apache.camel.util.LRUCache; -import org.apache.camel.util.LRUSoftCache; import org.apache.camel.util.ServiceHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -60,14 +59,17 @@ public class ConsumerCache extends ServiceSupport { /** * Creates the {@link LRUCache} to be used. * <p/> - * This implementation returns a {@link org.apache.camel.util.LRUSoftCache} instance. + * This implementation returns a {@link LRUCache} instance. * @param cacheSize the cache size * @return the cache */ protected static LRUCache<String, PollingConsumer> createLRUCache(int cacheSize) { - // We use a soft reference cache to allow the JVM to re-claim memory if it runs low on memory. - return new LRUSoftCache<String, PollingConsumer>(cacheSize); + // Use a regular cache as we want to ensure that the lifecycle of the consumers + // being cache is properly handled, such as they are stopped when being evicted + // or when this cache is stopped. This is needed as some consumers requires to + // be stopped so they can shutdown internal resources that otherwise may cause leaks + return new LRUCache<String, PollingConsumer>(cacheSize); } public synchronized PollingConsumer getConsumer(Endpoint endpoint) { diff --git a/camel-core/src/main/java/org/apache/camel/impl/ProducerCache.java b/camel-core/src/main/java/org/apache/camel/impl/ProducerCache.java index 89fadb0..8c5f976 100644 --- a/camel-core/src/main/java/org/apache/camel/impl/ProducerCache.java +++ b/camel-core/src/main/java/org/apache/camel/impl/ProducerCache.java @@ -37,7 +37,6 @@ import org.apache.camel.util.AsyncProcessorConverterHelper; import org.apache.camel.util.CamelContextHelper; import org.apache.camel.util.EventHelper; import org.apache.camel.util.LRUCache; -import org.apache.camel.util.LRUSoftCache; import org.apache.camel.util.ServiceHelper; import org.apache.camel.util.StopWatch; import org.slf4j.Logger; @@ -78,14 +77,17 @@ public class ProducerCache extends ServiceSupport { /** * Creates the {@link LRUCache} to be used. * <p/> - * This implementation returns a {@link LRUSoftCache} instance. + * This implementation returns a {@link LRUCache} instance. * @param cacheSize the cache size * @return the cache */ protected static LRUCache<String, Producer> createLRUCache(int cacheSize) { - // We use a soft reference cache to allow the JVM to re-claim memory if it runs low on memory. - return new LRUSoftCache<String, Producer>(cacheSize); + // Use a regular cache as we want to ensure that the lifecycle of the producers + // being cache is properly handled, such as they are stopped when being evicted + // or when this cache is stopped. This is needed as some producers requires to + // be stopped so they can shutdown internal resources that otherwise may cause leaks + return new LRUCache<String, Producer>(cacheSize); } public CamelContext getCamelContext() {
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-5683_0c3c7d1b.diff
bugs-dot-jar_data_CAMEL-7016_4ed448c7
--- BugID: CAMEL-7016 Summary: JMX - Update route from xml on route mbean should update current route only Description: |- If you do not have id of the route in the XML then Camel thinks its a new route to be added. We should ensure we handle that, and only update current route as that is the intend of this operation. If you want to add new routes use mbean operation on camelcontext instead. diff --git a/camel-core/src/main/java/org/apache/camel/management/mbean/ManagedRoute.java b/camel-core/src/main/java/org/apache/camel/management/mbean/ManagedRoute.java index b1cc984..51ce287 100644 --- a/camel-core/src/main/java/org/apache/camel/management/mbean/ManagedRoute.java +++ b/camel-core/src/main/java/org/apache/camel/management/mbean/ManagedRoute.java @@ -230,6 +230,16 @@ public class ManagedRoute extends ManagedPerformanceCounter implements TimerList return; } + // if the xml does not contain the route-id then we fix this by adding the actual route id + // this may be needed if the route-id was auto-generated, as the intend is to update this route + // and not add a new route, adding a new route, use the MBean operation on ManagedCamelContext instead. + if (ObjectHelper.isEmpty(def.getId())) { + def.setId(getRouteId()); + } else if (!def.getId().equals(getRouteId())) { + throw new IllegalArgumentException("Cannot update route from XML as routeIds does not match. routeId: " + + getRouteId() + ", routeId from XML: " + def.getId()); + } + // add will remove existing route first context.addRouteDefinition(def); }
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-7016_4ed448c7.diff
bugs-dot-jar_data_CAMEL-8626_d063f471
--- BugID: CAMEL-8626 Summary: Leaking exchangesInFlightKeys in ManagedRoute Description: | Having a camel context with a single route: {code} onException(Throwable.class) .handled(true) .process(handleException()); // essentially doing exchange.setException(someConvertedException); from("direct:generalFlow") .routingSlip(property(GeneralFlowRoute.class.getName())); {code} started from Spring: {code} <camelContext id="flows" xmlns="http://camel.apache.org/schema/spring"> <template id="template" defaultEndpoint="direct:generalFlow"/> <routeBuilder ref="generalFlow"/> </camelContext> <bean id="generalFlow" class="com.blabla.GeneralFlowRoute"/> {code} During performance test both exchangesInFlightKeys and exchangesInFlightStartTimestamps are accumulating over time. But if the test is run in one thread with debug - nothing is accumulated. Issue found after migration from 2.14.1 to 2.15.1 diff --git a/camel-core/src/main/java/org/apache/camel/management/mbean/ManagedRoute.java b/camel-core/src/main/java/org/apache/camel/management/mbean/ManagedRoute.java index d31e4e5..c4b6d85 100644 --- a/camel-core/src/main/java/org/apache/camel/management/mbean/ManagedRoute.java +++ b/camel-core/src/main/java/org/apache/camel/management/mbean/ManagedRoute.java @@ -417,8 +417,8 @@ public class ManagedRoute extends ManagedPerformanceCounter implements TimerList @Override public void init(ManagementStrategy strategy) { - super.init(strategy); exchangesInFlightStartTimestamps.clear(); + super.init(strategy); } @Override @@ -438,14 +438,23 @@ public class ManagedRoute extends ManagedPerformanceCounter implements TimerList super.completedExchange(exchange, time); } + @Override + public synchronized void failedExchange(Exchange exchange) { + InFlightKey key = exchangesInFlightKeys.remove(exchange.getExchangeId()); + if (key != null) { + exchangesInFlightStartTimestamps.remove(key); + } + super.failedExchange(exchange); + } + private static class InFlightKey implements Comparable<InFlightKey> { private final Long timeStamp; private final String exchangeId; InFlightKey(Long timeStamp, String exchangeId) { - this.exchangeId = exchangeId; this.timeStamp = timeStamp; + this.exchangeId = exchangeId; } @Override
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-8626_d063f471.diff
bugs-dot-jar_data_CAMEL-7125_6641f182
--- BugID: CAMEL-7125 Summary: tokenizeXml fails when attributes have a / in them Description: |- {{tokenizeXml}} does not work or produce value xml output when attributes contain a {{/}}. The test below will fail under 2.12.2 {code:java} import org.apache.camel.EndpointInject; import org.apache.camel.Produce; import org.apache.camel.ProducerTemplate; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.test.junit4.CamelTestSupport; import org.junit.Test; public class CamelTokenizeXmlTest extends CamelTestSupport { @EndpointInject(uri = "mock:result") protected MockEndpoint resultEndpoint; @Produce(uri = "direct:start") protected ProducerTemplate template; @Test public void testXmlWithSlash() throws Exception { String message = "<parent><child attr='/' /></parent>"; resultEndpoint.expectedBodiesReceived("<child attr='/' />"); template.sendBody(message); resultEndpoint.assertIsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:start").split().tokenizeXML("child").to("mock:result"); } }; } } {code} diff --git a/camel-core/src/main/java/org/apache/camel/support/TokenXMLExpressionIterator.java b/camel-core/src/main/java/org/apache/camel/support/TokenXMLExpressionIterator.java index 3048c64..ba21a71 100644 --- a/camel-core/src/main/java/org/apache/camel/support/TokenXMLExpressionIterator.java +++ b/camel-core/src/main/java/org/apache/camel/support/TokenXMLExpressionIterator.java @@ -47,7 +47,7 @@ import org.apache.camel.util.ObjectHelper; public class TokenXMLExpressionIterator extends ExpressionAdapter { private static final Pattern NAMESPACE_PATTERN = Pattern.compile("xmlns(:\\w+|)\\s*=\\s*('[^']+'|\"[^\"]+\")"); private static final String SCAN_TOKEN_NS_PREFIX_REGEX = "([^:<>]{1,15}?:|)"; - private static final String SCAN_BLOCK_TOKEN_REGEX_TEMPLATE = "<{0}(\\s+[^/^>]*)?/>|<{0}(\\s+[^>]*)?>(?:(?!(</{0}\\s*>)).)*</{0}\\s*>"; + private static final String SCAN_BLOCK_TOKEN_REGEX_TEMPLATE = "<{0}(\\s+[^>]*)?/>|<{0}(\\s+[^>]*)?>(?:(?!(</{0}\\s*>)).)*</{0}\\s*>"; private static final String SCAN_PARENT_TOKEN_REGEX_TEMPLATE = "<{0}(\\s+[^>]*\\s*)?>"; protected final String tagToken;
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-7125_6641f182.diff
bugs-dot-jar_data_CAMEL-6610_ed7e7c9f
--- BugID: CAMEL-6610 Summary: Always got IndexOutOfBoundsException when customized id of wireTap component Description: "when I'm tring to execute below route:\n{code}\nfrom(\"timer:foo\").wireTap(\"direct:a\").id(\"wiretap_1\").to(\"log:a\");\nfrom(\"direct:a\").to(\"log:b\");\n{code}\nI always got IndexOutOfBoundsException:\n{color:red}\nException in thread \"main\" java.lang.IndexOutOfBoundsException: Index: -1\n\tat java.util.Collections$EmptyList.get(Collections.java:3212)\n\tat org.apache.camel.model.ProcessorDefinition.id(ProcessorDefinition.java:1025)\n\tat org.talend.esb.liugang.camel.wiretap.TestWiretap$1.configure(TestWiretap.java:14)\n\tat org.apache.camel.builder.RouteBuilder.checkInitialized(RouteBuilder.java:322)\n\tat org.apache.camel.builder.RouteBuilder.configureRoutes(RouteBuilder.java:276)\n\tat org.apache.camel.builder.RouteBuilder.addRoutesToCamelContext(RouteBuilder.java:262)\n\tat org.apache.camel.impl.DefaultCamelContext.addRoutes(DefaultCamelContext.java:650)\n\tat org.talend.esb.liugang.camel.wiretap.TestWiretap.main(TestWiretap.java:10)\n{color}\nI tried on 2.11.1, 2.11.2-SNAPSHOT, both of them have the same problem (not sure 2.12-SNAPSHOT)." diff --git a/camel-core/src/main/java/org/apache/camel/model/ProcessorDefinition.java b/camel-core/src/main/java/org/apache/camel/model/ProcessorDefinition.java index ff16150..9b93a1a 100644 --- a/camel-core/src/main/java/org/apache/camel/model/ProcessorDefinition.java +++ b/camel-core/src/main/java/org/apache/camel/model/ProcessorDefinition.java @@ -1015,6 +1015,7 @@ public abstract class ProcessorDefinition<Type extends ProcessorDefinition<Type> // set id on this setId(id); } else { + // set it on last output as this is what the user means to do // for Block(s) with non empty getOutputs() the id probably refers // to the last definition in the current Block @@ -1027,7 +1028,12 @@ public abstract class ProcessorDefinition<Type extends ProcessorDefinition<Type> } } } - outputs.get(outputs.size() - 1).setId(id); + if (!getOutputs().isEmpty()) { + outputs.get(outputs.size() - 1).setId(id); + } else { + // the output could be empty + setId(id); + } } return (Type) this;
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-6610_ed7e7c9f.diff
bugs-dot-jar_data_CAMEL-5707_3f70d612
--- BugID: CAMEL-5707 Summary: NotifyBuilder should be thread safe Description: In high concurrent tests the NotifyBuilder may miss a counter. diff --git a/camel-core/src/main/java/org/apache/camel/builder/NotifyBuilder.java b/camel-core/src/main/java/org/apache/camel/builder/NotifyBuilder.java index 547efab..d5a346c 100644 --- a/camel-core/src/main/java/org/apache/camel/builder/NotifyBuilder.java +++ b/camel-core/src/main/java/org/apache/camel/builder/NotifyBuilder.java @@ -444,7 +444,7 @@ public class NotifyBuilder { @Override public boolean onExchangeCompleted(Exchange exchange) { if (exchange.getExchangeId().equals(id)) { - done.set(false); + done.set(true); } return true; }
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-5707_3f70d612.diff
bugs-dot-jar_data_CAMEL-7130_cc192f87
--- BugID: CAMEL-7130 Summary: Set XsltBuilder allowStax attribute to be true by default Description: It could be more effective and safe to use the stax API by default. diff --git a/camel-core/src/main/java/org/apache/camel/builder/xml/XsltBuilder.java b/camel-core/src/main/java/org/apache/camel/builder/xml/XsltBuilder.java index 3a7b9a4..d4291b2 100644 --- a/camel-core/src/main/java/org/apache/camel/builder/xml/XsltBuilder.java +++ b/camel-core/src/main/java/org/apache/camel/builder/xml/XsltBuilder.java @@ -452,9 +452,6 @@ public class XsltBuilder implements Processor { return (Source) body; } Source source = null; - if (body instanceof InputStream) { - return new StreamSource((InputStream)body); - } if (body != null) { if (isAllowStAX()) { source = exchange.getContext().getTypeConverter().tryConvertTo(StAXSource.class, exchange, body);
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-7130_cc192f87.diff
bugs-dot-jar_data_CAMEL-9340_1cab39f6
--- BugID: CAMEL-9340 Summary: FileIdempotentRepository fails to create fileStore when no path is specified Description: "I create a FileIdempotentRepository like this:\n\n{code}\n.idempotentConsumer(fileIdempotentRepository(new File('ids'))) {\n it.in.body.id\n}\n{code}\n\nI get an error, and I traced it to:\n{noformat}\nCaused by: java.lang.NullPointerException: null\n\tat org.apache.camel.processor.idempotent.mpotentRepository.loadStore(FileIdempotentRepository.java:293) ~[camel-core-2.16.0.jar:2.16.0]\n\tat org.apache.camel.processor.idempotent.FileIdempotentRepository.doStart(FileIdempotentRepository.java:328) ~[camel-core-2.16.0.jar:2.16.0]\n{noformat}\n\nThe FileIdempotentRepository is trying to create the parent directory of the file that was specified for the file store. If a path to the file is not specified, then getParentFile() returns null. Calling .mkdirs() on that bombs.\n\nThis route works the second time it runs because then the file exists. It also works if I specify my file name as \"./ids\" instead of \"ids\"." diff --git a/camel-core/src/main/java/org/apache/camel/processor/idempotent/FileIdempotentRepository.java b/camel-core/src/main/java/org/apache/camel/processor/idempotent/FileIdempotentRepository.java index 301fb0d..2451daf 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/idempotent/FileIdempotentRepository.java +++ b/camel-core/src/main/java/org/apache/camel/processor/idempotent/FileIdempotentRepository.java @@ -290,7 +290,9 @@ public class FileIdempotentRepository extends ServiceSupport implements Idempote if (!fileStore.exists()) { LOG.debug("Creating filestore: {}", fileStore); File parent = fileStore.getParentFile(); - parent.mkdirs(); + if (parent != null) { + parent.mkdirs(); + } boolean created = FileUtil.createNewFile(fileStore); if (!created) { throw new IOException("Cannot create filestore: " + fileStore);
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-9340_1cab39f6.diff
bugs-dot-jar_data_CAMEL-5215_033eb6fe
--- BugID: CAMEL-5215 Summary: The file producer should use the charset encoding when writing the file if configured Description: |- When writing to a file, we offer the charset option on the endpoint, as well the charset property set on the exchange. However in a route that is optimized as {code} from file to file {code} Then we optimize to do a file move operation instead. We should detect the charset configured and then we would need to stream and write using the configured charset. diff --git a/camel-core/src/main/java/org/apache/camel/component/file/FileBinding.java b/camel-core/src/main/java/org/apache/camel/component/file/FileBinding.java index 4fd0162..8a63748 100644 --- a/camel-core/src/main/java/org/apache/camel/component/file/FileBinding.java +++ b/camel-core/src/main/java/org/apache/camel/component/file/FileBinding.java @@ -54,7 +54,7 @@ public class FileBinding implements GenericFileBinding<File> { public void loadContent(Exchange exchange, GenericFile<?> file) throws IOException { if (content == null) { try { - content = exchange.getContext().getTypeConverter().mandatoryConvertTo(byte[].class, file.getFile()); + content = exchange.getContext().getTypeConverter().mandatoryConvertTo(byte[].class, exchange, file.getFile()); } catch (NoTypeConversionAvailableException e) { throw new IOException("Cannot load file content: " + file.getAbsoluteFilePath(), e); } diff --git a/camel-core/src/main/java/org/apache/camel/component/file/FileOperations.java b/camel-core/src/main/java/org/apache/camel/component/file/FileOperations.java index f22056e..fbc60bc 100644 --- a/camel-core/src/main/java/org/apache/camel/component/file/FileOperations.java +++ b/camel-core/src/main/java/org/apache/camel/component/file/FileOperations.java @@ -21,7 +21,10 @@ import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; +import java.io.InputStreamReader; import java.io.RandomAccessFile; +import java.io.Reader; +import java.io.Writer; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.util.Date; @@ -29,6 +32,8 @@ import java.util.List; import org.apache.camel.Exchange; import org.apache.camel.InvalidPayloadException; +import org.apache.camel.WrappedFile; +import org.apache.camel.converter.IOConverter; import org.apache.camel.util.FileUtil; import org.apache.camel.util.IOHelper; import org.apache.camel.util.ObjectHelper; @@ -173,10 +178,24 @@ public class FileOperations implements GenericFileOperations<File> { // 3. write stream to file try { - // is the body file based + // determine charset, exchange property overrides endpoint configuration + String charset = IOHelper.getCharsetName(exchange, false); + if (charset == null) { + charset = endpoint.getCharset(); + } + + // we can optimize and use file based if no charset must be used, and the input body is a file File source = null; - // get the File Object from in message - source = exchange.getIn().getBody(File.class); + if (charset == null) { + // if no charset, then we can try using file directly (optimized) + Object body = exchange.getIn().getBody(); + if (body instanceof WrappedFile) { + body = ((WrappedFile) body).getFile(); + } + if (body instanceof File) { + source = (File) body; + } + } if (source != null) { // okay we know the body is a file type @@ -205,9 +224,22 @@ public class FileOperations implements GenericFileOperations<File> { } } - // fallback and use stream based - InputStream in = exchange.getIn().getMandatoryBody(InputStream.class); - writeFileByStream(in, file); + if (charset != null) { + // charset configured so we must use a reader so we can write with encoding + Reader in = exchange.getIn().getBody(Reader.class); + if (in == null) { + // okay no direct reader conversion, so use an input stream (which a lot can be converted as) + InputStream is = exchange.getIn().getMandatoryBody(InputStream.class); + in = new InputStreamReader(is); + } + // buffer the reader + in = IOHelper.buffered(in); + writeFileByReaderWithCharset(in, file, charset); + } else { + // fallback and use stream based + InputStream in = exchange.getIn().getMandatoryBody(InputStream.class); + writeFileByStream(in, file); + } // try to keep last modified timestamp if configured to do so keepLastModified(exchange, file); return true; @@ -239,7 +271,6 @@ public class FileOperations implements GenericFileOperations<File> { private boolean writeFileByLocalWorkPath(File source, File file) throws IOException { LOG.trace("Using local work file being renamed from: {} to: {}", source, file); - return FileUtil.renameFile(source, file, endpoint.isCopyAndDeleteOnRenameFail()); } @@ -286,6 +317,19 @@ public class FileOperations implements GenericFileOperations<File> { } } + private void writeFileByReaderWithCharset(Reader in, File target, String charset) throws IOException { + boolean append = endpoint.getFileExist() == GenericFileExist.Append; + Writer out = IOConverter.toWriter(target, append, charset); + try { + LOG.trace("Using Reader to transfer from: {} to: {} with charset: {}", new Object[]{in, out, charset}); + int size = endpoint.getBufferSize(); + IOHelper.copy(in, out, size); + } finally { + IOHelper.close(in, target.getName(), LOG); + IOHelper.close(out, target.getName(), LOG); + } + } + /** * Creates and prepares the output file channel. Will position itself in correct position if the file is writable * eg. it should append or override any existing content. diff --git a/camel-core/src/main/java/org/apache/camel/component/file/GenericFileConverter.java b/camel-core/src/main/java/org/apache/camel/component/file/GenericFileConverter.java index 76bb929..49bc19d 100644 --- a/camel-core/src/main/java/org/apache/camel/component/file/GenericFileConverter.java +++ b/camel-core/src/main/java/org/apache/camel/component/file/GenericFileConverter.java @@ -17,7 +17,6 @@ package org.apache.camel.component.file; import java.io.File; -import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.Serializable; @@ -25,9 +24,9 @@ import java.io.Serializable; import org.apache.camel.Converter; import org.apache.camel.Exchange; import org.apache.camel.FallbackConverter; +import org.apache.camel.NoTypeConversionAvailableException; import org.apache.camel.TypeConverter; import org.apache.camel.spi.TypeConverterRegistry; -import org.apache.camel.util.IOHelper; /** * A set of converter methods for working with generic file types @@ -64,11 +63,15 @@ public final class GenericFileConverter { } @Converter - public static InputStream genericFileToInputStream(GenericFile<?> file, Exchange exchange) throws IOException { + public static InputStream genericFileToInputStream(GenericFile<?> file, Exchange exchange) throws IOException, NoTypeConversionAvailableException { if (exchange != null) { - // use a file input stream if its a java.io.File if (file.getFile() instanceof java.io.File) { - return IOHelper.buffered(new FileInputStream((File) file.getFile())); + // prefer to use a file input stream if its a java.io.File (must use type converter to take care of encoding) + File f = (File) file.getFile(); + InputStream is = exchange.getContext().getTypeConverter().convertTo(InputStream.class, exchange, f); + if (is != null) { + return is; + } } // otherwise ensure the body is loaded as we want the input stream of the body file.getBinding().loadContent(exchange, file); diff --git a/camel-core/src/main/java/org/apache/camel/component/file/GenericFileProducer.java b/camel-core/src/main/java/org/apache/camel/component/file/GenericFileProducer.java index b00cdf0..feab07b 100644 --- a/camel-core/src/main/java/org/apache/camel/component/file/GenericFileProducer.java +++ b/camel-core/src/main/java/org/apache/camel/component/file/GenericFileProducer.java @@ -59,8 +59,6 @@ public class GenericFileProducer<T> extends DefaultProducer { } public void process(Exchange exchange) throws Exception { - endpoint.configureExchange(exchange); - String target = createFileName(exchange); // use lock for same file name to avoid concurrent writes to the same file diff --git a/camel-core/src/main/java/org/apache/camel/converter/IOConverter.java b/camel-core/src/main/java/org/apache/camel/converter/IOConverter.java index 0307aef..fcc6fc8 100644 --- a/camel-core/src/main/java/org/apache/camel/converter/IOConverter.java +++ b/camel-core/src/main/java/org/apache/camel/converter/IOConverter.java @@ -101,12 +101,16 @@ public final class IOConverter { */ @Deprecated public static BufferedWriter toWriter(File file) throws IOException { - return toWriter(file, null); + return toWriter(file, false, IOHelper.getCharsetName(null, true)); } @Converter public static BufferedWriter toWriter(File file, Exchange exchange) throws IOException { - return IOHelper.buffered(new EncodingFileWriter(file, IOHelper.getCharsetName(exchange))); + return toWriter(file, false, IOHelper.getCharsetName(exchange)); + } + + public static BufferedWriter toWriter(File file, boolean append, String charset) throws IOException { + return IOHelper.buffered(new EncodingFileWriter(file, append, charset)); } /** @@ -434,6 +438,16 @@ public final class IOConverter { super(new FileOutputStream(file), charset); } + /** + * @param file file to write + * @param append whether to append to the file + * @param charset character set to use + */ + public EncodingFileWriter(File file, boolean append, String charset) + throws FileNotFoundException, UnsupportedEncodingException { + super(new FileOutputStream(file, append), charset); + } + } /** diff --git a/camel-core/src/main/java/org/apache/camel/util/IOHelper.java b/camel-core/src/main/java/org/apache/camel/util/IOHelper.java index 79aa06a..903ce19 100644 --- a/camel-core/src/main/java/org/apache/camel/util/IOHelper.java +++ b/camel-core/src/main/java/org/apache/camel/util/IOHelper.java @@ -191,6 +191,20 @@ public final class IOHelper { close(input, null, LOG); } + public static int copy(final Reader input, final Writer output, int bufferSize) throws IOException { + final char[] buffer = new char[bufferSize]; + int n = input.read(buffer); + int total = 0; + while (-1 != n) { + output.write(buffer, 0, n); + total += n; + n = input.read(buffer); + } + output.flush(); + return total; + } + + /** * Forces any updates to this channel's file to be written to the storage device that contains it. *
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-5215_033eb6fe.diff
bugs-dot-jar_data_CAMEL-6987_37e0e6bb
--- BugID: CAMEL-6987 Summary: JMX - browseMessageAsXml for files does not work if includeBody is enabled Description: |- If you use the JXM API to browse file endpoints and want to load the file content with includeBody = true, then the file is not loaded. There is a little bug in MessgeHelper diff --git a/camel-core/src/main/java/org/apache/camel/util/MessageHelper.java b/camel-core/src/main/java/org/apache/camel/util/MessageHelper.java index 3e38d23..c81b53b 100644 --- a/camel-core/src/main/java/org/apache/camel/util/MessageHelper.java +++ b/camel-core/src/main/java/org/apache/camel/util/MessageHelper.java @@ -223,7 +223,9 @@ public final class MessageHelper { } else if (obj instanceof Writer) { return prepend + "[Body is instance of java.io.Writer]"; } else if (obj instanceof WrappedFile || obj instanceof File) { - return prepend + "[Body is file based: " + obj + "]"; + if (!allowFiles) { + return prepend + "[Body is file based: " + obj + "]"; + } } }
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-6987_37e0e6bb.diff
bugs-dot-jar_data_CAMEL-7448_35bde2b2
--- BugID: CAMEL-7448 Summary: throttle EIP - unchanged value Description: | Throttler Documentation [1] states "If the header is absent, then the Throttler uses the old value. So that allows you to only provide a header if the value is to be changed". however if the expression evaluates to null (header missing from message) the Throttler throws an exception (Throttler.java:108). The workaround is to ensure that all messages carry the value (if the value is the same no changes will take affect). Adding an option to turn this on and off (e.g. allowNullException) would make it much easier to use (as per camel-users thread [2]). [1] http://camel.apache.org/throttler.html [2] http://camel.465427.n5.nabble.com/throttle-EIP-unchanged-value-td5751300.html diff --git a/camel-core/src/main/java/org/apache/camel/processor/Throttler.java b/camel-core/src/main/java/org/apache/camel/processor/Throttler.java index f70325d..c986bf7 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/Throttler.java +++ b/camel-core/src/main/java/org/apache/camel/processor/Throttler.java @@ -108,7 +108,7 @@ public class Throttler extends DelayProcessorSupport implements Traceable { protected long calculateDelay(Exchange exchange) { // evaluate as Object first to see if we get any result at all Object result = maxRequestsPerPeriodExpression.evaluate(exchange, Object.class); - if (result == null) { + if (maximumRequestsPerPeriod == 0 && result == null) { throw new RuntimeExchangeException("The max requests per period expression was evaluated as null: " + maxRequestsPerPeriodExpression, exchange); }
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-7448_35bde2b2.diff
bugs-dot-jar_data_CAMEL-4354_96e40c3c
--- BugID: CAMEL-4354 Summary: header added using an EventNotifier is not present at AggregationStrategy for http endpoints Description: "A new header added using an EventNotifier is not present when the exchange is aggregated with an AggregationStrategy.\nThis is happening only if the enpoint type is http, ftp doesn't have this issue.\n\nThis was working with an early version of 2.8.0-SNAPSHOT\n\nFollowing the EventNotifier code used.\n\n{code:title=ExchangeSentEventNotifier.java|borderStyle=solid}\npublic class ExchangeSentEventNotifier extends EventNotifierSupport {\n\n\t@Override\n\tprotected void doStart() throws Exception {\n /*\n * filter out unwanted events\n \ * we are interested only in ExchangeSentEvent\n */\n setIgnoreCamelContextEvents(true);\n \ setIgnoreServiceEvents(true);\n setIgnoreRouteEvents(true);\n setIgnoreExchangeCreatedEvent(true);\n \ setIgnoreExchangeCompletedEvent(true);\n setIgnoreExchangeFailedEvents(true);\n \ setIgnoreExchangeSentEvents(false);\t\t\n\t}\n\n\t@Override\n\tprotected void doStop() throws Exception {\n\n\t}\n\n\t@Override\n\tpublic boolean isEnabled(EventObject event) {\n\t\treturn event instanceof ExchangeSentEvent;\n\t}\n\n\t@Override\n\tpublic void notify(EventObject event) throws Exception {\n \tif(event.getClass() == ExchangeSentEvent.class){\n ExchangeSentEvent eventSent = (ExchangeSentEvent)event;\n \ \n log.debug(\"Took \" + eventSent.getTimeTaken() + \" millis to send to: \" + eventSent.getEndpoint());\n\n //storing time taken to the custom header \n eventSent.getExchange().getIn().setHeader(\"x-time-taken\", eventSent.getTimeTaken());\n \n \t}\n\t\t\n\t}\n\n}\n{code} " diff --git a/camel-core/src/main/java/org/apache/camel/impl/ProducerCache.java b/camel-core/src/main/java/org/apache/camel/impl/ProducerCache.java index e9093a4..c8304d6 100644 --- a/camel-core/src/main/java/org/apache/camel/impl/ProducerCache.java +++ b/camel-core/src/main/java/org/apache/camel/impl/ProducerCache.java @@ -259,11 +259,12 @@ public class ProducerCache extends ServiceSupport { * @param producerCallback the producer template callback to be executed * @return (doneSync) <tt>true</tt> to continue execute synchronously, <tt>false</tt> to continue being executed asynchronously */ - public boolean doInAsyncProducer(Endpoint endpoint, Exchange exchange, ExchangePattern pattern, AsyncCallback callback, AsyncProducerCallback producerCallback) { + public boolean doInAsyncProducer(final Endpoint endpoint, final Exchange exchange, final ExchangePattern pattern, + final AsyncCallback callback, final AsyncProducerCallback producerCallback) { boolean sync = true; // get the producer and we do not mind if its pooled as we can handle returning it back to the pool - Producer producer = doGetProducer(endpoint, true); + final Producer producer = doGetProducer(endpoint, true); if (producer == null) { if (isStopped()) { @@ -274,39 +275,44 @@ public class ProducerCache extends ServiceSupport { } } - StopWatch watch = null; - if (exchange != null) { - // record timing for sending the exchange using the producer - watch = new StopWatch(); - } + // record timing for sending the exchange using the producer + final StopWatch watch = exchange != null ? new StopWatch() : null; try { // invoke the callback AsyncProcessor asyncProcessor = AsyncProcessorTypeConverter.convert(producer); - sync = producerCallback.doInAsyncProducer(producer, asyncProcessor, exchange, pattern, callback); + sync = producerCallback.doInAsyncProducer(producer, asyncProcessor, exchange, pattern, new AsyncCallback() { + @Override + public void done(boolean doneSync) { + try { + if (watch != null) { + long timeTaken = watch.stop(); + // emit event that the exchange was sent to the endpoint + EventHelper.notifyExchangeSent(exchange.getContext(), exchange, endpoint, timeTaken); + } + + if (producer instanceof ServicePoolAware) { + // release back to the pool + pool.release(endpoint, producer); + } else if (!producer.isSingleton()) { + // stop non singleton producers as we should not leak resources + try { + ServiceHelper.stopService(producer); + } catch (Exception e) { + // ignore and continue + LOG.warn("Error stopping producer: " + producer, e); + } + } + } finally { + callback.done(doneSync); + } + } + }); } catch (Throwable e) { // ensure exceptions is caught and set on the exchange if (exchange != null) { exchange.setException(e); } - } finally { - if (exchange != null && exchange.getException() == null) { - long timeTaken = watch.stop(); - // emit event that the exchange was sent to the endpoint - EventHelper.notifyExchangeSent(exchange.getContext(), exchange, endpoint, timeTaken); - } - if (producer instanceof ServicePoolAware) { - // release back to the pool - pool.release(endpoint, producer); - } else if (!producer.isSingleton()) { - // stop non singleton producers as we should not leak resources - try { - ServiceHelper.stopService(producer); - } catch (Exception e) { - // ignore and continue - LOG.warn("Error stopping producer: " + producer, e); - } - } } return sync;
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-4354_96e40c3c.diff
bugs-dot-jar_data_CAMEL-6723_b92d6237
--- BugID: CAMEL-6723 Summary: Message history - Possible ArrayIndexOutOfBoundsException Description: diff --git a/camel-core/src/main/java/org/apache/camel/impl/DefaultExchange.java b/camel-core/src/main/java/org/apache/camel/impl/DefaultExchange.java index b755b70..2c4a615 100644 --- a/camel-core/src/main/java/org/apache/camel/impl/DefaultExchange.java +++ b/camel-core/src/main/java/org/apache/camel/impl/DefaultExchange.java @@ -26,6 +26,7 @@ import org.apache.camel.Endpoint; import org.apache.camel.Exchange; import org.apache.camel.ExchangePattern; import org.apache.camel.Message; +import org.apache.camel.MessageHistory; import org.apache.camel.spi.Synchronization; import org.apache.camel.spi.UnitOfWork; import org.apache.camel.util.ExchangeHelper; @@ -95,10 +96,18 @@ public final class DefaultExchange implements Exchange { return exchange; } + @SuppressWarnings("unchecked") private static Map<String, Object> safeCopy(Map<String, Object> properties) { if (properties == null) { return null; } + + // safe copy message history using a defensive copy + List<MessageHistory> history = (List<MessageHistory>) properties.remove(Exchange.MESSAGE_HISTORY); + if (history != null) { + properties.put(Exchange.MESSAGE_HISTORY, new ArrayList<MessageHistory>(history)); + } + return new ConcurrentHashMap<String, Object>(properties); } diff --git a/camel-core/src/main/java/org/apache/camel/processor/Splitter.java b/camel-core/src/main/java/org/apache/camel/processor/Splitter.java index 76b5e02..a9dd334 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/Splitter.java +++ b/camel-core/src/main/java/org/apache/camel/processor/Splitter.java @@ -252,6 +252,8 @@ public class Splitter extends MulticastProcessor implements AsyncProcessor, Trac Exchange answer = ExchangeHelper.createCopy(exchange, preserveExchangeId); // we do not want attachments for the splitted sub-messages answer.getIn().setAttachments(null); + // we do not want to copy the message history for splitted sub-messages + answer.getProperties().remove(Exchange.MESSAGE_HISTORY); return answer; } } diff --git a/camel-core/src/main/java/org/apache/camel/util/ExchangeHelper.java b/camel-core/src/main/java/org/apache/camel/util/ExchangeHelper.java index b6f04d8..bc9943d 100644 --- a/camel-core/src/main/java/org/apache/camel/util/ExchangeHelper.java +++ b/camel-core/src/main/java/org/apache/camel/util/ExchangeHelper.java @@ -16,7 +16,9 @@ */ package org.apache.camel.util; +import java.util.ArrayList; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutionException; @@ -32,6 +34,7 @@ import org.apache.camel.Exchange; import org.apache.camel.ExchangePattern; import org.apache.camel.InvalidPayloadException; import org.apache.camel.Message; +import org.apache.camel.MessageHistory; import org.apache.camel.NoSuchBeanException; import org.apache.camel.NoSuchEndpointException; import org.apache.camel.NoSuchHeaderException; @@ -813,10 +816,18 @@ public final class ExchangeHelper { return answer; } + @SuppressWarnings("unchecked") private static Map<String, Object> safeCopy(Map<String, Object> properties) { if (properties == null) { return null; } + + // safe copy message history using a defensive copy + List<MessageHistory> history = (List<MessageHistory>) properties.remove(Exchange.MESSAGE_HISTORY); + if (history != null) { + properties.put(Exchange.MESSAGE_HISTORY, new ArrayList<MessageHistory>(history)); + } + return new ConcurrentHashMap<String, Object>(properties); } }
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-6723_b92d6237.diff
bugs-dot-jar_data_CAMEL-7883_d57f402b
--- BugID: CAMEL-7883 Summary: XSD decoding bad guess in Validator Description: 'Validator component does not take imported XSD encoding into account when validating XML. That may lead to validation errors if an imported XSD is ISO-8859-1 encoded and containing non ASCII caracters, even though that XSD declares its encoding correctly in its XML prolog. ' diff --git a/camel-core/src/main/java/org/apache/camel/component/validator/DefaultLSResourceResolver.java b/camel-core/src/main/java/org/apache/camel/component/validator/DefaultLSResourceResolver.java index 622e257..38fa704 100644 --- a/camel-core/src/main/java/org/apache/camel/component/validator/DefaultLSResourceResolver.java +++ b/camel-core/src/main/java/org/apache/camel/component/validator/DefaultLSResourceResolver.java @@ -117,8 +117,7 @@ public class DefaultLSResourceResolver implements LSResourceResolver { @Override public Reader getCharacterStream() { - InputStream is = getByteStream(); - return camelContext.getTypeConverter().convertTo(Reader.class, is); + return null; } @Override
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-7883_d57f402b.diff
bugs-dot-jar_data_CAMEL-6964_6b2ffb30
--- BugID: CAMEL-6964 Summary: 'Camel FileComponent: Done file will not be removed if moveFailed option is configured and an error occurs' Description: Only the "real" file is moved to the directory specified with the moveFailed-option. The done file still exists in the source folder and will not be deleted. diff --git a/camel-core/src/main/java/org/apache/camel/component/file/GenericFileOnCompletion.java b/camel-core/src/main/java/org/apache/camel/component/file/GenericFileOnCompletion.java index 5bedc00..db16a66 100644 --- a/camel-core/src/main/java/org/apache/camel/component/file/GenericFileOnCompletion.java +++ b/camel-core/src/main/java/org/apache/camel/component/file/GenericFileOnCompletion.java @@ -117,27 +117,7 @@ public class GenericFileOnCompletion<T> implements Synchronization { } } - // must be last in batch to delete the done file name - // delete done file if used (and not noop=true) - boolean complete = exchange.getProperty(Exchange.BATCH_COMPLETE, false, Boolean.class); - if (endpoint.getDoneFileName() != null && !endpoint.isNoop()) { - // done file must be in same path as the original input file - String doneFileName = endpoint.createDoneFileName(absoluteFileName); - ObjectHelper.notEmpty(doneFileName, "doneFileName", endpoint); - // we should delete the dynamic done file - if (endpoint.getDoneFileName().indexOf("{file:name") > 0 || complete) { - try { - // delete done file - boolean deleted = operations.deleteFile(doneFileName); - log.trace("Done file: {} was deleted: {}", doneFileName, deleted); - if (!deleted) { - log.warn("Done file: " + doneFileName + " could not be deleted"); - } - } catch (Exception e) { - handleException("Error deleting done file: " + doneFileName, exchange, e); - } - } - } + handleDoneFile(exchange); try { log.trace("Commit file strategy: {} for file: {}", processStrategy, file); @@ -160,6 +140,13 @@ public class GenericFileOnCompletion<T> implements Synchronization { if (log.isWarnEnabled()) { log.warn("Rollback file strategy: " + processStrategy + " for file: " + file); } + + // only delete done file if moveFailed option is enabled, as otherwise on rollback, + // we should leave the done file so we can retry + if (endpoint.getMoveFailed() != null) { + handleDoneFile(exchange); + } + try { processStrategy.rollback(operations, endpoint, exchange, file); } catch (Exception e) { @@ -167,6 +154,30 @@ public class GenericFileOnCompletion<T> implements Synchronization { } } + protected void handleDoneFile(Exchange exchange) { + // must be last in batch to delete the done file name + // delete done file if used (and not noop=true) + boolean complete = exchange.getProperty(Exchange.BATCH_COMPLETE, false, Boolean.class); + if (endpoint.getDoneFileName() != null && !endpoint.isNoop()) { + // done file must be in same path as the original input file + String doneFileName = endpoint.createDoneFileName(absoluteFileName); + ObjectHelper.notEmpty(doneFileName, "doneFileName", endpoint); + // we should delete the dynamic done file + if (endpoint.getDoneFileName().indexOf("{file:name") > 0 || complete) { + try { + // delete done file + boolean deleted = operations.deleteFile(doneFileName); + log.trace("Done file: {} was deleted: {}", doneFileName, deleted); + if (!deleted) { + log.warn("Done file: " + doneFileName + " could not be deleted"); + } + } catch (Exception e) { + handleException("Error deleting done file: " + doneFileName, exchange, e); + } + } + } + } + protected void handleException(String message, Exchange exchange, Throwable t) { Throwable newt = (t == null) ? new IllegalArgumentException("Handling [null] exception") : t; getExceptionHandler().handleException(message, exchange, newt);
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-6964_6b2ffb30.diff
bugs-dot-jar_data_CAMEL-3878_b9094cb5
--- BugID: CAMEL-3878 Summary: Stopping a route should not stop context scoped error handler Description: |- When stopping a route using .stopRoute from CamelContext or JMX etc. then the error handler should not be stopped if its a context scoped error handler, as it would be re-used. We should defer stopping those resources till Camel is shutting down. diff --git a/camel-core/src/main/java/org/apache/camel/processor/RedeliveryErrorHandler.java b/camel-core/src/main/java/org/apache/camel/processor/RedeliveryErrorHandler.java index eb31c6b..efbaa17 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/RedeliveryErrorHandler.java +++ b/camel-core/src/main/java/org/apache/camel/processor/RedeliveryErrorHandler.java @@ -840,7 +840,13 @@ public abstract class RedeliveryErrorHandler extends ErrorHandlerSupport impleme @Override protected void doStop() throws Exception { - ServiceHelper.stopServices(deadLetter, output, outputAsync); + // noop, do not stop any services which we only do when shutting down + // as the error handler can be context scoped, and should not stop in case + // a route stops } + @Override + protected void doShutdown() throws Exception { + ServiceHelper.stopServices(deadLetter, output, outputAsync); + } }
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-3878_b9094cb5.diff
bugs-dot-jar_data_CAMEL-6557_2c5a42db
--- BugID: CAMEL-6557 Summary: AbstractListAggregationStrategy does not work with batch completion strategy Description: |- When my aggregator extends AbstractListAggregationStrategy, I never get aggregator completions from the batch consumer. If I change my aggregator to be something like: {code} Foo foo = newExchange.getIn().getBody(Foo.class); List<Foo> list = null; Exchange outExchange; if (oldExchange == null) { list = new LinkedList<Foo>(); list.add(foo); newExchange.getIn().setBody(list); outExchange = newExchange; } else { list = oldExchange.getIn().getBody(List.class); list.add(foo); outExchange = oldExchange; } return outExchange; {code} then it works fine. I'm guessing this is has something to do with AbstractListAggregationStrategy messing with properties or wrapping the actual exchanges (since the batch completion is triggered based on Exchange.BATCH_SIZE property) diff --git a/camel-core/src/main/java/org/apache/camel/processor/aggregate/AbstractListAggregationStrategy.java b/camel-core/src/main/java/org/apache/camel/processor/aggregate/AbstractListAggregationStrategy.java index d37bba3..a19bdbc 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/aggregate/AbstractListAggregationStrategy.java +++ b/camel-core/src/main/java/org/apache/camel/processor/aggregate/AbstractListAggregationStrategy.java @@ -80,11 +80,9 @@ public abstract class AbstractListAggregationStrategy<V> implements CompletionAw */ public Exchange aggregate(Exchange oldExchange, Exchange newExchange) { List<V> list; - Exchange answer = oldExchange; if (oldExchange == null) { - answer = new DefaultExchange(newExchange); - list = getList(answer); + list = getList(newExchange); } else { list = getList(oldExchange); } @@ -96,7 +94,7 @@ public abstract class AbstractListAggregationStrategy<V> implements CompletionAw } } - return answer; + return oldExchange != null ? oldExchange : newExchange; } @SuppressWarnings("unchecked")
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-6557_2c5a42db.diff
bugs-dot-jar_data_CAMEL-6607_2d7051ed
--- BugID: CAMEL-6607 Summary: Tokenize XML does not support child elements with names similar to their parent Description: |- This XML will not split on Trip, as Trip has a child which starts with Trip <Trip> <Triptype> </Triptype> </Trip> The bug was introduced in https://issues.apache.org/jira/browse/CAMEL-6004 I believe the regex in TokenXMLExpressionIterator needs to be fixed see enclosed test diff --git a/camel-core/src/main/java/org/apache/camel/support/TokenXMLExpressionIterator.java b/camel-core/src/main/java/org/apache/camel/support/TokenXMLExpressionIterator.java index b8d4374..938b1d6 100644 --- a/camel-core/src/main/java/org/apache/camel/support/TokenXMLExpressionIterator.java +++ b/camel-core/src/main/java/org/apache/camel/support/TokenXMLExpressionIterator.java @@ -47,7 +47,7 @@ import org.apache.camel.util.ObjectHelper; public class TokenXMLExpressionIterator extends ExpressionAdapter { private static final Pattern NAMESPACE_PATTERN = Pattern.compile("xmlns(:\\w+|)\\s*=\\s*('[^']+'|\"[^\"]+\")"); private static final String SCAN_TOKEN_NS_PREFIX_REGEX = "([^:<>]{1,15}?:|)"; - private static final String SCAN_BLOCK_TOKEN_REGEX_TEMPLATE = "<{0}(\\s+[^/]*)?/>|<{0}(\\s+[^>]*)?>(?:(?!</{0}).)*</{0}\\s*>"; + private static final String SCAN_BLOCK_TOKEN_REGEX_TEMPLATE = "<{0}(\\s+[^/]*)?/>|<{0}(\\s+[^>]*)?>(?:(?!(</{0}\\s*>)).)*</{0}\\s*>"; private static final String SCAN_PARENT_TOKEN_REGEX_TEMPLATE = "<{0}(\\s+[^>]*\\s*)?>"; protected final String tagToken; @@ -133,7 +133,7 @@ public class TokenXMLExpressionIterator extends ExpressionAdapter { this.tagToken = tagToken; this.in = in; this.charset = charset; - + // remove any beginning < and ending > as we need to support ns prefixes and attributes, so we use a reg exp patterns this.tagTokenPattern = Pattern.compile(MessageFormat.format(SCAN_BLOCK_TOKEN_REGEX_TEMPLATE,
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-6607_2d7051ed.diff
bugs-dot-jar_data_CAMEL-7767_eab06182
--- BugID: CAMEL-7767 Summary: Mock - Defining assertion on message doest work if using convertTo Description: |- See http://www.manning-sandbox.com/thread.jspa?threadID=41025&tstart=0 The reason is when you use a method in the fluent builder that returns a ValueBuilder then that didn't detect the predicate. diff --git a/camel-core/src/main/java/org/apache/camel/util/MessageHelper.java b/camel-core/src/main/java/org/apache/camel/util/MessageHelper.java index 6576c98..502da6a 100644 --- a/camel-core/src/main/java/org/apache/camel/util/MessageHelper.java +++ b/camel-core/src/main/java/org/apache/camel/util/MessageHelper.java @@ -17,6 +17,7 @@ package org.apache.camel.util; import java.io.File; +import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; @@ -285,12 +286,15 @@ public final class MessageHelper { } } - // is the body a stream cache - StreamCache cache; + // is the body a stream cache or input stream + StreamCache cache = null; + InputStream is = null; if (obj instanceof StreamCache) { cache = (StreamCache)obj; - } else { + is = null; + } else if (obj instanceof InputStream) { cache = null; + is = (InputStream) obj; } // grab the message body as a string @@ -309,6 +313,12 @@ public final class MessageHelper { // reset stream cache after use if (cache != null) { cache.reset(); + } else if (is != null && is.markSupported()) { + try { + is.reset(); + } catch (IOException e) { + // ignore + } } if (body == null) {
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-7767_eab06182.diff
bugs-dot-jar_data_CAMEL-7736_7ad36e3d
--- BugID: CAMEL-7736 Summary: Failure to create producer during routing slip or similar eip causes exchange causes error handler not to react properly Description: |- If an endpoint.createProducer throws an exception from a dynamic eip, then the exchange is kept marked as inflight, and the error handler does not react asap and as expected. This was working in Camel 2.10.x etc. diff --git a/camel-core/src/main/java/org/apache/camel/impl/ProducerCache.java b/camel-core/src/main/java/org/apache/camel/impl/ProducerCache.java index 94a352f..4ece29f 100644 --- a/camel-core/src/main/java/org/apache/camel/impl/ProducerCache.java +++ b/camel-core/src/main/java/org/apache/camel/impl/ProducerCache.java @@ -267,20 +267,31 @@ public class ProducerCache extends ServiceSupport { */ public boolean doInAsyncProducer(final Endpoint endpoint, final Exchange exchange, final ExchangePattern pattern, final AsyncCallback callback, final AsyncProducerCallback producerCallback) { - boolean sync = true; - // get the producer and we do not mind if its pooled as we can handle returning it back to the pool - final Producer producer = doGetProducer(endpoint, true); - - if (producer == null) { - if (isStopped()) { - LOG.warn("Ignoring exchange sent after processor is stopped: " + exchange); - return false; - } else { - throw new IllegalStateException("No producer, this processor has not been started: " + this); + Producer target; + try { + // get the producer and we do not mind if its pooled as we can handle returning it back to the pool + target = doGetProducer(endpoint, true); + + if (target == null) { + if (isStopped()) { + LOG.warn("Ignoring exchange sent after processor is stopped: " + exchange); + callback.done(true); + return true; + } else { + exchange.setException(new IllegalStateException("No producer, this processor has not been started: " + this)); + callback.done(true); + return true; + } } + } catch (Throwable e) { + exchange.setException(e); + callback.done(true); + return true; } + final Producer producer = target; + // record timing for sending the exchange using the producer final StopWatch watch = eventNotifierEnabled && exchange != null ? new StopWatch() : null; @@ -290,7 +301,7 @@ public class ProducerCache extends ServiceSupport { } // invoke the callback AsyncProcessor asyncProcessor = AsyncProcessorConverterHelper.convert(producer); - sync = producerCallback.doInAsyncProducer(producer, asyncProcessor, exchange, pattern, new AsyncCallback() { + return producerCallback.doInAsyncProducer(producer, asyncProcessor, exchange, pattern, new AsyncCallback() { @Override public void done(boolean doneSync) { try { @@ -322,9 +333,9 @@ public class ProducerCache extends ServiceSupport { if (exchange != null) { exchange.setException(e); } + callback.done(true); + return true; } - - return sync; } protected Exchange sendExchange(final Endpoint endpoint, ExchangePattern pattern,
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-7736_7ad36e3d.diff
bugs-dot-jar_data_CAMEL-6687_617eab1c
--- BugID: CAMEL-6687 Summary: Using simple language OGNL expressions doesn't work for Bean Binding when a field is null Description: "The following functionality doesn't work, when one of the fields is null: \n\nhttp://camel.apache.org/bean-binding.html\n{quote}\nYou can also use the OGNL support of the Simple expression language. Now suppose the message body is an object which has a method named asXml. To invoke the asXml method we can do as follows:\n{code}.bean(OrderService.class, \"doSomething(${body.asXml}, ${header.high})\"){code}\n\nInstead of using .bean as shown in the examples above, you may want to use .to instead as shown:\n{code}.to(\"bean:orderService?method=doSomething(${body.asXml}, ${header.high})\"){code}\n{quote}\n\nA test case is provided. Instead of getting values of fields \"foo\" and \"bar\" respectively, the first parameter (which should be null) receives value of pojo.toString(), while the second parameter receives the correct value." diff --git a/camel-core/src/main/java/org/apache/camel/component/bean/MethodInfo.java b/camel-core/src/main/java/org/apache/camel/component/bean/MethodInfo.java index 7160d3d..cc58c50 100644 --- a/camel-core/src/main/java/org/apache/camel/component/bean/MethodInfo.java +++ b/camel-core/src/main/java/org/apache/camel/component/bean/MethodInfo.java @@ -512,46 +512,47 @@ public class MethodInfo { try { expression = exchange.getContext().resolveLanguage("simple").createExpression(exp); parameterValue = expression.evaluate(exchange, Object.class); + // use "null" to indicate the expression returned a null value which is a valid response we need to honor + if (parameterValue == null) { + parameterValue = "null"; + } } catch (Exception e) { throw new ExpressionEvaluationException(expression, "Cannot create/evaluate simple expression: " + exp + " to be bound to parameter at index: " + index + " on method: " + getMethod(), exchange, e); } - if (parameterValue != null) { + // special for explicit null parameter values (as end users can explicit indicate they want null as parameter) + // see method javadoc for details + if ("null".equals(parameterValue)) { + return Void.TYPE; + } - // special for explicit null parameter values (as end users can explicit indicate they want null as parameter) - // see method javadoc for details - if ("null".equals(parameterValue)) { - return Void.TYPE; - } + // the parameter value was not already valid, but since the simple language have evaluated the expression + // which may change the parameterValue, so we have to check it again to see if its now valid + exp = exchange.getContext().getTypeConverter().convertTo(String.class, parameterValue); + // String values from the simple language is always valid + if (!valid) { + // re validate if the parameter was not valid the first time (String values should be accepted) + valid = parameterValue instanceof String || BeanHelper.isValidParameterValue(exp); + } - // the parameter value was not already valid, but since the simple language have evaluated the expression - // which may change the parameterValue, so we have to check it again to see if its now valid - exp = exchange.getContext().getTypeConverter().convertTo(String.class, parameterValue); - // String values from the simple language is always valid - if (!valid) { - // re validate if the parameter was not valid the first time (String values should be accepted) - valid = parameterValue instanceof String || BeanHelper.isValidParameterValue(exp); + if (valid) { + // we need to unquote String parameters, as the enclosing quotes is there to denote a parameter value + if (parameterValue instanceof String) { + parameterValue = StringHelper.removeLeadingAndEndingQuotes((String) parameterValue); } - - if (valid) { - // we need to unquote String parameters, as the enclosing quotes is there to denote a parameter value - if (parameterValue instanceof String) { - parameterValue = StringHelper.removeLeadingAndEndingQuotes((String) parameterValue); - } - if (parameterValue != null) { - try { - // its a valid parameter value, so convert it to the expected type of the parameter - answer = exchange.getContext().getTypeConverter().mandatoryConvertTo(parameterType, exchange, parameterValue); - if (LOG.isTraceEnabled()) { - LOG.trace("Parameter #{} evaluated as: {} type: ", new Object[]{index, answer, ObjectHelper.type(answer)}); - } - } catch (Exception e) { - if (LOG.isDebugEnabled()) { - LOG.debug("Cannot convert from type: {} to type: {} for parameter #{}", new Object[]{ObjectHelper.type(parameterValue), parameterType, index}); - } - throw new ParameterBindingException(e, method, index, parameterType, parameterValue); + if (parameterValue != null) { + try { + // its a valid parameter value, so convert it to the expected type of the parameter + answer = exchange.getContext().getTypeConverter().mandatoryConvertTo(parameterType, exchange, parameterValue); + if (LOG.isTraceEnabled()) { + LOG.trace("Parameter #{} evaluated as: {} type: ", new Object[]{index, answer, ObjectHelper.type(answer)}); + } + } catch (Exception e) { + if (LOG.isDebugEnabled()) { + LOG.debug("Cannot convert from type: {} to type: {} for parameter #{}", new Object[]{ObjectHelper.type(parameterValue), parameterType, index}); } + throw new ParameterBindingException(e, method, index, parameterType, parameterValue); } } }
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-6687_617eab1c.diff
bugs-dot-jar_data_CAMEL-7100_00a9b02b
--- BugID: CAMEL-7100 Summary: CLONE - Camel Splitter eat up exceptions recorded by the underlying Scanner Description: See http://camel.465427.n5.nabble.com/Trouble-with-split-tokenize-on-linux-td5721677.html for details diff --git a/camel-core/src/main/java/org/apache/camel/processor/Splitter.java b/camel-core/src/main/java/org/apache/camel/processor/Splitter.java index a9dd334..d1a0f64 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/Splitter.java +++ b/camel-core/src/main/java/org/apache/camel/processor/Splitter.java @@ -192,19 +192,20 @@ public class Splitter extends MulticastProcessor implements AsyncProcessor, Trac @Override public void close() throws IOException { - if (value instanceof Closeable) { - IOHelper.close((Closeable) value, value.getClass().getName(), LOG); - } else if (value instanceof Scanner) { - // special for Scanner as it does not implement Closeable + if (value instanceof Scanner) { + // special for Scanner which implement the Closeable since JDK7 Scanner scanner = (Scanner) value; scanner.close(); - IOException ioException = scanner.ioException(); if (ioException != null) { throw ioException; } + } else if (value instanceof Closeable) { + // we should throw out the exception here + IOHelper.closeWithException((Closeable) value); } } + } private Iterable<ProcessorExchangePair> createProcessorExchangePairsList(Exchange exchange, Object value) { diff --git a/camel-core/src/main/java/org/apache/camel/util/GroupIterator.java b/camel-core/src/main/java/org/apache/camel/util/GroupIterator.java index 95a5a1e..158dbed 100644 --- a/camel-core/src/main/java/org/apache/camel/util/GroupIterator.java +++ b/camel-core/src/main/java/org/apache/camel/util/GroupIterator.java @@ -65,16 +65,24 @@ public final class GroupIterator implements Iterator<Object>, Closeable { @Override public void close() throws IOException { - if (it instanceof Closeable) { - IOHelper.close((Closeable) it); - } else if (it instanceof Scanner) { - // special for Scanner as it does not implement Closeable - ((Scanner) it).close(); + try { + if (it instanceof Scanner) { + // special for Scanner which implement the Closeable since JDK7 + Scanner scanner = (Scanner) it; + scanner.close(); + IOException ioException = scanner.ioException(); + if (ioException != null) { + throw ioException; + } + } else if (it instanceof Closeable) { + IOHelper.closeWithException((Closeable) it); + } + } finally { + // close the buffer as well + bos.close(); + // we are now closed + closed = true; } - // close the buffer as well - bos.close(); - // we are now closed - closed = true; } @Override diff --git a/camel-core/src/main/java/org/apache/camel/util/IOHelper.java b/camel-core/src/main/java/org/apache/camel/util/IOHelper.java index efd8b56..ed2f793 100644 --- a/camel-core/src/main/java/org/apache/camel/util/IOHelper.java +++ b/camel-core/src/main/java/org/apache/camel/util/IOHelper.java @@ -337,6 +337,23 @@ public final class IOHelper { } } } + + /** + * Closes the given resource if it is available and don't catch the exception + * + * @param closeable the object to close + * @throws IOException + */ + public static void closeWithException(Closeable closeable) throws IOException { + if (closeable != null) { + try { + closeable.close(); + } catch (IOException e) { + // don't catch the exception here + throw e; + } + } + } /** * Closes the given channel if it is available, logging any closing exceptions to the given log.
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-7100_00a9b02b.diff
bugs-dot-jar_data_CAMEL-7611_e30f1c53
--- BugID: CAMEL-7611 Summary: org.apache.camel.util.KeyValueHolder equals bug Description: "According to java.lang.Object javadoc (http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html), \"equal objects must have equal hash codes\". \n\nCurrent implementation of the \"equals\" and \"hashCode\" method of the org.apache.camel.util.KeyValueHolder does not seem to follow that rule: hashCode is calculated from the key and value attributes while the equals compares only the key attribute. \n\nCould generate unexpected behaviour in certain circumstances." diff --git a/camel-core/src/main/java/org/apache/camel/util/KeyValueHolder.java b/camel-core/src/main/java/org/apache/camel/util/KeyValueHolder.java index 3cf5bf9..a9baf00 100644 --- a/camel-core/src/main/java/org/apache/camel/util/KeyValueHolder.java +++ b/camel-core/src/main/java/org/apache/camel/util/KeyValueHolder.java @@ -53,6 +53,8 @@ public class KeyValueHolder<K, V> { if (key != null ? !key.equals(that.key) : that.key != null) { return false; + } else if (value != null ? !value.equals(that.value) : that.value != null) { + return false; } return true;
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-7611_e30f1c53.diff
bugs-dot-jar_data_CAMEL-5432_93935780
--- BugID: CAMEL-5432 Summary: Dynamically added SEDA-route is not working Description: "Dynamically removing and adding a SEDA-route creates a not working route in Camel 2.10.0.\nIt is working in 2.9.2.\n\nTest-Code:\n{code}\npublic class DynamicRouteTest extends CamelTestSupport {\n\n @Override\n protected RouteBuilder createRouteBuilder() throws Exception {\n return new RouteBuilder() {\n\n @Override\n \ public void configure() throws Exception {\n from(\"seda:in\").id(\"sedaToMock\").to(\"mock:out\");\n \ }\n };\n }\n \n @Test\n public void testDynamicRoute() throws Exception {\n MockEndpoint out = getMockEndpoint(\"mock:out\");\n \ out.expectedMessageCount(1);\n \n template.sendBody(\"seda:in\", \"Test Message\");\n \n out.assertIsSatisfied();\n \n CamelContext camelContext = out.getCamelContext();\n camelContext.stopRoute(\"sedaToMock\");\n \ camelContext.removeRoute(\"sedaToMock\");\n \n camelContext.addRoutes(createRouteBuilder());\n \ out.reset();\n out.expectedMessageCount(1);\n \n template.sendBody(\"seda:in\", \"Test Message\");\n \n out.assertIsSatisfied();\n \n }\n} \n\n{code}" diff --git a/camel-core/src/main/java/org/apache/camel/component/seda/SedaEndpoint.java b/camel-core/src/main/java/org/apache/camel/component/seda/SedaEndpoint.java index 5b2d872..e33d21d 100644 --- a/camel-core/src/main/java/org/apache/camel/component/seda/SedaEndpoint.java +++ b/camel-core/src/main/java/org/apache/camel/component/seda/SedaEndpoint.java @@ -85,7 +85,7 @@ public class SedaEndpoint extends DefaultEndpoint implements BrowsableEndpoint, } public Producer createProducer() throws Exception { - return new SedaProducer(this, getQueue(), getWaitForTaskToComplete(), getTimeout(), isBlockWhenFull()); + return new SedaProducer(this, getWaitForTaskToComplete(), getTimeout(), isBlockWhenFull()); } public Consumer createConsumer(Processor processor) throws Exception { diff --git a/camel-core/src/main/java/org/apache/camel/component/seda/SedaProducer.java b/camel-core/src/main/java/org/apache/camel/component/seda/SedaProducer.java index d39e39f..3614460 100644 --- a/camel-core/src/main/java/org/apache/camel/component/seda/SedaProducer.java +++ b/camel-core/src/main/java/org/apache/camel/component/seda/SedaProducer.java @@ -32,6 +32,10 @@ import org.apache.camel.util.ExchangeHelper; * @version */ public class SedaProducer extends DefaultAsyncProducer { + /** + * @deprecated Better make use of the {@link SedaEndpoint#getQueue()} API which delivers the accurate reference to the queue currently being used. + */ + @Deprecated protected final BlockingQueue<Exchange> queue; private final SedaEndpoint endpoint; private final WaitForTaskToComplete waitForTaskToComplete; @@ -39,17 +43,24 @@ public class SedaProducer extends DefaultAsyncProducer { private final boolean blockWhenFull; /** - * @deprecated use the other constructor + * @deprecated Use {@link #SedaProducer(SedaEndpoint, WaitForTaskToComplete, long, boolean) the other constructor}. */ @Deprecated public SedaProducer(SedaEndpoint endpoint, BlockingQueue<Exchange> queue, WaitForTaskToComplete waitForTaskToComplete, long timeout) { - this(endpoint, queue, waitForTaskToComplete, timeout, false); + this(endpoint, waitForTaskToComplete, timeout, false); } - - public SedaProducer(SedaEndpoint endpoint, BlockingQueue<Exchange> queue, WaitForTaskToComplete waitForTaskToComplete, - long timeout, boolean blockWhenFull) { + + /** + * @deprecated Use {@link #SedaProducer(SedaEndpoint, WaitForTaskToComplete, long, boolean) the other constructor}. + */ + @Deprecated + public SedaProducer(SedaEndpoint endpoint, BlockingQueue<Exchange> queue, WaitForTaskToComplete waitForTaskToComplete, long timeout, boolean blockWhenFull) { + this(endpoint, waitForTaskToComplete, timeout, blockWhenFull); + } + + public SedaProducer(SedaEndpoint endpoint, WaitForTaskToComplete waitForTaskToComplete, long timeout, boolean blockWhenFull) { super(endpoint); - this.queue = queue; + this.queue = endpoint.getQueue(); this.endpoint = endpoint; this.waitForTaskToComplete = waitForTaskToComplete; this.timeout = timeout; @@ -125,7 +136,7 @@ public class SedaProducer extends DefaultAsyncProducer { if (!done) { exchange.setException(new ExchangeTimedOutException(exchange, timeout)); // remove timed out Exchange from queue - queue.remove(copy); + endpoint.getQueue().remove(copy); // count down to indicate timeout latch.countDown(); } @@ -183,6 +194,7 @@ public class SedaProducer extends DefaultAsyncProducer { * @param exchange the exchange to add to the queue */ protected void addToQueue(Exchange exchange) { + BlockingQueue<Exchange> queue = endpoint.getQueue(); if (blockWhenFull) { try { queue.put(exchange);
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-5432_93935780.diff
bugs-dot-jar_data_CAMEL-5699_6d63a502
--- BugID: CAMEL-5699 Summary: LogFormatter throws a NPE when all elements are disabled Description: |- There are perfectly valid cases where you may want to output a log message with no elements displayed, i.e. with showExchangeId=false, showBody=false, etc. For example, when you want to print a "signal" log line for a particular transaction and you're already using MDC logging with breadcrumbs enabled. You may already have all the info you need: logging category, severity, breadcrumbId. You are not interested in anything else. Currently, disabling all elements leads to a NPE. diff --git a/camel-core/src/main/java/org/apache/camel/component/log/LogFormatter.java b/camel-core/src/main/java/org/apache/camel/component/log/LogFormatter.java index 19eba1b..c190974 100644 --- a/camel-core/src/main/java/org/apache/camel/component/log/LogFormatter.java +++ b/camel-core/src/main/java/org/apache/camel/component/log/LogFormatter.java @@ -167,12 +167,24 @@ public class LogFormatter implements ExchangeFormatter { } } - // get rid of the leading space comma if needed - return "Exchange[" + (multiline ? answer.append(']').toString() : answer.toString().substring(2) + "]"); + // switch string buffer + sb = answer; } - // get rid of the leading space comma if needed - return "Exchange[" + (multiline ? sb.append(']').toString() : sb.toString().substring(2) + "]"); + if (multiline) { + sb.insert(0, "Exchange["); + sb.append("]"); + return sb.toString(); + } else { + // get rid of the leading space comma if needed + if (sb.length() > 0 && sb.charAt(0) == ',' && sb.charAt(1) == ' ') { + sb.replace(0, 2, ""); + } + sb.insert(0, "Exchange["); + sb.append("]"); + + return sb.toString(); + } } public boolean isShowExchangeId() {
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-5699_6d63a502.diff
bugs-dot-jar_data_CAMEL-7456_02da984a
--- BugID: CAMEL-7456 Summary: Camel PropertiesComponent ignores custom parser in Blueprint Description: "I have implemented a custom PropertiesParser which allows me to use system property placeholders in propertyPrefix and propertySuffix.\n\nIn my use case the propertyPrefix is defined as \"$\\{container.stage}.\", where container.stage is a jvm option defined at container creation. The value is one of dev, test and prod.\n\nThis works fine in Java DSL world (SCR bundle), but custom parser is ignored in Blueprint. Here is sample of my blueprint xml:\n{code}\n <cm:property-placeholder id=\"integration\" persistent-id=\"org.apache.camel.sample.temp\" placeholder-prefix=\"[[\" placeholder-suffix=\"]]\">\n <cm:default-properties>\n <cm:property name=\"example\" value=\"this value is the default\"/>\n <cm:property name=\"dev.example\" value=\"this value is used in development environment\"/>\n <cm:property name=\"test.example\" value=\"this value is used in test environment\"/>\n <cm:property name=\"prod.example\" value=\"this value is used in production environment\"/>\n \ </cm:default-properties>\n</cm:property-placeholder>\n\n<bean id=\"parser\" class=\"org.apache.camel.sample.MyCustomPropertiesParser\"/>\n\n<!-- Load properties for current container stage -->\n<bean id=\"properties\" class=\"org.apache.camel.component.properties.PropertiesComponent\">\n \ <property name=\"propertiesParser\" ref=\"parser\"/>\n <property name=\"propertyPrefix\" value=\"${container.stage}.\"/>\n <property name=\"fallbackToUnaugmentedProperty\" value=\"true\"/>\n <property name=\"location\" value=\"blueprint:integration,classpath:properties/temp.properties\"/></bean>\n\n<camelContext id=\"temp\" xmlns=\"http://camel.apache.org/schema/blueprint\">\n <route id=\"exampleRoute\">\n \ <from uri=\"timer:foo?period=5000\"/>\n <transform>\n <simple>{{example}}</simple>\n \ </transform>\n <to uri=\"log:something\"/>\n </route>\n</camelContext>\n{code}\n\nThe reason it did not work was because by default, it uses blueprint property resolver (useBlueprintPropertyResolver=\"true\") to bridge PropertiesComponent to blueprint in order to support looking up property placeholders from the Blueprint Property Placeholder Service. Then it always creates a BlueprintPropertiesParser object and set it to PropertiesComponent. \n\nThe customer Property Parser I created was only set into the BlueprintPropertiesParser object as a delegate Property Parser. Therefore, it was always the method parseUri() from the BlueprintPropertiesParser object got invoked. The same method from your custom parser was ignored. \n\nFor more detail, please take a look at org.apache.camel.blueprint.CamelContextFactoryBean.initPropertyPlaceholder() function.\n\nThe only workaround is to add the attribute useBlueprintPropertyResolver=\"false\" to <camelContext> element to disable default blueprint property resolver. However, I will have to change PropertiesComponent's \"location\" property to remove blueprint \"blueprint:integration\" from the comma separated value list:\n{code}\n <property name=\"location\" value=\"classpath:properties/temp.properties\"/> \n{code}\nBecause once I set it to false, I will no longer be able to lookup from blueprint property service." diff --git a/camel-core/src/main/java/org/apache/camel/component/properties/PropertiesComponent.java b/camel-core/src/main/java/org/apache/camel/component/properties/PropertiesComponent.java index 7d0e75c..3a7c13d 100644 --- a/camel-core/src/main/java/org/apache/camel/component/properties/PropertiesComponent.java +++ b/camel-core/src/main/java/org/apache/camel/component/properties/PropertiesComponent.java @@ -204,6 +204,9 @@ public class PropertiesComponent extends DefaultComponent { public void setPropertyPrefix(String propertyPrefix) { this.propertyPrefix = propertyPrefix; + if (ObjectHelper.isNotEmpty(this.propertyPrefix)) { + this.propertyPrefix = FilePathResolver.resolvePath(this.propertyPrefix); + } } public String getPropertySuffix() { @@ -212,6 +215,9 @@ public class PropertiesComponent extends DefaultComponent { public void setPropertySuffix(String propertySuffix) { this.propertySuffix = propertySuffix; + if (ObjectHelper.isNotEmpty(this.propertySuffix)) { + this.propertySuffix = FilePathResolver.resolvePath(this.propertySuffix); + } } public boolean isFallbackToUnaugmentedProperty() {
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-7456_02da984a.diff
bugs-dot-jar_data_CAMEL-9143_08077733
--- BugID: CAMEL-9143 Summary: Producers that implement the ServicePoolAware interface cause memory leak due to JMX references Description: "h4. Description\n\nProducer instances that implement the ServicePoolAware interface will leak memory if their route is stopped, with new producers being leaked every time the route is started/stopped.\n\nKnown implementations that are affected are RemoteFileProducer (ftp, sftp) and Mina2Producer.\n\nThis is due to the behaviour that the SendProcessor which when the route is stopped it shuts down it's `producerCache` instance.\n\n{code}\n protected void doStop() throws Exception {\n ServiceHelper.stopServices(producerCache, producer);\n }\n{code}\n\nthis in turn calls `stopAndShutdownService(pool)` which will call stop on the SharedProducerServicePool instance which is a NOOP however it also calls shutdown which effects a stop of the global pool (this stops all the registered services and then clears the pool.\n\n{code}\n protected void doStop() throws Exception {\n // when stopping we intend to shutdown\n ServiceHelper.stopAndShutdownService(pool);\n \ try {\n ServiceHelper.stopAndShutdownServices(producers.values());\n \ } finally {\n // ensure producers are removed, and also from JMX\n for (Producer producer : producers.values()) {\n getCamelContext().removeService(producer);\n \ }\n }\n producers.clear();\n }\n{code}\n\nHowever no call to `context.removeService(Producer) is called for the entries from the pool only those singleton instances that were in the `producers` map hence the JMX `ManagedProducer` that is created when `doGetProducer` invokes {code} getCamelContext().addService(answer, false);\n{code} is never removed. \n\nSince the global pool is empty when the next request to get a producer is called a new producer is created, jmx wrapper and all, whilst the old instance remains orphaned retaining any objects that pertain to that instance.\n\nOne workaround is for the producer to call {code}getEndpoint().getCamelContext().removeService(this){code} in it's stop method, however this is fairly obscure and it would probably be better to invoke removal of the producer when it is removed from the shared pool.\n\nAnother issue of note is that when a route is shutdown that contains a SendProcessor due to the shutdown invocation on the SharedProcessorServicePool the global pool is cleared of `everything` and remains in `Stopped` state until another route starts it (although it is still accessed and used whilst in the `Stopped` state).\n\nh4. Impact\n\nFor general use where there is no dynamic creation or passivation of routes this issue should be minimal, however in our use case where the routes are not static, there is a certain amount of recreation of routes as customer endpoints change and there is a need to passivate idle routes this causes a considerable memory leak (via SFTP in particular).\n\nh4. Test Case\n{code}\npackage org.apache.camel.component;\n\nimport com.google.common.util.concurrent.AtomicLongMap;\n\nimport org.apache.camel.CamelContext;\nimport org.apache.camel.Consumer;\nimport org.apache.camel.Endpoint;\nimport org.apache.camel.Exchange;\nimport org.apache.camel.Processor;\nimport org.apache.camel.Producer;\nimport org.apache.camel.Route;\nimport org.apache.camel.Service;\nimport org.apache.camel.ServicePoolAware;\nimport org.apache.camel.ServiceStatus;\nimport org.apache.camel.builder.RouteBuilder;\nimport org.apache.camel.impl.DefaultComponent;\nimport org.apache.camel.impl.DefaultEndpoint;\nimport org.apache.camel.impl.DefaultProducer;\nimport org.apache.camel.support.LifecycleStrategySupport;\nimport org.apache.camel.support.ServiceSupport;\nimport org.apache.camel.test.junit4.CamelTestSupport;\nimport org.junit.Test;\n\nimport java.util.Map;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\n/**\n * Test memory behaviour of producers using {@link ServicePoolAware} when using JMX.\n */\npublic class ServicePoolAwareLeakyTest extends CamelTestSupport {\n\n private static final String LEAKY_SIEVE_STABLE = \"leaky://sieve-stable?plugged=true\";\n \ private static final String LEAKY_SIEVE_TRANSIENT = \"leaky://sieve-transient?plugged=true\";\n\n\n \ private static boolean isPatchApplied() {\n return Boolean.parseBoolean(System.getProperty(\"patchApplied\", \"false\"));\n }\n\n /**\n * Component that provides leaks producers.\n */\n \ private static class LeakySieveComponent extends DefaultComponent {\n @Override\n \ protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {\n boolean plugged = \"true\".equalsIgnoreCase((String) parameters.remove(\"plugged\"));\n return new LeakySieveEndpoint(uri, isPatchApplied() && plugged);\n }\n }\n\n /**\n * Endpoint that provides leaky producers.\n \ */\n private static class LeakySieveEndpoint extends DefaultEndpoint {\n\n private final String uri;\n private final boolean plugged;\n\n public LeakySieveEndpoint(String uri, boolean plugged) {\n this.uri = checkNotNull(uri, \"uri must not be null\");\n \ this.plugged = plugged;\n }\n\n @Override\n public Producer createProducer() throws Exception {\n return new LeakySieveProducer(this, plugged);\n }\n\n \ @Override\n public Consumer createConsumer(Processor processor) throws Exception {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public boolean isSingleton() {\n return true;\n }\n\n @Override\n protected String createEndpointUri() {\n return uri;\n }\n }\n\n /**\n * Leaky producer - implements {@link ServicePoolAware}.\n */\n private static class LeakySieveProducer extends DefaultProducer implements ServicePoolAware {\n\n private final boolean plugged;\n\n public LeakySieveProducer(Endpoint endpoint, boolean plugged) {\n \ super(endpoint);\n this.plugged = plugged;\n }\n\n @Override\n \ public void process(Exchange exchange) throws Exception {\n // do nothing\n \ }\n\n @Override\n protected void doStop() throws Exception {\n super.doStop();\n\n \ //noinspection ConstantConditions\n if (plugged) {\n // need to remove self from services since we are ServicePoolAware this will not be handled for us otherwise we\n // leak memory\n getEndpoint().getCamelContext().removeService(this);\n \ }\n }\n }\n\n @Override\n protected boolean useJmx() {\n // only occurs when using JMX as the GC root for the producer is through a ManagedProducer created by the\n // context.addService() invocation\n return true;\n }\n\n \ /**\n * Returns true if verification of state should be performed during the test as opposed to at the end.\n */\n public boolean isFailFast() {\n return false;\n }\n\n /**\n * Returns true if during fast failure we should verify that the service pool remains in the started state.\n */\n public boolean isVerifyProducerServicePoolRemainsStarted() {\n return false;\n }\n\n @Override\n public boolean isUseAdviceWith() {\n \ return true;\n }\n\n @Test\n public void testForMemoryLeak() throws Exception {\n registerLeakyComponent();\n\n final AtomicLongMap<String> references = AtomicLongMap.create();\n\n // track LeakySieveProducer lifecycle\n context.addLifecycleStrategy(new LifecycleStrategySupport() {\n @Override\n public void onServiceAdd(CamelContext context, Service service, Route route) {\n if (service instanceof LeakySieveProducer) {\n references.incrementAndGet(((LeakySieveProducer) service).getEndpoint().getEndpointKey());\n \ }\n }\n\n @Override\n public void onServiceRemove(CamelContext context, Service service, Route route) {\n if (service instanceof LeakySieveProducer) {\n references.decrementAndGet(((LeakySieveProducer) service).getEndpoint().getEndpointKey());\n \ }\n }\n });\n\n context.addRoutes(new RouteBuilder() {\n @Override\n \ public void configure() throws Exception {\n from(\"direct:sieve-transient\")\n \ .id(\"sieve-transient\")\n .to(LEAKY_SIEVE_TRANSIENT);\n\n \ from(\"direct:sieve-stable\")\n .id(\"sieve-stable\")\n .to(LEAKY_SIEVE_STABLE);\n \ }\n });\n\n context.start();\n\n for (int i = 0; i < 1000; i++) {\n \ ServiceSupport service = (ServiceSupport) context.getProducerServicePool();\n \ assertEquals(ServiceStatus.Started, service.getStatus());\n if (isFailFast()) {\n assertEquals(2, context.getProducerServicePool().size());\n assertEquals(1, references.get(LEAKY_SIEVE_TRANSIENT));\n assertEquals(1, references.get(LEAKY_SIEVE_STABLE));\n \ }\n\n context.stopRoute(\"sieve-transient\");\n\n if (isFailFast()) {\n assertEquals(\"Expected no service references to remain\", 0, references.get(LEAKY_SIEVE_TRANSIENT));\n \ }\n\n if (isFailFast()) {\n // looks like we cleared more than just our route, we've stopped and cleared the global ProducerServicePool\n // since SendProcessor.stop() invokes ServiceHelper.stopServices(producerCache, producer); which in turn invokes\n // ServiceHelper.stopAndShutdownService(pool);.\n \ //\n // Whilst stop on the SharedProducerServicePool is a NOOP shutdown is not and effects a stop of the pool.\n\n if (isVerifyProducerServicePoolRemainsStarted()) {\n assertEquals(ServiceStatus.Started, service.getStatus());\n }\n \ assertEquals(\"Expected one stable producer to remain pooled\", 1, context.getProducerServicePool().size());\n \ assertEquals(\"Expected one stable producer to remain as service\", 1, references.get(LEAKY_SIEVE_STABLE));\n \ }\n\n // Send a body to verify behaviour of send producer after another route has been stopped\n sendBody(\"direct:sieve-stable\", \"\");\n\n if (isFailFast()) {\n // shared pool is used despite being 'Stopped'\n if (isVerifyProducerServicePoolRemainsStarted()) {\n assertEquals(ServiceStatus.Started, service.getStatus());\n }\n\n assertEquals(\"Expected only stable producer in pool\", 1, context.getProducerServicePool().size());\n assertEquals(\"Expected no references to transient producer\", 0, references.get(LEAKY_SIEVE_TRANSIENT));\n \ assertEquals(\"Expected reference to stable producer\", 1, references.get(LEAKY_SIEVE_STABLE));\n \ }\n\n context.startRoute(\"sieve-transient\");\n\n // ok, back to normal\n assertEquals(ServiceStatus.Started, service.getStatus());\n if (isFailFast()) {\n assertEquals(\"Expected both producers in pool\", 2, context.getProducerServicePool().size());\n \ assertEquals(\"Expected one transient producer as service\", 1, references.get(LEAKY_SIEVE_TRANSIENT));\n \ assertEquals(\"Expected one stable producer as service\", 1, references.get(LEAKY_SIEVE_STABLE));\n \ }\n }\n\n if (!isFailFast()) {\n assertEquals(\"Expected both producers in pool\", 2, context.getProducerServicePool().size());\n\n // if not fixed these will equal the number of iterations in the loop + 1\n assertEquals(\"Expected one transient producer as service\", 1, references.get(LEAKY_SIEVE_TRANSIENT));\n \ assertEquals(\"Expected one stable producer as service\", 1, references.get(LEAKY_SIEVE_STABLE));\n \ }\n }\n\n private void registerLeakyComponent() {\n // register leaky component\n \ context.addComponent(\"leaky\", new LeakySieveComponent());\n }\n}\n{code}" diff --git a/camel-core/src/main/java/org/apache/camel/impl/ProducerCache.java b/camel-core/src/main/java/org/apache/camel/impl/ProducerCache.java index 5b79954..586cc69 100644 --- a/camel-core/src/main/java/org/apache/camel/impl/ProducerCache.java +++ b/camel-core/src/main/java/org/apache/camel/impl/ProducerCache.java @@ -60,23 +60,31 @@ public class ProducerCache extends ServiceSupport { private boolean eventNotifierEnabled = true; private boolean extendedStatistics; private int maxCacheSize; + private boolean stopServicePool; public ProducerCache(Object source, CamelContext camelContext) { this(source, camelContext, CamelContextHelper.getMaximumCachePoolSize(camelContext)); } public ProducerCache(Object source, CamelContext camelContext, int cacheSize) { - this(source, camelContext, camelContext.getProducerServicePool(), createLRUCache(cacheSize)); + this(source, camelContext, null, createLRUCache(cacheSize)); } public ProducerCache(Object source, CamelContext camelContext, Map<String, Producer> cache) { - this(source, camelContext, camelContext.getProducerServicePool(), cache); + this(source, camelContext, null, cache); } public ProducerCache(Object source, CamelContext camelContext, ServicePool<Endpoint, Producer> producerServicePool, Map<String, Producer> cache) { this.source = source; this.camelContext = camelContext; - this.pool = producerServicePool; + if (producerServicePool == null) { + // use shared producer pool which lifecycle is managed by CamelContext + this.pool = camelContext.getProducerServicePool(); + this.stopServicePool = false; + } else { + this.pool = producerServicePool; + this.stopServicePool = true; + } this.producers = cache; if (producers instanceof LRUCache) { maxCacheSize = ((LRUCache) producers).getMaxCacheSize(); @@ -468,7 +476,10 @@ public class ProducerCache extends ServiceSupport { protected void doStop() throws Exception { // when stopping we intend to shutdown - ServiceHelper.stopAndShutdownServices(statistics, pool); + ServiceHelper.stopAndShutdownService(statistics); + if (stopServicePool) { + ServiceHelper.stopAndShutdownService(pool); + } try { ServiceHelper.stopAndShutdownServices(producers.values()); } finally {
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-9143_08077733.diff
bugs-dot-jar_data_CAMEL-3690_2a3f3392
--- BugID: CAMEL-3690 Summary: Endpoints may be shutdown twice as they are tracked in two lists in CamelContext Description: |- Endpoint is a Service which means they are listed in both a endpoint and service list. They should only be listed in the endpoint list. This avoids issues with endpoints may be shutdown twice when Camel shutdown. See nabble http://camel.465427.n5.nabble.com/QuartzComponent-do-not-delete-quartz-worker-threads-when-shutdown-Camel-tp3393728p3393728.html diff --git a/camel-core/src/main/java/org/apache/camel/impl/DefaultCamelContext.java b/camel-core/src/main/java/org/apache/camel/impl/DefaultCamelContext.java index a8b9c80..f1dd98d 100644 --- a/camel-core/src/main/java/org/apache/camel/impl/DefaultCamelContext.java +++ b/camel-core/src/main/java/org/apache/camel/impl/DefaultCamelContext.java @@ -891,7 +891,8 @@ public class DefaultCamelContext extends ServiceSupport implements CamelContext, if (service instanceof IsSingleton) { singleton = ((IsSingleton) service).isSingleton(); } - if (singleton) { + // do not add endpoints as they have their own list + if (singleton && !(service instanceof Endpoint)) { servicesToClose.add(service); } }
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-3690_2a3f3392.diff
bugs-dot-jar_data_CAMEL-3545_050c542e
--- BugID: CAMEL-3545 Summary: MethodCallExpression doesn't validate whether the method exists for all cases Description: "I tried to refactor\n\n{code:title=org.apache.camel.model.language.MethodCallExpression.java}\n \ public Expression createExpression(CamelContext camelContext) {\n Expression answer;\n\n if (beanType != null) { \n instance = ObjectHelper.newInstance(beanType);\n \ return new BeanExpression(instance, getMethod(), parameterType); // <--\n } else if (instance != null) {\n return new BeanExpression(instance, getMethod(), parameterType); // <--\n } else {\n String ref = beanName();\n // if its a ref then check that the ref exists\n BeanHolder holder = new RegistryBean(camelContext, ref);\n // get the bean which will check that it exists\n instance = holder.getBean();\n answer = new BeanExpression(ref, getMethod(), parameterType);\n }\n\n // validate method\n validateHasMethod(camelContext, instance, getMethod(), parameterType);\n\n return answer;\n }\n{code}\n\nto\n\n{code:title=org.apache.camel.model.language.MethodCallExpression.java}\n \ public Expression createExpression(CamelContext camelContext) {\n Expression answer;\n\n if (beanType != null) { \n instance = ObjectHelper.newInstance(beanType);\n \ answer = new BeanExpression(instance, getMethod(), parameterType); // <--\n } else if (instance != null) {\n answer = new BeanExpression(instance, getMethod(), parameterType); // <--\n } else {\n String ref = beanName();\n // if its a ref then check that the ref exists\n BeanHolder holder = new RegistryBean(camelContext, ref);\n // get the bean which will check that it exists\n instance = holder.getBean();\n answer = new BeanExpression(ref, getMethod(), parameterType);\n }\n\n // validate method\n validateHasMethod(camelContext, instance, getMethod(), parameterType);\n\n return answer;\n }\n{code}\n\nso that the created BeanExpression is also validate if you provide the bean type or an instance. With this change, some tests in org.apache.camel.language.SimpleTest fails.\nI'm not sure whether the tests are faulty or if it's a bug.\nAlso not sure whether this should fixed in 2.6. " diff --git a/camel-core/src/main/java/org/apache/camel/component/bean/MethodNotFoundException.java b/camel-core/src/main/java/org/apache/camel/component/bean/MethodNotFoundException.java index 8dceafd..e0ecab3 100644 --- a/camel-core/src/main/java/org/apache/camel/component/bean/MethodNotFoundException.java +++ b/camel-core/src/main/java/org/apache/camel/component/bean/MethodNotFoundException.java @@ -30,10 +30,12 @@ public class MethodNotFoundException extends CamelExchangeException { private final Object bean; private final String methodName; @SuppressWarnings("rawtypes") - private final List<Class> parameterTypes; + private List<Class> parameterTypes; public MethodNotFoundException(Exchange exchange, Object pojo, String methodName) { - this(exchange, pojo, methodName, null); + super("Method with name: " + methodName + " not found on bean: " + pojo, exchange); + this.methodName = methodName; + this.bean = pojo; } @SuppressWarnings("rawtypes") @@ -44,6 +46,12 @@ public class MethodNotFoundException extends CamelExchangeException { this.parameterTypes = parameterTypes; } + public MethodNotFoundException(Object pojo, String methodName, Throwable cause) { + super("Method with name: " + methodName + " not found on bean: " + pojo, null, cause); + this.methodName = methodName; + this.bean = pojo; + } + public String getMethodName() { return methodName; } diff --git a/camel-core/src/main/java/org/apache/camel/model/language/MethodCallExpression.java b/camel-core/src/main/java/org/apache/camel/model/language/MethodCallExpression.java index 511b5ad..46aa7b7 100644 --- a/camel-core/src/main/java/org/apache/camel/model/language/MethodCallExpression.java +++ b/camel-core/src/main/java/org/apache/camel/model/language/MethodCallExpression.java @@ -27,13 +27,16 @@ import javax.xml.bind.annotation.XmlTransient; import org.apache.camel.CamelContext; import org.apache.camel.Expression; +import org.apache.camel.ExpressionIllegalSyntaxException; import org.apache.camel.Predicate; import org.apache.camel.component.bean.BeanHolder; import org.apache.camel.component.bean.BeanInfo; import org.apache.camel.component.bean.MethodNotFoundException; import org.apache.camel.component.bean.RegistryBean; import org.apache.camel.language.bean.BeanExpression; +import org.apache.camel.language.bean.RuntimeBeanExpressionException; import org.apache.camel.util.ObjectHelper; +import org.apache.camel.util.OgnlHelper; /** * For expressions and predicates using the @@ -127,22 +130,23 @@ public class MethodCallExpression extends ExpressionDefinition { @Override public Expression createExpression(CamelContext camelContext) { + Expression answer; if (beanType != null) { instance = ObjectHelper.newInstance(beanType); - return new BeanExpression(instance, getMethod(), parameterType); + answer = new BeanExpression(instance, getMethod(), parameterType); } else if (instance != null) { - return new BeanExpression(instance, getMethod(), parameterType); + answer = new BeanExpression(instance, getMethod(), parameterType); } else { String ref = beanName(); // if its a ref then check that the ref exists BeanHolder holder = new RegistryBean(camelContext, ref); // get the bean which will check that it exists instance = holder.getBean(); - // only validate when it was a ref for a bean, so we can eager check - // this on startup of Camel - validateHasMethod(camelContext, instance, getMethod(), parameterType); - return new BeanExpression(ref, getMethod(), parameterType); + answer = new BeanExpression(ref, getMethod(), parameterType); } + + validateHasMethod(camelContext, instance, getMethod(), parameterType); + return answer; } @Override @@ -151,7 +155,9 @@ public class MethodCallExpression extends ExpressionDefinition { } /** - * Validates the given bean has the method + * Validates the given bean has the method. + * <p/> + * This implementation will skip trying to validate OGNL method name expressions. * * @param context camel context * @param bean the bean instance @@ -164,11 +170,23 @@ public class MethodCallExpression extends ExpressionDefinition { return; } + // do not try to validate ognl methods + if (OgnlHelper.isValidOgnlExpression(method)) { + return; + } + + // if invalid OGNL then fail + if (OgnlHelper.isInvalidValidOgnlExpression(method)) { + ExpressionIllegalSyntaxException cause = new ExpressionIllegalSyntaxException(method); + throw ObjectHelper.wrapRuntimeCamelException(new MethodNotFoundException(bean, method, cause)); + } + BeanInfo info = new BeanInfo(context, bean.getClass()); List<Class> parameterTypes = new ArrayList<Class>(); if (parameterType != null) { - parameterTypes.add(parameterType); + parameterTypes.add(parameterType); } + if (!info.hasMethod(method, parameterTypes)) { throw ObjectHelper.wrapRuntimeCamelException(new MethodNotFoundException(null, bean, method, parameterTypes)); }
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-3545_050c542e.diff
bugs-dot-jar_data_CAMEL-3531_41e4b5b9
--- BugID: CAMEL-3531 Summary: scala - xpath not working together with choice/when Description: "When using the Scala DSL, xpath expressions inside when() do not work as expected. As an example:\n{code:none}\n \"direct:a\" ==> {\n choice {\n \ when (xpath(\"//hello\")) to (\"mock:english\")\n when (xpath(\"//hallo\")) {\n to (\"mock:dutch\")\n to (\"mock:german\")\n } \n otherwise to (\"mock:french\")\n }\n }\n\n// Send messages\n\"direct:a\" ! (\"<hello/>\", \"<hallo/>\", \"<hellos/>\")\n{code}\n\nHere we should receive 1 message in each of the mocks. For whatever reason, all 3 messages go to mock:english. Similar routes work as expected with the Java DSL. " diff --git a/camel-core/src/main/java/org/apache/camel/util/ObjectHelper.java b/camel-core/src/main/java/org/apache/camel/util/ObjectHelper.java index 6bb393d..636c4a8 100644 --- a/camel-core/src/main/java/org/apache/camel/util/ObjectHelper.java +++ b/camel-core/src/main/java/org/apache/camel/util/ObjectHelper.java @@ -38,6 +38,7 @@ import java.util.Map; import java.util.Properties; import java.util.Scanner; +import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; @@ -1118,6 +1119,14 @@ public final class ObjectHelper { } else if ("false".equalsIgnoreCase((String)value)) { return false; } + } else if (value instanceof NodeList) { + // is it an empty dom + NodeList list = (NodeList) value; + return list.getLength() > 0; + } else if (value instanceof Collection) { + // is it an empty collection + Collection col = (Collection) value; + return col.size() > 0; } return value != null; }
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-3531_41e4b5b9.diff
bugs-dot-jar_data_CAMEL-9672_84922699
--- BugID: CAMEL-9672 Summary: ClassCastException with interceptFrom Description: |- If a statement like {code:java} interceptFrom().when(simple("${header.foo} == 'bar'")).to("mock:intercepted"); {code} is available in a route builder with JMX enabled the startup will fail in Camel 2.16.2 (and the current 2.17-SNAPSHOT) with a ClassCastException in line 310 of DefaultManagementObjectStrategy. The generated processor is a FilterProcessor, but the resulting definition is a WhenDefinition not a FilterDefinition. The reason is that CAMEL-8992 introduced a too precise class check for this. The attached patch relexes the class constraint on the definition. diff --git a/camel-core/src/main/java/org/apache/camel/management/DefaultManagementObjectStrategy.java b/camel-core/src/main/java/org/apache/camel/management/DefaultManagementObjectStrategy.java index d30e4fe..c53cffb 100644 --- a/camel-core/src/main/java/org/apache/camel/management/DefaultManagementObjectStrategy.java +++ b/camel-core/src/main/java/org/apache/camel/management/DefaultManagementObjectStrategy.java @@ -96,6 +96,7 @@ import org.apache.camel.management.mbean.ManagedUnmarshal; import org.apache.camel.management.mbean.ManagedValidate; import org.apache.camel.management.mbean.ManagedWeightedLoadBalancer; import org.apache.camel.management.mbean.ManagedWireTapProcessor; +import org.apache.camel.model.ExpressionNode; import org.apache.camel.model.LoadBalanceDefinition; import org.apache.camel.model.ModelCamelContext; import org.apache.camel.model.ProcessDefinition; @@ -307,7 +308,7 @@ public class DefaultManagementObjectStrategy implements ManagementObjectStrategy } else if (target instanceof RoutingSlip) { answer = new ManagedRoutingSlip(context, (RoutingSlip) target, (org.apache.camel.model.RoutingSlipDefinition) definition); } else if (target instanceof FilterProcessor) { - answer = new ManagedFilter(context, (FilterProcessor) target, (org.apache.camel.model.FilterDefinition) definition); + answer = new ManagedFilter(context, (FilterProcessor) target, (ExpressionNode)definition); } else if (target instanceof LogProcessor) { answer = new ManagedLog(context, (LogProcessor) target, definition); } else if (target instanceof LoopProcessor) { diff --git a/camel-core/src/main/java/org/apache/camel/management/mbean/ManagedFilter.java b/camel-core/src/main/java/org/apache/camel/management/mbean/ManagedFilter.java index 9d9ae5a..2d253b6 100644 --- a/camel-core/src/main/java/org/apache/camel/management/mbean/ManagedFilter.java +++ b/camel-core/src/main/java/org/apache/camel/management/mbean/ManagedFilter.java @@ -19,7 +19,7 @@ package org.apache.camel.management.mbean; import org.apache.camel.CamelContext; import org.apache.camel.api.management.ManagedResource; import org.apache.camel.api.management.mbean.ManagedFilterMBean; -import org.apache.camel.model.FilterDefinition; +import org.apache.camel.model.ExpressionNode; import org.apache.camel.processor.FilterProcessor; /** @@ -29,14 +29,14 @@ import org.apache.camel.processor.FilterProcessor; public class ManagedFilter extends ManagedProcessor implements ManagedFilterMBean { private final FilterProcessor processor; - public ManagedFilter(CamelContext context, FilterProcessor processor, FilterDefinition definition) { + public ManagedFilter(CamelContext context, FilterProcessor processor, ExpressionNode definition) { super(context, processor, definition); this.processor = processor; } @Override - public FilterDefinition getDefinition() { - return (FilterDefinition) super.getDefinition(); + public ExpressionNode getDefinition() { + return (ExpressionNode) super.getDefinition(); } @Override
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-9672_84922699.diff
bugs-dot-jar_data_CAMEL-3433_e76d23b0
--- BugID: CAMEL-3433 Summary: Undefined header results in Nullpointer when expression is evaluated Description: "If you define a filter for a header that is not defined like\n\nfrom(\"p:a\").filter(header(\"header\").in(\"value\")).to(\"p:b\");\n\nit results in a NullPointerException:\n\n{code}\n2010-12-15 10:07:45,920 [main] ERROR DefaultErrorHandler - \nFailed delivery for exchangeId: 0215-1237-1292404064936-0-2. \nExhausted after delivery attempt: 1 caught: java.lang.NullPointerException\n\tat org.apache.camel.builder.ExpressionBuilder$40.evaluate(ExpressionBuilder.java:955)\n\tat org.apache.camel.impl.ExpressionAdapter.evaluate(ExpressionAdapter.java:36)\n\tat org.apache.camel.builder.BinaryPredicateSupport.matches(BinaryPredicateSupport.java:54)\n\tat org.apache.camel.builder.PredicateBuilder$5.matches(PredicateBuilder.java:127)\n\tat org.apache.camel.processor.FilterProcessor.process(FilterProcessor.java:46)\n\tat org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:70)\n\tat org.apache.camel.processor.DelegateAsyncProcessor.processNext(DelegateAsyncProcessor.java:98)\n\tat org.apache.camel.processor.DelegateAsyncProcessor.process(DelegateAsyncProcessor.java:89)\n{code}\n\nThis test reproduces the problem:\n{code}\npublic void testExpressionForUndefinedHeader(){\n \ Expression type = ExpressionBuilder.headerExpression(\"header\");\n Expression expression = ExpressionBuilder.constantExpression(\"value\");\n Expression convertToExpression = ExpressionBuilder.convertToExpression(expression, type);\n convertToExpression.evaluate(exchange, Object.class);\n}\n{code}" diff --git a/camel-core/src/main/java/org/apache/camel/builder/ExpressionBuilder.java b/camel-core/src/main/java/org/apache/camel/builder/ExpressionBuilder.java index 5f73fe3..db029ec 100644 --- a/camel-core/src/main/java/org/apache/camel/builder/ExpressionBuilder.java +++ b/camel-core/src/main/java/org/apache/camel/builder/ExpressionBuilder.java @@ -935,12 +935,16 @@ public final class ExpressionBuilder { public static Expression convertToExpression(final Expression expression, final Class type) { return new ExpressionAdapter() { public Object evaluate(Exchange exchange) { - return expression.evaluate(exchange, type); + if (type != null) { + return expression.evaluate(exchange, type); + } else { + return expression; + } } @Override public String toString() { - return "" + expression + ".convertTo(" + type.getCanonicalName() + ".class)"; + return "" + expression; } }; } @@ -952,12 +956,17 @@ public final class ExpressionBuilder { public static Expression convertToExpression(final Expression expression, final Expression type) { return new ExpressionAdapter() { public Object evaluate(Exchange exchange) { - return expression.evaluate(exchange, type.evaluate(exchange, Object.class).getClass()); + Object result = type.evaluate(exchange, Object.class); + if (result != null) { + return expression.evaluate(exchange, result.getClass()); + } else { + return expression; + } } @Override public String toString() { - return "" + expression + ".convertToEvaluatedType(" + type + ")"; + return "" + expression; } }; }
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-3433_e76d23b0.diff
bugs-dot-jar_data_CAMEL-8125_36e7b668
--- BugID: CAMEL-8125 Summary: PropertyInject gives NullPointerException Description: "Using the annotation @PropertyInject on a field of the RouteBuilder class gives a NullPointerException\n\npublic class RouteBuilder extends SpringRouteBuilder {\n\t\n\t@PropertyInject(\"foo.bar\")\n\tprivate String fooBar;\n ...\n}\n\nUsing the {{ }} notation in endpoint URIs is working though.\n\n\t\n\n\n" diff --git a/camel-core/src/main/java/org/apache/camel/impl/CamelPostProcessorHelper.java b/camel-core/src/main/java/org/apache/camel/impl/CamelPostProcessorHelper.java index 04dbc4d..817a2f9 100644 --- a/camel-core/src/main/java/org/apache/camel/impl/CamelPostProcessorHelper.java +++ b/camel-core/src/main/java/org/apache/camel/impl/CamelPostProcessorHelper.java @@ -22,6 +22,7 @@ import javax.xml.bind.annotation.XmlTransient; import org.apache.camel.CamelContext; import org.apache.camel.CamelContextAware; +import org.apache.camel.Component; import org.apache.camel.Consume; import org.apache.camel.Consumer; import org.apache.camel.ConsumerTemplate; @@ -37,7 +38,6 @@ import org.apache.camel.Service; import org.apache.camel.component.bean.BeanInfo; import org.apache.camel.component.bean.BeanProcessor; import org.apache.camel.component.bean.ProxyHelper; -import org.apache.camel.component.properties.PropertiesComponent; import org.apache.camel.processor.CamelInternalProcessor; import org.apache.camel.processor.UnitOfWorkProducer; import org.apache.camel.util.CamelContextHelper; @@ -227,17 +227,13 @@ public class CamelPostProcessorHelper implements CamelContextAware { public Object getInjectionPropertyValue(Class<?> type, String propertyName, String propertyDefaultValue, String injectionPointName, Object bean, String beanName) { try { + // enforce a properties component to be created if none existed + CamelContextHelper.lookupPropertiesComponent(getCamelContext(), true); + String key; String prefix = getCamelContext().getPropertyPrefixToken(); String suffix = getCamelContext().getPropertySuffixToken(); - - if (prefix == null && suffix == null) { - // if no custom prefix/suffix then use defaults - prefix = PropertiesComponent.DEFAULT_PREFIX_TOKEN; - suffix = PropertiesComponent.DEFAULT_SUFFIX_TOKEN; - } - - if (!propertyName.startsWith(prefix)) { + if (!propertyName.contains(prefix)) { // must enclose the property name with prefix/suffix to have it resolved key = prefix + propertyName + suffix; } else { diff --git a/camel-core/src/main/java/org/apache/camel/impl/DefaultCamelContext.java b/camel-core/src/main/java/org/apache/camel/impl/DefaultCamelContext.java index 256fc8c..7eb7fe6 100644 --- a/camel-core/src/main/java/org/apache/camel/impl/DefaultCamelContext.java +++ b/camel-core/src/main/java/org/apache/camel/impl/DefaultCamelContext.java @@ -37,7 +37,6 @@ import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; - import javax.naming.Context; import javax.xml.bind.JAXBContext; import javax.xml.bind.Unmarshaller; @@ -1458,23 +1457,8 @@ public class DefaultCamelContext extends ServiceSupport implements ModelCamelCon if (text != null && !text.startsWith("properties:")) { // No component, assume default tokens. if (pc == null && text.contains(PropertiesComponent.DEFAULT_PREFIX_TOKEN)) { - - // try to lookup component, as we may be initializing CamelContext itself - Component existing = lookupPropertiesComponent(); - if (existing != null) { - if (existing instanceof PropertiesComponent) { - pc = (PropertiesComponent) existing; - } else { - // properties component must be expected type - throw new IllegalArgumentException("Found properties component of type: " + existing.getClass() + " instead of expected: " + PropertiesComponent.class); - } - } - - if (pc == null) { - // create a default properties component to be used as there may be default values we can use - log.info("No existing PropertiesComponent has been configured, creating a new default PropertiesComponent with name: properties"); - pc = getComponent("properties", PropertiesComponent.class); - } + // lookup existing properties component, or force create a new default component + pc = (PropertiesComponent) CamelContextHelper.lookupPropertiesComponent(this, true); } if (pc != null && text.contains(pc.getPrefixToken())) { @@ -2111,7 +2095,7 @@ public class DefaultCamelContext extends ServiceSupport implements ModelCamelCon // eager lookup any configured properties component to avoid subsequent lookup attempts which may impact performance // due we use properties component for property placeholder resolution at runtime - Component existing = lookupPropertiesComponent(); + Component existing = CamelContextHelper.lookupPropertiesComponent(this, false); if (existing != null) { // store reference to the existing properties component if (existing instanceof PropertiesComponent) { @@ -3075,16 +3059,12 @@ public class DefaultCamelContext extends ServiceSupport implements ModelCamelCon } } + /** + * @deprecated use {@link org.apache.camel.util.CamelContextHelper#lookupPropertiesComponent(org.apache.camel.CamelContext, boolean)} + */ + @Deprecated protected Component lookupPropertiesComponent() { - // no existing properties component so lookup and add as component if possible - PropertiesComponent answer = (PropertiesComponent) hasComponent("properties"); - if (answer == null) { - answer = getRegistry().lookupByNameAndType("properties", PropertiesComponent.class); - if (answer != null) { - addComponent("properties", answer); - } - } - return answer; + return CamelContextHelper.lookupPropertiesComponent(this, false); } public ShutdownStrategy getShutdownStrategy() { diff --git a/camel-core/src/main/java/org/apache/camel/model/ProcessorDefinitionHelper.java b/camel-core/src/main/java/org/apache/camel/model/ProcessorDefinitionHelper.java index 87689a3..5ba236b 100644 --- a/camel-core/src/main/java/org/apache/camel/model/ProcessorDefinitionHelper.java +++ b/camel-core/src/main/java/org/apache/camel/model/ProcessorDefinitionHelper.java @@ -31,6 +31,7 @@ import javax.xml.namespace.QName; import org.apache.camel.Exchange; import org.apache.camel.spi.ExecutorServiceManager; import org.apache.camel.spi.RouteContext; +import org.apache.camel.util.CamelContextHelper; import org.apache.camel.util.IntrospectionSupport; import org.apache.camel.util.ObjectHelper; import org.slf4j.Logger; @@ -524,6 +525,9 @@ public final class ProcessorDefinitionHelper { String local = key.getLocalPart(); Object value = processorDefinition.getOtherAttributes().get(key); if (value != null && value instanceof String) { + // enforce a properties component to be created if none existed + CamelContextHelper.lookupPropertiesComponent(routeContext.getCamelContext(), true); + // value must be enclosed with placeholder tokens String s = (String) value; String prefixToken = routeContext.getCamelContext().getPropertyPrefixToken(); diff --git a/camel-core/src/main/java/org/apache/camel/util/CamelContextHelper.java b/camel-core/src/main/java/org/apache/camel/util/CamelContextHelper.java index ab829f6..097ed29 100644 --- a/camel-core/src/main/java/org/apache/camel/util/CamelContextHelper.java +++ b/camel-core/src/main/java/org/apache/camel/util/CamelContextHelper.java @@ -35,6 +35,7 @@ import org.apache.camel.Endpoint; import org.apache.camel.Exchange; import org.apache.camel.NoSuchBeanException; import org.apache.camel.NoSuchEndpointException; +import org.apache.camel.component.properties.PropertiesComponent; import org.apache.camel.spi.ClassResolver; import org.apache.camel.spi.RouteStartupOrder; import org.slf4j.Logger; @@ -477,4 +478,30 @@ public final class CamelContextHelper { return 0; } + /** + * Lookup the {@link org.apache.camel.component.properties.PropertiesComponent} from the {@link org.apache.camel.CamelContext}. + * <p/> + * @param camelContext the camel context + * @param autoCreate whether to automatic create a new default {@link org.apache.camel.component.properties.PropertiesComponent} if no custom component + * has been configured. + * @return the properties component, or <tt>null</tt> if none has been defined, and auto create is <tt>false</tt>. + */ + public static Component lookupPropertiesComponent(CamelContext camelContext, boolean autoCreate) { + // no existing properties component so lookup and add as component if possible + PropertiesComponent answer = (PropertiesComponent) camelContext.hasComponent("properties"); + if (answer == null) { + answer = camelContext.getRegistry().lookupByNameAndType("properties", PropertiesComponent.class); + if (answer != null) { + camelContext.addComponent("properties", answer); + } + } + if (answer == null && autoCreate) { + // create a default properties component to be used as there may be default values we can use + LOG.info("No existing PropertiesComponent has been configured, creating a new default PropertiesComponent with name: properties"); + answer = camelContext.getComponent("properties", PropertiesComponent.class); + } + return answer; + } + + }
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-8125_36e7b668.diff
bugs-dot-jar_data_CAMEL-4513_9e05f77f
--- BugID: CAMEL-4513 Summary: simple predicate fails to introspect the exception in an onException clause using onWhen Description: |- The bug occured in the 2.6.0 version of Camel I'm using. I haven't test it against the latest version but I've checked the sources and it doesn't seem to have change since. Given a camel route, with a onException clause like this : {code} this.onException(MyException.class) .onWhen(simple("${exception.myExceptionInfo.aValue} == true")) ... {code} MyException is a customed exception like this : {code:title=MyException.java} public class MyException extends Exception { .... public MyExceptionInfo getMyExceptionInfo() { ... } } {code} What I've observed is that when BeanExpression.OgnlInvokeProcessor.process iterate through the methods to calls, it does : {code} // only invoke if we have a method name to use to invoke if (methodName != null) { InvokeProcessor invoke = new InvokeProcessor(holder, methodName); invoke.process(resultExchange); // check for exception and rethrow if we failed if (resultExchange.getException() != null) { throw new RuntimeBeanExpressionException(exchange, beanName, methodName, resultExchange.getException()); } result = invoke.getResult(); } {code} It successfully invoke the method : invoke.process(resultExchange); But it checks for exception in the exchange. Since we are in an exception clause, there is an actual exception (thrown by the application, but unrelated with the expression language search) and it fails There is a simple workaround for that : writing his own predicate class to test wanted conditions diff --git a/camel-core/src/main/java/org/apache/camel/language/bean/BeanExpression.java b/camel-core/src/main/java/org/apache/camel/language/bean/BeanExpression.java index 98ac1c5..f79e041 100644 --- a/camel-core/src/main/java/org/apache/camel/language/bean/BeanExpression.java +++ b/camel-core/src/main/java/org/apache/camel/language/bean/BeanExpression.java @@ -154,6 +154,9 @@ public class BeanExpression implements Expression, Predicate { try { // copy the original exchange to avoid side effects on it Exchange resultExchange = exchange.copy(); + // remove any existing exception in case we do OGNL on the exception + resultExchange.setException(null); + // force to use InOut to retrieve the result on the OUT message resultExchange.setPattern(ExchangePattern.InOut); processor.process(resultExchange); @@ -195,6 +198,8 @@ public class BeanExpression implements Expression, Predicate { public void process(Exchange exchange) throws Exception { // copy the original exchange to avoid side effects on it Exchange resultExchange = exchange.copy(); + // remove any existing exception in case we do OGNL on the exception + resultExchange.setException(null); // force to use InOut to retrieve the result on the OUT message resultExchange.setPattern(ExchangePattern.InOut); // do not propagate any method name when using OGNL, as with OGNL we
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-4513_9e05f77f.diff
bugs-dot-jar_data_CAMEL-3709_4c37e773
--- BugID: CAMEL-3709 Summary: interceptFrom and from(Endpoint) don't work together Description: "When using interceptFrom(String) together with from(Endpoint), the below Exception occurs during the routes building process. Looking at RoutesDefinition.java:217 reveals, that the FromDefintion just created has no URI. That causes the comparison to all the interceptFroms' URIs to fail. As far as I can tell, the way to fix this would be to add {{setUri(myEndpoint.getEndpointUri())}} in the constructor {{FromDefinition(Endpoint endpoint)}}.\n\nBelow the stack trace, there is a unit test that demonstrates the issue. Until it if fixed, it can be easily circumvented by adding the commented-out line, and then change to {{from(\"myEndpoint\")}}.\n{code}\norg.apache.camel.ResolveEndpointFailedException: Failed to resolve endpoint: null due to: null\n\tat org.apache.camel.util.EndpointHelper.matchEndpoint(EndpointHelper.java:109)\n\tat org.apache.camel.model.RoutesDefinition.route(RoutesDefinition.java:217)\n\tat org.apache.camel.model.RoutesDefinition.from(RoutesDefinition.java:167)\n\tat org.apache.camel.builder.RouteBuilder.from(RouteBuilder.java:101)\n\tat dk.mobilethink.adc2.endpoint.UnsetUriTest$1.configure(UnsetUriTest.java:18)\n\tat org.apache.camel.builder.RouteBuilder.checkInitialized(RouteBuilder.java:318)\n\tat org.apache.camel.builder.RouteBuilder.configureRoutes(RouteBuilder.java:273)\n\tat org.apache.camel.builder.RouteBuilder.addRoutesToCamelContext(RouteBuilder.java:259)\n\tat org.apache.camel.impl.DefaultCamelContext.addRoutes(DefaultCamelContext.java:612)\n\tat org.apache.camel.test.CamelTestSupport.setUp(CamelTestSupport.java:111)\n\tat junit.framework.TestCase.runBare(TestCase.java:132)\n\tat org.apache.camel.test.TestSupport.runBare(TestSupport.java:65)\n\tat junit.framework.TestResult$1.protect(TestResult.java:110)\n\tat junit.framework.TestResult.runProtected(TestResult.java:128)\n\tat junit.framework.TestResult.run(TestResult.java:113)\n\tat junit.framework.TestCase.run(TestCase.java:124)\n\tat junit.framework.TestSuite.runTest(TestSuite.java:232)\n\tat junit.framework.TestSuite.run(TestSuite.java:227)\n\tat org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:83)\n\tat org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49)\n\tat org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)\n\tat org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)\n\tat org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)\n\tat org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)\n\tat org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)\nCaused by: java.lang.NullPointerException\n\tat org.apache.camel.util.UnsafeUriCharactersEncoder.encode(UnsafeUriCharactersEncoder.java:56)\n\tat org.apache.camel.util.URISupport.normalizeUri(URISupport.java:162)\n\tat org.apache.camel.util.EndpointHelper.matchEndpoint(EndpointHelper.java:107)\n\t... 24 more\n{code}\n\n{code}\npackage dk.mobilethink.adc2.endpoint;\n\nimport org.apache.camel.Endpoint;\nimport org.apache.camel.builder.RouteBuilder;\nimport org.apache.camel.test.CamelTestSupport;\n\npublic class UnsetUriTest extends CamelTestSupport {\n\t@Override\n\tprotected RouteBuilder createRouteBuilder() throws Exception {\n\n\t\treturn new RouteBuilder() {\n\t\t\tpublic void configure() throws Exception {\n\t\t\t\tinterceptFrom(\"URI1\").to(\"irrelevantURI\");\n\n\t\t\t\tEndpoint myEndpoint = getContext().getComponent(\"direct\").createEndpoint(\"ignoredURI\");\n\t\t\t\t\n//\t\t\t\tgetContext().addEndpoint(\"myEndpoint\", myEndpoint);\n\t\t\t\tfrom(myEndpoint)\n\t\t\t\t\t.inOnly(\"log:foo\");\n\t\t\t}\n\t\t};\n\t}\n\n\tpublic void testNothing() { }\n}\n{code}\n" diff --git a/camel-core/src/main/java/org/apache/camel/model/FromDefinition.java b/camel-core/src/main/java/org/apache/camel/model/FromDefinition.java index 63e4710..7fb6666 100644 --- a/camel-core/src/main/java/org/apache/camel/model/FromDefinition.java +++ b/camel-core/src/main/java/org/apache/camel/model/FromDefinition.java @@ -77,8 +77,15 @@ public class FromDefinition extends OptionalIdentifiedDefinition<FromDefinition> // Properties // ----------------------------------------------------------------------- + public String getUri() { - return uri; + if (uri != null) { + return uri; + } else if (endpoint != null) { + return endpoint.getEndpointUri(); + } else { + return null; + } } /**
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-3709_4c37e773.diff
bugs-dot-jar_data_CAMEL-5681_78c73502
--- BugID: CAMEL-5681 Summary: Using recipient list in a doTry ... doCatch situation dont work properly Description: | See nabble http://camel.465427.n5.nabble.com/Issue-with-doTry-doCatch-not-routing-correctly-tp5720325.html The end user would expect that doTry .. doCatch will overrule. However it gets a bit further more complicated if the try block routes to other routes and using EIPs such as recipient list. diff --git a/camel-core/src/main/java/org/apache/camel/processor/MulticastProcessor.java b/camel-core/src/main/java/org/apache/camel/processor/MulticastProcessor.java index e538801..b2930f6 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/MulticastProcessor.java +++ b/camel-core/src/main/java/org/apache/camel/processor/MulticastProcessor.java @@ -200,19 +200,11 @@ public class MulticastProcessor extends ServiceSupport implements AsyncProcessor final AtomicExchange result = new AtomicExchange(); final Iterable<ProcessorExchangePair> pairs; - // multicast uses fine grained error handling on the output processors - // so use try .. catch to cater for this - boolean exhaust = false; try { boolean sync = true; pairs = createProcessorExchangePairs(exchange); - // after we have created the processors we consider the exchange as exhausted if an unhandled - // exception was thrown, (used in the catch block) - // if the processors is working in Streaming model, the exchange could not be processed at this point. - exhaust = !isStreaming(); - if (isParallelProcessing()) { // ensure an executor is set when running in parallel ObjectHelper.notNull(executorService, "executorService", this); @@ -228,15 +220,16 @@ public class MulticastProcessor extends ServiceSupport implements AsyncProcessor } } catch (Throwable e) { exchange.setException(e); + // unexpected exception was thrown, maybe from iterator etc. so do not regard as exhausted // and do the done work - doDone(exchange, null, callback, true, exhaust); + doDone(exchange, null, callback, true, false); return true; } // multicasting was processed successfully // and do the done work Exchange subExchange = result.get() != null ? result.get() : null; - doDone(exchange, subExchange, callback, true, exhaust); + doDone(exchange, subExchange, callback, true, true); return true; } @@ -308,7 +301,8 @@ public class MulticastProcessor extends ServiceSupport implements AsyncProcessor // throw caused exception if (subExchange.getException() != null) { // wrap in exception to explain where it failed - throw new CamelExchangeException("Parallel processing failed for number " + number, subExchange, subExchange.getException()); + CamelExchangeException cause = new CamelExchangeException("Parallel processing failed for number " + number, subExchange, subExchange.getException()); + subExchange.setException(cause); } } @@ -527,14 +521,14 @@ public class MulticastProcessor extends ServiceSupport implements AsyncProcessor if (stopOnException && !continueProcessing) { if (subExchange.getException() != null) { // wrap in exception to explain where it failed - throw new CamelExchangeException("Sequential processing failed for number " + total.get(), subExchange, subExchange.getException()); - } else { - // we want to stop on exception, and the exception was handled by the error handler - // this is similar to what the pipeline does, so we should do the same to not surprise end users - // so we should set the failed exchange as the result and be done - result.set(subExchange); - return true; + CamelExchangeException cause = new CamelExchangeException("Sequential processing failed for number " + total.get(), subExchange, subExchange.getException()); + subExchange.setException(cause); } + // we want to stop on exception, and the exception was handled by the error handler + // this is similar to what the pipeline does, so we should do the same to not surprise end users + // so we should set the failed exchange as the result and be done + result.set(subExchange); + return true; } LOG.trace("Sequential processing complete for number {} exchange: {}", total, subExchange); diff --git a/camel-core/src/main/java/org/apache/camel/processor/TryProcessor.java b/camel-core/src/main/java/org/apache/camel/processor/TryProcessor.java index 9c4b00d..6cac402 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/TryProcessor.java +++ b/camel-core/src/main/java/org/apache/camel/processor/TryProcessor.java @@ -361,6 +361,8 @@ public class TryProcessor extends ServiceSupport implements AsyncProcessor, Navi // give the rest of the pipeline another chance exchange.setProperty(Exchange.EXCEPTION_CAUGHT, caught); exchange.setException(null); + // and we should not be regarded as exhausted as we are in a try .. catch block + exchange.removeProperty(Exchange.REDELIVERY_EXHAUSTED); // is the exception handled by the catch clause final Boolean handled = catchClause.handles(exchange);
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-5681_78c73502.diff
bugs-dot-jar_data_CAMEL-8106_39ccf5d6
--- BugID: CAMEL-8106 Summary: XML parsing error is ignored by xtoknize XML tokenizer Description: 'XML parsing exceptions are ignored by xtokenize XML tokenizer and this is leading to the same token extracted repeated times. ' diff --git a/camel-core/src/main/java/org/apache/camel/support/XMLTokenExpressionIterator.java b/camel-core/src/main/java/org/apache/camel/support/XMLTokenExpressionIterator.java index f233281..19cc2a6 100644 --- a/camel-core/src/main/java/org/apache/camel/support/XMLTokenExpressionIterator.java +++ b/camel-core/src/main/java/org/apache/camel/support/XMLTokenExpressionIterator.java @@ -575,7 +575,8 @@ public class XMLTokenExpressionIterator extends ExpressionAdapter implements Nam try { nextToken = getNextToken(); } catch (XMLStreamException e) { - // + nextToken = null; + throw new RuntimeException(e); } return o; }
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-8106_39ccf5d6.diff
bugs-dot-jar_data_CAMEL-3760_5225e6e3
--- BugID: CAMEL-3760 Summary: ManagementNamingStrategy - Should normalize ObjectName to avoid using illegal characters Description: "For example when using JMS in the loanbroaker example. There us a colon in the JMS queue name which is invalid char in JMX.\n\n2011-03-06 08:26:55,859 [main \ ] WARN ManagedManagementStrategy - Cannot check whether the managed object is registered. This exception will be ignored.\njavax.management.MalformedObjectNameException: Could not create ObjectName from: org.apache.camel:context=vesta.apache.org/camel-1,type=threadpools,name=JmsReplyManagerTimeoutChecker[queue2:parallelLoanRequestQueue]. Reason: javax.management.MalformedObjectNameException: Invalid character ':' in value part of property\n\tat org.apache.camel.management.DefaultManagementNamingStrategy.createObjectName(DefaultManagementNamingStrategy.java:315)[camel-core-2.7-SNAPSHOT.jar:2.7-SNAPSHOT]\n\n\n" diff --git a/camel-core/src/main/java/org/apache/camel/management/DefaultManagementNamingStrategy.java b/camel-core/src/main/java/org/apache/camel/management/DefaultManagementNamingStrategy.java index 473c07f..ef21e26 100644 --- a/camel-core/src/main/java/org/apache/camel/management/DefaultManagementNamingStrategy.java +++ b/camel-core/src/main/java/org/apache/camel/management/DefaultManagementNamingStrategy.java @@ -254,11 +254,13 @@ public class DefaultManagementNamingStrategy implements ManagementNamingStrategy buffer.append(domainName).append(":"); buffer.append(KEY_CONTEXT + "=").append(getContextId(context)).append(","); buffer.append(KEY_TYPE + "=" + TYPE_THREAD_POOL + ","); - buffer.append(KEY_NAME + "=").append(id); + + String name = id; if (sourceId != null) { // provide source id if we know it, this helps end user to know where the pool is used - buffer.append("(").append(sourceId).append(")"); + name = name + "(" + sourceId + ")"; } + buffer.append(KEY_NAME + "=").append(ObjectName.quote(name)); return createObjectName(buffer); }
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-3760_5225e6e3.diff
bugs-dot-jar_data_CAMEL-5571_0e87b84f
--- BugID: CAMEL-5571 Summary: Camel proxies should not forward hashCode() method invocations Description: | Given a Camel proxy for an @InOnly service interface, and a route from the proxy to a JMS endpoint, calling hashCode() on the proxy throws an exception, either immediately or after a number of retries, depending on the route configuration. See the attached test case for different scenarios. The reason is that hashCode() is forwarded by the CamelInvocationHandler to the remote endpoint, which does not make sense in this case. diff --git a/camel-core/src/main/java/org/apache/camel/component/bean/AbstractCamelInvocationHandler.java b/camel-core/src/main/java/org/apache/camel/component/bean/AbstractCamelInvocationHandler.java index 953d60e..21e407b 100644 --- a/camel-core/src/main/java/org/apache/camel/component/bean/AbstractCamelInvocationHandler.java +++ b/camel-core/src/main/java/org/apache/camel/component/bean/AbstractCamelInvocationHandler.java @@ -19,6 +19,9 @@ package org.apache.camel.component.bean; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; @@ -41,10 +44,16 @@ import org.slf4j.LoggerFactory; public abstract class AbstractCamelInvocationHandler implements InvocationHandler { private static final transient Logger LOG = LoggerFactory.getLogger(CamelInvocationHandler.class); + private static final List<Method> EXCLUDED_METHODS = new ArrayList<Method>(); private static ExecutorService executorService; protected final Endpoint endpoint; protected final Producer producer; + static { + // exclude all java.lang.Object methods as we dont want to invoke them + EXCLUDED_METHODS.addAll(Arrays.asList(Object.class.getMethods())); + } + public AbstractCamelInvocationHandler(Endpoint endpoint, Producer producer) { this.endpoint = endpoint; this.producer = producer; @@ -67,7 +76,26 @@ public abstract class AbstractCamelInvocationHandler implements InvocationHandle } } - protected Object invokeWithbody(final Method method, Object body, final ExchangePattern pattern) throws InterruptedException, Throwable { + @Override + public final Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable { + if (isValidMethod(method)) { + return doInvokeProxy(proxy, method, args); + } else { + // invalid method then invoke methods on this instead + if ("toString".equals(method.getName())) { + return this.toString(); + } else if ("hashCode".equals(method.getName())) { + return this.hashCode(); + } else if ("equals".equals(method.getName())) { + return Boolean.FALSE; + } + return null; + } + } + + public abstract Object doInvokeProxy(final Object proxy, final Method method, final Object[] args) throws Throwable; + + protected Object invokeWithBody(final Method method, Object body, final ExchangePattern pattern) throws Throwable { final Exchange exchange = new DefaultExchange(endpoint, pattern); exchange.getIn().setBody(body); @@ -214,4 +242,15 @@ public abstract class AbstractCamelInvocationHandler implements InvocationHandle return null; } + protected boolean isValidMethod(Method method) { + // must not be in the excluded list + for (Method excluded : EXCLUDED_METHODS) { + if (ObjectHelper.isOverridingMethod(excluded, method)) { + // the method is overriding an excluded method so its not valid + return false; + } + } + return true; + } + } diff --git a/camel-core/src/main/java/org/apache/camel/component/bean/CamelInvocationHandler.java b/camel-core/src/main/java/org/apache/camel/component/bean/CamelInvocationHandler.java index b78dcd3..55b993b 100644 --- a/camel-core/src/main/java/org/apache/camel/component/bean/CamelInvocationHandler.java +++ b/camel-core/src/main/java/org/apache/camel/component/bean/CamelInvocationHandler.java @@ -37,11 +37,12 @@ public class CamelInvocationHandler extends AbstractCamelInvocationHandler imple this.methodInfoCache = methodInfoCache; } - public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable { + @Override + public Object doInvokeProxy(Object proxy, Method method, Object[] args) throws Throwable { BeanInvocation invocation = new BeanInvocation(method, args); MethodInfo methodInfo = methodInfoCache.getMethodInfo(method); final ExchangePattern pattern = methodInfo != null ? methodInfo.getPattern() : ExchangePattern.InOut; - return invokeWithbody(method, invocation, pattern); + return invokeWithBody(method, invocation, pattern); } } diff --git a/camel-core/src/main/java/org/apache/camel/component/bean/PojoMessageInvocationHandler.java b/camel-core/src/main/java/org/apache/camel/component/bean/PojoMessageInvocationHandler.java index 906ad71..b97865a 100644 --- a/camel-core/src/main/java/org/apache/camel/component/bean/PojoMessageInvocationHandler.java +++ b/camel-core/src/main/java/org/apache/camel/component/bean/PojoMessageInvocationHandler.java @@ -24,17 +24,19 @@ import org.apache.camel.Producer; import org.apache.camel.RuntimeCamelException; /** - * Special InvocationHandler for methods that have only one parameter. This + * Special {@link java.lang.reflect.InvocationHandler} for methods that have only one parameter. This * parameter is directly sent to as the body of the message. The idea is to use * that as a very open message format especially when combined with e.g. JAXB * serialization. */ public class PojoMessageInvocationHandler extends AbstractCamelInvocationHandler { + public PojoMessageInvocationHandler(Endpoint endpoint, Producer producer) { super(endpoint, producer); } - public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable { + @Override + public Object doInvokeProxy(Object proxy, Method method, Object[] args) throws Throwable { int argsLength = (args == null) ? 0 : args.length; if (argsLength != 1) { throw new RuntimeCamelException(String.format("Error creating proxy for %s.%s Number of arguments must be 1 but is %d", @@ -42,7 +44,7 @@ public class PojoMessageInvocationHandler extends AbstractCamelInvocationHandler method.getName(), argsLength)); } final ExchangePattern pattern = method.getReturnType() != Void.TYPE ? ExchangePattern.InOut : ExchangePattern.InOnly; - return invokeWithbody(method, args[0], pattern); + return invokeWithBody(method, args[0], pattern); } }
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-5571_0e87b84f.diff
bugs-dot-jar_data_CAMEL-9673_7944093f
--- BugID: CAMEL-9673 Summary: doTry .. doFinally should run the finally block for fault messages also Description: If a message has fault flag, then a doFinally block is only executed the first processor. We should ensure the entire block is processed like we do if an exception was thrown. The same kind of logic should apply for fault. diff --git a/camel-core/src/main/java/org/apache/camel/processor/FinallyProcessor.java b/camel-core/src/main/java/org/apache/camel/processor/FinallyProcessor.java index b04e172..4fe21a6 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/FinallyProcessor.java +++ b/camel-core/src/main/java/org/apache/camel/processor/FinallyProcessor.java @@ -41,37 +41,30 @@ public class FinallyProcessor extends DelegateAsyncProcessor implements Traceabl @Override public boolean process(final Exchange exchange, final AsyncCallback callback) { - // clear exception so finally block can be executed - final Exception e = exchange.getException(); + // clear exception and fault so finally block can be executed + final boolean fault; + if (exchange.hasOut()) { + fault = exchange.getOut().isFault(); + exchange.getOut().setFault(false); + } else { + fault = exchange.getIn().isFault(); + exchange.getIn().setFault(false); + } + + final Exception exception = exchange.getException(); exchange.setException(null); // but store the caught exception as a property - if (e != null) { - exchange.setProperty(Exchange.EXCEPTION_CAUGHT, e); + if (exception != null) { + exchange.setProperty(Exchange.EXCEPTION_CAUGHT, exception); } + // store the last to endpoint as the failure endpoint if (exchange.getProperty(Exchange.FAILURE_ENDPOINT) == null) { exchange.setProperty(Exchange.FAILURE_ENDPOINT, exchange.getProperty(Exchange.TO_ENDPOINT)); } - boolean sync = processor.process(exchange, new AsyncCallback() { - public void done(boolean doneSync) { - if (e == null) { - exchange.removeProperty(Exchange.FAILURE_ENDPOINT); - } else { - // set exception back on exchange - exchange.setException(e); - exchange.setProperty(Exchange.EXCEPTION_CAUGHT, e); - } - - if (!doneSync) { - // signal callback to continue routing async - ExchangeHelper.prepareOutToIn(exchange); - LOG.trace("Processing complete for exchangeId: {} >>> {}", exchange.getExchangeId(), exchange); - } - callback.done(doneSync); - } - }); - return sync; + // continue processing + return processor.process(exchange, new FinallyAsyncCallback(exchange, callback, exception, fault)); } @Override @@ -90,4 +83,55 @@ public class FinallyProcessor extends DelegateAsyncProcessor implements Traceabl public void setId(String id) { this.id = id; } + + private static final class FinallyAsyncCallback implements AsyncCallback { + + private final Exchange exchange; + private final AsyncCallback callback; + private final Exception exception; + private final boolean fault; + + public FinallyAsyncCallback(Exchange exchange, AsyncCallback callback, Exception exception, boolean fault) { + this.exchange = exchange; + this.callback = callback; + this.exception = exception; + this.fault = fault; + } + + @Override + public void done(boolean doneSync) { + try { + if (exception == null) { + exchange.removeProperty(Exchange.FAILURE_ENDPOINT); + } else { + // set exception back on exchange + exchange.setException(exception); + exchange.setProperty(Exchange.EXCEPTION_CAUGHT, exception); + } + // set fault flag back + if (fault) { + if (exchange.hasOut()) { + exchange.getOut().setFault(true); + } else { + exchange.getIn().setFault(true); + } + } + + if (!doneSync) { + // signal callback to continue routing async + ExchangeHelper.prepareOutToIn(exchange); + LOG.trace("Processing complete for exchangeId: {} >>> {}", exchange.getExchangeId(), exchange); + } + } finally { + // callback must always be called + callback.done(doneSync); + } + } + + @Override + public String toString() { + return "FinallyAsyncCallback"; + } + } + }
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-9673_7944093f.diff
bugs-dot-jar_data_CAMEL-7973_799b45df
--- BugID: CAMEL-7973 Summary: CircuitBreakerLoadBalancer fails on async processors Description: "The CircuitBreakerLoadBalancer works fine on direct synchronous processor, but it seems to not behave as expected in case of async processor.\n\nTo reproduce the error, it's enough to add a .threads(1) before the mock processor in the CircuitBreakerLoadBalancerTest routeBuilder configuration.\n\nThis misbehaviour seems to be related to the use of the AsyncProcessorConverterHelper to force any processor to behave like asynchronous. \n\nI'm going to propose a patch with the failing test and a proposal of solution.\n\nEDIT:\n\nthe patch contains the fix also to other unexpected behaviour of the CircuitBreaker.\n\nThe second problem addressed is that, after the opening of the circuit, the RejectedExecutionException raised by the circuit breaker is set in the Exchange, but it doesn't return. This cause the processor will receive the Exchange even if the circuit is open. In this case also, if the CircuitBreaker is instructed to react only to specific Exception, it will close the circuit after the following request, because the raised exception would be a RejectedExecutionException instead of the one specified in the configuration." diff --git a/camel-core/src/main/java/org/apache/camel/processor/loadbalancer/CircuitBreakerLoadBalancer.java b/camel-core/src/main/java/org/apache/camel/processor/loadbalancer/CircuitBreakerLoadBalancer.java index b8e23b4..3e84e6e 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/loadbalancer/CircuitBreakerLoadBalancer.java +++ b/camel-core/src/main/java/org/apache/camel/processor/loadbalancer/CircuitBreakerLoadBalancer.java @@ -107,6 +107,13 @@ public class CircuitBreakerLoadBalancer extends LoadBalancerSupport implements T if (failures.get() >= threshold && System.currentTimeMillis() - lastFailure < halfOpenAfter) { exchange.setException(new RejectedExecutionException("CircuitBreaker Open: failures: " + failures + ", lastFailure: " + lastFailure)); + /* + * If the circuit opens, we have to prevent the execution of any processor. + * The failures count can be set to 0. + */ + failures.set(0); + callback.done(true); + return true; } Processor processor = getProcessors().get(0); if (processor == null) { @@ -114,18 +121,20 @@ public class CircuitBreakerLoadBalancer extends LoadBalancerSupport implements T } AsyncProcessor albp = AsyncProcessorConverterHelper.convert(processor); - boolean sync = albp.process(exchange, callback); - - boolean failed = hasFailed(exchange); - - if (!failed) { - failures.set(0); + // Added a callback for processing the exchange in the callback + boolean sync = albp.process(exchange, new CircuitBreakerCallback(exchange, callback)); + + // We need to check the exception here as albp is use sync call + if (sync) { + boolean failed = hasFailed(exchange); + if (!failed) { + failures.set(0); + } else { + failures.incrementAndGet(); + lastFailure = System.currentTimeMillis(); + } } else { - failures.incrementAndGet(); - lastFailure = System.currentTimeMillis(); - } - - if (!sync) { + // CircuitBreakerCallback can take care of failure check of the exchange log.trace("Processing exchangeId: {} is continued being processed asynchronously", exchange.getExchangeId()); return false; } @@ -142,4 +151,28 @@ public class CircuitBreakerLoadBalancer extends LoadBalancerSupport implements T public String getTraceLabel() { return "circuitbreaker"; } + + class CircuitBreakerCallback implements AsyncCallback { + private final AsyncCallback callback; + private final Exchange exchange; + CircuitBreakerCallback(Exchange exchange, AsyncCallback callback) { + this.callback = callback; + this.exchange = exchange; + } + + @Override + public void done(boolean doneSync) { + if (!doneSync) { + boolean failed = hasFailed(exchange); + if (!failed) { + failures.set(0); + } else { + failures.incrementAndGet(); + lastFailure = System.currentTimeMillis(); + } + } + callback.done(doneSync); + } + + } }
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-7973_799b45df.diff
bugs-dot-jar_data_CAMEL-8137_53b4e90c
--- BugID: CAMEL-8137 Summary: Simple language does not resolve overloaded method calls Description: |- I am having an issue with the Simple language. I have a property named {{myFile}} with a value of a {{java.nio.file.Path}} object. When I try to use the following expression {noformat} ${property.file.getFileName} {noformat} in order to invoke the getFileName() method I get an exception saying: {noformat} Ambiguous method invocations possible: [public sun.nio.fs.UnixPath.getFileName(), public abstract java.nio.file.Path java.nio.file.Path.getFileName()] {noformat} I am able to use SpEL if I do {noformat} #{properties[myFile].getFileName()} {noformat} It would be nice if Simple supported this as well so I wouldn't have to go through hoops in order to use SpEL since I can't use SpEL to specify parameters in a uri. diff --git a/camel-core/src/main/java/org/apache/camel/component/bean/BeanInfo.java b/camel-core/src/main/java/org/apache/camel/component/bean/BeanInfo.java index 1c19945..fb9c533 100644 --- a/camel-core/src/main/java/org/apache/camel/component/bean/BeanInfo.java +++ b/camel-core/src/main/java/org/apache/camel/component/bean/BeanInfo.java @@ -311,22 +311,27 @@ public class BeanInfo { methods.addAll(extraMethods); } - // it may have duplicate methods already, even from declared or from interfaces + declared Set<Method> overrides = new HashSet<Method>(); - for (Method source : methods) { - for (Method target : methods) { - // skip ourselves - if (ObjectHelper.isOverridingMethod(source, target, true)) { - continue; - } - // skip duplicates which may be assign compatible (favor keep first added method when duplicate) - if (ObjectHelper.isOverridingMethod(source, target, false)) { - overrides.add(target); + + // do not remove duplicates form class from the Java itself as they have some "duplicates" we need + boolean javaClass = clazz.getName().startsWith("java.") || clazz.getName().startsWith("javax."); + if (!javaClass) { + // it may have duplicate methods already, even from declared or from interfaces + declared + for (Method source : methods) { + for (Method target : methods) { + // skip ourselves + if (ObjectHelper.isOverridingMethod(source, target, true)) { + continue; + } + // skip duplicates which may be assign compatible (favor keep first added method when duplicate) + if (ObjectHelper.isOverridingMethod(source, target, false)) { + overrides.add(target); + } } } + methods.removeAll(overrides); + overrides.clear(); } - methods.removeAll(overrides); - overrides.clear(); // if we are a public class, then add non duplicate interface classes also if (Modifier.isPublic(clazz.getModifiers())) {
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-8137_53b4e90c.diff
bugs-dot-jar_data_CAMEL-4370_7345fefc
--- BugID: CAMEL-4370 Summary: It's hardly possible to use all expression of the Simple language to create file names in the file component Description: |- Sometimes it can be necessary to use custom headers to create a file name. For example, I declare my file endpoint in the following manner: {code} <route id="fileReader"> <from uri="file://rootFolder?move=.backup&amp;moveFailed=.error/${header.CustomHeader}" /> <to uri="file://out"/> </route> {code} The header "CustomHeader" cannot be read because of the following snippets of code in the org.apache.camel.component.file.GenericFile {code} /** * Bind this GenericFile to an Exchange */ public void bindToExchange(Exchange exchange) { exchange.setProperty(FileComponent.FILE_EXCHANGE_FILE, this); GenericFileMessage<T> in = new GenericFileMessage<T>(this); exchange.setIn(in); populateHeaders(in); } /** * Populates the {@link GenericFileMessage} relevant headers * * @param message the message to populate with headers */ public void populateHeaders(GenericFileMessage<T> message) { if (message != null) { message.setHeader(Exchange.FILE_NAME_ONLY, getFileNameOnly()); message.setHeader(Exchange.FILE_NAME, getFileName()); message.setHeader("CamelFileAbsolute", isAbsolute()); message.setHeader("CamelFileAbsolutePath", getAbsoluteFilePath()); if (isAbsolute()) { message.setHeader(Exchange.FILE_PATH, getAbsoluteFilePath()); } else { // we must normalize path according to protocol if we build our own paths String path = normalizePathToProtocol(getEndpointPath() + File.separator + getRelativeFilePath()); message.setHeader(Exchange.FILE_PATH, path); } message.setHeader("CamelFileRelativePath", getRelativeFilePath()); message.setHeader(Exchange.FILE_PARENT, getParent()); if (getFileLength() >= 0) { message.setHeader("CamelFileLength", getFileLength()); } if (getLastModified() > 0) { message.setHeader(Exchange.FILE_LAST_MODIFIED, new Date(getLastModified())); } } } {code} As you can see a new "in" message is created and not all the headers from the original message are copied to it. diff --git a/camel-core/src/main/java/org/apache/camel/component/file/GenericFile.java b/camel-core/src/main/java/org/apache/camel/component/file/GenericFile.java index 69b15d5..ead41ea 100644 --- a/camel-core/src/main/java/org/apache/camel/component/file/GenericFile.java +++ b/camel-core/src/main/java/org/apache/camel/component/file/GenericFile.java @@ -18,6 +18,7 @@ package org.apache.camel.component.file; import java.io.File; import java.util.Date; +import java.util.Map; import org.apache.camel.Exchange; import org.apache.camel.util.FileUtil; @@ -93,10 +94,25 @@ public class GenericFile<T> { * Bind this GenericFile to an Exchange */ public void bindToExchange(Exchange exchange) { + Map<String, Object> headers; + exchange.setProperty(FileComponent.FILE_EXCHANGE_FILE, this); - GenericFileMessage<T> in = new GenericFileMessage<T>(this); - exchange.setIn(in); - populateHeaders(in); + GenericFileMessage<T> msg = new GenericFileMessage<T>(this); + if (exchange.hasOut()) { + headers = exchange.getOut().hasHeaders() ? exchange.getOut().getHeaders() : null; + exchange.setOut(msg); + } else { + headers = exchange.getIn().hasHeaders() ? exchange.getIn().getHeaders() : null; + exchange.setIn(msg); + } + + // preserve any existing (non file) headers, before we re-populate headers + if (headers != null) { + msg.setHeaders(headers); + // remove any file related headers, as we will re-populate file headers + msg.removeHeaders("CamelFile*"); + } + populateHeaders(msg); } /**
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-4370_7345fefc.diff
bugs-dot-jar_data_CAMEL-7213_336663c9
--- BugID: CAMEL-7213 Summary: NIOConverter need to call flip() when we put something into the buffer Description: When we create a ByteBuffer, we need to make sure it is ready to be read. diff --git a/camel-core/src/main/java/org/apache/camel/converter/NIOConverter.java b/camel-core/src/main/java/org/apache/camel/converter/NIOConverter.java index 0bf08ac..41273b6 100644 --- a/camel-core/src/main/java/org/apache/camel/converter/NIOConverter.java +++ b/camel-core/src/main/java/org/apache/camel/converter/NIOConverter.java @@ -107,6 +107,7 @@ public final class NIOConverter { public static ByteBuffer toByteBuffer(Short value) { ByteBuffer buf = ByteBuffer.allocate(2); buf.putShort(value); + buf.flip(); return buf; } @@ -114,6 +115,7 @@ public final class NIOConverter { public static ByteBuffer toByteBuffer(Integer value) { ByteBuffer buf = ByteBuffer.allocate(4); buf.putInt(value); + buf.flip(); return buf; } @@ -121,6 +123,7 @@ public final class NIOConverter { public static ByteBuffer toByteBuffer(Long value) { ByteBuffer buf = ByteBuffer.allocate(8); buf.putLong(value); + buf.flip(); return buf; } @@ -128,6 +131,7 @@ public final class NIOConverter { public static ByteBuffer toByteBuffer(Float value) { ByteBuffer buf = ByteBuffer.allocate(4); buf.putFloat(value); + buf.flip(); return buf; } @@ -135,6 +139,7 @@ public final class NIOConverter { public static ByteBuffer toByteBuffer(Double value) { ByteBuffer buf = ByteBuffer.allocate(8); buf.putDouble(value); + buf.flip(); return buf; }
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-7213_336663c9.diff
bugs-dot-jar_data_CAMEL-3757_c1b2f2f8
--- BugID: CAMEL-3757 Summary: Auto mock endpoints should strip parameters to avoid confusing when accessing the mocked endpoint Description: |- If you use mocking existing endpoints, which is detailed here http://camel.apache.org/mock.html We should stip parameters of the mocked endpoint, eg {{file:xxxx?noop=true}}. eg so the mocked endpoint would be {{mock:file:xxxx}} without any of the parameters. Otherwise the mock endpoint expects those parameters is part of the mock endpoint and will fail creating the mock endpoint. diff --git a/camel-core/src/main/java/org/apache/camel/builder/AdviceWithRouteBuilder.java b/camel-core/src/main/java/org/apache/camel/builder/AdviceWithRouteBuilder.java index cf6cf02..fb472a7 100644 --- a/camel-core/src/main/java/org/apache/camel/builder/AdviceWithRouteBuilder.java +++ b/camel-core/src/main/java/org/apache/camel/builder/AdviceWithRouteBuilder.java @@ -68,7 +68,6 @@ public abstract class AdviceWithRouteBuilder extends RouteBuilder { * @throws Exception can be thrown if error occurred */ public void mockEndpoints() throws Exception { - getContext().removeEndpoints("*"); getContext().addRegisterEndpointCallback(new InterceptSendToMockEndpointStrategy(null)); } @@ -80,7 +79,6 @@ public abstract class AdviceWithRouteBuilder extends RouteBuilder { * @see org.apache.camel.util.EndpointHelper#matchEndpoint(String, String) */ public void mockEndpoints(String pattern) throws Exception { - getContext().removeEndpoints(pattern); getContext().addRegisterEndpointCallback(new InterceptSendToMockEndpointStrategy(pattern)); } @@ -95,7 +93,6 @@ public abstract class AdviceWithRouteBuilder extends RouteBuilder { */ public AdviceWithBuilder weaveById(String pattern) { ObjectHelper.notNull(originalRoute, "originalRoute", this); - return new AdviceWithBuilder(this, pattern, null); } @@ -110,7 +107,6 @@ public abstract class AdviceWithRouteBuilder extends RouteBuilder { */ public AdviceWithBuilder weaveByToString(String pattern) { ObjectHelper.notNull(originalRoute, "originalRoute", this); - return new AdviceWithBuilder(this, null, pattern); } diff --git a/camel-core/src/main/java/org/apache/camel/impl/InterceptSendToEndpoint.java b/camel-core/src/main/java/org/apache/camel/impl/InterceptSendToEndpoint.java index bd97de1..80c5b11 100644 --- a/camel-core/src/main/java/org/apache/camel/impl/InterceptSendToEndpoint.java +++ b/camel-core/src/main/java/org/apache/camel/impl/InterceptSendToEndpoint.java @@ -114,6 +114,7 @@ public class InterceptSendToEndpoint implements Endpoint { if (LOG.isDebugEnabled()) { LOG.debug("Sending to endpoint: " + getEndpointUri() + " is intercepted and detoured to: " + detour + " for exchange: " + exchange); } + LOG.info("Sending to endpoint: " + getEndpointUri() + " is intercepted and detoured to: " + detour + " for exchange: " + exchange); // add header with the real endpoint uri exchange.getIn().setHeader(Exchange.INTERCEPTED_ENDPOINT, delegate.getEndpointUri()); diff --git a/camel-core/src/main/java/org/apache/camel/impl/InterceptSendToMockEndpointStrategy.java b/camel-core/src/main/java/org/apache/camel/impl/InterceptSendToMockEndpointStrategy.java index e0b168c..e1d52d1 100644 --- a/camel-core/src/main/java/org/apache/camel/impl/InterceptSendToMockEndpointStrategy.java +++ b/camel-core/src/main/java/org/apache/camel/impl/InterceptSendToMockEndpointStrategy.java @@ -21,6 +21,7 @@ import org.apache.camel.Processor; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.spi.EndpointStrategy; import org.apache.camel.util.EndpointHelper; +import org.apache.camel.util.ObjectHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -73,6 +74,10 @@ public class InterceptSendToMockEndpointStrategy implements EndpointStrategy { // create mock endpoint which we will use as interceptor // replace :// from scheme to make it easy to lookup the mock endpoint without having double :// in uri String key = "mock:" + endpoint.getEndpointKey().replaceFirst("://", ":"); + // strip off parameters as well + if (key.contains("?")) { + key = ObjectHelper.before(key, "?"); + } LOG.info("Adviced endpoint [" + uri + "] with mock endpoint [" + key + "]"); MockEndpoint mock = endpoint.getCamelContext().getEndpoint(key, MockEndpoint.class);
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-3757_c1b2f2f8.diff
bugs-dot-jar_data_CAMEL-5261_55c2e2d8
--- BugID: CAMEL-5261 Summary: SEDA/VM requires completely same URI on producer and consumer side when consumer route is adviced Description: |- The producer side and consumer side of the SEDA (and VM) component seems to require the completely same URI to be able to communicate. Completely same meaning that all URI options must be the same on both sides. The strange thing is that this only is required when I have adviced the consumer route. 2.9.0 does not have this problem. Attached a unit test - the producerWithDifferentUri will fail on 2.9.1 and 2.9.2. If the advice is removed it will not. diff --git a/camel-core/src/main/java/org/apache/camel/component/seda/SedaComponent.java b/camel-core/src/main/java/org/apache/camel/component/seda/SedaComponent.java index ed0f066..23c70bd 100644 --- a/camel-core/src/main/java/org/apache/camel/component/seda/SedaComponent.java +++ b/camel-core/src/main/java/org/apache/camel/component/seda/SedaComponent.java @@ -53,7 +53,7 @@ public class SedaComponent extends DefaultComponent { return defaultConcurrentConsumers; } - public synchronized BlockingQueue<Exchange> createQueue(String uri, Map<String, Object> parameters) { + public synchronized BlockingQueue<Exchange> getOrCreateQueue(String uri, Integer size) { String key = getQueueKey(uri); QueueReference ref = getQueues().get(key); @@ -65,7 +65,6 @@ public class SedaComponent extends DefaultComponent { // create queue BlockingQueue<Exchange> queue; - Integer size = getAndRemoveParameter(parameters, "size", Integer.class); if (size != null && size > 0) { queue = new LinkedBlockingQueue<Exchange>(size); } else { @@ -96,7 +95,8 @@ public class SedaComponent extends DefaultComponent { throw new IllegalArgumentException("The limitConcurrentConsumers flag in set to true. ConcurrentConsumers cannot be set at a value greater than " + maxConcurrentConsumers + " was " + consumers); } - SedaEndpoint answer = new SedaEndpoint(uri, this, createQueue(uri, parameters), consumers); + Integer size = getAndRemoveParameter(parameters, "size", Integer.class); + SedaEndpoint answer = new SedaEndpoint(uri, this, getOrCreateQueue(uri, size), consumers); answer.configureProperties(parameters); return answer; } diff --git a/camel-core/src/main/java/org/apache/camel/component/seda/SedaEndpoint.java b/camel-core/src/main/java/org/apache/camel/component/seda/SedaEndpoint.java index 2095a93..5b2d872 100644 --- a/camel-core/src/main/java/org/apache/camel/component/seda/SedaEndpoint.java +++ b/camel-core/src/main/java/org/apache/camel/component/seda/SedaEndpoint.java @@ -94,15 +94,27 @@ public class SedaEndpoint extends DefaultEndpoint implements BrowsableEndpoint, public synchronized BlockingQueue<Exchange> getQueue() { if (queue == null) { - if (size > 0) { - queue = new LinkedBlockingQueue<Exchange>(size); + // prefer to lookup queue from component, so if this endpoint is re-created or re-started + // then the existing queue from the component can be used, so new producers and consumers + // can use the already existing queue referenced from the component + if (getComponent() != null) { + queue = getComponent().getOrCreateQueue(getEndpointUri(), getSize()); } else { - queue = new LinkedBlockingQueue<Exchange>(); + // fallback and create queue (as this endpoint has no component) + queue = createQueue(); } } return queue; } + protected BlockingQueue<Exchange> createQueue() { + if (size > 0) { + return new LinkedBlockingQueue<Exchange>(size); + } else { + return new LinkedBlockingQueue<Exchange>(); + } + } + protected synchronized MulticastProcessor getConsumerMulticastProcessor() throws Exception { if (!multicastStarted && consumerMulticastProcessor != null) { // only start it on-demand to avoid starting it during stopping @@ -363,6 +375,10 @@ public class SedaEndpoint extends DefaultEndpoint implements BrowsableEndpoint, getCamelContext().getExecutorServiceManager().shutdownNow(multicastExecutor); multicastExecutor = null; } + + // clear queue, as we are shutdown, so if re-created then the queue must be updated + queue = null; + super.doShutdown(); } } diff --git a/camel-core/src/main/java/org/apache/camel/component/seda/SedaProducer.java b/camel-core/src/main/java/org/apache/camel/component/seda/SedaProducer.java index 1067042..d39e39f 100644 --- a/camel-core/src/main/java/org/apache/camel/component/seda/SedaProducer.java +++ b/camel-core/src/main/java/org/apache/camel/component/seda/SedaProducer.java @@ -27,7 +27,6 @@ import org.apache.camel.WaitForTaskToComplete; import org.apache.camel.impl.DefaultAsyncProducer; import org.apache.camel.support.SynchronizationAdapter; import org.apache.camel.util.ExchangeHelper; -import org.apache.camel.util.URISupport; /** * @version
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-5261_55c2e2d8.diff
bugs-dot-jar_data_CAMEL-5570_a57830ed
--- BugID: CAMEL-5570 Summary: maximumRedeliveries is inherited for other exceptions thrown while redelivering with maximumRedeliveries(-1) Description: |- Given a route: {code} from("direct:source") .onException(FirstException.class) .handled(true) .maximumRedeliveries(-1) .end() .onException(SecondException.class) .handled(true) .to("direct:error") .end() .to("direct:destination"); {code} If the consumer of direct:destination throws a FirstException, the message will be redelivered. Now if a SecondException is thrown while redelivering the message to direct:destination, it does NOT go to direct:error, as you would expect, but is redelivered again; using the same RedeliveryPolicy as for FirstException. I have attached a test that illustrates this. In OnExceptionDefinition.createRedeliveryPolicy, maximumRedeliveries is set to 0 if the OnExceptionDefinition has outputs and the parent RedeliveryPolicy has explicitly set maximumRedeliveries > 0. The latter check fails when maximumRedeliveries is -1 (infinite retries), and the parent RedeliveryPolicy is returned. I have attached a patch that ensures that we don't inherit the parent maximumRedeliveries even if it is set to -1. diff --git a/camel-core/src/main/java/org/apache/camel/model/OnExceptionDefinition.java b/camel-core/src/main/java/org/apache/camel/model/OnExceptionDefinition.java index 50a41a3..f8e42b9 100644 --- a/camel-core/src/main/java/org/apache/camel/model/OnExceptionDefinition.java +++ b/camel-core/src/main/java/org/apache/camel/model/OnExceptionDefinition.java @@ -144,7 +144,7 @@ public class OnExceptionDefinition extends ProcessorDefinition<OnExceptionDefini return CamelContextHelper.mandatoryLookup(context, redeliveryPolicyRef, RedeliveryPolicy.class); } else if (redeliveryPolicy != null) { return redeliveryPolicy.createRedeliveryPolicy(context, parentPolicy); - } else if (!outputs.isEmpty() && parentPolicy.getMaximumRedeliveries() > 0) { + } else if (!outputs.isEmpty() && parentPolicy.getMaximumRedeliveries() != 0) { // if we have outputs, then do not inherit parent maximumRedeliveries // as you would have to explicit configure maximumRedeliveries on this onException to use it // this is the behavior Camel has always had
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-5570_a57830ed.diff
bugs-dot-jar_data_CAMEL-7055_15e1077d
--- BugID: CAMEL-7055 Summary: NullPointerException at FileInputStreamCache.<init>(FileInputStreamCache.java:52) in connection with DataFormat.marshal Description: "Stack Trace:\n{code}\nCaused by: java.lang.NullPointerException\n\tat org.apache.camel.converter.stream.FileInputStreamCache.<init>(FileInputStreamCache.java:52)\n\tat org.apache.camel.converter.stream.CachedOutputStream.newStreamCache(CachedOutputStream.java:199)\n\tat org.apache.camel.processor.MarshalProcessor.process(MarshalProcessor.java:79)\n{code}\n\nError occurs, if streamCache is true and the stream is put into the file system because the spool threashold is reached. \n\nThe following is happening:\nThe Marshall Processor handels over to the DataFromat.marshal method a CachedOutputStream instance. In the marschal method data are written into the output stream, when the spool threshold is reached the data are streamed into the file system. Finally the output stream is closed and the CachedOutputStream instance deletes the cached file during closing. The next processor tries to read the FileInputStreamCache and gets the NullPointerException.\n\nCurrently this problem can occur in the following DataFormat classes (because they close the stream, which is actually correct):\n\nGzipDataFormat\nCryptoDataFormat\nPGPDataFormat\nSerializationDataFormat\nXMLSecurityDataFormat\nZipDataFormat\n\nMy proposal is not to delete the cached file during closing the output stream. The cached file shall only be closed on the onCompletion event of the route. See attached patch.\n\n\n" diff --git a/camel-core/src/main/java/org/apache/camel/converter/stream/CachedOutputStream.java b/camel-core/src/main/java/org/apache/camel/converter/stream/CachedOutputStream.java index c5f3b49..0e3540c 100644 --- a/camel-core/src/main/java/org/apache/camel/converter/stream/CachedOutputStream.java +++ b/camel-core/src/main/java/org/apache/camel/converter/stream/CachedOutputStream.java @@ -71,31 +71,36 @@ public class CachedOutputStream extends OutputStream { this(exchange, true); } - public CachedOutputStream(Exchange exchange, boolean closedOnCompletion) { + public CachedOutputStream(Exchange exchange, final boolean closedOnCompletion) { this.strategy = exchange.getContext().getStreamCachingStrategy(); currentStream = new CachedByteArrayOutputStream(strategy.getBufferSize()); - if (closedOnCompletion) { - // add on completion so we can cleanup after the exchange is done such as deleting temporary files - exchange.addOnCompletion(new SynchronizationAdapter() { - @Override - public void onDone(Exchange exchange) { - try { - if (fileInputStreamCache != null) { - fileInputStreamCache.close(); - } + // add on completion so we can cleanup after the exchange is done such as deleting temporary files + exchange.addOnCompletion(new SynchronizationAdapter() { + @Override + public void onDone(Exchange exchange) { + try { + if (fileInputStreamCache != null) { + fileInputStreamCache.close(); + } + if (closedOnCompletion) { close(); - } catch (Exception e) { - LOG.warn("Error deleting temporary cache file: " + tempFile, e); } + } catch (Exception e) { + LOG.warn("Error closing streams. This exception will be ignored.", e); } - - @Override - public String toString() { - return "OnCompletion[CachedOutputStream]"; + try { + cleanUpTempFile(); + } catch (Exception e) { + LOG.warn("Error deleting temporary cache file: " + tempFile + ". This exception will be ignored.", e); } - }); - } + } + + @Override + public String toString() { + return "OnCompletion[CachedOutputStream]"; + } + }); } public void flush() throws IOException { @@ -104,7 +109,6 @@ public class CachedOutputStream extends OutputStream { public void close() throws IOException { currentStream.close(); - cleanUpTempFile(); } public boolean equals(Object obj) {
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-7055_15e1077d.diff
bugs-dot-jar_data_CAMEL-3394_18e1a142
--- BugID: CAMEL-3394 Summary: Splitter and Multicast EIP marks exchange as exhausted to early if exception was thrown from an evaluation Description: |- See nabble http://camel.465427.n5.nabble.com/Cannot-handle-Exception-thrown-from-Splitter-Expression-tp3286043p3286043.html diff --git a/camel-core/src/main/java/org/apache/camel/processor/MulticastProcessor.java b/camel-core/src/main/java/org/apache/camel/processor/MulticastProcessor.java index fcb8bfc..bdee56f 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/MulticastProcessor.java +++ b/camel-core/src/main/java/org/apache/camel/processor/MulticastProcessor.java @@ -174,10 +174,16 @@ public class MulticastProcessor extends ServiceSupport implements AsyncProcessor // multicast uses fine grained error handling on the output processors // so use try .. catch to cater for this + boolean exhaust = false; try { boolean sync = true; pairs = createProcessorExchangePairs(exchange); + + // after we have created the processors we consider the exchange as exhausted if an unhandled + // exception was thrown, (used in the catch block) + exhaust = true; + if (isParallelProcessing()) { // ensure an executor is set when running in parallel ObjectHelper.notNull(executorService, "executorService", this); @@ -194,14 +200,14 @@ public class MulticastProcessor extends ServiceSupport implements AsyncProcessor } catch (Throwable e) { exchange.setException(e); // and do the done work - doDone(exchange, null, callback, true); + doDone(exchange, null, callback, true, exhaust); return true; } // multicasting was processed successfully // and do the done work Exchange subExchange = result.get() != null ? result.get() : null; - doDone(exchange, subExchange, callback, true); + doDone(exchange, subExchange, callback, true, exhaust); return true; } @@ -455,7 +461,7 @@ public class MulticastProcessor extends ServiceSupport implements AsyncProcessor result.set(subExchange); } // and do the done work - doDone(original, subExchange, callback, false); + doDone(original, subExchange, callback, false, true); return; } @@ -465,7 +471,7 @@ public class MulticastProcessor extends ServiceSupport implements AsyncProcessor // wrap in exception to explain where it failed subExchange.setException(new CamelExchangeException("Sequential processing failed for number " + total, subExchange, e)); // and do the done work - doDone(original, subExchange, callback, false); + doDone(original, subExchange, callback, false, true); return; } @@ -501,7 +507,7 @@ public class MulticastProcessor extends ServiceSupport implements AsyncProcessor result.set(subExchange); } // and do the done work - doDone(original, subExchange, callback, false); + doDone(original, subExchange, callback, false, true); return; } @@ -511,7 +517,7 @@ public class MulticastProcessor extends ServiceSupport implements AsyncProcessor // wrap in exception to explain where it failed subExchange.setException(new CamelExchangeException("Sequential processing failed for number " + total, subExchange, e)); // and do the done work - doDone(original, subExchange, callback, false); + doDone(original, subExchange, callback, false, true); return; } @@ -520,7 +526,7 @@ public class MulticastProcessor extends ServiceSupport implements AsyncProcessor // do the done work subExchange = result.get() != null ? result.get() : null; - doDone(original, subExchange, callback, false); + doDone(original, subExchange, callback, false, true); } }); } finally { @@ -589,15 +595,16 @@ public class MulticastProcessor extends ServiceSupport implements AsyncProcessor * @param subExchange the current sub exchange, can be <tt>null</tt> for the synchronous part * @param callback the callback * @param doneSync the <tt>doneSync</tt> parameter to call on callback + * @param exhaust whether or not error handling is exhausted */ - protected void doDone(Exchange original, Exchange subExchange, AsyncCallback callback, boolean doneSync) { + protected void doDone(Exchange original, Exchange subExchange, AsyncCallback callback, boolean doneSync, boolean exhaust) { // cleanup any per exchange aggregation strategy removeAggregationStrategyFromExchange(original); if (original.getException() != null) { // multicast uses error handling on its output processors and they have tried to redeliver // so we shall signal back to the other error handlers that we are exhausted and they should not // also try to redeliver as we will then do that twice - original.setProperty(Exchange.REDELIVERY_EXHAUSTED, Boolean.TRUE); + original.setProperty(Exchange.REDELIVERY_EXHAUSTED, exhaust); } if (subExchange != null) { // and copy the current result to original so it will contain this exception
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-3394_18e1a142.diff
bugs-dot-jar_data_CAMEL-7271_a5a2f750
--- BugID: CAMEL-7271 Summary: AbstractListGroupedExchangeAggregationStrategy produces failed exchange if first received exchange fails Description: | If the first exchange received by a (concrete implementation of) AggregationStrategy contains an exception, then the result of the aggregation will also contain that exception, and so will not continue routing without error. This makes the first received exchange have an effect that subsequent exchanges do not have. The specific use case multicasts to GroupedExchangeAggregationStrategy. The MulticastProcessor.doDone function uses ExchangeHelper.copyResults to copy the aggregated result to the original exchange. The copyResults method copies the exception as well, thereby propagating the error. The attached unit test has 3 tests, testAFail, testBFail, and testAllGood. All three of these should pass, but testAFail does not. What is happening is that AbstractListAggregationStrategy is directly storing its values on and returning the first exchange: public Exchange aggregate(Exchange oldExchange, Exchange newExchange) { List<V> list; if (oldExchange == null) { list = getList(newExchange); } else { list = getList(oldExchange); } if (newExchange != null) { V value = getValue(newExchange); if (value != null) { list.add(value); } } return oldExchange != null ? oldExchange : newExchange; } The pre-CAMEL-5579 version of GroupedExchangeAggregationStrategy created a fresh exchange to store and return the aggregated exchanges: public Exchange aggregate(Exchange oldExchange, Exchange newExchange) { List<Exchange> list; Exchange answer = oldExchange; if (oldExchange == null) { answer = new DefaultExchange(newExchange); list = new ArrayList<Exchange>(); answer.setProperty(Exchange.GROUPED_EXCHANGE, list); } else { list = oldExchange.getProperty(Exchange.GROUPED_EXCHANGE, List.class); } if (newExchange != null) { list.add(newExchange); } return answer; } diff --git a/camel-core/src/main/java/org/apache/camel/processor/aggregate/GroupedExchangeAggregationStrategy.java b/camel-core/src/main/java/org/apache/camel/processor/aggregate/GroupedExchangeAggregationStrategy.java index 84b375d..2906270 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/aggregate/GroupedExchangeAggregationStrategy.java +++ b/camel-core/src/main/java/org/apache/camel/processor/aggregate/GroupedExchangeAggregationStrategy.java @@ -19,6 +19,7 @@ package org.apache.camel.processor.aggregate; import java.util.List; import org.apache.camel.Exchange; +import org.apache.camel.impl.DefaultExchange; /** * Aggregate all exchanges into a single combined Exchange holding all the aggregated exchanges @@ -29,7 +30,6 @@ import org.apache.camel.Exchange; public class GroupedExchangeAggregationStrategy extends AbstractListAggregationStrategy<Exchange> { @Override - public void onCompletion(Exchange exchange) { if (isStoreAsBodyOnCompletion()) { // lets be backwards compatible @@ -43,13 +43,12 @@ public class GroupedExchangeAggregationStrategy extends AbstractListAggregationS @Override public Exchange aggregate(Exchange oldExchange, Exchange newExchange) { - Exchange answer = super.aggregate(oldExchange, newExchange); if (oldExchange == null) { - // for the first time we must do a copy as the answer, so the outgoing - // exchange is not one of the grouped exchanges, as that causes a endless circular reference - answer = answer.copy(); + // for the first time we must create a new empty exchange as the holder, as the outgoing exchange + // must not be one of the grouped exchanges, as that causes a endless circular reference + oldExchange = new DefaultExchange(newExchange); } - return answer; + return super.aggregate(oldExchange, newExchange); } @Override
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-7271_a5a2f750.diff
bugs-dot-jar_data_CAMEL-5187_8cadc344
--- BugID: CAMEL-5187 Summary: JMX issues on WebSphere Description: "While setting up a Camel web application for WebSphere (7) I encountered two issues\n\n1. Documentation: the Camel JMX docs proposes the following settings for WebSphere:\n{code}\n<camel:jmxAgent id=\"agent\" createConnector=\"true\" mbeanObjectDomainName=\"org.yourname\" mbeanServerDefaultDomain=\"WebSphere\"/>\n{code}\n\nThis registers the beans with the PlatformMbeanServer instead of the WebSphere MBean server. The following setup works better:\n{code}\n<camel:jmxAgent id=\"agent\" createConnector=\"false\" mbeanObjectDomainName=\"org.yourname\" usePlatformMBeanServer=\"false\" mbeanServerDefaultDomain=\"WebSphere\"/>\n{code}\n\n2. For each Camel route, the same Tracer and DefaultErrorHandler MBeans are tried to be registered over and over again. Because WebSphere changes the ObjectNames on registration, \n\n{{server.isRegistered(name);}} in {{DefaultManagementAgent#registerMBeanWithServer}} always returns false, which causes the MBean to be re-registered, which again cause Exceptions, e.g.\n\n{code}\n14:35:48,198 [WebContainer : 4] [] WARN - DefaultManagementLifecycleStrategy.onErrorHandlerAdd(485) | Could not register error handler builder: ErrorHandlerBuilderRef[CamelDefaultErrorHandlerBuilder] as ErrorHandler MBean.\njavax.management.InstanceAlreadyExistsException: org.apache.camel:cell=wdf-lap-0319Node01Cell,name=\"DefaultErrorHandlerBuilder(ref:CamelDefaultErrorHandlerBuilder)\",context=wdf-lap-0319/camelContext,type=errorhandlers,node=wdf-lap-0319Node01,process=server1\n\tat com.sun.jmx.mbeanserver.Repository.addMBean(Repository.java:465)\n\tat com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.internal_addObject(DefaultMBeanServerInterceptor.java:1496)\n\tat com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerDynamicMBean(DefaultMBeanServerInterceptor.java:975)\n\tat com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerObject(DefaultMBeanServerInterceptor.java:929)\n\tat com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerMBean(DefaultMBeanServerInterceptor.java:324)\n\tat com.sun.jmx.mbeanserver.JmxMBeanServer.registerMBean(JmxMBeanServer.java:494)\n\tat com.ibm.ws.management.PlatformMBeanServer.registerMBean(PlatformMBeanServer.java:484)\n\tat org.apache.camel.management.DefaultManagementAgent.registerMBeanWithServer(DefaultManagementAgent.java:320)\n\tat org.apache.camel.management.DefaultManagementAgent.register(DefaultManagementAgent.java:236)\n...\n{code}\n\nThe web application starts up, but with a lot of exceptions in the log.\n\nProposal:\nInstead of using a Set<ObjectName> for mbeansRegistered, use a Map<ObjectName, ObjectName> where the key is the \"Camel\" ObjectName and the value is the actually deployed ObjectName.\n\nI will provide a patch that illustrates the idea.\n" diff --git a/camel-core/src/main/java/org/apache/camel/management/DefaultManagementAgent.java b/camel-core/src/main/java/org/apache/camel/management/DefaultManagementAgent.java index d59c492..c9aa47d 100644 --- a/camel-core/src/main/java/org/apache/camel/management/DefaultManagementAgent.java +++ b/camel-core/src/main/java/org/apache/camel/management/DefaultManagementAgent.java @@ -22,9 +22,9 @@ import java.net.InetAddress; import java.net.UnknownHostException; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; -import java.util.HashSet; +import java.util.HashMap; import java.util.List; -import java.util.Set; +import java.util.Map; import java.util.concurrent.ExecutorService; import javax.management.JMException; import javax.management.MBeanServer; @@ -60,7 +60,8 @@ public class DefaultManagementAgent extends ServiceSupport implements Management private CamelContext camelContext; private ExecutorService executorService; private MBeanServer server; - private final Set<ObjectName> mbeansRegistered = new HashSet<ObjectName>(); + // need a name -> actual name mapping as some servers changes the names (suc as WebSphere) + private final Map<ObjectName, ObjectName> mbeansRegistered = new HashMap<ObjectName, ObjectName>(); private JMXConnectorServer cs; private Integer registryPort; @@ -240,15 +241,17 @@ public class DefaultManagementAgent extends ServiceSupport implements Management } public void unregister(ObjectName name) throws JMException { - if (server.isRegistered(name)) { - server.unregisterMBean(name); + if (isRegistered(name)) { + server.unregisterMBean(mbeansRegistered.get(name)); LOG.debug("Unregistered MBean with ObjectName: {}", name); } mbeansRegistered.remove(name); } public boolean isRegistered(ObjectName name) { - return server.isRegistered(name); + return (mbeansRegistered.containsKey(name) + && server.isRegistered(mbeansRegistered.get(name))) + || server.isRegistered(name); } protected void doStart() throws Exception { @@ -280,11 +283,10 @@ public class DefaultManagementAgent extends ServiceSupport implements Management } // Using the array to hold the busMBeans to avoid the CurrentModificationException - ObjectName[] mBeans = mbeansRegistered.toArray(new ObjectName[mbeansRegistered.size()]); + ObjectName[] mBeans = mbeansRegistered.keySet().toArray(new ObjectName[mbeansRegistered.size()]); int caught = 0; for (ObjectName name : mBeans) { try { - mbeansRegistered.remove(name); unregister(name); } catch (Exception e) { LOG.info("Exception unregistering MBean with name " + name, e); @@ -302,7 +304,7 @@ public class DefaultManagementAgent extends ServiceSupport implements Management throws JMException { // have we already registered the bean, there can be shared instances in the camel routes - boolean exists = server.isRegistered(name); + boolean exists = isRegistered(name); if (exists) { if (forceRegistration) { LOG.info("ForceRegistration enabled, unregistering existing MBean with ObjectName: {}", name); @@ -324,7 +326,7 @@ public class DefaultManagementAgent extends ServiceSupport implements Management if (instance != null) { ObjectName registeredName = instance.getObjectName(); LOG.debug("Registered MBean with ObjectName: {}", registeredName); - mbeansRegistered.add(registeredName); + mbeansRegistered.put(name, registeredName); } }
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-5187_8cadc344.diff
bugs-dot-jar_data_CAMEL-9666_da035952
--- BugID: CAMEL-9666 Summary: 'Safe copy of DefaultExchange does not propagate ''fault'' property ' Description: |- {{fault}} property should be copied in the following places: https://github.com/apache/camel/blob/master/camel-core/src/main/java/org/apache/camel/impl/DefaultExchange.java#L100 https://github.com/apache/camel/blob/master/camel-core/src/main/java/org/apache/camel/impl/DefaultExchange.java#L107 Consequences: {{DefaultExchange#isFault()}} does not work if {{exception}} property is not set. diff --git a/camel-core/src/main/java/org/apache/camel/impl/DefaultExchange.java b/camel-core/src/main/java/org/apache/camel/impl/DefaultExchange.java index e1f83f6..923c0d8 100644 --- a/camel-core/src/main/java/org/apache/camel/impl/DefaultExchange.java +++ b/camel-core/src/main/java/org/apache/camel/impl/DefaultExchange.java @@ -98,6 +98,7 @@ public final class DefaultExchange implements Exchange { if (safeCopy) { exchange.getIn().setBody(getIn().getBody()); + exchange.getIn().setFault(getIn().isFault()); if (getIn().hasHeaders()) { exchange.getIn().setHeaders(safeCopyHeaders(getIn().getHeaders())); // just copy the attachments here @@ -105,6 +106,7 @@ public final class DefaultExchange implements Exchange { } if (hasOut()) { exchange.getOut().setBody(getOut().getBody()); + exchange.getOut().setFault(getOut().isFault()); if (getOut().hasHeaders()) { exchange.getOut().setHeaders(safeCopyHeaders(getOut().getHeaders())); }
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-9666_da035952.diff
bugs-dot-jar_data_CAMEL-7795_19b2aa31
--- BugID: CAMEL-7795 Summary: 'Regression: MDC may lose values after when Async Routing Engine is used' Description: |- CAMEL-6377 introduced some optimisations in the MDC Logging mechanism which make it lose MDC values when the async routing engine is used. If we are using an async component such as CXF, the response or done() callback will be issued from a thread NOT managed by Camel. Therefore, we need the MDCCallback to reset *ALL* MDC values, not just the routeId (as was intended by the commits that caused the regression). The situation may be salvaged by the fact that underlying MDC implementations use an InheritableThreadLocal, so the first requests after system initialisation may see correct behaviour, because the MDC values from the requesting thread is propagated to the newly initialised threads in the underlying stack's ThreadPool, as the coreThreads are being initialised within the context of the original threads which act like parent threads. But after those first attempts, odd behaviour is seen and all responses from the async endpoint come back without an MDC. diff --git a/camel-core/src/main/java/org/apache/camel/impl/MDCUnitOfWork.java b/camel-core/src/main/java/org/apache/camel/impl/MDCUnitOfWork.java index 62f6b16..1726b80 100644 --- a/camel-core/src/main/java/org/apache/camel/impl/MDCUnitOfWork.java +++ b/camel-core/src/main/java/org/apache/camel/impl/MDCUnitOfWork.java @@ -217,13 +217,15 @@ public class MDCUnitOfWork extends DefaultUnitOfWork { if (correlationId != null) { MDC.put(MDC_CORRELATION_ID, correlationId); } - if (routeId != null) { - MDC.put(MDC_ROUTE_ID, routeId); - } if (camelContextId != null) { MDC.put(MDC_CAMEL_CONTEXT_ID, camelContextId); } } + // need to setup the routeId finally + if (routeId != null) { + MDC.put(MDC_ROUTE_ID, routeId); + } + } finally { // muse ensure delegate is invoked delegate.done(doneSync);
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-7795_19b2aa31.diff
bugs-dot-jar_data_CAMEL-4482_e38494f1
--- BugID: CAMEL-4482 Summary: Using custom expression in Splitter EIP which throws exception, is not triggering onException Description: |- See nabble http://camel.465427.n5.nabble.com/Global-exception-not-invoked-in-case-of-Exception-fired-while-iterating-through-File-Splitter-td4826097.html We should detect exceptions occurred during evaluation of the expression, and then cause the splitter EIP to fail asap. diff --git a/camel-core/src/main/java/org/apache/camel/processor/MulticastProcessor.java b/camel-core/src/main/java/org/apache/camel/processor/MulticastProcessor.java index 8727bef..f9b361e 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/MulticastProcessor.java +++ b/camel-core/src/main/java/org/apache/camel/processor/MulticastProcessor.java @@ -797,6 +797,12 @@ public class MulticastProcessor extends ServiceSupport implements AsyncProcessor 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; } diff --git a/camel-core/src/main/java/org/apache/camel/processor/Splitter.java b/camel-core/src/main/java/org/apache/camel/processor/Splitter.java index bb7783a..ce14657 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/Splitter.java +++ b/camel-core/src/main/java/org/apache/camel/processor/Splitter.java @@ -98,14 +98,26 @@ public class Splitter extends MulticastProcessor implements AsyncProcessor, Trac } @Override - protected Iterable<ProcessorExchangePair> createProcessorExchangePairs(Exchange exchange) { + protected Iterable<ProcessorExchangePair> createProcessorExchangePairs(Exchange exchange) throws Exception { Object value = expression.evaluate(exchange, Object.class); + if (exchange.getException() != null) { + // force any exceptions occurred during evaluation to be thrown + throw exchange.getException(); + } + Iterable<ProcessorExchangePair> answer; if (isStreaming()) { - return createProcessorExchangePairsIterable(exchange, value); + answer = createProcessorExchangePairsIterable(exchange, value); } else { - return createProcessorExchangePairsList(exchange, value); + answer = createProcessorExchangePairsList(exchange, value); + } + if (exchange.getException() != null) { + // force any exceptions occurred during creation of exchange paris to be thrown + // before returning the answer; + throw exchange.getException(); } + + return answer; } @SuppressWarnings("unchecked")
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-4482_e38494f1.diff
bugs-dot-jar_data_CAMEL-8146_17475d80
--- BugID: CAMEL-8146 Summary: Starting and stopping routes leak threads Description: | Seems to be identical consequence as with previous issue CAMEL-5677, but perhaps due to a different cause. Having a file or SFTP based route, trying something like: {code} for (int i = 0; i < 50; i++) { camelContext.startRoute(routeId); camelContext.stopRoute(routeId); } {code} results in 50 orphan threads of this type: {code} "Camel (camel) thread #231 - sftp://user@host/path" #10170 daemon prio=5 os_prio=0 tid=0x00007fa4b46a5800 nid=0x10fc waiting on condition [0x00007fa452934000] java.lang.Thread.State: TIMED_WAITING (parking) at sun.misc.Unsafe.park(Native Method) - parking to wait for <0x00000000b83dc900> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject) at java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:215) at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.awaitNanos(AbstractQueuedSynchronizer.java:2078) at java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:1093) at java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:809) at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1067) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1127) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) {code} Switching to suspend/resume solves the problem, however I guess the start/stop issue should be addressed. diff --git a/camel-core/src/main/java/org/apache/camel/impl/DefaultScheduledPollConsumerScheduler.java b/camel-core/src/main/java/org/apache/camel/impl/DefaultScheduledPollConsumerScheduler.java index c132cad..729ee75 100644 --- a/camel-core/src/main/java/org/apache/camel/impl/DefaultScheduledPollConsumerScheduler.java +++ b/camel-core/src/main/java/org/apache/camel/impl/DefaultScheduledPollConsumerScheduler.java @@ -156,17 +156,15 @@ public class DefaultScheduledPollConsumerScheduler extends org.apache.camel.supp protected void doStop() throws Exception { if (future != null) { LOG.debug("This consumer is stopping, so cancelling scheduled task: " + future); - future.cancel(false); + future.cancel(true); future = null; } - } - @Override - protected void doShutdown() throws Exception { if (shutdownExecutor && scheduledExecutorService != null) { getCamelContext().getExecutorServiceManager().shutdownNow(scheduledExecutorService); scheduledExecutorService = null; future = null; } } + } diff --git a/camel-core/src/main/java/org/apache/camel/impl/ScheduledPollConsumer.java b/camel-core/src/main/java/org/apache/camel/impl/ScheduledPollConsumer.java index 5d080e2..e300d49 100644 --- a/camel-core/src/main/java/org/apache/camel/impl/ScheduledPollConsumer.java +++ b/camel-core/src/main/java/org/apache/camel/impl/ScheduledPollConsumer.java @@ -514,7 +514,8 @@ public abstract class ScheduledPollConsumer extends DefaultConsumer implements R @Override protected void doStop() throws Exception { - ServiceHelper.stopService(scheduler); + scheduler.unscheduleTask(); + ServiceHelper.stopAndShutdownServices(scheduler); // clear counters backoffCounter = 0;
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-8146_17475d80.diff
bugs-dot-jar_data_CAMEL-8964_ea8ee025
--- BugID: CAMEL-8964 Summary: CamelContext - API for control routes may cause Route not to update it state Description: |- See CAMEL-8963 Its the Route instance that do not update it state as well. But the RouteService has the correct state. So one can be Started and the other Suspended. diff --git a/camel-core/src/main/java/org/apache/camel/impl/DefaultCamelContext.java b/camel-core/src/main/java/org/apache/camel/impl/DefaultCamelContext.java index c24674e..0ed913a 100644 --- a/camel-core/src/main/java/org/apache/camel/impl/DefaultCamelContext.java +++ b/camel-core/src/main/java/org/apache/camel/impl/DefaultCamelContext.java @@ -984,6 +984,9 @@ public class DefaultCamelContext extends ServiceSupport implements ModelCamelCon RouteService routeService = routeServices.get(routeId); if (routeService != null) { resumeRouteService(routeService); + // must resume the route as well + Route route = getRoute(routeId); + ServiceHelper.resumeService(route); } } @@ -1125,12 +1128,15 @@ public class DefaultCamelContext extends ServiceSupport implements ModelCamelCon RouteService routeService = routeServices.get(routeId); if (routeService != null) { List<RouteStartupOrder> routes = new ArrayList<RouteStartupOrder>(1); - RouteStartupOrder order = new DefaultRouteStartupOrder(1, routeService.getRoutes().iterator().next(), routeService); + Route route = routeService.getRoutes().iterator().next(); + RouteStartupOrder order = new DefaultRouteStartupOrder(1, route, routeService); routes.add(order); getShutdownStrategy().suspend(this, routes); // must suspend route service as well suspendRouteService(routeService); + // must suspend the route as well + ServiceHelper.suspendService(route); } } @@ -1143,12 +1149,15 @@ public class DefaultCamelContext extends ServiceSupport implements ModelCamelCon RouteService routeService = routeServices.get(routeId); if (routeService != null) { List<RouteStartupOrder> routes = new ArrayList<RouteStartupOrder>(1); - RouteStartupOrder order = new DefaultRouteStartupOrder(1, routeService.getRoutes().iterator().next(), routeService); + Route route = routeService.getRoutes().iterator().next(); + RouteStartupOrder order = new DefaultRouteStartupOrder(1, route, routeService); routes.add(order); getShutdownStrategy().suspend(this, routes, timeout, timeUnit); // must suspend route service as well suspendRouteService(routeService); + // must suspend the route as well + ServiceHelper.suspendService(route); } } diff --git a/camel-core/src/main/java/org/apache/camel/util/ServiceHelper.java b/camel-core/src/main/java/org/apache/camel/util/ServiceHelper.java index 0a7df51..90b5ce9 100644 --- a/camel-core/src/main/java/org/apache/camel/util/ServiceHelper.java +++ b/camel-core/src/main/java/org/apache/camel/util/ServiceHelper.java @@ -260,7 +260,7 @@ public final class ServiceHelper { * If there's any exception being thrown while resuming the elements one after the * other this method would rethrow the <b>first</b> such exception being thrown. * - * @see #resumeService(Service) + * @see #resumeService(Object) */ public static void resumeServices(Collection<?> services) throws Exception { if (services == null) { @@ -308,7 +308,7 @@ public final class ServiceHelper { * @throws Exception is thrown if error occurred * @see #startService(Service) */ - public static boolean resumeService(Service service) throws Exception { + public static boolean resumeService(Object service) throws Exception { if (service instanceof SuspendableService) { SuspendableService ss = (SuspendableService) service; if (ss.isSuspended()) { @@ -331,7 +331,7 @@ public final class ServiceHelper { * If there's any exception being thrown while suspending the elements one after the * other this method would rethrow the <b>first</b> such exception being thrown. * - * @see #suspendService(Service) + * @see #suspendService(Object) */ public static void suspendServices(Collection<?> services) throws Exception { if (services == null) { @@ -379,7 +379,7 @@ public final class ServiceHelper { * @throws Exception is thrown if error occurred * @see #stopService(Object) */ - public static boolean suspendService(Service service) throws Exception { + public static boolean suspendService(Object service) throws Exception { if (service instanceof SuspendableService) { SuspendableService ss = (SuspendableService) service; if (!ss.isSuspended()) {
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-8964_ea8ee025.diff
bugs-dot-jar_data_CAMEL-3847_de9399f3
--- BugID: CAMEL-3847 Summary: Adding type converter should clear misses map for the given type Description: |- See nabble http://camel.465427.n5.nabble.com/addTypeConverter-does-not-clear-misses-in-BaseTypeConverterRegistry-tp4288871p4288871.html diff --git a/camel-core/src/main/java/org/apache/camel/impl/converter/BaseTypeConverterRegistry.java b/camel-core/src/main/java/org/apache/camel/impl/converter/BaseTypeConverterRegistry.java index ec766af..b3de5e6 100644 --- a/camel-core/src/main/java/org/apache/camel/impl/converter/BaseTypeConverterRegistry.java +++ b/camel-core/src/main/java/org/apache/camel/impl/converter/BaseTypeConverterRegistry.java @@ -223,9 +223,7 @@ public abstract class BaseTypeConverterRegistry extends ServiceSupport implement } // Could not find suitable conversion, so remember it - synchronized (misses) { - misses.put(key, key); - } + misses.put(key, key); // Could not find suitable conversion, so return Void to indicate not found return Void.TYPE; @@ -243,6 +241,8 @@ public abstract class BaseTypeConverterRegistry extends ServiceSupport implement log.warn("Overriding type converter from: " + converter + " to: " + typeConverter); } typeMappings.put(key, typeConverter); + // remove any previous misses, as we added the new type converter + misses.remove(key); } } }
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-3847_de9399f3.diff
bugs-dot-jar_data_CAMEL-6889_cd40b712
--- BugID: CAMEL-6889 Summary: CBR - Should break out if exception was thrown when evaluating predicate Description: |+ If having a CBR and the predicate throws an exception, then the next predicate is called before error handler triggers. We should break out when exception is detected like pipeline/multicast can do. diff --git a/camel-core/src/main/java/org/apache/camel/processor/ChoiceProcessor.java b/camel-core/src/main/java/org/apache/camel/processor/ChoiceProcessor.java index 0310c9a..44f4b10 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/ChoiceProcessor.java +++ b/camel-core/src/main/java/org/apache/camel/processor/ChoiceProcessor.java @@ -30,6 +30,10 @@ import org.apache.camel.support.ServiceSupport; import org.apache.camel.util.AsyncProcessorConverterHelper; import org.apache.camel.util.AsyncProcessorHelper; import org.apache.camel.util.ServiceHelper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import static org.apache.camel.processor.PipelineHelper.continueProcessing; /** * Implements a Choice structure where one or more predicates are used which if @@ -39,6 +43,7 @@ import org.apache.camel.util.ServiceHelper; * @version */ public class ChoiceProcessor extends ServiceSupport implements AsyncProcessor, Navigate<Processor>, Traceable { + private static final Logger LOG = LoggerFactory.getLogger(ChoiceProcessor.class); private final List<Processor> filters; private final Processor otherwise; @@ -84,13 +89,16 @@ public class ChoiceProcessor extends ServiceSupport implements AsyncProcessor, N try { matches = filter.getPredicate().matches(exchange); exchange.setProperty(Exchange.FILTER_MATCHED, matches); + // as we have pre evaluated the predicate then use its processor directly when routing + processor = filter.getProcessor(); } catch (Throwable e) { exchange.setException(e); - choiceCallback.done(true); - return true; } - // as we have pre evaluated the predicate then use its processor directly when routing - processor = filter.getProcessor(); + } + + // check for error if so we should break out + if (!continueProcessing(exchange, "so breaking out of choice", LOG)) { + break; } // if we did not match then continue to next filter
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-6889_cd40b712.diff
bugs-dot-jar_data_CAMEL-6447_020c451a
--- BugID: CAMEL-6447 Summary: endChoice() has no effect in nested choice definition Description: "I just upgraded from 2.10.4 to 2.11.0 and noticed that nested choice definitions started acting strangely. For example:\n\n{code:java}\n .choice()\n \ .when(header(Exchange.EXCEPTION_CAUGHT).isNotNull())\n // 1\n .setBody(exceptionMessage().append(SystemUtils.LINE_SEPARATOR).append(exceptionStackTrace()))\n \ .choice()\n .when(header(HEADER_CONTROLLER_ID).isNotNull())\n \ // 1a\n .setHeader(Exchange.FILE_NAME, simple(AUDIT_CONTROLLER_FAILED_FILENAME + \".error.log\"))\n .to(ENDPOINT_AUDIT_DIR)\n \ .otherwise()\n // 1b\n .setHeader(Exchange.FILE_NAME, simple(AUDIT_FAILED_FILENAME + \".error.log\"))\n .to(ENDPOINT_AUDIT_DIR)\n \ // INSERTING .end() here solves the issue\n .endChoice()\n \ .log(LoggingLevel.WARN, \"DLQ written: ${in.header.CamelExceptionCaught}\"\n \ .otherwise()\n // 2\n .log(LoggingLevel.WARN, \"DLQ written\" + MESSAGE_LOG_FORMAT)\n .end()\n{code}\n\nI have a test that is supposed to go through 1 and 1a. However it now passes through 1 and 2!\nIt looks like the endChoice() in 1b has no effect and the otherwise() in 2 is executed instead of 1b. Inserting and end() statement as shown seems to solve the issue, but it looks suspicious.\n\nIt's probably a regression introduced by the fix for CAMEL-5953, but I'm not 100% sure. " diff --git a/camel-core/src/main/java/org/apache/camel/model/ProcessorDefinition.java b/camel-core/src/main/java/org/apache/camel/model/ProcessorDefinition.java index 45889c3..9998e51 100644 --- a/camel-core/src/main/java/org/apache/camel/model/ProcessorDefinition.java +++ b/camel-core/src/main/java/org/apache/camel/model/ProcessorDefinition.java @@ -1295,8 +1295,13 @@ public abstract class ProcessorDefinition<Type extends ProcessorDefinition<Type> * @return the builder */ public ChoiceDefinition endChoice() { - // are we already a choice? + // are we nested choice? ProcessorDefinition<?> def = this; + if (def.getParent() instanceof WhenDefinition) { + return (ChoiceDefinition) def.getParent().getParent(); + } + + // are we already a choice? if (def instanceof ChoiceDefinition) { return (ChoiceDefinition) def; } diff --git a/camel-core/src/main/java/org/apache/camel/processor/ChoiceProcessor.java b/camel-core/src/main/java/org/apache/camel/processor/ChoiceProcessor.java index 5af8b36..0310c9a 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/ChoiceProcessor.java +++ b/camel-core/src/main/java/org/apache/camel/processor/ChoiceProcessor.java @@ -30,10 +30,6 @@ import org.apache.camel.support.ServiceSupport; import org.apache.camel.util.AsyncProcessorConverterHelper; import org.apache.camel.util.AsyncProcessorHelper; import org.apache.camel.util.ServiceHelper; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static org.apache.camel.processor.PipelineHelper.continueProcessing; /** * Implements a Choice structure where one or more predicates are used which if @@ -43,7 +39,6 @@ import static org.apache.camel.processor.PipelineHelper.continueProcessing; * @version */ public class ChoiceProcessor extends ServiceSupport implements AsyncProcessor, Navigate<Processor>, Traceable { - private static final Logger LOG = LoggerFactory.getLogger(ChoiceProcessor.class); private final List<Processor> filters; private final Processor otherwise; @@ -56,91 +51,61 @@ public class ChoiceProcessor extends ServiceSupport implements AsyncProcessor, N AsyncProcessorHelper.process(this, exchange); } - public boolean process(Exchange exchange, AsyncCallback callback) { + public boolean process(final Exchange exchange, final AsyncCallback callback) { Iterator<Processor> processors = next().iterator(); - exchange.setProperty(Exchange.FILTER_MATCHED, false); - while (continueRouting(processors, exchange)) { + // callback to restore existing FILTER_MATCHED property on the Exchange + final Object existing = exchange.getProperty(Exchange.FILTER_MATCHED); + final AsyncCallback choiceCallback = new AsyncCallback() { + @Override + public void done(boolean doneSync) { + if (existing != null) { + exchange.setProperty(Exchange.FILTER_MATCHED, existing); + } else { + exchange.removeProperty(Exchange.FILTER_MATCHED); + } + callback.done(doneSync); + } + }; + + // as we only pick one processor to process, then no need to have async callback that has a while loop as well + // as this should not happen, eg we pick the first filter processor that matches, or the otherwise (if present) + // and if not, we just continue without using any processor + while (processors.hasNext()) { // get the next processor Processor processor = processors.next(); - AsyncProcessor async = AsyncProcessorConverterHelper.convert(processor); - boolean sync = process(exchange, callback, processors, async); - - // continue as long its being processed synchronously - if (!sync) { - LOG.trace("Processing exchangeId: {} is continued being processed asynchronously", exchange.getExchangeId()); - // the remainder of the CBR 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; + // evaluate the predicate on filter predicate early to be faster + // and avoid issues when having nested choices + // as we should only pick one processor + boolean matches = true; + if (processor instanceof FilterProcessor) { + FilterProcessor filter = (FilterProcessor) processor; + try { + matches = filter.getPredicate().matches(exchange); + exchange.setProperty(Exchange.FILTER_MATCHED, matches); + } catch (Throwable e) { + exchange.setException(e); + choiceCallback.done(true); + return true; + } + // as we have pre evaluated the predicate then use its processor directly when routing + processor = filter.getProcessor(); } - LOG.trace("Processing exchangeId: {} is continued being processed synchronously", exchange.getExchangeId()); - - // check for error if so we should break out - if (!continueProcessing(exchange, "so breaking out of content based router", LOG)) { - break; + // if we did not match then continue to next filter + if (!matches) { + continue; } - } - - LOG.trace("Processing complete for exchangeId: {} >>> {}", exchange.getExchangeId(), exchange); - callback.done(true); - return true; - } - - protected boolean continueRouting(Iterator<Processor> it, Exchange exchange) { - boolean answer = it.hasNext(); - if (answer) { - Object matched = exchange.getProperty(Exchange.FILTER_MATCHED); - if (matched != null) { - boolean hasMatched = exchange.getContext().getTypeConverter().convertTo(Boolean.class, matched); - if (hasMatched) { - LOG.debug("ExchangeId: {} has been matched: {}", exchange.getExchangeId(), exchange); - answer = false; - } - } + // okay we found a filter or its the otherwise we are processing + AsyncProcessor async = AsyncProcessorConverterHelper.convert(processor); + return async.process(exchange, choiceCallback); } - LOG.trace("ExchangeId: {} should continue matching: {}", exchange.getExchangeId(), answer); - return answer; - } - - private boolean process(final Exchange exchange, final AsyncCallback callback, - final Iterator<Processor> processors, final AsyncProcessor asyncProcessor) { - // this does the actual processing so log at trace level - LOG.trace("Processing exchangeId: {} >>> {}", exchange.getExchangeId(), exchange); - - // implement asynchronous routing logic in callback so we can have the callback being - // triggered and then continue routing where we left - boolean sync = asyncProcessor.process(exchange, new AsyncCallback() { - public void done(boolean doneSync) { - // we only have to handle async completion of the pipeline - if (doneSync) { - return; - } - // continue processing the pipeline asynchronously - while (continueRouting(processors, exchange)) { - AsyncProcessor processor = AsyncProcessorConverterHelper.convert(processors.next()); - - // check for error if so we should break out - if (!continueProcessing(exchange, "so breaking out of pipeline", LOG)) { - break; - } - - doneSync = process(exchange, callback, processors, processor); - if (!doneSync) { - LOG.trace("Processing exchangeId: {} is continued being processed asynchronously", exchange.getExchangeId()); - return; - } - } - - LOG.trace("Processing complete for exchangeId: {} >>> {}", exchange.getExchangeId(), exchange); - callback.done(false); - } - }); - - return sync; + // when no filter matches and there is no otherwise, then just continue + choiceCallback.done(true); + return true; } @Override
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-6447_020c451a.diff
bugs-dot-jar_data_CAMEL-5515_b3bb8670
--- BugID: CAMEL-5515 Summary: thread java DSL doesn't provide full function out of box Description: |2- thread() doesn't has extra parameter for setting the thread name, and the other thread() method doesn't add the output process rightly. diff --git a/camel-core/src/main/java/org/apache/camel/model/ProcessorDefinition.java b/camel-core/src/main/java/org/apache/camel/model/ProcessorDefinition.java index 28b7eb9..3ba39cb 100644 --- a/camel-core/src/main/java/org/apache/camel/model/ProcessorDefinition.java +++ b/camel-core/src/main/java/org/apache/camel/model/ProcessorDefinition.java @@ -1130,7 +1130,7 @@ public abstract class ProcessorDefinition<Type extends ProcessorDefinition<Type> * @return the builder */ public ThreadsDefinition threads(int poolSize) { - ThreadsDefinition answer = threads(); + ThreadsDefinition answer = new ThreadsDefinition(); answer.setPoolSize(poolSize); addOutput(answer); return answer; @@ -1144,7 +1144,7 @@ public abstract class ProcessorDefinition<Type extends ProcessorDefinition<Type> * @return the builder */ public ThreadsDefinition threads(int poolSize, int maxPoolSize) { - ThreadsDefinition answer = threads(); + ThreadsDefinition answer = new ThreadsDefinition(); answer.setPoolSize(poolSize); answer.setMaxPoolSize(maxPoolSize); addOutput(answer); @@ -1160,7 +1160,7 @@ public abstract class ProcessorDefinition<Type extends ProcessorDefinition<Type> * @return the builder */ public ThreadsDefinition threads(int poolSize, int maxPoolSize, String threadName) { - ThreadsDefinition answer = threads(); + ThreadsDefinition answer = new ThreadsDefinition(); answer.setPoolSize(poolSize); answer.setMaxPoolSize(maxPoolSize); answer.setThreadName(threadName);
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-5515_b3bb8670.diff
bugs-dot-jar_data_CAMEL-7146_b6981cfd
--- BugID: CAMEL-7146 Summary: NPE in Aggregator when completionSize = 1 Description: "A Camel aggregator with persistence repository cannot have a completionSize of 1. If this is configured, every message produces a NPE with the attached stacktrace. \n\nI have also attached a small example project that shows the Exception. As soon as the completionSize is > 1, it runs fine.\n\nThis is just a minor flaw, since I cannot think about a really useful case with completionSize 1, but it worked with earlier versions of Camel. \n\nAs an alternative (if completionSize 1 should not be used), Camel could throw an error during Context startup when completionSize < 2." diff --git a/camel-core/src/main/java/org/apache/camel/processor/aggregate/AggregateProcessor.java b/camel-core/src/main/java/org/apache/camel/processor/aggregate/AggregateProcessor.java index 8fe24c5..e7a094f 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/aggregate/AggregateProcessor.java +++ b/camel-core/src/main/java/org/apache/camel/processor/aggregate/AggregateProcessor.java @@ -481,8 +481,12 @@ public class AggregateProcessor extends ServiceSupport implements AsyncProcessor } aggregated.setProperty(Exchange.AGGREGATED_CORRELATION_KEY, key); - // remove from repository as its completed, we do this first as to trigger any OptimisticLockingException's - aggregationRepository.remove(aggregated.getContext(), key, original); + // only remove if we have previous added (as we could potentially complete with only 1 exchange) + // (if we have previous added then we have that as the original exchange) + if (original != null) { + // remove from repository as its completed, we do this first as to trigger any OptimisticLockingException's + aggregationRepository.remove(aggregated.getContext(), key, original); + } if (!fromTimeout && timeoutMap != null) { // cleanup timeout map if it was a incoming exchange which triggered the timeout (and not the timeout checker) diff --git a/camel-core/src/main/java/org/apache/camel/spi/AggregationRepository.java b/camel-core/src/main/java/org/apache/camel/spi/AggregationRepository.java index 669a956..ba1de6a 100644 --- a/camel-core/src/main/java/org/apache/camel/spi/AggregationRepository.java +++ b/camel-core/src/main/java/org/apache/camel/spi/AggregationRepository.java @@ -32,6 +32,9 @@ public interface AggregationRepository { * Add the given {@link Exchange} under the correlation key. * <p/> * Will replace any existing exchange. + * <p/> + * <b>Important:</b> This method is <b>not</b> invoked if only one exchange was completed, and therefore + * the exchange does not need to be added to a repository, as its completed immediately. * * @param camelContext the current CamelContext * @param key the correlation key @@ -42,6 +45,8 @@ public interface AggregationRepository { /** * Gets the given exchange with the correlation key + * <p/> + * This method is always invoked for any incoming exchange in the aggregator. * * @param camelContext the current CamelContext * @param key the correlation key @@ -52,6 +57,9 @@ public interface AggregationRepository { /** * Removes the exchange with the given correlation key, which should happen * when an {@link Exchange} is completed + * <p/> + * <b>Important:</b> This method is <b>not</b> invoked if only one exchange was completed, and therefore + * the exchange does not need to be added to a repository, as its completed immediately. * * @param camelContext the current CamelContext * @param key the correlation key @@ -61,6 +69,8 @@ public interface AggregationRepository { /** * Confirms the completion of the {@link Exchange}. + * <p/> + * This method is always invoked. * * @param camelContext the current CamelContext * @param exchangeId exchange id to confirm
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-7146_b6981cfd.diff
bugs-dot-jar_data_CAMEL-3791_52106681
--- BugID: CAMEL-3791 Summary: Camel should reset the stream cache if the useOriginalInMessage option is true Description: "{code}\n--- src/main/java/org/apache/camel/processor/RedeliveryErrorHandler.java\t(revision 1083672)\n+++ src/main/java/org/apache/camel/processor/RedeliveryErrorHandler.java\t(working copy)\n@@ -591,18 +591,23 @@\n // is the a failure processor to process the Exchange\n if (processor != null) {\n \n- // reset cached streams so they can be read again\n- MessageHelper.resetStreamCache(exchange.getIn());\n-\n \ // prepare original IN body if it should be moved instead of current body\n if (data.useOriginalInMessage) {\n if (log.isTraceEnabled()) {\n log.trace(\"Using the original IN message instead of current\");\n \ }\n Message original = exchange.getUnitOfWork().getOriginalInMessage();\n \ exchange.setIn(original);\n }\n\n+ // reset cached streams so they can be read again\n+ MessageHelper.resetStreamCache(exchange.getIn());\n{code}" diff --git a/camel-core/src/main/java/org/apache/camel/processor/RedeliveryErrorHandler.java b/camel-core/src/main/java/org/apache/camel/processor/RedeliveryErrorHandler.java index 51fe6bf..d7f11e0 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/RedeliveryErrorHandler.java +++ b/camel-core/src/main/java/org/apache/camel/processor/RedeliveryErrorHandler.java @@ -591,18 +591,23 @@ public abstract class RedeliveryErrorHandler extends ErrorHandlerSupport impleme // is the a failure processor to process the Exchange if (processor != null) { - // reset cached streams so they can be read again - MessageHelper.resetStreamCache(exchange.getIn()); - // prepare original IN body if it should be moved instead of current body if (data.useOriginalInMessage) { if (log.isTraceEnabled()) { log.trace("Using the original IN message instead of current"); } - Message original = exchange.getUnitOfWork().getOriginalInMessage(); exchange.setIn(original); + if (exchange.hasOut()) { + if (log.isTraceEnabled()) { + log.trace("Removing the out message to avoid some uncertain behavior"); + } + exchange.setOut(null); + } } + + // reset cached streams so they can be read again + MessageHelper.resetStreamCache(exchange.getIn()); if (log.isTraceEnabled()) { log.trace("Failure processor " + processor + " is processing Exchange: " + exchange);
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-3791_52106681.diff
bugs-dot-jar_data_CAMEL-7163_5f726d0b
--- BugID: CAMEL-7163 Summary: BacklogDebugger - Should not change body/header type to string Description: |- When using the backlog debugger then updating the body/headers would currently force those to become string type. We should preserve existing type, and allow end users to specify a new type. And also make it possible to remove body/headers as well. diff --git a/camel-core/src/main/java/org/apache/camel/api/management/mbean/ManagedBacklogDebuggerMBean.java b/camel-core/src/main/java/org/apache/camel/api/management/mbean/ManagedBacklogDebuggerMBean.java index 02d2d96..036ef3d 100644 --- a/camel-core/src/main/java/org/apache/camel/api/management/mbean/ManagedBacklogDebuggerMBean.java +++ b/camel-core/src/main/java/org/apache/camel/api/management/mbean/ManagedBacklogDebuggerMBean.java @@ -53,11 +53,23 @@ public interface ManagedBacklogDebuggerMBean { @ManagedOperation(description = "Resume running from the suspended breakpoint at the given node id") void resumeBreakpoint(String nodeId); - @ManagedOperation(description = "Updates the message body on the suspended breakpoint at the given node id") - void setMessageBodyOnBreakpoint(String nodeId, String body); + @ManagedOperation(description = "Updates the message body (uses same type as old body) on the suspended breakpoint at the given node id") + void setMessageBodyOnBreakpoint(String nodeId, Object body); - @ManagedOperation(description = "Updates/adds the message header on the suspended breakpoint at the given node id") - void setMessageHeaderOnBreakpoint(String nodeId, String headerName, String value); + @ManagedOperation(description = "Updates the message body (with a new type) on the suspended breakpoint at the given node id") + void setMessageBodyOnBreakpoint(String nodeId, Object body, String type); + + @ManagedOperation(description = "Removes the message body on the suspended breakpoint at the given node id") + void removeMessageBodyOnBreakpoint(String nodeId); + + @ManagedOperation(description = "Updates/adds the message header (uses same type as old header value) on the suspended breakpoint at the given node id") + void setMessageHeaderOnBreakpoint(String nodeId, String headerName, Object value); + + @ManagedOperation(description = "Removes the message header on the suspended breakpoint at the given node id") + void removeMessageHeaderOnBreakpoint(String nodeId, String headerName); + + @ManagedOperation(description = "Updates/adds the message header (with a new type) on the suspended breakpoint at the given node id") + void setMessageHeaderOnBreakpoint(String nodeId, String headerName, Object value, String type); @ManagedOperation(description = "Resume running any suspended breakpoints, and exits step mode") void resumeAll(); diff --git a/camel-core/src/main/java/org/apache/camel/management/mbean/ManagedBacklogDebugger.java b/camel-core/src/main/java/org/apache/camel/management/mbean/ManagedBacklogDebugger.java index 33f1310..9f3a94c 100644 --- a/camel-core/src/main/java/org/apache/camel/management/mbean/ManagedBacklogDebugger.java +++ b/camel-core/src/main/java/org/apache/camel/management/mbean/ManagedBacklogDebugger.java @@ -19,10 +19,12 @@ package org.apache.camel.management.mbean; import java.util.Set; import org.apache.camel.CamelContext; +import org.apache.camel.NoTypeConversionAvailableException; import org.apache.camel.api.management.ManagedResource; import org.apache.camel.api.management.mbean.ManagedBacklogDebuggerMBean; import org.apache.camel.processor.interceptor.BacklogDebugger; import org.apache.camel.spi.ManagementStrategy; +import org.apache.camel.util.ObjectHelper; @ManagedResource(description = "Managed BacklogDebugger") public class ManagedBacklogDebugger implements ManagedBacklogDebuggerMBean { @@ -91,12 +93,42 @@ public class ManagedBacklogDebugger implements ManagedBacklogDebuggerMBean { backlogDebugger.resumeBreakpoint(nodeId); } - public void setMessageBodyOnBreakpoint(String nodeId, String body) { + public void setMessageBodyOnBreakpoint(String nodeId, Object body) { backlogDebugger.setMessageBodyOnBreakpoint(nodeId, body); } - public void setMessageHeaderOnBreakpoint(String nodeId, String headerName, String value) { - backlogDebugger.setMessageHeaderOnBreakpoint(nodeId, headerName, value); + public void setMessageBodyOnBreakpoint(String nodeId, Object body, String type) { + try { + Class<?> classType = camelContext.getClassResolver().resolveMandatoryClass(type); + backlogDebugger.setMessageBodyOnBreakpoint(nodeId, body, classType); + } catch (ClassNotFoundException e) { + throw ObjectHelper.wrapRuntimeCamelException(e); + } + } + + public void removeMessageBodyOnBreakpoint(String nodeId) { + backlogDebugger.removeMessageBodyOnBreakpoint(nodeId); + } + + public void setMessageHeaderOnBreakpoint(String nodeId, String headerName, Object value) { + try { + backlogDebugger.setMessageHeaderOnBreakpoint(nodeId, headerName, value); + } catch (NoTypeConversionAvailableException e) { + throw ObjectHelper.wrapRuntimeCamelException(e); + } + } + + public void setMessageHeaderOnBreakpoint(String nodeId, String headerName, Object value, String type) { + try { + Class<?> classType = camelContext.getClassResolver().resolveMandatoryClass(type); + backlogDebugger.setMessageHeaderOnBreakpoint(nodeId, headerName, value, classType); + } catch (Exception e) { + throw ObjectHelper.wrapRuntimeCamelException(e); + } + } + + public void removeMessageHeaderOnBreakpoint(String nodeId, String headerName) { + backlogDebugger.removeMessageHeaderOnBreakpoint(nodeId, headerName); } public void resumeAll() { diff --git a/camel-core/src/main/java/org/apache/camel/processor/interceptor/BacklogDebugger.java b/camel-core/src/main/java/org/apache/camel/processor/interceptor/BacklogDebugger.java index 3c2e290..571b174 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/interceptor/BacklogDebugger.java +++ b/camel-core/src/main/java/org/apache/camel/processor/interceptor/BacklogDebugger.java @@ -31,6 +31,7 @@ import java.util.concurrent.atomic.AtomicLong; import org.apache.camel.CamelContext; import org.apache.camel.Exchange; import org.apache.camel.LoggingLevel; +import org.apache.camel.NoTypeConversionAvailableException; import org.apache.camel.Predicate; import org.apache.camel.Processor; import org.apache.camel.api.management.mbean.BacklogTracerEventMessage; @@ -268,26 +269,105 @@ public class BacklogDebugger extends ServiceSupport implements InterceptStrategy } } - public void setMessageBodyOnBreakpoint(String nodeId, String body) { + public void setMessageBodyOnBreakpoint(String nodeId, Object body) { SuspendedExchange se = suspendedBreakpoints.get(nodeId); if (se != null) { - logger.log("Breakpoint at node " + nodeId + " is updating message body on exchangeId: " + se.getExchange().getExchangeId() + " with new body: " + body); + boolean remove = body == null; + if (remove) { + removeMessageBodyOnBreakpoint(nodeId); + } else { + Class oldType; + if (se.getExchange().hasOut()) { + oldType = se.getExchange().getOut().getBody() != null ? se.getExchange().getOut().getBody().getClass() : null; + } else { + oldType = se.getExchange().getIn().getBody() != null ? se.getExchange().getIn().getBody().getClass() : null; + } + setMessageBodyOnBreakpoint(nodeId, body, oldType); + } + } + } + + public void setMessageBodyOnBreakpoint(String nodeId, Object body, Class type) { + SuspendedExchange se = suspendedBreakpoints.get(nodeId); + if (se != null) { + boolean remove = body == null; + if (remove) { + removeMessageBodyOnBreakpoint(nodeId); + } else { + logger.log("Breakpoint at node " + nodeId + " is updating message body on exchangeId: " + se.getExchange().getExchangeId() + " with new body: " + body); + if (se.getExchange().hasOut()) { + // preserve type + if (type != null) { + se.getExchange().getOut().setBody(body, type); + } else { + se.getExchange().getOut().setBody(body); + } + } else { + if (type != null) { + se.getExchange().getIn().setBody(body, type); + } else { + se.getExchange().getIn().setBody(body); + } + } + } + } + } + + public void removeMessageBodyOnBreakpoint(String nodeId) { + SuspendedExchange se = suspendedBreakpoints.get(nodeId); + if (se != null) { + logger.log("Breakpoint at node " + nodeId + " is removing message body on exchangeId: " + se.getExchange().getExchangeId()); if (se.getExchange().hasOut()) { - se.getExchange().getOut().setBody(body); + se.getExchange().getOut().setBody(null); } else { - se.getExchange().getIn().setBody(body); + se.getExchange().getIn().setBody(null); } } } - public void setMessageHeaderOnBreakpoint(String nodeId, String headerName, String value) { + public void setMessageHeaderOnBreakpoint(String nodeId, String headerName, Object value) throws NoTypeConversionAvailableException { + SuspendedExchange se = suspendedBreakpoints.get(nodeId); + if (se != null) { + Class oldType; + if (se.getExchange().hasOut()) { + oldType = se.getExchange().getOut().getHeader(headerName) != null ? se.getExchange().getOut().getHeader(headerName).getClass() : null; + } else { + oldType = se.getExchange().getIn().getHeader(headerName) != null ? se.getExchange().getIn().getHeader(headerName).getClass() : null; + } + setMessageHeaderOnBreakpoint(nodeId, headerName, value, oldType); + } + } + + public void setMessageHeaderOnBreakpoint(String nodeId, String headerName, Object value, Class type) throws NoTypeConversionAvailableException { SuspendedExchange se = suspendedBreakpoints.get(nodeId); if (se != null) { logger.log("Breakpoint at node " + nodeId + " is updating message header on exchangeId: " + se.getExchange().getExchangeId() + " with header: " + headerName + " and value: " + value); if (se.getExchange().hasOut()) { - se.getExchange().getOut().setHeader(headerName, value); + if (type != null) { + Object convertedValue = se.getExchange().getContext().getTypeConverter().mandatoryConvertTo(type, se.getExchange(), value); + se.getExchange().getOut().setHeader(headerName, convertedValue); + } else { + se.getExchange().getOut().setHeader(headerName, value); + } + } else { + if (type != null) { + Object convertedValue = se.getExchange().getContext().getTypeConverter().mandatoryConvertTo(type, se.getExchange(), value); + se.getExchange().getIn().setHeader(headerName, convertedValue); + } else { + se.getExchange().getIn().setHeader(headerName, value); + } + } + } + } + + public void removeMessageHeaderOnBreakpoint(String nodeId, String headerName) { + SuspendedExchange se = suspendedBreakpoints.get(nodeId); + if (se != null) { + logger.log("Breakpoint at node " + nodeId + " is removing message header on exchangeId: " + se.getExchange().getExchangeId() + " with header: " + headerName); + if (se.getExchange().hasOut()) { + se.getExchange().getOut().removeHeader(headerName); } else { - se.getExchange().getIn().setHeader(headerName, value); + se.getExchange().getIn().removeHeader(headerName); } } }
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-7163_5f726d0b.diff
bugs-dot-jar_data_CAMEL-5154_a8586a69
--- BugID: CAMEL-5154 Summary: Simple language - OGNL - Invoking explicit method with no parameters should not cause ambiguous exception for overloaded methods Description: | If you want to invoke a method on a bean which is overloaded, such as a String with toUpperCase having - toUpperCase() - toUpperCase(Locale) Then if you specify this in a simple ognl expression as follows {code} ${body.toUpperCase()} {code} Then Camel bean component should pick the no-parameter method as specified. diff --git a/camel-core/src/main/java/org/apache/camel/component/bean/BeanInfo.java b/camel-core/src/main/java/org/apache/camel/component/bean/BeanInfo.java index 43f40f5..4a8ddef 100644 --- a/camel-core/src/main/java/org/apache/camel/component/bean/BeanInfo.java +++ b/camel-core/src/main/java/org/apache/camel/component/bean/BeanInfo.java @@ -71,6 +71,7 @@ public class BeanInfo { // shared state with details of operations introspected from the bean, created during the constructor private Map<String, List<MethodInfo>> operations = new HashMap<String, List<MethodInfo>>(); private List<MethodInfo> operationsWithBody = new ArrayList<MethodInfo>(); + private List<MethodInfo> operationsWithNoBody = new ArrayList<MethodInfo>(); private List<MethodInfo> operationsWithCustomAnnotation = new ArrayList<MethodInfo>(); private List<MethodInfo> operationsWithHandlerAnnotation = new ArrayList<MethodInfo>(); private Map<Method, MethodInfo> methodMap = new HashMap<Method, MethodInfo>(); @@ -130,6 +131,7 @@ public class BeanInfo { // to keep this code thread safe operations = Collections.unmodifiableMap(operations); operationsWithBody = Collections.unmodifiableList(operationsWithBody); + operationsWithNoBody = Collections.unmodifiableList(operationsWithNoBody); operationsWithCustomAnnotation = Collections.unmodifiableList(operationsWithCustomAnnotation); operationsWithHandlerAnnotation = Collections.unmodifiableList(operationsWithHandlerAnnotation); methodMap = Collections.unmodifiableMap(methodMap); @@ -311,6 +313,8 @@ public class BeanInfo { operationsWithCustomAnnotation.add(methodInfo); } else if (methodInfo.hasBodyParameter()) { operationsWithBody.add(methodInfo); + } else { + operationsWithNoBody.add(methodInfo); } if (methodInfo.hasHandlerAnnotation()) { @@ -442,6 +446,7 @@ public class BeanInfo { // must use defensive copy, to avoid altering the shared lists // and we want to remove unwanted operations from these local lists final List<MethodInfo> localOperationsWithBody = new ArrayList<MethodInfo>(operationsWithBody); + final List<MethodInfo> localOperationsWithNoBody = new ArrayList<MethodInfo>(operationsWithNoBody); final List<MethodInfo> localOperationsWithCustomAnnotation = new ArrayList<MethodInfo>(operationsWithCustomAnnotation); final List<MethodInfo> localOperationsWithHandlerAnnotation = new ArrayList<MethodInfo>(operationsWithHandlerAnnotation); @@ -450,11 +455,13 @@ public class BeanInfo { removeNonMatchingMethods(localOperationsWithHandlerAnnotation, name); removeNonMatchingMethods(localOperationsWithCustomAnnotation, name); removeNonMatchingMethods(localOperationsWithBody, name); + removeNonMatchingMethods(localOperationsWithNoBody, name); } else { // remove all getter/setter as we do not want to consider these methods removeAllSetterOrGetterMethods(localOperationsWithHandlerAnnotation); removeAllSetterOrGetterMethods(localOperationsWithCustomAnnotation); removeAllSetterOrGetterMethods(localOperationsWithBody); + removeAllSetterOrGetterMethods(localOperationsWithNoBody); } if (localOperationsWithHandlerAnnotation.size() > 1) { @@ -468,6 +475,13 @@ public class BeanInfo { } else if (localOperationsWithCustomAnnotation.size() == 1) { // if there is one method with an annotation then use that one return localOperationsWithCustomAnnotation.get(0); + } + + // named method and with no parameters + boolean noParameters = name != null && name.endsWith("()"); + if (noParameters && localOperationsWithNoBody.size() == 1) { + // if there was a method name configured and it has no parameters, then use the method with no body (eg no parameters) + return localOperationsWithNoBody.get(0); } else if (localOperationsWithBody.size() == 1) { // if there is one method with body then use that one return localOperationsWithBody.get(0);
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-5154_a8586a69.diff
bugs-dot-jar_data_CAMEL-6604_55751402
--- BugID: CAMEL-6604 Summary: Routing slip and dynamic router EIP - Stream caching not working Description: |- See nabble http://camel.465427.n5.nabble.com/stream-caching-to-HTTP-end-point-tp5736608.html diff --git a/camel-core/src/main/java/org/apache/camel/processor/RoutingSlip.java b/camel-core/src/main/java/org/apache/camel/processor/RoutingSlip.java index cd4a864..bde0f42 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/RoutingSlip.java +++ b/camel-core/src/main/java/org/apache/camel/processor/RoutingSlip.java @@ -36,6 +36,7 @@ import org.apache.camel.impl.ProducerCache; import org.apache.camel.support.ServiceSupport; import org.apache.camel.util.AsyncProcessorHelper; import org.apache.camel.util.ExchangeHelper; +import org.apache.camel.util.MessageHelper; import org.apache.camel.util.ObjectHelper; import org.apache.camel.util.ServiceHelper; import org.slf4j.Logger; @@ -268,6 +269,10 @@ public class RoutingSlip extends ServiceSupport implements AsyncProcessor, Trace // exchange being routed. copy.setExchangeId(current.getExchangeId()); copyOutToIn(copy, current); + + // ensure stream caching is reset + MessageHelper.resetStreamCache(copy.getIn()); + return copy; }
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-6604_55751402.diff
bugs-dot-jar_data_CAMEL-5704_708e756d
--- BugID: CAMEL-5704 Summary: 'Split inside Split - Parallel processing issue - Thread is getting wrong Exchange when leaving inner split ' Description: "A small JUnit recreation case is attached.\nWhen using embedded split inside a split with parallel processing, threads are getting a wrong exchange (or wrong exchange copy) just after leaving the inner split and returning to the parent split.\n\nIn the test case, we split a file by comma in a parent split (Block split), then by line separator in inner split (Line Split). \nWe expect 2 files in output, each of them containing the respective Blocks.\n\nHowever, once inner split is complete, each thread is supposed to add a 11th line in the result(i).txt file saying split(i) is complete. \nBug is that one of the thread ends up with parent split Exchange (copy?) from the other thread, and appends wrong information into the wrong file.\n\nExpected:\n---------\n(result0.txt)\nBlock1 Line 1:Status=OK\nBlock1 Line 2:Status=OK\nBlock1 Line 0:Status=OK\nBlock1 Line 4:Status=OK\nBlock1 Line 3:Status=OK\nBlock1 Line 8:Status=OK\nBlock1 Line 5:Status=OK\nBlock1 Line 6:Status=OK\nBlock1 Line 7:Status=OK\nBlock1 Line 9:Status=OK\n0 complete\n\n(result1.txt)\nBlock2 Line 0:Status=OK\nBlock2 Line 3:Status=OK\nBlock2 Line 1:Status=OK\nBlock2 Line 2:Status=OK\nBlock2 Line 6:Status=OK\nBlock2 Line 4:Status=OK\nBlock2 Line 7:Status=OK\nBlock2 Line 9:Status=OK\nBlock2 Line 5:Status=OK\nBlock2 Line 8:Status=OK\n1 complete\n\nActual:\n-------\n(result0.txt)\nBlock1 Line 1:Status=OK\nBlock1 Line 2:Status=OK\nBlock1 Line 0:Status=OK\nBlock1 Line 4:Status=OK\nBlock1 Line 3:Status=OK\nBlock1 Line 8:Status=OK\nBlock1 Line 5:Status=OK\nBlock1 Line 6:Status=OK\nBlock1 Line 7:Status=OK\nBlock1 Line 9:Status=OK\n0 complete0 complete\n\n(result1.txt)\nBlock2 Line 0:Status=OK\nBlock2 Line 3:Status=OK\nBlock2 Line 1:Status=OK\nBlock2 Line 2:Status=OK\nBlock2 Line 6:Status=OK\nBlock2 Line 4:Status=OK\nBlock2 Line 7:Status=OK\nBlock2 Line 9:Status=OK\nBlock2 Line 5:Status=OK\nBlock2 Line 8:Status=OK\n\n\nThis issue exist in 2.8.x, and probably in 2.10.x as well.\nThis is a Splitter/MulticastProcessor or Pipeline issue but not quite familiar with the code, I am having hard time tracking it. " diff --git a/camel-core/src/main/java/org/apache/camel/processor/MulticastProcessor.java b/camel-core/src/main/java/org/apache/camel/processor/MulticastProcessor.java index b2930f6..3993086 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/MulticastProcessor.java +++ b/camel-core/src/main/java/org/apache/camel/processor/MulticastProcessor.java @@ -1002,6 +1002,10 @@ public class MulticastProcessor extends ServiceSupport implements AsyncProcessor Map<Object, AggregationStrategy> map = CastUtils.cast(property); if (map == null) { map = new HashMap<Object, AggregationStrategy>(); + } else { + // it is not safe to use the map directly as the exchange doesn't have the deep copy of it's properties + // we just create a new copy if we need to change the map + map = new HashMap<Object, AggregationStrategy>(map); } // store the strategy using this processor as the key // (so we can store multiple strategies on the same exchange)
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-5704_708e756d.diff
bugs-dot-jar_data_CAMEL-9444_baece126
--- BugID: CAMEL-9444 Summary: Incorrect exceptions handling from Splitter Description: "Steps to reproduce:\n1. Create global onException handler\n{code}\n<onException>\n \ <exception>java.lang.Exception</exception>\n <handled>\n <constant>false</constant>\n \ </handled>\n <log message=\"SOME MESSAGE\"/>\n</onException>\n{code}\n\n2. Create 2 routes with Splitter (set shareUnitOfWork to TRUE, important)\n{code}\n<route>\n \ <from uri=\"timer://foo?repeatCount=1\"/>\n\n <!-- Add some value list to body here -->\n\n <split shareUnitOfWork=\"true\" stopOnException=\"true\">\n \ <simple>${body}</simple>\n <to uri=\"direct:handleSplit\"/>\n </split>\n</route>\n\n<route>\n \ <from uri=\"direct:handleSplit\"/>\n <throwException ref=\"myException\"/>\n</route>\n{code}\n\nExpected: string \"SOME MESSAGE\" is logged\nActual: <log message=\"SOME MESSAGE\"/> is not executed at all " diff --git a/camel-core/src/main/java/org/apache/camel/model/MulticastDefinition.java b/camel-core/src/main/java/org/apache/camel/model/MulticastDefinition.java index 55f6ad0..42b3e59 100644 --- a/camel-core/src/main/java/org/apache/camel/model/MulticastDefinition.java +++ b/camel-core/src/main/java/org/apache/camel/model/MulticastDefinition.java @@ -31,6 +31,7 @@ import org.apache.camel.processor.CamelInternalProcessor; import org.apache.camel.processor.MulticastProcessor; import org.apache.camel.processor.aggregate.AggregationStrategy; import org.apache.camel.processor.aggregate.AggregationStrategyBeanAdapter; +import org.apache.camel.processor.aggregate.ShareUnitOfWorkAggregationStrategy; import org.apache.camel.processor.aggregate.UseLatestAggregationStrategy; import org.apache.camel.spi.Metadata; import org.apache.camel.spi.RouteContext; @@ -287,11 +288,7 @@ public class MulticastDefinition extends OutputDefinition<MulticastDefinition> i } protected Processor createCompositeProcessor(RouteContext routeContext, List<Processor> list) throws Exception { - AggregationStrategy strategy = createAggregationStrategy(routeContext); - if (strategy == null) { - // default to use latest aggregation strategy - strategy = new UseLatestAggregationStrategy(); - } + final AggregationStrategy strategy = createAggregationStrategy(routeContext); boolean isParallelProcessing = getParallelProcessing() != null && getParallelProcessing(); boolean isShareUnitOfWork = getShareUnitOfWork() != null && getShareUnitOfWork(); @@ -333,14 +330,23 @@ public class MulticastDefinition extends OutputDefinition<MulticastDefinition> i } } - if (strategy != null && strategy instanceof CamelContextAware) { + if (strategy == null) { + // default to use latest aggregation strategy + strategy = new UseLatestAggregationStrategy(); + } + + if (strategy instanceof CamelContextAware) { ((CamelContextAware) strategy).setCamelContext(routeContext.getCamelContext()); } + if (shareUnitOfWork != null && shareUnitOfWork) { + // wrap strategy in share unit of work + strategy = new ShareUnitOfWorkAggregationStrategy(strategy); + } + return strategy; } - public AggregationStrategy getAggregationStrategy() { return aggregationStrategy; } diff --git a/camel-core/src/main/java/org/apache/camel/model/ProcessorDefinition.java b/camel-core/src/main/java/org/apache/camel/model/ProcessorDefinition.java index 0705d69..eacb304 100644 --- a/camel-core/src/main/java/org/apache/camel/model/ProcessorDefinition.java +++ b/camel-core/src/main/java/org/apache/camel/model/ProcessorDefinition.java @@ -54,7 +54,6 @@ import org.apache.camel.model.language.ExpressionDefinition; import org.apache.camel.model.language.LanguageExpression; import org.apache.camel.model.language.SimpleExpression; import org.apache.camel.model.rest.RestDefinition; -import org.apache.camel.processor.CamelInternalProcessor; import org.apache.camel.processor.InterceptEndpointProcessor; import org.apache.camel.processor.Pipeline; import org.apache.camel.processor.aggregate.AggregationStrategy; @@ -535,16 +534,10 @@ public abstract class ProcessorDefinition<Type extends ProcessorDefinition<Type> processor = createProcessor(routeContext); } - // unwrap internal processor so we can set id on the actual processor - Processor idProcessor = processor; - if (processor instanceof CamelInternalProcessor) { - idProcessor = ((CamelInternalProcessor) processor).getProcessor(); - } - // inject id - if (idProcessor instanceof IdAware) { + if (processor instanceof IdAware) { String id = this.idOrCreate(routeContext.getCamelContext().getNodeIdFactory()); - ((IdAware) idProcessor).setId(id); + ((IdAware) processor).setId(id); } if (processor == null) { diff --git a/camel-core/src/main/java/org/apache/camel/model/RecipientListDefinition.java b/camel-core/src/main/java/org/apache/camel/model/RecipientListDefinition.java index 49d75f9..0d02a48 100644 --- a/camel-core/src/main/java/org/apache/camel/model/RecipientListDefinition.java +++ b/camel-core/src/main/java/org/apache/camel/model/RecipientListDefinition.java @@ -34,6 +34,7 @@ import org.apache.camel.processor.Pipeline; import org.apache.camel.processor.RecipientList; import org.apache.camel.processor.aggregate.AggregationStrategy; import org.apache.camel.processor.aggregate.AggregationStrategyBeanAdapter; +import org.apache.camel.processor.aggregate.ShareUnitOfWorkAggregationStrategy; import org.apache.camel.processor.aggregate.UseLatestAggregationStrategy; import org.apache.camel.spi.Metadata; import org.apache.camel.spi.RouteContext; @@ -192,8 +193,9 @@ public class RecipientListDefinition<Type extends ProcessorDefinition<Type>> ext throw new IllegalArgumentException("Cannot find AggregationStrategy in Registry with name: " + strategyRef); } } + if (strategy == null) { - // fallback to use latest + // default to use latest aggregation strategy strategy = new UseLatestAggregationStrategy(); } @@ -201,6 +203,11 @@ public class RecipientListDefinition<Type extends ProcessorDefinition<Type>> ext ((CamelContextAware) strategy).setCamelContext(routeContext.getCamelContext()); } + if (shareUnitOfWork != null && shareUnitOfWork) { + // wrap strategy in share unit of work + strategy = new ShareUnitOfWorkAggregationStrategy(strategy); + } + return strategy; } diff --git a/camel-core/src/main/java/org/apache/camel/model/SplitDefinition.java b/camel-core/src/main/java/org/apache/camel/model/SplitDefinition.java index ccfd045..5e49de2 100644 --- a/camel-core/src/main/java/org/apache/camel/model/SplitDefinition.java +++ b/camel-core/src/main/java/org/apache/camel/model/SplitDefinition.java @@ -31,6 +31,7 @@ import org.apache.camel.processor.CamelInternalProcessor; import org.apache.camel.processor.Splitter; import org.apache.camel.processor.aggregate.AggregationStrategy; import org.apache.camel.processor.aggregate.AggregationStrategyBeanAdapter; +import org.apache.camel.processor.aggregate.ShareUnitOfWorkAggregationStrategy; import org.apache.camel.spi.Metadata; import org.apache.camel.spi.RouteContext; import org.apache.camel.util.CamelContextHelper; @@ -119,6 +120,12 @@ public class SplitDefinition extends ExpressionNode implements ExecutorServiceAw Splitter answer = new Splitter(routeContext.getCamelContext(), exp, childProcessor, aggregationStrategy, isParallelProcessing, threadPool, shutdownThreadPool, isStreaming, isStopOnException(), timeout, onPrepare, isShareUnitOfWork, isParallelAggregate); +// if (isShareUnitOfWork) { + // wrap answer in a sub unit of work, since we share the unit of work +// CamelInternalProcessor internalProcessor = new CamelInternalProcessor(answer); +// internalProcessor.addAdvice(new CamelInternalProcessor.SubUnitOfWorkProcessorAdvice()); +// return internalProcessor; +// } return answer; } @@ -144,6 +151,11 @@ public class SplitDefinition extends ExpressionNode implements ExecutorServiceAw ((CamelContextAware) strategy).setCamelContext(routeContext.getCamelContext()); } + if (strategy != null && shareUnitOfWork != null && shareUnitOfWork) { + // wrap strategy in share unit of work + strategy = new ShareUnitOfWorkAggregationStrategy(strategy); + } + return strategy; } diff --git a/camel-core/src/main/java/org/apache/camel/processor/RecipientList.java b/camel-core/src/main/java/org/apache/camel/processor/RecipientList.java index 98f8e45..ded8ca9 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/RecipientList.java +++ b/camel-core/src/main/java/org/apache/camel/processor/RecipientList.java @@ -166,16 +166,8 @@ public class RecipientList extends ServiceSupport implements AsyncProcessor, IdA return true; } - AsyncProcessor target = rlp; - if (isShareUnitOfWork()) { - // wrap answer in a sub unit of work, since we share the unit of work - CamelInternalProcessor internalProcessor = new CamelInternalProcessor(rlp); - internalProcessor.addAdvice(new CamelInternalProcessor.SubUnitOfWorkProcessorAdvice()); - target = internalProcessor; - } - // now let the multicast process the exchange - return target.process(exchange, callback); + return rlp.process(exchange, callback); } protected Endpoint resolveEndpoint(Exchange exchange, Object recipient) { diff --git a/camel-core/src/main/java/org/apache/camel/processor/Splitter.java b/camel-core/src/main/java/org/apache/camel/processor/Splitter.java index 55a9bd9..40ca426 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/Splitter.java +++ b/camel-core/src/main/java/org/apache/camel/processor/Splitter.java @@ -36,6 +36,7 @@ import org.apache.camel.Processor; import org.apache.camel.RuntimeCamelException; import org.apache.camel.Traceable; import org.apache.camel.processor.aggregate.AggregationStrategy; +import org.apache.camel.processor.aggregate.ShareUnitOfWorkAggregationStrategy; import org.apache.camel.processor.aggregate.UseOriginalAggregationStrategy; import org.apache.camel.spi.RouteContext; import org.apache.camel.util.ExchangeHelper; @@ -97,7 +98,10 @@ public class Splitter extends MulticastProcessor implements AsyncProcessor, Trac // and propagate exceptions which is done by a per exchange specific aggregation strategy // to ensure it supports async routing if (strategy == null) { - UseOriginalAggregationStrategy original = new UseOriginalAggregationStrategy(exchange, true); + AggregationStrategy original = new UseOriginalAggregationStrategy(exchange, true); + if (isShareUnitOfWork()) { + original = new ShareUnitOfWorkAggregationStrategy(original); + } setAggregationStrategyOnExchange(exchange, original); } diff --git a/camel-core/src/main/java/org/apache/camel/processor/aggregate/ShareUnitOfWorkAggregationStrategy.java b/camel-core/src/main/java/org/apache/camel/processor/aggregate/ShareUnitOfWorkAggregationStrategy.java new file mode 100644 index 0000000..4a1187f --- /dev/null +++ b/camel-core/src/main/java/org/apache/camel/processor/aggregate/ShareUnitOfWorkAggregationStrategy.java @@ -0,0 +1,77 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.processor.aggregate; + +import org.apache.camel.Exchange; + +import static org.apache.camel.util.ExchangeHelper.hasExceptionBeenHandledByErrorHandler; + +/** + * An {@link AggregationStrategy} which are used when the option <tt>shareUnitOfWork</tt> is enabled + * on EIPs such as multicast, splitter or recipientList. + * <p/> + * This strategy wraps the actual in use strategy to provide the logic needed for making shareUnitOfWork work. + * <p/> + * This strategy is <b>not</b> intended for end users to use. + */ +public final class ShareUnitOfWorkAggregationStrategy implements AggregationStrategy { + + private final AggregationStrategy strategy; + + public ShareUnitOfWorkAggregationStrategy(AggregationStrategy strategy) { + this.strategy = strategy; + } + + public Exchange aggregate(Exchange oldExchange, Exchange newExchange) { + // aggreagate using the actual strategy first + Exchange answer = strategy.aggregate(oldExchange, newExchange); + // ensure any errors is propagated from the new exchange to the answer + propagateFailure(answer, newExchange); + + return answer; + } + + protected void propagateFailure(Exchange answer, Exchange newExchange) { + // if new exchange failed then propagate all the error related properties to the answer + boolean exceptionHandled = hasExceptionBeenHandledByErrorHandler(newExchange); + if (newExchange.isFailed() || newExchange.isRollbackOnly() || exceptionHandled) { + if (newExchange.getException() != null) { + answer.setException(newExchange.getException()); + } + if (newExchange.getProperty(Exchange.EXCEPTION_CAUGHT) != null) { + answer.setProperty(Exchange.EXCEPTION_CAUGHT, newExchange.getProperty(Exchange.EXCEPTION_CAUGHT)); + } + if (newExchange.getProperty(Exchange.FAILURE_ENDPOINT) != null) { + answer.setProperty(Exchange.FAILURE_ENDPOINT, newExchange.getProperty(Exchange.FAILURE_ENDPOINT)); + } + if (newExchange.getProperty(Exchange.FAILURE_ROUTE_ID) != null) { + answer.setProperty(Exchange.FAILURE_ROUTE_ID, newExchange.getProperty(Exchange.FAILURE_ROUTE_ID)); + } + if (newExchange.getProperty(Exchange.ERRORHANDLER_HANDLED) != null) { + answer.setProperty(Exchange.ERRORHANDLER_HANDLED, newExchange.getProperty(Exchange.ERRORHANDLER_HANDLED)); + } + if (newExchange.getProperty(Exchange.FAILURE_HANDLED) != null) { + answer.setProperty(Exchange.FAILURE_HANDLED, newExchange.getProperty(Exchange.FAILURE_HANDLED)); + } + } + } + + @Override + public String toString() { + return "ShareUnitOfWorkAggregationStrategy"; + } +}
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-9444_baece126.diff
bugs-dot-jar_data_CAMEL-7130_7c9326f4
--- BugID: CAMEL-7130 Summary: Set XsltBuilder allowStax attribute to be true by default Description: It could be more effective and safe to use the stax API by default. diff --git a/camel-core/src/main/java/org/apache/camel/builder/xml/XsltBuilder.java b/camel-core/src/main/java/org/apache/camel/builder/xml/XsltBuilder.java index 8984828..3a7b9a4 100644 --- a/camel-core/src/main/java/org/apache/camel/builder/xml/XsltBuilder.java +++ b/camel-core/src/main/java/org/apache/camel/builder/xml/XsltBuilder.java @@ -79,7 +79,7 @@ public class XsltBuilder implements Processor { private URIResolver uriResolver; private boolean deleteOutputFile; private ErrorListener errorListener = new XsltErrorListener(); - private boolean allowStAX; + private boolean allowStAX = true; public XsltBuilder() { }
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-7130_7c9326f4.diff
bugs-dot-jar_data_CAMEL-5826_a04674f2
--- BugID: CAMEL-5826 Summary: Apache Camel 2.9 Splitter with tokenize dont work with namespaces Description: | when trying to tokenize a stream having namespaces, no tokens are produced with inheritNamespaceTagName property. ------------------------------------------------------------------- <route id="hrp.connectorsCtxt.sddRcvFile2"> <from uri="file:C:\Temp\esb\sdd\in?recursive=true&amp;preMove=.processing&amp;move=../.processed" /> <camel:split streaming="true"> <tokenize token="suiviDemande" inheritNamespaceTagName="suivisDemandes" xml="true"/> <log message="${header.CamelSplitIndex} : ${in.body}" /> </camel:split> </route> ------------------------------------------------------------------- diff --git a/camel-core/src/main/java/org/apache/camel/support/TokenXMLPairExpressionIterator.java b/camel-core/src/main/java/org/apache/camel/support/TokenXMLPairExpressionIterator.java index da5afaa..9ae1477 100644 --- a/camel-core/src/main/java/org/apache/camel/support/TokenXMLPairExpressionIterator.java +++ b/camel-core/src/main/java/org/apache/camel/support/TokenXMLPairExpressionIterator.java @@ -41,6 +41,7 @@ public class TokenXMLPairExpressionIterator extends TokenPairExpressionIterator private static final Pattern NAMESPACE_PATTERN = Pattern.compile("xmlns(:\\w+|)=\\\"(.*?)\\\""); private static final String SCAN_TOKEN_REGEX = "(\\s+.*?|)>"; + private static final String SCAN_TOKEN_NS_PREFIX_REGEX = "(.{1,15}?:|)"; protected final String inheritNamespaceToken; public TokenXMLPairExpressionIterator(String startToken, String endToken, String inheritNamespaceToken) { @@ -81,15 +82,22 @@ public class TokenXMLPairExpressionIterator extends TokenPairExpressionIterator XMLTokenPairIterator(String startToken, String endToken, String inheritNamespaceToken, InputStream in, String charset) { super(startToken, endToken, true, in, charset); - // remove any ending > as we need to support attributes on the tags, so we need to use a reg exp pattern - String token = startToken.substring(0, startToken.length() - 1) + SCAN_TOKEN_REGEX; - this.startTokenPattern = Pattern.compile(token); - this.scanEndToken = endToken.substring(0, endToken.length() - 1) + SCAN_TOKEN_REGEX; + // remove any beginning < and ending > as we need to support ns prefixes and attributes, so we use a reg exp patterns + StringBuilder tokenSb = new StringBuilder("<").append(SCAN_TOKEN_NS_PREFIX_REGEX). + append(startToken.substring(1, startToken.length() - 1)).append(SCAN_TOKEN_REGEX); + this.startTokenPattern = Pattern.compile(tokenSb.toString()); + + tokenSb = new StringBuilder("</").append(SCAN_TOKEN_NS_PREFIX_REGEX). + append(endToken.substring(2, endToken.length() - 1)).append(SCAN_TOKEN_REGEX); + this.scanEndToken = tokenSb.toString(); + this.inheritNamespaceToken = inheritNamespaceToken; if (inheritNamespaceToken != null) { - token = inheritNamespaceToken.substring(0, inheritNamespaceToken.length() - 1) + SCAN_TOKEN_REGEX; + // the inherit namespace token may itself have a namespace prefix + tokenSb = new StringBuilder("<").append(SCAN_TOKEN_NS_PREFIX_REGEX). + append(inheritNamespaceToken.substring(1, inheritNamespaceToken.length() - 1)).append(SCAN_TOKEN_REGEX); // the namespaces on the parent tag can be in multi line, so we need to instruct the dot to support multilines - this.inheritNamespaceTokenPattern = Pattern.compile(token, Pattern.MULTILINE | Pattern.DOTALL); + this.inheritNamespaceTokenPattern = Pattern.compile(tokenSb.toString(), Pattern.MULTILINE | Pattern.DOTALL); } } @@ -125,17 +133,26 @@ public class TokenXMLPairExpressionIterator extends TokenPairExpressionIterator next = next.substring(index); } + // make sure the end tag matches the begin tag if the tag has a namespace prefix + String tag = ObjectHelper.before(next, ">"); + StringBuilder endTagSb = new StringBuilder("</"); + int firstSpaceIndex = tag.indexOf(" "); + if (firstSpaceIndex > 0) { + endTagSb.append(tag.substring(1, firstSpaceIndex)).append(">"); + } else { + endTagSb.append(tag.substring(1, tag.length())).append(">"); + } + // build answer accordingly to whether namespaces should be inherited or not StringBuilder sb = new StringBuilder(); if (inheritNamespaceToken != null && rootTokenNamespaces != null) { // append root namespaces to local start token - String tag = ObjectHelper.before(next, ">"); // grab the text String text = ObjectHelper.after(next, ">"); // build result with inherited namespaces - next = sb.append(tag).append(rootTokenNamespaces).append(">").append(text).append(endToken).toString(); + next = sb.append(tag).append(rootTokenNamespaces).append(">").append(text).append(endTagSb.toString()).toString(); } else { - next = sb.append(next).append(endToken).toString(); + next = sb.append(next).append(endTagSb.toString()).toString(); } return next;
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-5826_a04674f2.diff
bugs-dot-jar_data_CAMEL-7429_43956f93
--- BugID: CAMEL-7429 Summary: 'Camel Properties Component concatenation issue ' Description: "Hi,\n\nSuppose you have a properties file of this type\n\n{code}\n#PROPERTIES CONCATENATION\nprop1=file:\nprop2=dirname\nconcat.property={{prop1}}{{prop2}}\n\n#PROPERTIES WITHOUT CONCATENATION\nproperty.complete=file:dirname\n{code}\n\nand you want to use the property concat.property. Using Camel 2.10.3 loading this property doesn't create any kind of problem. When I upgrade to Camel 2.12.3 I get an exception, that you can reproduce with the following informations.\n\nIn *DefaultPropertiesParser* class of org.apache.camel.component.properties package, I found a strange behaviour relative to that specific kind of property. When I execute a test like the following, (the first try to use concatenated property and the second try to use property without concatenation):\n\n{code:title=PropertiesComponentConcatenatePropertiesTest.java}\nimport org.apache.camel.CamelContext;\nimport org.apache.camel.ContextTestSupport;\nimport org.apache.camel.builder.RouteBuilder;\n\npublic class PropertiesComponentConcatenatePropertiesTest extends ContextTestSupport {\n \n @Override\n protected CamelContext createCamelContext() throws Exception {\n CamelContext context = super.createCamelContext();\n \ context.addComponent(\"properties\", new PropertiesComponent(\"classpath:org/apache/camel/component/properties/concatenation.properties\"));\n \ return context;\n }\n \n @Override\n protected void setUp() throws Exception {\n System.setProperty(\"environment\", \"junit\");\n super.setUp();\n \ }\n \n @Override\n protected void tearDown() throws Exception {\n System.clearProperty(\"environment\");\n \ super.tearDown();\n }\n \n public void testConcatPropertiesComponentDefault() throws Exception {\n context.addRoutes(new RouteBuilder() {\n @Override\n \ public void configure() throws Exception {\n from(\"direct:start\").setBody(simple(\"${properties:concat.property}\"))\n \ .to(\"mock:result\");\n }\n });\n context.start();\n\n \ getMockEndpoint(\"mock:result\").expectedBodiesReceived(\"file:dirname\");\n\n \ template.sendBody(\"direct:start\", \"Test\");\n\n assertMockEndpointsSatisfied();\n \ }\n \n public void testWithoutConcatPropertiesComponentDefault() throws Exception {\n context.addRoutes(new RouteBuilder() {\n @Override\n \ public void configure() throws Exception {\n from(\"direct:start\").setBody(simple(\"${properties:property.complete}\"))\n \ .to(\"mock:result\");\n }\n });\n context.start();\n\n \ getMockEndpoint(\"mock:result\").expectedBodiesReceived(\"file:dirname\");\n\n \ template.sendBody(\"direct:start\", \"Test\");\n\n assertMockEndpointsSatisfied();\n \ }\n}\n{code}\n\nThe first test return the following exception:\n{code}\norg.apache.camel.CamelExecutionException: Exception occurred during execution on the exchange: Exchange[Message: Test]\n\tat org.apache.camel.util.ObjectHelper.wrapCamelExecutionException(ObjectHelper.java:1379)\n\tat org.apache.camel.util.ExchangeHelper.extractResultBody(ExchangeHelper.java:622)\n\tat org.apache.camel.impl.DefaultProducerTemplate.extractResultBody(DefaultProducerTemplate.java:467)\n\tat org.apache.camel.impl.DefaultProducerTemplate.extractResultBody(DefaultProducerTemplate.java:463)\n\tat org.apache.camel.impl.DefaultProducerTemplate.sendBody(DefaultProducerTemplate.java:139)\n\tat org.apache.camel.impl.DefaultProducerTemplate.sendBody(DefaultProducerTemplate.java:144)\n\tat org.apache.camel.component.properties.PropertiesComponentConcatenatePropertiesTest.testConcatPropertiesComponentDefault(PropertiesComponentConcatenatePropertiesTest.java:56)\n\tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n\tat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)\n\tat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\n\tat java.lang.reflect.Method.invoke(Method.java:606)\n\tat junit.framework.TestCase.runTest(TestCase.java:176)\n\tat junit.framework.TestCase.runBare(TestCase.java:141)\n\tat org.apache.camel.TestSupport.runBare(TestSupport.java:58)\n\tat junit.framework.TestResult$1.protect(TestResult.java:122)\n\tat junit.framework.TestResult.runProtected(TestResult.java:142)\n\tat junit.framework.TestResult.run(TestResult.java:125)\n\tat junit.framework.TestCase.run(TestCase.java:129)\n\tat junit.framework.TestSuite.runTest(TestSuite.java:255)\n\tat junit.framework.TestSuite.run(TestSuite.java:250)\n\tat org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:84)\n\tat org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)\n\tat org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)\n\tat org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)\n\tat org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)\n\tat org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)\n\tat org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)\nCaused by: org.apache.camel.RuntimeCamelException: java.lang.IllegalArgumentException: Expecting }} but found end of string from text: prop1}}{{prop2\n\tat org.apache.camel.util.ObjectHelper.wrapRuntimeCamelException(ObjectHelper.java:1363)\n\tat org.apache.camel.builder.ExpressionBuilder$78.evaluate(ExpressionBuilder.java:1784)\n\tat org.apache.camel.support.ExpressionAdapter.evaluate(ExpressionAdapter.java:36)\n\tat org.apache.camel.builder.SimpleBuilder.evaluate(SimpleBuilder.java:83)\n\tat org.apache.camel.processor.SetBodyProcessor.process(SetBodyProcessor.java:46)\n\tat org.apache.camel.processor.RedeliveryErrorHandler.process(RedeliveryErrorHandler.java:398)\n\tat org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:191)\n\tat org.apache.camel.processor.Pipeline.process(Pipeline.java:118)\n\tat org.apache.camel.processor.Pipeline.process(Pipeline.java:80)\n\tat org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:191)\n\tat org.apache.camel.component.direct.DirectProducer.process(DirectProducer.java:51)\n\tat org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:191)\n\tat org.apache.camel.processor.UnitOfWorkProducer.process(UnitOfWorkProducer.java:73)\n\tat org.apache.camel.impl.ProducerCache$2.doInProducer(ProducerCache.java:378)\n\tat org.apache.camel.impl.ProducerCache$2.doInProducer(ProducerCache.java:1)\n\tat org.apache.camel.impl.ProducerCache.doInProducer(ProducerCache.java:242)\n\tat org.apache.camel.impl.ProducerCache.sendExchange(ProducerCache.java:346)\n\tat org.apache.camel.impl.ProducerCache.send(ProducerCache.java:184)\n\tat org.apache.camel.impl.DefaultProducerTemplate.send(DefaultProducerTemplate.java:124)\n\tat org.apache.camel.impl.DefaultProducerTemplate.sendBody(DefaultProducerTemplate.java:137)\n\t... 22 more\nCaused by: java.lang.IllegalArgumentException: Expecting }} but found end of string from text: prop1}}{{prop2\n\tat org.apache.camel.component.properties.DefaultPropertiesParser.doParseUri(DefaultPropertiesParser.java:90)\n\tat org.apache.camel.component.properties.DefaultPropertiesParser.parseUri(DefaultPropertiesParser.java:51)\n\tat org.apache.camel.component.properties.DefaultPropertiesParser.parseUri(DefaultPropertiesParser.java:38)\n\tat org.apache.camel.component.properties.DefaultPropertiesParser.createPlaceholderPart(DefaultPropertiesParser.java:189)\n\tat org.apache.camel.component.properties.DefaultPropertiesParser.doParseUri(DefaultPropertiesParser.java:105)\n\tat org.apache.camel.component.properties.DefaultPropertiesParser.parseUri(DefaultPropertiesParser.java:51)\n\tat org.apache.camel.component.properties.PropertiesComponent.parseUri(PropertiesComponent.java:158)\n\tat org.apache.camel.component.properties.PropertiesComponent.parseUri(PropertiesComponent.java:117)\n\tat org.apache.camel.builder.ExpressionBuilder$78.evaluate(ExpressionBuilder.java:1781)\n\t... 40 more\n{code}\n\nIt seems that *DefaultPropertiesParser* doesn't like concatenation of properties. I've forked Camel project on GitHub and I've added the unit test posted above. Here is the link: https://github.com/ancosen/camel\n\nInvestigating the history of the particular class I found that the problem should arise from:\n *CAMEL-5328 supports resolution of nested properties in PropertiesComponent*\n\nHere is the link of the commit:\nhttps://github.com/apache/camel/commit/83f4b0f485521967d05de4e65025c4558a75ff3c\n\nThanks.\nBye" diff --git a/camel-core/src/main/java/org/apache/camel/component/properties/DefaultPropertiesParser.java b/camel-core/src/main/java/org/apache/camel/component/properties/DefaultPropertiesParser.java index f7bffa7..1ee227a 100644 --- a/camel-core/src/main/java/org/apache/camel/component/properties/DefaultPropertiesParser.java +++ b/camel-core/src/main/java/org/apache/camel/component/properties/DefaultPropertiesParser.java @@ -16,189 +16,278 @@ */ package org.apache.camel.component.properties; -import java.util.ArrayList; -import java.util.List; +import java.util.HashSet; import java.util.Properties; +import java.util.Set; -import org.apache.camel.util.ObjectHelper; -import org.apache.camel.util.StringHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static java.lang.String.format; + /** * A parser to parse a string which contains property placeholders - * - * @version */ public class DefaultPropertiesParser implements AugmentedPropertyNameAwarePropertiesParser { protected final Logger log = LoggerFactory.getLogger(getClass()); - + @Override public String parseUri(String text, Properties properties, String prefixToken, String suffixToken) throws IllegalArgumentException { return parseUri(text, properties, prefixToken, suffixToken, null, null, false); } - public String parseUri(String text, Properties properties, String prefixToken, String suffixToken, - String propertyPrefix, String propertySuffix, boolean fallbackToUnaugmentedProperty) throws IllegalArgumentException { - String answer = text; - boolean done = false; - - // the placeholders can contain nested placeholders so we need to do recursive parsing - // we must therefore also do circular reference check and must keep a list of visited keys - List<String> visited = new ArrayList<String>(); - while (!done) { - List<String> replaced = new ArrayList<String>(); - answer = doParseUri(answer, properties, replaced, prefixToken, suffixToken, propertyPrefix, propertySuffix, fallbackToUnaugmentedProperty); - - // check the replaced with the visited to avoid circular reference - for (String replace : replaced) { - if (visited.contains(replace)) { - throw new IllegalArgumentException("Circular reference detected with key [" + replace + "] from text: " + text); - } - } - // okay all okay so add the replaced as visited - visited.addAll(replaced); - - // we are done when we can no longer find any prefix tokens in the answer - done = findTokenPosition(answer, 0, prefixToken) == -1; - } - return answer; + public String parseUri(String text, Properties properties, String prefixToken, String suffixToken, String propertyPrefix, String propertySuffix, + boolean fallbackToUnaugmentedProperty) throws IllegalArgumentException { + ParsingContext context = new ParsingContext(properties, prefixToken, suffixToken, propertyPrefix, propertySuffix, fallbackToUnaugmentedProperty); + return context.parse(text); } public String parseProperty(String key, String value, Properties properties) { return value; } - private String doParseUri(String uri, Properties properties, List<String> replaced, String prefixToken, String suffixToken, - String propertyPrefix, String propertySuffix, boolean fallbackToUnaugmentedProperty) { - StringBuilder sb = new StringBuilder(); - - int pivot = 0; - int size = uri.length(); - while (pivot < size) { - int idx = findTokenPosition(uri, pivot, prefixToken); - if (idx < 0) { - sb.append(createConstantPart(uri, pivot, size)); - break; - } else { - if (pivot < idx) { - sb.append(createConstantPart(uri, pivot, idx)); - } - pivot = idx + prefixToken.length(); - int endIdx = findTokenPosition(uri, pivot, suffixToken); - if (endIdx < 0) { - throw new IllegalArgumentException("Expecting " + suffixToken + " but found end of string from text: " + uri); - } - String key = uri.substring(pivot, endIdx); - String augmentedKey = key; - - if (propertyPrefix != null) { - log.debug("Augmenting property key [{}] with prefix: {}", key, propertyPrefix); - augmentedKey = propertyPrefix + augmentedKey; - } - - if (propertySuffix != null) { - log.debug("Augmenting property key [{}] with suffix: {}", key, propertySuffix); - augmentedKey = augmentedKey + propertySuffix; - } + /** + * This inner class helps replacing properties. + */ + private final class ParsingContext { + private final Properties properties; + private final String prefixToken; + private final String suffixToken; + private final String propertyPrefix; + private final String propertySuffix; + private final boolean fallbackToUnaugmentedProperty; - String part = createPlaceholderPart(augmentedKey, properties, replaced, prefixToken, suffixToken); - - // Note: Only fallback to unaugmented when the original key was actually augmented - if (part == null && fallbackToUnaugmentedProperty && (propertyPrefix != null || propertySuffix != null)) { - log.debug("Property wth key [{}] not found, attempting with unaugmented key: {}", augmentedKey, key); - part = createPlaceholderPart(key, properties, replaced, prefixToken, suffixToken); - } - - if (part == null) { - StringBuilder esb = new StringBuilder(); - esb.append("Property with key [").append(augmentedKey).append("] "); - if (fallbackToUnaugmentedProperty && (propertyPrefix != null || propertySuffix != null)) { - esb.append("(and original key [").append(key).append("]) "); - } - esb.append("not found in properties from text: ").append(uri); - throw new IllegalArgumentException(esb.toString()); + public ParsingContext(Properties properties, String prefixToken, String suffixToken, String propertyPrefix, String propertySuffix, + boolean fallbackToUnaugmentedProperty) { + this.properties = properties; + this.prefixToken = prefixToken; + this.suffixToken = suffixToken; + this.propertyPrefix = propertyPrefix; + this.propertySuffix = propertySuffix; + this.fallbackToUnaugmentedProperty = fallbackToUnaugmentedProperty; + } + + /** + * Parses the given input string and replaces all properties + * + * @param input Input string + * @return Evaluated string + */ + public String parse(String input) { + return doParse(input, new HashSet<String>()); + } + + /** + * Recursively parses the given input string and replaces all properties + * + * @param input Input string + * @param replacedPropertyKeys Already replaced property keys used for tracking circular references + * @return Evaluated string + */ + private String doParse(String input, Set<String> replacedPropertyKeys) { + String answer = input; + Property property; + while ((property = readProperty(answer)) != null) { + // Check for circular references + if (replacedPropertyKeys.contains(property.getKey())) { + throw new IllegalArgumentException("Circular reference detected with key [" + property.getKey() + "] from text: " + input); } - sb.append(part); - pivot = endIdx + suffixToken.length(); + + Set<String> newReplaced = new HashSet<String>(replacedPropertyKeys); + newReplaced.add(property.getKey()); + + String before = answer.substring(0, property.getBeginIndex()); + String after = answer.substring(property.getEndIndex()); + answer = before + doParse(property.getValue(), newReplaced) + after; } + return answer; } - return sb.toString(); - } - - private int findTokenPosition(String uri, int pivot, String token) { - int idx = uri.indexOf(token, pivot); - while (idx > 0) { - // grab part as the previous char + token + next char, to test if the token is quoted - String part = null; - int len = idx + token.length() + 1; - if (uri.length() >= len) { - part = uri.substring(idx - 1, len); + + /** + * Finds a property in the given string. It returns {@code null} if there's no property defined. + * + * @param input Input string + * @return A property in the given string or {@code null} if not found + */ + private Property readProperty(String input) { + // Find the index of the first valid suffix token + int suffix = getSuffixIndex(input); + + // If not found, ensure that there is no valid prefix token in the string + if (suffix == -1) { + if (getMatchingPrefixIndex(input, input.length()) != -1) { + throw new IllegalArgumentException(format("Missing %s from the text: %s", suffixToken, input)); + } + return null; } - if (StringHelper.isQuoted(part)) { - // the token was quoted, so regard it as a literal - // and then try to find from next position - pivot = idx + token.length() + 1; - idx = uri.indexOf(token, pivot); - } else { - // found token - return idx; + + // Find the index of the prefix token that matches the suffix token + int prefix = getMatchingPrefixIndex(input, suffix); + if (prefix == -1) { + throw new IllegalArgumentException(format("Missing %s from the text: %s", prefixToken, input)); } + + String key = input.substring(prefix + prefixToken.length(), suffix); + String value = getPropertyValue(key, input); + return new Property(prefix, suffix + suffixToken.length(), key, value); } - return idx; - } - - private boolean isNestProperty(String uri, String prefixToken, String suffixToken) { - if (ObjectHelper.isNotEmpty(uri)) { - uri = uri.trim(); - if (uri.startsWith(prefixToken) && uri.endsWith(suffixToken)) { - return true; + + /** + * Gets the first index of the suffix token that is not surrounded by quotes + * + * @param input Input string + * @return First index of the suffix token that is not surrounded by quotes + */ + private int getSuffixIndex(String input) { + int index = -1; + do { + index = input.indexOf(suffixToken, index + 1); + } while (index != -1 && isQuoted(input, index, suffixToken)); + return index; + } + + /** + * Gets the index of the prefix token that matches the suffix at the given index and that is not surrounded by quotes + * + * @param input Input string + * @param suffixIndex Index of the suffix token + * @return Index of the prefix token that matches the suffix at the given index and that is not surrounded by quotes + */ + private int getMatchingPrefixIndex(String input, int suffixIndex) { + int index = suffixIndex; + do { + index = input.lastIndexOf(prefixToken, index - 1); + } while (index != -1 && isQuoted(input, index, prefixToken)); + return index; + } + + /** + * Indicates whether or not the token at the given index is surrounded by single or double quotes + * + * @param input Input string + * @param index Index of the token + * @param token Token + * @return {@code true} + */ + private boolean isQuoted(String input, int index, String token) { + int beforeIndex = index - 1; + int afterIndex = index + token.length(); + if (beforeIndex >= 0 && afterIndex < input.length()) { + char before = input.charAt(beforeIndex); + char after = input.charAt(afterIndex); + return (before == after) && (before == '\'' || before == '"'); } + return false; } - return false; - } - - private String takeOffNestTokes(String uri, String prefixToken, String suffixToken) { - int start = prefixToken.length(); - int end = uri.length() - suffixToken.length(); - return uri.substring(start, end); - } - private String createConstantPart(String uri, int start, int end) { - return uri.substring(start, end); - } + /** + * Gets the value of the property with given key + * + * @param key Key of the property + * @param input Input string (used for exception message if value not found) + * @return Value of the property with the given key + */ + private String getPropertyValue(String key, String input) { + String augmentedKey = getAugmentedKey(key); + boolean shouldFallback = fallbackToUnaugmentedProperty && !key.equals(augmentedKey); + + String value = doGetPropertyValue(augmentedKey); + if (value == null && shouldFallback) { + log.debug("Property with key [{}] not found, attempting with unaugmented key: {}", augmentedKey, key); + value = doGetPropertyValue(key); + } + + if (value == null) { + StringBuilder esb = new StringBuilder(); + esb.append("Property with key [").append(augmentedKey).append("] "); + if (shouldFallback) { + esb.append("(and original key [").append(key).append("]) "); + } + esb.append("not found in properties from text: ").append(input); + throw new IllegalArgumentException(esb.toString()); + } - private String createPlaceholderPart(String key, Properties properties, List<String> replaced, String prefixToken, String suffixToken) { - // keep track of which parts we have replaced - replaced.add(key); - - String propertyValue = System.getProperty(key); - if (propertyValue != null) { - log.debug("Found a JVM system property: {} with value: {} to be used.", key, propertyValue); - } else if (properties != null) { - propertyValue = properties.getProperty(key); + return value; } - - // we need to check if the propertyValue is nested - // we need to check if there is cycle dependency of the nested properties - List<String> visited = new ArrayList<String>(); - while (isNestProperty(propertyValue, prefixToken, suffixToken)) { - visited.add(key); - // need to take off the token first - String value = takeOffNestTokes(propertyValue, prefixToken, suffixToken); - key = parseUri(value, properties, prefixToken, suffixToken); - if (visited.contains(key)) { - throw new IllegalArgumentException("Circular reference detected with key [" + key + "] from text: " + propertyValue); + + /** + * Gets the augmented key of the given base key + * + * @param key Base key + * @return Augmented key + */ + private String getAugmentedKey(String key) { + String augmentedKey = key; + if (propertyPrefix != null) { + log.debug("Augmenting property key [{}] with prefix: {}", key, propertyPrefix); + augmentedKey = propertyPrefix + augmentedKey; } - propertyValue = System.getProperty(key); - if (propertyValue != null) { - log.debug("Found a JVM system property: {} with value: {} to be used.", key, propertyValue); - } else if (properties != null) { - propertyValue = properties.getProperty(key); + if (propertySuffix != null) { + log.debug("Augmenting property key [{}] with suffix: {}", key, propertySuffix); + augmentedKey = augmentedKey + propertySuffix; } + return augmentedKey; } - return parseProperty(key, propertyValue, properties); + /** + * Gets the property with the given key, it returns {@code null} if the property is not found + * + * @param key Key of the property + * @return Value of the property or {@code null} if not found + */ + private String doGetPropertyValue(String key) { + String value = System.getProperty(key); + if (value != null) { + log.debug("Found a JVM system property: {} with value: {} to be used.", key, value); + } else if (properties != null) { + value = properties.getProperty(key); + } + return value; + } } + /** + * This inner class is the definition of a property used in a string + */ + private static final class Property { + private final int beginIndex; + private final int endIndex; + private final String key; + private final String value; + + private Property(int beginIndex, int endIndex, String key, String value) { + this.beginIndex = beginIndex; + this.endIndex = endIndex; + this.key = key; + this.value = value; + } + + /** + * Gets the begin index of the property (including the prefix token). + */ + public int getBeginIndex() { + return beginIndex; + } + + /** + * Gets the end index of the property (including the suffix token). + */ + public int getEndIndex() { + return endIndex; + } + + /** + * Gets the key of the property. + */ + public String getKey() { + return key; + } + + /** + * Gets the value of the property. + */ + public String getValue() { + return value; + } + } }
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-7429_43956f93.diff
bugs-dot-jar_data_CAMEL-3535_b56d2962
--- BugID: CAMEL-3535 Summary: Aggregation fails to call onComplete for exchanges if the aggregation is after a bean or process. Description: |- When creating a route that contains an aggregation, if that aggregation is preceded by a bean or process, it will fail to call AggregateOnCompletion.onComplete(). I've attached a unit test that can show you the behavior. Trace level loggging will need to be enabled to see the difference. With the call to the bean, it won't show the following log entry: {noformat}TRACE org.apache.camel.processor.aggregate.AggregateProcessor - Aggregated exchange onComplete: Exchange[Message: ab]{noformat} If you remove the bean call, it'll start calling onComplete() again. What I've noticed is that if this call is not made, it ends up in a memory leak since the inProgressCompleteExchanges HashSet in AggregateProcessor never has any exchange ID's removed. diff --git a/camel-core/src/main/java/org/apache/camel/processor/aggregate/AggregateProcessor.java b/camel-core/src/main/java/org/apache/camel/processor/aggregate/AggregateProcessor.java index f2f09c0..78ab290 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/aggregate/AggregateProcessor.java +++ b/camel-core/src/main/java/org/apache/camel/processor/aggregate/AggregateProcessor.java @@ -177,12 +177,16 @@ public class AggregateProcessor extends ServiceSupport implements Processor, Nav throw new ClosedCorrelationKeyException(key, exchange); } + // copy exchange, and do not share the unit of work + // the aggregated output runs in another unit of work + Exchange copy = ExchangeHelper.createCorrelatedCopy(exchange, false); + // when memory based then its fast using synchronized, but if the aggregation repository is IO // bound such as JPA etc then concurrent aggregation per correlation key could // improve performance as we can run aggregation repository get/add in parallel lock.lock(); try { - doAggregation(key, exchange); + doAggregation(key, copy); } finally { lock.unlock(); }
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-3535_b56d2962.diff
bugs-dot-jar_data_CAMEL-4682_1e54865c
--- BugID: CAMEL-4682 Summary: When stopping CamelContext should not clear lifecycleStrategies, to make restart safely possible Description: We should not clear the lifecycleStrategies on CamelContext when stop() is invoked, as if we restart by invoking start(), the lifecycle strategies should be in use again. diff --git a/camel-core/src/main/java/org/apache/camel/impl/DefaultCamelContext.java b/camel-core/src/main/java/org/apache/camel/impl/DefaultCamelContext.java index 5cc505b..7857a78 100644 --- a/camel-core/src/main/java/org/apache/camel/impl/DefaultCamelContext.java +++ b/camel-core/src/main/java/org/apache/camel/impl/DefaultCamelContext.java @@ -1560,7 +1560,7 @@ public class DefaultCamelContext extends ServiceSupport implements ModelCamelCon // shutdown management as the last one shutdownServices(managementStrategy); shutdownServices(lifecycleStrategies); - lifecycleStrategies.clear(); + // do not clear lifecycleStrategies as we can start Camel again and get the route back as before // stop the lazy created so they can be re-created on restart forceStopLazyInitialization();
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-4682_1e54865c.diff
bugs-dot-jar_data_CAMEL-9124_9da2c05a
--- BugID: CAMEL-9124 Summary: RedeliveryPattern should support property placeholders Description: |- See nabble http://camel.465427.n5.nabble.com/Can-t-configure-delayPattern-with-property-placeholders-tp5771356.html diff --git a/camel-core/src/main/java/org/apache/camel/model/RedeliveryPolicyDefinition.java b/camel-core/src/main/java/org/apache/camel/model/RedeliveryPolicyDefinition.java index 41e53e9..f695d26 100644 --- a/camel-core/src/main/java/org/apache/camel/model/RedeliveryPolicyDefinition.java +++ b/camel-core/src/main/java/org/apache/camel/model/RedeliveryPolicyDefinition.java @@ -156,13 +156,13 @@ public class RedeliveryPolicyDefinition { } } if (delayPattern != null) { - answer.setDelayPattern(delayPattern); + answer.setDelayPattern(CamelContextHelper.parseText(context, delayPattern)); } if (allowRedeliveryWhileStopping != null) { answer.setAllowRedeliveryWhileStopping(CamelContextHelper.parseBoolean(context, allowRedeliveryWhileStopping)); } if (exchangeFormatterRef != null) { - answer.setExchangeFormatterRef(exchangeFormatterRef); + answer.setExchangeFormatterRef(CamelContextHelper.parseText(context, exchangeFormatterRef)); } } catch (Exception e) { throw ObjectHelper.wrapRuntimeCamelException(e);
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-9124_9da2c05a.diff
bugs-dot-jar_data_CAMEL-8227_54d7fc59
--- BugID: CAMEL-8227 Summary: Using exchangePattern=InOnly in to uris are not used Description: |- Related to CAMEL-5301 Which was implemented for recipient list. But the same thing should be fixed/implemented for send processor as well. See nabble http://camel.465427.n5.nabble.com/Rest-DSL-org-apache-camel-ExchangeTimedOutException-The-OUT-message-was-not-received-within-20000-mis-tp5761530.html diff --git a/camel-core/src/main/java/org/apache/camel/processor/RecipientListProcessor.java b/camel-core/src/main/java/org/apache/camel/processor/RecipientListProcessor.java index 1087da6..db6af86 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/RecipientListProcessor.java +++ b/camel-core/src/main/java/org/apache/camel/processor/RecipientListProcessor.java @@ -17,12 +17,11 @@ package org.apache.camel.processor; import java.io.UnsupportedEncodingException; -import java.net.URI; +import java.net.MalformedURLException; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; -import java.util.Map; import java.util.concurrent.ExecutorService; import org.apache.camel.CamelContext; @@ -34,6 +33,7 @@ import org.apache.camel.Producer; import org.apache.camel.impl.ProducerCache; import org.apache.camel.processor.aggregate.AggregationStrategy; import org.apache.camel.spi.RouteContext; +import org.apache.camel.util.EndpointHelper; import org.apache.camel.util.ExchangeHelper; import org.apache.camel.util.MessageHelper; import org.apache.camel.util.ServiceHelper; @@ -191,7 +191,7 @@ public class RecipientListProcessor extends MulticastProcessor { ExchangePattern pattern; try { endpoint = resolveEndpoint(exchange, recipient); - pattern = resolveExchangePattern(exchange, recipient); + pattern = resolveExchangePattern(recipient); producer = producerCache.acquireProducer(endpoint); } catch (Exception e) { if (isIgnoreInvalidEndpoints()) { @@ -254,18 +254,13 @@ public class RecipientListProcessor extends MulticastProcessor { return ExchangeHelper.resolveEndpoint(exchange, recipient); } - protected ExchangePattern resolveExchangePattern(Exchange exchange, Object recipient) throws UnsupportedEncodingException, URISyntaxException { + protected ExchangePattern resolveExchangePattern(Object recipient) throws UnsupportedEncodingException, URISyntaxException, MalformedURLException { // trim strings as end users might have added spaces between separators if (recipient instanceof String) { String s = ((String) recipient).trim(); // see if exchangePattern is a parameter in the url s = URISupport.normalizeUri(s); - URI url = new URI(s); - Map<String, Object> parameters = URISupport.parseParameters(url); - String pattern = (String) parameters.get("exchangePattern"); - if (pattern != null) { - return ExchangePattern.asEnum(pattern); - } + return EndpointHelper.resolveExchangePatternFromUrl(s); } return null; } diff --git a/camel-core/src/main/java/org/apache/camel/processor/SendProcessor.java b/camel-core/src/main/java/org/apache/camel/processor/SendProcessor.java index d8e8803..efd6a60 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/SendProcessor.java +++ b/camel-core/src/main/java/org/apache/camel/processor/SendProcessor.java @@ -16,6 +16,7 @@ */ package org.apache.camel.processor; +import java.net.URISyntaxException; import java.util.HashMap; import org.apache.camel.AsyncCallback; @@ -33,6 +34,7 @@ import org.apache.camel.impl.ProducerCache; import org.apache.camel.support.ServiceSupport; import org.apache.camel.util.AsyncProcessorConverterHelper; import org.apache.camel.util.AsyncProcessorHelper; +import org.apache.camel.util.EndpointHelper; import org.apache.camel.util.EventHelper; import org.apache.camel.util.ObjectHelper; import org.apache.camel.util.ServiceHelper; @@ -53,6 +55,7 @@ public class SendProcessor extends ServiceSupport implements AsyncProcessor, Tra protected ProducerCache producerCache; protected AsyncProcessor producer; protected Endpoint destination; + protected ExchangePattern destinationExchangePattern; protected final boolean unhandleException; public SendProcessor(Endpoint destination) { @@ -69,6 +72,12 @@ public class SendProcessor extends ServiceSupport implements AsyncProcessor, Tra this.camelContext = destination.getCamelContext(); this.pattern = pattern; this.unhandleException = unhandleException; + try { + this.destinationExchangePattern = null; + this.destinationExchangePattern = EndpointHelper.resolveExchangePatternFromUrl(destination.getEndpointUri()); + } catch (URISyntaxException e) { + throw ObjectHelper.wrapRuntimeCamelException(e); + } ObjectHelper.notNull(this.camelContext, "camelContext"); } @@ -133,11 +142,9 @@ public class SendProcessor extends ServiceSupport implements AsyncProcessor, Tra } }); } catch (Throwable throwable) { - if (exchange != null) { - exchange.setException(throwable); - checkException(exchange); - } - + exchange.setException(throwable); + checkException(exchange); + callback.done(sync); } return sync; @@ -180,7 +187,10 @@ public class SendProcessor extends ServiceSupport implements AsyncProcessor, Tra } protected Exchange configureExchange(Exchange exchange, ExchangePattern pattern) { - if (pattern != null) { + // destination exchange pattern overrides pattern + if (destinationExchangePattern != null) { + exchange.setPattern(destinationExchangePattern); + } else if (pattern != null) { exchange.setPattern(pattern); } // set property which endpoint we send to diff --git a/camel-core/src/main/java/org/apache/camel/util/EndpointHelper.java b/camel-core/src/main/java/org/apache/camel/util/EndpointHelper.java index 9df3ca2..18181b3 100644 --- a/camel-core/src/main/java/org/apache/camel/util/EndpointHelper.java +++ b/camel-core/src/main/java/org/apache/camel/util/EndpointHelper.java @@ -16,6 +16,8 @@ */ package org.apache.camel.util; +import java.net.URI; +import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -29,6 +31,7 @@ import org.apache.camel.CamelContext; import org.apache.camel.DelegateEndpoint; import org.apache.camel.Endpoint; import org.apache.camel.Exchange; +import org.apache.camel.ExchangePattern; import org.apache.camel.Message; import org.apache.camel.PollingConsumer; import org.apache.camel.Processor; @@ -486,5 +489,22 @@ public final class EndpointHelper { sb.append("\n</messages>"); return sb.toString(); } - + + /** + * Attempts to resolve if the url has an <tt>exchangePattern</tt> option configured + * + * @param url the url + * @return the exchange pattern, or <tt>null</tt> if the url has no <tt>exchangePattern</tt> configured. + * @throws URISyntaxException is thrown if uri is invalid + */ + public static ExchangePattern resolveExchangePatternFromUrl(String url) throws URISyntaxException { + URI uri = new URI(url); + Map<String, Object> parameters = URISupport.parseParameters(uri); + String pattern = (String) parameters.get("exchangePattern"); + if (pattern != null) { + return ExchangePattern.asEnum(pattern); + } + return null; + } + }
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-8227_54d7fc59.diff
bugs-dot-jar_data_CAMEL-7241_18c23fa8
--- BugID: CAMEL-7241 Summary: ByteBuffer to String conversion uses buffer capacity not limit Description: |- Camel's conversion logic for ByteBuffer's to String's has a bug where camel uses a ByteBuffers capacity() instead of it's limit(). If you allocate a large byte buffer and only partially fill it with data, and use camel to convert this into a string, camel tries to convert all the bytes, even the non-used ones. This unit test reproduces this bug. {code} @Test public void testByteBufferToStringConversion() { String str = "123456789"; ByteBuffer buffer = ByteBuffer.allocate( 16 ); buffer.put( str.getBytes() ); Exchange exchange = new DefaultExchange( context() ); exchange.getIn().setBody( buffer ); assertEquals( str, exchange.getIn().getBody( String.class ) ); } {code} diff --git a/camel-core/src/main/java/org/apache/camel/converter/NIOConverter.java b/camel-core/src/main/java/org/apache/camel/converter/NIOConverter.java index 41273b6..e1cf6d6 100644 --- a/camel-core/src/main/java/org/apache/camel/converter/NIOConverter.java +++ b/camel-core/src/main/java/org/apache/camel/converter/NIOConverter.java @@ -54,7 +54,7 @@ public final class NIOConverter { @Converter public static String toString(ByteBuffer buffer, Exchange exchange) throws IOException { - return IOConverter.toString(buffer.array(), exchange); + return IOConverter.toString(toByteArray(buffer), exchange); } @Converter
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-7241_18c23fa8.diff
bugs-dot-jar_data_CAMEL-6918_5761250c
--- BugID: CAMEL-6918 Summary: Error handler for SEDA producer doesn't work Description: "Exceptions thrown by seda producer bypass exception handling and bubble up to original caller. \n\n" diff --git a/camel-core/src/main/java/org/apache/camel/processor/SendProcessor.java b/camel-core/src/main/java/org/apache/camel/processor/SendProcessor.java index b7d3c3c..6ba6fc8 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/SendProcessor.java +++ b/camel-core/src/main/java/org/apache/camel/processor/SendProcessor.java @@ -107,20 +107,31 @@ public class SendProcessor extends ServiceSupport implements AsyncProcessor, Tra EventHelper.notifyExchangeSending(exchange.getContext(), target, destination); LOG.debug(">>>> {} {}", destination, exchange); - return producer.process(exchange, new AsyncCallback() { - @Override - public void done(boolean doneSync) { - try { - // restore previous MEP - target.setPattern(existingPattern); - // emit event that the exchange was sent to the endpoint - long timeTaken = watch.stop(); - EventHelper.notifyExchangeSent(target.getContext(), target, destination, timeTaken); - } finally { - callback.done(doneSync); + + boolean sync = true; + try { + sync = producer.process(exchange, new AsyncCallback() { + @Override + public void done(boolean doneSync) { + try { + // restore previous MEP + target.setPattern(existingPattern); + // emit event that the exchange was sent to the endpoint + long timeTaken = watch.stop(); + EventHelper.notifyExchangeSent(target.getContext(), target, destination, timeTaken); + } finally { + callback.done(doneSync); + } } + }); + } catch (Throwable throwable) { + if (exchange != null) { + exchange.setException(throwable); } - }); + + } + + return sync; } // send the exchange to the destination using the producer cache for the non optimized producers
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-6918_5761250c.diff
bugs-dot-jar_data_CAMEL-3395_8433e6db
--- BugID: CAMEL-3395 Summary: Splitter - Exchange.CORRELATION_ID should point back to parent Exchange id Description: |- See nabble http://camel.465427.n5.nabble.com/Splitted-exchange-has-incorrect-correlation-ID-tp3289354p3289354.html diff --git a/camel-core/src/main/java/org/apache/camel/processor/Splitter.java b/camel-core/src/main/java/org/apache/camel/processor/Splitter.java index 1f51134..97e5178 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/Splitter.java +++ b/camel-core/src/main/java/org/apache/camel/processor/Splitter.java @@ -137,7 +137,7 @@ public class Splitter extends MulticastProcessor implements AsyncProcessor, Trac public Object next() { Object part = iterator.next(); - Exchange newExchange = exchange.copy(); + Exchange newExchange = ExchangeHelper.createCopy(exchange, true); if (part instanceof Message) { newExchange.setIn((Message)part); } else { diff --git a/camel-core/src/main/java/org/apache/camel/util/ExchangeHelper.java b/camel-core/src/main/java/org/apache/camel/util/ExchangeHelper.java index 03ce98e..606a69a 100644 --- a/camel-core/src/main/java/org/apache/camel/util/ExchangeHelper.java +++ b/camel-core/src/main/java/org/apache/camel/util/ExchangeHelper.java @@ -168,6 +168,8 @@ public final class ExchangeHelper { * @param handover whether the on completion callbacks should be handed over to the new copy. */ public static Exchange createCorrelatedCopy(Exchange exchange, boolean handover) { + String id = exchange.getExchangeId(); + Exchange copy = exchange.copy(); // do not share the unit of work copy.setUnitOfWork(null); @@ -177,7 +179,23 @@ public final class ExchangeHelper { uow.handoverSynchronization(copy); } // set a correlation id so we can track back the original exchange - copy.setProperty(Exchange.CORRELATION_ID, exchange.getExchangeId()); + copy.setProperty(Exchange.CORRELATION_ID, id); + return copy; + } + + /** + * Creates a new instance and copies from the current message exchange so that it can be + * forwarded to another destination as a new instance. + * + * @param exchange original copy of the exchange + * @param preserveExchangeId whether or not the exchange id should be preserved + * @return the copy + */ + public static Exchange createCopy(Exchange exchange, boolean preserveExchangeId) { + Exchange copy = exchange.copy(); + if (preserveExchangeId) { + copy.setExchangeId(exchange.getExchangeId()); + } return copy; }
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-3395_8433e6db.diff
bugs-dot-jar_data_CAMEL-8053_cac72b14
--- BugID: CAMEL-8053 Summary: Memory leak when adding/removing a lot of routes Description: Dynamically adding/removing routes to camel causes registrations in org.apache.camel.builder.ErrorHandlerBuilderRef.handlers (Map<RouteContext, ErrorHandlerBuilder>) for RouteContext instances. Those never get removed and can cause leaks if memory consuming objects are attached in the RouteContext for example constant definitions. diff --git a/camel-core/src/main/java/org/apache/camel/builder/ErrorHandlerBuilder.java b/camel-core/src/main/java/org/apache/camel/builder/ErrorHandlerBuilder.java index 303feb1..3c5a3f1 100644 --- a/camel-core/src/main/java/org/apache/camel/builder/ErrorHandlerBuilder.java +++ b/camel-core/src/main/java/org/apache/camel/builder/ErrorHandlerBuilder.java @@ -90,4 +90,5 @@ public interface ErrorHandlerBuilder extends ErrorHandlerFactory { * @return a clone of this {@link ErrorHandlerBuilder} */ ErrorHandlerBuilder cloneBuilder(); + } diff --git a/camel-core/src/main/java/org/apache/camel/builder/ErrorHandlerBuilderRef.java b/camel-core/src/main/java/org/apache/camel/builder/ErrorHandlerBuilderRef.java index 0cf9d57..4d06b7f 100644 --- a/camel-core/src/main/java/org/apache/camel/builder/ErrorHandlerBuilderRef.java +++ b/camel-core/src/main/java/org/apache/camel/builder/ErrorHandlerBuilderRef.java @@ -50,6 +50,18 @@ public class ErrorHandlerBuilderRef extends ErrorHandlerBuilderSupport { } super.addErrorHandlers(routeContext, exception); } + + @Override + public boolean removeOnExceptionList(String id) { + for (RouteContext routeContext : handlers.keySet()) { + if (getRouteId(routeContext).equals(id)) { + handlers.remove(routeContext); + break; + } + } + return super.removeOnExceptionList(id); + } + public Processor createErrorHandler(RouteContext routeContext, Processor processor) throws Exception { ErrorHandlerBuilder handler = handlers.get(routeContext); diff --git a/camel-core/src/main/java/org/apache/camel/builder/ErrorHandlerBuilderSupport.java b/camel-core/src/main/java/org/apache/camel/builder/ErrorHandlerBuilderSupport.java index 747a6dd..365ebc0 100644 --- a/camel-core/src/main/java/org/apache/camel/builder/ErrorHandlerBuilderSupport.java +++ b/camel-core/src/main/java/org/apache/camel/builder/ErrorHandlerBuilderSupport.java @@ -21,6 +21,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import org.apache.camel.CamelContext; import org.apache.camel.model.OnExceptionDefinition; import org.apache.camel.processor.ErrorHandler; import org.apache.camel.processor.ErrorHandlerSupport; @@ -94,4 +95,28 @@ public abstract class ErrorHandlerBuilderSupport implements ErrorHandlerBuilder ObjectHelper.notNull(exceptionPolicyStrategy, "ExceptionPolicyStrategy"); this.exceptionPolicyStrategy = exceptionPolicyStrategy; } + + /** + * Remove the OnExceptionList by look up the route id from the ErrorHandlerBuilder internal map + * @param id the route id + * @return true if the route context is found and removed + */ + public boolean removeOnExceptionList(String id) { + for (RouteContext routeContext : onExceptions.keySet()) { + if (getRouteId(routeContext).equals(id)) { + onExceptions.remove(routeContext); + return true; + } + } + return false; + } + + protected String getRouteId(RouteContext routeContext) { + CamelContext context = routeContext.getCamelContext(); + if (context != null) { + return routeContext.getRoute().idOrCreate(context.getNodeIdFactory()); + } else { + return routeContext.getRoute().getId(); + } + } } diff --git a/camel-core/src/main/java/org/apache/camel/impl/DefaultCamelContext.java b/camel-core/src/main/java/org/apache/camel/impl/DefaultCamelContext.java index deba649..bd4488c 100644 --- a/camel-core/src/main/java/org/apache/camel/impl/DefaultCamelContext.java +++ b/camel-core/src/main/java/org/apache/camel/impl/DefaultCamelContext.java @@ -71,6 +71,7 @@ import org.apache.camel.SuspendableService; import org.apache.camel.TypeConverter; import org.apache.camel.VetoCamelContextStartException; import org.apache.camel.builder.ErrorHandlerBuilder; +import org.apache.camel.builder.ErrorHandlerBuilderSupport; import org.apache.camel.component.properties.PropertiesComponent; import org.apache.camel.impl.converter.BaseTypeConverterRegistry; import org.apache.camel.impl.converter.DefaultTypeConverter; @@ -147,7 +148,6 @@ import org.apache.camel.util.TimeUtils; import org.apache.camel.util.URISupport; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - import static org.apache.camel.util.StringQuoteHelper.doubleQuote; /** @@ -928,6 +928,11 @@ public class DefaultCamelContext extends ServiceSupport implements ModelCamelCon } public synchronized boolean removeRoute(String routeId) throws Exception { + // remove the route from ErrorHandlerBuilder if possible + if (getErrorHandlerBuilder() instanceof ErrorHandlerBuilderSupport) { + ErrorHandlerBuilderSupport builder = (ErrorHandlerBuilderSupport)getErrorHandlerBuilder(); + builder.removeOnExceptionList(routeId); + } RouteService routeService = routeServices.get(routeId); if (routeService != null) { if (getRouteStatus(routeId).isStopped()) {
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-8053_cac72b14.diff
bugs-dot-jar_data_CAMEL-7418_cabee0e9
--- BugID: CAMEL-7418 Summary: org.apache.camel.impl.JndiRegistry.findByTypeWithName Description: "I guess this line isn't correct:\nif (type.isInstance(pair.getClass()) || type.getName().equals(pair.getClassName()))\n\nThe variable \"pair.getClass()\" always returns \"javax.naming.NameClassPair\" or its subclasses and the method \"isInstance\" works only with Instances, but doesnt Classes.\n\n\n I think the correct code should be:\nif (type.isAssignableFrom(Class.forName(pair.getClassName())))\n\n\nI've tried to test a transacted route, but i couldnt because the error: \nFailed to create route route1 at: >>> Transacted[] <<< in route: Route(route1)[[From[direct:start]] -> [Transacted[]]] because of No bean could be found in the registry of type: PlatformTransactionManager\n" diff --git a/camel-core/src/main/java/org/apache/camel/impl/JndiRegistry.java b/camel-core/src/main/java/org/apache/camel/impl/JndiRegistry.java index dc663e3..8a077b3 100644 --- a/camel-core/src/main/java/org/apache/camel/impl/JndiRegistry.java +++ b/camel-core/src/main/java/org/apache/camel/impl/JndiRegistry.java @@ -78,8 +78,8 @@ public class JndiRegistry implements Registry { NamingEnumeration<NameClassPair> list = getContext().list(""); while (list.hasMore()) { NameClassPair pair = list.next(); - if (type.isInstance(pair.getClass()) || type.getName().equals(pair.getClassName())) { - Object instance = context.lookup(pair.getName()); + Object instance = context.lookup(pair.getName()); + if (type.isInstance(instance)) { answer.put(pair.getName(), type.cast(instance)); } } @@ -96,8 +96,8 @@ public class JndiRegistry implements Registry { NamingEnumeration<NameClassPair> list = getContext().list(""); while (list.hasMore()) { NameClassPair pair = list.next(); - if (type.isInstance(pair.getClass()) || type.getName().equals(pair.getClassName())) { - Object instance = context.lookup(pair.getName()); + Object instance = context.lookup(pair.getName()); + if (type.isInstance(instance)) { answer.add(type.cast(instance)); } }
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-7418_cabee0e9.diff
bugs-dot-jar_data_CAMEL-9217_e7ac45b6
--- BugID: CAMEL-9217 Summary: URI validation verifies usage of & char incorrectly Description: |- Hello Camel team, I have faced a URI validation issue that does not allow me to use a correct file producer URI if it does not contain parameters. My file endpoint URI looks like this: {code} raw form: file:D:\camel_test\test&run in encoded format: file:D%3A%5Ccamel_test%5Ctest%26run {code} As you can see this is a simple file endpoint URI which does not contain any parameters, please note that the target folder name contains '&' char. When I try to start a route for this endpoint I get the following error: {code} Caused by: org.apache.camel.ResolveEndpointFailedException: Failed to resolve endpoint: file://D:%5Ccamel_test%5Ctest&run due to: Failed to resolve endpoint: file://D:%5Ccamel_test%5Ctest&run due to: Invalid uri syntax: no ? marker however the uri has & parameter separators. Check the uri if its missing a ? marker. at org.apache.camel.impl.DefaultCamelContext.getEndpoint(DefaultCamelContext.java:547) at org.apache.camel.util.CamelContextHelper.getMandatoryEndpoint(CamelContextHelper.java:72) at org.apache.camel.model.RouteDefinition.resolveEndpoint(RouteDefinition.java:202) at org.apache.camel.impl.DefaultRouteContext.resolveEndpoint(DefaultRouteContext.java:107) at org.apache.camel.impl.DefaultRouteContext.resolveEndpoint(DefaultRouteContext.java:113) at org.apache.camel.model.SendDefinition.resolveEndpoint(SendDefinition.java:61) at org.apache.camel.model.SendDefinition.createProcessor(SendDefinition.java:55) at org.apache.camel.model.ProcessorDefinition.makeProcessor(ProcessorDefinition.java:500) at org.apache.camel.model.ProcessorDefinition.addRoutes(ProcessorDefinition.java:213) at org.apache.camel.model.RouteDefinition.addRoutes(RouteDefinition.java:942) Caused by: org.apache.camel.ResolveEndpointFailedException: Failed to resolve endpoint: file://D:%5Ccamel_test%5Ctest&run due to: Invalid uri syntax: no ? marker however the uri has & parameter separators. Check the uri if its missing a ? marker. at org.apache.camel.impl.DefaultComponent.validateURI(DefaultComponent.java:210) at org.apache.camel.impl.DefaultComponent.createEndpoint(DefaultComponent.java:115) at org.apache.camel.impl.DefaultCamelContext.getEndpoint(DefaultCamelContext.java:527) {code} The issue is that I have an '&' char in my folder path and do not have URI parameters. As a result the DefaultComponent.validateURI() function throws the exception at this point: {code} if (uri.contains("&") && !uri.contains("?")) { throw new ResolveEndpointFailedException(uri, "Invalid uri syntax: no ? marker however the uri " + "has & parameter separators. Check the uri if its missing a ? marker."); } {code} I think the issue is that for some reason & char at this point is in decoded form which is incorrect because it should be URI encoded here. I know that Camel has issues with + and & chars and in case of URI parameters we can use RAW() wrapper as a workaround. But as far as I can see we cannot do the same in base endpoint URI. Please note that if I add an URI parameter (any parameter works) the issue disappears and the event target works fine. For example: {code} raw form: file:D:\camel_test\test&run?forceWrites=true in encoded format: file:D%3A%5Ccamel_test%5Ctest%26run?forceWrites=true {code} I also found that Camel cannot normally handle URIs with ? char in base URI string. For example in case of File endpoint it tries to handle the second part of the base URI (which follows the ? char) as a parameter which is incorrect because ? char was correctly encoded and should not be used as the point where parameters string starts. If I try to use ? char in bucket name for S3 endpoint the part after ? is simply ignored. For example the following URI produces an error: {code} raw form: file:D:\camel_test\test?run?forceWrites=true in encoded format: file:D%3A%5Ccamel_test%5Ctest%3Frun?forceWrites=true {code} Error: {code} 2015-10-13 13:26:38,285 INFO [com.informatica.saas.infaagentv3.agentcore.TomcatManager] - Caused by: org.apache.camel.ResolveEndpointFailedException: Failed to resolve endpoint: file://D:%5Ccamel_test%5Ctest?run%3FforceWrites=true due to: There are 1 parameters that couldn't be set on the endpoint. Check the uri if the parameters are spelt correctly and that they are properties of the endpoint. Unknown parameters=[{run?forceWrites=true}] at org.apache.camel.impl.DefaultComponent.validateParameters(DefaultComponent.java:192) at org.apache.camel.impl.DefaultComponent.createEndpoint(DefaultComponent.java:137) at org.apache.camel.impl.DefaultCamelContext.getEndpoint(DefaultCamelContext.java:527) {code} And yes I know that ? char in a file path is not the best idea, I used the above example to illustrate a global camel issue. diff --git a/camel-core/src/main/java/org/apache/camel/impl/DefaultComponent.java b/camel-core/src/main/java/org/apache/camel/impl/DefaultComponent.java index c7ab7ff..c6492ea 100644 --- a/camel-core/src/main/java/org/apache/camel/impl/DefaultComponent.java +++ b/camel-core/src/main/java/org/apache/camel/impl/DefaultComponent.java @@ -196,12 +196,6 @@ public abstract class DefaultComponent extends ServiceSupport implements Compone * @throws ResolveEndpointFailedException should be thrown if the URI validation failed */ protected void validateURI(String uri, String path, Map<String, Object> parameters) { - // check for uri containing & but no ? marker - if (uri.contains("&") && !uri.contains("?")) { - throw new ResolveEndpointFailedException(uri, "Invalid uri syntax: no ? marker however the uri " - + "has & parameter separators. Check the uri if its missing a ? marker."); - } - // check for uri containing double && markers without include by RAW if (uri.contains("&&")) { Pattern pattern = Pattern.compile("RAW(.*&&.*)");
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-9217_e7ac45b6.diff
bugs-dot-jar_data_CAMEL-7160_095fa2b4
--- BugID: CAMEL-7160 Summary: Throttling has problems with rate changes Description: "When using the throttler with the header expression for controlling the rate, changing the rate does not work reliably. \n\nSome more information can be found in the following mail thread:\n\nhttp://camel.465427.n5.nabble.com/Problems-with-dynamic-throttling-td5746613.html" diff --git a/camel-core/src/main/java/org/apache/camel/processor/Throttler.java b/camel-core/src/main/java/org/apache/camel/processor/Throttler.java index ae6bc26..6b51a2c 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/Throttler.java +++ b/camel-core/src/main/java/org/apache/camel/processor/Throttler.java @@ -35,8 +35,8 @@ import org.apache.camel.util.ObjectHelper; * as only allowing 100 requests per second; or if huge load can cause a * particular system to malfunction or to reduce its throughput you might want * to introduce some throttling. - * - * @version + * + * @version */ public class Throttler extends DelayProcessorSupport implements Traceable { private volatile long maximumRequestsPerPeriod; @@ -80,7 +80,7 @@ public class Throttler extends DelayProcessorSupport implements Traceable { public Expression getMaximumRequestsPerPeriodExpression() { return maxRequestsPerPeriodExpression; } - + public long getTimePeriodMillis() { return timePeriodMillis.get(); } @@ -116,6 +116,9 @@ public class Throttler extends DelayProcessorSupport implements Traceable { if (maximumRequestsPerPeriod > 0 && longValue.longValue() != maximumRequestsPerPeriod) { log.debug("Throttler changed maximum requests per period from {} to {}", maximumRequestsPerPeriod, longValue); } + if (maximumRequestsPerPeriod > longValue) { + slot.capacity = 0; + } maximumRequestsPerPeriod = longValue; } @@ -131,7 +134,7 @@ public class Throttler extends DelayProcessorSupport implements Traceable { return 0; } } - + /* * Determine what the next available time slot is for handling an Exchange */ @@ -139,7 +142,7 @@ public class Throttler extends DelayProcessorSupport implements Traceable { if (slot == null) { slot = new TimeSlot(); } - if (slot.isFull() || !slot.isActive()) { + if (slot.isFull() || !slot.isPast()) { slot = slot.next(); } slot.assign(); @@ -150,7 +153,7 @@ public class Throttler extends DelayProcessorSupport implements Traceable { * A time slot is capable of handling a number of exchanges within a certain period of time. */ protected class TimeSlot { - + private volatile long capacity = Throttler.this.maximumRequestsPerPeriod; private final long duration = Throttler.this.timePeriodMillis.get(); private final long startTime; @@ -166,7 +169,7 @@ public class Throttler extends DelayProcessorSupport implements Traceable { protected void assign() { capacity--; } - + /* * Start the next time slot either now or in the future * (no time slots are being created in the past) @@ -174,15 +177,20 @@ public class Throttler extends DelayProcessorSupport implements Traceable { protected TimeSlot next() { return new TimeSlot(Math.max(System.currentTimeMillis(), this.startTime + this.duration)); } - + + protected boolean isPast() { + long current = System.currentTimeMillis(); + return current < (startTime + duration); + } + protected boolean isActive() { long current = System.currentTimeMillis(); return startTime <= current && current < (startTime + duration); } - + protected boolean isFull() { return capacity <= 0; - } + } } TimeSlot getSlot() {
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-7160_095fa2b4.diff
bugs-dot-jar_data_CAMEL-6779_f412d744
--- BugID: CAMEL-6779 Summary: 'StaxConverter: encoding problems for XMLEventReader and XMLStreamReader' Description: |- StaxConverter creates XMLEventReader and XMLStreamReader always with a specified encoding. However, the encoding of the data the readers should read is not always known. Therefore exceptions occur. The solution is easy: The encoding should not be set so that the readers can determine the encoding. diff --git a/camel-core/src/main/java/org/apache/camel/converter/jaxp/StaxConverter.java b/camel-core/src/main/java/org/apache/camel/converter/jaxp/StaxConverter.java index 1cd33ae..5469df5 100644 --- a/camel-core/src/main/java/org/apache/camel/converter/jaxp/StaxConverter.java +++ b/camel-core/src/main/java/org/apache/camel/converter/jaxp/StaxConverter.java @@ -167,7 +167,7 @@ public class StaxConverter { public XMLStreamReader createXMLStreamReader(InputStream in, Exchange exchange) throws XMLStreamException { XMLInputFactory factory = getInputFactory(); try { - return factory.createXMLStreamReader(IOHelper.buffered(in), IOHelper.getCharsetName(exchange)); + return factory.createXMLStreamReader(IOHelper.buffered(in), IOHelper.getCharsetName(exchange, false)); } finally { returnXMLInputFactory(factory); } @@ -236,7 +236,7 @@ public class StaxConverter { public XMLEventReader createXMLEventReader(InputStream in, Exchange exchange) throws XMLStreamException { XMLInputFactory factory = getInputFactory(); try { - return factory.createXMLEventReader(IOHelper.buffered(in), IOHelper.getCharsetName(exchange)); + return factory.createXMLEventReader(IOHelper.buffered(in), IOHelper.getCharsetName(exchange, false)); } finally { returnXMLInputFactory(factory); }
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-6779_f412d744.diff
bugs-dot-jar_data_CAMEL-4536_df9f4a6a
--- BugID: CAMEL-4536 Summary: Using AuthorizationPolicy on a Route prevents Processors from being exposed via JMX Description: "Using AuthorizationPolicy on a route (e.g., using .policy(myAuthPolicy) in a Java DSL) prevents that processors on this route are exposed via JMX. \n\nSteps to reproduce:\n\n-) Start the Camel app in the attached test case (MyRouteBuilder)\n-) Open JConsole\n-) Connect to the corresponding local process\n-) Under \"processors\" only the processors from the route without the policy are shown, but not the ones from the route where a policy is used" diff --git a/camel-core/src/main/java/org/apache/camel/processor/WrapProcessor.java b/camel-core/src/main/java/org/apache/camel/processor/WrapProcessor.java index 4b3b7c8..adb508a 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/WrapProcessor.java +++ b/camel-core/src/main/java/org/apache/camel/processor/WrapProcessor.java @@ -16,6 +16,8 @@ */ package org.apache.camel.processor; +import java.util.List; + import org.apache.camel.Processor; import org.apache.camel.util.ServiceHelper; @@ -38,6 +40,14 @@ public class WrapProcessor extends DelegateAsyncProcessor { } @Override + public List<Processor> next() { + // must include wrapped in navigate + List<Processor> list = super.next(); + list.add(wrapped); + return list; + } + + @Override protected void doStart() throws Exception { ServiceHelper.startService(wrapped); super.doStart(); diff --git a/camel-core/src/main/java/org/apache/camel/util/AsyncProcessorConverterHelper.java b/camel-core/src/main/java/org/apache/camel/util/AsyncProcessorConverterHelper.java index 7a5a6f2..656136c 100644 --- a/camel-core/src/main/java/org/apache/camel/util/AsyncProcessorConverterHelper.java +++ b/camel-core/src/main/java/org/apache/camel/util/AsyncProcessorConverterHelper.java @@ -41,9 +41,8 @@ public final class AsyncProcessorConverterHelper { } /** - * Creates a AsnycProcossor that delegates to the given processor. - * It is important that this implements DelegateProcessor - * + * Creates a {@link AsyncProcessor} that delegates to the given processor. + * It is important that this implements {@link DelegateProcessor} */ private static final class ProcessorToAsyncProcessorBridge implements DelegateProcessor, AsyncProcessor, Navigate<Processor>, Service { protected Processor processor;
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-4536_df9f4a6a.diff
bugs-dot-jar_data_CAMEL-5796_de6dd425
--- BugID: CAMEL-5796 Summary: The combination of the transacted DSL together with the <setHeader> or <setBody> prohibits to resolve the properties properly. Description: | Given the property {{myKey}} defined as: {code} myKey=myValue {code} Then consider the following trivial route: {code:xml} <route> <from uri="activemq:queue:okay" /> <transacted /> <setHeader headerName="myHeader"> <constant>{{myKey}}</constant> </setHeader> <to uri="mock:test" /> </route> {code} Because of the usage of the {{transacted}} DSL the property placeholder {{{{myKey}}}} will not be resolved to {{myValue}} properly. This behaviour would disappear if you would remove the {{transacted}} DSL. And I'm observing the same behaviour using the {{setBody}} DSL as well. diff --git a/camel-core/src/main/java/org/apache/camel/model/ProcessorDefinition.java b/camel-core/src/main/java/org/apache/camel/model/ProcessorDefinition.java index 2db4f13..38989d1 100644 --- a/camel-core/src/main/java/org/apache/camel/model/ProcessorDefinition.java +++ b/camel-core/src/main/java/org/apache/camel/model/ProcessorDefinition.java @@ -367,9 +367,29 @@ public abstract class ProcessorDefinition<Type extends ProcessorDefinition<Type> List<Processor> list = new ArrayList<Processor>(); for (ProcessorDefinition<?> output : outputs) { + // allow any custom logic before we create the processor + output.preCreateProcessor(); + // resolve properties before we create the processor resolvePropertyPlaceholders(routeContext, output); + // resolve constant fields (eg Exchange.FILE_NAME) + resolveKnownConstantFields(output); + + // also resolve properties and constant fields on embedded expressions + ProcessorDefinition<?> me = (ProcessorDefinition<?>) output; + if (me instanceof ExpressionNode) { + ExpressionNode exp = (ExpressionNode) me; + ExpressionDefinition expressionDefinition = exp.getExpression(); + if (expressionDefinition != null) { + // resolve properties before we create the processor + resolvePropertyPlaceholders(routeContext, expressionDefinition); + + // resolve constant fields (eg Exchange.FILE_NAME) + resolveKnownConstantFields(expressionDefinition); + } + } + Processor processor = null; // at first use custom factory if (routeContext.getCamelContext().getProcessorFactory() != null) { @@ -472,10 +492,9 @@ public abstract class ProcessorDefinition<Type extends ProcessorDefinition<Type> // include additional properties which have the Camel placeholder QName // and when the definition parameter is this (otherAttributes belong to this) if (processorDefinition != null && processorDefinition.getOtherAttributes() != null) { - for (Object key : processorDefinition.getOtherAttributes().keySet()) { - QName qname = (QName) key; - if (Constants.PLACEHOLDER_QNAME.equals(qname.getNamespaceURI())) { - String local = qname.getLocalPart(); + for (QName key : processorDefinition.getOtherAttributes().keySet()) { + if (Constants.PLACEHOLDER_QNAME.equals(key.getNamespaceURI())) { + String local = key.getLocalPart(); Object value = processorDefinition.getOtherAttributes().get(key); if (value != null && value instanceof String) { // value must be enclosed with placeholder tokens
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-5796_de6dd425.diff
bugs-dot-jar_data_CAMEL-7209_5f78c646
--- BugID: CAMEL-7209 Summary: NIOConverter.toByteArray return bad data. Description: |- Current implmentation of NIOConverter.toByteArray return the byte array that back the buffer. Array can be bigger that relevant data in ByteBuffer. diff --git a/camel-core/src/main/java/org/apache/camel/converter/NIOConverter.java b/camel-core/src/main/java/org/apache/camel/converter/NIOConverter.java index 9a2b60a..0bf08ac 100644 --- a/camel-core/src/main/java/org/apache/camel/converter/NIOConverter.java +++ b/camel-core/src/main/java/org/apache/camel/converter/NIOConverter.java @@ -99,6 +99,7 @@ public final class NIOConverter { bytes = value.getBytes(); } buf.put(bytes); + buf.flip(); return buf; }
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-7209_5f78c646.diff
bugs-dot-jar_data_CAMEL-3617_02626724
--- BugID: CAMEL-3617 Summary: Inconsistent filename value when move attribute is used with File component Description: "Unless I miss a point, when I use the following endpoint, the file:name value is incorrect and is equal to file:absolute.path\n\n<endpoint id=\"fileEndpoint\" uri=\"file:${queue.input.folder}?recursive=true&amp;include=.*\\.dat&amp;move=${queue.done.folder}/$simple{file:name}&amp;moveFailed=${queue.failed.folder}/$simple{file:name}\" />\n\n${queue.input.folder}, ${queue.done.folder} and ${queue.failed.folder} are absolute paths resolved by Spring.\n\nIn fact, Camel tries to move the file to ${queue.done.folder}/${queue.input.folder}/$simple{file:name}\nI've also tried using $simple{header.CamelFileName} instead of $simple{file:name} and it gives the same result.\n\nFor now, I've found a workaround using a processor which put the CamelFileName header value into a \"destFile\" property \n<endpoint id=\"fileEndpoint\" uri=\"file:${queue.input.folder}?recursive=true&amp;include=.*\\.dat&amp;move=${queue.done.folder}/$simple{property.destFile}&amp;moveFailed=${queue.failed.folder}/$simple{property.destFile}\" />\n" diff --git a/camel-core/src/main/java/org/apache/camel/builder/xml/DefaultTransformErrorHandler.java b/camel-core/src/main/java/org/apache/camel/builder/xml/DefaultTransformErrorHandler.java index 214ea39..6e6b59d 100644 --- a/camel-core/src/main/java/org/apache/camel/builder/xml/DefaultTransformErrorHandler.java +++ b/camel-core/src/main/java/org/apache/camel/builder/xml/DefaultTransformErrorHandler.java @@ -19,12 +19,13 @@ package org.apache.camel.builder.xml; import javax.xml.transform.ErrorListener; import javax.xml.transform.TransformerException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * {@link ErrorHandler} and {@link ErrorListener} which will log warnings, * and throws error and fatal as exception, which ensures those can be caught by Camel and dealt-with. diff --git a/camel-core/src/main/java/org/apache/camel/component/file/FileConsumer.java b/camel-core/src/main/java/org/apache/camel/component/file/FileConsumer.java index 8e8b320..6d2c809 100644 --- a/camel-core/src/main/java/org/apache/camel/component/file/FileConsumer.java +++ b/camel-core/src/main/java/org/apache/camel/component/file/FileConsumer.java @@ -137,24 +137,21 @@ public class FileConsumer extends GenericFileConsumer<File> { answer.setAbsolute(FileUtil.isAbsolute(file)); answer.setAbsoluteFilePath(file.getAbsolutePath()); answer.setLastModified(file.lastModified()); - if (answer.isAbsolute()) { - // use absolute path as relative - answer.setRelativeFilePath(file.getAbsolutePath()); + + // compute the file path as relative to the starting directory + File path; + String endpointNormalized = FileUtil.normalizePath(endpointPath); + if (file.getPath().startsWith(endpointNormalized)) { + // skip duplicate endpoint path + path = new File(ObjectHelper.after(file.getPath(), endpointNormalized + File.separator)); } else { - File path; - String endpointNormalized = FileUtil.normalizePath(endpointPath); - if (file.getPath().startsWith(endpointNormalized)) { - // skip duplicate endpoint path - path = new File(ObjectHelper.after(file.getPath(), endpointNormalized + File.separator)); - } else { - path = new File(file.getPath()); - } + path = new File(file.getPath()); + } - if (path.getParent() != null) { - answer.setRelativeFilePath(path.getParent() + File.separator + file.getName()); - } else { - answer.setRelativeFilePath(path.getName()); - } + if (path.getParent() != null) { + answer.setRelativeFilePath(path.getParent() + File.separator + file.getName()); + } else { + answer.setRelativeFilePath(path.getName()); } // the file name should be the relative path
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-3617_02626724.diff
bugs-dot-jar_data_CAMEL-7239_ae419224
--- BugID: CAMEL-7239 Summary: Address the SchemaFactory thread safe issue. Description: SchemaFactory is not thread safe, we need to do addition work in ValidatorProcessor to avoid the threads issue. diff --git a/camel-core/src/main/java/org/apache/camel/processor/validation/ValidatingProcessor.java b/camel-core/src/main/java/org/apache/camel/processor/validation/ValidatingProcessor.java index bcbc671..2d9fa8e 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/validation/ValidatingProcessor.java +++ b/camel-core/src/main/java/org/apache/camel/processor/validation/ValidatingProcessor.java @@ -22,6 +22,7 @@ import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Collections; + import javax.xml.XMLConstants; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Result; @@ -38,6 +39,7 @@ import javax.xml.validation.Validator; import org.w3c.dom.Node; import org.w3c.dom.ls.LSResourceResolver; + import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; @@ -50,10 +52,10 @@ import org.apache.camel.TypeConverter; import org.apache.camel.converter.jaxp.XmlConverter; import org.apache.camel.util.AsyncProcessorHelper; import org.apache.camel.util.IOHelper; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; + /** * A processor which validates the XML version of the inbound message body * against some schema either in XSD or RelaxNG @@ -62,9 +64,9 @@ public class ValidatingProcessor implements AsyncProcessor { private static final Logger LOG = LoggerFactory.getLogger(ValidatingProcessor.class); private XmlConverter converter = new XmlConverter(); private String schemaLanguage = XMLConstants.W3C_XML_SCHEMA_NS_URI; - private Schema schema; + private volatile Schema schema; private Source schemaSource; - private SchemaFactory schemaFactory; + private volatile SchemaFactory schemaFactory; private URL schemaUrl; private File schemaFile; private byte[] schemaAsByteArray; @@ -190,7 +192,11 @@ public class ValidatingProcessor implements AsyncProcessor { public Schema getSchema() throws IOException, SAXException { if (schema == null) { - schema = createSchema(); + synchronized (this) { + if (schema == null) { + schema = createSchema(); + } + } } return schema; } @@ -244,7 +250,11 @@ public class ValidatingProcessor implements AsyncProcessor { public SchemaFactory getSchemaFactory() { if (schemaFactory == null) { - schemaFactory = createSchemaFactory(); + synchronized (this) { + if (schemaFactory == null) { + schemaFactory = createSchemaFactory(); + } + } } return schemaFactory; } @@ -336,21 +346,29 @@ public class ValidatingProcessor implements AsyncProcessor { URL url = getSchemaUrl(); if (url != null) { - return factory.newSchema(url); + synchronized (this) { + return factory.newSchema(url); + } } File file = getSchemaFile(); if (file != null) { - return factory.newSchema(file); + synchronized (this) { + return factory.newSchema(file); + } } byte[] bytes = getSchemaAsByteArray(); if (bytes != null) { - return factory.newSchema(new StreamSource(new ByteArrayInputStream(schemaAsByteArray))); + synchronized (this) { + return factory.newSchema(new StreamSource(new ByteArrayInputStream(schemaAsByteArray))); + } } Source source = getSchemaSource(); - return factory.newSchema(source); + synchronized (this) { + return factory.newSchema(source); + } } /**
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-7239_ae419224.diff
bugs-dot-jar_data_CAMEL-7364_7bbb88ba
--- BugID: CAMEL-7364 Summary: JpaMessageIdRepository uses EntityManager non thread-safe Description: |- In our product we have found strange behavior of JpaMessageIdRepository when change version 2.9.2 to 2.12.3. The reason for this was that EntityManager assigned in the constructor org.apache.camel.processor.idempotent.jpa.JpaMessageIdRepository, but EntityManager not required to be thread safe. http://download.oracle.com/otn-pub/jcp/persistence-2.0-fr-oth-JSpec/persistence-2_0-final-spec.pdf page 286. I think need assign the EntityManager in each method separately. diff --git a/camel-core/src/main/java/org/apache/camel/model/rest/RestConfigurationDefinition.java b/camel-core/src/main/java/org/apache/camel/model/rest/RestConfigurationDefinition.java index 0e8c170..797b06a 100644 --- a/camel-core/src/main/java/org/apache/camel/model/rest/RestConfigurationDefinition.java +++ b/camel-core/src/main/java/org/apache/camel/model/rest/RestConfigurationDefinition.java @@ -16,9 +16,14 @@ */ package org.apache.camel.model.rest; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlElementRef; import javax.xml.bind.annotation.XmlRootElement; import org.apache.camel.CamelContext; @@ -41,10 +46,8 @@ public class RestConfigurationDefinition { @XmlAttribute private String port; - // TODO: get properties to work with JAXB in the XSD model - -// @XmlElementRef -// private List<PropertyDefinition> properties = new ArrayList<PropertyDefinition>(); + @XmlElementRef + private List<RestPropertyDefinition> properties = new ArrayList<RestPropertyDefinition>(); public String getComponent() { return component; @@ -70,6 +73,14 @@ public class RestConfigurationDefinition { this.port = port; } + public List<RestPropertyDefinition> getProperties() { + return properties; + } + + public void setProperties(List<RestPropertyDefinition> properties) { + this.properties = properties; + } + // Fluent API //------------------------------------------------------------------------- @@ -97,10 +108,10 @@ public class RestConfigurationDefinition { } public RestConfigurationDefinition property(String key, String value) { - /*PropertyDefinition prop = new PropertyDefinition(); + RestPropertyDefinition prop = new RestPropertyDefinition(); prop.setKey(key); prop.setValue(value); - getProperties().add(prop);*/ + getProperties().add(prop); return this; } @@ -116,26 +127,25 @@ public class RestConfigurationDefinition { */ public RestConfiguration asRestConfiguration(CamelContext context) throws Exception { RestConfiguration answer = new RestConfiguration(); - if (getComponent() != null) { - answer.setComponent(CamelContextHelper.parseText(context, getComponent())); + if (component != null) { + answer.setComponent(CamelContextHelper.parseText(context, component)); } - if (getHost() != null) { - answer.setHost(CamelContextHelper.parseText(context, getHost())); + if (host != null) { + answer.setHost(CamelContextHelper.parseText(context, host)); } - if (getPort() != null) { - answer.setPort(CamelContextHelper.parseInteger(context, getPort())); + if (port != null) { + answer.setPort(CamelContextHelper.parseInteger(context, port)); } - /*if (!properties.isEmpty()) { + if (!properties.isEmpty()) { Map<String, Object> props = new HashMap<String, Object>(); - for (PropertyDefinition prop : properties) { + for (RestPropertyDefinition prop : properties) { String key = prop.getKey(); String value = CamelContextHelper.parseText(context, prop.getValue()); props.put(key, value); } answer.setProperties(props); - }*/ + } return answer; - } } diff --git a/camel-core/src/main/java/org/apache/camel/model/rest/RestPropertyDefinition.java b/camel-core/src/main/java/org/apache/camel/model/rest/RestPropertyDefinition.java new file mode 100644 index 0000000..e1d5897 --- /dev/null +++ b/camel-core/src/main/java/org/apache/camel/model/rest/RestPropertyDefinition.java @@ -0,0 +1,52 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.model.rest; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlRootElement; + +/** + * Represents the XML type for &lt;restProperty&gt;. + */ +@XmlRootElement(name = "restProperty") +@XmlAccessorType(XmlAccessType.FIELD) +public class RestPropertyDefinition { + + @XmlAttribute(required = true) + String key; + + @XmlAttribute(required = true) + String value; + + public void setKey(String key) { + this.key = key; + } + + public String getKey() { + return key; + } + + public void setValue(String value) { + this.value = value; + } + + public String getValue() { + return value; + } +}
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-7364_7bbb88ba.diff
bugs-dot-jar_data_CAMEL-5437_da05f5aa
--- BugID: CAMEL-5437 Summary: Add support for batch consumer's empty messages to aggregator Description: |- Aggregator supports completion based on the batch consumer data (option completionFromBatchConsumer) Some batch consumers (eg. File) can send an empty message if there is no input (option sendEmptyMessageWhenIdle for File consumer). Aggregator is unable to handle such messages properly - the messages are aggregated, but Aggregator never completes. Here is the relevant fragment from AggregateProcessor.isCompleted(String, Exchange) int size = exchange.getProperty(Exchange.BATCH_SIZE, 0, Integer.class); if (size > 0 && batchConsumerCounter.intValue() >= size) { .... } Please add support for this combination of options. diff --git a/camel-core/src/main/java/org/apache/camel/impl/ScheduledBatchPollingConsumer.java b/camel-core/src/main/java/org/apache/camel/impl/ScheduledBatchPollingConsumer.java index 5ff6208..c54240c 100644 --- a/camel-core/src/main/java/org/apache/camel/impl/ScheduledBatchPollingConsumer.java +++ b/camel-core/src/main/java/org/apache/camel/impl/ScheduledBatchPollingConsumer.java @@ -20,6 +20,7 @@ import java.util.concurrent.ScheduledExecutorService; import org.apache.camel.BatchConsumer; import org.apache.camel.Endpoint; +import org.apache.camel.Exchange; import org.apache.camel.Processor; import org.apache.camel.ShutdownRunningTask; import org.apache.camel.spi.ShutdownAware; @@ -112,4 +113,15 @@ public abstract class ScheduledBatchPollingConsumer extends ScheduledPollConsume // we are shutting down so only continue if we are configured to complete all tasks return ShutdownRunningTask.CompleteAllTasks == shutdownRunningTask; } + + @Override + protected void processEmptyMessage() throws Exception { + Exchange exchange = getEndpoint().createExchange(); + // enrich exchange, so we send an empty message with the batch details + exchange.setProperty(Exchange.BATCH_INDEX, 0); + exchange.setProperty(Exchange.BATCH_SIZE, 1); + exchange.setProperty(Exchange.BATCH_COMPLETE, true); + log.debug("Sending empty message as there were no messages from polling: {}", this.getEndpoint()); + getProcessor().process(exchange); + } }
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-5437_da05f5aa.diff
bugs-dot-jar_data_CAMEL-6593_7f8a295a
--- BugID: CAMEL-6593 Summary: Predicates from java dsl are not dumped to xml correctly Description: |- Predicates defined in the java dsl are not dumped to xml when using jmx. Eg, this java dsl route: {code} from("seda:a").choice().when(header("test").isNotNull()).log("not null").end().to("mock:a"); {code} Will be dumped as this: {code} <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <route group="com.example.TestRoute" id="route1" xmlns="http://camel.apache.org/schema/spring"> <from uri="seda:a"/> <choice id="choice23"> <when id="when24"> <expressionDefinition/> <log message="not null" id="log20"/> </when> </choice> <to uri="mock:a" id="to17"/> </route> {code} The <expressionDefinition> element should contain the expression. This seems similar to CAMEL-4733. diff --git a/camel-core/src/main/java/org/apache/camel/model/ExpressionNode.java b/camel-core/src/main/java/org/apache/camel/model/ExpressionNode.java index 41f97ce..ef64c2d 100644 --- a/camel-core/src/main/java/org/apache/camel/model/ExpressionNode.java +++ b/camel-core/src/main/java/org/apache/camel/model/ExpressionNode.java @@ -143,5 +143,14 @@ public class ExpressionNode extends ProcessorDefinition<ExpressionNode> { expression = clause.getExpressionType(); } } + + if (expression != null && expression.getExpression() == null) { + // use toString from predicate or expression so we have some information to show in the route model + if (expression.getPredicate() != null) { + expression.setExpression(expression.getPredicate().toString()); + } else if (expression.getExpressionValue() != null) { + expression.setExpression(expression.getExpressionValue().toString()); + } + } } } diff --git a/camel-core/src/main/java/org/apache/camel/model/language/ExpressionDefinition.java b/camel-core/src/main/java/org/apache/camel/model/language/ExpressionDefinition.java index b423afa..52b0d1c 100644 --- a/camel-core/src/main/java/org/apache/camel/model/language/ExpressionDefinition.java +++ b/camel-core/src/main/java/org/apache/camel/model/language/ExpressionDefinition.java @@ -243,20 +243,17 @@ public class ExpressionDefinition implements Expression, Predicate { * Returns some descriptive text to describe this node */ public String getLabel() { - String language = getExpression(); - if (ObjectHelper.isEmpty(language)) { - Predicate predicate = getPredicate(); - if (predicate != null) { - return predicate.toString(); - } - Expression expressionValue = getExpressionValue(); - if (expressionValue != null) { - return expressionValue.toString(); - } - } else { - return language; + Predicate predicate = getPredicate(); + if (predicate != null) { + return predicate.toString(); } - return ""; + Expression expressionValue = getExpressionValue(); + if (expressionValue != null) { + return expressionValue.toString(); + } + + String exp = getExpression(); + return exp != null ? exp : ""; } /**
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-6593_7f8a295a.diff
bugs-dot-jar_data_CAMEL-3276_205420e2
--- BugID: CAMEL-3276 Summary: Multicast with pipeline may cause wrong aggregated exchange Description: |+ This is a problem when using 2 set of nested pipeline and doing a transform as the first processor in that pipeline {code} from("direct:start").multicast(new SumAggregateBean()) .pipeline().transform(bean(IncreaseOne.class)).bean(new IncreaseTwo()).to("log:foo").end() .pipeline().transform(bean(IncreaseOne.class)).bean(new IncreaseTwo()).to("log:bar").end() .end() .to("mock:result"); {code} diff --git a/camel-core/src/main/java/org/apache/camel/util/ExchangeHelper.java b/camel-core/src/main/java/org/apache/camel/util/ExchangeHelper.java index 0aa9501..7b59811 100644 --- a/camel-core/src/main/java/org/apache/camel/util/ExchangeHelper.java +++ b/camel-core/src/main/java/org/apache/camel/util/ExchangeHelper.java @@ -208,11 +208,15 @@ public final class ExchangeHelper { // have created any OUT; such as a mock:endpoint // so lets assume the last IN is the OUT if (result.getPattern().isOutCapable()) { - // only set OUT if its OUT capable + // only set OUT if its OUT capable or already has OUT result.getOut().copyFrom(source.getIn()); } else { // if not replace IN instead to keep the MEP result.getIn().copyFrom(source.getIn()); + // clear any existing OUT as the result is on the IN + if (result.hasOut()) { + result.setOut(null); + } } }
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-3276_205420e2.diff
bugs-dot-jar_data_CAMEL-4509_8e3450f4
--- BugID: CAMEL-4509 Summary: Header not set after dead letter queue handles unmarshal error Description: |- We have a route which unmarshals a soap msg into an object. On that route is a dead letter queue error handler. That DLQ sets headers on the message used later for error reporting. If the error is thrown by the marshaller, the *first header* that we try to set is wiped out. The 2nd header is set with no problem. If an error is thrown by something other than the marshaller, the correct headers are set. See attached project with failed test case (canSetHeadersOnBadXmlDeadLetter) diff --git a/camel-core/src/main/java/org/apache/camel/processor/MarshalProcessor.java b/camel-core/src/main/java/org/apache/camel/processor/MarshalProcessor.java index b4e3289..9a01a55 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/MarshalProcessor.java +++ b/camel-core/src/main/java/org/apache/camel/processor/MarshalProcessor.java @@ -55,9 +55,15 @@ public class MarshalProcessor extends ServiceSupport implements Processor, Trace Message out = exchange.getOut(); out.copyFrom(in); - dataFormat.marshal(exchange, body, buffer); - byte[] data = buffer.toByteArray(); - out.setBody(data); + try { + dataFormat.marshal(exchange, body, buffer); + byte[] data = buffer.toByteArray(); + out.setBody(data); + } catch (Exception e) { + // remove OUT message, as an exception occurred + exchange.setOut(null); + throw e; + } } @Override diff --git a/camel-core/src/main/java/org/apache/camel/processor/UnmarshalProcessor.java b/camel-core/src/main/java/org/apache/camel/processor/UnmarshalProcessor.java index 414b088..b8c5e5f 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/UnmarshalProcessor.java +++ b/camel-core/src/main/java/org/apache/camel/processor/UnmarshalProcessor.java @@ -27,6 +27,7 @@ import org.apache.camel.Traceable; import org.apache.camel.spi.DataFormat; import org.apache.camel.support.ServiceSupport; import org.apache.camel.util.ExchangeHelper; +import org.apache.camel.util.IOHelper; import org.apache.camel.util.ObjectHelper; import org.apache.camel.util.ServiceHelper; @@ -56,10 +57,12 @@ public class UnmarshalProcessor extends ServiceSupport implements Processor, Tra Object result = dataFormat.unmarshal(exchange, stream); out.setBody(result); + } catch (Exception e) { + // remove OUT message, as an exception occurred + exchange.setOut(null); + throw e; } finally { - if (stream != null) { - stream.close(); - } + IOHelper.close(stream, "input stream"); } }
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-4509_8e3450f4.diff
bugs-dot-jar_data_CAMEL-4474_06a8489a
--- BugID: CAMEL-4474 Summary: 'file: consumer does not create directory' Description: "According to http://camel.apache.org/file2.html autoCreate is true by default and should for a consumer create the directory.\n{noformat}\nautoCreate \ttrue \tAutomatically create missing directories in the file's pathname. For the file consumer, that means creating the starting directory. For the file producer, it means the directory the files should be written to. \n{noformat}\nThis does not happen and thus a route startup would fail." diff --git a/camel-core/src/main/java/org/apache/camel/component/file/FileEndpoint.java b/camel-core/src/main/java/org/apache/camel/component/file/FileEndpoint.java index 8109971..b8aaff3 100644 --- a/camel-core/src/main/java/org/apache/camel/component/file/FileEndpoint.java +++ b/camel-core/src/main/java/org/apache/camel/component/file/FileEndpoint.java @@ -49,14 +49,8 @@ public class FileEndpoint extends GenericFileEndpoint<File> { ObjectHelper.notNull(operations, "operations"); ObjectHelper.notNull(file, "file"); - // we assume its a file if the name has a dot in it (eg foo.txt) - boolean isDirectory = file.isDirectory(); - if (!isDirectory && file.getName().contains(".")) { - throw new IllegalArgumentException("Only directory is supported. Endpoint must be configured with a valid starting directory: " + file); - } - // auto create starting directory if needed - if (!file.exists() && !isDirectory) { + if (!file.exists() && !file.isDirectory()) { if (isAutoCreate()) { log.debug("Creating non existing starting directory: {}", file); boolean absolute = FileUtil.isAbsolute(file);
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-4474_06a8489a.diff
bugs-dot-jar_data_CAMEL-3314_4badd9c5
--- BugID: CAMEL-3314 Summary: Property resolve in EIP does not work when in a sub route. Description: "The 2.5 feature: \"The EIP now supports property placeholders in the String based options (a few spots in Java DSL where its not possible). For example: \n<convertBodyTo type=\"String\" charset=\"{{foo.myCharset}}\"/>\" does not work correctly when ie nested in a <choice> tag.\n\nSee discussion: http://camel.465427.n5.nabble.com/Camel-2-5-Propertyplaceholders-and-Spring-DSL-still-not-working-td3251608.html#a3251608\n\nExample route:\n\nThis works: \n<route> \n <from uri=\"direct:in\" /> \n <convertBodyTo type=\"String\" charset=\"{{charset.external}}\" />\t\n <log message=\"Charset: {{charset.external}}\" /> \n <to uri=\"mock:out\" /> \n</route> \n\nThis fails: \n<route> \n <from uri=\"direct:in\" /> \n <choice> \n <when> \n <constant>true</constant> \n <convertBodyTo type=\"String\" charset=\"{{charset.external}}\" />\t\n </when> \n \ </choice> \n <to uri=\"mock:out\" /> \n</route> " diff --git a/camel-core/src/main/java/org/apache/camel/model/ProcessorDefinition.java b/camel-core/src/main/java/org/apache/camel/model/ProcessorDefinition.java index a270651..67d135a 100644 --- a/camel-core/src/main/java/org/apache/camel/model/ProcessorDefinition.java +++ b/camel-core/src/main/java/org/apache/camel/model/ProcessorDefinition.java @@ -345,6 +345,10 @@ public abstract class ProcessorDefinition<Type extends ProcessorDefinition<Type> protected Processor createOutputsProcessor(RouteContext routeContext, Collection<ProcessorDefinition> outputs) throws Exception { List<Processor> list = new ArrayList<Processor>(); for (ProcessorDefinition<?> output : outputs) { + + // resolve properties before we create the processor + resolvePropertyPlaceholders(routeContext, output); + Processor processor = null; // at first use custom factory if (routeContext.getCamelContext().getProcessorFactory() != null) { @@ -383,7 +387,7 @@ public abstract class ProcessorDefinition<Type extends ProcessorDefinition<Type> Processor processor = null; // resolve properties before we create the processor - resolvePropertyPlaceholders(routeContext); + resolvePropertyPlaceholders(routeContext, this); // at first use custom factory if (routeContext.getCamelContext().getProcessorFactory() != null) { @@ -402,28 +406,29 @@ public abstract class ProcessorDefinition<Type extends ProcessorDefinition<Type> } /** - * Inspects this processor definition and resolves any property placeholders from its properties. + * Inspects the given processor definition and resolves any property placeholders from its properties. * <p/> * This implementation will check all the getter/setter pairs on this instance and for all the values * (which is a String type) will be property placeholder resolved. * * @param routeContext the route context + * @param definition the processor definition * @throws Exception is thrown if property placeholders was used and there was an error resolving them * @see org.apache.camel.CamelContext#resolvePropertyPlaceholders(String) * @see org.apache.camel.component.properties.PropertiesComponent */ - protected void resolvePropertyPlaceholders(RouteContext routeContext) throws Exception { + protected void resolvePropertyPlaceholders(RouteContext routeContext, ProcessorDefinition definition) throws Exception { if (log.isTraceEnabled()) { - log.trace("Resolving property placeholders for: " + this); + log.trace("Resolving property placeholders for: " + definition); } // find all String getter/setter Map<Object, Object> properties = new HashMap<Object, Object>(); - IntrospectionSupport.getProperties(this, properties, null); + IntrospectionSupport.getProperties(definition, properties, null); if (!properties.isEmpty()) { if (log.isTraceEnabled()) { - log.trace("There are " + properties.size() + " properties on: " + this); + log.trace("There are " + properties.size() + " properties on: " + definition); } // lookup and resolve properties for String based properties @@ -437,7 +442,7 @@ public abstract class ProcessorDefinition<Type extends ProcessorDefinition<Type> text = routeContext.getCamelContext().resolvePropertyPlaceholders(text); if (text != value) { // invoke setter as the text has changed - IntrospectionSupport.setProperty(this, name, text); + IntrospectionSupport.setProperty(definition, name, text); if (log.isDebugEnabled()) { log.debug("Changed property [" + name + "] from: " + value + " to: " + text); }
bugs-dot-jar/camel_extracted_diff/developer-patch_bugs-dot-jar_CAMEL-3314_4badd9c5.diff