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 2020/09/29 13:13:07 UTC

[camel] branch master updated: CAMEL-15577 Camel-stringtemplate: Misleading and incorrect implementation of parameter 'allowTemplateFromHeader' (#4312)

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


The following commit(s) were added to refs/heads/master by this push:
     new be50820  CAMEL-15577 Camel-stringtemplate: Misleading and incorrect implementation of parameter 'allowTemplateFromHeader' (#4312)
be50820 is described below

commit be508206b26cd40d3574a2feced5847098798967
Author: JiriOndrusek <on...@gmail.com>
AuthorDate: Tue Sep 29 15:12:50 2020 +0200

    CAMEL-15577 Camel-stringtemplate: Misleading and incorrect implementation of parameter 'allowTemplateFromHeader' (#4312)
---
 .../catalog/docs/string-template-component.adoc    | 17 ++++++
 .../src/main/docs/string-template-component.adoc   | 17 ++++++
 .../stringtemplate/StringTemplateConstants.java    |  1 +
 .../stringtemplate/StringTemplateEndpoint.java     | 45 ++++++++++++--
 .../StringTemplateViaHeaderTest.java               | 69 ++++++++++++++++++++++
 .../ROOT/pages/string-template-component.adoc      | 17 ++++++
 6 files changed, 162 insertions(+), 4 deletions(-)

diff --git a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/string-template-component.adoc b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/string-template-component.adoc
index 52172d7..dbb0752 100644
--- a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/string-template-component.adoc
+++ b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/string-template-component.adoc
@@ -113,6 +113,23 @@ and classpath resources (expanded jar). If you set `contentCache=true`,
 Camel loads the resource only once and hot-reloading is not possible.
 This scenario can be used in production when the resource never changes.
 
+== Dynamic templates
+
+Camel provides two headers by which you can define a different resource
+location for a template or the template content itself. If any of these
+headers is set then Camel uses this over the endpoint configured
+resource. This allows you to provide a dynamic template at runtime.
+
+[width="100%",cols="10%,10%,80%",options="header",]
+|=======================================================================
+|Header |Type |Description
+
+|CamelStringTemplateResourceUri |String |A URI for the template resource to use instead of the
+endpoint configured.
+
+|CamelStringTemplateTemplate |String |The template to use instead of the endpoint configured.
+|=======================================================================
+
 == StringTemplate Attributes
 
 You can define the custom context map by setting the
diff --git a/components/camel-stringtemplate/src/main/docs/string-template-component.adoc b/components/camel-stringtemplate/src/main/docs/string-template-component.adoc
index 52172d7..dbb0752 100644
--- a/components/camel-stringtemplate/src/main/docs/string-template-component.adoc
+++ b/components/camel-stringtemplate/src/main/docs/string-template-component.adoc
@@ -113,6 +113,23 @@ and classpath resources (expanded jar). If you set `contentCache=true`,
 Camel loads the resource only once and hot-reloading is not possible.
 This scenario can be used in production when the resource never changes.
 
+== Dynamic templates
+
+Camel provides two headers by which you can define a different resource
+location for a template or the template content itself. If any of these
+headers is set then Camel uses this over the endpoint configured
+resource. This allows you to provide a dynamic template at runtime.
+
+[width="100%",cols="10%,10%,80%",options="header",]
+|=======================================================================
+|Header |Type |Description
+
+|CamelStringTemplateResourceUri |String |A URI for the template resource to use instead of the
+endpoint configured.
+
+|CamelStringTemplateTemplate |String |The template to use instead of the endpoint configured.
+|=======================================================================
+
 == StringTemplate Attributes
 
 You can define the custom context map by setting the
diff --git a/components/camel-stringtemplate/src/main/java/org/apache/camel/component/stringtemplate/StringTemplateConstants.java b/components/camel-stringtemplate/src/main/java/org/apache/camel/component/stringtemplate/StringTemplateConstants.java
index 2eb2db2..4e4c480 100644
--- a/components/camel-stringtemplate/src/main/java/org/apache/camel/component/stringtemplate/StringTemplateConstants.java
+++ b/components/camel-stringtemplate/src/main/java/org/apache/camel/component/stringtemplate/StringTemplateConstants.java
@@ -23,6 +23,7 @@ public final class StringTemplateConstants {
 
     public static final String STRINGTEMPLATE_RESOURCE_URI = "CamelStringTemplateResourceUri";
     public static final String STRINGTEMPLATE_VARIABLE_MAP = "CamelStringTemplateVariableMap";
+    public static final String STRINGTEMPLATE_TEMPLATE = "CamelStringTemplateTemplate";
 
     private StringTemplateConstants() {
         // Utility class
diff --git a/components/camel-stringtemplate/src/main/java/org/apache/camel/component/stringtemplate/StringTemplateEndpoint.java b/components/camel-stringtemplate/src/main/java/org/apache/camel/component/stringtemplate/StringTemplateEndpoint.java
index 302eb73..2a996db 100644
--- a/components/camel-stringtemplate/src/main/java/org/apache/camel/component/stringtemplate/StringTemplateEndpoint.java
+++ b/components/camel-stringtemplate/src/main/java/org/apache/camel/component/stringtemplate/StringTemplateEndpoint.java
@@ -28,6 +28,7 @@ import org.apache.camel.component.ResourceEndpoint;
 import org.apache.camel.spi.UriEndpoint;
 import org.apache.camel.spi.UriParam;
 import org.apache.camel.support.ExchangeHelper;
+import org.apache.camel.util.ObjectHelper;
 import org.stringtemplate.v4.NoIndentWriter;
 import org.stringtemplate.v4.ST;
 import org.stringtemplate.v4.STGroup;
@@ -95,26 +96,62 @@ public class StringTemplateEndpoint extends ResourceEndpoint {
         this.allowTemplateFromHeader = allowTemplateFromHeader;
     }
 
+    public StringTemplateEndpoint findOrCreateEndpoint(String uri, String newResourceUri) {
+        String newUri = uri.replace(getResourceUri(), newResourceUri);
+        log.debug("Getting endpoint with URI: {}", newUri);
+        return getCamelContext().getEndpoint(newUri, StringTemplateEndpoint.class);
+    }
+
     @Override
     protected void onExchange(Exchange exchange) throws Exception {
+        String template = null;
+        String path = getResourceUri();
+        ObjectHelper.notNull(path, "resourceUri");
+
         StringWriter buffer = new StringWriter();
 
         Map<String, Object> variableMap = null;
+
         if (allowTemplateFromHeader) {
+            String newResourceUri
+                    = exchange.getIn().getHeader(StringTemplateConstants.STRINGTEMPLATE_RESOURCE_URI, String.class);
+            if (newResourceUri != null) {
+                exchange.getIn().removeHeader(StringTemplateConstants.STRINGTEMPLATE_RESOURCE_URI);
+
+                log.debug("{} set to {} creating new endpoint to handle exchange",
+                        StringTemplateConstants.STRINGTEMPLATE_RESOURCE_URI,
+                        newResourceUri);
+                StringTemplateEndpoint newEndpoint = findOrCreateEndpoint(getEndpointUri(), newResourceUri);
+                newEndpoint.onExchange(exchange);
+                return;
+            }
             variableMap = exchange.getIn().getHeader(StringTemplateConstants.STRINGTEMPLATE_VARIABLE_MAP, Map.class);
+            template = exchange.getIn().getHeader(StringTemplateConstants.STRINGTEMPLATE_TEMPLATE, String.class);
         }
+
         if (variableMap == null) {
             variableMap = ExchangeHelper.createVariableMap(exchange, isAllowContextMapAll());
         }
 
+        if (template != null) {
+            log.debug("StringTemplate content read from header {} for endpoint {}",
+                    StringTemplateConstants.STRINGTEMPLATE_TEMPLATE,
+                    getEndpointUri());
+            // remove the header to avoid it being propagated in the routing
+            exchange.getIn().removeHeader(StringTemplateConstants.STRINGTEMPLATE_TEMPLATE);
+        } else {
+            log.debug("StringTemplate content read from resource {} with resourceUri: {} for endpoint {}", getResourceUri(),
+                    path,
+                    getEndpointUri());
+            template = exchange.getContext().getTypeConverter().mandatoryConvertTo(String.class, getResourceAsInputStream());
+        }
         // getResourceAsInputStream also considers the content cache
-        String text = exchange.getContext().getTypeConverter().mandatoryConvertTo(String.class, getResourceAsInputStream());
-        ST template = new ST(text, delimiterStart, delimiterStop);
+        ST stTemplate = new ST(template, delimiterStart, delimiterStop);
         for (Map.Entry<String, Object> entry : variableMap.entrySet()) {
-            template.add(entry.getKey(), entry.getValue());
+            stTemplate.add(entry.getKey(), entry.getValue());
         }
         log.debug("StringTemplate is writing using attributes: {}", variableMap);
-        template.write(new NoIndentWriter(buffer));
+        stTemplate.write(new NoIndentWriter(buffer));
 
         // now lets output the results to the exchange
         Message out = exchange.getOut();
diff --git a/components/camel-stringtemplate/src/test/java/org/apache/camel/component/stringtemplate/StringTemplateViaHeaderTest.java b/components/camel-stringtemplate/src/test/java/org/apache/camel/component/stringtemplate/StringTemplateViaHeaderTest.java
new file mode 100644
index 0000000..1260d07
--- /dev/null
+++ b/components/camel-stringtemplate/src/test/java/org/apache/camel/component/stringtemplate/StringTemplateViaHeaderTest.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.component.stringtemplate;
+
+import org.apache.camel.Exchange;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.test.junit5.CamelTestSupport;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+public class StringTemplateViaHeaderTest extends CamelTestSupport {
+
+    @Test
+    public void testByHeaderTemplate() throws Exception {
+        Exchange response = template.request("direct:b", exchange -> {
+            exchange.getIn().setHeader("name", "Sheldon");
+            exchange.getIn().setHeader(StringTemplateConstants.STRINGTEMPLATE_TEMPLATE,
+                    "Hi <headers.name>.");
+        });
+
+        assertEquals("Hi Sheldon.", response.getMessage().getBody());
+        assertEquals("dummy",
+                response.getMessage().getHeader(StringTemplateConstants.STRINGTEMPLATE_RESOURCE_URI));
+        assertEquals("Sheldon", response.getMessage().getHeader("name"));
+    }
+
+    @Test
+    public void testByHeaderUri() throws Exception {
+        Exchange response = template.request("direct:a", exchange -> {
+            exchange.getIn().setBody("Monday");
+            exchange.getIn().setHeader("name", "Christian");
+            exchange.getIn().setHeader(StringTemplateConstants.STRINGTEMPLATE_RESOURCE_URI,
+                    "org/apache/camel/component/stringtemplate/template.tm");
+            exchange.setProperty("item", "7");
+        });
+
+        assertEquals("Dear Christian. You ordered item 7 on Monday.", response.getMessage().getBody());
+        assertEquals("org/apache/camel/component/stringtemplate/template.tm",
+                response.getMessage().getHeader(StringTemplateConstants.STRINGTEMPLATE_RESOURCE_URI));
+        assertEquals("Christian", response.getMessage().getHeader("name"));
+    }
+
+    @Override
+    protected RouteBuilder createRouteBuilder() {
+        return new RouteBuilder() {
+            public void configure() {
+                from("direct:a").to(
+                        "string-template:dummy?allowTemplateFromHeader=true&allowContextMapAll=true");
+                from("direct:b").to(
+                        "string-template:dummy?allowTemplateFromHeader=true");
+            }
+        };
+    }
+}
diff --git a/docs/components/modules/ROOT/pages/string-template-component.adoc b/docs/components/modules/ROOT/pages/string-template-component.adoc
index 175f276..391beca 100644
--- a/docs/components/modules/ROOT/pages/string-template-component.adoc
+++ b/docs/components/modules/ROOT/pages/string-template-component.adoc
@@ -115,6 +115,23 @@ and classpath resources (expanded jar). If you set `contentCache=true`,
 Camel loads the resource only once and hot-reloading is not possible.
 This scenario can be used in production when the resource never changes.
 
+== Dynamic templates
+
+Camel provides two headers by which you can define a different resource
+location for a template or the template content itself. If any of these
+headers is set then Camel uses this over the endpoint configured
+resource. This allows you to provide a dynamic template at runtime.
+
+[width="100%",cols="10%,10%,80%",options="header",]
+|=======================================================================
+|Header |Type |Description
+
+|CamelStringTemplateResourceUri |String |A URI for the template resource to use instead of the
+endpoint configured.
+
+|CamelStringTemplateTemplate |String |The template to use instead of the endpoint configured.
+|=======================================================================
+
 == StringTemplate Attributes
 
 You can define the custom context map by setting the