Instruction
stringclasses
1 value
Input
stringlengths
161
22.9k
Output
stringlengths
40
18.2k
apache-camel
I upgraded my Apache Camel+Springboot+Camel-Mail project from 3.20.6 to 4.7 (camel) and 2.5.0 to 3.3.3 (Springboot starter). And the project starts failing to run with below extract of logs.Error: WARN 16272 --- [main] o.s.b.f.xml.XmlBeanDefinitionReader : Ignored XML validation warning org.xml.sax.SAXParseException: schema_reference.4: Failed to read schema document 'http://camel.apache.org/schema/spring/camel-spring.xsd', because 1) could not find the document; 2) the document could not be read; 3) the root element of the document is not xsd:schema.camel-context.xml: <code><?xml version=';1.0'; encoding=';UTF-8';?>; <beans xmlns=';http://www.springframework.org/schema/beans'; xmlns:xsi=';http://www.w3.org/2001/XMLSchema-instance'; xmlns:camel=';http://camel.apache.org/schema/spring'; xsi:schemaLocation=';http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd';>; //some more business logic code here </code> I have already included camel-spring as a dependency. It is already a compile time dependency in the camel-spring-boot-starter. The nearest questions on this doesn't help me either. What am I missing?
Reading the answer you linked, and trying to replicate the dependencies, I noticed that the artifact <code>camel-spring-xml</code> is not included by default through <code>camel-spring-boot-starter</code>, and it's in that artifact that is stored the local copy of the xsd. Try to add this dependency to your pom: <code><dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-spring-xml</artifactId>; <version>;4.7.0</version>; </dependency>; </code>
apache-camel
Apache Camel+Springboot+Email integration. I am trying to render a ftl template as a reply to an email query send to my backend chatbot. However, my .ftl file fails to render with an error as below. I am novice with FTLs. Any suggestions where I am going wrong or how to fix this will be great and very appreciated! <code>reemarker.core.InvalidReferenceException: The following has evaluated to null or missing: ==>; ftlDataMap [in template ';MyFtl.ftl'; at line 61, column 14] ---- Tip: If the failing expression is known to legally refer to something that's sometimes null or missing, either specify a default value like myOptionalVar!myDefault, or use <#if myOptionalVar??>;when-present<#else>;when-missing</#if>;. (These only cover the last step of the expression; to cover the whole expression, use parenthesis: (myOptionalVar.foo)!myDefault, (myOptionalVar.foo)?? FTL stack trace (';~'; means nesting-related): - Failed at: #if ftlDataMap.replyMessages?size [in template ';MyFtl.ftl'; at line 61, column 9] </code> MyFtl.ftl: <code><!DOCTYPE html>; <html>; <head>; <meta charset=';UTF-8';>; <title>;Email Reply</title>; <style>; body { font-family: Arial, sans-serif; line-height: 1.6; margin: 0; padding: 0; background-color: #f4f4f4; } .email-container { width: 100%; max-width: 800px; margin: 20px auto; padding: 20px; border: 1px solid #ddd; border-radius: 5px; background-color: #fff; } .title-ribbon { background-color: #007bff; color: #fff; padding: 10px; border-radius: 5px 5px 0 0; font-size: 20px; font-weight: bold; text-align: center; } .reply-section { margin: 20px 0; } .reply-section p { margin: 10px 0; } .content-html { background-color: #f9f9f9; padding: 10px; border: 1px solid #ddd; border-radius: 5px; word-wrap: break-word; } .original-message { border-top: 1px solid #ddd; padding-top: 20px; } .separator { margin: 20px 0; border-top: 2px dashed #ddd; } </style>; </head>; <body>; <div class=';email-container';>; <div class=';title-ribbon';>; Email Reply </div>; <#if ftlDataMap.replyMessages?size >; 0>; <#list ftlDataMap.replyMessages as reply>; <#if reply.replyMessage?size >; 0>; <#list reply.replyMessage?reverse as item>; <#if item.type == ';AI Reply';>; <p>;<strong>;AI Reply:</strong>; ${item.value}</p>; <#else>; <div class=';content-html';>;${item.value?html}</div>; </#if>; </#list>; <#else>; <p>;No replies found.</p>; </#if>; </#list>; <#else>; <p>;No reply messages found.</p>; </#if>; <div class=';separator';>;</div>; <div class=';original-message';>; <p>;<strong>;-----Original Message-----</strong>;</p>; <#if ftlDataMap.replyMessages?size >; 0>; <#list ftlDataMap.replyMessages[0].originalMessage as item>; <p>;<strong>;${item.label}</strong>; ${item.value}</p>; </#list>; <#else>; <p>;No original message content found.</p>; </#if>; </div>; </div>; </body>; </html>; </code> My Java class: <code>public class CamelIMAPProcessor implements Processor { private static final Logger LOG = LoggerFactory.getLogger(CamelIMAPProcessor.class); @Override public void process(Exchange exchange) throws Exception { Map<String, Object>; ftlDataMap = new LinkedHashMap<>;(); List<ValueExampleObject>; originalMessage = new ArrayList<>;(); Map<String, Object>; reply = new LinkedHashMap<>;(); List<Object>; previousResp = new ArrayList<>;(); List<ValueExampleObject>; chatBotReply = new ArrayList<>;(); String backendResponse = exchange.getIn().getBody(String.class); String originalEmailBody = (String) exchange.getProperty(';originalEmailBody';); String user_message = ';';; String fromAddress = exchange.getProperty(';From';, String.class); String toAddress = exchange.getIn().getHeader(';To';, String.class); String subject = exchange.getIn().getHeader(';Subject';, String.class); String timeStamp = exchange.getIn().getHeader(';Date';, String.class); ObjectMapper objectMapper = new ObjectMapper(); JsonNode rootNode = objectMapper.readTree(backendResponse); JsonNode groupInfo = rootNode.path(';group_info';); JsonNode conversationObjects = groupInfo.path(';conversation_objects';); // Extract ';chat-text'; and ';html-embed'; objects for (JsonNode objectNode : conversationObjects) { String objectType = objectNode.path(';object_type';).asText(); JsonNode objectContent = objectNode.path(';object_content';); if (';chat-text';.equals(objectType)) { LOG.info(';Inside chat-text....';); String myBackendResponseResponse = objectContent.path(';response';).path(';textData';).asText(); user_message = objectContent.path(';query';).asText(); chatBotReply.add(new ValueExampleObject(';AI Reply';, myBackendResponseResponse)); } if (';html-embed';.equals(objectType)) { LOG.info(';Inside html-embed-response....';); String htmlContent = objectContent.path(';content';).asText(); chatBotReply.add(new ValueExampleObject(';Embedded Content';, htmlContent)); } } reply.put(';replyMessage';, chatBotReply); originalMessage.add(new ValueExampleObject(';-----Original Message-----';, ';';)); originalMessage.add(new ValueExampleObject(';From: ';, fromAddress)); originalMessage.add(new ValueExampleObject(';Sent: ';, timeStamp != null ? timeStamp : ';';)); originalMessage.add(new ValueExampleObject(';To: ';, toAddress)); originalMessage.add(new ValueExampleObject(';Subject: ';, subject != null ? subject : ';';)); originalMessage.add(new ValueExampleObject(';User Query:';, user_message)); originalMessage.add(new ValueExampleObject(';';, ';';)); reply.put(';originalMessage';, originalMessage); if (!reply.isEmpty()) { previousResp.add(reply); ftlDataMap.put(';replyMessages';, previousResp); } String output = createHtmlFromFreeMarkerTemplate(ftlDataMap); exchange.getIn().setBody(output); } private String createHtmlFromFreeMarkerTemplate(Map<String, Object>; obj { try { Configuration cfg = new Configuration(Configuration.VERSION_2_3_28); cfg.setClassForTemplateLoading(CamelIMAPProcessor.class, ';/templates';); cfg.setDefaultEncoding(';UTF-8';); cfg.setLocale(Locale.US); cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); Template template = cfg.getTemplate(';MyFtl.ftl';); StringWriter writer = new StringWriter(); template.process(obj, writer); return writer.toString(); } catch (Exception e) { // handle exc } } } </code>
You have this Java local variable, <code>Map<String, Object>; ftlDataMap</code>, but the name of that (<code>ftlDataMap</code>) is transparent to everything, as it's just a local variable, and its name is lost during compilation (apart from debug info). So you can't refer to that in the template with that name. Anyway, you are using that <code>Map</code> as the root of the data-model, so the keys in that <code>Map</code> are the top-level variable names in the template. So instead of <code>ftlDataMap.replyMessages</code> you should just write <code>replyMessages</code>. Also <code><#if ftlDataMap.replyMessages?size >; 0>;</code> is incorrect, a the <code>>;</code> in <code>>; 0</code> will close the tag. Use <code><#if ftlDataMap.replyMessages?size != 0>;</code> instead. (Where you really need to use <code>>;</code> operator, if it's not already inside parentheses for some reason, you have to write <code>gt</code> instead.)
apache-camel
We have a number of Camel route unit tests in JUnit 5 that extend <code>CamelTestSupport</code>. They currently override the <code>isUseAdviceWith</code> method to return <code>true</code>, so that the Camel context is not started automatically and using <code>adviceWith</code> in the tests does not trigger a restart of the context. So far, so good. After upgrading to Camel 4.7.0, the <code>isUseAdviceWith</code> method is deprecated. This appears to be due to work on CAMEL-20785 and CAMEL-20843. These are good changes, FWIW :) From what I understand, the replacement for overriding <code>isUseAdviceWith</code> would be to configure <code>testConfigurationBuilder.withUseAdviceWith(true); </code> in the <code>setupResources</code> method or in a <code>@BeforeEach</code> method. My questions are: (1) do I understand that correctly? And (2) if that is the path forward, is it a mistake that <code>withUseAdviceWith</code> is currently <code>protected</code> and can therefore not be called when setting up the unit test? If the above is not the way forward, I'd love to learn what is, because I have not been able to find it so far in the documentation.
I probably shouldn't have been that restrictive with the <code>TestExecutionConfiguration</code> class. Preventing enabling <code>withAdviceWith</code> is a mistake and I logged it as CAMEL-21078. It will be fixed for Camel 4.8.0.
apache-camel
I'm upgrading an old application from camel 2.22.0 to camel 3.14.10 (Yes, I'm late, I know). This includes updating from camel-test-spring to camel-test-spring-junit5. After a couple of changes to annotations and some other things, I had a compiling build again. But the tests all fail, and the reason is that none of my @Autowired and @MockBean properties actually contain anything. They're all uninitialized. Here's a short example of what the tests look like now and what they looked like before. Now (injection not working): <code>@CamelSpringBootTest @ActiveProfiles(';test';) @TestPropertySource(properties = [';ftp.enabled=true';]) @SpringBootTest(webEnvironment = RANDOM_PORT) @DirtiesContext class ImageGatewayApplicationTest { @MockBean private lateinit var authenticationService: AuthenticationService @MockBean private lateinit var panoramaService: PanoramaService @MockBean private lateinit var bmetryService: BmetryEventService @Autowired private lateinit var template: ProducerTemplate @Autowired private lateinit var restTemplate: TestRestTemplate @EndpointInject(uri = ';mock:new-image';) private lateinit var newImageMock: MockEndpoint @Test fun `upload with ftp`() { val resource = ClassPathResource(TEST_PNG) val tempFile = FileHelper.createTempFile(resource) template.sendBodyAndHeader(TEST_FTP, tempFile, FILE_NAME, TEST_PNG) // <- template not initialised // verify mock verify<AuthenticationService>;(authenticationService).checkCredentials(TEST_USER, TEST_PW) // clean up tempFile.delete() } </code> Here are the annotations as they were before the update. Nothing except the annotations changed (injection worked perfectly fine): <code>@RunWith(CamelSpringRunner::class) @ActiveProfiles(';test';) @TestPropertySource(properties = [';ftp.enabled=true';]) @SpringBootTest(webEnvironment = RANDOM_PORT) @DirtiesContext class ImageGatewayApplicationTest { } </code> The precise error I'm getting is this: <code>kotlin.UninitializedPropertyAccessException: lateinit property restTemplate has not been initialized </code> Note that it is not complaining about not finding beans or not being able to instantiate them or any of the stuff one might expect. It's as though the annotations are simply ignored. When I pause the code and look at the class, none of them are initialised. Nothing's being injected. I'm halfways certain that I'm missing some annotation, but I can't find it. I have tried adding @EnableAutoConfiguration, @ContextConfiguration and @UseAdviceWith (as that is in fact used in some tests), all with no result. Additional data: Turns out it's running on JUnit4 Prompted by sidgates comment, I took a look at the complete stacktrace. I wasn't even aware there's more of it, Intellij for some reason saw fit to hide it by default. This revealed something rather surprising, and something that probably explains my predicament: The whole thing is still running on JUnit4! <code>kotlin.UninitializedPropertyAccessException: lateinit property restTemplate has not been initialized at webcam.yellow.gateway.ImageGatewayApplicationTest.upload with http(ImageGatewayApplicationTest.kt:82) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:78) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:567) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306) at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63) at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329) at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293) at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306) at org.junit.runners.ParentRunner.run(ParentRunner.java:413) at org.junit.runner.JUnitCore.run(JUnitCore.java:137) at org.junit.runner.JUnitCore.run(JUnitCore.java:115) at org.junit.vintage.engine.execution.RunnerExecutor.execute(RunnerExecutor.java:42) at org.junit.vintage.engine.VintageTestEngine.executeAllChildren(VintageTestEngine.java:80) at org.junit.vintage.engine.VintageTestEngine.execute(VintageTestEngine.java:72) at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:107) at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88) at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54) at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67) at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52) at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:114) at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:86) at org.junit.platform.launcher.core.DefaultLauncherSession$DelegatingLauncher.execute(DefaultLauncherSession.java:86) at org.junit.platform.launcher.core.SessionPerRequestLauncher.execute(SessionPerRequestLauncher.java:53) at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:57) at com.intellij.rt.junit.IdeaTestRunner$Repeater$1.execute(IdeaTestRunner.java:38) at com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11) at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35) at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:232) at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:55) </code> That's a step in the right direction, but try as I might, I can't get it to run with Junit5. Honestly I had thought it already did, as the spring-boot version (2.7.18) does support it (spring-boot 2.2+). It turns out that the old kotlin-test dependency in there forced junit4 to run. Once I replaced it with a newer kotest-junit5-runner dependency the tests finally run. They don't check out yet, though, there's still plenty of issues with camel it seems, but it looks like this is another kind of animal...
It turns out that while I was assuming that the tests were running on JUnit5 due to the spring-boot version, they were in fact still running on junit-vintage. Responsible for that was another outdated dependency on kotlintest. Once I replaced that with kotest-runner-junit5-jvm, the problem was gone. Still lots of issues left with the camel tests, but that's another problem.
apache-camel
i have a route camel 4.0.0 with toD(query_jpa) but when running a field have XML string, with pre:timestamp2024-07-13T11:06:25+02:00</pre:timestamp>;, the '+' desaspear on database.... and replacing by SPACE caracter. OK i know than toD use the URI HTTP , but i want keep all xml to insert on column database. i have try into query a RAW(${header.xmlresponse})INSERT INTO xxxx SET x,y,z values (x,y,RAW(${header.xmlResponse})but the same thing... a lose the '+' caracter in db... how can insert xml without lose something. Thanks you.
Assuming you have a route like this: <code>... .toD(';sql:INSERT INTO xxxx SET x,y,z values (x,y,RAW(${header.xmlResponse})';) ... </code> you can try to use an external <code>sql</code> file like: resources/sql/insert.sql <code>INSERT INTO xxxx SET x,y,z values (x,y, :#xmlResponse) </code> and then use it like this in your route: <code>... .toD(';sql:classpath:sql/insert.sql';) ... </code> By using an external file instead of the <code>uri</code> notation, every character should be preserved.
apache-camel
I am using this POM and i want to add the correct dependencies to read from a linerized string with Camel (with annotations like @FixedLengthRecord) and convert it to a JSON. Does anyone know the correct dependencies for this Spring boot version? I tried to find them from org.apache.camel.springboot group but they are not available. <code><?xml version=';1.0'; encoding=';UTF-8';?>; <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 https://maven.apache.org/xsd/maven-4.0.0.xsd';>; <modelVersion>;4.0.0</modelVersion>; <parent>; <groupId>;org.springframework.boot</groupId>; <artifactId>;spring-boot-starter-parent</artifactId>; <version>;3.3.0</version>; <relativePath/>; <!-- lookup parent from repository -->; </parent>; <groupId>;com.tsdevelopment</groupId>; <artifactId>;spring-boot-camel</artifactId>; <version>;0.0.1-SNAPSHOT</version>; <name>;spring-boot-camel</name>; <description>;Demo project for Spring Boot</description>; <url/>; <licenses>; <license/>; </licenses>; <developers>; <developer/>; </developers>; <scm>; <connection/>; <developerConnection/>; <tag/>; <url/>; </scm>; <properties>; <java.version>;17</java.version>; </properties>; <dependencies>; <dependency>; <groupId>;org.springframework.boot</groupId>; <artifactId>;spring-boot-starter</artifactId>; </dependency>; <dependency>; <groupId>;org.springframework.boot</groupId>; <artifactId>;spring-boot-starter-test</artifactId>; <scope>;test</scope>; </dependency>; <dependency>; <groupId>;org.springframework.boot</groupId>; <artifactId>;spring-boot-starter-web</artifactId>; </dependency>; <dependency>; <groupId>;org.apache.camel.springboot</groupId>; <artifactId>;camel-core-starter</artifactId>; <version>;4.6.0</version>; </dependency>; <dependency>; <groupId>;org.apache.camel.springboot</groupId>; <artifactId>;camel-spring-boot</artifactId>; <version>;4.6.0</version>; </dependency>; <dependency>; <groupId>;org.apache.camel.springboot</groupId>; <artifactId>;camel-spring-boot-starter</artifactId>; <version>;4.6.0</version>; </dependency>; <dependency>; <groupId>;org.apache.camel.springboot</groupId>; <artifactId>;camel-spring-boot-xml-starter</artifactId>; <version>;4.6.0</version>; </dependency>; <dependency>; <groupId>;org.apache.camel.springboot</groupId>; <artifactId>;camel-jsonpath-starter</artifactId>; <version>;4.6.0</version>; </dependency>; </dependencies>; <build>; <plugins>; <plugin>; <groupId>;org.springframework.boot</groupId>; <artifactId>;spring-boot-maven-plugin</artifactId>; </plugin>; </plugins>; </build>;</project>;</code>
@FixedLengthRecord is part of camel-bindy. For spring boot 3.3.x it looks like you should add the following dependency: <code><dependency>; <groupId>;org.apache.camel.springboot</groupId>; <artifactId>;camel-bindy-starter</artifactId>; <version>;4.6.0</version>; </dependency>; </code>
apache-camel
I am trying to update from camel 3 to 4, but i have an issue with the following line, <code>camelContext.adapt(ExtendedCamelContext.class).setUnitOfWorkFactory(new CustomUnitOfWorkFactory()); </code> I found already this post: Apache Camel adapt() method removed in version 4 So with the help of that I transformed it into: <code> ExtendedCamelContext context = camelContext .getCamelContextExtension() .getContextPlugin(ExtendedCamelContext.class); </code> but on the extended camel context the setUnitOfWorkFactory doesnt seem to be available anymore. Does someone know how to set this in camel 4.6
In the end the solution was quite simple. if you dont use spring boot <code>camelContext.getRegistry().bind(';customUnitOfWorkFactory';, new CustomUnitOfWorkFactory()); </code> if you use spring boot make it a component <code>@Component public class CustomUnitOfWorkFactory implements UnitOfWorkFactory { </code>
apache-camel
I tried to add Apache Camel support in an Eclipse RCP application. With the new Eclipse, I can also add maven repositories in the target platform file, so that is what I did. My target platform contains: <code><dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-core</artifactId>; <version>;4.6.0</version>; <type>;jar</type>; </dependency>; </code> I also checked the includeDependency field to include the required dependencies. All is well so far, I get all 20 or so plugins for the camel projects auto-generated. I add them in my manifest files, compile is working, everything is fine. Except when I try to start camel, I get a runtime exception saying <code>No language for 'simple' found</code>(something similar, I don't have the exact stackstrace now). The problem is this one:The <code>simple</code> language is in the core-languages module The <code>core-engine</code> module tries to load the <code>simple</code> language(from the <code>core-languages</code>) into the camel context <code>core-engine</code> and <code>core-languages</code> are 2 distinct plugins, thus the Equinox classloader will not allow <code>core-engine</code> to see any files in the META-INF folder inside the <code>core-languages</code> moduleI can only think of 2 possible solutions for this:Include Apache Camel as a jar dependency. The problem is I don't see any downloadable jar for the core Apache Camel in Maven. I will have to clone the repositories and build my own jar. Build a Maven project that takes all Camel core dependencies and outputs a single rcp plugin containing the dependencies. For this one I don't need to clone the Camel repositories, but I'm not 100% sure I can achieve this.For both approaches I think is quite cumbersome to add another Camel component afterwards, because it will probably involve modifying the custom project I created to include the new component(assuming <code>core-engine</code> needs to access it to load it into the context). Also I don't see how I can separate the Camel core from the optional components. Any ideas to make Camel work with Eclipse RCP? You can find my target platform here: https://github.com/grozadanut/ro.linic.ui/blob/main/target-platform/target-platform.target And the RCP product is here: https://github.com/grozadanut/ro.linic.ui/blob/main/ro.linic.ui.product/linic.product
I ended up adding all Camel core jars to my ro.linic.ui.camel.core plugin. And to be able to use camel in other plugins I add this ro.linic.ui.camel.core plugin as a dependency and I exported the required packages to be able to use camel code in my other plugins. I did use Maven to automate downloading the jars, so I don't have to download each one individually. The pom I used: <code><project>; <modelVersion>;4.0.0</modelVersion>;<parent>; <relativePath>;../pom.xml</relativePath>; <groupId>;ro.linic.tycho</groupId>; <artifactId>;releng</artifactId>; <version>;1.0.0-SNAPSHOT</version>; </parent>;<groupId>;ro.linic.ui</groupId>; <artifactId>;ro.linic.ui.camel.core</artifactId>; <version>;0.0.1</version>; <packaging>;eclipse-plugin</packaging>;<dependencyManagement>; <dependencies>; <!-- Camel BOM -->; <dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-bom</artifactId>; <version>;4.6.0</version>; <scope>;import</scope>; <type>;pom</type>; </dependency>; </dependencies>; </dependencyManagement>;<dependencies>; <dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-core</artifactId>; </dependency>;</dependencies>;<build>; <plugins>; <plugin>; <groupId>;org.apache.maven.plugins</groupId>; <artifactId>;maven-dependency-plugin</artifactId>; <executions>; <execution>; <id>;copy-dependencies</id>; <phase>;prepare-package</phase>; <goals>; <goal>;copy-dependencies</goal>; </goals>; <configuration>; <outputDirectory>;${project.build.directory}/${project.build.finalName}.lib </outputDirectory>; </configuration>; </execution>; </executions>; </plugin>; </plugins>; </build>; </code> Then I took all camel jars from the generated output folder and added them to the manifest, in the Runtime ->; Classpath section.
apache-camel
I'm using Apache Camel OPC UA client component to test the data change filter with Deadband Value to acquire the single tag value from Industrial Gateway OPCUA Server. Current Spring boot and camel-milo component version: <code>implementation group: 'org.apache.camel', name: 'camel-milo', version: '3.22.2' implementation group: 'org.apache.camel.springboot', name: 'camel-spring-boot-starter', version: '4.4.2' </code> Reading Apache Camel OPC UA client documentation to apply deadband filter feature, if I understood well, I have to use the following properties key:dataChangeFilterTrigger = StatusValue (I'm using statusValue for checking the value ) dataChangeFilterDeadbandValue = xx (it depends on the deadband that I want to apply on the tag)My performed tests is telling me that the deadband filter is not working as I showed in the following tests: Base route with placeholder values replaced on the test id performed : <code>from(';milo-client:opc.tcp://127.0.0.1:49310? keyStoreUrl=file:C:\\Temp\\application\\certificate\\clientkeystore.jks &;keyPassword=123456 &;keyStorePassword=123456 &;applicationUri=urn:8409:test:camelopcua &;applicationName=camelopcua&;node=RAW(ns=2;s=Channel2 SIMUL.SIM_1.BNAp1.18VGG1_BP) &;dataChangeFilterDeadbandValue=@placeholderTest_x@ &;dataChangeFilterTrigger=@placeholderTest_x@ &;monitorFilterType=dataChangeFilter';) .log(';**** ${body}';) .routeId(';routeDeadband';); </code> Test_1) dataChangeFilterTrigger = StatusValue dataChangeFilterDeadbandValue = 0.001 <code>2024-07-04 06:36:51,852 milo-shared-thread-pool-1 INFO - [routeDeadband] - **** DataValue{value=Variant{value=3.0}, status=StatusCode{name=Good, value=0x00000000, quality=good}, sourceTime=DateTime{utcTime=133645486117072252, javaDate=Thu Jul 04 06:36:51 UTC 2024}, serverTime=DateTime{utcTime=133645486117072252, javaDate=Thu Jul 04 06:36:51 UTC 2024}}2024-07-04 06:36:52,853 milo-shared-thread-pool-1 INFO - [routeDeadband] - **** DataValue{value=Variant{value=2.9666667}, status=StatusCode{name=Good, value=0x00000000, quality=good}, sourceTime=DateTime{utcTime=133645486126951326, javaDate=Thu Jul 04 06:36:52 UTC 2024}, serverTime=DateTime{utcTime=133645486126951326, javaDate=Thu Jul 04 06:36:52 UTC 2024}}2024-07-04 06:36:53,849 milo-shared-thread-pool-1 INFO - [routeDeadband] - **** DataValue{value=Variant{value=2.925}, status=StatusCode{name=Good, value=0x00000000, quality=good}, sourceTime=DateTime{utcTime=133645486136802804, javaDate=Thu Jul 04 06:36:53 UTC 2024}, serverTime=DateTime{utcTime=133645486136802804, javaDate=Thu Jul 04 06:36:53 UTC 2024}}2024-07-04 06:36:54,844 milo-shared-thread-pool-2 INFO - [routeDeadband] - **** DataValue{value=Variant{value=3.05}, status=StatusCode{name=Good, value=0x00000000, quality=good}, sourceTime=DateTime{utcTime=133645486146648052, javaDate=Thu Jul 04 06:36:54 UTC 2024}, serverTime=DateTime{utcTime=133645486146648052, javaDate=Thu Jul 04 06:36:54 UTC 2024}}2024-07-04 06:36:55,854 milo-shared-thread-pool-1 INFO - [routeDeadband] - **** DataValue{value=Variant{value=2.942857}, status=StatusCode{name=Good, value=0x00000000, quality=good}, sourceTime=DateTime{utcTime=133645486156406461, javaDate=Thu Jul 04 06:36:55 UTC 2024}, serverTime=DateTime{utcTime=133645486156406461, javaDate=Thu Jul 04 06:36:55 UTC 2024}}2024-07-04 06:36:56,849 milo-shared-thread-pool-1 INFO - [routeDeadband] - **** DataValue{value=Variant{value=2.9666667}, status=StatusCode{name=Good, value=0x00000000, quality=good}, sourceTime=DateTime{utcTime=133645486166262211, javaDate=Thu Jul 04 06:36:56 UTC 2024}, serverTime=DateTime{utcTime=133645486166262211, javaDate=Thu Jul 04 06:36:56 UTC 2024}}2024-07-04 06:36:57,851 milo-shared-thread-pool-1 INFO - [routeDeadband] - **** DataValue{value=Variant{value=3.1333334}, status=StatusCode{name=Good, value=0x00000000, quality=good}, sourceTime=DateTime{utcTime=133645486171756029, javaDate=Thu Jul 04 06:36:57 UTC 2024}, serverTime=DateTime{utcTime=133645486171756029, javaDate=Thu Jul 04 06:36:57 UTC 2024}}2024-07-04 06:36:58,844 milo-shared-thread-pool-1 INFO - [routeDeadband] - **** DataValue{value=Variant{value=2.8}, status=StatusCode{name=Good, value=0x00000000, quality=good}, sourceTime=DateTime{utcTime=133645486187076878, javaDate=Thu Jul 04 06:36:58 UTC 2024}, serverTime=DateTime{utcTime=133645486187076878, javaDate=Thu Jul 04 06:36:58 UTC 2024}}2024-07-04 06:36:59,849 milo-shared-thread-pool-3 INFO - [routeDeadband] - **** DataValue{value=Variant{value=3.1333334}, status=StatusCode{name=Good, value=0x00000000, quality=good}, sourceTime=DateTime{utcTime=133645486196926821, javaDate=Thu Jul 04 06:36:59 UTC 2024}, serverTime=DateTime{utcTime=133645486196926821, javaDate=Thu Jul 04 06:36:59 UTC 2024}}2024-07-04 06:37:00,851 milo-shared-thread-pool-3 INFO - [routeDeadband] - **** DataValue{value=Variant{value=3.1333334}, status=StatusCode{name=Good, value=0x00000000, quality=good}, sourceTime=DateTime{utcTime=133645486206806697, javaDate=Thu Jul 04 06:37:00 UTC 2024}, serverTime=DateTime{utcTime=133645486206806697, javaDate=Thu Jul 04 06:37:00 UTC 2024}}2024-07-04 06:37:01,846 milo-shared-thread-pool-3 INFO - [routeDeadband] - **** DataValue{value=Variant{value=3.05}, status=StatusCode{name=Good, value=0x00000000, quality=good}, sourceTime=DateTime{utcTime=133645486216593861, javaDate=Thu Jul 04 06:37:01 UTC 2024}, serverTime=DateTime{utcTime=133645486216593861, javaDate=Thu Jul 04 06:37:01 UTC 2024}} 2024-07-04 06:37:02,847 milo-shared-thread-pool-3 INFO - [routeDeadband] - **** DataValue{value=Variant{value=3.2}, status=StatusCode{name=Good, value=0x00000000, quality=good}, sourceTime=DateTime{utcTime=133645486222116969, javaDate=Thu Jul 04 06:37:02 UTC 2024}, serverTime=DateTime{utcTime=133645486222116969, javaDate=Thu Jul 04 06:37:02 UTC 2024}} 2024-07-04 06:37:03,849 milo-shared-thread-pool-3 INFO - [routeDeadband] - **** DataValue{value=Variant{value=3.2}, status=StatusCode{name=Good, value=0x00000000, quality=good}, sourceTime=DateTime{utcTime=133645486236275381, javaDate=Thu Jul 04 06:37:03 UTC 2024}, serverTime=DateTime{utcTime=133645486236275381, javaDate=Thu Jul 04 06:37:03 UTC 2024}} 2024-07-04 06:37:04,849 milo-shared-thread-pool-3 INFO - [routeDeadband] - **** DataValue{value=Variant{value=3.0}, status=StatusCode{name=Good, value=0x00000000, quality=good}, sourceTime=DateTime{utcTime=133645486247209000, javaDate=Thu Jul 04 06:37:04 UTC 2024}, serverTime=DateTime{utcTime=133645486247209000, javaDate=Thu Jul 04 06:37:04 UTC 2024}} 2024-07-04 06:37:05,853 milo-shared-thread-pool-3 INFO - [routeDeadband] - **** DataValue{value=Variant{value=3.2}, status=StatusCode{name=Good, value=0x00000000, quality=good}, sourceTime=DateTime{utcTime=133645486257072613, javaDate=Thu Jul 04 06:37:05 UTC 2024}, serverTime=DateTime{utcTime=133645486257072613, javaDate=Thu Jul 04 06:37:05 UTC 2024}} 2024-07-04 06:37:06,851 milo-shared-thread-pool-3 INFO - [routeDeadband] - **** DataValue{value=Variant{value=2.925}, status=StatusCode{name=Good, value=0x00000000, quality=good}, sourceTime=DateTime{utcTime=133645486266939791, javaDate=Thu Jul 04 06:37:06 UTC 2024}, serverTime=DateTime{utcTime=133645486266939791, javaDate=Thu Jul 04 06:37:06 UTC 2024}} 2024-07-04 06:37:07,848 milo-shared-thread-pool-3 INFO - [routeDeadband] - **** DataValue{value=Variant{value=3.2}, status=StatusCode{name=Good, value=0x00000000, quality=good}, sourceTime=DateTime{utcTime=133645486276787705, javaDate=Thu Jul 04 06:37:07 UTC 2024}, serverTime=DateTime{utcTime=133645486276787705, javaDate=Thu Jul 04 06:37:07 UTC 2024}} 2024-07-04 06:37:08,846 milo-shared-thread-pool-3 INFO - [routeDeadband] - **** DataValue{value=Variant{value=3.2}, status=StatusCode{name=Good, value=0x00000000, quality=good}, sourceTime=DateTime{utcTime=133645486286565108, javaDate=Thu Jul 04 06:37:08 UTC 2024}, serverTime=DateTime{utcTime=133645486286565108, javaDate=Thu Jul 04 06:37:08 UTC 2024}} </code> Test_2) dataChangeFilterTrigger = StatusValue dataChangeFilterDeadbandValue = 0.01 <code>2024-07-04 06:34:09,570 milo-shared-thread-pool-2 INFO - [routeDeadband] - **** DataValue{value=Variant{value=2.925}, status=StatusCode{name=Good, value=0x00000000, quality=good}, sourceTime=DateTime{utcTime=133645484491791570, javaDate=Thu Jul 04 06:34:09 UTC 2024}, serverTime=DateTime{utcTime=133645484491791570, javaDate=Thu Jul 04 06:34:09 UTC 2024}} 2024-07-04 06:34:10,573 milo-shared-thread-pool-2 INFO - [routeDeadband] - **** DataValue{value=Variant{value=3.2}, status=StatusCode{name=Good, value=0x00000000, quality=good}, sourceTime=DateTime{utcTime=133645484501646388, javaDate=Thu Jul 04 06:34:10 UTC 2024}, serverTime=DateTime{utcTime=133645484501646388, javaDate=Thu Jul 04 06:34:10 UTC 2024}} 2024-07-04 06:34:11,569 milo-shared-thread-pool-2 INFO - [routeDeadband] - **** DataValue{value=Variant{value=2.925}, status=StatusCode{name=Good, value=0x00000000, quality=good}, sourceTime=DateTime{utcTime=133645484511409944, javaDate=Thu Jul 04 06:34:11 UTC 2024}, serverTime=DateTime{utcTime=133645484511409944, javaDate=Thu Jul 04 06:34:11 UTC 2024}} 2024-07-04 06:34:12,568 milo-shared-thread-pool-1 INFO - [routeDeadband] - **** DataValue{value=Variant{value=2.8}, status=StatusCode{name=Good, value=0x00000000, quality=good}, sourceTime=DateTime{utcTime=133645484521286485, javaDate=Thu Jul 04 06:34:12 UTC 2024}, serverTime=DateTime{utcTime=133645484521286485, javaDate=Thu Jul 04 06:34:12 UTC 2024}} 2024-07-04 06:34:13,570 milo-shared-thread-pool-0 INFO - [routeDeadband] - **** DataValue{value=Variant{value=3.0}, status=StatusCode{name=Good, value=0x00000000, quality=good}, sourceTime=DateTime{utcTime=133645484531171024, javaDate=Thu Jul 04 06:34:13 UTC 2024}, serverTime=DateTime{utcTime=133645484531171024, javaDate=Thu Jul 04 06:34:13 UTC 2024}} 2024-07-04 06:34:14,567 milo-shared-thread-pool-0 INFO - [routeDeadband] - **** DataValue{value=Variant{value=2.8}, status=StatusCode{name=Good, value=0x00000000, quality=good}, sourceTime=DateTime{utcTime=133645484541032215, javaDate=Thu Jul 04 06:34:14 UTC 2024}, serverTime=DateTime{utcTime=133645484541032215, javaDate=Thu Jul 04 06:34:14 UTC 2024}} 2024-07-04 06:34:15,566 milo-shared-thread-pool-0 INFO - [routeDeadband] - **** DataValue{value=Variant{value=3.0}, status=StatusCode{name=Good, value=0x00000000, quality=good}, sourceTime=DateTime{utcTime=133645484550859004, javaDate=Thu Jul 04 06:34:15 UTC 2024}, serverTime=DateTime{utcTime=133645484550859004, javaDate=Thu Jul 04 06:34:15 UTC 2024}} 2024-07-04 06:34:16,570 milo-shared-thread-pool-0 INFO - [routeDeadband] - **** DataValue{value=Variant{value=3.2}, status=StatusCode{name=Good, value=0x00000000, quality=good}, sourceTime=DateTime{utcTime=133645484561764724, javaDate=Thu Jul 04 06:34:16 UTC 2024}, serverTime=DateTime{utcTime=133645484561764724, javaDate=Thu Jul 04 06:34:16 UTC 2024}} 2024-07-04 06:34:17,571 milo-shared-thread-pool-0 INFO - [routeDeadband] - **** DataValue{value=Variant{value=2.8}, status=StatusCode{name=Good, value=0x00000000, quality=good}, sourceTime=DateTime{utcTime=133645484571580985, javaDate=Thu Jul 04 06:34:17 UTC 2024}, serverTime=DateTime{utcTime=133645484571580985, javaDate=Thu Jul 04 06:34:17 UTC 2024}} 2024-07-04 06:34:18,573 milo-shared-thread-pool-2 INFO - [routeDeadband] - **** DataValue{value=Variant{value=2.9666667}, status=StatusCode{name=Good, value=0x00000000, quality=good}, sourceTime=DateTime{utcTime=133645484581482454, javaDate=Thu Jul 04 06:34:18 UTC 2024}, serverTime=DateTime{utcTime=133645484581482454, javaDate=Thu Jul 04 06:34:18 UTC 2024}} </code> Test_3) dataChangeFilterTrigger = StatusValue dataChangeFilterDeadbandValue = 0.1 <code> 2024-07-04 06:38:56,790 milo-shared-thread-pool-1 INFO - [routeDeadband] - **** DataValue{value=Variant{value=3.0}, status=StatusCode{name=Good, value=0x00000000, quality=good}, sourceTime=DateTime{utcTime=133645487367572683, javaDate=Thu Jul 04 06:38:56 UTC 2024}, serverTime=DateTime{utcTime=133645487367572683, javaDate=Thu Jul 04 06:38:56 UTC 2024}} 2024-07-04 06:38:57,787 milo-shared-thread-pool-1 INFO - [routeDeadband] - **** DataValue{value=Variant{value=3.2}, status=StatusCode{name=Good, value=0x00000000, quality=good}, sourceTime=DateTime{utcTime=133645487373034158, javaDate=Thu Jul 04 06:38:57 UTC 2024}, serverTime=DateTime{utcTime=133645487373034158, javaDate=Thu Jul 04 06:38:57 UTC 2024}} 2024-07-04 06:38:58,785 milo-shared-thread-pool-1 INFO - [routeDeadband] - **** DataValue{value=Variant{value=3.2}, status=StatusCode{name=Good, value=0x00000000, quality=good}, sourceTime=DateTime{utcTime=133645487387204906, javaDate=Thu Jul 04 06:38:58 UTC 2024}, serverTime=DateTime{utcTime=133645487387204906, javaDate=Thu Jul 04 06:38:58 UTC 2024}} 2024-07-04 06:38:59,790 milo-shared-thread-pool-3 INFO - [routeDeadband] - **** DataValue{value=Variant{value=3.1333334}, status=StatusCode{name=Good, value=0x00000000, quality=good}, sourceTime=DateTime{utcTime=133645487397079011, javaDate=Thu Jul 04 06:38:59 UTC 2024}, serverTime=DateTime{utcTime=133645487397079011, javaDate=Thu Jul 04 06:38:59 UTC 2024}} 2024-07-04 06:39:00,789 milo-shared-thread-pool-0 INFO - [routeDeadband] - **** DataValue{value=Variant{value=3.0}, status=StatusCode{name=Good, value=0x00000000, quality=good}, sourceTime=DateTime{utcTime=133645487402524037, javaDate=Thu Jul 04 06:39:00 UTC 2024}, serverTime=DateTime{utcTime=133645487402524037, javaDate=Thu Jul 04 06:39:00 UTC 2024}} 2024-07-04 06:39:01,783 milo-shared-thread-pool-0 INFO - [routeDeadband] - **** DataValue{value=Variant{value=2.925}, status=StatusCode{name=Good, value=0x00000000, quality=good}, sourceTime=DateTime{utcTime=133645487412409085, javaDate=Thu Jul 04 06:39:01 UTC 2024}, serverTime=DateTime{utcTime=133645487412409085, javaDate=Thu Jul 04 06:39:01 UTC 2024}} 2024-07-04 06:39:02,785 milo-shared-thread-pool-0 INFO - [routeDeadband] - **** DataValue{value=Variant{value=3.05}, status=StatusCode{name=Good, value=0x00000000, quality=good}, sourceTime=DateTime{utcTime=133645487427749867, javaDate=Thu Jul 04 06:39:02 UTC 2024}, serverTime=DateTime{utcTime=133645487427749867, javaDate=Thu Jul 04 06:39:02 UTC 2024}} 2024-07-04 06:39:03,787 milo-shared-thread-pool-0 INFO - [routeDeadband] - **** DataValue{value=Variant{value=3.05}, status=StatusCode{name=Good, value=0x00000000, quality=good}, sourceTime=DateTime{utcTime=133645487437559370, javaDate=Thu Jul 04 06:39:03 UTC 2024}, serverTime=DateTime{utcTime=133645487437559370, javaDate=Thu Jul 04 06:39:03 UTC 2024}} 2024-07-04 06:39:04,791 milo-shared-thread-pool-0 INFO - [routeDeadband] - **** DataValue{value=Variant{value=2.8}, status=StatusCode{name=Good, value=0x00000000, quality=good}, sourceTime=DateTime{utcTime=133645487447390847, javaDate=Thu Jul 04 06:39:04 UTC 2024}, serverTime=DateTime{utcTime=133645487447390847, javaDate=Thu Jul 04 06:39:04 UTC 2024}} 2024-07-04 06:39:05,782 milo-shared-thread-pool-0 INFO - [routeDeadband] - **** DataValue{value=Variant{value=3.1333334}, status=StatusCode{name=Good, value=0x00000000, quality=good}, sourceTime=DateTime{utcTime=133645487457187133, javaDate=Thu Jul 04 06:39:05 UTC 2024}, serverTime=DateTime{utcTime=133645487457187133, javaDate=Thu Jul 04 06:39:05 UTC 2024}} 2024-07-04 06:39:06,789 milo-shared-thread-pool-0 INFO - [routeDeadband] - **** DataValue{value=Variant{value=3.05}, status=StatusCode{name=Good, value=0x00000000, quality=good}, sourceTime=DateTime{utcTime=133645487467051678, javaDate=Thu Jul 04 06:39:06 UTC 2024}, serverTime=DateTime{utcTime=133645487467051678, javaDate=Thu Jul 04 06:39:06 UTC 2024}} 2024-07-04 06:39:07,783 milo-shared-thread-pool-0 INFO - [routeDeadband] - **** DataValue{value=Variant{value=3.2}, status=StatusCode{name=Good, value=0x00000000, quality=good}, sourceTime=DateTime{utcTime=133645487472586697, javaDate=Thu Jul 04 06:39:07 UTC 2024}, serverTime=DateTime{utcTime=133645487472586697, javaDate=Thu Jul 04 06:39:07 UTC 2024}} </code> Test_4) dataChangeFilterTrigger = StatusValue dataChangeFilterDeadbandValue = 1 <code>2024-07-04 06:40:24,583 milo-shared-thread-pool-1 INFO - [routeDeadband] - **** DataValue{value=Variant{value=2.8}, status=StatusCode{name=Good, value=0x00000000, quality=good}, sourceTime=DateTime{utcTime=133645488242348177, javaDate=Thu Jul 04 06:40:24 UTC 2024}, serverTime=DateTime{utcTime=133645488242348177, javaDate=Thu Jul 04 06:40:24 UTC 2024}} 2024-07-04 06:40:25,584 milo-shared-thread-pool-1 INFO - [routeDeadband] - **** DataValue{value=Variant{value=3.05}, status=StatusCode{name=Good, value=0x00000000, quality=good}, sourceTime=DateTime{utcTime=133645488252284656, javaDate=Thu Jul 04 06:40:25 UTC 2024}, serverTime=DateTime{utcTime=133645488252284656, javaDate=Thu Jul 04 06:40:25 UTC 2024}} 2024-07-04 06:40:26,584 milo-shared-thread-pool-1 INFO - [routeDeadband] - **** DataValue{value=Variant{value=2.8}, status=StatusCode{name=Good, value=0x00000000, quality=good}, sourceTime=DateTime{utcTime=133645488257747604, javaDate=Thu Jul 04 06:40:25 UTC 2024}, serverTime=DateTime{utcTime=133645488257747604, javaDate=Thu Jul 04 06:40:25 UTC 2024}} 2024-07-04 06:40:27,586 milo-shared-thread-pool-1 INFO - [routeDeadband] - **** DataValue{value=Variant{value=3.1333334}, status=StatusCode{name=Good, value=0x00000000, quality=good}, sourceTime=DateTime{utcTime=133645488273022197, javaDate=Thu Jul 04 06:40:27 UTC 2024}, serverTime=DateTime{utcTime=133645488273022197, javaDate=Thu Jul 04 06:40:27 UTC 2024}} 2024-07-04 06:40:28,584 milo-shared-thread-pool-1 INFO - [routeDeadband] - **** DataValue{value=Variant{value=2.925}, status=StatusCode{name=Good, value=0x00000000, quality=good}, sourceTime=DateTime{utcTime=133645488282885735, javaDate=Thu Jul 04 06:40:28 UTC 2024}, serverTime=DateTime{utcTime=133645488282885735, javaDate=Thu Jul 04 06:40:28 UTC 2024}} 2024-07-04 06:40:29,583 milo-shared-thread-pool-1 INFO - [routeDeadband] - **** DataValue{value=Variant{value=3.0}, status=StatusCode{name=Good, value=0x00000000, quality=good}, sourceTime=DateTime{utcTime=133645488292682931, javaDate=Thu Jul 04 06:40:29 UTC 2024}, serverTime=DateTime{utcTime=133645488292682931, javaDate=Thu Jul 04 06:40:29 UTC 2024}} 2024-07-04 06:40:30,588 milo-shared-thread-pool-1 INFO - [routeDeadband] - **** DataValue{value=Variant{value=2.8}, status=StatusCode{name=Good, value=0x00000000, quality=good}, sourceTime=DateTime{utcTime=133645488302517455, javaDate=Thu Jul 04 06:40:30 UTC 2024}, serverTime=DateTime{utcTime=133645488302517455, javaDate=Thu Jul 04 06:40:30 UTC 2024}} 2024-07-04 06:40:31,587 milo-shared-thread-pool-1 INFO - [routeDeadband] - **** DataValue{value=Variant{value=2.9666667}, status=StatusCode{name=Good, value=0x00000000, quality=good}, sourceTime=DateTime{utcTime=133645488312376079, javaDate=Thu Jul 04 06:40:31 UTC 2024}, serverTime=DateTime{utcTime=133645488312376079, javaDate=Thu Jul 04 06:40:31 UTC 2024}} 2024-07-04 06:40:32,588 milo-shared-thread-pool-0 INFO - [routeDeadband] - **** DataValue{value=Variant{value=3.0}, status=StatusCode{name=Good, value=0x00000000, quality=good}, sourceTime=DateTime{utcTime=133645488322267329, javaDate=Thu Jul 04 06:40:32 UTC 2024}, serverTime=DateTime{utcTime=133645488322267329, javaDate=Thu Jul 04 06:40:32 UTC 2024}} 2024-07-04 06:40:33,586 milo-shared-thread-pool-0 INFO - [routeDeadband] - **** DataValue{value=Variant{value=3.2}, status=StatusCode{name=Good, value=0x00000000, quality=good}, sourceTime=DateTime{utcTime=133645488327669740, javaDate=Thu Jul 04 06:40:32 UTC 2024}, serverTime=DateTime{utcTime=133645488327669740, javaDate=Thu Jul 04 06:40:32 UTC 2024}} 2024-07-04 06:40:34,581 milo-shared-thread-pool-0 INFO - [routeDeadband] - **** DataValue{value=Variant{value=3.0}, status=StatusCode{name=Good, value=0x00000000, quality=good}, sourceTime=DateTime{utcTime=133645488342986708, javaDate=Thu Jul 04 06:40:34 UTC 2024}, serverTime=DateTime{utcTime=133645488342986708, javaDate=Thu Jul 04 06:40:34 UTC 2024}} </code> Test_5) dataChangeFilterTrigger = StatusValue dataChangeFilterDeadbandValue = 10 <code>2024-07-04 09:00:48,048 milo-shared-thread-pool-1 INFO - [routeDeadband] - **** DataValue{value=Variant{value=3.2}, status=StatusCode{name=Good, value=0x00000000, quality=good}, sourceTime=DateTime{utcTime=133645572479092312, javaDate=Thu Jul 04 09:00:47 UTC 2024}, serverTime=DateTime{utcTime=133645572479092312, javaDate=Thu Jul 04 09:00:47 UTC 2024}} 2024-07-04 09:00:49,049 milo-shared-thread-pool-1 INFO - [routeDeadband] - **** DataValue{value=Variant{value=3.1333334}, status=StatusCode{name=Good, value=0x00000000, quality=good}, sourceTime=DateTime{utcTime=133645572490049997, javaDate=Thu Jul 04 09:00:49 UTC 2024}, serverTime=DateTime{utcTime=133645572490049997, javaDate=Thu Jul 04 09:00:49 UTC 2024}} 2024-07-04 09:00:50,056 milo-shared-thread-pool-1 INFO - [routeDeadband] - **** DataValue{value=Variant{value=2.925}, status=StatusCode{name=Good, value=0x00000000, quality=good}, sourceTime=DateTime{utcTime=133645572499931469, javaDate=Thu Jul 04 09:00:49 UTC 2024}, serverTime=DateTime{utcTime=133645572499931469, javaDate=Thu Jul 04 09:00:49 UTC 2024}} 2024-07-04 09:00:51,056 milo-shared-thread-pool-1 INFO - [routeDeadband] - **** DataValue{value=Variant{value=2.925}, status=StatusCode{name=Good, value=0x00000000, quality=good}, sourceTime=DateTime{utcTime=133645572509718650, javaDate=Thu Jul 04 09:00:50 UTC 2024}, serverTime=DateTime{utcTime=133645572509718650, javaDate=Thu Jul 04 09:00:50 UTC 2024}} 2024-07-04 09:00:52,057 milo-shared-thread-pool-1 INFO - [routeDeadband] - **** DataValue{value=Variant{value=3.1333334}, status=StatusCode{name=Good, value=0x00000000, quality=good}, sourceTime=DateTime{utcTime=133645572519602261, javaDate=Thu Jul 04 09:00:51 UTC 2024}, serverTime=DateTime{utcTime=133645572519602261, javaDate=Thu Jul 04 09:00:51 UTC 2024}} 2024-07-04 09:00:53,053 milo-shared-thread-pool-1 INFO - [routeDeadband] - **** DataValue{value=Variant{value=3.2}, status=StatusCode{name=Good, value=0x00000000, quality=good}, sourceTime=DateTime{utcTime=133645572525013237, javaDate=Thu Jul 04 09:00:52 UTC 2024}, serverTime=DateTime{utcTime=133645572525013237, javaDate=Thu Jul 04 09:00:52 UTC 2024}} 2024-07-04 09:00:54,056 milo-shared-thread-pool-1 INFO - [routeDeadband] - **** DataValue{value=Variant{value=3.1333334}, status=StatusCode{name=Good, value=0x00000000, quality=good}, sourceTime=DateTime{utcTime=133645572539303064, javaDate=Thu Jul 04 09:00:53 UTC 2024}, serverTime=DateTime{utcTime=133645572539303064, javaDate=Thu Jul 04 09:00:53 UTC 2024}} </code> In the tests performed the behavior is always the same. if you look the sequence data values <code>DataValue{value=Variant{value=xx}</code> of each test in several cases I wouldn't have to receive any values, because the deadband value wasn't overcome. if I try to set the same deadband value like the Test_4 with Prosys OPC UA Client I have got the right behavior
ISSUE SOLVED Created UInteger Bean instance set to 1 value in Bean Configuration, see the following: <code>import org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.UInteger; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;@Configuration public class AppConfig { @Bean(';DeadbandParamater';) public UInteger deadbandParamater() { return UInteger.valueOf(1); }} </code> After that the right configuration of OPC UA milo client <code>from(';milo-client:opc.tcp://127.0.0.1:49310? keyStoreUrl=file:C:\\Temp\\application\\certificate\\clientkeystore.jks &;keyPassword=123456 &;keyStorePassword=123456 &;applicationUri=urn:8409:test:camelopcua &;applicationName=camelopcua&;node=RAW(ns=2;s=Channel2 SIMUL.SIM_1.BNAp1.18VGG1_1XA) &;dataChangeFilterDeadbandValue=0.2 &;dataChangeFilterTrigger=StatusValue &;dataChangeFilterDeadbandType=#bean:DeadbandParamater &;monitorFilterType=dataChangeFilter &;samplingInterval=1000';).log(';**** ${body}';).routeId(';routeDeadband';); </code> ref bean by using query parameter syntax <code>dataChangeFilterDeadbandType=#bean:DeadbandParamater </code> link to DataChangeFilter Test performed:
apache-camel
I need to read a file from sftp server which is proxy enabled. How to build endpoint for apache camel route with spring boot to consume a file from the sftp folder. Without proxy, i am able to read it from one channel. With proxy enabled for the sftp channel, the spring boot application itself is not starting. I am using apache camel version 4.16.0. Please help me with the syntax how to achieve it.? <code>sftp://\<sftp_username\>;@\<sftp_host\>;:\<sftp_port\>;\<root_folder\>;?delay=5000&;delete=true&;include=.\*%5C.json&;noop=false&;password=xxxxxx&;proxy=true&;proxyHost=\<proxy_host\>;&;proxyPort=\<proxy_port\>;&;readLock=rename </code> Getting the below error:... 29 common frames omitted Caused by: org.apache.camel.RuntimeCamelException: org.apache.camel.NoTypeConversionAvailableException: No type converter available to convert from type: java.lang.String to the required type: com.jcraft.jsch.ProxyTrying to read a file but getting an error when starting the application.
The camel documentation doesn't say anything about the <code>proxyHost</code> and <code>proxyPort</code> query parameters. You need to use the parameter <code>proxy</code>, but this is not a boolean, but an implementation of type <code>com.jcraft.jsch.Proxy</code>. For example, if you want to use a Http proxy, you can create a bean like this: <code>Proxy myProxy = new ProxyHTTP(';localhost';, 8080); </code> You need to then pass this object as a reference to your route, indicated by the <code>#</code>: <code>sftp://\<sftp_username\>;@\<sftp_host\>;:\<sftp_port\>;\<root_folder\>;?delay=5000&;delete=true&;include=.\*%5C.json&;noop=false&;password=xxxxxx&;proxy=#myProxy&;readLock=rename </code> https://camel.apache.org/components/4.4.x/sftp-component.html
apache-camel
Good morning, I am currently working with Quarkus and Apache Camel and I am using a variable from the application.properties in a processor, I try to bring it in using the @ConfigProperty annotation, but it is giving me a null error, this is how I have it configured: The variable is called encryptionKey UserProfileProcessorUserIdParamReq <code>@ApplicationScoped @Slf4j public class UserProfileProcessorUserIdParamReq implements Processor { @ConfigProperty(name=';aes.encrypt.key';) String encryptionKey; private final IValidationFieldsUserID validationFields; public UserProfileProcessorUserIdParamReq() { validationFields = new ValidationFieldsUserID(); } @Override public void process(Exchange exchange) throws Exception { String documentType; String documentNumber; String userId; String correlatorId; String tokenInfo; String userIdDecodedBase64; String userIdDecrypt; try { correlatorId= Optional.ofNullable(exchange.getIn().getHeader(';x-correlator';)).map(Object::toString).orElse(';';); exchange.setProperty(';correlatorId';,correlatorId); userId = exchange.getIn().getHeader(';user_id';).toString(); tokenInfo= Optional.ofNullable(exchange.getIn().getHeader(';x-token-info';)).map(Object::toString).orElse(';';); validationFields.validateUserId(exchange); userId=validateUserIdValue(userId, tokenInfo); exchange.setProperty(';userIdEncrypt';, userId); userIdDecodedBase64= EncodeBase64.decrypt(userId); log.info(';userIdDecodedBase64'; + userIdDecodedBase64); userIdDecrypt= EncryptUtil.decrypt(userIdDecodedBase64,encryptionKey); exchange.setProperty(';userId';, userIdDecrypt); validateTokenInfo(exchange,userId, tokenInfo); validateUserIdDecrypt(userIdDecrypt); documentType = userIdDecrypt.split(';-';)[0]; documentNumber = userIdDecrypt.split(';-';)[1]; exchange.setProperty(';documentType';, documentType); exchange.setProperty(';documentNumber';, documentNumber); exchange.setProperty(';isSearchByQueryParam';,';false';); } catch (RequiredValueException | NullPointerException e) { throw new RequiredValueException(e.getMessage()); } catch (NotFoundDataException e) { throw new NotFoundDataException(e.getMessage()); } catch (PermissionDeniedException e) { throw new PermissionDeniedException(e.getMessage()); } catch (Exception e){ if( e.getMessage().contains(';Input byte array';)) throw new NotFoundDataException(e.getMessage()); throw new Exception(e.getMessage()); } } private static void validateTokenInfo(Exchange exchange, String userId, String tokenInfoValidated) { if (!tokenInfoValidated.isEmpty()) { log.info(';Valor del x-token-info: {}';, tokenInfoValidated); /* Se obtiene el Objeto JSON con el valor del campo x-token-info */ JSONObject jsonObject = new JSONObject(tokenInfoValidated); /*String subValue=jsonObject.get(';sub';).toString(); */ /* Mediante el optString obtenemos el valor sub si viene (token 3 patas) o no viene (token 2 patas), para este ultimo caso el valor es vacio */ String subValue = jsonObject.optString(';sub';); log.info(';Valor sub que esta llegando en el valor x-token-info: {}';, subValue); if (!subValue.isEmpty()) { if(!subValue.equals(userId)) { throw new PermissionDeniedException(';Error validando el campo sub de la autenticacion en el campo x-token-info, no hace match con userId enviado';); } } } } /* Se valida que el UserId sea un valor valido para venezuela, sea enviado cifrado o no*/ private static void validateUserIdDecrypt (String userId) { if(!Pattern.matches(';^(CI|RIF|P|CD|NIT)(-).*';,userId)){ throw new NotFoundDataException(';UserId enviado esta en formato incorrecto';); } } /*Se valida el valor del campo UserId, si el mismo pudiera contener el valor de me, en este caso se debe extraer el valor de UserId del json token-info, en especifico del campo sub */ private String validateUserIdValue(String userId,String tokenInfo) { if(userId.equals(';me';)){ if(!tokenInfo.isEmpty()){ JSONObject jsonObject = new JSONObject(tokenInfo); userId = jsonObject.optString(';sub';); } else { throw new RequiredValueException(';Se requiere parametro x-token-info (autenticacion 3 patas) para campo userId=me';); } } return userId; } } </code> And this is the error it gives: <code>14:52:44 INFO traceId=2a0a8e8cd93ddb947e2ab7206ef4f25d, parentId=, spanId=394c6d08dec8d551, sampled=true [route23] (vert.x-worker-thread-0) [2024-07-01 14:52:44.0] Descripcion de la Exception: Cannot invoke ';String.getBytes()'; because ';key'; is null </code> This is how it is in my application.properties: <code>aes.encrypt.key=${AES_ENCRYPT_KEY:xxxxxxxxxxxx} </code> Like from ResRoute call to processor without constructor: <code>from(';direct:usersQueryParam';) /*.removeHeaders(';CamelHttp*';) */ .doTry() .process(new UserProfileProcessorQueryParamReq()) .choice() /* code */ </code> How can I do here so that it takes the value of the @ConfigProperty?
I think it's not working because you're creating the <code>Processor</code> manually. Try to pass the <code>encryptionKey</code> as a constructor parameter and move your <code>@ConfigProperty</code> to the route builder: UserProfileProcessorUserIdParamReq <code>@Slf4j public class UserProfileProcessorUserIdParamReq implements Processor { private String encryptionKey; private final IValidationFieldsUserID validationFields; public UserProfileProcessorUserIdParamReq(String encryptionKey) { validationFields = new ValidationFieldsUserID(); this.encryptionKey = encryptionKey; } @Override public void process(Exchange exchange) throws Exception { String documentType; String documentNumber; String userId; String correlatorId; String tokenInfo; String userIdDecodedBase64; String userIdDecrypt; try { correlatorId= Optional.ofNullable(exchange.getIn().getHeader(';x-correlator';)).map(Object::toString).orElse(';';); exchange.setProperty(';correlatorId';,correlatorId); userId = exchange.getIn().getHeader(';user_id';).toString(); tokenInfo= Optional.ofNullable(exchange.getIn().getHeader(';x-token-info';)).map(Object::toString).orElse(';';); validationFields.validateUserId(exchange); userId=validateUserIdValue(userId, tokenInfo); exchange.setProperty(';userIdEncrypt';, userId); userIdDecodedBase64= EncodeBase64.decrypt(userId); log.info(';userIdDecodedBase64'; + userIdDecodedBase64); userIdDecrypt= EncryptUtil.decrypt(userIdDecodedBase64,encryptionKey); exchange.setProperty(';userId';, userIdDecrypt); validateTokenInfo(exchange,userId, tokenInfo); validateUserIdDecrypt(userIdDecrypt); documentType = userIdDecrypt.split(';-';)[0]; documentNumber = userIdDecrypt.split(';-';)[1]; exchange.setProperty(';documentType';, documentType); exchange.setProperty(';documentNumber';, documentNumber); exchange.setProperty(';isSearchByQueryParam';,';false';); } catch (RequiredValueException | NullPointerException e) { throw new RequiredValueException(e.getMessage()); } catch (NotFoundDataException e) { throw new NotFoundDataException(e.getMessage()); } catch (PermissionDeniedException e) { throw new PermissionDeniedException(e.getMessage()); } catch (Exception e){ if( e.getMessage().contains(';Input byte array';)) throw new NotFoundDataException(e.getMessage()); throw new Exception(e.getMessage()); } } private static void validateTokenInfo(Exchange exchange, String userId, String tokenInfoValidated) { if (!tokenInfoValidated.isEmpty()) { log.info(';Valor del x-token-info: {}';, tokenInfoValidated); /* Se obtiene el Objeto JSON con el valor del campo x-token-info */ JSONObject jsonObject = new JSONObject(tokenInfoValidated); /*String subValue=jsonObject.get(';sub';).toString(); */ /* Mediante el optString obtenemos el valor sub si viene (token 3 patas) o no viene (token 2 patas), para este ultimo caso el valor es vacio */ String subValue = jsonObject.optString(';sub';); log.info(';Valor sub que esta llegando en el valor x-token-info: {}';, subValue); if (!subValue.isEmpty()) { if(!subValue.equals(userId)) { throw new PermissionDeniedException(';Error validando el campo sub de la autenticacion en el campo x-token-info, no hace match con userId enviado';); } } } } /* Se valida que el UserId sea un valor valido para venezuela, sea enviado cifrado o no*/ private static void validateUserIdDecrypt (String userId) { if(!Pattern.matches(';^(CI|RIF|P|CD|NIT)(-).*';,userId)){ throw new NotFoundDataException(';UserId enviado esta en formato incorrecto';); } } /*Se valida el valor del campo UserId, si el mismo pudiera contener el valor de me, en este caso se debe extraer el valor de UserId del json token-info, en especifico del campo sub */ private String validateUserIdValue(String userId,String tokenInfo) { if(userId.equals(';me';)){ if(!tokenInfo.isEmpty()){ JSONObject jsonObject = new JSONObject(tokenInfo); userId = jsonObject.optString(';sub';); } else { throw new RequiredValueException(';Se requiere parametro x-token-info (autenticacion 3 patas) para campo userId=me';); } } return userId; } } </code> ResRoute <code> package org.tmve.customer.ms.route; import org.apache.camel.Exchange; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.caffeine.CaffeineConstants; import org.apache.camel.model.rest.RestBindingMode; import org.apache.http.NoHttpResponseException; import org.apache.http.conn.HttpHostConnectException; import org.eclipse.microprofile.config.inject.ConfigProperty; import org.tmve.customer.ms.beans.response.UserProfile; import org.tmve.customer.ms.exceptions.NotFoundDataException; import org.tmve.customer.ms.exceptions.EmptyDataExceptionQueryParam; import org.tmve.customer.ms.exceptions.PermissionDeniedException; import org.tmve.customer.ms.exceptions.RequiredValueException; import org.tmve.customer.ms.processor.*; import org.tmve.customer.ms.utilities.BeanDate; import javax.enterprise.context.ApplicationScoped; import java.net.UnknownHostException; import static org.apache.camel.model.rest.RestParamType.body; @ApplicationScoped public class ResRoute extends RouteBuilder { @ConfigProperty(name=';aes.encrypt.key';) String encryptionKey; @ConfigProperty(name=';client.findCustomerByDocId';) String findCustomerByDocId; @ConfigProperty(name=';client.findCustomerAccountListByDocId';) String findCustomerAccountsListByDocId; @ConfigProperty(name=';client.findPostpaidAccountInfo';) String findPostpaidAccountInfo; @ConfigProperty(name=';client.findCustomerDocumentBySubscriberId';) String findCustomerDocumentBySubscriberId; @ConfigProperty(name=';client.findFeatureByAccount';) String findFeatureByAccount; @ConfigProperty(name = ';path.openapi';) String openApiPath; @ConfigProperty(name = ';descripcion.servicio';) String serviceDescription; private ConfigureSsl configureSsl; private static final String SALIDA_BSS_EXCEPTION = ';Salida del microservicio BSS UserProfile ${exchangeProperty[bodyRs]}';; private static final String USER_PROFILE = ';UserProfile';; private static final String MSG_EXCEPTION = ';Descripcion de la Exception: ${exception.message}';; private static final String DATE_LOG = ';[${bean:BeanDate.getCurrentDateTime()}] ';; private static final String DIRECT_PIPELINE = ';direct:pipeline';; public ResRoute() { configureSsl = new ConfigureSsl(); } @Override public void configure() throws Exception { BeanDate beanDate= new BeanDate(); getContext().getRegistry().bind(';BeanDate';,beanDate); restConfiguration() .bindingMode(RestBindingMode.json) .dataFormatProperty(';json.in.disableFeatures';, ';FAIL_ON_UNKNOWN_PROPERTIES';) .apiContextPath(openApiPath) .apiProperty(';api.title';, USER_PROFILE) .apiProperty(';api.description';, serviceDescription) .apiProperty(';api.version';, ';1.0.0';) .apiProperty(';cors';, ';true';); rest(';userProfile/v3/';) .get(';/users/{user_id}';).to(';direct:/{user_id}';) .outType(UserProfile.class) .param().name(USER_PROFILE).type(body).description(';parametro de salida';).required(true) .endParam() .to(';direct:userIdParam';); rest(';/userProfile/v3/';) .get(';/users?';).to(';direct:/users?';) .outType(UserProfile.class) .param().name(USER_PROFILE).type(body).description(';parametro de salida';).required(true).endParam() .to(';direct:usersQueryParam';); onException(RequiredValueException.class) .handled(true) .process(new UserProfileProcessorInvalidFormatException()) .log(DATE_LOG+MSG_EXCEPTION) .log(DATE_LOG+SALIDA_BSS_EXCEPTION); onException(NotFoundDataException.class) .handled(true) .process(new UserProfileProcessorInformationSubscriber()) .log(DATE_LOG+MSG_EXCEPTION) .log(DATE_LOG+SALIDA_BSS_EXCEPTION); onException(HttpHostConnectException.class) .handled(true) .process(new UserProfileProcessHttpHostConectionException()) .log(DATE_LOG+MSG_EXCEPTION) .log(DATE_LOG+SALIDA_BSS_EXCEPTION); onException(PermissionDeniedException.class) .handled(true) .process(new UserProfileProcessorPermissionDenied()) .log(DATE_LOG+MSG_EXCEPTION) .log(DATE_LOG+SALIDA_BSS_EXCEPTION); onException(Exception.class) .handled(true) .process(new UserProfileProcessorException()) .log(DATE_LOG+MSG_EXCEPTION) .log(DATE_LOG+SALIDA_BSS_EXCEPTION); from(';direct:userIdParam';) .doTry() .process(new UserProfileProcessorUserIdParamReq(encryptionKey)) .log(DATE_LOG+';User ID: ${exchangeProperty[userId]}';) .log(DATE_LOG+';UserId Encrypt: ${exchangeProperty[userIdEncrypt]}';) .log(DATE_LOG+';Correlator ID: ${exchangeProperty[correlatorId]}';) .endDoTry() .to(DIRECT_PIPELINE); from(';direct:usersQueryParam';) /*.removeHeaders(';CamelHttp*';) */ .doTry() .process(new UserProfileProcessorQueryParamReq()) .choice() .when(simple(';${exchangeProperty[isSearchByQueryParamIdDocumentValueAndIdDocumentType]} == 'true'';)) .to(DIRECT_PIPELINE) .otherwise() .log(DATE_LOG+';Identity: ${exchangeProperty[identityQueryParam]}';) .log(DATE_LOG+';IdentityType: ${exchangeProperty[identityTypeQueryParam]}';) .process(new FindCustomerDocumentBySubscriberIdReq()) .log(DATE_LOG+';Entrada Microservicio FindCustomerDocumentBySubscriberId: ${exchangeProperty[findCustomerDocumentBySubscriberIdRequest]}';) .to(configureSsl.setupSSLContext(getCamelContext(), findCustomerDocumentBySubscriberId)) .process(new FindCustomerDocumentBySubscriberIdRes()) .log(DATE_LOG+';Salida FindCustomerDocumentBySubscriberId: ${exchangeProperty[findCustomerDocumentBySubscriberIdResponseStatus]}';) .log(DATE_LOG+';User ID Mediante QueryParam: ${exchangeProperty[userId]}';) .to(DIRECT_PIPELINE) .endDoTry() /*.to(DIRECT_PIPELINE) */ .doCatch(EmptyDataExceptionQueryParam.class) .process(new UserProfileEmptyDataSubscriberQueryParam()) .log(DATE_LOG+MSG_EXCEPTION) .log(DATE_LOG+SALIDA_BSS_EXCEPTION); from(DIRECT_PIPELINE) .doTry() .log(DATE_LOG+';UserId: ${exchangeProperty[userId]}';) .process(new FindCustomerByDocIdProcessorReq()) .to(configureSsl.setupSSLContext(getCamelContext(), findCustomerByDocId)) .choice() .when(header(Exchange.HTTP_RESPONSE_CODE).isEqualTo(200)) .process(new FindCustomerByDocIdProcessorRes()) .log(DATE_LOG+';Mensaje Ejecucion MS FindCustomerByDocId: ${exchangeProperty[findCustomerByDocIdResponseMessage]}';) .when(header(Exchange.HTTP_RESPONSE_CODE).isEqualTo(404)) .process(new FindCustomerByDocIdProcessorResHttp404()) .log(DATE_LOG+';Mensaje Ejecucion MS FindCustomerByDocId: ${exchangeProperty[findCustomerByDocIdResponseMessage]}';) .otherwise() .log(';Error al consultar Microservicio FindCustomerByDocId con codigo de respuesta: ${header.CamelHttpResponseCode}';) .process(new UserProfileFaultProcessRes()) .end() .log(DATE_LOG+';Document userId: ${exchangeProperty[userDocument]}';) .log(DATE_LOG+';Name userId: ${exchangeProperty[userName]}';) .process(new FindCustomerAccountListByDocIdReq()) .to(configureSsl.setupSSLContext(getCamelContext(), findCustomerAccountsListByDocId)) .choice() .when(header(Exchange.HTTP_RESPONSE_CODE).isEqualTo(200)) .process(new FindCustomerAccountsListByDocIdRes()) .log(DATE_LOG+';Mensaje Ejecucion MS FindCustomerAccountListByDocId: ${exchangeProperty[findCustomerAccountListByDocIdResponseMessage]}';) .log(DATE_LOG+';Total Cuentas Prepago: ${exchangeProperty[prepaidAccountCount]}';) .log(DATE_LOG+';Total Cuentas Pospago: ${exchangeProperty[postpaidAccountCount]}';) .log(DATE_LOG+';Cuentas Prepago: ${exchangeProperty[prepaidAccounts]}';) .log(DATE_LOG+';Cuentas Pospago: ${exchangeProperty[postpaidAccounts]}';) .otherwise() .log(';Error al consultar Microservicio FindCustomerAccountsListByDocId con codigo de respuesta: ${header.CamelHttpResponseCode}';) .process(new UserProfileFaultProcessRes()) .end() .loop(simple(';${exchangeProperty[postpaidAccountCount]}';)) .process(new FindPostpaidAccountInfoProcessReq()) .setHeader(CaffeineConstants.ACTION, constant(CaffeineConstants.ACTION_GET)) .setHeader(CaffeineConstants.KEY).exchangeProperty(';postpaidAccount';) .toF(';caffeine-cache://%s';, ';SVAPostpaid';) .choice().when(header(CaffeineConstants.ACTION_HAS_RESULT).isEqualTo(Boolean.FALSE)) .to(configureSsl.setupSSLContext(getCamelContext(), findPostpaidAccountInfo)) .setHeader(CaffeineConstants.ACTION, constant(CaffeineConstants.ACTION_PUT)) .setHeader(CaffeineConstants.KEY).exchangeProperty(';postpaidAccount';) .toF(';caffeine-cache://%s';, ';SVAPostpaid';) .process(new FindPostpaidAccountInfoProcessRes()) .otherwise() .process(new FindPostpaidAccountInfoProcessRes()) .end() .end() .log(DATE_LOG+';Busqueda SVA para Cuentas Pospago Exitosa....';) .loop(simple(';${exchangeProperty[prepaidAccountCount]}';)) .process(new FindFeaturesByAccountProcessorReq()) .setHeader(CaffeineConstants.ACTION, constant(CaffeineConstants.ACTION_GET)) .setHeader(CaffeineConstants.KEY).exchangeProperty(';prepaidAccount';) .toF(';caffeine-cache://%s';, ';SVAPrepaid';) .choice().when(header(CaffeineConstants.ACTION_HAS_RESULT).isEqualTo(Boolean.FALSE)) .to(configureSsl.setupSSLContext(getCamelContext(), findFeatureByAccount)) .setHeader(CaffeineConstants.ACTION, constant(CaffeineConstants.ACTION_PUT)) .setHeader(CaffeineConstants.KEY).exchangeProperty(';prepaidAccount';) .toF(';caffeine-cache://%s';, ';SVAPrepaid';) .process(new FindFeatureByAccountProcessorRes()) .otherwise() .process(new FindFeatureByAccountProcessorRes()) .end() .end() .log(DATE_LOG+';Busqueda SVA para Cuentas Prepago Exitosa....';) .choice() .when(simple(';${exchangeProperty[isSearchByQueryParam]} == 'true'';)) .process(new UserProfileProcessorQueryParamRes()) .log(DATE_LOG+';Salida MS UserProfile: ${exchangeProperty[userProfileResponse]}';) .otherwise() .process(new UserProfileProcessorUserIdRes()) .log(DATE_LOG+';Salida MS UserProfile: ${exchangeProperty[userProfileResponse]}';) .endDoTry() .doCatch(UnknownHostException.class) .process(new UserProfileProcessHttpHostConectionException()) .log(DATE_LOG+MSG_EXCEPTION) .log(DATE_LOG+SALIDA_BSS_EXCEPTION) .doCatch(NoHttpResponseException.class) .process(new UserProfileProcessHttpHostConectionException()) .log(DATE_LOG+MSG_EXCEPTION) .log(DATE_LOG+SALIDA_BSS_EXCEPTION); } } </code>
apache-camel
I am working with apache camel in quarkus and I am enabling cache deletion after certain time but I am not able to delete it i.e. I use properties camel.component.caffeine-cache.expire-after-access-time and camel.component.caffeine - cache .expire-after-write-time in the properties, however I am testing it and after setting a time of 60 seconds the query is still done in the cache: <code>#cache camel.component.caffeine-cache.expire-after-write-time=60 camel.component.caffeine-cache.expire-after-access-time=60 </code> Test number 1 at 2:00 PM:Query the cache: CamelCaffeineActionHasResult =trueTest number 2 at 2:04 PM, in this chaos 240 seconds have already passed since it was cached:Keep consulting the cache: CamelCaffeineActionHasResult =trueWhat could be the cause of this behavior? Shouldn't it be possible to consult the service again outside the cache after the expiration time (60sec)? This is how I ended up configuring my ResRoute <code>@ApplicationScoped public class ResRoute extends RouteBuilder { @ConfigProperty(name = ';client.findIndividualCustomerByDocId';) String findIndividualCustomerByDocId; @ConfigProperty(name = ';client.findOrganizacionCustomerByDocId';) String findOrganizacionCustomerByDocId; @ConfigProperty(name = ';path.openapi';) String pathOpenapi; @ConfigProperty(name = ';descripcion.servicio';) String descripcionServicio; private ConfigureSsl configureSsl; private static final String SALIDA_BSS_EXCEPTION = ';Salida del microservicio BSS FindCustomerByDocId ${exchangeProperty[bodyRs]}';; private static final String MSG_EXCEPTION = ';Descripcion de la Exception: ${exception.message}';; public ResRoute() { configureSsl = new ConfigureSsl(); } @Override public void configure() throws Exception { BeanDate beanDate= new BeanDate(); getContext().getRegistry().bind(';BeanDate';,beanDate); restConfiguration() .bindingMode(RestBindingMode.json) .dataFormatProperty(';json.in.disableFeatures';, ';FAIL_ON_UNKNOWN_PROPERTIES';) .apiContextPath(pathOpenapi) .apiProperty(';api.title';, ';FindCustomerByDocId';) .apiProperty(';api.description';, descripcionServicio) .apiProperty(';api.version';, ';1.0.0';) .apiProperty(';cors';, ';true';); rest(';customerInformation/v1.4.0/users/';) .get(';/{user_id}/customers';).to(';direct:/{user_id}/customers';) .outType(Customer.class) .param().name(';FindCustomerByDocIdResponse';).type(body).description(';parametro de salida';).required(true) .endParam() .to(';direct:pipeline';); from(';direct:pipeline';) .doTry() .process(new FindCustomerByDocIdProcessorReq()) .log('; [${bean:BeanDate.getCurrentDateTime()}] ';+';User ID: ${exchangeProperty[userId]}';) .log('; [${bean:BeanDate.getCurrentDateTime()}] ';+';Correlator ID: ${exchangeProperty[correlatorId]}';) .log('; [${bean:BeanDate.getCurrentDateTime()}] ';+';Tipo de Documento (Num): ${exchangeProperty[documentTypeNum]}';) .log('; [${bean:BeanDate.getCurrentDateTime()}] ';+';Tipo de Cliente: ${exchangeProperty[customerType]}';) .choice() .when(simple(';${exchangeProperty[customerType]} == 'NATURAL'';)) .process(new FindIndividualCustomerByDocIdProcessorReq()) .setHeader(CaffeineConstants.ACTION, constant(CaffeineConstants.ACTION_GET)) .setHeader(CaffeineConstants.KEY).exchangeProperty(';documentNumber';) .toF(';caffeine-cache://%s';, ';IndividualCache';) .log(';Hay Resultado en Cache de la consulta asociado al siguiente documento: ${exchangeProperty[userId]} ${header.CamelCaffeineActionHasResult}}';) .log(';CamelCaffeineActionSucceeded: ${header.CamelCaffeineActionSucceeded}';) .choice().when(header(CaffeineConstants.ACTION_HAS_RESULT).isEqualTo(Boolean.FALSE)) .to(configureSsl.setupSSLContext(getCamelContext(), findIndividualCustomerByDocId)) .setHeader(CaffeineConstants.ACTION, constant(CaffeineConstants.ACTION_PUT)) .setHeader(CaffeineConstants.KEY).exchangeProperty(';documentNumber';) .toF(';caffeine-cache://%s';, ';IndividualCache';) .process(new FindIndividualCustomerByDocIdProcessorRes()) .log('; [${bean:BeanDate.getCurrentDateTime()}] ';+';Salida del microservicio FindIndividualCustomerByDocId ${exchangeProperty[findIndividualCustomerByDocIdResponse]}';) .log('; [${bean:BeanDate.getCurrentDateTime()}] ';+';Salida del microservicio BSS FindCustomerByDocId ${exchangeProperty[findCustomerByDocIdResponse]}';) .otherwise() .log(';Cache is working';) .process(new FindIndividualCustomerByDocIdProcessorRes()) .log('; [${bean:BeanDate.getCurrentDateTime()}] ';+';Salida del microservicio FindIndividualCustomerByDocId ${exchangeProperty[findIndividualCustomerByDocIdResponse]}';) .log('; [${bean:BeanDate.getCurrentDateTime()}] ';+';Salida del microservicio BSS FindCustomerByDocId ${exchangeProperty[findCustomerByDocIdResponse]}';) .when(simple(';${exchangeProperty[customerType]} == 'JURIDICO'';)) .process(new FindOrganizationCustomerByDocIdProcessorReq()) .to(configureSsl.setupSSLContext(getCamelContext(), findOrganizacionCustomerByDocId)) .process(new FindOrganizationCustomerByDocIdProcessorRes()) /*.log('; [';+getCurrentDate()+';]';+';Entrada del microservicio FindOrganizationCustomerByDocId ${exchangeProperty[findOrganizationCustomerByDocIdRequest]}';) */ .log('; [${bean:BeanDate.getCurrentDateTime()}] ';+';Salida del microservicio FindOrganizationCustomerByDocId ${exchangeProperty[findOrganizationCustomerByDocIdResponse]}';) .log('; [${bean:BeanDate.getCurrentDateTime()}] ';+';Salida del microservicio BSS FindCustomerByDocId ${exchangeProperty[findCustomerByDocIdResponse]}';) .endChoice() .endDoTry() .doCatch(RequiredValueException.class) .process(new FindCustomerByDocIdProcessorInvalidFormatException()) .log('; [${bean:BeanDate.getCurrentDateTime()}] ';+MSG_EXCEPTION) .log('; [${bean:BeanDate.getCurrentDateTime()}] ';+SALIDA_BSS_EXCEPTION) .doCatch(HttpHostConnectException.class) .process(new FindCustomerByDocIdProcessorHttpHostConectionException()) .log('; [${bean:BeanDate.getCurrentDateTime()}] ';+MSG_EXCEPTION) .log('; [${bean:BeanDate.getCurrentDateTime()}] ';+SALIDA_BSS_EXCEPTION) .doCatch(NotFoundDataException.class) .process(new FindCustomerByDocIdProcessorInformationSubscriber()) .log('; [${bean:BeanDate.getCurrentDateTime()}] ';+MSG_EXCEPTION) .log('; [${bean:BeanDate.getCurrentDateTime()}] ';+SALIDA_BSS_EXCEPTION) .doCatch(UnknownHostException.class) .process(new FindCustomerByDocIdProcessorHttpHostConectionException()) .log('; [${bean:BeanDate.getCurrentDateTime()}] ';+MSG_EXCEPTION) .log('; [${bean:BeanDate.getCurrentDateTime()}] ';+SALIDA_BSS_EXCEPTION) .doCatch(NoHttpResponseException.class) .process(new FindCustomerByDocIdProcessorHttpHostConectionException()) .log('; [${bean:BeanDate.getCurrentDateTime()}] ';+MSG_EXCEPTION) .log('; [${bean:BeanDate.getCurrentDateTime()}] ';+SALIDA_BSS_EXCEPTION) .doCatch(Exception.class) .process(new FindCustomerByDocIdProcessorException()) .log('; [${bean:BeanDate.getCurrentDateTime()}] ';+MSG_EXCEPTION) .log('; [${bean:BeanDate.getCurrentDateTime()}] ';+SALIDA_BSS_EXCEPTION); } } </code>
Configuration options: <code>camel.component.caffeine-cache.expire-after-write-time camel.component.caffeine-cache.expire-after-access-time </code> Only apply when the <code>evictionType</code> option is set to <code>TIME_BASED</code>. The default is <code>SIZE_BASED</code>. Thus <code>write-time</code> &; <code>access-time</code> will have no effect. You can configure the eviction type like this: <code>camel.component.caffeine-cache.eviction-type = TIME_BASED </code> See the Camel Caffeine component documentation: https://camel.apache.org/components/next/caffeine-cache-component.html#_component_option_evictionType https://camel.apache.org/components/next/caffeine-cache-component.html#_sb_option_camel_component_caffeine-loadcache_eviction-type
apache-camel
I have the following Camel route <code>from(';file://target/input/?delete=true';) .log(';Started processing [${header.CamelFileNameOnly}] ...';) .split(body().tokenize('; ';)).streaming() .log(';ELEMENT ${body}';) .process(this::doStuffWithElement); </code> I'd like to know somehow when the last line in the file is reached, and then do further processing. I have tried to call <code>end()</code> however in this case it doesn't work as I want. I'd like to find a solution that could be applied to all sort of sources, eg. an incoming HTTP request, a file downloaded from S3 or SFTP - to name a few. The idea is to implement a streaming-style processing solution, that doesn't spike in memory consumption, but that it's aware of when the end of the stream is reached correctly.
After <code>.split()</code> is called the exchange will have a property called <code>CamelSplitComplete</code>. More importantly though, if you want to make <code>.end()</code> work as intended by common sense, you need to call it twice in a row: <code>.end().end()</code> will effectively mean the stream is finished, and after that call you can do further processing. Found this solution because of this (<code>camel-4.6.x</code>).
apache-camel
Is there a way to split body of exchange (List) into bigger chuncks than 1 element exchanges? When using big files to process, i end up with huge number of one-line exchanges and alot of memory consumption. <code> from(url.concat(';RAW('; + filesToInclude + ';)';)) .log(';Start processing file: ${header.CamelFileName}';) .routeId(CamelRoutes.LIST_ROUTE_ID + endpointConfig.getConfigId()) .setHeader(CamelHeaders.ENDPOINT_CONFIG, constant(endpointConfig)) .unmarshal(getCsvDataFormat(endpointConfig)) .split(body()) .streaming().parallelProcessing().executorService(Executors.newFixedThreadPool(CONCURRENT_THREADS_NUMBER)) .stopOnException().stopOnAggregateException() .marshal().json(JsonLibrary.Jackson) .log(';Starting aggregating for batch processing';) .aggregate(header(Exchange.FILE_NAME), new ListAggregationStrategy()) .completionPredicate(new BatchSizePredicate(endpointConfig.getMaxBatchSize())) .completionTimeout(endpointConfig.getBatchTimeout()) .log(';Start one batch processing';) .bean(rowCamelService, ';saveInDB';) .log(';Finished one batch processing';) .end() .log(';Finished aggregating for batch processing';) .log(';Finished processing file: ${header.CamelFileName}';) .end(); </code> For 60MB of CSV file, it takes over 1G or memory. I need to lower it down to 500MB at maximum.
You use setBody(...) to partition the list before splitting <code>public class MyRouteBuilder extends RouteBuilder { private static final int BATCH_SIZE = 1000; private <T>; List<List<T>;>; splitIntoBatches(List<T>; list, int batchSize) { // TODO implement using one of the suggestions from https://www.baeldung.com/java-list-split } public void configure() { from(...) .setBody(exchange ->; { List<String>; list = exchange.getMessage().getBody(List.class); return splitIntoBatches(list, BATCH_SIZE); }) .split(body()) .streaming() ... } } </code>
apache-camel
I'm finally in the process of upgrading our old Camel 2.x stack. <code>WireTapDefinition.newExchange(Processor processor)</code> was removed in 3.16 and I haven't found any examples of how to replace it. What should I replace it with in this instance? <code>exceptionErrorHandlers.forEach { onException(it.exceptionToHandle) .process(MyErrorProcessor()) .wireTap(someUri) .newExchange(MyProcessor()) .end() .handled(true) .bean(failedCounter, ';inc()';) } </code>
I ended up doing this (as mentioned by @ChinHuang in the comments), which seems to work: <code>exceptionErrorHandlers.forEach { onException(it.exceptionToHandle) .process(MyErrorProcessor()) .wireTap(someUri).copy() .onPrepare(MyProcessor()) .end() .handled(true) .bean(failedCounter, ';inc()';) } </code> It's described in the Camel 3.16 upgrade guide, albeit somewhat unclearly:Removed the new message mode as this functionality is better done by using onPrepare processor in copy mode
apache-camel
I try to define a simple kamelet and run it in Camel Spring Boot route. <code>my-kamelet.kamelet.yaml</code> is located in <code>resources/kamelets</code> <code>apiVersion: camel.apache.org/v1alpha1 kind: Kamelet metadata: name: my-kamelet spec: template: from: uri: timer:mykamelet?period=1000 steps: - log: ';Executing Kamelet scheduled job'; </code> my routeBuilder <code>@Component public class KameletRoute extends RouteBuilder { @Override public void configure() throws Exception { from(';kamelet:my-kamelet';) .log(';Executing main route';); } } </code> relevant dependencies in <code>pom.xml</code> <code> <dependency>; <groupId>;org.springframework.boot</groupId>; <artifactId>;spring-boot-starter-web</artifactId>; </dependency>; <dependency>; <groupId>;org.apache.camel.springboot</groupId>; <artifactId>;camel-spring-boot-starter</artifactId>; <version>;${camel.version}</version>; </dependency>; <dependency>; <groupId>;org.apache.camel.springboot</groupId>; <artifactId>;camel-kamelet-starter</artifactId>; <version>;${camel.version}</version>; </dependency>; </code> When I start the application i get following error: ERROR 20372 --- [kamelet-poc] [ restartedMain] o.s.boot.SpringApplication : Application run failed <code>org.apache.camel.FailedToCreateRouteException: Failed to create route route1: Route(route1)[From[kamelet:my-kamelet] ->; [Log[Executing mai... because of No endpoint could be found for: kamelet://my-kamelet, please check your classpath contains the needed Camel component jar. </code> I guess am missing something stupid but I am not able to discover what.
The missing part was <code>camel-yaml-dsl</code> dependency <code> <dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-yaml-dsl</artifactId>; <version>;${camel.version}</version>; </dependency>; </code>
apache-camel
I am currently having an issue with json validation of date time fields in camel. I am using the inbuilt json validator of camel, where it takes in parameter json schema as reference for validation. My issue is with date time fields, if the date time field in the json request doesn't have the time zone it fails. I am trying to override the format or skip date time validation it fails unsuccessfully. I have : <code>.choice() .when(isJsonValidationEnabled) .to(jsonValidator(';classpath:of_json_schema.json';)) .endChoice() .end() </code> Above is the json <code>';date_time_field';: { ';description';: ';date_time_field';, ';type';: ';string';, ';format';: ';date-time'; } </code> When having something like this in the schema : any request having this : <code>';date_time_field';: ';2022-10-05T07:03:19';, </code> but having this : <code>';date_time_field';: ';2022-10-05T07:03:19Z';, </code> is a success. I want a way to either override date time fields validation to accept things like this : ';2023-10-05T07:03:19';, or skip them. I tried json schema instantiation and a custom format, and passed it as paramer in the json validator endpoint with no luck.
The thing to do was to : 1- Implement Format <code>public class CustomDateTimeFormat implements Format { //implementation } </code> 2- Create Json schema and add to it the format <code> public class CustomJsonUriSchemaLoader implements JsonUriSchemaLoader { //implementation public JsonSchema createSchema(CamelContext camelContext, String schemaUri) throws Exception { //implementation JsonMetaSchema overrideDateTimeValidator = new JsonMetaSchema .Builder(jsonSchemaVersion.getInstance().getUri()) .idKeyword(';$id';) .addKeywords(ValidatorTypeCode.getNonFormatKeywords(version)) .addFormats(Collections.singletonList(new CustomDateTimeFormat())) .build(); } } </code> 3- Load the schema in the json validator endpoint. <code>.choice() .when(this::isJsonValidationEnabled) .to(jsonValidator(CLASSPATH_SCHEMA_JSON) .advanced().uriSchemaLoader(new CustomJsonUriSchemaLoader())) .endChoice() .end() </code> Then date time validation will be overridden.
apache-camel
I´m trying to validate an incoming json string against a json schema, but instead of throwing an exception if that validation fails, I´d like to forward the validation errors together with the validated json payload: <code>from(';direct:myValidator';) .log(';Validating json...';) .to(';json-validator:myschema.json';) .onException(org.apache.camel.component.jsonvalidator.JsonValidationException.class) .continued(true) .transform().???; </code> So ideally I would have a a json object like <code>';validatedJson';:*original json*, ';validationResult';:*excepted integer but got string*';</code> after that. I understand that with simple and ${exception.message} I can access the errors. But I didn´t manage to turn that into valid json and combine it with the original message.
You need to process the message with a <code>Processor</code> to transform it accordingly. You can do something like this in your <code>onException</code> block: <code>.process(exchange ->; { String originalJson = exchange.getIn().getBody(String.class); JsonValidationException cause = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, JsonValidationException.class); String out = ';{\';validatedJson\';: \';'; + originalJson + ';\';, \';validationResult\';: \';'; + cause.toString() + ';\';}';; exchange.getIn().setBody(out); }) </code> First you will read the body as the original json. You can also get the exception as you already know. And then you will create a new body, containing the original json and the error message. We're creating the json by hand, but of course, with more complex structure, you should use a library.
apache-camel
I have a connection to an Azure service bus queue defined in <code>xml</code> <code><route id=';Elexon_IRIS_Route';>; <from uri=';azureQueueEndpoint'; />; <convertBodyTo type=';java.lang.String';/>; <unmarshal>;<json/>;</unmarshal>; <to uri=';localAMQ:topic:IRIS-Elexon';/>; </route>;<bean id=';azureServiceBusComponent'; class=';org.apache.camel.component.azure.servicebus.ServiceBusComponent';>; <property name=';configuration';>; <bean class=';org.apache.camel.component.azure.servicebus.ServiceBusConfiguration';>; <property name=';credentialType'; value=';TOKEN_CREDENTIAL'; />; <property name=';tokenCredential'; ref=';azauth'; />; <property name=';fullyQualifiedNamespace'; value=';elexon-iris.servicebus.windows.net'; />; </bean>; </property>; </bean>;</code> Using <code>camel-azure-servicebus-4.4.1</code> I get the following headers returned for each message: <code>{';expires';=>;';0';, ';CamelAzureServiceBusEnqueuedSequenceNumber';=>;';10655170';, ';destination';=>;';/topic/IRIS-Elexon';, ';CamelAzureServiceBusDeliveryCount';=>;';0';, ';ack';=>;';ID:bravo-43103-1716763678894-2:59';, ';CamelAzureServiceBusSubject';=>;';MELS';, ';subscription';=>;';4b0062c6-48be-4cb2-abce85d1481b3401';, ';priority';=>;';4';, ';CamelAzureServiceBusSequenceNumber';=>;';7955951';, ';CamelAzureServiceBusMessageId';=>;';MELS_202405262248_85602.json';, ';message-id';=>;';ID:bravo-43103-1716763678894-10:1:3:1:1272';, ';persistent';=>;';true';, ';timestamp';=>;';1716763744004';, ';CamelAzureServiceBusLockToken';=>;';64179600-27db-48ed-be93-eb19ebe0f66b';} </code> But when I change to <code>camel-azure-servicebus-4.4.2</code> the only headers I get are: <code>{';expires';=>;';0';, ';destination';=>;';/topic/IRIS-Elexon';, ';ack';=>;';ID:bravo-34173-1716750388709-2:15634';, ';subscription';=>;';16b02d1f-40df-4f31-b538738618f91316';, ';priority';=>;';4';, ';message-id';=>;';ID:bravo-34173-1716750388709-10:1:5:1:43221';, ';persistent';=>;';true';, ';source_file_name';=>;';MELS_202405262245_85595.json';, ';timestamp';=>;';1716763562372';} </code> How do I get the <code>CamelAzureServiceBus</code> headers back? I filter on those within a processing script so this is a rather breaking change. I can't see anything obvious updated in the docs, but there is this JIRA
This was caused by a bug in <code>4.4.2</code> and has now been resolved and confirmed working as expected in <code>4.4.3</code> https://issues.apache.org/jira/browse/CAMEL-20699 https://issues.apache.org/jira/browse/CAMEL-20691
apache-camel
I have a problem with adjusting the Camel route on the need of tests. I have following route defined: <code>from(source) .routeId(ROUTE_GENERAL_ID) .wireTap(inputMetrics) .to(mappingStep) .process(enrichingWithInternalData) .process(enrichingWithExternalData) </code> I want to test the route which ends with the wiretap. So there is no need to perform processing of the steps from the ';main'; route. These ones mentioned below: <code> .to(mappingStep) .process(enrichingWithInternalData) .process(enrichingWithExternalData) </code> If there is no need to run them, I want to remove them to not waste time on the executing them. I was able to remove them, but I could only accomplish it by removing them one by one using adviceWith. <code> adviceWith(context, ROUTE_GENERAL_ID, builder ->; builder.weaveByToUri(';mappingStep';).remove()) adviceWith(context, ROUTE_GENERAL_ID, builder ->; builder.weaveByToUri(';enrichingWithInternalData';).remove()) adviceWith(context, ROUTE_GENERAL_ID, builder ->; builder.weaveByToUri(';enrichingWithExternalData';).remove()) </code> But this solution requires to modify test, when any step will be added/removed to main path. Another idea is to manually iterate over the route. But I'm curious, if there is something already in camel, which I can use here. Or maybe you know more smooth solution for it.
You can divide your original route, for example like this: <code>from(source) .routeId(ROUTE_GENERAL_ID) .wireTap(inputMetrics) .to(';direct:mappingStep';);from(';direct:mappinStep';) .routeId(';mappingStep';) .process(enrichingWithInternalData) .process(enrichingWithExternalData); </code> Now you can skip the routing to the <code>direct:mappingStep</code> endpoint in your test like follows. Also don't forget to tell your test, you're using <code>AdviceWith</code>: <code>... @Override public boolean isUseAdviceWith() { return true; }@Test public void testRoute() throws Exception { adviceWith(context, ROUTE_GENERAL_ID, builder ->; builder.weaveByToUri(';mappingStep';).remove()) ... } </code>
apache-camel
I am currently working with Apache Camel in Quarkus and I need to catch an exception of the following type using throw, so that the class that calls it can handle it: <code>java.lang.Exception: Input byte array has wrong 4-byte ending unit at org.tmve.customer.ms.processor.UserProfileProcessorUserIdParamReq.process(UserProfileProcessorUserIdParamReq.java:57) at org.apache.camel.support.processor.DelegateSyncProcessor.process(DelegateSyncProcessor.java:65) at org.apache.camel.impl.engine.CamelInternalProcessor.process(CamelInternalProcessor.java:392) at org.apache.camel.processor.Pipeline$PipelineTask.run(Pipeline.java:104) at org.apache.camel.impl.engine.DefaultReactiveExecutor$Worker.schedule(DefaultReactiveExecutor.java:181) at org.apache.camel.impl.engine.DefaultReactiveExecutor.scheduleMain(DefaultReactiveExecutor.java:59) at org.apache.camel.processor.Pipeline.process(Pipeline.java:165) at org.apache.camel.impl.engine.CamelInternalProcessor.process(CamelInternalProcessor.java:392) at org.apache.camel.component.platform.http.vertx.VertxPlatformHttpConsumer.lambda$handleRequest$2(VertxPlatformHttpConsumer.java:201) at io.vertx.core.impl.ContextBase.lambda$null$0(ContextBase.java:137) at io.vertx.core.impl.ContextInternal.dispatch(ContextInternal.java:264) at io.vertx.core.impl.ContextBase.lambda$executeBlocking$1(ContextBase.java:135) at org.jboss.threads.ContextHandler$1.runWith(ContextHandler.java:18) at org.jboss.threads.EnhancedQueueExecutor$Task.run(EnhancedQueueExecutor.java:2449) at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1478) at org.jboss.threads.DelegatingRunnable.run(DelegatingRunnable.java:29) at org.jboss.threads.ThreadLocalResettingRunnable.run(ThreadLocalResettingRunnable.java:29) at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30) at java.base/java.lang.Thread.run(Thread.java:840) </code> Basically I need to catch the exception personality java.lang.Exception: input byte array has wrong 4 byte trailing unit, so far I know that I can catch the global exception exception, but in this case I would like to catch the one mentioned above . , since for this case it should return a custom error for this case: This is how I am currently catching my exceptions in the class: <code>public class UserProfileProcessorUserIdParamReq implements Processor { private final IValidationFieldsUserID validationFields; public UserProfileProcessorUserIdParamReq() { validationFields = new ValidationFieldsUserID(); } @Override public void process(Exchange exchange) throws Exception { String documentType; String documentNumber; String userId; String correlatorId; String tokenInfo; String userIdDecoded; try { userId = exchange.getIn().getHeader(';user_id';).toString(); /*correlatorId = exchange.getIn().getHeader(';x-correlator';).toString(); */ userIdDecoded = EncryptBase64.decrypt(userId); validateUserIdDecrypt(userIdDecoded); validationFields.validateUserId(exchange); documentType = userIdDecoded.split(';-';)[0]; documentNumber = userIdDecoded.split(';-';)[1]; validateTokenInfo(exchange,userId); } catch (RequiredValueException | NullPointerException re) { throw new RequiredValueException(';Error validando campos de entrada para UserID';); } catch (NotFoundDataException e) { throw new NotFoundDataException(e.getMessage()); } catch (PermissionDeniedException e) { throw new PermissionDeniedException(e.getMessage()); } catch (Exception e){ throw new Exception(e.getMessage()); } correlatorId= Optional.ofNullable(exchange.getIn().getHeader(';x-correlator';).toString()).map(Object::toString).orElse(';';); exchange.setProperty(';isSearchByQueryParam';,';false';); exchange.setProperty(';userId';, userIdDecoded); exchange.setProperty(';userIdEncrypt';, userId); exchange.setProperty(';correlatorId';,correlatorId); exchange.setProperty(';documentType';, documentType); exchange.setProperty(';documentNumber';, documentNumber); } </code> How can I do it here?
I had to do this with an Amazon library once too. It's not very difficult but it's a bit ugly: <code>... catch (PermissionDeniedException e) { throw new PermissionDeniedException(e.getMessage()); } catch (Exception e){ if( e.getMessage().contains(';Input byte array has wrong 4-byte ending unit';) ) throw new SpecialException(e.getMessage()); throw new Exception(e.getMessage()); } </code> In this code, we're checking to see if the string in the Exception matches your special case. If so, throw a <code>SpecialException</code> which is where you could throw an exception that indicates that the ';4-byte'; error has occurred. Note that this code is a bit fragile in that you'll need to test if you upgrade the underlying library to make sure that they haven't updated the string. And, it may not be easily internationalized as the string could be different depending on the locale. But, unfortunately, if the Camel libraries are not throwing something more specific there are limited ways to handle this.
apache-camel
Good afternoon. I am currently working with quarkus and apache camel and I need to return a controlled error for the different http codes, in the case of 404 I need to return the following message that I have configured as a variable in the application.properties:Basically my service receives a mobile number as an input parameter and what I want to do is where the value of %1 is, that is, if I pass the number 5842410000 and it does not exist, return an error like the following: <code>Resource 5842410000 does not exist </code> I know that I can get the value of the properties in my mappign class as follows: <code>private final String exceptionText = ConfigProvider.getConfig().getValue(';error.404.exceptionText';, String.class); </code> The issue is how can I make it dynamic to insert the value of the input field into the error message
You can have the <code>%s</code> placeholder in your <code>application.properties</code> file <code>error.404.exceptionText=Resource %s does not exist </code> And you can dynamically format the exceptionText with phone. <code>private final String exceptionText = ConfigProvider.getConfig().getValue(';error.404.exceptionText';, String.class);...String dynamicExceptionText = String.format(exceptionText, phoneNumber); </code> Now <code>%s</code> placeholder will have <code>phoneNumber</code> value.
apache-camel
When executing the route, the content-type header does not reach the destination. <code>restConfiguration() .host(';localhost';) .port(8082)from(';seda:my-route';) .setHeader(RestConstants.CONTENT_TYPE, constant(';application/json';)) .to(';rest:get:/docp/supply-chain2/v1/invoice-responses';) </code> I have tried to add the header from the route, using a processor and it does not work. Use apache camel constants and plain text. I have tried with the HTTP and REST component but neither has worked for me. Is there a way to force the sending of this header?
The GET method do not send the header ';Content-Type'; by default, You must have a body (different from null) and then use the getWithBody=true option to force it to be sent, so you can send the header: <code>from(';direct:start';).routeId(';hello';) .setHeader(HttpConstants.CONTENT_TYPE, constant(';application/json';)) .setBody(constant(';';)) // use this and the Content-Type will be sent //.setBody(constant(null)) // use this and the Content-Type will not be sent .to(';http://httpbin.org/anything?httpMethod=GET&;getWithBody=true';) // set getWithBody=false (the default) and the ContentType will not be sent // sorry if stating the obvious: if you use anything but GET, this is not needed .log(';${body}';); </code>
apache-camel
For Camel 3, the following configuration worked <code>camel.component.spring-rabbitmq.connection-factory=org.springframework.amqp.rabbit.connection.CachingConnectionFactory </code> to use a <code>CachingConnectionFactory</code>. With Camel 4, this fails withNo type converter available to convert from type: java.lang.String to the required type: org.springframework.amqp.rabbit.connection.ConnectionFactoryI tried to use a Bean that returns a <code>new CachingConnectionFactory()</code>, but this does not heed the <code>spring.rabbitmq.host</code> etc. configuration, and only connects to localhost. How is this fixed ?
It seems like the <code>CachingConnectionFactory</code> is the default. There is no need to configure anything.
apache-camel
I have an apache camel route that has a takes the key from a map entry (an int) and does a choice if the key is in the list. But I am getting an exception <code>.`when`(simple(';\${body.key} in [123, 456]';)) </code> Caused by: <code>org.apache.camel.language.simple.types.SimpleIllegalSyntaxException: Unexpected token 456 at location 23 ${body.key} in [123, 456] </code> Can anyone see what I'm doing wrong? I tried to replace in with 'contains'.
This worked: <code> .`when`(simple(';'[123, 456]' contains \${body.key}';)) </code>
apache-camel
I'm trying to run camel-k with jdbc locally with the following configuration. Integration DSL KamelKJdbcRouter.java: <code>import org.apache.camel.builder.RouteBuilder;// camel-k: dependency=camel:jdbc // camel-k: dependency=mvn:io.quarkus:quarkus-jdbc-postgresqlpublic class KamelKJdbcRouter extends RouteBuilder { @Override public void configure() throws Exception { from(';timer://foo?period=10000';) .setBody(constant(';SELECT data FROM test LIMIT 5 OFFSET 0';)) .to(';jdbc:default';) .to(';log:info';); }} </code> application.properties: <code>quarkus.datasource.jdbc.url=jdbc:postgresql://postgres:5432/test quarkus.datasource.username=postgresadmin quarkus.datasource.password=admin123 quarkus.datasource.db-kind=postgresql </code> Command: <code>jbang run -Dcamel.jbang.version=4.2.0 camel@apache/camel run KamelKJdbcRouter.java </code> But I get following error: <code>Caused by: java.lang.IllegalArgumentException: No default DataSource found in the registry at org.apache.camel.component.jdbc.JdbcComponent.createEndpoint(JdbcComponent.java:67) at org.apache.camel.support.DefaultComponent.createEndpoint(DefaultComponent.java:170) at org.apache.camel.impl.engine.AbstractCamelContext.doGetEndpoint(AbstractCamelContext.java:804) ... 34 more </code> It seems like quarkus build isn't kicking in and the datasource is not being created. The example works fine on k8s. I'm using camel-k with jbang with other components (like activemq) and they work fine. Do you have any idea? Thanks!
camel-jbang does not understand quarkus specific connection pools and whatnot. However this may be something we can add to camel-jbang for a common feature like databases etc. You can configure a generic datasource as a bean and let camel-jbang use that until we have something for camel-jbang OOTB. https://issues.apache.org/jira/browse/CAMEL-20681
apache-camel
I am upgrading from Apache Camel 3.20.x to 4.x.x and found that camel-swagger-java(version 3.20.x) which was supported with Camel 3 isn't supported with Camel 4. The camel-swagger-java library hasn't been upgraded to 4.x.x like camel and the latest version available is only 3.22.1. Some of the methods in CamelContext class(present in camel-api dependency) like getExtension which were available in 3.20.x and are invoked in RestSwaggerSupport class( present in camel-swagger-java) appear deprecated in CamelContext class with Camel 4.x.x versions due to which I am getting NoSuchMethodError. Issue is occurring as using the same 3.20.x version in camel-swagger-java with Camel 4.x.x Is there a way to make it work with the Camel 4 upgrade? <code>java.lang.NoSuchMethodError: 'java.lang.Object org.apache.camel.CamelContext.getExtension(java.lang.Class)' at org.apache.camel.swagger.RestSwaggerSupport.getRestDefinitions(RestSwaggerSupport.java:133) </code>
Are you maybe looking for camel-openapi-java? It was supported since Camel 3.1 and continues to be supported in 4.x - When you were used to Swagger 2.x you can see OpenAPI a bit like the successor of Swagger, but this blog entry describes it a bit better:The easiest way to understand the difference is:OpenAPI = Specification Swagger = Tools for implementing the specification So the camel component provides the OpenAPI description of your REST interface, but Swagger UI is a tool to display it in the browser and make sample requests etc.
apache-camel
I've got Camel based app (Camel 2.25.4) and I have a route as follows: <code>rest(';/example/';) ... .put(';putExample';).to(';direct:putExample';); ...from(';direct:putExample';) .onException(HttpOperationFailedException.class) .handled(true) .process(new Processor() { @Override public void process(Exchange exchange) throws Exception { HttpOperationFailedException exception = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, HttpOperationFailedException.class); if (exception.getStatusCode() == 404) { // Log, set a default message, or perform other actions // For example, set a default body exchange.getIn().setBody(';Default response for 404';); } // You could set a flag or header to indicate this exchange was handled due to a 404 exchange.getIn().setHeader(';404Handled';, true); } }) .end() .setHeader(Constants.HEADER_EMAIL, simple(';${body[email]}';)) .to(';direct:getSomeDataAndReturn404';) .choice() .when(header(';404Handled';)) // Process the exchange differently if it was handled due to a 404 .log(';Handled a 404 error. Continuing with custom logic.';) .process(exchange ->; { System.out.println(';Test';); }) .otherwise() // Continue normal processing if no 404 was encountered .log(';No 404 error. Continuing normal route.';) .process(exchange ->; { System.out.println(';Test';); }) .endChoice(); </code> ';direct:getSomeDataAndReturn404'; may return 404 if email won't be found. My problem is, that I cannot ';catch'; this 404 and continue processing (I would like to execute another route, no matter if there will be 404 or not). However, no matter what I'm I doing, this route always returns 404, without going in to any of the processors. If the email is found and there is 200 returned, everything is working fine. I've also tried ';doTry()'; but effect was the same.
TL;DR; Instead of ';to()';, I should use ';.enrich()';. More about ';enrich()'; here. Long Version I think my problem was, that I've treaded routes as a methods and I was expecting that ';to()'; is just evaluation of the method that return something. If I'm not mistaken, that is a wrong assumption. When you use ';to()'; is more like you redirect flow, and then the target is ';in charge'; of it. So it can, for example, finish it (which I belive was a problem in my case). There are some ways to prevent this (like, for example, use .onException(Exception.class).continued(true)) but that's a different approach. However, using ';.enrich()'; and a custom aggregation strategy (example is in docs in TLDR of this answer)
apache-camel
Good afternoon I am new to apache camel and I am working with a microservice using apache camel and quarkus, I am currently implementing validation of the input fields as automated as possible and in this case I want to validate the header and I want to return a 400 code and a custom response but no I manage to do it. I am implementing the line <code>clientRequestValidation(true)</code> in the DSL definition of the logic in addition to the line to validate my input parameter: <code>param().name(';x-correlator';).type(RestParamType.header).required(true).endParam() </code> With these two lines what I get is the following response:And I want an answer like this:My RestRoure code is the following: <code>@ApplicationScoped public class RestRoute extends RouteBuilder { @ConfigProperty(name = ';client.url.userProfile';) String urlUserProfile; @ConfigProperty(name = ';client.utl.getActiveSessionByIp';) String urlGetActivateSessionByIp; @ConfigProperty(name = ';path.openapi';) String pathOpenapi; @ConfigProperty(name = ';descripcion.servicio';) String descriptionService; private final IGetCurrentDateTime getCurrentDateTime; private ConfigureSsl configureSsl; private static final String SALIDA_BSS_EXCEPTION = ';Salida Microservicio IdentifyOrigin ${body}';; private static final String MSG_EXCEPTION = ';Descripcion de la Exception: ${exception.message}';; private static final String DATE_LOG = ';[${bean:BeanDate.getCurrentDateTime()}] ';; public RestRoute() { getCurrentDateTime = new GetCurrentDateTime(); TimeZone.setDefault(TimeZone.getTimeZone(';GMT-4';)); configureSsl= new ConfigureSsl(); } @Override public void configure() throws Exception { BeanDate beanDate= new BeanDate(); getContext().getRegistry().bind(';BeanDate';, beanDate); restConfiguration().bindingMode(RestBindingMode.json).dataFormatProperty(';json.in.disableFeatures';,';FAIL_ON_UNKNOWN_PROPERTIES';) .clientRequestValidation(true) .apiContextPath(pathOpenapi) .apiProperty(';api.title';,';IdentifyOrigin';) .apiProperty(';api.description';,descriptionService) .apiProperty(';api-version';,';1.0.0';) .apiProperty(';cors';,';true';); rest(';/api/';) .produces(';application/json';) .consumes(';application/json';) .post(';/identifyOrigin/v1/info';) .type(Request.class) .param().name(';x-correlator';).type(RestParamType.header).required(true).endParam() .outType(ResponseSuccess.class) .param().name(';Response';).type(RestParamType.body).description(';Parametros de Salidas';) .required(true) .endParam().to(';direct:pipeline';); from(';direct:pipeline';) .doTry() .to(';bean-validator:validateRequest';) .log(';[';+';${bean:BeanDate.getCurrentDateTime()}';+';] ';+ ';Datos de Entrada del MS: ${body}';) .process(new GetActivateSessionByIpReqProcessor()) .log('; [${bean:BeanDate.getCurrentDateTime()}] ';+';Entrada Microservicio GetActivateSessionByIp: ${exchangeProperty[getActivateSessionByIpRequest]}';) .to(configureSsl.setupSSLContext(getCamelContext(), urlGetActivateSessionByIp)) .choice() .when(header(Exchange.HTTP_RESPONSE_CODE).isEqualTo(200)) .process(new GetActivateSessionByIpResProcessor()) .log(';[';+';${bean:BeanDate.getCurrentDateTime()}';+';] ';+ ';Salida MS GetActivateSessionByIp: ${body}';) .log(';[';+';${bean:BeanDate.getCurrentDateTime()}';+';] ';+ ';PhoneNumberByIp obtenido desde MS GetActivateSessionByIp: ${exchangeProperty[phoneNumberByIp]}';) .process(new UserProfileReqProcessor()) .to(configureSsl.setupSSLContext(getCamelContext(), urlUserProfile)) .log(';[';+';${bean:BeanDate.getCurrentDateTime()}';+';] ';+ ';Datos de Salida del MS UserProfile: ${body}';) .otherwise() .process(new ApiResponseFaultProcessor()) .end() .process(new UserProfileReqProcessor()) .to(configureSsl.setupSSLContext(getCamelContext(), urlUserProfile)) .log(';[';+';${bean:BeanDate.getCurrentDateTime()}';+';] ';+ ';Datos de Salida del MS UserProfile: ${body}';) .choice() .when(header(Exchange.HTTP_RESPONSE_CODE).isEqualTo(200)) .process(new UserProfileResProcessor()) .log(';[';+';${bean:BeanDate.getCurrentDateTime()}';+';] ';+ ';UserId obtenido desde UserProfile: ${exchangeProperty[userId]}';) .process(new IdentifyOriginResProcessor()) .log(DATE_LOG+';Salida MS IdentifyOrigin: ${exchangeProperty[identifyOriginResponse]}';) .otherwise() .process(new ApiResponseFaultProcessor()) .end() .endDoTry() .doCatch(BeanValidationException.class) .process(new InvalidFormatExcepctionProcessor()) .log(DATE_LOG+MSG_EXCEPTION) .log(DATE_LOG+SALIDA_BSS_EXCEPTION) .doCatch(NotFoundDataException.class) .process(new NotFoundDataExceptionProcessor()) .log(DATE_LOG+MSG_EXCEPTION) .log(DATE_LOG+SALIDA_BSS_EXCEPTION) .doCatch(HttpHostConnectException.class) .process(new HttpHostConnectExceptionProcessor()) .log(DATE_LOG+MSG_EXCEPTION) .log(DATE_LOG+SALIDA_BSS_EXCEPTION) .doCatch(Exception.class) .process(new IdentifyOriginExceptionProcessor()) .log(DATE_LOG+MSG_EXCEPTION) .log(DATE_LOG+SALIDA_BSS_EXCEPTION); } } </code> How can I do this?
<code>from(';direct:pipeline';) .process(exchange ->; { String xCorrelator = exchange.getIn().getHeader(';x-correlator';, String.class); // Implement your validation logic here if (xCorrelator == null || xCorrelator.isEmpty()) { throw new ValidationException(';x-correlator header is missing or invalid';); } }) // Rest of your route....doCatch(ValidationException.class) .process(exchange ->; { exchange.getIn().setHeader(Exchange.HTTP_RESPONSE_CODE, 400); exchange.getIn().setBody(';Invalid header information provided';); }) .log(DATE_LOG+MSG_EXCEPTION) .log(DATE_LOG+SALIDA_BSS_EXCEPTION) // Continue with other exception handling... </code> or <code>// Custom exception handling for validation errors onException(PredicateValidationException.class) .handled(true) // Stop the exception from propagating .setHeader(Exchange.HTTP_RESPONSE_CODE, constant(400)) // Set HTTP status 400 .setBody().constant(';Invalid 'x-correlator' header value';); // Custom error message</code>
apache-camel
<code>org.xml.sax.SAXParseException; lineNumber: 4268; columnNumber: 51; cos-nonambig: ';http://camel.apache.org/schema/spring';:onFallback and ';http://camel.apache.org/schema/spring';:onFallback (or elements from their substitution group) violate ';Unique Particle Attribution';. During validation against this schema, ambiguity would be created for those two particles.      at org.apache.xerces.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source)       at org.apache.xerces.util.ErrorHandlerWrapper.error(Unknown Source)       at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)       at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)       at org.apache.xerces.impl.xs.XSConstraints.reportSchemaError(Unknown Source)       at org.apache.xerces.impl.xs.XSConstraints.fullSchemaChecking(Unknown Source)       at org.apache.xerces.impl.xs.XMLSchemaLoader.loadGrammar(Unknown Source)       at org.apache.xerces.impl.xs.XMLSchemaLoader.loadGrammar(Unknown Source)       at org.apache.xerces.jaxp.validation.XMLSchemaFactory.newSchema(Unknown Source) </code> I'm getting this error when trying to create a new schema from camel-spring.xsd after updated Camel version to 4.0.4 and Java 17 The code is this one, and the error happens in the last line: <code>import com.google.common.io.Resources;import javax.xml.XMLConstants; import javax.xml.transform.Source; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.SchemaFactory; import java.io.ByteArrayInputStream; import java.net.URL; import java.util.ArrayList; import java.util.List; public class Camel { public static void main( String[] args ) throws Exception { SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); List<Source>; tmp = new ArrayList(); String loc = ';camel-spring.xsd';; URL url = Resources.getResource(loc); byte[] bytes = Resources.toByteArray(url); StreamSource src = new StreamSource(new ByteArrayInputStream(bytes)); tmp.add(src); schemaFactory.newSchema((Source[]) tmp.toArray(new Source[tmp.size()])); } } </code> Have you ever seen this error? I have seen that up camel-spring.xsd 4.x (https://camel.apache.org/schema/spring/) on circuitBreakerDefinition element has two ';onFallBack'; elements and this is the error. When I comment one of those, I don't get an error. But I can't modify the jar, do you know if there is a way to get the schema from the xsd Camel 4.x? camel-spring.xsd
You could try setting this feature to false: <code>schemaFactory.setFeature(';http://apache.org/xml/features/validation/schema-full-checking';, false); </code> This (very old) documentation mentions that ';unique particle attribution'; is one of the checks turned off.
apache-camel
There are multiple spring boot application working on the same server. On spring boot application A there is an apache camel route that has been stopped. On spring boot application B there is a service that after it finishes it needs to start the apache camel route in application A. Is it possible to achieve this?
If you have route you need to start from any external application or service you can expose a rest-api from your Application A with rest endpoint that will start the desired route when requested. Not only will this allow you to signal Application A the route from another camel application like your Application B but from many other services as well. Since both applications are on the same server you can <code>restConfiguration().host(';localhost';)</code> to limit connections to local ones. DocumentationApache Camel Rest-dsl Apache Camel http-componentAlternative would be to use message broker like ActiveMQ artemis to pass messages between different applications using jms. I generally would avoid any solutions where one would enable disabled routes. Not only are those messy to implement but also very inflexible and hard to test. With Apache camel you'd probably need use JMX to enable disabled routes.
apache-camel
I am trying to expose <code>/management/prometheus</code> endpoint from a Camel Spring Boot application. While doing so, I observed all the requests that I trigger to the rest endpoint are getting pushed to the prometheus endpoint. E.g. PFB. The requests triggered from Postman are visible in the prometheus endpoint.Here's the request that I triggered to my endpointIs there a way I can get rid of these requests getting into the prometheus endpoint. My concern for a bigger JSON, if it keeps on pushing the requests to prometheus endpoint, heap will keep on growing and I might encounter an OOM.
I figured out the solution. Posting for anyone who could be going through the same. Just had to exclude the <code>ObservationAutoConfiguration.class</code> from the Main class. Post this I saw the requests were not getting pushed to prometheus endpoint.
apache-camel
In this code snippet I want to unzip a gzip body using Camel. According to the Camel documentation, no other dependencies are needed apart from camel-core. <code> public static void main(final String[] args) throws Exception { try (final CamelContext context = new DefaultCamelContext()) { context.addRoutes(new RouteBuilder() { @Override public void configure() { this.from(';direct:test';).unmarshal().gzipDeflater().to(';seda:test2';); } }); context.start(); context.createProducerTemplate().sendBody(';direct:test';, ';this is not gzip but it does not matter.';); Thread.currentThread().join(); } } </code> When I run the code I get this error: <code>Caused by: java.lang.IllegalArgumentException: Data format 'gzipDeflater' could not be created. Ensure that the data format is valid and the associated Camel component is present on the classpath at org.apache.camel.reifier.dataformat.DataFormatReifier.createDataFormat(DataFormatReifier.java:279) at org.apache.camel.reifier.dataformat.DataFormatReifier.getDataFormat(DataFormatReifier.java:152) at org.apache.camel.reifier.dataformat.DataFormatReifier.getDataFormat(DataFormatReifier.java:112) at org.apache.camel.reifier.UnmarshalReifier.createProcessor(UnmarshalReifier.java:35) at org.apache.camel.reifier.ProcessorReifier.makeProcessor(ProcessorReifier.java:870) at org.apache.camel.reifier.ProcessorReifier.addRoutes(ProcessorReifier.java:610) at org.apache.camel.reifier.RouteReifier.doCreateRoute(RouteReifier.java:213) ... 11 more </code> The error message says I need another dependency, but the Camel documentation says I don't need one. So how is this supposed to work?
Ok, the solution is to add the camel-zip-deflater jar. The GZip Deflater doc is outdated.
apache-camel
I'm new to camel and I'm trying to use property placeholders in a (YAML) route. However I can only access them if I create a custom CamelConfiguration, if I don't use it, it complains that it cannot find such property. I know camel is reading the application.properties file because its getting its own configuration from there, but somehow the rest of the properties are not published into the context. I'm running camel locally with camel-main. My route is below. <code>- route: id: route-1579 from: id: from-1606 uri: timer parameters: period: ';0'; timerName: start steps: - bean: id: ReadFiles method: getExports({{azure.delta_path}},{{azure.full_path}}) ref: reader - loop: id: loop-2f61 steps: - log: id: log-6422 logName: loggy message: ${body} expression: simple: id: simple-f05c expression: ${body.size()} </code>
Add a PropertiesComponent Bean like so: <code>- beans: - builderMethod: ';'; constructors: {} name: properties properties: location: classpath:/application.properties type: org.apache.camel.component.properties.PropertiesComponent </code>
apache-camel
I have an apache camel route that will be started by a process. Once the route is started it will process all of the messages on the queue. I want to stop the route once the queue is emptied out, so is it possible to do it in camel and maybe provide a short example.
This is the approach that worked for me: Route configuration: <code>from(';direct:start';) .routeId(';testRoute';) .setHeader(';shutDownRoute';).method(myBean) // you business logic .choice() when(header(';shutDownRoute';).isEqualTo(true)) .toD(';controlbus:route?async=true&;routeId=${routeId}&;action=stop';) end(); </code> MyBean.java <code>@Service public class MyBean { private JmsTemplate jmsTemplate; private String queueName; @Autowired public MyBean (JmsTemplate jmsTemplate, String queueName) { this.jmsTemplate = jmsTemplate; this.queueName = queueName; } private Message browseMessageFromQueue(String queueName) { BrowserCallback<Message>; browserCallback = (session, browser) ->; { Enumeration<?>; enumeration = browser.getEnumeration(); if(enumeration.hasMoreElements()) { return (Message) enumeration.nextElement(); } return null; }; return jmsTemplate.browse(queueName, browserCallback); } @Handler public boolean isLastMessage() { Message message = browseMessageFromQueue(queueName); return message == null; } } </code>
apache-camel
This question is regarding Apache camel SMPP and GSM-7 using camel-smpp-starter 4.2.0 Our SMSC sends sms messages to our application using SMSC Default Alphabet according to the header. This is according to SMSC docs GSM-7. When I try to set encoding to GSM-7. it throws an error. I can see that the code uses String(body, ) to decode the body. I'm wondering if anyone has used camel smpp with GSM-7 and could provide some details <code>camel: springboot: main-run-controller: true component: enabled: true smpp: encoding: GSM-7 </code> <code> 2024-01-29T07:33:26.154+01:00 WARN 11636 --- [pool-2-thread-1] o.a.camel.component.smpp.SmppConsumer : Cannot create exchange. This exception will be ignored.. Caused by: [java.io.UnsupportedEncodingException - GSM-7] java.io.UnsupportedEncodingException: GSM-7 at java.base/java.lang.String.lookupCharset(String.java:861) ~[na:na] at java.base/java.lang.String.<init>;(String.java:1401) ~[na:na] at org.apache.camel.component.smpp.SmppUtils.decodeBody(SmppUtils.java:372) </code>
Answering this myself: the apache camel smpp component doesnt support gsm-7, it only supports formats installed in the jvm out-of-the-box. What we did was to change the config of the smsc to send messages in latin1 format.
apache-camel
I'm trying to write simple unit test verifying if Camel route is configured properly and redelivering attempts were truly made. I have this route builder implementation: <code>class LocalEndpoint extends RouteBuilder { private final CamelContext camelContext; private final String targetEndpoint; public LocalEndpoint(CamelContext camelContext, String targetEndpoint) { super(camelContext); this.camelContext = camelContext; this.targetEndpoint = targetEndpoint; } @Override public void configure() { onException(TargetServerErrorException.class) .maximumRedeliveries(2) .redeliveryDelay(2500) .retryAttemptedLogLevel(LoggingLevel.WARN) .process(exchange ->; { // bellow equals 2 int redeliveryAttempts = exchange.getIn().getHeader(Exchange.REDELIVERY_COUNTER, Integer.class); }) .stop(); from(';direct:local-endpoint';) .marshal() .json() .to(targetEndpoint) .choice() .when(header(HTTP_RESPONSE_CODE).isEqualTo(';500';)) .throwException(new TargetServerErrorException()) .endChoice() .end(); } public void callTarget(String objectId) { camelContext.createProducerTemplate().sendBody(';direct:local-endpoint';, Map.of(';objectId';, objectId)); } } </code> and I've came up with bellow test: <code>@TestInstance(TestInstance.Lifecycle.PER_CLASS) class LocalEndpointTest { private static final String MOCK_ENDPOINT = ';mock:target-endpoint';; CamelContext camelContext; MockEndpoint mockEndpoint; LocalEndpoint localEndpoint; @BeforeAll void beforeAll() throws Exception { camelContext = new DefaultCamelContext(); localEndpoint = new LocalEndpoint(camelContext, MOCK_ENDPOINT); camelContext.addRoutes(localEndpoint); camelContext.start(); mockEndpoint = camelContext.getEndpoint(MOCK_ENDPOINT, MockEndpoint.class); } @AfterAll void afterAll() { camelContext.stop(); } @Test void testCallTarget_serverError() throws InterruptedException { // given mockEndpoint.returnReplyHeader(Exchange.HTTP_RESPONSE_CODE, new ConstantExpression(';500';)); mockEndpoint.expectedMessageCount(3); // gives: AssertionError: mock://target-endpoint Received message count. Expected: <3>; but was: <1>; mockEndpoint.expectedHeaderReceived(Exchange.REDELIVERY_COUNTER, 2); // gives: AssertionError: mock://target-endpoint No header with name CamelRedeliveryCounter found for message: 0 // when Throwable thrown = catchThrowable(() ->; localEndpoint.callTarget(';object-id';)); // then mockEndpoint.assertIsSatisfied(); assertThat(thrown) .cause().isInstanceOf(TargetServerErrorException.class) .hasMessageContaining(';received:';, 500); } } </code> I've expected to see value 3 in message count assertion, but to my surprise it was 1. I assume this issue and lack of Camel headers in <code>mockEndpoint</code>'s exchange may be related to separated <code>onException(Exception.class)</code> block in route definition and different context, but I'm not sure as I don't know Camel well enough. Is there any way to verify re-delivery attempts in such a simple test? Or at least is it possible to get somehow Camel headers (like <code>CamelRedeliveryCounter</code>) within <code>mockEndpoint</code>? Camel version: 4.3.0 Edit: I've found this info: https://camel.apache.org/manual/faq/how-do-i-retry-processing-a-message-from-a-certain-point-back-or-an-entire-route.html Issue may be caused due to:By default Apache Camel will perform any redelivery (retry) attempts from the point of failureI've added <code>.errorHandler(noErrorHandler())</code> and redefined the route a bit: <code>onException(TargetServerErrorException.class) .maximumRedeliveries(2) .redeliveryDelay(2500) .retryAttemptedLogLevel(LoggingLevel.WARN) .process(exchange ->; { int redeliveryAttempts = exchange.getIn().getHeader(Exchange.REDELIVERY_COUNTER, Integer.class); // equals 2 });from(';direct:local-endpoint';) .marshal() .json() .to(';direct:retryable';) .end();from(';direct:retryable';) .errorHandler(noErrorHandler()) .to(targetEndpoint) .choice() .when(header(HTTP_RESPONSE_CODE).isEqualTo(';500';)) .throwException(new TargetServerErrorException()) .endChoice() </code> but still it doesn't work - I'm getting: <code>java.lang.AssertionError: mock://target-endpoint Received message count. Expected: <3>; but was: <1>; </code>
It turned out that the already mentioned solution from FAQ does work fine and is exactly what I was looking for. I also had some garbage in tests and after cleaning them, and adding <code>mockEndpoint.reset()</code> everything started to pass successfully.
apache-camel
Background: I am a python developer &; have never done Java. Camel Salesforce Source Connector: v3.20.6 ( I have tried 3.21.0 &; 4.0.0 and I'm facing the same issue) Kafka: v3.6.1 Issue: Trying to create CamelSalesforcesourceSourceConnector for my kafka instance and it fails with the exception ResolveEndpointFailedException. I have tried a few variations of creating the connector using Kafka's REST API. Variation 1: { ';name';: ';sf-source-connector';, ';config';: { ';tasks.max';:';1';, ';connector.class';:';org.apache.camel.kafkaconnector.salesforcesource.CamelSalesforcesourceSourceConnector';, ';key.converter';:';org.apache.kafka.connect.storage.StringConverter';, ';value.converter';:';org.apache.kafka.connect.storage.StringConverter';, ';camel.kamelet.salesforce-source.query';: ';SELECT * FROM Account';, ';camel.kamelet.salesforce-source.topicName';: ';/data/AccountChangeEvent';, ';camel.kamelet.salesforce-source.loginUrl';: ';https://login.salesforce.com/';, ';camel.kamelet.salesforce-source.clientId';: ';';, ';camel.kamelet.salesforce-source.clientSecret';: ';';, ';camel.kamelet.salesforce-source.userName';: ';';, ';camel.kamelet.salesforce-source.password';: ';';, ';camel.kamelet.salesforce-source.notifyForOperationCreate';: ';true';, ';camel.kamelet.salesforce-source.notifyForOperationUpdate';: ';true';, ';camel.kamelet.salesforce-source.notifyForOperationDelete';: ';true';, ';camel.kamelet.salesforce-source.notifyForOperationUndelete';: ';true';, ';camel.source.endpoint.rawPayload';: ';true';, ';camel.kamelet.salesforce-source.operation';: ';subscribe';, ';topics';: ';camelsfstream'; } } Failure Exception Summary - Starts with - org.apache.kafka.connect.errors.ConnectException: Failed to create and start Camel context \tat org.apache.camel.kafkaconnector.CamelSourceTask.start(CamelSourceTask.java:184) Ends with - Caused by: java.lang.IllegalArgumentException: /data/AccountChangeEvent \tat org.apache.camel.component.salesforce.internal.OperationName.fromValue(OperationName.java:128) \tat org.apache.camel.component.salesforce.SalesforceComponent.createEndpoint(SalesforceComponent.java:303) \tat org.apache.camel.support.DefaultComponent.createEndpoint(DefaultComponent.java:171) \tat org.apache.camel.impl.engine.AbstractCamelContext.doGetEndpoint(AbstractCamelContext.java:975) Key Issue - IllegalArgumentException: /data/AccountChangeEvent Variation 2 - In my connector I replaced the topic name: ';camel.kamelet.salesforce-source.topicName';: ';subscribe:/data/AccountChangeEvent'; The exception starts with Failed to create and start Camel context, but the final exception changes to - due to: There are 1 parameters that couldn't be set on the endpoint. Check the uri if the parameters are spelt correctly and that they are properties of the endpoint. Unknown parameters=[{operationName=subscribe}] I am unable to overwrite the endpoint url to test the above variation without the operationName and I am also aware that subscribe is the default. So even if I remove that property from the json, it makes no difference. On another note the endpoint starts with local-salesforce-1:// the # increments - is that right? I couldnt find any property to change this. I imagine it gets replaced eventually. Raised github issue - https://github.com/apache/camel-kafka-connector/issues/1587
Found a workaround that is described in my own github issue as a comment - https://github.com/apache/camel-kafka-connector/issues/1587#issuecomment-1903530176 In summary, moved to connector version 3.18.x, before the operationName was added as a kamelet property and added the operation as a prefix in the topic. Did face a few more issues and its resolution is described in my github comment (linked above). Edit - Another issue: The received message did not contain the record-id / sObjectId of the record in the payload nor in the header. A workaround for this converter v3.18.x has been described at https://github.com/apache/camel-kafka-connector/issues/1592#issuecomment-1905444125 Permanent fix for both the issues (operationName &; no recordId in message) has been added to the release milestone and can be tracked here -https://github.com/apache/camel-kamelets/issues/1841 https://github.com/apache/camel-kamelets/issues/1843
apache-camel
I'm using the Quartz component from Apache Camel to run some scheduled routes. I would like to configure the JDBC JobStore for the scheduler, and was able to set the necessary properties in a <code>quartz.properties</code> file, as shown below. <code>org.quartz.jobStore.useProperties = true org.quartz.jobStore.dataSource=myDataSource org.quartz.jobStore.tablePrefix = II_QRTZ_org.quartz.dataSource.myDataSource.driver = com.ibm.db2.jcc.DB2Driver org.quartz.dataSource.myDataSource.URL = url org.quartz.dataSource.myDataSource.user = example-user org.quartz.dataSource.myDataSource.password = example-pwd </code> However, we need to set different data sources/credentials based on different server environments (dev vs test vs prod). I can't seem to find a way to dynamically set the data source from the properties file. We already had a datasource bean that would connect to the correct database based on the environment, and so I tried referencing to that after annotating it with the <code>@QuartzDataSource</code> annotation. Ideally this would have been the cleanest solution. For example, <code>DataSourceConfig.java @Bean(name=';myDataSource';) @QuartzDataSource @ConfigurationProperties(prefix=';org.quartz.mydatasource';) @Autowired public DataSource myDataSource(@Qualifier(';applicationProps';) BasePropReader applicationProperties) { String connectionString = (String) applicationProperties.get(';spring.datasource.connection.url';); return buildDataSource(applicationProperties, ';example-user';, ';example-pwd';, ';com.ibm.db2.jcc.DB2Driver';, connectionString); }/////////////////////////quartz.propertiesorg.quartz.jobStore.useProperties = true org.quartz.jobStore.dataSource=myDataSource org.quartz.jobStore.tablePrefix = II_QRTZ_ </code> In our web applications we did something similar as the above, where in the quartz properties file we could refer to data sources that were already configured by environment by a JNDI url. For example: <code>org.quartz.jobStore.useProperties = true org.quartz.jobStore.dataSource=myDataSource org.quartz.jobStore.tablePrefix = II_QRTZ_org.quartz.dataSource.myDataSource.jndiURL=java:/MYDATASOURCE </code> We also tried setting the properties from <code>application.properties</code> but that didn't work - I suspect because we're using the Quartz component from Camel. I've tried reading up on reading environment variables from the properties file itself (via this thread), but all the variables I read end up as empty strings. Is this even possible via Apache Camel's Quartz? Ideally we would like to continue using Camel as it saves us a lot of refactoring. EDIT: I'm also trying to configure the quartz component by defining it as a bean in the context xml file and then passing a quartz property file based on the environment/spring active profile, but the quartz component doesn't seem to be picking up on that either. for example: <code> <bean id=';quartz'; class=';org.apache.camel.component.quartz.QuartzComponent';>; <property name=';propertiesFile'; value=';org/quartz/quartz-dev.properties';/>; </bean>; </code>
I ended up creating a <code>QuartzConfig.java</code> file. From there I created the <code>quartz</code> bean I loaded the easily configurable properties with my existing properties file, and then sourced the environment/secret properties from code. It went something like this <code> @Bean(';quartz';) public QuartzComponent quartzComponent() { QuartzComponent quartzComponent = new QuartzComponent(); Properties quartzPropertiesObj = quartzProperties.getProperties(); String env = ';dev';; // however you get your environment // applicationProperties was an instance of our class that allowed us to get our secrets by environment quartzPropertiesObj.setProperty(';org.quartz.dataSource.dataSourceDB2.URL';, applicationProperties.get(';spring.datasource.connection.url';).toString()); quartzPropertiesObj.setProperty(';org.quartz.dataSource.dataSourceDB2.user';, applicationProperties.get(';user'; + env).toString()); quartzPropertiesObj.setProperty(';org.quartz.dataSource.dataSourceDB2.password';, applicationProperties.get(';pwd'; + env).toString()); quartzComponent.setProperties(quartzPropertiesObj); LOG.info(';Quartz Config: Quartz properties file loaded into quartz component.';); return quartzComponent; } </code>
apache-camel
I am implementing a redelivery policy for ActiveMQ Classic, and I configured the destination so my message is sent to a different queue after the maximum deliveries is reached, but my message is lost and not sent to the other queue. <code>RedeliveryPolicy redeliveryPolicy = new RedeliveryPolicy(); redeliveryPolicy.setInitialRedeliveryDelay(5000); redeliveryPolicy.setRedeliveryDelay(10000); redeliveryPolicy.setBackOffMultiplier(2); redeliveryPolicy.setMaximumRedeliveries(2); redeliveryPolicy.setUseExponentialBackOff(true); redeliveryPolicy.setQueue(';swift_messages_out';); redeliveryPolicy.setDestination(new ActiveMQQueue(';swift_messages_out.DLQ';));ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(System.getenv(SwiftWriterProperties.MQ_URI)); connectionFactory.setRedeliveryPolicy(redeliveryPolicy);JmsTransactionManager transactionManager = new JmsTransactionManager(); transactionManager.setConnectionFactory(connectionFactory); transactionManager.setRollbackOnCommitFailure(true); registry.put(';jmsTransactionManager';, transactionManager);CamelContext context = new DefaultCamelContext(registry);ActiveMQComponent activemqComponent; try { String brokerUrl = System.getenv(SwiftWriterProperties.MQ_URI); activemqComponent = ActiveMQComponent.activeMQComponent(brokerUrl); activemqComponent.setDeliveryPersistent(true); activemqComponent.setTransacted(true); activemqComponent.setCacheLevelName(';CACHE_CONSUMER';); activemqComponent.setTransactionManager(transactionManager); activemqComponent.setConnectionFactory(connectionFactory); context.addComponent(';jms';, activemqComponent); } catch (Exception e) { log.error(e.getLocalizedMessage()); throw new KantoxException(KantoxExceptionType.FATAL_ERROR, e.getLocalizedMessage()); } </code>
You cannot define DLQ configurations on the client side, the broker must be configured appropriately for the behavior you are seeking. The <code>setDestination</code> and <code>setQueue</code> calls you are using is an API that exists there merely because the policy class are shared between the client and broker, however the Broker is the only user of that class that acts on destination settings. The RedeliveryPolicy when set on the client applies to each consumer on the client and controls client side redelivery options such as maximum times a redelivery will be attempted
apache-camel
Apache Artemis: 2.31.2 Spring-boot : 2.7.18 Apache Camel: 3.22.0I have a question about Camel shared durable subscription in ActiveMQ Artemis. I have migrated from ActiveMQ Classic VirtualTopics, and I have the following configuration in my broker: <code><address name=';VirtualTopic.ccncsi.fromEurope';>; <multicast>; <queue name=';Consumer.dispatcher.VirtualTopic.ccncsi.fromEurope';/>; <queue name=';Consumer.ccncsiaudit.VirtualTopic.ccncsi.fromEurope';/>; <queue name=';Consumer.ccncsigateway.VirtualTopic.ccncsi.fromEurope';/>; </multicast>; </address>; </code> I am trying to use the JMS endpoint to connect to the address <code>VirtualTopic.ccncsi.fromEurope</code> and subscription name <code>Consumer.dispatcher.VirtualTopic.ccncsi.fromEurope</code> with the endpoint <code>jms:topic:VirtualTopic.ccncsi.fromEurope?subscriptionName=Consumer.dispatcher.VirtualTopic.ccncsi.fromEurope&;subscriptionDurable=true&;subscriptionShared=true</code> inspired by this thread on Stack Overflow. However, when the route is deployed and given enough rights the endpoint creates a new queue on the address with the dots (<code>.</code>) escaped (i.e. <code>Consumer\.dispatcher\.VirtualTopic\.ccncsi\.fromEurope</code>) next to the existing one (i.e. <code>Consumer.dispatcher.VirtualTopic.ccncsi.fromEurope</code>) defined in <code>broker.xml</code>. I need to keep this consumer queue name because older clients connect through WebLogic and Openwire protocol using the VirtualTopic mapping.In that configuration I can observe that there is a consumer on the queue <code>Consumer\.dispatcher\.VirtualTopic.ccncsi\.fromEurope</code> but I was expecting my endpoint to consume from the existing queue: <code>Consumer.dispatcher.VirtualTopic.ccncsi.fromEurope</code> I could not workout if the culprit was Camel or Artemis, but when <code>org.apache.activemq.artemis.core.protocol.core.ServerSessionPacketHandler#session.createSharedQueue(request.toQueueConfiguration());</code> is called, and the request (<code>org.apache.activemq.artemis.core.protocol.core.Packet</code>) is transformed in a <code>QueueConfiguration</code>, I can see that dots are already escaped. Is this normal behaviour?
This behavior is expected. The first thing to note here is that the name of the subscription queue (i.e. <code>Consumer\.dispatcher\.VirtualTopic\.ccncsi\.fromEurope</code> in this case) is an implementation detail under the broker's control. For unshared, durable subscriptions the broker will compose the subscription queue name with the client ID and the subscription name separated by a dot character (<code>.</code>). Since the dot character is a separator the broker escapes any existing dots in the client ID and subscription name. For shared durable subscriptions the client ID is left out and only the subscription name is used, but the broker still escapes the dots. That said, you can still get the behavior you want by using the fully qualified queue name in your Camel route, e.g.: <code>jms:queue:VirtualTopic.ccncsi.fromEurope::Consumer.dispatcher.VirtualTopic.ccncsi.fromEurope </code> I'm not super familiar with Camel so the extra colons in there (i.e. <code>::</code>) may need to be escaped, but hopefully you get the idea. Using the FQQN will allow you to create a consumer on the queue that will share the messages with the other Virtual Topic consumers in your environment.
apache-camel
I have created Simple JBossFUSE spring boot application with following dependencies <code><?xml version=';1.0'; encoding=';UTF-8';?>; <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/xsd/maven-4.0.0.xsd';>; <modelVersion>;4.0.0</modelVersion>; <groupId>;sample.fuse</groupId>; <artifactId>;sample-FUSE</artifactId>; <version>;0.0.1-SNAPSHOT</version>; <packaging>;war</packaging>; <name>;springboot-camel-restdsl-api</name>; <description>;Camel SpringBoot REST API Example with REST DSL</description>; <parent>; <groupId>;org.springframework.boot</groupId>; <artifactId>;spring-boot-starter-parent</artifactId>; <version>;1.5.9.RELEASE</version>; <relativePath />; <!-- lookup parent from repository -->; </parent>; <properties>; <project.build.sourceEncoding>;UTF-8</project.build.sourceEncoding>; <project.reporting.outputEncoding>;UTF-8</project.reporting.outputEncoding>; <java.version>;1.8</java.version>; <start-class>;sample.fuse.UrarepSpringBootApplication</start-class>; </properties>; <dependencies>; <dependency>; <groupId>;org.springframework.boot</groupId>; <artifactId>;spring-boot-starter-web</artifactId>; <exclusions>; <exclusion>; <groupId>;org.apache.tomcat.embed</groupId>; <artifactId>;tomcat-embed-websocket</artifactId>; </exclusion>; </exclusions>; </dependency>; <dependency>; <groupId>;org.springframework.boot</groupId>; <artifactId>;spring-boot-starter-data-jpa</artifactId>; </dependency>; <dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-spring-boot-starter</artifactId>; <version>;2.19.0</version>; </dependency>; <dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-servlet-starter</artifactId>; <version>;2.19.0</version>; </dependency>; <dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-jackson</artifactId>; <version>;2.19.0</version>; </dependency>; <dependency>; <groupId>;javax</groupId>; <artifactId>;javaee-api</artifactId>; <version>;7.0</version>; </dependency>; <dependency>; <groupId>;com.fasterxml.jackson.core</groupId>; <artifactId>;jackson-databind</artifactId>; </dependency>; <dependency>; <groupId>;com.ibm.mq</groupId>; <artifactId>;mq-jms-spring-boot-starter</artifactId>; <version>;2.3.2</version>; </dependency>; <dependency>; <groupId>;com.ibm.mq</groupId>; <artifactId>;com.ibm.mq.allclient</artifactId>; <version>;9.2.0.0</version>; </dependency>; <dependency>; <groupId>;org.springframework.boot</groupId>; <artifactId>;spring-boot-starter-artemis</artifactId>; </dependency>; <dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-quartz</artifactId>; <version>;2.13.0</version>; </dependency>; </dependencies>; <build>; <plugins>; <plugin>; <groupId>;org.springframework.boot</groupId>; <artifactId>;spring-boot-maven-plugin</artifactId>; </plugin>; </plugins>; </build>;</project>; </code> Then I created simple RouteBuilder with following content <code>package sample.fuse.routebuilder;import com.fasterxml.jackson.core.JsonProcessingException; import org.apache.camel.Exchange; import org.apache.camel.LoggingLevel; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.model.rest.RestBindingMode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import sample.fuse.process.*;import javax.ws.rs.core.MediaType;@Component public class MyRouteBuilder extends RouteBuilder { static Logger LOG = LoggerFactory.getLogger(MyRouteBuilder.class); @Autowired TestProcessor testProcessor; @Override public void configure() throws Exception { from(';quartz://seasonParkingProcessorCron?cron=10+*+*+*+*+?&;trigger.timeZone=America/Chicago&;job.name=seasonParkingProcessorCron';) .log(LoggingLevel.INFO, ';seasonParkingProcessorCron job kicked off';) .process(testProcessor); } } </code> Sample processor have following content. <code>package sample.fuse.process;import org.apache.camel.Exchange; import org.apache.camel.Processor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; import sample.fuse.repository.MevEhtVideoImagesRepository;import java.util.Calendar;@Service @Component public class TestProcessor implements Processor { static Logger LOG = LoggerFactory.getLogger(TestProcessor.class); @Autowired Environment environment; @Autowired private MevEhtVideoImagesRepository mevEhtVideoImagesRepository; public TestProcessor(){ } @Override public void process(Exchange exchange) throws Exception { String body= (String) exchange.getIn().getBody(); LOG.info(';TestProcessor Called with exchange: '; + body); System.out.println(';AAAAAAAAAAAAAa';); exchange.getOut().setBody(body+'; ';+ Calendar.getInstance().getTime()); }}</code> I'm expecting to call my Processor method every 10 seconds and print the log. However its giving following error on the log.11:58:10,013 WARN [org.apache.camel.component.quartz.QuartzEndpoint] (DefaultQuartzScheduler-camel-1_Worker-1) Cannot execute Quartz Job with context: JobExecutionContext: trigger: 'Camel.seasonParkingProcessorCron job: DEFAULT.seasonParkingProcessorCron fireTime: 'Thu Dec 21 11:58:10 SGT 2023 scheduledFireTime: Thu Dec 21 11:58:10 SGT 2023 previousFireTime: 'null nextFireTime: Thu Dec 21 11:59:10 SGT 2023 isRecovering: false refireCount: 0 because processor is not started: RoundRobinLoadBalancerAnyone else experience this kind of error?
You have to use same version of the camel-core version for the camel-quartz. But in your pom file camel-core and camel-quartz versions should be matched. Your camel-quartz dependency in pom file should be updated as following <code> <dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-quartz</artifactId>; <version>;2.19.0</version>; </dependency>; </code> Then your MyRouteBuilder class configure method content need to changed as below. <code> from(';quartz://seasonParkingProcessorCron?cron=10+*+*+*+*+?';) .log(LoggingLevel.INFO, ';seasonParkingProcessorCron job kicked off';) .process(testProcessor); </code> Hope this will help to resolve your issue.
apache-camel
For context: I am currently working with Apache Camel to do some integration tasks. I compile the code with Maven which gives me bundles I install in my Apache Karaf instance (v. 4.4.1). On top of that I also have some XML files I put into the deploy folder. My actual question is that after developing locally on my computer, what is considered best practice to transfer the Apache Karaf instance with its content to a production server? I have tried transfering files which works fine (copy-pasting the Apache Karaf folder). Note: I am using Git for versioning and have different builds locally. I don't want to use Docker or other containerization methods. Best Regards
Karaf is very flexible. In my humble opinion, I prefer generating a Karaf custom distribution that already contains all my bundles or features with all the dependencies. You can create your custom distribution to include your XML files or any extra configuration file. Finally, the end user takes your custom distribution, usually in the form of a zip file, and unzips it on the server to launch the application as a regular application or service. Apache Unomi works in this way: https://unomi.incubator.apache.org/. If you want to see an example of a custom distribution, take a look at these links: <code>https://github.com/apache/karaf/tree/main/examples/karaf-docker-example https://github.com/yupiik/esb </code> Another possible alternative is to have an instance of Karaf already configured on your server and deploy your application as a KAR file. The KAR files can include bundles and/or features and all the dependencies required. You can deploy the KAR file by moving it to the /deploy folder.
apache-camel
I'm currently working on an Apache Camel project without Spring Boot, and I'm facing challenges with creating a route that handles form data. I've encountered a JsonParseException issue that I'm struggling to resolve. Problem: I'm trying to create a Camel route that receives form data and uploads it to a downstream service. However, I'm encountering the following error:2023-12-11T15:51:33,380 ERROR [XNIO-1 task-6] : Failed delivery for (MessageId: AFFA0D62E217B39-0000000000000002 on ExchangeId: AFFA0D62E217B39-0000000000000002). Exhausted after delivery attempt: 1 caught: com.fasterxml.jackson.core.JsonParseException: Unexpected character ('-' (code 45)) in numeric value: expected digit (0-9) to follow minus sign, for valid numeric value.Class: <code>public class PageUpload extends RouteBuilder {@Override public void configure() throws Exception { String URL = ';some link';; restConfiguration() .component(';servlet';) .bindingMode(RestBindingMode.auto) .dataFormatProperty(';prettyPrint';, ';true';); rest(';/pageUpload';) .post() .description(';IG API to upload file in ImageRight';) .id(';pageUpload';) .consumes(';multipart/form-data';) .type(IRPageUploadRequestPayload.class) .produces(APPLICATION_JSON) .route() .to(PAGE_UPLOAD) .endRest(); from(PAGE_UPLOAD) .routeId(this.getClass().getSimpleName()) .unmarshall().mimeMultipart() .process(new TokenProcessor()) // token processor for bearer token gen .toD(URL + BRIDGE_ENDPOINT) .log(';Azure Response Body: ${body}';) .end(); } } </code> Payload Class (IRPageUploadRequestPayload): <code>@Getter @Setter public class IRPageUploadRequestPayload { @JsonProperty(';DocumentType';) private String DocumentType; @JsonProperty(';FileNumber';) private String FileNumber; @JsonProperty(';PolicyEffectiveDate';) private String PolicyEffectiveDate; @JsonProperty(';Content';) private File Content; @JsonProperty(';Description';) private String Description; @JsonProperty(';UserId';) private String UserId; @JsonProperty(';Username';) private String Username; } </code> Question: What could be causing the JsonParseException error in this scenario, and how can I ensure that my Apache Camel route correctly handles form data without attempting to parse it as JSON? Additional Information: I'm trying to consume the route from Swagger. I've verified that the Content-Type header is set to multipart/form-data. I've included the TokenProcessor for bearer token generation. I appreciate any insights or suggestions to resolve this issue. Thank you!
You can turn off binding mode.bindingMode(RestBindingMode.auto)to.bindingMode(RestBindingMode.off)
apache-camel
We have scenario where we deliver our Camel application as jar to customer, and allow customer to create customisations to it, in some scenarios they might want to replace node in camel route, Is it advisable to use AdviceWith in this scenario, or is its use only meant for testing? I was able to use AdviceWith to replace route for non-testing purpose by extending EventNotifierSupport's notify method
Advice with is only intended for testing. And its feature and design is for testing purposes only. However you can of course do anything you like with Camel. Maybe what you want to do can be archived in another way, as advice with is using existing functionality in the camel-api that you could look at using directly also.
apache-camel
Good morning. Currently I am developing an API in Apache Camel in which I have to use queryParameters for the query and some parameters may be mandatory and others not, so I need to handle in case I don't send the parameter have some way to handle the nullPointerException, I was using Optional However, I don't know if I'm using it incorrectly, but I'm not getting the error: Currently I am using the following line that in theory if it receives a null value, it would return an empty optional, however, I get an error: <code>Optional<String>; optionalServices= Optional.ofNullable(exchange.getIn().getHeader(';services';).toString()); </code> Exception <code>Stacktrace ---------------------------------------------------------------------------------------------------------------------------------------: java.lang.NullPointerException: Cannot invoke ';Object.toString()'; because the return value of ';org.apache.camel.Message.getHeader(String)'; is null at org.tmve.customer.ms.processor.UserProfileProcessorQueryParamReq.process(UserProfileProcessorQueryParamReq.java:35) at org.apache.camel.support.processor.DelegateSyncProcessor.process(DelegateSyncProcessor.java:65) at org.apache.camel.impl.engine.CamelInternalProcessor.process(CamelInternalProcessor.java:392) at org.apache.camel.processor.Pipeline$PipelineTask.run(Pipeline.java:104) at org.apache.camel.impl.engine.DefaultReactiveExecutor$Worker.schedule(DefaultReactiveExecutor.java:181) at org.apache.camel.impl.engine.DefaultReactiveExecutor.scheduleMain(DefaultReactiveExecutor.java:59) at org.apache.camel.processor.Pipeline.process(Pipeline.java:165) at org.apache.camel.impl.engine.CamelInternalProcessor.process(CamelInternalProcessor.java:392) at org.apache.camel.component.platform.http.vertx.VertxPlatformHttpConsumer.lambda$handleRequest$2(VertxPlatformHttpConsumer.java:201) at io.vertx.core.impl.ContextBase.lambda$null$0(ContextBase.java:137) at io.vertx.core.impl.ContextInternal.dispatch(ContextInternal.java:264) at io.vertx.core.impl.ContextBase.lambda$executeBlocking$1(ContextBase.java:135) at org.jboss.threads.ContextHandler$1.runWith(ContextHandler.java:18) at org.jboss.threads.EnhancedQueueExecutor$Task.run(EnhancedQueueExecutor.java:2449) at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1478) at org.jboss.threads.DelegatingRunnable.run(DelegatingRunnable.java:29) at org.jboss.threads.ThreadLocalResettingRunnable.run(ThreadLocalResettingRunnable.java:29) at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30) at java.base/java.lang.Thread.run(Thread.java:840) </code> This is how I am testing from postman when it does not send the value:In this case, how can I handle the value of the Query Parameters if it is not sent?
According to the error log, it is , <code>Message.getHeader(String)</code> returns null. Your statement could be corrected as the following. <code>Optional<String>; optionalServices= Optional.ofNullable(exchange.getIn().getHeader(';services';)) .map(Object::toString) </code> If I explain the above in multiple steps. <code>Optional<Object>; optObj = Optional.ofNullable(exchange.getIn().getHeader(';services';)); Optional<String>; optStr = optObj.map(obj ->; obj.toString()); </code> So, the function (<code>obj ->; obj.toString()</code>) within <code>Optional.map()</code> is called only when Optional has a value.
apache-camel
I have a process like this to send some queries by body to the next process: <code>.process(exchange ->; { List<GlossaryDTOResponse[]>; glossaries = exchange.getIn().getBody(List.class); List<String>; queries = new ArrayList<>;(); queries.add(';countries=AF&;planttypes=AA&;status=DD&;language=en-EN&;pagesize=1';); queries.add(';countries=BF&;planttypes=AA&;status=DB&;language=en-EN&;pagesize=1';); List<ActivityIssuesDTO>; responses = new ArrayList<>;(); // just to send an empity response array to create the final result Util.setProperty(exchange, ';response';, responses); exchange.getIn().setBody(queries); }) </code> And then i split the body to read each body element: <code>.split(body()) </code> Then i read the body in each element and send it by HTTP query to a microservice: <code>.process(exchange ->; { List<GlossaryDTOResponse>; glossaryDTOResponses = exchange.getIn().getBody(List.class); List<ActivityIssuesDTO>; responses = exchange.getProperty(';response';, List.class); Util.setProperty(exchange, ';response';, responses); exchange.getIn().setHeader(Exchange.HTTP_QUERY, glossaryDTOResponses.get(0)); }) .toD(serviceUtils.getActivityEndpoint() + ServiceUtils.ACTIVITIES + Util.BRIDGE_ENDPOINT) .unmarshal().json(ActivityIssuesDTO.class) </code> In this process i have my final response in activityIssuesDTO and i send it with body. <code>.process(exchange ->; { ActivityIssuesDTO activityIssuesDTO = exchange.getIn().getBody(ActivityIssuesDTO.class); List<ActivityIssuesDTO>; activityIssuesDTOs = exchange.getProperty(';response';, List.class); activityIssuesDTOs.add(activityIssuesDTO); exchange.getIn().setBody(activityIssuesDTOs); }) .marshal().json(); </code> The problem is that i can't see my response and can't marshal it. Thank you. I removed the split and for one item(query) it's ok and i can see my response but for many query i can't see my response. I tried it also with static array and it's the same.
As I understood it in each Split we need also an aggregator to aggregation our message to continue the process and i resolved it by creating an aggregator and put create the finale result inside my aggregator this result is coming from my micro service. this is the final result: <code> .split(body()) .aggregationStrategy(new ActivityAggregator()) .streaming() .to(direct(GET_QUERY_FINAL)) .end()</code> and this is my internal route: <code> from(direct(GET_QUERY_FINAL)) .log(';getting the query and send to activity ms';) .process(exchange ->; { String queries = exchange.getIn().getBody(String.class); List<ActivityIssuesDTO>; response = exchange.getProperty(';response';, List.class); Util.setProperty(exchange, ';response';, response); exchange.getIn().setHeader(Exchange.HTTP_QUERY, queries); }) .toD(serviceUtils.getActivityEndpoint() + ServiceUtils.ACTIVITIES + Util.BRIDGE_ENDPOINT) .unmarshal().json(ActivityIssuesDTO.class);</code> and inside my aggregator i just put the final result inside my new array. Thanks.
apache-camel
I am trying to upgrade from Camel 4.0 to 4.1, and none of the timer properties appear to be on the exchange. Were these moved somewhere else? The time does appear to work correctly. Theses are the properties I am referring to: https://camel.apache.org/components/4.0.x/timer-component.html Prior to 4.1, you would be able to access these like so: <code>exchange.getProperty(Exchange.TIMER_NAME, String.class) exchange.getProperty(Exchange.TIMER_PERIOD, String.class) </code> Using 4.0 I can see the properties are there, but in 4.1 they are simply not there.
You should follow the upgrade guides, where you can find details how to turn this on again https://camel.apache.org/manual/camel-4x-upgrade-guide-4_1.html#_camel_timer
apache-camel
How do I provide a username and password into a <code>org.springframework.jms.connection.CachingConnectionFactory</code>? (NOT the rabbit one). Using Apache Camel, I'm trying the following: <code>ActiveMQComponent amqComponent = new ActiveMQComponent(); //amqComponent.setUsername(amqUser); //amqComponent.setPassword(amqPassword); ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(); cf.setBrokerURL(';tcp://'; + amqServer + ';:'; + amqPort + ';?jms.watchTopicAdvisories=false';);CachingConnectionFactory ccf = new CachingConnectionFactory(cf); ccf.setClientId(';clientID';); amqComponent.setConnectionFactory(ccf);context.addComponent(';activemq';, amqComponent); </code> If I uncomment the <code>.setUsername</code> and <code>.setPassword</code> calls, I get an error:';SingleConnectionFactory does not support custom username and password';(because <code>SingleConnectionFactory</code> is the parent class for this <code>CachingConnectionFactory</code>). Clearly if I leave the lines commented, I get an authentication error because I'm not providing a user/password. How can I pass the ActiveMQ credentials when using a <code>CachingConnectionFactory</code>? (as an aside, Spring Integration: How to use SingleConnectionFactory with ActiveMQ? discusses why I am trying to use a CCF as opposed to just using the ActiveMQConnectionFactory - ';with each poll, it creates a new connection to the Broker - flooding my broker with hundreds of connections';)
You need to use a <code>UserCredentialsConnectionFactoryAdaptor</code>, e.g. as follows: <code>ActiveMQComponent amqComponent = new ActiveMQComponent(); ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(); cf.setBrokerURL(';tcp://'; + amqServer + ';:'; + amqPort + '; jms.watchTopicAdvisories=false';); UserCredentialsConnectionFactoryAdapter uca = new UserCredentialsConnectionFactoryAdapter(); uca.setUsername(amqUser); uca.setPassword(amqPassword); uca.setTargetConnectionFactory(cf); CachingConnectionFactory ccf = new CachingConnectionFactory(uca); ccf.setClientId(amqClientID); amqComponent.setConnectionFactory(ccf); amqComponent.setMaxConcurrentConsumers(1); context.addComponent(';activemq';, amqComponent); </code>
apache-camel
I am using Apache Camel to connect and subscribe to ActiveMQ Artemis feeds and forward to Kafka topics. It runs fine for a while, but then stops with an exception: <code>jakarta.jms.JMSSecurityException: username 'x...@yy.com' has too many connections</code> So clearly there's something in the way Camel works that ActiveMQ Artemis, or some security settings on that side of the connection, doesn't like. I know that the feed I'm connecting to does have some checks in place to prevent applications from connecting and disconnecting multiple times in quick succession; so I think I'm hitting that. Looking into it, it appears that camel reconnects and pulls regularly, rather than creating a single connection (or even a single connection per Camel Route); and so I think this is causing the broker to kick me out. Has anyone else come across this? Any ideas? Code for reference: <code>ActiveMQComponent amqComponent = new ActiveMQComponent(); amqComponent.setUsername(amqUser); amqComponent.setPassword(amqPassword); amqComponent.setClientId(';clientID';);ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(); cf.setTrustedPackages(List.of(';com...';)); cf.setBrokerURL(';tcp://'; + amqServer + ';:'; + amqPort + ';?jms.watchTopicAdvisories=false';); amqComponent.setConnectionFactory(cf); //amqComponent.setMaxConcurrentConsumers(1); //amqComponent.setSubscriptionShared(true); //amqComponent.setUsePooledConnection(true); context.addComponent(';activemq';, amqComponent);//...from(';activemq:topic:'; + amqFeedTopic + ';?clientId='; + clientid + ';&;durableSubscriptionName='; + clientid + ';-sub';) .id(clientid) .description(';Connection for '; + clientid) .to(';kafka:'; + kafkaTopic + ';?brokers='; + kafkaBootstrapServers); </code>
This answer: Spring Integration: How to use SingleConnectionFactory with ActiveMQ? pointed me in the right direction. Essentially, the connection factory determines the approach; and the default connection factory will disconnect and reconnect regularly. For clarity, it is the Spring JMS code, not the connection factory, that is doing the disconnect and reconnect. In fact, it still does this even when using the solution outlined below. The caching connection factory vends a proxy to Spring JMS and keeps the connection open. Thanks to Doug Grove in the comments for pointing this out. To fix this, use a <code>SingleConnectionFactory</code> or its subclass, <code>CachingConnectionFactory</code> instead. Now, these can't accept user/password like the standard AMQ one can, and so you need to use a <code>UserCredentialsConnectionFactoryAdapter</code> to provide those. Simple, right? Here's some code: <code>ActiveMQComponent amqComponent = new ActiveMQComponent(); ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(); cf.setBrokerURL(';tcp://'; + amqServer + ';:'; + amqPort + '; jms.watchTopicAdvisories=false';); UserCredentialsConnectionFactoryAdapter uca = new UserCredentialsConnectionFactoryAdapter(); uca.setUsername(amqUser); uca.setPassword(amqPassword); uca.setTargetConnectionFactory(cf); CachingConnectionFactory ccf = new CachingConnectionFactory(uca); ccf.setClientId(amqClientID); amqComponent.setConnectionFactory(ccf); amqComponent.setMaxConcurrentConsumers(1); context.addComponent(';activemq';, amqComponent); </code> Note also, with this approach, you can only have one Camel Route using this Caching Connection Factory. If you try to add more than one, you'll get errors on the other routes. To fix this, you'll need to use a whole new Camel Context for each Route, and configure these connections factories on each.
apache-camel
I am copying file from ftp to local system and file is in gigs. I notice that each time when I tried to copy file in iteration it overrides the content. <code><route id=';ftp'; >; <';ftp://xxx@myftp.com/ftp-test/?password=mypassword';/>; <to uri=';file://filepath/temp';/>; </route>;</code> Tried using .done extension but didn't worked also tried to copy file to another folder but that's also overlapping.
Have you tried this. <code><route id=';incoming'; >; <from uri=';file://my/path/incoming';/>; <to uri=';file://my/path/incoming/temp?fileExist=Append';/>; </route>; </code>
apache-camel
I am trying to run the Camel in Action 2 examples from Chapter 2 - Spring folder ...the Camel-3.20 Branch of the repo. ( Camel in Action 2 - Chapter 2 - Spring ) My Java settings are : openjdk version ';18.0.2'; 2022-07-19 OpenJDK Runtime Environment (build 18.0.2+9-61) OpenJDK 64-Bit Server VM (build 18.0.2+9-61, mixed mode, sharing) My Maven settings are : Maven home: D:\Installed_Apps\Maven\apache-maven-3.8.4 Java version: 18.0.2, vendor: Oracle Corporation, runtime: D:\Installed_Apps\Open_JDK_18 Default locale: en_US, platform encoding: UTF-8 OS name: ';windows 10';, version: ';10.0';, arch: ';amd64';, family: ';windows'; When I run from the command line I see error :java.lang.ClassNotFoundException: org.apache.camel.spring.MainI then adjusted the pom file to include : <code> <plugin>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-maven-plugin</artifactId>; <dependencies>; <dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-spring</artifactId>; <version>;2.25.3</version>; </dependency>; </dependencies>; </plugin>; </code> When I run this version from the command line I see error : <code>java.lang.reflect.InvocationTargetException </code> Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Could not resolve bean definition resource pattern [META-INF/spring/*.xml]; nested exception is java.io.FileNotFoundException: class path resource [META-INF/spring/] cannot be resolved to URL because it does not exist Caused by: java.io.FileNotFoundException: class path resource [META-INF/spring/] cannot be resolved to URL because it does not exist Anyone have thoughts on how to correct this ? these are the existing sample projects without any changes.
Camel 3 does not support Java 18. It only supports Java 11 (Java 8 if you use Java 3.14 or older). So you would need to install JDK 11 and use that with this example.
apache-camel
In one of our legacy applications we would create data objects that contained data from our SQL tables, and then we would marshal them with the Apache Camel routes in XML DSL and the BeanIO formatting library. This worked fine. In our new application I am trying to emulate the same behaviour, but with the Java DSL routing instead. I'm using Apache Camel 4.0.0, Spring 4.0.0, and BeanIO 3.4.0. The routes look something like this: <code>BeanIODataFormat dataFormat = new BeanIODataFormat(';path/beanioFormats/beanio_format.xml';, ';FormatSourceName';);from(';{{cron.process}}';) .log(LoggingLevel.INFO, ';Creating File';) .transform().method(';fileGeneratorClass';, ';generatorMethod';) .to(';direct:marshalFile';) .end();from(';direct:marshalFile';) .marshal(dataFormat) .to(';file:{{output.file.path}}';) .end(); </code> while the beanio format file looks very standard and similar to what we had before, like so: <code><?xml version=';1.0'; encoding=';UTF-8';?>;<beanio xmlns=';http://www.beanio.org/2012/03'; xmlns:xsi=';http://www.w3.org/2001/XMLSchema-instance'; xsi:schemaLocation=';http://www.beanio.org/2012/03 http://www.beanio.org/2012/03/mapping.xsd';>; <stream name=';FormatSourceName'; format=';fixedlength';>; <group name=';fileWrapperObject'; class=';path.to.wrapper.class';>; <record name=';fileHeader'; class=';path.to.header.class'; minOccurs=';1'; maxOccurs=';1';>; <field name=';fileRecordIdentifier'; rid=';true'; length=';3'; required=';true'; literal=';000';/>; </record>; ... etc</code> and finally, the <code>generatorMethod</code> that sets the data object into the exchange is as such: <code> public void generatorMethod(Exchange exchange) { FileWrapperObject fileWrapperObject = new fileWrapperObject(); // fill it with data LOG.info(';Wrapper object created';); exchange.getIn().setBody(wrapper); String fileName = ';fileName';; exchange.getIn().setHeader(Exchange.FILE_NAME, fileName); } </code> I'm certain the data object is not null nor are any of its fields, but the resulting file is always empty. Any clue on where I went wrong? My gut says it's the way I've written the marshalling in the routes file, but I'm not sure where to proceed, given the BeanIO documentation is rather bereft. The main difference I see in the XML DSL based approach is that the dataFormats would be defined in the <code><camelContext>;</code> and then be accessed by ID, but to me, what I have written seems correct.
I ended up using the <code>BeanWriter</code> class provided by the BeanIO library to marshal to an output file, although from my processor method instead of from my routes. I essentially copied the documentation here regarding marshalling: https://beanio.github.io/docs/

No dataset card yet

New: Create and edit this dataset card directly on the website!

Contribute a Dataset Card
Downloads last month
0
Add dataset card