Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions docs/modules/ROOT/pages/reference/extensions/qute.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,16 @@ from("direct:start")
.to("qute:dynamic?allowTemplateFromHeader=true");
---------------------------------------------------------------------------------------------

Dynamic template content with specified content type.

[source,java]
---------------------------------------------------------------------------------------------
from("direct:start")
.setHeader(QuteConstants.QUTE_TEMPLATE).constant("<hello>{headers.greeting}</hello>")
.setHeader(QuteConstants.QUTE_TEMPLATE_CONTENT_TYPE).constant("text/html")
.to("qute:dynamic?allowTemplateFromHeader=true");
---------------------------------------------------------------------------------------------

Dynamic template instance.

[source,java]
Expand Down
5 changes: 5 additions & 0 deletions extensions/qute/component/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,11 @@
<artifactId>junit-platform-launcher</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.logging</groupId>
<artifactId>jboss-logging</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,13 @@
"CamelQuteResourceUri": { "index": 0, "kind": "header", "displayName": "", "group": "producer", "label": "", "required": false, "javaType": "String", "deprecated": false, "deprecationNote": "", "autowired": false, "secret": false, "description": "A URI for the template resource to use instead of the endpoint configured one.", "constantName": "org.apache.camel.component.qute.QuteConstants#QUTE_RESOURCE_URI" },
"CamelQuteTemplate": { "index": 1, "kind": "header", "displayName": "", "group": "producer", "label": "", "required": false, "javaType": "String", "deprecated": false, "deprecationNote": "", "autowired": false, "secret": false, "description": "The template to use instead of the endpoint configured one.", "constantName": "org.apache.camel.component.qute.QuteConstants#QUTE_TEMPLATE" },
"CamelQuteTemplateInstance": { "index": 2, "kind": "header", "displayName": "", "group": "producer", "label": "", "required": false, "javaType": "TemplateInstance", "deprecated": false, "deprecationNote": "", "autowired": false, "secret": false, "description": "The template instance to use instead of the endpoint configured one.", "constantName": "org.apache.camel.component.qute.QuteConstants#QUTE_TEMPLATE_INSTANCE" },
"CamelQuteTemplateData": { "index": 3, "kind": "header", "displayName": "", "group": "producer", "label": "", "required": false, "javaType": "Map", "deprecated": false, "deprecationNote": "", "autowired": false, "secret": false, "description": "The template model data.", "constantName": "org.apache.camel.component.qute.QuteConstants#QUTE_TEMPLATE_DATA" }
"CamelQuteTemplateData": { "index": 3, "kind": "header", "displayName": "", "group": "producer", "label": "", "required": false, "javaType": "Map", "deprecated": false, "deprecationNote": "", "autowired": false, "secret": false, "description": "The template model data.", "constantName": "org.apache.camel.component.qute.QuteConstants#QUTE_TEMPLATE_DATA" },
"CamelQuteTemplateContentType": { "index": 4, "kind": "header", "displayName": "", "group": "producer", "label": "", "required": false, "javaType": "String", "deprecated": false, "deprecationNote": "", "autowired": false, "secret": false, "description": "The content type to use for templates rendered from content provided from the CamelQuteTemplate header", "constantName": "org.apache.camel.component.qute.QuteConstants#QUTE_TEMPLATE_CONTENT_TYPE" }
},
"properties": {
"resourceUri": { "index": 0, "kind": "path", "displayName": "Resource Uri", "group": "producer", "label": "", "required": true, "type": "string", "javaType": "java.lang.String", "deprecated": false, "deprecationNote": "", "autowired": false, "secret": false, "supportFileReference": true, "description": "Path to the resource. You can prefix with: classpath, file, http, ref, or bean. classpath, file and http loads the resource using these protocols (classpath is default). ref will lookup the resource in the registry. bean will call a method on a bean to be used as the resource. For bean you can specify the method name after dot, eg bean:myBean.myMethod." },
"allowContextMapAll": { "index": 1, "kind": "parameter", "displayName": "Allow Context Map All", "group": "producer", "label": "", "required": false, "type": "boolean", "javaType": "boolean", "deprecated": false, "autowired": false, "secret": false, "defaultValue": false, "description": "Sets whether the context map should allow access to all details. By default only the message body and headers can be accessed. This option can be enabled for full access to the current Exchange and CamelContext. Doing so impose a potential security risk as this opens access to the full power of CamelContext API." },
"allowTemplateFromHeader": { "index": 2, "kind": "parameter", "displayName": "Allow Template From Header", "group": "producer", "label": "", "required": false, "type": "boolean", "javaType": "boolean", "deprecated": false, "autowired": false, "secret": false, "defaultValue": false, "description": "Whether to allow to use resource template from header or not (default false). Enabling this allows to specify dynamic templates via message header. However this can be seen as a potential security vulnerability if the header is coming from a malicious user, so use this with care." },
"allowTemplateFromHeader": { "index": 2, "kind": "parameter", "displayName": "Allow Template From Header", "group": "producer", "label": "", "required": false, "type": "boolean", "javaType": "boolean", "deprecated": false, "autowired": false, "secret": false, "defaultValue": false, "description": "Whether to allow to use resource template from header or not (default false). Enabling this allows to specify dynamic templates via message header. However, this can be seen as a potential security vulnerability if the header is coming from a malicious user, so use this with care." },
"contentCache": { "index": 3, "kind": "parameter", "displayName": "Content Cache", "group": "producer", "label": "", "required": false, "type": "boolean", "javaType": "boolean", "deprecated": false, "autowired": false, "secret": false, "defaultValue": true, "description": "Sets whether to use resource content cache or not" },
"encoding": { "index": 4, "kind": "parameter", "displayName": "Encoding", "group": "producer", "label": "", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": false, "description": "Character encoding of the resource content." },
"lazyStartProducer": { "index": 5, "kind": "parameter", "displayName": "Lazy Start Producer", "group": "producer (advanced)", "label": "producer,advanced", "required": false, "type": "boolean", "javaType": "boolean", "deprecated": false, "autowired": false, "secret": false, "defaultValue": false, "description": "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 starting the producer may take a little time and prolong the total processing time of the processing." }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ public final class QuteConstants {
public static final String QUTE_TEMPLATE_INSTANCE = "CamelQuteTemplateInstance";
@Metadata(description = "The template model data.", javaType = "Map")
public static final String QUTE_TEMPLATE_DATA = "CamelQuteTemplateData";
@Metadata(description = "The content type to use for templates rendered from content provided from the CamelQuteTemplate header", javaType = "String")
public static final String QUTE_TEMPLATE_CONTENT_TYPE = "CamelQuteTemplateContentType";

private QuteConstants() {
// Utility class
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,14 @@
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;
import java.util.Optional;

import io.quarkus.qute.Engine;
import io.quarkus.qute.EngineBuilder;
import io.quarkus.qute.HtmlEscaper;
import io.quarkus.qute.ImmutableList;
import io.quarkus.qute.Qute;
import io.quarkus.qute.ReflectionValueResolver;
import io.quarkus.qute.Template;
import io.quarkus.qute.TemplateException;
Expand Down Expand Up @@ -69,29 +72,17 @@ public void setQuteEngine(Engine engine) {

private synchronized Engine getQuteEngine() {
if (quteEngine == null) {
EngineBuilder builder = Engine.builder().addDefaults();
builder.addValueResolver(ReflectionValueResolver::new);
builder.addLocator(this::locate);

quteEngine = builder.build();
quteEngine = Engine.builder()
.addDefaults()
.addValueResolver(ReflectionValueResolver::new)
.addLocator(this::locate)
.addParserHook(new Qute.IndexedArgumentsParserHook())
.addResultMapper(new HtmlEscaper(ImmutableList.of("text/html", "text/xml")))
.build();
}
return quteEngine;
}

public boolean isAllowTemplateFromHeader() {
return allowTemplateFromHeader;
}

/**
* Whether to allow to use resource template from header or not (default false).
*
* Enabling this allows to specify dynamic templates via message header. However this can
* be seen as a potential security vulnerability if the header is coming from a malicious user, so use this with care.
*/
public void setAllowTemplateFromHeader(boolean allowTemplateFromHeader) {
this.allowTemplateFromHeader = allowTemplateFromHeader;
}

private Optional<TemplateLocation> locate(String path) {
return Optional.of(new TemplateLocation() {
private URL locatePath(String path) {
Expand All @@ -113,33 +104,24 @@ public Reader read() {
in = locatePath(path).openStream();
}

Reader reader = getEncoding() != null ? new InputStreamReader(in, getEncoding())
: new InputStreamReader(in);
return reader;
return getEncoding() != null ? new InputStreamReader(in, getEncoding()) : new InputStreamReader(in);
} catch (Exception e) {
log.warn("Can not load template " + path + " due to " + e);
log.warn("Cannot load template {}", path, e);
return null;
}
}

@Override
public Optional<Variant> getVariant() {
String contentType = URLConnection.getFileNameMap().getContentTypeFor(path);
if (ObjectHelper.isNotEmpty(contentType)) {
return Optional.of(Variant.forContentType(contentType));
}
return Optional.empty();
}
});
}

/**
* Character encoding of the resource content.
*/
public void setEncoding(String encoding) {
this.encoding = encoding;
}

public String getEncoding() {
return encoding;
}

public QuteEndpoint findOrCreateEndpoint(String uri, String newResourceUri) {
String newUri = uri.replace(getResourceUri(), newResourceUri);
log.debug("Getting endpoint with URI: {}", newUri);
Expand Down Expand Up @@ -194,8 +176,14 @@ protected void onExchange(Exchange exchange) throws Exception {
throw new TemplateException("Unable to parse Qute template from path: " + path);
}
} else {
// This is the first time to parse the content
template = engine.parse(content);
Variant variant = null;
String templateContentType = exchange.getMessage().getHeader(QuteConstants.QUTE_TEMPLATE_CONTENT_TYPE,
String.class);
if (ObjectHelper.isNotEmpty(templateContentType)) {
variant = Variant.forContentType(templateContentType);
}

template = engine.parse(content, variant);
if (template == null) {
throw new TemplateException("Unable to parse Qute template");
}
Expand All @@ -212,4 +200,29 @@ protected void onExchange(Exchange exchange) throws Exception {

exchange.getMessage().setBody(instance.render().trim());
}

/**
* Character encoding of the resource content.
*/
public void setEncoding(String encoding) {
this.encoding = encoding;
}

public String getEncoding() {
return encoding;
}

public boolean isAllowTemplateFromHeader() {
return allowTemplateFromHeader;
}

/**
* Whether to allow to use resource template from header or not (default false).
*
* Enabling this allows to specify dynamic templates via message header. However, this can
* be seen as a potential security vulnerability if the header is coming from a malicious user, so use this with care.
*/
public void setAllowTemplateFromHeader(boolean allowTemplateFromHeader) {
this.allowTemplateFromHeader = allowTemplateFromHeader;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
/*
* 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.qute;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import org.apache.camel.RoutesBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertTrue;

class QuteContentTypeTest extends QuteTestBase {
private static final String MESSAGE = "<h1>Hello World!</h1>";
private static final String MESSAGE_ENCODED = "&lt;h1&gt;Hello World!&lt;/h1&gt;";

@Test
void customTemplateContentType() throws IOException {
Map<String, Object> headers = new HashMap<>();

try (InputStream stream = getClass().getResourceAsStream("hello.html")) {
if (stream == null) {
throw new IllegalArgumentException("hello.html not found");
}

String content = context.getTypeConverter().convertTo(String.class, stream);

headers.put(QuteConstants.QUTE_TEMPLATE, content);
headers.put(QuteConstants.QUTE_TEMPLATE_CONTENT_TYPE, "text/html");

String result = template.requestBodyAndHeaders("direct:start", MESSAGE, headers, String.class);
assertTrue(result.contains(MESSAGE_ENCODED));
}
}

@Override
protected RoutesBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
public void configure() {
from("direct:start")
.to("qute:dynamic?allowTemplateFromHeader=true");
}
};
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,20 @@
## See the License for the specific language governing permissions and
## limitations under the License.
## ---------------------------------------------------------------------------
loggers=org.jboss.logmanager

appender.file.type = File
appender.file.name = file
appender.file.fileName = target/camel-qute-test.log
appender.file.layout.type = PatternLayout
appender.file.layout.pattern = %d [%-15.15t] %-5p %-30.30c{1} - %m%n
appender.out.type = Console
appender.out.name = out
appender.out.layout.type = PatternLayout
appender.out.layout.pattern = %d [%-15.15t] %-5p %-30.30c{1} - %m%n
rootLogger.level = INFO
rootLogger.appenderRef.file.ref = file
logger.level=INFO
logger.handlers=CONSOLE

logger.org.jboss.logmanager.useParentHandlers=true
logger.org.jboss.logmanager.level=INFO

handler.CONSOLE=org.jboss.logmanager.handlers.ConsoleHandler
handler.CONSOLE.formatter=PATTERN
handler.CONSOLE.properties=autoFlush,target
handler.CONSOLE.autoFlush=true
handler.CONSOLE.target=SYSTEM_OUT

formatter.PATTERN=org.jboss.logmanager.formatters.PatternFormatter
formatter.PATTERN.properties=pattern
formatter.PATTERN.pattern=%d{HH:mm:ss,SSS} %-5p [%c] (%t) %s%E%n
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<!--

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.

-->
<html>
<head>
<title>Greetings from Camel Quarkus Qute</title>
</head>
<body>
<code>
{body}
</code>
</body>
</html>
10 changes: 10 additions & 0 deletions extensions/qute/runtime/src/main/doc/usage.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,16 @@ from("direct:start")
.to("qute:dynamic?allowTemplateFromHeader=true");
---------------------------------------------------------------------------------------------

Dynamic template content with specified content type.

[source,java]
---------------------------------------------------------------------------------------------
from("direct:start")
.setHeader(QuteConstants.QUTE_TEMPLATE).constant("<hello>{headers.greeting}</hello>")
.setHeader(QuteConstants.QUTE_TEMPLATE_CONTENT_TYPE).constant("text/html")
.to("qute:dynamic?allowTemplateFromHeader=true");
---------------------------------------------------------------------------------------------

Dynamic template instance.

[source,java]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,17 @@
*/
package org.apache.camel.quarkus.component.qute.it;

import java.util.HashMap;
import java.util.Map;

import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.core.MediaType;
import org.apache.camel.CamelExecutionException;
import org.apache.camel.ProducerTemplate;
Expand Down Expand Up @@ -61,4 +65,18 @@ public String getInvalidTemplatePath() throws Exception {
return e.getCause().getMessage();
}
}

@Path("/template/dynamic")
@POST
@Produces(MediaType.TEXT_PLAIN)
public String getDynamicTemplate(
@QueryParam("contentType") String contentType,
String templateContent) {

Map<String, Object> headers = new HashMap<>();
headers.put(QuteConstants.QUTE_TEMPLATE, templateContent);
headers.put(QuteConstants.QUTE_TEMPLATE_CONTENT_TYPE, contentType);

return producerTemplate.requestBodyAndHeaders("direct:dynamic", "<h1>Hello World!</h1>", headers, String.class);
}
}
Loading