You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@camel.apache.org by da...@apache.org on 2024/09/13 11:06:11 UTC

(camel) 01/01: CAMEL-21174: camel-groovy - Allow to use groovy in the log EIP

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

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

commit ae0670cc84f5826c8ba2911d8dc369a8b193900e
Author: Claus Ibsen <cl...@gmail.com>
AuthorDate: Fri Sep 13 13:05:50 2024 +0200

    CAMEL-21174: camel-groovy - Allow to use groovy in the log EIP
---
 .../main/camel-main-configuration-metadata.json    |  1 +
 .../camel/processor/groovy/GroovyLogEipTest.java   | 69 ++++++++++++++++++++++
 .../org/apache/camel/ExchangeConstantProvider.java |  3 +-
 .../src/main/java/org/apache/camel/Exchange.java   |  1 +
 .../camel/impl/engine/AbstractCamelContext.java    |  6 ++
 .../impl/engine/DefaultCamelContextExtension.java  |  2 +-
 .../org/apache/camel/processor/LogProcessor.java   |  2 +-
 .../java/org/apache/camel/reifier/LogReifier.java  |  7 ++-
 .../MainConfigurationPropertiesConfigurer.java     |  6 ++
 .../camel-main-configuration-metadata.json         |  1 +
 core/camel-main/src/main/docs/main.adoc            |  3 +-
 .../camel/main/DefaultConfigurationConfigurer.java |  3 +
 .../camel/main/DefaultConfigurationProperties.java | 22 +++++++
 13 files changed, 121 insertions(+), 5 deletions(-)

diff --git a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/main/camel-main-configuration-metadata.json b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/main/camel-main-configuration-metadata.json
index db3b4711ef2..caa7c733bca 100644
--- a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/main/camel-main-configuration-metadata.json
+++ b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/main/camel-main-configuration-metadata.json
@@ -81,6 +81,7 @@
     { "name": "camel.main.loadTypeConverters", "description": "Whether to load custom type converters by scanning classpath. This is used for backwards compatibility with Camel 2.x. Its recommended to migrate to use fast type converter loading by setting Converter(loader = true) on your custom type converter classes.", "sourceType": "org.apache.camel.main.DefaultConfigurationProperties", "type": "boolean", "javaType": "boolean", "defaultValue": "false" },
     { "name": "camel.main.logDebugMaxChars", "description": "Is used to limit the maximum length of the logging Camel message bodies. If the message body is longer than the limit, the log message is clipped. Use -1 to have unlimited length. Use for example 1000 to log at most 1000 characters.", "sourceType": "org.apache.camel.main.DefaultConfigurationProperties", "type": "integer", "javaType": "int" },
     { "name": "camel.main.logExhaustedMessageBody", "description": "Sets whether to log exhausted message body with message history. Default is false.", "sourceType": "org.apache.camel.main.DefaultConfigurationProperties", "type": "boolean", "javaType": "boolean", "defaultValue": "false" },
+    { "name": "camel.main.logLanguage", "description": "To configure the language to use for Log EIP. By default, the simple language is used. However, Camel also supports other languages such as groovy.", "sourceType": "org.apache.camel.main.DefaultConfigurationProperties", "type": "string", "javaType": "java.lang.String" },
     { "name": "camel.main.logMask", "description": "Sets whether log mask is enabled or not. Default is false.", "sourceType": "org.apache.camel.main.DefaultConfigurationProperties", "type": "boolean", "javaType": "boolean", "defaultValue": "false" },
     { "name": "camel.main.logName", "description": "The global name to use for Log EIP The name is default the routeId or the source:line if source location is enabled. You can also specify the name using tokens: ${class} - the logger class name (org.apache.camel.processor.LogProcessor) ${contextId} - the camel context id ${routeId} - the route id ${groupId} - the route group id ${nodeId} - the node id ${nodePrefixId} - the node prefix id ${source} - the source:line (source location must [...]
     { "name": "camel.main.mainListenerClasses", "description": "Sets classes names that will be used for MainListener that makes it possible to do custom logic during starting and stopping camel-main.", "sourceType": "org.apache.camel.main.MainConfigurationProperties", "type": "string", "javaType": "java.lang.String" },
diff --git a/components/camel-groovy/src/test/java/org/apache/camel/processor/groovy/GroovyLogEipTest.java b/components/camel-groovy/src/test/java/org/apache/camel/processor/groovy/GroovyLogEipTest.java
new file mode 100644
index 00000000000..6a02b09d64a
--- /dev/null
+++ b/components/camel-groovy/src/test/java/org/apache/camel/processor/groovy/GroovyLogEipTest.java
@@ -0,0 +1,69 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.processor.groovy;
+
+import groovy.lang.MissingPropertyException;
+import org.apache.camel.CamelContext;
+import org.apache.camel.Exchange;
+import org.apache.camel.RoutesBuilder;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.test.junit5.CamelTestSupport;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.fail;
+
+public class GroovyLogEipTest extends CamelTestSupport {
+
+    @Override
+    protected CamelContext createCamelContext() throws Exception {
+        CamelContext context = super.createCamelContext();
+        context.getGlobalOptions().put(Exchange.LOG_EIP_LANGUAGE, "groovy");
+        return context;
+    }
+
+    @Test
+    public void testLogOkay() {
+        template.sendBody("direct:start", 3);
+    }
+
+    @Test
+    public void testLogFail() {
+        try {
+            template.sendBody("direct:fail", 4);
+            fail("Should fail");
+        } catch (Exception e) {
+            Assertions.assertInstanceOf(MissingPropertyException.class, e.getCause());
+        }
+    }
+
+    @Override
+    protected RoutesBuilder createRouteBuilder() throws Exception {
+        return new RouteBuilder() {
+            @Override
+            public void configure() throws Exception {
+                from("direct:start")
+                        .log("body")
+                        .log("body * 2")
+                        .log("'Hello ${body}'");
+
+                from("direct:fail")
+                        .log("XXX");
+            }
+        };
+    }
+}
diff --git a/core/camel-api/src/generated/java/org/apache/camel/ExchangeConstantProvider.java b/core/camel-api/src/generated/java/org/apache/camel/ExchangeConstantProvider.java
index d56d611cc2d..a9f44b186c7 100644
--- a/core/camel-api/src/generated/java/org/apache/camel/ExchangeConstantProvider.java
+++ b/core/camel-api/src/generated/java/org/apache/camel/ExchangeConstantProvider.java
@@ -13,7 +13,7 @@ public class ExchangeConstantProvider {
 
     private static final Map<String, String> MAP;
     static {
-        Map<String, String> map = new HashMap<>(158);
+        Map<String, String> map = new HashMap<>(159);
         map.put("ACCEPT_CONTENT_TYPE", "CamelAcceptContentType");
         map.put("ACTIVE_SPAN", "OpenTracing.activeSpan");
         map.put("AGGREGATED_COLLECTION_GUARD", "CamelAggregatedCollectionGuard");
@@ -105,6 +105,7 @@ public class ExchangeConstantProvider {
         map.put("LANGUAGE_SCRIPT", "CamelLanguageScript");
         map.put("LOG_DEBUG_BODY_MAX_CHARS", "CamelLogDebugBodyMaxChars");
         map.put("LOG_DEBUG_BODY_STREAMS", "CamelLogDebugStreams");
+        map.put("LOG_EIP_LANGUAGE", "CamelLogEipLanguage");
         map.put("LOG_EIP_NAME", "CamelLogEipName");
         map.put("LOOP_INDEX", "CamelLoopIndex");
         map.put("LOOP_SIZE", "CamelLoopSize");
diff --git a/core/camel-api/src/main/java/org/apache/camel/Exchange.java b/core/camel-api/src/main/java/org/apache/camel/Exchange.java
index 82b0b115b08..3d21ca663ee 100644
--- a/core/camel-api/src/main/java/org/apache/camel/Exchange.java
+++ b/core/camel-api/src/main/java/org/apache/camel/Exchange.java
@@ -213,6 +213,7 @@ public interface Exchange extends VariableAware {
     String LOG_DEBUG_BODY_MAX_CHARS = "CamelLogDebugBodyMaxChars";
     String LOG_DEBUG_BODY_STREAMS = "CamelLogDebugStreams";
     String LOG_EIP_NAME = "CamelLogEipName";
+    String LOG_EIP_LANGUAGE = "CamelLogEipLanguage";
     @Metadata(label = "loop", description = "Index of the current iteration (0 based).", javaType = "int")
     String LOOP_INDEX = "CamelLoopIndex";
     @Metadata(label = "loop",
diff --git a/core/camel-base-engine/src/main/java/org/apache/camel/impl/engine/AbstractCamelContext.java b/core/camel-base-engine/src/main/java/org/apache/camel/impl/engine/AbstractCamelContext.java
index e12bd58a0b0..91550c0ecf3 100644
--- a/core/camel-base-engine/src/main/java/org/apache/camel/impl/engine/AbstractCamelContext.java
+++ b/core/camel-base-engine/src/main/java/org/apache/camel/impl/engine/AbstractCamelContext.java
@@ -2789,6 +2789,9 @@ public abstract class AbstractCamelContext extends BaseService
             startupStepRecorder.endStep(subStep);
         }
 
+        // start log listeners
+        ServiceHelper.startService(getCamelContextExtension().getLogListeners());
+
         // ensure components are started
         for (Map.Entry<String, Component> entry : components.entrySet()) {
             StartupStep step = startupStepRecorder.beginStep(Component.class, entry.getKey(), "Start Component");
@@ -3021,6 +3024,9 @@ public abstract class AbstractCamelContext extends BaseService
         // shutdown services as late as possible (except type converters as they may be needed during the remainder of the stopping)
         internalServiceManager.shutdownServices(this);
 
+        // shutdown log listeners
+        ServiceHelper.stopAndShutdownServices(getCamelContextExtension().getLogListeners());
+
         try {
             for (LifecycleStrategy strategy : lifecycleStrategies) {
                 strategy.onContextStopped(this);
diff --git a/core/camel-base-engine/src/main/java/org/apache/camel/impl/engine/DefaultCamelContextExtension.java b/core/camel-base-engine/src/main/java/org/apache/camel/impl/engine/DefaultCamelContextExtension.java
index 5650e78344e..6f8557fc90a 100644
--- a/core/camel-base-engine/src/main/java/org/apache/camel/impl/engine/DefaultCamelContextExtension.java
+++ b/core/camel-base-engine/src/main/java/org/apache/camel/impl/engine/DefaultCamelContextExtension.java
@@ -90,7 +90,6 @@ import org.slf4j.LoggerFactory;
 
 class DefaultCamelContextExtension implements ExtendedCamelContext {
 
-    private static final Logger log = LoggerFactory.getLogger(DefaultCamelContextExtension.class);
     private final AbstractCamelContext camelContext;
     private final ThreadLocal<Boolean> isSetupRoutes = new ThreadLocal<>();
     private final List<InterceptStrategy> interceptStrategies = new ArrayList<>();
@@ -424,6 +423,7 @@ class DefaultCamelContextExtension implements ExtendedCamelContext {
     @Override
     public void addLogListener(LogListener listener) {
         // avoid adding double which can happen with spring xml on spring boot
+        CamelContextAware.trySetCamelContext(listener, camelContext);
         logListeners.add(listener);
     }
 
diff --git a/core/camel-core-processor/src/main/java/org/apache/camel/processor/LogProcessor.java b/core/camel-core-processor/src/main/java/org/apache/camel/processor/LogProcessor.java
index 764f5d79086..537bca00ae1 100644
--- a/core/camel-core-processor/src/main/java/org/apache/camel/processor/LogProcessor.java
+++ b/core/camel-core-processor/src/main/java/org/apache/camel/processor/LogProcessor.java
@@ -96,7 +96,7 @@ public class LogProcessor extends AsyncProcessorSupport implements Traceable, Id
                 String output = listener.onLog(exchange, logger, message);
                 message = output != null ? output : message;
             } catch (Exception t) {
-                LOG.warn("Ignoring an exception thrown by {}: {}", listener.getClass().getName(), t.getMessage());
+                LOG.warn("Ignoring an exception: {} thrown by: {} caused by: {}", t.getClass().getName(), listener.getClass().getName(), t.getMessage());
                 if (LOG.isDebugEnabled()) {
                     LOG.debug("", t);
                 }
diff --git a/core/camel-core-reifier/src/main/java/org/apache/camel/reifier/LogReifier.java b/core/camel-core-reifier/src/main/java/org/apache/camel/reifier/LogReifier.java
index 0a245a75487..55d1afcc81a 100644
--- a/core/camel-core-reifier/src/main/java/org/apache/camel/reifier/LogReifier.java
+++ b/core/camel-core-reifier/src/main/java/org/apache/camel/reifier/LogReifier.java
@@ -48,10 +48,15 @@ public class LogReifier extends ProcessorReifier<LogDefinition> {
         StringHelper.notEmpty(definition.getMessage(), "message", this);
         String msg = parseString(definition.getMessage());
 
+        // use a custom language
+        String lan = camelContext.getGlobalOption(Exchange.LOG_EIP_LANGUAGE);
+
         // use simple language for the message string to give it more power
         Expression exp = null;
-        if (LanguageSupport.hasSimpleFunction(msg)) {
+        if (lan == null && LanguageSupport.hasSimpleFunction(msg)) {
             exp = camelContext.resolveLanguage("simple").createExpression(msg);
+        } else if (lan != null) {
+            exp = camelContext.resolveLanguage(lan).createExpression(msg);
         }
 
         // get logger explicitly set in the definition
diff --git a/core/camel-main/src/generated/java/org/apache/camel/main/MainConfigurationPropertiesConfigurer.java b/core/camel-main/src/generated/java/org/apache/camel/main/MainConfigurationPropertiesConfigurer.java
index 9e1a410fd6b..e8d03e9f36f 100644
--- a/core/camel-main/src/generated/java/org/apache/camel/main/MainConfigurationPropertiesConfigurer.java
+++ b/core/camel-main/src/generated/java/org/apache/camel/main/MainConfigurationPropertiesConfigurer.java
@@ -140,6 +140,8 @@ public class MainConfigurationPropertiesConfigurer extends org.apache.camel.supp
         case "logDebugMaxChars": target.setLogDebugMaxChars(property(camelContext, int.class, value)); return true;
         case "logexhaustedmessagebody":
         case "logExhaustedMessageBody": target.setLogExhaustedMessageBody(property(camelContext, boolean.class, value)); return true;
+        case "loglanguage":
+        case "logLanguage": target.setLogLanguage(property(camelContext, java.lang.String.class, value)); return true;
         case "logmask":
         case "logMask": target.setLogMask(property(camelContext, boolean.class, value)); return true;
         case "logname":
@@ -382,6 +384,8 @@ public class MainConfigurationPropertiesConfigurer extends org.apache.camel.supp
         case "logDebugMaxChars": return int.class;
         case "logexhaustedmessagebody":
         case "logExhaustedMessageBody": return boolean.class;
+        case "loglanguage":
+        case "logLanguage": return java.lang.String.class;
         case "logmask":
         case "logMask": return boolean.class;
         case "logname":
@@ -625,6 +629,8 @@ public class MainConfigurationPropertiesConfigurer extends org.apache.camel.supp
         case "logDebugMaxChars": return target.getLogDebugMaxChars();
         case "logexhaustedmessagebody":
         case "logExhaustedMessageBody": return target.isLogExhaustedMessageBody();
+        case "loglanguage":
+        case "logLanguage": return target.getLogLanguage();
         case "logmask":
         case "logMask": return target.isLogMask();
         case "logname":
diff --git a/core/camel-main/src/generated/resources/META-INF/camel-main-configuration-metadata.json b/core/camel-main/src/generated/resources/META-INF/camel-main-configuration-metadata.json
index db3b4711ef2..caa7c733bca 100644
--- a/core/camel-main/src/generated/resources/META-INF/camel-main-configuration-metadata.json
+++ b/core/camel-main/src/generated/resources/META-INF/camel-main-configuration-metadata.json
@@ -81,6 +81,7 @@
     { "name": "camel.main.loadTypeConverters", "description": "Whether to load custom type converters by scanning classpath. This is used for backwards compatibility with Camel 2.x. Its recommended to migrate to use fast type converter loading by setting Converter(loader = true) on your custom type converter classes.", "sourceType": "org.apache.camel.main.DefaultConfigurationProperties", "type": "boolean", "javaType": "boolean", "defaultValue": "false" },
     { "name": "camel.main.logDebugMaxChars", "description": "Is used to limit the maximum length of the logging Camel message bodies. If the message body is longer than the limit, the log message is clipped. Use -1 to have unlimited length. Use for example 1000 to log at most 1000 characters.", "sourceType": "org.apache.camel.main.DefaultConfigurationProperties", "type": "integer", "javaType": "int" },
     { "name": "camel.main.logExhaustedMessageBody", "description": "Sets whether to log exhausted message body with message history. Default is false.", "sourceType": "org.apache.camel.main.DefaultConfigurationProperties", "type": "boolean", "javaType": "boolean", "defaultValue": "false" },
+    { "name": "camel.main.logLanguage", "description": "To configure the language to use for Log EIP. By default, the simple language is used. However, Camel also supports other languages such as groovy.", "sourceType": "org.apache.camel.main.DefaultConfigurationProperties", "type": "string", "javaType": "java.lang.String" },
     { "name": "camel.main.logMask", "description": "Sets whether log mask is enabled or not. Default is false.", "sourceType": "org.apache.camel.main.DefaultConfigurationProperties", "type": "boolean", "javaType": "boolean", "defaultValue": "false" },
     { "name": "camel.main.logName", "description": "The global name to use for Log EIP The name is default the routeId or the source:line if source location is enabled. You can also specify the name using tokens: ${class} - the logger class name (org.apache.camel.processor.LogProcessor) ${contextId} - the camel context id ${routeId} - the route id ${groupId} - the route group id ${nodeId} - the node id ${nodePrefixId} - the node prefix id ${source} - the source:line (source location must [...]
     { "name": "camel.main.mainListenerClasses", "description": "Sets classes names that will be used for MainListener that makes it possible to do custom logic during starting and stopping camel-main.", "sourceType": "org.apache.camel.main.MainConfigurationProperties", "type": "string", "javaType": "java.lang.String" },
diff --git a/core/camel-main/src/main/docs/main.adoc b/core/camel-main/src/main/docs/main.adoc
index 1081c568312..d9c7e718d9e 100644
--- a/core/camel-main/src/main/docs/main.adoc
+++ b/core/camel-main/src/main/docs/main.adoc
@@ -19,7 +19,7 @@ The following tables lists all the options:
 
 // main options: START
 === Camel Main configurations
-The camel.main supports 121 options, which are listed below.
+The camel.main supports 122 options, which are listed below.
 
 [width="100%",cols="2,5,^1,2",options="header"]
 |===
@@ -84,6 +84,7 @@ The camel.main supports 121 options, which are listed below.
 | *camel.main.loadTypeConverters* | Whether to load custom type converters by scanning classpath. This is used for backwards compatibility with Camel 2.x. Its recommended to migrate to use fast type converter loading by setting Converter(loader = true) on your custom type converter classes. | false | boolean
 | *camel.main.logDebugMaxChars* | Is used to limit the maximum length of the logging Camel message bodies. If the message body is longer than the limit, the log message is clipped. Use -1 to have unlimited length. Use for example 1000 to log at most 1000 characters. |  | int
 | *camel.main.logExhaustedMessage{zwsp}Body* | Sets whether to log exhausted message body with message history. Default is false. | false | boolean
+| *camel.main.logLanguage* | To configure the language to use for Log EIP. By default, the simple language is used. However, Camel also supports other languages such as groovy. |  | String
 | *camel.main.logMask* | Sets whether log mask is enabled or not. Default is false. | false | boolean
 | *camel.main.logName* | The global name to use for Log EIP The name is default the routeId or the source:line if source location is enabled. You can also specify the name using tokens: $\{class} - the logger class name (org.apache.camel.processor.LogProcessor) $\{contextId} - the camel context id $\{routeId} - the route id $\{groupId} - the route group id $\{nodeId} - the node id $\{nodePrefixId} - the node prefix id $\{source} - the source:line (source location must be enabled) ${sourc [...]
 | *camel.main.mainListenerClasses* | Sets classes names that will be used for MainListener that makes it possible to do custom logic during starting and stopping camel-main. |  | String
diff --git a/core/camel-main/src/main/java/org/apache/camel/main/DefaultConfigurationConfigurer.java b/core/camel-main/src/main/java/org/apache/camel/main/DefaultConfigurationConfigurer.java
index 7428fa7efac..efb5611c1cb 100644
--- a/core/camel-main/src/main/java/org/apache/camel/main/DefaultConfigurationConfigurer.java
+++ b/core/camel-main/src/main/java/org/apache/camel/main/DefaultConfigurationConfigurer.java
@@ -246,6 +246,9 @@ public final class DefaultConfigurationConfigurer {
         if (config.getLogName() != null) {
             camelContext.getGlobalOptions().put(Exchange.LOG_EIP_NAME, config.getLogName());
         }
+        if (config.getLogLanguage() != null) {
+            camelContext.getGlobalOptions().put(Exchange.LOG_EIP_LANGUAGE, config.getLogLanguage());
+        }
         camelContext.setLogMask(config.isLogMask());
         camelContext.setLogExhaustedMessageBody(config.isLogExhaustedMessageBody());
         camelContext.setAutoStartup(config.isAutoStartup());
diff --git a/core/camel-main/src/main/java/org/apache/camel/main/DefaultConfigurationProperties.java b/core/camel-main/src/main/java/org/apache/camel/main/DefaultConfigurationProperties.java
index 93aa72b5b6f..d2392f983c8 100644
--- a/core/camel-main/src/main/java/org/apache/camel/main/DefaultConfigurationProperties.java
+++ b/core/camel-main/src/main/java/org/apache/camel/main/DefaultConfigurationProperties.java
@@ -83,6 +83,7 @@ public abstract class DefaultConfigurationProperties<T> {
     private boolean logMask;
     private boolean logExhaustedMessageBody;
     private String logName;
+    private String logLanguage;
     private boolean autoStartup = true;
     private boolean allowUseOriginalMessage;
     private boolean caseInsensitiveHeaders = true;
@@ -769,6 +770,18 @@ public abstract class DefaultConfigurationProperties<T> {
         this.logName = logName;
     }
 
+    public String getLogLanguage() {
+        return logLanguage;
+    }
+
+    /**
+     * To configure the language to use for Log EIP. By default, the simple language is used.
+     * However, Camel also supports other languages such as groovy.
+     */
+    public void setLogLanguage(String logLanguage) {
+        this.logLanguage = logLanguage;
+    }
+
     public boolean isAutoStartup() {
         return autoStartup;
     }
@@ -2056,6 +2069,15 @@ public abstract class DefaultConfigurationProperties<T> {
         return (T) this;
     }
 
+    /**
+     * To configure the language to use for Log EIP. By default, the simple language is used.
+     * However, Camel also supports other languages such as groovy.
+     */
+    public T withLogLanguage(String logLanguage) {
+        this.logLanguage = logLanguage;
+        return (T) this;
+    }
+
     /**
      * Sets whether the object should automatically start when Camel starts. Important: Currently only routes can be
      * disabled, as CamelContext's are always started. Note: When setting auto startup false on CamelContext then that