[camel] branch master updated (7dc7bac -> 056ef4e)

classic Classic list List threaded Threaded
14 messages Options
Reply | Threaded
Open this post in threaded view
|

[camel] branch master updated (7dc7bac -> 056ef4e)

davsclaus-2
This is an automated email from the ASF dual-hosted git repository.

davsclaus pushed a change to branch master
in repository https://gitbox.apache.org/repos/asf/camel.git.


    from 7dc7bac  Update documentation, as CamelContext#getProperties was replaced with CamelContext#getGlobalOptions in Camel 3.
     new cd2f6a3  camel-core - Optimize to let type converter be eager created to avoid overhead in getTypeConverter method which is used a lot.
     new 005921c  camel-core - Optimize to let type converter be eager created to avoid overhead in getTypeConverter method which is used a lot.
     new 857c432  camel-core - Optimize
     new e0d7b8c  Polished
     new 55f2cd4  Add missing license header
     new 53acc37  camel-core - Optimize to let type converter be eager created to avoid overhead in getTypeConverter method which is used a lot.
     new 4fce147  CAMEL-14565: camel-webhook refactor a bit and add docs for missing option.
     new 37c415c  Regen
     new 62ae98f  CAMEL-14565: camel-webhook refactor a bit and add docs for missing option.
     new da1e828  CAMEL-14572: camel-core - Optimize type converter for some basic convertions
     new 6c891f4  Reduce logging noise
     new f1a5202  CAMEL-14572: camel-core - Optimize type converter for some basic convertions
     new 056ef4e  Fixed CS

The 13 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 .../apache/camel/component/bean/MethodInfo.java    |   2 +-
 .../java/org/apache/camel/cdi/CdiCamelContext.java |  11 +++
 .../org/apache/camel/cdi/CdiCamelExtension.java    |  11 +--
 .../component/couchdb/CouchDbComponentTest.java    |   2 +-
 .../camel/component/cxf/CxfEndpointTest.java       |  16 +++-
 .../debezium/DebeziumMySqlComponentTest.java       |   4 +-
 .../quartz/QuartzOneCamelContextRestartTest.java   |   4 +-
 .../camel/component/rabbitmq/RabbitConsumer.java   |   5 +-
 .../sql/stored/ProducerBatchInvalidTest.java       |   3 +-
 .../component/webhook/WebhookCapableEndpoint.java  |   5 +-
 .../camel/component/webhook/WebhookComponent.java  |  62 +-----------
 .../component/webhook/WebhookConfiguration.java    |  91 +++++++++++++++++-
 .../camel/component/webhook/WebhookEndpoint.java   |  11 +--
 .../component/webhook/WebhookBasePathTest.java     |   2 +-
 .../component/webhook/WebhookHttpBindingTest.java  |   4 +-
 .../component/webhook/WebhookMultiRouteTest.java   |   4 +-
 components/camel-workday/pom.xml                   |  18 ++++
 .../main/java/org/apache/camel/CamelContext.java   |   4 +-
 .../java/org/apache/camel/ExchangePattern.java     |   7 +-
 ...ware.java => AnnotationScanTypeConverters.java} |  19 ++--
 .../camel/support/service/ServiceSupport.java      |   5 +-
 .../camel/converter/TimePatternConverter.java      |   1 -
 .../impl/converter/BaseTypeConverterRegistry.java  | 104 ++++++++++++++++++---
 .../camel/impl/converter/DefaultTypeConverter.java |  44 ++++++---
 .../camel/impl/engine/AbstractCamelContext.java    |  23 +++++
 .../camel/impl/engine/DefaultProducerTemplate.java |  42 ++++-----
 .../camel/impl/engine/DefaultReactiveExecutor.java |   4 +-
 .../org/apache/camel/impl/DefaultCamelContext.java |   4 +
 ...seMethodWithMatchingTypeAndSkipSettersTest.java |   3 +-
 .../camel/impl/MultipleLifecycleStrategyTest.java  |   4 +-
 .../org/apache/camel/main/BaseMainSupport.java     |   3 +
 .../org/apache/camel/support/DefaultMessage.java   |  62 +++++++++---
 .../main/java/org/apache/camel/util/TimeUtils.java |  12 +--
 .../modules/ROOT/pages/mail-component.adoc         |   3 +-
 .../modules/ROOT/pages/webhook-component.adoc      |  12 +--
 .../modules/ROOT/pages/yammer-component.adoc       |   6 +-
 .../modules/ROOT/pages/release-guide.adoc          |   4 +-
 pom.xml                                            |   3 +
 38 files changed, 427 insertions(+), 197 deletions(-)
 copy core/camel-api/src/main/java/org/apache/camel/spi/{RouteIdAware.java => AnnotationScanTypeConverters.java} (62%)

Reply | Threaded
Open this post in threaded view
|

[camel] 01/13: camel-core - Optimize to let type converter be eager created to avoid overhead in getTypeConverter method which is used a lot.

davsclaus-2
This is an automated email from the ASF dual-hosted git repository.

davsclaus pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/camel.git

commit cd2f6a312dd632891deae6fe70fe05b7aebc37f0
Author: Claus Ibsen <[hidden email]>
AuthorDate: Sat Feb 15 15:49:33 2020 +0100

    camel-core - Optimize to let type converter be eager created to avoid overhead in getTypeConverter method which is used a lot.
---
 .../main/java/org/apache/camel/component/bean/MethodInfo.java  |  2 +-
 .../src/main/java/org/apache/camel/ExchangePattern.java        |  7 +------
 .../org/apache/camel/impl/engine/AbstractCamelContext.java     | 10 +++-------
 .../main/java/org/apache/camel/impl/DefaultCamelContext.java   |  4 ++++
 .../BeanChoseMethodWithMatchingTypeAndSkipSettersTest.java     |  3 ++-
 .../org/apache/camel/impl/MultipleLifecycleStrategyTest.java   |  4 ++--
 6 files changed, 13 insertions(+), 17 deletions(-)

diff --git a/components/camel-bean/src/main/java/org/apache/camel/component/bean/MethodInfo.java b/components/camel-bean/src/main/java/org/apache/camel/component/bean/MethodInfo.java
index fa76971..96a68c5 100644
--- a/components/camel-bean/src/main/java/org/apache/camel/component/bean/MethodInfo.java
+++ b/components/camel-bean/src/main/java/org/apache/camel/component/bean/MethodInfo.java
@@ -310,7 +310,7 @@ public class MethodInfo {
         LOG.trace("Setting bean invocation result : {}", result);
 
         // the bean component forces OUT if the MEP is OUT capable
-        boolean out = ExchangeHelper.isOutCapable(exchange) || exchange.hasOut();
+        boolean out = exchange.hasOut() || ExchangeHelper.isOutCapable(exchange);
         Message old;
         if (out) {
             old = exchange.getOut();
diff --git a/core/camel-api/src/main/java/org/apache/camel/ExchangePattern.java b/core/camel-api/src/main/java/org/apache/camel/ExchangePattern.java
index 0f6344c..65e5a45 100644
--- a/core/camel-api/src/main/java/org/apache/camel/ExchangePattern.java
+++ b/core/camel-api/src/main/java/org/apache/camel/ExchangePattern.java
@@ -38,12 +38,7 @@ public enum ExchangePattern {
      * Return true if there can be an OUT message
      */
     public boolean isOutCapable() {
-        switch (this) {
-            case InOnly:
-                return false;
-            default:
-                return true;
-        }
+        return this != ExchangePattern.InOnly;
     }
 
     public static ExchangePattern asEnum(String value) {
diff --git a/core/camel-base/src/main/java/org/apache/camel/impl/engine/AbstractCamelContext.java b/core/camel-base/src/main/java/org/apache/camel/impl/engine/AbstractCamelContext.java
index 1387bad..d15ad4a 100644
--- a/core/camel-base/src/main/java/org/apache/camel/impl/engine/AbstractCamelContext.java
+++ b/core/camel-base/src/main/java/org/apache/camel/impl/engine/AbstractCamelContext.java
@@ -345,6 +345,9 @@ public abstract class AbstractCamelContext extends ServiceSupport implements Ext
             LRUCacheFactory.init();
         }
 
+        // setup type converter eager as its highly in use and should not be lazy initialized
+        setTypeConverter(createTypeConverter());
+
         // setup management first since end users may use it to add event
         // notifiers using the management strategy before the CamelContext has been started
         setupManagement(null);
@@ -1699,13 +1702,6 @@ public abstract class AbstractCamelContext extends ServiceSupport implements Ext
 
     @Override
     public TypeConverter getTypeConverter() {
-        if (typeConverter == null) {
-            synchronized (lock) {
-                if (typeConverter == null) {
-                    setTypeConverter(createTypeConverter());
-                }
-            }
-        }
         return typeConverter;
     }
 
diff --git a/core/camel-core-engine/src/main/java/org/apache/camel/impl/DefaultCamelContext.java b/core/camel-core-engine/src/main/java/org/apache/camel/impl/DefaultCamelContext.java
index 6e141a8..df1997a 100644
--- a/core/camel-core-engine/src/main/java/org/apache/camel/impl/DefaultCamelContext.java
+++ b/core/camel-core-engine/src/main/java/org/apache/camel/impl/DefaultCamelContext.java
@@ -176,6 +176,10 @@ public class DefaultCamelContext extends AbstractModelCamelContext {
     @Override
     protected TypeConverterRegistry createTypeConverterRegistry() {
         TypeConverter typeConverter = getTypeConverter();
+        // type converter is also registry so create type converter
+        if (typeConverter == null) {
+            typeConverter = createTypeConverter();
+        }
         if (typeConverter instanceof TypeConverterRegistry) {
             return (TypeConverterRegistry)typeConverter;
         }
diff --git a/core/camel-core/src/test/java/org/apache/camel/component/bean/BeanChoseMethodWithMatchingTypeAndSkipSettersTest.java b/core/camel-core/src/test/java/org/apache/camel/component/bean/BeanChoseMethodWithMatchingTypeAndSkipSettersTest.java
index 65b5d24..62d8c5c 100644
--- a/core/camel-core/src/test/java/org/apache/camel/component/bean/BeanChoseMethodWithMatchingTypeAndSkipSettersTest.java
+++ b/core/camel-core/src/test/java/org/apache/camel/component/bean/BeanChoseMethodWithMatchingTypeAndSkipSettersTest.java
@@ -46,7 +46,6 @@ public class BeanChoseMethodWithMatchingTypeAndSkipSettersTest extends ContextTe
     @Override
     protected CamelContext createCamelContext() throws Exception {
         CamelContext context = super.createCamelContext();
-        service.setConverter(context.getTypeConverter());
         return context;
     }
 
@@ -76,6 +75,8 @@ public class BeanChoseMethodWithMatchingTypeAndSkipSettersTest extends ContextTe
         return new RouteBuilder() {
             @Override
             public void configure() throws Exception {
+                service.setConverter(context.getTypeConverter());
+
                 from("file://target/data/file/order?initialDelay=0&delay=10").bean("orderService").to("mock:queue:order");
 
                 from("seda:xml").bean("orderService").to("mock:queue:order");
diff --git a/core/camel-core/src/test/java/org/apache/camel/impl/MultipleLifecycleStrategyTest.java b/core/camel-core/src/test/java/org/apache/camel/impl/MultipleLifecycleStrategyTest.java
index baab809..b636e2e 100644
--- a/core/camel-core/src/test/java/org/apache/camel/impl/MultipleLifecycleStrategyTest.java
+++ b/core/camel-core/src/test/java/org/apache/camel/impl/MultipleLifecycleStrategyTest.java
@@ -50,8 +50,8 @@ public class MultipleLifecycleStrategyTest extends TestSupport {
         context.stop();
 
         List<String> expectedEvents = Arrays.asList("onContextStart",
-            "onServiceAdd", "onServiceAdd", "onServiceAdd", "onServiceAdd", "onServiceAdd", "onServiceAdd",
-            "onServiceAdd", "onServiceAdd", "onServiceAdd", "onServiceAdd", "onServiceAdd", "onServiceAdd",
+            "onServiceAdd", "onServiceAdd", "onServiceAdd", "onServiceAdd", "onServiceAdd",
+            "onServiceAdd", "onServiceAdd", "onServiceAdd", "onServiceAdd", "onServiceAdd",
             "onComponentAdd", "onEndpointAdd", "onComponentRemove", "onContextStop");
         
         assertEquals(expectedEvents, dummy1.getEvents());

Reply | Threaded
Open this post in threaded view
|

[camel] 02/13: camel-core - Optimize to let type converter be eager created to avoid overhead in getTypeConverter method which is used a lot.

davsclaus-2
In reply to this post by davsclaus-2
This is an automated email from the ASF dual-hosted git repository.

davsclaus pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/camel.git

commit 005921c72932a12ca6ca2149aaf7b782e4b5dd5b
Author: Claus Ibsen <[hidden email]>
AuthorDate: Sat Feb 15 19:37:45 2020 +0100

    camel-core - Optimize to let type converter be eager created to avoid overhead in getTypeConverter method which is used a lot.
---
 .../java/org/apache/camel/cdi/CdiCamelContext.java | 11 +++++++++++
 .../org/apache/camel/cdi/CdiCamelExtension.java    | 11 +++++------
 .../camel/component/cxf/CxfEndpointTest.java       | 16 +++++++++++++--
 .../main/java/org/apache/camel/CamelContext.java   |  4 +++-
 .../camel/support/service/ServiceSupport.java      |  5 +++--
 .../camel/impl/engine/AbstractCamelContext.java    | 23 +++++++++++++++++++++-
 .../org/apache/camel/main/BaseMainSupport.java     |  3 +++
 7 files changed, 61 insertions(+), 12 deletions(-)

diff --git a/components/camel-cdi/src/main/java/org/apache/camel/cdi/CdiCamelContext.java b/components/camel-cdi/src/main/java/org/apache/camel/cdi/CdiCamelContext.java
index deca9f6..63a39b5 100644
--- a/components/camel-cdi/src/main/java/org/apache/camel/cdi/CdiCamelContext.java
+++ b/components/camel-cdi/src/main/java/org/apache/camel/cdi/CdiCamelContext.java
@@ -16,6 +16,7 @@
  */
 package org.apache.camel.cdi;
 
+import org.apache.camel.TypeConverter;
 import org.apache.camel.impl.DefaultCamelContext;
 
 /**
@@ -35,4 +36,14 @@ import org.apache.camel.impl.DefaultCamelContext;
 @Vetoed
 public class CdiCamelContext extends DefaultCamelContext {
 
+    @Override
+    protected boolean eagerCreateTypeConverter() {
+        // camel-cdi is complex so we cant optimize
+        return false;
+    }
+
+    @Override
+    public TypeConverter getTypeConverter() {
+        return getOrCreateTypeConverter();
+    }
 }
diff --git a/components/camel-cdi/src/main/java/org/apache/camel/cdi/CdiCamelExtension.java b/components/camel-cdi/src/main/java/org/apache/camel/cdi/CdiCamelExtension.java
index 4b4d7b2..ad64f8d 100644
--- a/components/camel-cdi/src/main/java/org/apache/camel/cdi/CdiCamelExtension.java
+++ b/components/camel-cdi/src/main/java/org/apache/camel/cdi/CdiCamelExtension.java
@@ -65,7 +65,6 @@ import org.apache.camel.PropertyInject;
 import org.apache.camel.RoutesBuilder;
 import org.apache.camel.ServiceStatus;
 import org.apache.camel.TypeConverter;
-import org.apache.camel.impl.DefaultCamelContext;
 import org.apache.camel.model.Model;
 import org.apache.camel.model.RouteContainer;
 import org.apache.camel.spi.CamelEvent;
@@ -348,12 +347,12 @@ public class CdiCamelExtension implements Extension {
     }
 
     private SyntheticBean<?> camelContextBean(BeanManager manager, Class<?> beanClass, Annotation... qualifiers) {
-        SyntheticAnnotated annotated = new SyntheticAnnotated(DefaultCamelContext.class,
-            manager.createAnnotatedType(DefaultCamelContext.class).getTypeClosure(), beanClass, qualifiers);
-        return new SyntheticBean<>(manager, annotated, DefaultCamelContext.class,
+        SyntheticAnnotated annotated = new SyntheticAnnotated(CdiCamelContext.class,
+            manager.createAnnotatedType(CdiCamelContext.class).getTypeClosure(), beanClass, qualifiers);
+        return new SyntheticBean<>(manager, annotated, CdiCamelContext.class,
             environment.camelContextInjectionTarget(
-                new SyntheticInjectionTarget<>(DefaultCamelContext::new), annotated, manager, this), bean ->
-            "Default Camel context bean with qualifiers " + bean.getQualifiers());
+                new SyntheticInjectionTarget<>(CdiCamelContext::new), annotated, manager, this), bean ->
+            "CdiCamelContext bean with qualifiers " + bean.getQualifiers());
     }
 
     private void afterDeploymentValidation(@Observes AfterDeploymentValidation adv, BeanManager manager) {
diff --git a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfEndpointTest.java b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfEndpointTest.java
index 9826f89..7863092 100644
--- a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfEndpointTest.java
+++ b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfEndpointTest.java
@@ -57,6 +57,8 @@ public class CxfEndpointTest extends Assert {
     @Test
     public void testSettingContinucationTimout() throws Exception {
         CamelContext context = new DefaultCamelContext();
+        context.start();
+
         CxfEndpoint endpoint = context.getEndpoint(routerEndpointURI + "&continuationTimeout=800000",
                 CxfEndpoint.class);
         assertEquals("Get a wrong continucationTimeout value", 800000, endpoint.getContinuationTimeout());
@@ -67,7 +69,11 @@ public class CxfEndpointTest extends Assert {
 
         ClassPathXmlApplicationContext ctx =
                 new ClassPathXmlApplicationContext(new String[]{"org/apache/camel/component/cxf/CxfEndpointBeans.xml"});
-        CxfComponent cxfComponent = new CxfComponent(new SpringCamelContext(ctx));
+
+        SpringCamelContext context = new SpringCamelContext(ctx);
+        context.start();
+
+        CxfComponent cxfComponent = new CxfComponent(context);
         CxfSpringEndpoint endpoint = (CxfSpringEndpoint)cxfComponent.createEndpoint("cxf://bean:serviceEndpoint");
 
         assertEquals("Got the wrong endpoint address", endpoint.getAddress(),
@@ -85,7 +91,11 @@ public class CxfEndpointTest extends Assert {
 
         ExtensionManagerBus newBus = (ExtensionManagerBus) BusFactory.newInstance().createBus();
         newBus.setId("newCXF");
-        CxfComponent cxfComponent = new CxfComponent(new DefaultCamelContext());
+
+        CamelContext context = new DefaultCamelContext();
+        context.start();
+
+        CxfComponent cxfComponent = new CxfComponent(context);
         CxfEndpoint endpoint = (CxfEndpoint)cxfComponent.createEndpoint(routerEndpointURI);
         endpoint.setBus(newBus);
         CamelCxfClientImpl client = (CamelCxfClientImpl)endpoint.createClient();
@@ -104,6 +114,8 @@ public class CxfEndpointTest extends Assert {
         Processor processor = mock(Processor.class);
         registry.bind("myConfigurer", configurer);
         CamelContext camelContext = new DefaultCamelContext(registry);
+        camelContext.start();
+
         CxfComponent cxfComponent = new CxfComponent(camelContext);
         CxfEndpoint endpoint = (CxfEndpoint)cxfComponent.createEndpoint(routerEndpointURI + "&cxfConfigurer=#myConfigurer");
 
diff --git a/core/camel-api/src/main/java/org/apache/camel/CamelContext.java b/core/camel-api/src/main/java/org/apache/camel/CamelContext.java
index eb9dd95..bb122b3 100644
--- a/core/camel-api/src/main/java/org/apache/camel/CamelContext.java
+++ b/core/camel-api/src/main/java/org/apache/camel/CamelContext.java
@@ -673,7 +673,9 @@ public interface CamelContext extends StatefulService, RuntimeConfiguration {
     //-----------------------------------------------------------------------
 
     /**
-     * Returns the type converter used to coerce types from one type to another
+     * Returns the type converter used to coerce types from one type to another.
+     * <p/>
+     * Notice that this {@link CamelContext} should be at least initialized before you can get the type converter.
      *
      * @return the converter
      */
diff --git a/core/camel-api/src/main/java/org/apache/camel/support/service/ServiceSupport.java b/core/camel-api/src/main/java/org/apache/camel/support/service/ServiceSupport.java
index e2f5735..7602c73 100644
--- a/core/camel-api/src/main/java/org/apache/camel/support/service/ServiceSupport.java
+++ b/core/camel-api/src/main/java/org/apache/camel/support/service/ServiceSupport.java
@@ -74,9 +74,10 @@ public abstract class ServiceSupport implements StatefulService {
 
     @Override
     public void init() {
-        if (status <= BUILDED) {
+        // allow to initialize again if failed
+        if (status <= BUILDED || status >= FAILED) {
             synchronized (lock) {
-                if (status <= BUILDED) {
+                if (status <= BUILDED || status >= FAILED) {
                     LOG.trace("Initializing service: {}", this);
                     try {
                         doInit();
diff --git a/core/camel-base/src/main/java/org/apache/camel/impl/engine/AbstractCamelContext.java b/core/camel-base/src/main/java/org/apache/camel/impl/engine/AbstractCamelContext.java
index d15ad4a..58c1594 100644
--- a/core/camel-base/src/main/java/org/apache/camel/impl/engine/AbstractCamelContext.java
+++ b/core/camel-base/src/main/java/org/apache/camel/impl/engine/AbstractCamelContext.java
@@ -338,6 +338,14 @@ public abstract class AbstractCamelContext extends ServiceSupport implements Ext
         }
     }
 
+    /**
+     * Whether to eager create {@link TypeConverter} during initialization of CamelContext.
+     * This is enabled by default to optimize camel-core.
+     */
+    protected boolean eagerCreateTypeConverter() {
+        return true;
+    }
+
     @Override
     public void doInit() throws Exception {
         if (initialization != Initialization.Lazy) {
@@ -346,7 +354,9 @@ public abstract class AbstractCamelContext extends ServiceSupport implements Ext
         }
 
         // setup type converter eager as its highly in use and should not be lazy initialized
-        setTypeConverter(createTypeConverter());
+        if (eagerCreateTypeConverter()) {
+            getOrCreateTypeConverter();
+        }
 
         // setup management first since end users may use it to add event
         // notifiers using the management strategy before the CamelContext has been started
@@ -1705,6 +1715,17 @@ public abstract class AbstractCamelContext extends ServiceSupport implements Ext
         return typeConverter;
     }
 
+    protected TypeConverter getOrCreateTypeConverter() {
+        if (typeConverter == null) {
+            synchronized (lock) {
+                if (typeConverter == null) {
+                    setTypeConverter(createTypeConverter());
+                }
+            }
+        }
+        return typeConverter;
+    }
+
     public void setTypeConverter(TypeConverter typeConverter) {
         this.typeConverter = doAddService(typeConverter);
     }
diff --git a/core/camel-main/src/main/java/org/apache/camel/main/BaseMainSupport.java b/core/camel-main/src/main/java/org/apache/camel/main/BaseMainSupport.java
index cd5e5b6..3ac7b7b 100644
--- a/core/camel-main/src/main/java/org/apache/camel/main/BaseMainSupport.java
+++ b/core/camel-main/src/main/java/org/apache/camel/main/BaseMainSupport.java
@@ -574,6 +574,9 @@ public abstract class BaseMainSupport extends ServiceSupport {
     }
 
     protected void postProcessCamelContext(CamelContext camelContext) throws Exception {
+        // ensure camel is initialized
+        camelContext.init();
+
         configurePropertiesService(camelContext);
 
         // allow to do configuration before its started

Reply | Threaded
Open this post in threaded view
|

[camel] 03/13: camel-core - Optimize

davsclaus-2
In reply to this post by davsclaus-2
This is an automated email from the ASF dual-hosted git repository.

davsclaus pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/camel.git

commit 857c4325170a7b160677a6968bad59d91eeb6227
Author: Claus Ibsen <[hidden email]>
AuthorDate: Sat Feb 15 20:47:39 2020 +0100

    camel-core - Optimize
---
 .../camel/impl/engine/DefaultProducerTemplate.java | 42 +++++++--------
 .../org/apache/camel/support/DefaultMessage.java   | 62 +++++++++++++++++-----
 2 files changed, 71 insertions(+), 33 deletions(-)

diff --git a/core/camel-base/src/main/java/org/apache/camel/impl/engine/DefaultProducerTemplate.java b/core/camel-base/src/main/java/org/apache/camel/impl/engine/DefaultProducerTemplate.java
index 9352d69..d4bdd1e 100644
--- a/core/camel-base/src/main/java/org/apache/camel/impl/engine/DefaultProducerTemplate.java
+++ b/core/camel-base/src/main/java/org/apache/camel/impl/engine/DefaultProducerTemplate.java
@@ -199,11 +199,11 @@ public class DefaultProducerTemplate extends ServiceSupport implements ProducerT
     public Object sendBody(String endpointUri, ExchangePattern pattern, Object body) throws CamelExecutionException {
         Endpoint endpoint = resolveMandatoryEndpoint(endpointUri);
         Object result = sendBody(endpoint, pattern, body);
-        if (pattern.isOutCapable()) {
-            return result;
-        } else {
+        if (pattern == ExchangePattern.InOnly) {
             // return null if not OUT capable
             return null;
+        } else {
+            return result;
         }
     }
 
@@ -224,11 +224,11 @@ public class DefaultProducerTemplate extends ServiceSupport implements ProducerT
                                     final String header, final Object headerValue) throws CamelExecutionException {
         Exchange exchange = send(endpoint, pattern, createBodyAndHeaderProcessor(body, header, headerValue));
         Object result = extractResultBody(exchange, pattern);
-        if (pattern.isOutCapable()) {
-            return result;
-        } else {
+        if (pattern == ExchangePattern.InOnly) {
             // return null if not OUT capable
             return null;
+        } else {
+            return result;
         }
     }
 
@@ -237,11 +237,11 @@ public class DefaultProducerTemplate extends ServiceSupport implements ProducerT
                                     final String header, final Object headerValue) throws CamelExecutionException {
         Exchange exchange = send(endpoint, pattern, createBodyAndHeaderProcessor(body, header, headerValue));
         Object result = extractResultBody(exchange, pattern);
-        if (pattern.isOutCapable()) {
-            return result;
-        } else {
+        if (pattern == ExchangePattern.InOnly) {
             // return null if not OUT capable
             return null;
+        } else {
+            return result;
         }
     }
 
@@ -264,11 +264,11 @@ public class DefaultProducerTemplate extends ServiceSupport implements ProducerT
                                       final String property, final Object propertyValue) throws CamelExecutionException {
         Exchange exchange = send(endpoint, pattern, createBodyAndPropertyProcessor(body, property, propertyValue));
         Object result = extractResultBody(exchange, pattern);
-        if (pattern.isOutCapable()) {
-            return result;
-        } else {
+        if (pattern == ExchangePattern.InOnly) {
             // return null if not OUT capable
             return null;
+        } else {
+            return result;
         }
     }
 
@@ -277,11 +277,11 @@ public class DefaultProducerTemplate extends ServiceSupport implements ProducerT
                                       final String property, final Object propertyValue) throws CamelExecutionException {
         Exchange exchange = send(endpoint, pattern, createBodyAndPropertyProcessor(body, property, propertyValue));
         Object result = extractResultBody(exchange, pattern);
-        if (pattern.isOutCapable()) {
-            return result;
-        } else {
+        if (pattern == ExchangePattern.InOnly) {
             // return null if not OUT capable
             return null;
+        } else {
+            return result;
         }
     }
 
@@ -306,11 +306,11 @@ public class DefaultProducerTemplate extends ServiceSupport implements ProducerT
     public Object sendBodyAndHeaders(Endpoint endpoint, ExchangePattern pattern, final Object body, final Map<String, Object> headers) throws CamelExecutionException {
         Exchange exchange = send(endpoint, pattern, createBodyAndHeaders(body, headers));
         Object result = extractResultBody(exchange, pattern);
-        if (pattern.isOutCapable()) {
-            return result;
-        } else {
+        if (pattern == ExchangePattern.InOnly) {
             // return null if not OUT capable
             return null;
+        } else {
+            return result;
         }
     }
 
@@ -757,11 +757,11 @@ public class DefaultProducerTemplate extends ServiceSupport implements ProducerT
                 .thenApply(createCompletionFunction(onCompletion))
                 .thenApply(answer -> {
                     Object result = extractResultBody(answer, pattern);
-                    if (pattern.isOutCapable()) {
-                        return result;
-                    } else {
+                    if (pattern == ExchangePattern.InOnly) {
                         // return null if not OUT capable
                         return null;
+                    } else {
+                        return result;
                     }
                 });
     }
diff --git a/core/camel-support/src/main/java/org/apache/camel/support/DefaultMessage.java b/core/camel-support/src/main/java/org/apache/camel/support/DefaultMessage.java
index 0a5550a..e6a3a21 100644
--- a/core/camel-support/src/main/java/org/apache/camel/support/DefaultMessage.java
+++ b/core/camel-support/src/main/java/org/apache/camel/support/DefaultMessage.java
@@ -16,7 +16,6 @@
  */
 package org.apache.camel.support;
 
-import java.util.Collections;
 import java.util.HashMap;
 import java.util.HashSet;
 import java.util.Map;
@@ -25,6 +24,7 @@ import java.util.function.Supplier;
 
 import org.apache.camel.CamelContext;
 import org.apache.camel.Exchange;
+import org.apache.camel.ExtendedCamelContext;
 import org.apache.camel.spi.HeadersMapFactory;
 
 /**
@@ -48,12 +48,18 @@ public class DefaultMessage extends MessageSupport {
     }
 
     public DefaultMessage(CamelContext camelContext) {
-        setCamelContext(camelContext);
+        this.camelContext = (ExtendedCamelContext) camelContext;
+        this.typeConverter = camelContext.getTypeConverter();
     }
 
     @Override
     public Object getHeader(String name) {
-        if (hasHeaders()) {
+        if (headers == null) {
+            // force creating headers
+            headers = createHeaders();
+        }
+
+        if (!headers.isEmpty()) {
             return headers.get(name);
         } else {
             return null;
@@ -63,7 +69,13 @@ public class DefaultMessage extends MessageSupport {
     @Override
     public Object getHeader(String name, Object defaultValue) {
         Object answer = null;
-        if (hasHeaders()) {
+
+        if (headers == null) {
+            // force creating headers
+            headers = createHeaders();
+        }
+
+        if (!headers.isEmpty()) {
             answer = headers.get(name);
         }
         return answer != null ? answer : defaultValue;
@@ -72,7 +84,13 @@ public class DefaultMessage extends MessageSupport {
     @Override
     public Object getHeader(String name, Supplier<Object> defaultValueSupplier) {
         Object answer = null;
-        if (hasHeaders()) {
+
+        if (headers == null) {
+            // force creating headers
+            headers = createHeaders();
+        }
+
+        if (!headers.isEmpty()) {
             answer = headers.get(name);
         }
         return answer != null ? answer : defaultValueSupplier.get();
@@ -82,7 +100,13 @@ public class DefaultMessage extends MessageSupport {
     @SuppressWarnings("unchecked")
     public <T> T getHeader(String name, Class<T> type) {
         Object value = null;
-        if (hasHeaders()) {
+
+        if (headers == null) {
+            // force creating headers
+            headers = createHeaders();
+        }
+
+        if (!headers.isEmpty()) {
             value = headers.get(name);
         }
         if (value == null) {
@@ -111,7 +135,13 @@ public class DefaultMessage extends MessageSupport {
     @SuppressWarnings("unchecked")
     public <T> T getHeader(String name, Object defaultValue, Class<T> type) {
         Object value = null;
-        if (hasHeaders()) {
+
+        if (headers == null) {
+            // force creating headers
+            headers = createHeaders();
+        }
+
+        if (!headers.isEmpty()) {
             value = headers.get(name);
         }
         if (value == null) {
@@ -175,7 +205,11 @@ public class DefaultMessage extends MessageSupport {
 
     @Override
     public Object removeHeader(String name) {
-        if (!hasHeaders()) {
+        if (headers == null) {
+            // force creating headers
+            headers = createHeaders();
+        }
+        if (headers.isEmpty()) {
             return null;
         }
         return headers.remove(name);
@@ -188,7 +222,11 @@ public class DefaultMessage extends MessageSupport {
 
     @Override
     public boolean removeHeaders(String pattern, String... excludePatterns) {
-        if (!hasHeaders()) {
+        if (headers == null) {
+            // force creating headers
+            headers = createHeaders();
+        }
+        if (headers.isEmpty()) {
             return false;
         }
 
@@ -239,11 +277,11 @@ public class DefaultMessage extends MessageSupport {
 
     @Override
     public boolean hasHeaders() {
-        if (!hasPopulatedHeaders()) {
+        if (headers == null) {
             // force creating headers
-            getHeaders();
+            headers = createHeaders();
         }
-        return headers != null && !headers.isEmpty();
+        return !headers.isEmpty();
     }
 
     @Override

Reply | Threaded
Open this post in threaded view
|

[camel] 04/13: Polished

davsclaus-2
In reply to this post by davsclaus-2
This is an automated email from the ASF dual-hosted git repository.

davsclaus pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/camel.git

commit e0d7b8cc103cabf3564c74669485581482f8cb1b
Author: Claus Ibsen <[hidden email]>
AuthorDate: Sat Feb 15 23:16:27 2020 +0100

    Polished
---
 docs/user-manual/modules/ROOT/pages/release-guide.adoc | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)

diff --git a/docs/user-manual/modules/ROOT/pages/release-guide.adoc b/docs/user-manual/modules/ROOT/pages/release-guide.adoc
index 6a72a67..93a751b 100644
--- a/docs/user-manual/modules/ROOT/pages/release-guide.adoc
+++ b/docs/user-manual/modules/ROOT/pages/release-guide.adoc
@@ -1,5 +1,7 @@
 [[ReleaseGuide-ReleaseGuide]]
-= How to Create and Announce a Camel Release
+= Release Guide
+
+This guide covers how to create and announce a Camel release.
 
 [[ReleaseGuide-Prequisites]]
 == Prequisites

Reply | Threaded
Open this post in threaded view
|

[camel] 05/13: Add missing license header

davsclaus-2
In reply to this post by davsclaus-2
This is an automated email from the ASF dual-hosted git repository.

davsclaus pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/camel.git

commit 55f2cd452b941485a5432d5079046961af7bb3c8
Author: Claus Ibsen <[hidden email]>
AuthorDate: Sat Feb 15 23:23:53 2020 +0100

    Add missing license header
---
 components/camel-workday/pom.xml | 18 ++++++++++++++++++
 pom.xml                          |  3 +++
 2 files changed, 21 insertions(+)

diff --git a/components/camel-workday/pom.xml b/components/camel-workday/pom.xml
index 5e75b6c..9382f7b 100644
--- a/components/camel-workday/pom.xml
+++ b/components/camel-workday/pom.xml
@@ -1,4 +1,22 @@
 <?xml version="1.0" encoding="UTF-8"?>
+<!--
+
+    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.
+
+-->
 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
 
   <modelVersion>4.0.0</modelVersion>
diff --git a/pom.xml b/pom.xml
index 917a92a..d88390e 100644
--- a/pom.xml
+++ b/pom.xml
@@ -196,6 +196,7 @@
                     <configuration>
                         <excludeSubProjects>false</excludeSubProjects>
                         <excludes>
+                            <exclude>**/generated/**</exclude>
                             <exclude>**/generated.txt</exclude>
                             <exclude>**/*.json</exclude>
                             <exclude>**/README</exclude>
@@ -242,6 +243,7 @@
                             <!-- camel-salesforce BSD license from salesforce developers -->
                             <exclude>**/CometDReplayExtension.java</exclude>
                             <exclude>**/LICENSE-SALESFORCE.txt</exclude>
+                            <exclude>**/LICENSE-ICU4J.txt</exclude>
                             <!-- camel-as2 -->
                             <exclude>**/mdnDescription.vm</exclude>
                             <!-- camel-jbpm -->
@@ -278,6 +280,7 @@
                             <exclude>
                                 **/src/main/resources/META-INF/services/org.kie.server.services.api.KieServerExtension
                             </exclude>
+                            <exclude>**/META-INF/MANIFEST.MF</exclude>
                             <!-- Maven Wrapper -->
                             <exclude>.mvn/**/*</exclude>
                         </excludes>

Reply | Threaded
Open this post in threaded view
|

[camel] 06/13: camel-core - Optimize to let type converter be eager created to avoid overhead in getTypeConverter method which is used a lot.

davsclaus-2
In reply to this post by davsclaus-2
This is an automated email from the ASF dual-hosted git repository.

davsclaus pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/camel.git

commit 53acc37eb40e2429cfb5f095ce39bc70b8a9b263
Author: Claus Ibsen <[hidden email]>
AuthorDate: Sun Feb 16 08:32:51 2020 +0100

    camel-core - Optimize to let type converter be eager created to avoid overhead in getTypeConverter method which is used a lot.
---
 .../camel/component/quartz/QuartzOneCamelContextRestartTest.java    | 4 ++--
 .../main/java/org/apache/camel/support/service/ServiceSupport.java  | 6 +++---
 .../java/org/apache/camel/impl/engine/AbstractCamelContext.java     | 1 +
 3 files changed, 6 insertions(+), 5 deletions(-)

diff --git a/components/camel-quartz/src/test/java/org/apache/camel/component/quartz/QuartzOneCamelContextRestartTest.java b/components/camel-quartz/src/test/java/org/apache/camel/component/quartz/QuartzOneCamelContextRestartTest.java
index d372e89..d842ba8 100644
--- a/components/camel-quartz/src/test/java/org/apache/camel/component/quartz/QuartzOneCamelContextRestartTest.java
+++ b/components/camel-quartz/src/test/java/org/apache/camel/component/quartz/QuartzOneCamelContextRestartTest.java
@@ -51,14 +51,14 @@ public class QuartzOneCamelContextRestartTest {
         mock1.expectedMinimumMessageCount(2);
         mock1.assertIsSatisfied();
 
+        // restart
         camel1.stop();
+        camel1.start();
 
         // fetch mock endpoint again because we have stopped camel context
         mock1 = camel1.getEndpoint("mock:one", MockEndpoint.class);
         // should resume triggers when we start camel 1 again
         mock1.expectedMinimumMessageCount(3);
-        camel1.start();
-
         mock1.assertIsSatisfied();
     }
 
diff --git a/core/camel-api/src/main/java/org/apache/camel/support/service/ServiceSupport.java b/core/camel-api/src/main/java/org/apache/camel/support/service/ServiceSupport.java
index 7602c73..8c9fc4e 100644
--- a/core/camel-api/src/main/java/org/apache/camel/support/service/ServiceSupport.java
+++ b/core/camel-api/src/main/java/org/apache/camel/support/service/ServiceSupport.java
@@ -74,10 +74,10 @@ public abstract class ServiceSupport implements StatefulService {
 
     @Override
     public void init() {
-        // allow to initialize again if failed
-        if (status <= BUILDED || status >= FAILED) {
+        // allow to initialize again if stopped or failed
+        if (status <= BUILDED || status >= STOPPED) {
             synchronized (lock) {
-                if (status <= BUILDED || status >= FAILED) {
+                if (status <= BUILDED || status >= STOPPED) {
                     LOG.trace("Initializing service: {}", this);
                     try {
                         doInit();
diff --git a/core/camel-base/src/main/java/org/apache/camel/impl/engine/AbstractCamelContext.java b/core/camel-base/src/main/java/org/apache/camel/impl/engine/AbstractCamelContext.java
index 58c1594..fe96711 100644
--- a/core/camel-base/src/main/java/org/apache/camel/impl/engine/AbstractCamelContext.java
+++ b/core/camel-base/src/main/java/org/apache/camel/impl/engine/AbstractCamelContext.java
@@ -834,6 +834,7 @@ public abstract class AbstractCamelContext extends ServiceSupport implements Ext
 
     @Override
     public Endpoint getEndpoint(String uri, Map<String, Object> parameters) {
+        // ensure CamelContext are initialized before we can get an endpoint
         init();
 
         StringHelper.notEmpty(uri, "uri");

Reply | Threaded
Open this post in threaded view
|

[camel] 07/13: CAMEL-14565: camel-webhook refactor a bit and add docs for missing option.

davsclaus-2
In reply to this post by davsclaus-2
This is an automated email from the ASF dual-hosted git repository.

davsclaus pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/camel.git

commit 4fce14747bceffc4e82b1e76ee749a8218c7e166
Author: Claus Ibsen <[hidden email]>
AuthorDate: Sun Feb 16 08:49:36 2020 +0100

    CAMEL-14565: camel-webhook refactor a bit and add docs for missing option.
---
 .../camel/component/telegram/TelegramEndpoint.java    |  7 +++++--
 .../component/telegram/TelegramWebhookCallTest.java   |  4 +++-
 .../component/webhook/WebhookCapableEndpoint.java     |  8 +++++---
 .../camel/component/webhook/WebhookConfiguration.java | 19 +++++++++++++++++++
 .../camel/component/webhook/WebhookEndpoint.java      |  2 +-
 .../camel/component/webhook/support/TestEndpoint.java |  5 ++++-
 .../modules/ROOT/pages/webhook-component.adoc         | 12 ++++++------
 7 files changed, 43 insertions(+), 14 deletions(-)

diff --git a/components/camel-telegram/src/main/java/org/apache/camel/component/telegram/TelegramEndpoint.java b/components/camel-telegram/src/main/java/org/apache/camel/component/telegram/TelegramEndpoint.java
index 59bfe5d..ce66c59 100644
--- a/components/camel-telegram/src/main/java/org/apache/camel/component/telegram/TelegramEndpoint.java
+++ b/components/camel-telegram/src/main/java/org/apache/camel/component/telegram/TelegramEndpoint.java
@@ -29,6 +29,7 @@ import org.apache.camel.component.telegram.model.Update;
 import org.apache.camel.component.telegram.service.TelegramServiceRestBotAPIAdapter;
 import org.apache.camel.component.webhook.WebhookCapableEndpoint;
 import org.apache.camel.component.webhook.WebhookConfiguration;
+import org.apache.camel.spi.RestConfiguration;
 import org.apache.camel.spi.UriEndpoint;
 import org.apache.camel.spi.UriParam;
 import org.apache.camel.support.ScheduledPollEndpoint;
@@ -58,6 +59,7 @@ public class TelegramEndpoint extends ScheduledPollEndpoint implements WebhookCa
     private int bufferSize = 4 * 1024;
 
     private WebhookConfiguration webhookConfiguration;
+    private RestConfiguration restConfiguration;
 
     private AsyncHttpClient client;
     private TelegramService telegramService;
@@ -136,7 +138,7 @@ public class TelegramEndpoint extends ScheduledPollEndpoint implements WebhookCa
 
     @Override
     public void registerWebhook() throws Exception {
-        if (!telegramService.setWebhook(webhookConfiguration.computeFullExternalUrl())) {
+        if (!telegramService.setWebhook(webhookConfiguration.computeFullExternalUrl(restConfiguration))) {
             throw new RuntimeCamelException("The Telegram API refused to register a webhook");
         }
     }
@@ -153,8 +155,9 @@ public class TelegramEndpoint extends ScheduledPollEndpoint implements WebhookCa
     }
 
     @Override
-    public void setWebhookConfiguration(WebhookConfiguration webhookConfiguration) {
+    public void setWebhookConfiguration(WebhookConfiguration webhookConfiguration, RestConfiguration restConfiguration) {
         this.webhookConfiguration = webhookConfiguration;
+        this.restConfiguration = restConfiguration;
     }
 
     @Override
diff --git a/components/camel-telegram/src/test/java/org/apache/camel/component/telegram/TelegramWebhookCallTest.java b/components/camel-telegram/src/test/java/org/apache/camel/component/telegram/TelegramWebhookCallTest.java
index 65fd3ef..accc17f 100644
--- a/components/camel-telegram/src/test/java/org/apache/camel/component/telegram/TelegramWebhookCallTest.java
+++ b/components/camel-telegram/src/test/java/org/apache/camel/component/telegram/TelegramWebhookCallTest.java
@@ -25,6 +25,7 @@ import org.apache.camel.component.mock.MockEndpoint;
 import org.apache.camel.component.telegram.util.TelegramTestSupport;
 import org.apache.camel.component.webhook.WebhookConfiguration;
 import org.apache.camel.component.webhook.WebhookEndpoint;
+import org.apache.camel.spi.RestConfiguration;
 import org.apache.camel.test.AvailablePortFinder;
 import org.junit.jupiter.api.Test;
 
@@ -38,7 +39,8 @@ public class TelegramWebhookCallTest extends TelegramTestSupport {
     @Test
     public void testWebhookCall() throws Exception {
         WebhookConfiguration config = ((WebhookEndpoint) context().getRoute("webhook").getConsumer().getEndpoint()).getConfiguration();
-        String url = config.computeFullExternalUrl();
+        RestConfiguration rest = context().getRestConfiguration();
+        String url = config.computeFullExternalUrl(rest);
 
         try (InputStream content = getClass().getClassLoader().getResourceAsStream("messages/webhook-call.json")) {
             MockEndpoint mock = getMockEndpoint("mock:endpoint");
diff --git a/components/camel-webhook/src/main/java/org/apache/camel/component/webhook/WebhookCapableEndpoint.java b/components/camel-webhook/src/main/java/org/apache/camel/component/webhook/WebhookCapableEndpoint.java
index ff61cc0..cc0f1f5 100644
--- a/components/camel-webhook/src/main/java/org/apache/camel/component/webhook/WebhookCapableEndpoint.java
+++ b/components/camel-webhook/src/main/java/org/apache/camel/component/webhook/WebhookCapableEndpoint.java
@@ -20,6 +20,7 @@ import java.util.List;
 
 import org.apache.camel.Endpoint;
 import org.apache.camel.Processor;
+import org.apache.camel.spi.RestConfiguration;
 
 /**
  * A {@code WebhookCapableEndpoint} is a special kind of endpoint that is able to operate in webhook mode if required.
@@ -44,7 +45,7 @@ public interface WebhookCapableEndpoint extends Endpoint {
      * Register the webhook at the remote site using endpoint specific instruction.
      * <p>
      * Additional configuration is injected into the endpoint using the
-     * {@link WebhookCapableEndpoint#setWebhookConfiguration(WebhookConfiguration)} method.
+     * setWebhookConfiguration method.
      *
      * @throws Exception if something goes wrong during the registration.
      */
@@ -54,7 +55,7 @@ public interface WebhookCapableEndpoint extends Endpoint {
      * Unregister the webhook at the remote site using endpoint specific instruction.
      * <p>
      * Additional configuration is injected into the endpoint using the
-     * {@link WebhookCapableEndpoint#setWebhookConfiguration(WebhookConfiguration)} method.
+     * setWebhookConfiguration method.
      *
      * @throws Exception if something goes wrong during the un-registration.
      */
@@ -64,8 +65,9 @@ public interface WebhookCapableEndpoint extends Endpoint {
      * Used by the workflow manager to inject webhook configuration options.
      *
      * @param webhookConfiguration the webhook configuration options.
+     * @param restConfiguration    the webhook rest configuration options.
      */
-    void setWebhookConfiguration(WebhookConfiguration webhookConfiguration);
+    void setWebhookConfiguration(WebhookConfiguration webhookConfiguration, RestConfiguration restConfiguration);
 
     /**
      * Used by the endpoint to enlist the HTTP methods it's able to handle.
diff --git a/components/camel-webhook/src/main/java/org/apache/camel/component/webhook/WebhookConfiguration.java b/components/camel-webhook/src/main/java/org/apache/camel/component/webhook/WebhookConfiguration.java
index 35c1efe..98a312c 100644
--- a/components/camel-webhook/src/main/java/org/apache/camel/component/webhook/WebhookConfiguration.java
+++ b/components/camel-webhook/src/main/java/org/apache/camel/component/webhook/WebhookConfiguration.java
@@ -16,6 +16,8 @@
  */
 package org.apache.camel.component.webhook;
 
+import java.net.UnknownHostException;
+
 import org.apache.camel.RuntimeCamelException;
 import org.apache.camel.spi.Metadata;
 import org.apache.camel.spi.RestConfiguration;
@@ -23,6 +25,8 @@ import org.apache.camel.spi.UriParam;
 import org.apache.camel.spi.UriParams;
 import org.apache.camel.spi.UriPath;
 
+import static org.apache.camel.component.webhook.WebhookComponent.computeServerUriPrefix;
+
 /**
  * Configuration class for the webhook component.
  */
@@ -70,6 +74,21 @@ public class WebhookConfiguration implements Cloneable {
     }
 
     /**
+     * Computes the external URL of the webhook as seen by the remote webhook provider.
+     *
+     * @param restConfiguration rest configuration
+     * @return the webhook external URL
+     */
+    public String computeFullExternalUrl(RestConfiguration restConfiguration) throws UnknownHostException {
+        String externalServerUrl = this.webhookExternalUrl;
+        if (externalServerUrl == null) {
+            externalServerUrl = computeServerUriPrefix(restConfiguration);
+        }
+        String path = computeFullPath(restConfiguration, true);
+        return externalServerUrl + path;
+    }
+
+    /**
      * Computes the path part of the webhook.
      *
      * @param restConfiguration rest configuration
diff --git a/components/camel-webhook/src/main/java/org/apache/camel/component/webhook/WebhookEndpoint.java b/components/camel-webhook/src/main/java/org/apache/camel/component/webhook/WebhookEndpoint.java
index 7f7ba62..e83f0a6 100644
--- a/components/camel-webhook/src/main/java/org/apache/camel/component/webhook/WebhookEndpoint.java
+++ b/components/camel-webhook/src/main/java/org/apache/camel/component/webhook/WebhookEndpoint.java
@@ -79,7 +79,7 @@ public class WebhookEndpoint extends DefaultEndpoint implements DelegateEndpoint
             throw new IllegalArgumentException("The provided endpoint is not capable of being used in webhook mode: " + configuration.getEndpointUri());
         }
         delegateEndpoint = (WebhookCapableEndpoint) delegate;
-        delegateEndpoint.setWebhookConfiguration(configuration);
+        delegateEndpoint.setWebhookConfiguration(configuration, restConfiguration);
     }
 
     @Override
diff --git a/components/camel-webhook/src/test/java/org/apache/camel/component/webhook/support/TestEndpoint.java b/components/camel-webhook/src/test/java/org/apache/camel/component/webhook/support/TestEndpoint.java
index fd53c36..0cd5a5a 100644
--- a/components/camel-webhook/src/test/java/org/apache/camel/component/webhook/support/TestEndpoint.java
+++ b/components/camel-webhook/src/test/java/org/apache/camel/component/webhook/support/TestEndpoint.java
@@ -27,6 +27,7 @@ import org.apache.camel.Processor;
 import org.apache.camel.Producer;
 import org.apache.camel.component.webhook.WebhookCapableEndpoint;
 import org.apache.camel.component.webhook.WebhookConfiguration;
+import org.apache.camel.spi.RestConfiguration;
 import org.apache.camel.support.DefaultEndpoint;
 
 /**
@@ -49,6 +50,7 @@ public class TestEndpoint extends DefaultEndpoint implements WebhookCapableEndpo
     private Function<Processor, Consumer> consumer;
 
     private WebhookConfiguration webhookConfiguration;
+    private RestConfiguration restConfiguration;
 
     private boolean singleton;
 
@@ -89,8 +91,9 @@ public class TestEndpoint extends DefaultEndpoint implements WebhookCapableEndpo
     }
 
     @Override
-    public void setWebhookConfiguration(WebhookConfiguration webhookConfiguration) {
+    public void setWebhookConfiguration(WebhookConfiguration webhookConfiguration, RestConfiguration restConfiguration) {
         this.webhookConfiguration = webhookConfiguration;
+        this.restConfiguration = restConfiguration;
     }
 
     public WebhookConfiguration getWebhookConfiguration() {
diff --git a/docs/components/modules/ROOT/pages/webhook-component.adoc b/docs/components/modules/ROOT/pages/webhook-component.adoc
index d63003f..0dd53ea 100644
--- a/docs/components/modules/ROOT/pages/webhook-component.adoc
+++ b/docs/components/modules/ROOT/pages/webhook-component.adoc
@@ -70,7 +70,7 @@ with the following path and query parameters:
 [width="100%",cols="2,5,^1,2",options="header"]
 |===
 | Name | Description | Default | Type
-| *endpointUri* | The delegate uri. Must belong to a component that supports webhooks. |  | String
+| *endpointUri* | *Required* The delegate uri. Must belong to a component that supports webhooks. |  | String
 |===
 
 
@@ -80,12 +80,12 @@ with the following path and query parameters:
 [width="100%",cols="2,5,^1,2",options="header"]
 |===
 | Name | Description | Default | Type
-| *webhookAutoRegister* (common) | Automatically register the webhook at startup and unregister it on shutdown. | true | boolean
-| *webhookBasePath* (common) | The first (base) path element where the webhook will be exposed. It's a good practice to set it to a random string, so that it cannot be guessed by unauthorized parties. |  | String
-| *webhookComponentName* (common) | The Camel Rest component to use for the REST transport, such as netty-http. |  | String
-| *webhookExternalUrl* (common) | The URL of the current service as seen by the webhook provider |  | String
-| *webhookPath* (common) | The path where the webhook endpoint will be exposed (relative to basePath, if any) |  | String
 | *bridgeErrorHandler* (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean
+| *webhookAutoRegister* (consumer) | Automatically register the webhook at startup and unregister it on shutdown. | true | boolean
+| *webhookBasePath* (consumer) | The first (base) path element where the webhook will be exposed. It's a good practice to set it to a random string, so that it cannot be guessed by unauthorized parties. |  | String
+| *webhookComponentName* (consumer) | The Camel Rest component to use for the REST transport, such as netty-http. |  | String
+| *webhookExternalUrl* (consumer) | The URL of the current service as seen by the webhook provider |  | String
+| *webhookPath* (consumer) | The path where the webhook endpoint will be exposed (relative to basePath, if any) |  | String
 | *exceptionHandler* (consumer) | To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored. |  | ExceptionHandler
 | *exchangePattern* (consumer) | Sets the exchange pattern when the consumer creates an exchange. The value can be one of: InOnly, InOut, InOptionalOut |  | ExchangePattern
 | *basicPropertyBinding* (advanced) | Whether the endpoint should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities | false | boolean

Reply | Threaded
Open this post in threaded view
|

[camel] 08/13: Regen

davsclaus-2
In reply to this post by davsclaus-2
This is an automated email from the ASF dual-hosted git repository.

davsclaus pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/camel.git

commit 37c415cdd271ef12ed456c86cb3d1a5cf3ebd2e4
Author: Claus Ibsen <[hidden email]>
AuthorDate: Sun Feb 16 08:50:15 2020 +0100

    Regen
---
 docs/components/modules/ROOT/pages/mail-component.adoc   | 3 ++-
 docs/components/modules/ROOT/pages/yammer-component.adoc | 6 ++++--
 2 files changed, 6 insertions(+), 3 deletions(-)

diff --git a/docs/components/modules/ROOT/pages/mail-component.adoc b/docs/components/modules/ROOT/pages/mail-component.adoc
index 2efba86..363bda8 100644
--- a/docs/components/modules/ROOT/pages/mail-component.adoc
+++ b/docs/components/modules/ROOT/pages/mail-component.adoc
@@ -136,7 +136,7 @@ with the following path and query parameters:
 |===
 
 
-=== Query Parameters (64 parameters):
+=== Query Parameters (65 parameters):
 
 
 [width="100%",cols="2,5,^1,2",options="header"]
@@ -182,6 +182,7 @@ with the following path and query parameters:
 | *headerFilterStrategy* (advanced) | To use a custom org.apache.camel.spi.HeaderFilterStrategy to filter headers. |  | HeaderFilterStrategy
 | *ignoreUnsupportedCharset* (advanced) | Option to let Camel ignore unsupported charset in the local JVM when sending mails. If the charset is unsupported then charset=XXX (where XXX represents the unsupported charset) is removed from the content-type and it relies on the platform default instead. | false | boolean
 | *ignoreUriScheme* (advanced) | Option to let Camel ignore unsupported charset in the local JVM when sending mails. If the charset is unsupported then charset=XXX (where XXX represents the unsupported charset) is removed from the content-type and it relies on the platform default instead. | false | boolean
+| *javaMailProperties* (advanced) | Sets the java mail options. Will clear any default properties and only use the properties provided for this method. |  | Properties
 | *session* (advanced) | Specifies the mail session that camel should use for all mail interactions. Useful in scenarios where mail sessions are created and managed by some other resource, such as a JavaEE container. When using a custom mail session, then the hostname and port from the mail session will be used (if configured on the session). |  | Session
 | *synchronous* (advanced) | Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported). | false | boolean
 | *useInlineAttachments* (advanced) | Whether to use disposition inline or attachment. | false | boolean
diff --git a/docs/components/modules/ROOT/pages/yammer-component.adoc b/docs/components/modules/ROOT/pages/yammer-component.adoc
index 8d8ecc6..ea49c88 100644
--- a/docs/components/modules/ROOT/pages/yammer-component.adoc
+++ b/docs/components/modules/ROOT/pages/yammer-component.adoc
@@ -44,7 +44,7 @@ The Yammer component can be configured with the Yammer account settings which ar
 
 
 // component options: START
-The Yammer component supports 7 options, which are listed below.
+The Yammer component supports 8 options, which are listed below.
 
 
 
@@ -55,6 +55,7 @@ The Yammer component supports 7 options, which are listed below.
 | *lazyStartProducer* (producer) | Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel's routing error handlers. Beware that when the first message is processed then creating and [...]
 | *basicPropertyBinding* (advanced) | Whether the component should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities | false | boolean
 | *config* (advanced) | To use a shared yammer configuration |  | YammerConfiguration
+| *requestor* (advanced) | To use a specific requester to communicate with Yammer. |  | ApiRequestor
 | *accessToken* (security) | The access token |  | String
 | *consumerKey* (security) | The consumer key |  | String
 | *consumerSecret* (security) | The consumer secret |  | String
@@ -89,7 +90,7 @@ with the following path and query parameters:
 |===
 
 
-=== Query Parameters (31 parameters):
+=== Query Parameters (32 parameters):
 
 
 [width="100%",cols="2,5,^1,2",options="header"]
@@ -109,6 +110,7 @@ with the following path and query parameters:
 | *pollStrategy* (consumer) | A pluggable org.apache.camel.PollingConsumerPollingStrategy allowing you to provide your custom implementation to control error handling usually occurred during the poll operation before an Exchange have been created and being routed in Camel. |  | PollingConsumerPollStrategy
 | *lazyStartProducer* (producer) | Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel's routing error handlers. Beware that when the first message is processed then creating and [...]
 | *basicPropertyBinding* (advanced) | Whether the endpoint should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities | false | boolean
+| *requestor* (advanced) | To use a specific requester to communicate with Yammer. |  | ApiRequestor
 | *synchronous* (advanced) | Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported). | false | boolean
 | *backoffErrorThreshold* (scheduler) | The number of subsequent error polls (failed due some error) that should happen before the backoffMultipler should kick-in. |  | int
 | *backoffIdleThreshold* (scheduler) | The number of subsequent idle polls that should happen before the backoffMultipler should kick-in. |  | int

Reply | Threaded
Open this post in threaded view
|

[camel] 09/13: CAMEL-14565: camel-webhook refactor a bit and add docs for missing option.

davsclaus-2
In reply to this post by davsclaus-2
This is an automated email from the ASF dual-hosted git repository.

davsclaus pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/camel.git

commit 62ae98fb0bd1df64a40098b4e3936c921e0ed0a4
Author: Claus Ibsen <[hidden email]>
AuthorDate: Sun Feb 16 08:59:55 2020 +0100

    CAMEL-14565: camel-webhook refactor a bit and add docs for missing option.
---
 .../camel/component/telegram/TelegramEndpoint.java |  7 +-
 .../telegram/TelegramWebhookCallTest.java          |  4 +-
 .../component/webhook/WebhookCapableEndpoint.java  |  3 +-
 .../camel/component/webhook/WebhookComponent.java  | 62 +---------------
 .../component/webhook/WebhookConfiguration.java    | 84 +++++++++++++++++++---
 .../camel/component/webhook/WebhookEndpoint.java   | 13 ++--
 .../component/webhook/WebhookBasePathTest.java     |  2 +-
 .../component/webhook/WebhookHttpBindingTest.java  |  4 +-
 .../component/webhook/WebhookMultiRouteTest.java   |  4 +-
 .../component/webhook/support/TestEndpoint.java    |  5 +-
 10 files changed, 92 insertions(+), 96 deletions(-)

diff --git a/components/camel-telegram/src/main/java/org/apache/camel/component/telegram/TelegramEndpoint.java b/components/camel-telegram/src/main/java/org/apache/camel/component/telegram/TelegramEndpoint.java
index ce66c59..59bfe5d 100644
--- a/components/camel-telegram/src/main/java/org/apache/camel/component/telegram/TelegramEndpoint.java
+++ b/components/camel-telegram/src/main/java/org/apache/camel/component/telegram/TelegramEndpoint.java
@@ -29,7 +29,6 @@ import org.apache.camel.component.telegram.model.Update;
 import org.apache.camel.component.telegram.service.TelegramServiceRestBotAPIAdapter;
 import org.apache.camel.component.webhook.WebhookCapableEndpoint;
 import org.apache.camel.component.webhook.WebhookConfiguration;
-import org.apache.camel.spi.RestConfiguration;
 import org.apache.camel.spi.UriEndpoint;
 import org.apache.camel.spi.UriParam;
 import org.apache.camel.support.ScheduledPollEndpoint;
@@ -59,7 +58,6 @@ public class TelegramEndpoint extends ScheduledPollEndpoint implements WebhookCa
     private int bufferSize = 4 * 1024;
 
     private WebhookConfiguration webhookConfiguration;
-    private RestConfiguration restConfiguration;
 
     private AsyncHttpClient client;
     private TelegramService telegramService;
@@ -138,7 +136,7 @@ public class TelegramEndpoint extends ScheduledPollEndpoint implements WebhookCa
 
     @Override
     public void registerWebhook() throws Exception {
-        if (!telegramService.setWebhook(webhookConfiguration.computeFullExternalUrl(restConfiguration))) {
+        if (!telegramService.setWebhook(webhookConfiguration.computeFullExternalUrl())) {
             throw new RuntimeCamelException("The Telegram API refused to register a webhook");
         }
     }
@@ -155,9 +153,8 @@ public class TelegramEndpoint extends ScheduledPollEndpoint implements WebhookCa
     }
 
     @Override
-    public void setWebhookConfiguration(WebhookConfiguration webhookConfiguration, RestConfiguration restConfiguration) {
+    public void setWebhookConfiguration(WebhookConfiguration webhookConfiguration) {
         this.webhookConfiguration = webhookConfiguration;
-        this.restConfiguration = restConfiguration;
     }
 
     @Override
diff --git a/components/camel-telegram/src/test/java/org/apache/camel/component/telegram/TelegramWebhookCallTest.java b/components/camel-telegram/src/test/java/org/apache/camel/component/telegram/TelegramWebhookCallTest.java
index accc17f..65fd3ef 100644
--- a/components/camel-telegram/src/test/java/org/apache/camel/component/telegram/TelegramWebhookCallTest.java
+++ b/components/camel-telegram/src/test/java/org/apache/camel/component/telegram/TelegramWebhookCallTest.java
@@ -25,7 +25,6 @@ import org.apache.camel.component.mock.MockEndpoint;
 import org.apache.camel.component.telegram.util.TelegramTestSupport;
 import org.apache.camel.component.webhook.WebhookConfiguration;
 import org.apache.camel.component.webhook.WebhookEndpoint;
-import org.apache.camel.spi.RestConfiguration;
 import org.apache.camel.test.AvailablePortFinder;
 import org.junit.jupiter.api.Test;
 
@@ -39,8 +38,7 @@ public class TelegramWebhookCallTest extends TelegramTestSupport {
     @Test
     public void testWebhookCall() throws Exception {
         WebhookConfiguration config = ((WebhookEndpoint) context().getRoute("webhook").getConsumer().getEndpoint()).getConfiguration();
-        RestConfiguration rest = context().getRestConfiguration();
-        String url = config.computeFullExternalUrl(rest);
+        String url = config.computeFullExternalUrl();
 
         try (InputStream content = getClass().getClassLoader().getResourceAsStream("messages/webhook-call.json")) {
             MockEndpoint mock = getMockEndpoint("mock:endpoint");
diff --git a/components/camel-webhook/src/main/java/org/apache/camel/component/webhook/WebhookCapableEndpoint.java b/components/camel-webhook/src/main/java/org/apache/camel/component/webhook/WebhookCapableEndpoint.java
index cc0f1f5..7fab370 100644
--- a/components/camel-webhook/src/main/java/org/apache/camel/component/webhook/WebhookCapableEndpoint.java
+++ b/components/camel-webhook/src/main/java/org/apache/camel/component/webhook/WebhookCapableEndpoint.java
@@ -65,9 +65,8 @@ public interface WebhookCapableEndpoint extends Endpoint {
      * Used by the workflow manager to inject webhook configuration options.
      *
      * @param webhookConfiguration the webhook configuration options.
-     * @param restConfiguration    the webhook rest configuration options.
      */
-    void setWebhookConfiguration(WebhookConfiguration webhookConfiguration, RestConfiguration restConfiguration);
+    void setWebhookConfiguration(WebhookConfiguration webhookConfiguration);
 
     /**
      * Used by the endpoint to enlist the HTTP methods it's able to handle.
diff --git a/components/camel-webhook/src/main/java/org/apache/camel/component/webhook/WebhookComponent.java b/components/camel-webhook/src/main/java/org/apache/camel/component/webhook/WebhookComponent.java
index aff4fd7..2bf7cb3 100644
--- a/components/camel-webhook/src/main/java/org/apache/camel/component/webhook/WebhookComponent.java
+++ b/components/camel-webhook/src/main/java/org/apache/camel/component/webhook/WebhookComponent.java
@@ -17,21 +17,14 @@
 package org.apache.camel.component.webhook;
 
 import java.net.URISyntaxException;
-import java.net.UnknownHostException;
-import java.nio.charset.StandardCharsets;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
-import java.util.Base64;
 import java.util.Map;
 import java.util.stream.Collectors;
 
 import org.apache.camel.Endpoint;
-import org.apache.camel.RuntimeCamelException;
 import org.apache.camel.spi.Metadata;
 import org.apache.camel.spi.RestConfiguration;
 import org.apache.camel.spi.annotations.Component;
 import org.apache.camel.support.DefaultComponent;
-import org.apache.camel.util.HostUtils;
 import org.apache.camel.util.ObjectHelper;
 import org.apache.camel.util.URISupport;
 
@@ -56,8 +49,9 @@ public class WebhookComponent extends DefaultComponent {
 
         WebhookConfiguration config = configuration != null ? configuration.copy() : new WebhookConfiguration();
         RestConfiguration restConfig = getCamelContext().getRestConfiguration(config.getWebhookComponentName(), true);
+        config.storeConfiguration(restConfig);
 
-        WebhookEndpoint endpoint = new WebhookEndpoint(uri, this, config, restConfig);
+        WebhookEndpoint endpoint = new WebhookEndpoint(uri, this, config);
         setProperties(endpoint, parameters);
         // we need to apply the params here
         if (parameters != null && !parameters.isEmpty()) {
@@ -95,56 +89,4 @@ public class WebhookComponent extends DefaultComponent {
         this.configuration = configuration;
     }
 
-    /**
-     * Computes the URL of the webhook that should be used to bind the REST endpoint locally.
-     */
-    public static String computeServerUriPrefix(RestConfiguration restConfiguration) throws UnknownHostException {
-        // if no explicit port/host configured, then use port from rest configuration
-        String scheme = "http";
-        String host = "";
-        int port = 80;
-
-        if (restConfiguration.getScheme() != null) {
-            scheme = restConfiguration.getScheme();
-        }
-        if (restConfiguration.getHost() != null) {
-            host = restConfiguration.getHost();
-        }
-        int num = restConfiguration.getPort();
-        if (num > 0) {
-            port = num;
-        }
-
-        // if no explicit hostname set then resolve the hostname
-        if (ObjectHelper.isEmpty(host)) {
-            if (restConfiguration.getHostNameResolver() == RestConfiguration.RestHostNameResolver.allLocalIp) {
-                host = "0.0.0.0";
-            } else if (restConfiguration.getHostNameResolver() == RestConfiguration.RestHostNameResolver.localHostName) {
-                host = HostUtils.getLocalHostName();
-            } else if (restConfiguration.getHostNameResolver() == RestConfiguration.RestHostNameResolver.localIp) {
-                host = HostUtils.getLocalIp();
-            }
-        }
-
-        return scheme + "://" + host + (port != 80 ? ":" + port : "");
-    }
-
-    /**
-     * A default path is computed for the webhook if not provided by the user.
-     * It uses a hash of the delegate endpoint in order for it to be reproducible.
-     *
-     * This is not random on purpose.
-     */
-    public static String computeDefaultPath(String uri) {
-        try {
-            MessageDigest md = MessageDigest.getInstance("SHA-256");
-            md.update(uri.getBytes(StandardCharsets.UTF_8));
-            byte[] digest = md.digest();
-
-            return "/" + Base64.getUrlEncoder().encodeToString(digest);
-        } catch (NoSuchAlgorithmException e) {
-            throw new RuntimeCamelException("Cannot compute default webhook path", e);
-        }
-    }
-
 }
diff --git a/components/camel-webhook/src/main/java/org/apache/camel/component/webhook/WebhookConfiguration.java b/components/camel-webhook/src/main/java/org/apache/camel/component/webhook/WebhookConfiguration.java
index 98a312c..4395ea1 100644
--- a/components/camel-webhook/src/main/java/org/apache/camel/component/webhook/WebhookConfiguration.java
+++ b/components/camel-webhook/src/main/java/org/apache/camel/component/webhook/WebhookConfiguration.java
@@ -17,6 +17,10 @@
 package org.apache.camel.component.webhook;
 
 import java.net.UnknownHostException;
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.Base64;
 
 import org.apache.camel.RuntimeCamelException;
 import org.apache.camel.spi.Metadata;
@@ -24,8 +28,8 @@ import org.apache.camel.spi.RestConfiguration;
 import org.apache.camel.spi.UriParam;
 import org.apache.camel.spi.UriParams;
 import org.apache.camel.spi.UriPath;
-
-import static org.apache.camel.component.webhook.WebhookComponent.computeServerUriPrefix;
+import org.apache.camel.util.HostUtils;
+import org.apache.camel.util.ObjectHelper;
 
 /**
  * Configuration class for the webhook component.
@@ -33,6 +37,8 @@ import static org.apache.camel.component.webhook.WebhookComponent.computeServerU
 @UriParams
 public class WebhookConfiguration implements Cloneable {
 
+    private transient RestConfiguration restConfiguration;
+
     /*
      * Note: all properties start with the 'webhook' prefix to avoid collision with the delegate endpoint.
      */
@@ -73,33 +79,41 @@ public class WebhookConfiguration implements Cloneable {
         }
     }
 
+    // cannot use getter/setter as its not a regular option
+    public void storeConfiguration(RestConfiguration restConfiguration) {
+        this.restConfiguration = restConfiguration;
+    }
+
+    // cannot use getter/setter as its not a regular option
+    public RestConfiguration retrieveRestConfiguration() {
+        return restConfiguration;
+    }
+
     /**
      * Computes the external URL of the webhook as seen by the remote webhook provider.
      *
-     * @param restConfiguration rest configuration
      * @return the webhook external URL
      */
-    public String computeFullExternalUrl(RestConfiguration restConfiguration) throws UnknownHostException {
+    public String computeFullExternalUrl() throws UnknownHostException {
         String externalServerUrl = this.webhookExternalUrl;
         if (externalServerUrl == null) {
-            externalServerUrl = computeServerUriPrefix(restConfiguration);
+            externalServerUrl = computeServerUriPrefix();
         }
-        String path = computeFullPath(restConfiguration, true);
+        String path = computeFullPath(true);
         return externalServerUrl + path;
     }
 
     /**
      * Computes the path part of the webhook.
      *
-     * @param restConfiguration rest configuration
      * @param external indicates if it's the path seen by the external provider or the internal one.
      * @return the webhook full path
      */
-    public String computeFullPath(RestConfiguration restConfiguration, boolean external) {
+    public String computeFullPath(boolean external) {
         // calculate the url to the rest service
         String path = webhookPath;
         if (path == null) {
-            path = WebhookComponent.computeDefaultPath(endpointUri);
+            path = computeDefaultPath(endpointUri);
         } else if (!path.startsWith("/")) {
             path = "/" + path;
         }
@@ -126,6 +140,58 @@ public class WebhookConfiguration implements Cloneable {
         return path;
     }
 
+    /**
+     * Computes the URL of the webhook that should be used to bind the REST endpoint locally.
+     */
+    public String computeServerUriPrefix() throws UnknownHostException {
+        // if no explicit port/host configured, then use port from rest configuration
+        String scheme = "http";
+        String host = "";
+        int port = 80;
+
+        if (restConfiguration.getScheme() != null) {
+            scheme = restConfiguration.getScheme();
+        }
+        if (restConfiguration.getHost() != null) {
+            host = restConfiguration.getHost();
+        }
+        int num = restConfiguration.getPort();
+        if (num > 0) {
+            port = num;
+        }
+
+        // if no explicit hostname set then resolve the hostname
+        if (ObjectHelper.isEmpty(host)) {
+            if (restConfiguration.getHostNameResolver() == RestConfiguration.RestHostNameResolver.allLocalIp) {
+                host = "0.0.0.0";
+            } else if (restConfiguration.getHostNameResolver() == RestConfiguration.RestHostNameResolver.localHostName) {
+                host = HostUtils.getLocalHostName();
+            } else if (restConfiguration.getHostNameResolver() == RestConfiguration.RestHostNameResolver.localIp) {
+                host = HostUtils.getLocalIp();
+            }
+        }
+
+        return scheme + "://" + host + (port != 80 ? ":" + port : "");
+    }
+
+    /**
+     * A default path is computed for the webhook if not provided by the user.
+     * It uses a hash of the delegate endpoint in order for it to be reproducible.
+     *
+     * This is not random on purpose.
+     */
+    public static String computeDefaultPath(String uri) {
+        try {
+            MessageDigest md = MessageDigest.getInstance("SHA-256");
+            md.update(uri.getBytes(StandardCharsets.UTF_8));
+            byte[] digest = md.digest();
+
+            return "/" + Base64.getUrlEncoder().encodeToString(digest);
+        } catch (NoSuchAlgorithmException e) {
+            throw new RuntimeCamelException("Cannot compute default webhook path", e);
+        }
+    }
+
     public String getEndpointUri() {
         return endpointUri;
     }
diff --git a/components/camel-webhook/src/main/java/org/apache/camel/component/webhook/WebhookEndpoint.java b/components/camel-webhook/src/main/java/org/apache/camel/component/webhook/WebhookEndpoint.java
index e83f0a6..e4c7d6c 100644
--- a/components/camel-webhook/src/main/java/org/apache/camel/component/webhook/WebhookEndpoint.java
+++ b/components/camel-webhook/src/main/java/org/apache/camel/component/webhook/WebhookEndpoint.java
@@ -23,7 +23,6 @@ import org.apache.camel.DelegateEndpoint;
 import org.apache.camel.Endpoint;
 import org.apache.camel.Processor;
 import org.apache.camel.Producer;
-import org.apache.camel.spi.RestConfiguration;
 import org.apache.camel.spi.RestConsumerFactory;
 import org.apache.camel.spi.UriEndpoint;
 import org.apache.camel.spi.UriParam;
@@ -41,15 +40,13 @@ public class WebhookEndpoint extends DefaultEndpoint implements DelegateEndpoint
     private static final Logger LOG = LoggerFactory.getLogger(WebhookEndpoint.class);
 
     private WebhookCapableEndpoint delegateEndpoint;
-    private RestConfiguration restConfiguration;
 
     @UriParam(label = "advanced")
     private WebhookConfiguration configuration;
 
-    public WebhookEndpoint(String uri, WebhookComponent component, WebhookConfiguration configuration, RestConfiguration restConfiguration) {
+    public WebhookEndpoint(String uri, WebhookComponent component, WebhookConfiguration configuration) {
         super(uri, component);
         this.configuration = configuration;
-        this.restConfiguration = restConfiguration;
     }
 
     @Override
@@ -61,14 +58,14 @@ public class WebhookEndpoint extends DefaultEndpoint implements DelegateEndpoint
     public Consumer createConsumer(Processor processor) throws Exception {
         RestConsumerFactory factory = WebhookUtils.locateRestConsumerFactory(getCamelContext(), configuration);
 
-        String path = configuration.computeFullPath(restConfiguration, false);
-        String serverUrl = WebhookComponent.computeServerUriPrefix(restConfiguration);
+        String path = configuration.computeFullPath(false);
+        String serverUrl = configuration.computeServerUriPrefix();
         String url = serverUrl + path;
 
         Processor handler = delegateEndpoint.createWebhookHandler(processor);
 
         return new MultiRestConsumer(getCamelContext(), factory, this, handler, delegateEndpoint.getWebhookMethods(), url, path,
-                restConfiguration, this::configureConsumer);
+                configuration.retrieveRestConfiguration(), this::configureConsumer);
     }
 
     @Override
@@ -79,7 +76,7 @@ public class WebhookEndpoint extends DefaultEndpoint implements DelegateEndpoint
             throw new IllegalArgumentException("The provided endpoint is not capable of being used in webhook mode: " + configuration.getEndpointUri());
         }
         delegateEndpoint = (WebhookCapableEndpoint) delegate;
-        delegateEndpoint.setWebhookConfiguration(configuration, restConfiguration);
+        delegateEndpoint.setWebhookConfiguration(configuration);
     }
 
     @Override
diff --git a/components/camel-webhook/src/test/java/org/apache/camel/component/webhook/WebhookBasePathTest.java b/components/camel-webhook/src/test/java/org/apache/camel/component/webhook/WebhookBasePathTest.java
index 35c351e..ec7da63 100644
--- a/components/camel-webhook/src/test/java/org/apache/camel/component/webhook/WebhookBasePathTest.java
+++ b/components/camel-webhook/src/test/java/org/apache/camel/component/webhook/WebhookBasePathTest.java
@@ -41,7 +41,7 @@ public class WebhookBasePathTest extends WebhookTestBase {
     @Test
     public void testAutoPath() {
         String result = template.requestBody("netty-http:http://localhost:" + port + "/base"
-                + WebhookComponent.computeDefaultPath("wb-delegate://auto"), "", String.class);
+                + WebhookConfiguration.computeDefaultPath("wb-delegate://auto"), "", String.class);
         assertEquals("auto: webhook", result);
     }
 
diff --git a/components/camel-webhook/src/test/java/org/apache/camel/component/webhook/WebhookHttpBindingTest.java b/components/camel-webhook/src/test/java/org/apache/camel/component/webhook/WebhookHttpBindingTest.java
index e91b1d8..8e42d21 100644
--- a/components/camel-webhook/src/test/java/org/apache/camel/component/webhook/WebhookHttpBindingTest.java
+++ b/components/camel-webhook/src/test/java/org/apache/camel/component/webhook/WebhookHttpBindingTest.java
@@ -31,11 +31,11 @@ public class WebhookHttpBindingTest extends WebhookTestBase {
     @Test
     public void testWrapper() {
         String result = template.requestBody("netty-http:http://localhost:" + port
-                + WebhookComponent.computeDefaultPath("wb-delegate://xx"), "", String.class);
+                + WebhookConfiguration.computeDefaultPath("wb-delegate://xx"), "", String.class);
         assertEquals("msg: webhook", result);
 
         result = template.requestBodyAndHeader("netty-http:http://localhost:" + port
-                + WebhookComponent.computeDefaultPath("wb-delegate://xx"), "", Exchange.HTTP_METHOD, "PUT", String.class);
+                + WebhookConfiguration.computeDefaultPath("wb-delegate://xx"), "", Exchange.HTTP_METHOD, "PUT", String.class);
         assertEquals("msg: webhook", result);
     }
 
diff --git a/components/camel-webhook/src/test/java/org/apache/camel/component/webhook/WebhookMultiRouteTest.java b/components/camel-webhook/src/test/java/org/apache/camel/component/webhook/WebhookMultiRouteTest.java
index 1a43bab..5a0b0c3 100644
--- a/components/camel-webhook/src/test/java/org/apache/camel/component/webhook/WebhookMultiRouteTest.java
+++ b/components/camel-webhook/src/test/java/org/apache/camel/component/webhook/WebhookMultiRouteTest.java
@@ -27,11 +27,11 @@ public class WebhookMultiRouteTest extends WebhookTestBase {
     @Test
     public void testMultiRoute() {
         String result = template.requestBody("netty-http:http://localhost:" + port
-                + WebhookComponent.computeDefaultPath("wb-delegate://yy"), "", String.class);
+                + WebhookConfiguration.computeDefaultPath("wb-delegate://yy"), "", String.class);
         assertEquals("uri: webhook", result);
 
         result = template.requestBody("netty-http:http://localhost:" + port
-                + WebhookComponent.computeDefaultPath("wb-delegate://xx"), "", String.class);
+                + WebhookConfiguration.computeDefaultPath("wb-delegate://xx"), "", String.class);
         assertEquals("msg: webhook", result);
     }
 
diff --git a/components/camel-webhook/src/test/java/org/apache/camel/component/webhook/support/TestEndpoint.java b/components/camel-webhook/src/test/java/org/apache/camel/component/webhook/support/TestEndpoint.java
index 0cd5a5a..fd53c36 100644
--- a/components/camel-webhook/src/test/java/org/apache/camel/component/webhook/support/TestEndpoint.java
+++ b/components/camel-webhook/src/test/java/org/apache/camel/component/webhook/support/TestEndpoint.java
@@ -27,7 +27,6 @@ import org.apache.camel.Processor;
 import org.apache.camel.Producer;
 import org.apache.camel.component.webhook.WebhookCapableEndpoint;
 import org.apache.camel.component.webhook.WebhookConfiguration;
-import org.apache.camel.spi.RestConfiguration;
 import org.apache.camel.support.DefaultEndpoint;
 
 /**
@@ -50,7 +49,6 @@ public class TestEndpoint extends DefaultEndpoint implements WebhookCapableEndpo
     private Function<Processor, Consumer> consumer;
 
     private WebhookConfiguration webhookConfiguration;
-    private RestConfiguration restConfiguration;
 
     private boolean singleton;
 
@@ -91,9 +89,8 @@ public class TestEndpoint extends DefaultEndpoint implements WebhookCapableEndpo
     }
 
     @Override
-    public void setWebhookConfiguration(WebhookConfiguration webhookConfiguration, RestConfiguration restConfiguration) {
+    public void setWebhookConfiguration(WebhookConfiguration webhookConfiguration) {
         this.webhookConfiguration = webhookConfiguration;
-        this.restConfiguration = restConfiguration;
     }
 
     public WebhookConfiguration getWebhookConfiguration() {

Reply | Threaded
Open this post in threaded view
|

[camel] 10/13: CAMEL-14572: camel-core - Optimize type converter for some basic convertions

davsclaus-2
In reply to this post by davsclaus-2
This is an automated email from the ASF dual-hosted git repository.

davsclaus pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/camel.git

commit da1e828f21d569c7994be70a0a6fb2cb56dec45b
Author: Claus Ibsen <[hidden email]>
AuthorDate: Sun Feb 16 14:21:32 2020 +0100

    CAMEL-14572: camel-core - Optimize type converter for some basic convertions
---
 .../component/couchdb/CouchDbComponentTest.java    |   2 +-
 .../debezium/DebeziumMySqlComponentTest.java       |   4 +-
 .../sql/stored/ProducerBatchInvalidTest.java       |   3 +-
 .../camel/spi/AnnotationScanTypeConverters.java    |  17 ++++
 .../camel/converter/TimePatternConverter.java      |   1 -
 .../impl/converter/BaseTypeConverterRegistry.java  | 102 ++++++++++++++++++---
 .../camel/impl/converter/DefaultTypeConverter.java |  44 ++++++---
 .../camel/impl/engine/AbstractCamelContext.java    |   5 +
 .../main/java/org/apache/camel/util/TimeUtils.java |  12 +--
 9 files changed, 154 insertions(+), 36 deletions(-)

diff --git a/components/camel-couchdb/src/test/java/org/apache/camel/component/couchdb/CouchDbComponentTest.java b/components/camel-couchdb/src/test/java/org/apache/camel/component/couchdb/CouchDbComponentTest.java
index 5d472a6..aca029b 100644
--- a/components/camel-couchdb/src/test/java/org/apache/camel/component/couchdb/CouchDbComponentTest.java
+++ b/components/camel-couchdb/src/test/java/org/apache/camel/component/couchdb/CouchDbComponentTest.java
@@ -46,7 +46,7 @@ public class CouchDbComponentTest extends CamelTestSupport {
         params.put("createDatabase", true);
         params.put("username", "coldplay");
         params.put("password", "chrism");
-        params.put("heartbeat", 1000);
+        params.put("heartbeat", "1000");
         params.put("style", "gothic");
         params.put("deletes", false);
         params.put("updates", false);
diff --git a/components/camel-debezium-mysql/src/test/java/org/apache/camel/component/debezium/DebeziumMySqlComponentTest.java b/components/camel-debezium-mysql/src/test/java/org/apache/camel/component/debezium/DebeziumMySqlComponentTest.java
index e4a2d91..aa434f5 100644
--- a/components/camel-debezium-mysql/src/test/java/org/apache/camel/component/debezium/DebeziumMySqlComponentTest.java
+++ b/components/camel-debezium-mysql/src/test/java/org/apache/camel/component/debezium/DebeziumMySqlComponentTest.java
@@ -37,7 +37,7 @@ public class DebeziumMySqlComponentTest {
         params.put("databaseUser", "dbz");
         params.put("databasePassword", "pwd");
         params.put("databaseServerName", "test");
-        params.put("databaseServerId", 1234);
+        params.put("databaseServerId", "1234");
         params.put("databaseHistoryFileFilename", "/db_history_file_test");
 
         final String remaining = "test_name";
@@ -60,7 +60,7 @@ public class DebeziumMySqlComponentTest {
         assertEquals("dbz", configuration.getDatabaseUser());
         assertEquals("pwd", configuration.getDatabasePassword());
         assertEquals("test", configuration.getDatabaseServerName());
-        assertEquals(1234, configuration.getDatabaseServerId());
+        assertEquals(1234L, configuration.getDatabaseServerId());
         assertEquals("/db_history_file_test", configuration.getDatabaseHistoryFileFilename());
     }
 
diff --git a/components/camel-sql/src/test/java/org/apache/camel/component/sql/stored/ProducerBatchInvalidTest.java b/components/camel-sql/src/test/java/org/apache/camel/component/sql/stored/ProducerBatchInvalidTest.java
index 37fe02c..22bed0d 100644
--- a/components/camel-sql/src/test/java/org/apache/camel/component/sql/stored/ProducerBatchInvalidTest.java
+++ b/components/camel-sql/src/test/java/org/apache/camel/component/sql/stored/ProducerBatchInvalidTest.java
@@ -19,7 +19,6 @@ package org.apache.camel.component.sql.stored;
 import org.apache.camel.FailedToCreateRouteException;
 import org.apache.camel.PropertyBindingException;
 import org.apache.camel.ResolveEndpointFailedException;
-import org.apache.camel.TypeConversionException;
 import org.apache.camel.builder.RouteBuilder;
 import org.apache.camel.test.junit4.CamelTestSupport;
 import org.junit.After;
@@ -72,7 +71,7 @@ public class ProducerBatchInvalidTest extends CamelTestSupport {
             ResolveEndpointFailedException refe = assertIsInstanceOf(ResolveEndpointFailedException.class, e.getCause());
             PropertyBindingException pbe = assertIsInstanceOf(PropertyBindingException.class, refe.getCause());
             assertEquals("batch", pbe.getPropertyName());
-            TypeConversionException tce = assertIsInstanceOf(TypeConversionException.class, pbe.getCause());
+            assertIsInstanceOf(IllegalArgumentException.class, pbe.getCause());
             assertEquals("[true, true]", pbe.getValue().toString());
         }
     }
diff --git a/core/camel-api/src/main/java/org/apache/camel/spi/AnnotationScanTypeConverters.java b/core/camel-api/src/main/java/org/apache/camel/spi/AnnotationScanTypeConverters.java
new file mode 100644
index 0000000..41dd5fa
--- /dev/null
+++ b/core/camel-api/src/main/java/org/apache/camel/spi/AnnotationScanTypeConverters.java
@@ -0,0 +1,17 @@
+package org.apache.camel.spi;
+
+/**
+ * A {@link org.apache.camel.TypeConverter} which is capable of annotation scanning for {@link org.apache.camel.Converter}
+ * classes and add these as type converters.
+ * <p/>
+ * This is using Camel 2.x style and its recommended to migrate to @Converter(loader = true) for fast type converter mode.
+ */
+public interface AnnotationScanTypeConverters {
+
+    /**
+     * Scan for {@link org.apache.camel.Converter} classes and add those as type converters.
+     *
+     * @throws Exception is thrown if error happened
+     */
+    void scanTypeConverters() throws Exception;
+}
diff --git a/core/camel-base/src/main/java/org/apache/camel/converter/TimePatternConverter.java b/core/camel-base/src/main/java/org/apache/camel/converter/TimePatternConverter.java
index 4ccb021..c809fed 100644
--- a/core/camel-base/src/main/java/org/apache/camel/converter/TimePatternConverter.java
+++ b/core/camel-base/src/main/java/org/apache/camel/converter/TimePatternConverter.java
@@ -21,7 +21,6 @@ import org.apache.camel.util.TimeUtils;
 
 /**
  * Converter from String syntax to milli seconds.
- * Code is copied to org.apache.camel.catalog.TimePatternConverter in camel-catalog
  */
 @Converter(generateLoader = true)
 public final class TimePatternConverter {  
diff --git a/core/camel-base/src/main/java/org/apache/camel/impl/converter/BaseTypeConverterRegistry.java b/core/camel-base/src/main/java/org/apache/camel/impl/converter/BaseTypeConverterRegistry.java
index 6ef8380..0fbff03 100644
--- a/core/camel-base/src/main/java/org/apache/camel/impl/converter/BaseTypeConverterRegistry.java
+++ b/core/camel-base/src/main/java/org/apache/camel/impl/converter/BaseTypeConverterRegistry.java
@@ -48,6 +48,7 @@ import org.apache.camel.TypeConverterExists;
 import org.apache.camel.TypeConverterExistsException;
 import org.apache.camel.TypeConverterLoaderException;
 import org.apache.camel.TypeConverters;
+import org.apache.camel.converter.ObjectConverter;
 import org.apache.camel.spi.CamelLogger;
 import org.apache.camel.spi.FactoryFinder;
 import org.apache.camel.spi.Injector;
@@ -126,6 +127,46 @@ public abstract class BaseTypeConverterRegistry extends ServiceSupport implement
     @SuppressWarnings("unchecked")
     @Override
     public <T> T convertTo(Class<T> type, Exchange exchange, Object value) {
+        // optimize for a few common conversions
+        if (value != null) {
+            if (type.isInstance(value)) {
+                // same instance
+                return (T) value;
+            }
+            if (type == boolean.class) {
+                // primitive boolean which must return a value so throw exception if not possible
+                Object answer = ObjectConverter.toBoolean(value);
+                if (answer == null) {
+                    throw new IllegalArgumentException("Cannot convert type: " + value.getClass().getName() + " to boolean");
+                }
+                return (T) answer;
+            } else if (type == Boolean.class && (value instanceof String)) {
+                // String -> Boolean
+                String str = (String) value;
+                if ("true".equalsIgnoreCase(str)) {
+                    return (T) Boolean.TRUE;
+                } else if ("false".equalsIgnoreCase(str)) {
+                    return (T) Boolean.FALSE;
+                }
+            } else if (type.isPrimitive()) {
+                // okay its a wrapper -> primitive then return as-is for some common types
+                Class cls = value.getClass();
+                if (cls == Integer.class || cls == Long.class) {
+                    return (T) value;
+                }
+            } else if (type == String.class) {
+                // okay its a primitive -> string then return as-is for some common types
+                Class cls = value.getClass();
+                if (cls.isPrimitive()
+                        || cls == Boolean.class || cls == boolean.class
+                        || cls == Integer.class || cls == int.class
+                        || cls == Long.class || cls == long.class) {
+                    return (T) value.toString();
+                }
+            }
+            // NOTE: we cannot optimize any more if value is String as it may be time pattern and other patterns
+        }
+
         return (T) doConvertTo(type, exchange, value, false, false);
     }
 
@@ -137,6 +178,46 @@ public abstract class BaseTypeConverterRegistry extends ServiceSupport implement
     @SuppressWarnings("unchecked")
     @Override
     public <T> T mandatoryConvertTo(Class<T> type, Exchange exchange, Object value) throws NoTypeConversionAvailableException {
+        // optimize for a few common conversions
+        if (value != null) {
+            if (type.isInstance(value)) {
+                // same instance
+                return (T) value;
+            }
+            if (type == boolean.class) {
+                // primitive boolean which must return a value so throw exception if not possible
+                Object answer = ObjectConverter.toBoolean(value);
+                if (answer == null) {
+                    throw new IllegalArgumentException("Cannot convert type: " + value.getClass().getName() + " to boolean");
+                }
+                return (T) answer;
+            } else if (type == Boolean.class && (value instanceof String)) {
+                // String -> Boolean
+                String str = (String) value;
+                if ("true".equalsIgnoreCase(str)) {
+                    return (T) Boolean.TRUE;
+                } else if ("false".equalsIgnoreCase(str)) {
+                    return (T) Boolean.FALSE;
+                }
+            } else if (type.isPrimitive()) {
+                // okay its a wrapper -> primitive then return as-is for some common types
+                Class cls = value.getClass();
+                if (cls == Integer.class || cls == Long.class) {
+                    return (T) value;
+                }
+            } else if (type == String.class) {
+                // okay its a primitive -> string then return as-is for some common types
+                Class cls = value.getClass();
+                if (cls.isPrimitive()
+                        || cls == Boolean.class || cls == boolean.class
+                        || cls == Integer.class || cls == int.class
+                        || cls == Long.class || cls == long.class) {
+                    return (T) value.toString();
+                }
+            }
+            // NOTE: we cannot optimize any more if value is String as it may be time pattern and other patterns
+        }
+
         Object answer = doConvertTo(type, exchange, value, true, false);
         if (answer == null) {
             // Could not find suitable conversion
@@ -156,7 +237,8 @@ public abstract class BaseTypeConverterRegistry extends ServiceSupport implement
         return (T) doConvertTo(type, exchange, value, false, true);
     }
 
-    protected Object doConvertTo(final Class<?> type, final Exchange exchange, final Object value, final boolean mandatory, final boolean tryConvert) {
+    protected Object doConvertTo(final Class<?> type, final Exchange exchange, final Object value,
+                                 final boolean mandatory, final boolean tryConvert) {
         Object answer;
         try {
             answer = doConvertTo(type, exchange, value, tryConvert);
@@ -192,7 +274,8 @@ public abstract class BaseTypeConverterRegistry extends ServiceSupport implement
         }
     }
 
-    protected Object doConvertTo(final Class<?> type, final Exchange exchange, final Object value, final boolean tryConvert) throws Exception {
+    protected Object doConvertTo(final Class<?> type, final Exchange exchange, final Object value,
+                                 final boolean tryConvert) throws Exception {
         boolean trace = LOG.isTraceEnabled();
         boolean statisticsEnabled = statistics.isStatisticsEnabled();
 
@@ -411,7 +494,8 @@ public abstract class BaseTypeConverterRegistry extends ServiceSupport implement
         }
     }
 
-    private void addCoreFallbackTypeConverterToList(TypeConverter typeConverter, boolean canPromote, List<FallbackTypeConverter> converters) {
+    private void addCoreFallbackTypeConverterToList(TypeConverter typeConverter, boolean canPromote, List<
+            FallbackTypeConverter> converters) {
         LOG.trace("Adding core fallback type converter: {} which can promote: {}", typeConverter, canPromote);
 
         // add in top of fallback as the toString() fallback will nearly always be able to convert
@@ -496,7 +580,7 @@ public abstract class BaseTypeConverterRegistry extends ServiceSupport implement
                 TypeConverter converter = typeMappings.getFirst(
                         toType::isAssignableFrom,
                         // skip Object based we do them last
-                    from -> !from.equals(Object.class) && from.isAssignableFrom(fromType));
+                        from -> !from.equals(Object.class) && from.isAssignableFrom(fromType));
                 if (converter != null) {
                     return converter;
                 }
@@ -653,7 +737,8 @@ public abstract class BaseTypeConverterRegistry extends ServiceSupport implement
         }
     }
 
-    protected TypeConversionException createTypeConversionException(Exchange exchange, Class<?> type, Object value, Throwable cause) {
+    protected TypeConversionException createTypeConversionException(Exchange exchange, Class<?> type, Object
+            value, Throwable cause) {
         if (cause instanceof TypeConversionException) {
             if (((TypeConversionException) cause).getToType() == type) {
                 return (TypeConversionException) cause;
@@ -708,7 +793,6 @@ public abstract class BaseTypeConverterRegistry extends ServiceSupport implement
         if (resolver == null && camelContext != null) {
             resolver = camelContext.adapt(ExtendedCamelContext.class).getPackageScanClassResolver();
         }
-        initTypeConverterLoaders();
 
         List<FallbackTypeConverter> fallbacks = new ArrayList<>();
         // add to string first as it will then be last in the last as to string can nearly
@@ -728,12 +812,6 @@ public abstract class BaseTypeConverterRegistry extends ServiceSupport implement
         fallbackConverters.addAll(fallbacks);
     }
 
-    protected void initTypeConverterLoaders() {
-        if (resolver != null) {
-            typeConverterLoaders.add(new AnnotationTypeConverterLoader(resolver));
-        }
-    }
-
     @Override
     protected void doStart() throws Exception {
         // noop
diff --git a/core/camel-base/src/main/java/org/apache/camel/impl/converter/DefaultTypeConverter.java b/core/camel-base/src/main/java/org/apache/camel/impl/converter/DefaultTypeConverter.java
index e3f5f57..086af3c 100644
--- a/core/camel-base/src/main/java/org/apache/camel/impl/converter/DefaultTypeConverter.java
+++ b/core/camel-base/src/main/java/org/apache/camel/impl/converter/DefaultTypeConverter.java
@@ -17,6 +17,7 @@
 package org.apache.camel.impl.converter;
 
 import org.apache.camel.CamelContext;
+import org.apache.camel.spi.AnnotationScanTypeConverters;
 import org.apache.camel.spi.FactoryFinder;
 import org.apache.camel.spi.Injector;
 import org.apache.camel.spi.PackageScanClassResolver;
@@ -31,10 +32,11 @@ import org.slf4j.LoggerFactory;
  * <p/>
  * This implementation will load type converters up-front on startup.
  */
-public class DefaultTypeConverter extends BaseTypeConverterRegistry {
+public class DefaultTypeConverter extends BaseTypeConverterRegistry implements AnnotationScanTypeConverters {
 
     private static final Logger LOG = LoggerFactory.getLogger(DefaultTypeConverter.class);
 
+    private volatile boolean loadTypeConvertersDone;
     private final boolean loadTypeConverters;
 
     public DefaultTypeConverter(PackageScanClassResolver resolver, Injector injector,
@@ -73,8 +75,35 @@ public class DefaultTypeConverter extends BaseTypeConverterRegistry {
         // core type converters is always loaded which does not use any classpath scanning and therefore is fast
         loadCoreAndFastTypeConverters();
 
+        String time = TimeUtils.printDuration(watch.taken());
+        LOG.debug("Loaded {} type converters in {}", typeMappings.size(), time);
+
+        if (!loadTypeConvertersDone && isLoadTypeConverters()) {
+            scanTypeConverters();
+        }
+    }
+
+    private boolean isLoadTypeConverters() {
+        boolean load = loadTypeConverters;
+        if (camelContext != null) {
+            // camel context can override
+            load = camelContext.isLoadTypeConverters();
+        }
+        return load;
+    }
+
+    @Override
+    public void scanTypeConverters() throws Exception {
+        StopWatch watch = new StopWatch();
+
         // we are using backwards compatible legacy mode to detect additional converters
-        if (loadTypeConverters) {
+        if (!loadTypeConvertersDone) {
+            loadTypeConvertersDone = true;
+
+            if (resolver != null) {
+                typeConverterLoaders.add(new AnnotationTypeConverterLoader(resolver));
+            }
+
             int fast = typeMappings.size();
             // load type converters up front
             loadTypeConverters();
@@ -93,15 +122,6 @@ public class DefaultTypeConverter extends BaseTypeConverterRegistry {
         }
 
         String time = TimeUtils.printDuration(watch.taken());
-        LOG.debug("Loaded {} type converters in {}", typeMappings.size(), time);
+        LOG.debug("Scanned {} type converters in {}", typeMappings.size(), time);
     }
-
-    @Override
-    protected void initTypeConverterLoaders() {
-        // only use Camel 2.x annotation based loaders if enabled
-        if (resolver != null && loadTypeConverters)  {
-            typeConverterLoaders.add(new FastAnnotationTypeConverterLoader(resolver));
-        }
-    }
-
 }
diff --git a/core/camel-base/src/main/java/org/apache/camel/impl/engine/AbstractCamelContext.java b/core/camel-base/src/main/java/org/apache/camel/impl/engine/AbstractCamelContext.java
index fe96711..3473ef4 100644
--- a/core/camel-base/src/main/java/org/apache/camel/impl/engine/AbstractCamelContext.java
+++ b/core/camel-base/src/main/java/org/apache/camel/impl/engine/AbstractCamelContext.java
@@ -80,6 +80,7 @@ import org.apache.camel.catalog.RuntimeCamelCatalog;
 import org.apache.camel.impl.transformer.TransformerKey;
 import org.apache.camel.impl.validator.ValidatorKey;
 import org.apache.camel.spi.AnnotationBasedProcessorFactory;
+import org.apache.camel.spi.AnnotationScanTypeConverters;
 import org.apache.camel.spi.AsyncProcessorAwaitManager;
 import org.apache.camel.spi.BeanIntrospection;
 import org.apache.camel.spi.BeanProcessorFactory;
@@ -2512,6 +2513,10 @@ public abstract class AbstractCamelContext extends ServiceSupport implements Ext
     }
 
     protected void doStartCamel() throws Exception {
+        // ensure additional type converters is loaded
+        if (loadTypeConverters && typeConverter instanceof AnnotationScanTypeConverters) {
+            ((AnnotationScanTypeConverters) typeConverter).scanTypeConverters();
+        }
 
         // custom properties may use property placeholders so resolve those
         // early on
diff --git a/core/camel-util/src/main/java/org/apache/camel/util/TimeUtils.java b/core/camel-util/src/main/java/org/apache/camel/util/TimeUtils.java
index d6edf36..2773cc3 100644
--- a/core/camel-util/src/main/java/org/apache/camel/util/TimeUtils.java
+++ b/core/camel-util/src/main/java/org/apache/camel/util/TimeUtils.java
@@ -99,7 +99,7 @@ public final class TimeUtils {
             }
         }
         if (digit) {
-            return Long.valueOf(source);
+            return Long.parseLong(source);
         }
 
         long milliseconds = 0;
@@ -112,17 +112,17 @@ public final class TimeUtils {
         if (matcher.find()) {
             // Note: This will also be used for regular numeric strings.
             //       This String -> long converter will be used for all strings.
-            milliseconds = Long.valueOf(source);
+            milliseconds = Long.parseLong(source);
         } else {
             matcher = createMatcher(HOUR_REGEX_PATTERN, source);
             if (matcher.find()) {
-                milliseconds = milliseconds + (3600000 * Long.valueOf(matcher.group(1)));
+                milliseconds = milliseconds + (3600000 * Long.parseLong(matcher.group(1)));
                 foundFlag = true;
             }
 
             matcher = createMatcher(MINUTES_REGEX_PATTERN, source);
             if (matcher.find()) {
-                long minutes = Long.valueOf(matcher.group(1));
+                long minutes = Long.parseLong(matcher.group(1));
                 if ((minutes > 59) && foundFlag) {
                     throw new IllegalArgumentException("Minutes should contain a valid value between 0 and 59: " + source);
                 }
@@ -132,7 +132,7 @@ public final class TimeUtils {
 
             matcher = createMatcher(SECONDS_REGEX_PATTERN, source);
             if (matcher.find()) {
-                long seconds = Long.valueOf(matcher.group(1));
+                long seconds = Long.parseLong(matcher.group(1));
                 if ((seconds > 59) && foundFlag) {
                     throw new IllegalArgumentException("Seconds should contain a valid value between 0 and 59: " + source);
                 }
@@ -143,7 +143,7 @@ public final class TimeUtils {
             // No pattern matched... initiating fallback check and conversion (if required).
             // The source at this point may contain illegal values or special characters
             if (!foundFlag) {
-                milliseconds = Long.valueOf(source);
+                milliseconds = Long.parseLong(source);
             }
         }
 

Reply | Threaded
Open this post in threaded view
|

[camel] 11/13: Reduce logging noise

davsclaus-2
In reply to this post by davsclaus-2
This is an automated email from the ASF dual-hosted git repository.

davsclaus pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/camel.git

commit 6c891f405f5ee6a43787b21de382fb1d1ee964e8
Author: Claus Ibsen <[hidden email]>
AuthorDate: Sun Feb 16 15:03:46 2020 +0100

    Reduce logging noise
---
 .../java/org/apache/camel/impl/engine/DefaultReactiveExecutor.java    | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/core/camel-base/src/main/java/org/apache/camel/impl/engine/DefaultReactiveExecutor.java b/core/camel-base/src/main/java/org/apache/camel/impl/engine/DefaultReactiveExecutor.java
index e33b85f..dbba46e 100644
--- a/core/camel-base/src/main/java/org/apache/camel/impl/engine/DefaultReactiveExecutor.java
+++ b/core/camel-base/src/main/java/org/apache/camel/impl/engine/DefaultReactiveExecutor.java
@@ -160,8 +160,8 @@ public class DefaultReactiveExecutor extends ServiceSupport implements ReactiveE
                     executor.runningWorkers.decrementAndGet();
                 }
             } else {
-                if (LOG.isDebugEnabled()) {
-                    LOG.debug("Queuing reactive work: {}", runnable);
+                if (LOG.isTraceEnabled()) {
+                    LOG.trace("Queuing reactive work: {}", runnable);
                 }
             }
         }

Reply | Threaded
Open this post in threaded view
|

[camel] 12/13: CAMEL-14572: camel-core - Optimize type converter for some basic convertions

davsclaus-2
In reply to this post by davsclaus-2
This is an automated email from the ASF dual-hosted git repository.

davsclaus pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/camel.git

commit f1a52024555d1d9e219e235a0159e12e20413303
Author: Claus Ibsen <[hidden email]>
AuthorDate: Sun Feb 16 16:20:47 2020 +0100

    CAMEL-14572: camel-core - Optimize type converter for some basic convertions
---
 .../java/org/apache/camel/component/rabbitmq/RabbitConsumer.java     | 5 ++---
 1 file changed, 2 insertions(+), 3 deletions(-)

diff --git a/components/camel-rabbitmq/src/main/java/org/apache/camel/component/rabbitmq/RabbitConsumer.java b/components/camel-rabbitmq/src/main/java/org/apache/camel/component/rabbitmq/RabbitConsumer.java
index aaaa4a0..7ec1618 100644
--- a/components/camel-rabbitmq/src/main/java/org/apache/camel/component/rabbitmq/RabbitConsumer.java
+++ b/components/camel-rabbitmq/src/main/java/org/apache/camel/component/rabbitmq/RabbitConsumer.java
@@ -30,7 +30,6 @@ import org.apache.camel.Exchange;
 import org.apache.camel.ExchangePattern;
 import org.apache.camel.Message;
 import org.apache.camel.RuntimeCamelException;
-import org.apache.camel.TypeConversionException;
 import org.apache.camel.support.service.ServiceSupport;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -160,8 +159,8 @@ class RabbitConsumer extends ServiceSupport implements com.rabbitmq.client.Consu
                 boolean isRequeueHeaderSet = false;
                 try {
                     isRequeueHeaderSet = msg.getHeader(RabbitMQConstants.REQUEUE, false, boolean.class);
-                } catch (TypeConversionException e) {
-                    LOG.warn("Header [{}] with value=[{}] evaluated as [false]", RabbitMQConstants.REQUEUE, e.getValue());
+                } catch (Exception e) {
+                    // ignore as its an invalid header
                 }
 
                 // processing failed, then reject and handle the exception

Reply | Threaded
Open this post in threaded view
|

[camel] 13/13: Fixed CS

davsclaus-2
In reply to this post by davsclaus-2
This is an automated email from the ASF dual-hosted git repository.

davsclaus pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/camel.git

commit 056ef4ee67dfa0b0f263cce4ad7f9ea46f7d86fa
Author: Claus Ibsen <[hidden email]>
AuthorDate: Sun Feb 16 16:26:04 2020 +0100

    Fixed CS
---
 .../apache/camel/spi/AnnotationScanTypeConverters.java   | 16 ++++++++++++++++
 .../camel/impl/converter/BaseTypeConverterRegistry.java  |  6 +++---
 2 files changed, 19 insertions(+), 3 deletions(-)

diff --git a/core/camel-api/src/main/java/org/apache/camel/spi/AnnotationScanTypeConverters.java b/core/camel-api/src/main/java/org/apache/camel/spi/AnnotationScanTypeConverters.java
index 41dd5fa..2a8e785 100644
--- a/core/camel-api/src/main/java/org/apache/camel/spi/AnnotationScanTypeConverters.java
+++ b/core/camel-api/src/main/java/org/apache/camel/spi/AnnotationScanTypeConverters.java
@@ -1,3 +1,19 @@
+/*
+ * 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.spi;
 
 /**
diff --git a/core/camel-base/src/main/java/org/apache/camel/impl/converter/BaseTypeConverterRegistry.java b/core/camel-base/src/main/java/org/apache/camel/impl/converter/BaseTypeConverterRegistry.java
index 0fbff03..aec5b68 100644
--- a/core/camel-base/src/main/java/org/apache/camel/impl/converter/BaseTypeConverterRegistry.java
+++ b/core/camel-base/src/main/java/org/apache/camel/impl/converter/BaseTypeConverterRegistry.java
@@ -578,9 +578,9 @@ public abstract class BaseTypeConverterRegistry extends ServiceSupport implement
 
                 // lets try classes derived from this toType
                 TypeConverter converter = typeMappings.getFirst(
-                        toType::isAssignableFrom,
-                        // skip Object based we do them last
-                        from -> !from.equals(Object.class) && from.isAssignableFrom(fromType));
+                    toType::isAssignableFrom,
+                    // skip Object based we do them last
+                    from -> !from.equals(Object.class) && from.isAssignableFrom(fromType));
                 if (converter != null) {
                     return converter;
                 }