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/
|
apache-camel
|
I am getting an error while accessing an endpoint in the local machine: Error Logs: <code>org.apache.camel.CamelExecutionException: Exception occurred during execution on the exchange: Exchange[ID-aaayush-mac-1697010426104-0-3] at org.apache.camel.util.ObjectHelper.wrapCamelExecutionException(ObjectHelper.java:1842) at org.apache.camel.impl.DefaultExchange.setException(DefaultExchange.java:389) at org.apache.camel.util.AsyncProcessorConverterHelper$ProcessorToAsyncProcessorBridge.process(AsyncProcessorConverterHelper.java:64) at org.apache.camel.processor.SendProcessor.process(SendProcessor.java:148) at org.apache.camel.processor.RedeliveryErrorHandler.process(RedeliveryErrorHandler.java:548) at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:201) at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:201) at org.apache.camel.component.jetty.CamelContinuationServlet.doService(CamelContinuationServlet.java:220) at org.apache.camel.http.common.CamelServlet.service(CamelServlet.java:79) at javax.servlet.http.HttpServlet.service(HttpServlet.java:750) at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:799) at org.eclipse.jetty.servlet.ServletHandler$ChainEnd.doFilter(ServletHandler.java:1656) at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:552) at org.eclipse.jetty.server.handler.ScopedHandler.nextHandle(ScopedHandler.java:233) at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1440) at org.eclipse.jetty.server.handler.ScopedHandler.nextScope(ScopedHandler.java:188) at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:505) at org.eclipse.jetty.server.handler.ScopedHandler.nextScope(ScopedHandler.java:186) at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1355) at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141) at org.eclipse.jetty.server.handler.RequestLogHandler.handle(RequestLogHandler.java:54) at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:127) at org.eclipse.jetty.server.Server.handle(Server.java:516) at org.eclipse.jetty.server.HttpChannel.lambda$handle$1(HttpChannel.java:487) at org.eclipse.jetty.server.HttpChannel.dispatch(HttpChannel.java:732) at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:479) at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:277) at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:311) at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:105) at org.eclipse.jetty.io.ssl.SslConnection$DecryptedEndPoint.onFillable(SslConnection.java:555) at org.eclipse.jetty.io.ssl.SslConnection.onFillable(SslConnection.java:410) at org.eclipse.jetty.io.ssl.SslConnection$2.succeeded(SslConnection.java:164) at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:105) at org.eclipse.jetty.io.ChannelEndPoint$1.run(ChannelEndPoint.java:104) at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.runTask(EatWhatYouKill.java:338) at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.doProduce(EatWhatYouKill.java:315) at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.tryProduce(EatWhatYouKill.java:173) at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.run(EatWhatYouKill.java:131) at org.eclipse.jetty.util.thread.ReservedThreadExecutor$ReservedThread.run(ReservedThreadExecutor.java:409) at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:883) at org.eclipse.jetty.util.thread.QueuedThreadPool$Runner.run(QueuedThreadPool.java:1034) at java.lang.Thread.run(Thread.java:750) Caused by: java.lang.NoSuchMethodError: com.fasterxml.jackson.databind.introspect.AnnotatedMember.getType(Lcom/fasterxml/jackson/databind/type/TypeBindings;)Lcom/fasterxml/jackson/databind/JavaType; at io.swagger.jackson.ModelResolver.resolve(ModelResolver.java:421) at io.swagger.jackson.ModelResolver.resolve(ModelResolver.java:199) at io.swagger.converter.ModelConverterContextImpl.resolve(ModelConverterContextImpl.java:103) at io.swagger.converter.ModelConverters.read(ModelConverters.java:76) at io.swagger.converter.ModelConverters.read(ModelConverters.java:67) at org.apache.camel.swagger.RestModelConverters.readClass(RestModelConverters.java:33) at org.apache.camel.swagger.RestSwaggerReader.appendModels(RestSwaggerReader.java:755) at org.apache.camel.swagger.RestSwaggerReader.parse(RestSwaggerReader.java:227) at org.apache.camel.swagger.RestSwaggerReader.read(RestSwaggerReader.java:113) at org.apache.camel.swagger.RestSwaggerSupport.renderResourceListing(RestSwaggerSupport.java:224) at org.apache.camel.swagger.RestSwaggerProcessor.process(RestSwaggerProcessor.java:119) at org.apache.camel.component.rest.RestApiProducer.process(RestApiProducer.java:36) at org.apache.camel.util.AsyncProcessorConverterHelper$ProcessorToAsyncProcessorBridge.process(AsyncProcessorConverterHelper.java:61) ... 39 more </code> Exception: <code>com.fasterxml.jackson.databind.introspect.AnnotatedMember.getType(Lcom/fasterxml/jackson/databind/type/TypeBindings;)Lcom/fasterxml/jackson/databind/JavaType; </code> pom.xml: <code><properties>; <camel.version>;2.25.4</camel.version>; </properties>; <dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-jackson-starter</artifactId>; <version>;${camel.version}</version>; </dependency>; <dependency>; <groupId>;com.fasterxml.jackson.datatype</groupId>; <artifactId>;jackson-datatype-jsr310</artifactId>; <version>;2.12.5</version>; </dependency>; </code> This is the Jackson dependency for Camel that I am using in the project.
|
camel-jackson-starter version <code>2.25.4</code> uses <code>2.9.10.7</code> version of jackson-databind. Please update your pom.xml by adding these dependencies: <code><dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-jackson-starter</artifactId>; <version>;2.25.4</version>; </dependency>; <dependency>; <groupId>;com.fasterxml.jackson.core</groupId>; <artifactId>;jackson-databind</artifactId>; <version>;2.9.10.7</version>; </dependency>; <dependency>; <groupId>;com.fasterxml.jackson.datatype</groupId>; <artifactId>;jackson-datatype-jsr310</artifactId>; <version>;2.9.10</version>; </dependency>; <dependency>; <groupId>;com.fasterxml.jackson.module</groupId>; <artifactId>;jackson-module-jaxb-annotations</artifactId>; <version>;2.9.10</version>; </dependency>; </code> See if this works.
|
apache-camel
|
I try to migrate my Apache Camel application from component RabbitMQ to component Spring RabbitMQ. Unfortunately some defaults are changed. One is the <code>durable</code> property for queues (see Durability), which is now <code>false</code> by default. Code <code>from(springRabbitmq(';my_exchange';) .routingKey(';my_routing_key';) .queues(';q_my_queue';) .autoDeclare(true)) </code> VersionsApache Camel 4.0.0 Spring Boot 3.1.3Logs <code>Caused by: com.rabbitmq.client.ShutdownSignalException: channel error; protocol method: #method<channel.close>;(reply-code=406, reply-text=PRECONDITION_FAILED - inequivalent arg 'durable' for queue 'q_my_queue' in vhost '/': received 'false' but current is 'true', class-id=50, method-id=10) </code> ResearchI read <code>SpringRabbitMQEndpointConsumerBuilder</code>, but there is no method for <code>durable</code>.I read <code>AdvancedSpringRabbitMQEndpointConsumerBuilder</code>, but there is no method for <code>durable</code>.I read AUTO DECLARE EXCHANGES, QUEUES AND BINDINGSThe elements can be configured using the multi-valued <code>args</code> option. For example to specify the queue as durable and exclusive, you can configure the endpoint uri with <code>arg.queue.durable=true&;arg.queue.exclusive=true</code>.but I want to use endpoint DSL.I read <code>args</code>Specify arguments for configuring the different RabbitMQ concepts, a different prefix is required for each element: arg.consumer. arg.exchange. arg.queue. arg.binding. arg.dlq.exchange. arg.dlq.queue. arg.dlq.binding. For example to declare a queue with message ttl argument: args=arg.queue.x-message-ttl=60000. The option is a: <code>java.util.Map<java.lang.String, java.lang.Object>;</code> type. The option is multivalued, and you can use the args(String, Object) method to add a value (call the method multiple times to set more values). Group: advancedand tried <code>from(springRabbitmq(';my_exchange';) .routingKey(';my_routing_key';) .queues(';q_my_queue';) .autoDeclare(true) .advanced() .args(';arg.queue.durable';, true)) </code> and <code>from(springRabbitmq(';my_exchange';) .routingKey(';my_routing_key';) .queues(';q_my_queue';) .autoDeclare(true) .advanced() .args(';arg.queue.durable';, ';true';)) </code> but I got the same error. Question How can I set the property <code>durable</code> for a queue?
|
Did you try this? <code>from(springRabbitmq(';my_exchange';) ... .args(';queue.durable';, ';true';)) </code>
|
apache-camel
|
This is my route <code> from(';sftp://userName:password@ip:22/<my-folder>;?move=.done';) .routeId(';my-route-1';) .<processing-logic>; </code> How to avoid processing the same files incase of multiple instances?
|
Camel recently introduced some interesting clustering capabilities - see here. In your particular case, you could model a route which is taking the leadership when starting the directory polling, preventing thereby other nodes from picking the (same or other) files. Set it up is very easy, and all you need is to prefix singleton endpoints according to the master component syntax: master:namespace:delegateUri This would result in something like this: <code>from(';master:mycluster:sftp://...';) .routeId(';clustered-route';) .log(';Clustered sftp polling !';); </code>
|
apache-camel
|
I am trying to connect a SFTP server with Private Key but I am getting this error. (Private Key works with WinSCP and Filezilla) <code>org.apache.camel.component.file.GenericFileOperationFailedException: Cannot connect to sftp://xxxxx@xxxx:22 at org.apache.camel.component.file.remote.SftpOperations.connect(SftpOperations.java:138) ~[camel-ftp-4.0.1.jar:4.0.1] at org.apache.camel.component.file.remote.RemoteFileConsumer.connectIfNecessary(RemoteFileConsumer.java:230) ~[camel-ftp-4.0.1.jar:4.0.1] at org.apache.camel.component.file.remote.RemoteFileConsumer.prePollCheck(RemoteFileConsumer.java:75) ~[camel-ftp-4.0.1.jar:4.0.1] at org.apache.camel.component.file.GenericFileConsumer.poll(GenericFileConsumer.java:126) ~[camel-file-4.0.1.jar:4.0.1] at org.apache.camel.support.ScheduledPollConsumer.doRun(ScheduledPollConsumer.java:203) ~[camel-support-4.0.1.jar:4.0.1] at org.apache.camel.support.ScheduledPollConsumer.run(ScheduledPollConsumer.java:117) ~[camel-support-4.0.1.jar:4.0.1] at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:539) ~[na:na] at java.base/java.util.concurrent.FutureTask.runAndReset(FutureTask.java:305) ~[na:na] at java.base/java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:305) ~[na:na] at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1136) ~[na:na] at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635) ~[na:na] at java.base/java.lang.Thread.run(Thread.java:833) ~[na:na] Caused by: com.jcraft.jsch.JSchException: Auth cancel for methods 'publickey,gssapi-keyex,gssapi-with-mic,password' at com.jcraft.jsch.Session.connect(Session.java:499) ~[jsch-0.2.11.jar:0.2.11] at org.apache.camel.component.file.remote.SftpOperations.tryConnect(SftpOperations.java:161) ~[camel-ftp-4.0.1.jar:4.0.1] at org.apache.camel.support.task.BlockingTask.lambda$run$0(BlockingTask.java:40) ~[camel-support-4.0.1.jar:4.0.1] at org.apache.camel.support.task.ForegroundTask.run(ForegroundTask.java:94) ~[camel-support-4.0.1.jar:4.0.1] at org.apache.camel.support.task.BlockingTask.run(BlockingTask.java:40) ~[camel-support-4.0.1.jar:4.0.1] at org.apache.camel.component.file.remote.SftpOperations.connect(SftpOperations.java:136) ~[camel-ftp-4.0.1.jar:4.0.1] ... 11 common frames omitted </code> I tried two SFTP server and I can connect one server with same configuration. Here is my SFTP router; <code>JSch.setConfig(';server_host_key';, JSch.getConfig(';server_host_key';) + ';,ssh-dss';); JSch.setConfig(';PubkeyAcceptedAlgorithms';, JSch.getConfig(';PubkeyAcceptedAlgorithms';) + ';,ssh-rsa';); JSch.setConfig(';kex';, JSch.getConfig(';kex';) + ';diffie-hellman-group1-sha1,diffie-hellman-group14-sha1,diffie-hellman-group-exchange-sha1,diffie-hellman-group-exchange-sha256';); byte[] privateKeyBytes = Base64.decodeBase64(';base64_key';); getContext().getRegistry().bind(';senderPrivateKeyArrRegistry';, privateKeyBytes); from(';sftp://xxxxx@xxxxx:22//?username=xxxxx&;throwExceptionOnConnectFailed=true&;privateKeyPassphrase=xxxxxx&;privateKey=#senderPrivateKeyArrRegistry&;minDepth=1&;recursive=false&;antInclude=xxx&;exclude=&;sortBy=file:modified&;noop=true&;maximumReconnectAttempts=0&;disconnect=true';) .process(exchange ->; { System.out.println(exchange.getIn().getBody()); }); </code> I tried to change Jsch library with ';com.github.mwiede'; but no luck. Also I tried add ';preferredAuthentications=publickey'; to route but same error. Camel Version : 4.0.1 <code>Connection established Remote version string: SSH-2.0-OpenSSH_8.0 Local version string: SSH-2.0-JSCH_0.2.11 CheckCiphers: chacha20-poly1305@openssh.com CheckKexes: curve25519-sha256,curve25519-sha256@libssh.org,curve448-sha512 CheckSignatures: ssh-ed25519,ssh-ed448 SSH_MSG_KEXINIT sent SSH_MSG_KEXINIT received server proposal: KEX algorithms: curve25519-sha256,curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group14-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1 server proposal: host key algorithms: rsa-sha2-512,rsa-sha2-256,ssh-rsa,ecdsa-sha2-nistp256,ssh-ed25519 server proposal: ciphers c2s: aes256-gcm@openssh.com,chacha20-poly1305@openssh.com,aes256-ctr,aes256-cbc,aes128-gcm@openssh.com,aes128-ctr,aes128-cbc server proposal: ciphers s2c: aes256-gcm@openssh.com,chacha20-poly1305@openssh.com,aes256-ctr,aes256-cbc,aes128-gcm@openssh.com,aes128-ctr,aes128-cbc server proposal: MACs c2s: hmac-sha2-256-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha2-256,hmac-sha1,umac-128@openssh.com,hmac-sha2-512 server proposal: MACs s2c: hmac-sha2-256-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha2-256,hmac-sha1,umac-128@openssh.com,hmac-sha2-512 server proposal: compression c2s: none,zlib@openssh.com server proposal: compression s2c: none,zlib@openssh.com server proposal: languages c2s: server proposal: languages s2c: client proposal: KEX algorithms: curve25519-sha256,curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group14-sha256diffie-hellman-group1-sha1,diffie-hellman-group14-sha1,diffie-hellman-group-exchange-sha1,diffie-hellman-group-exchange-sha256,ext-info-c client proposal: host key algorithms: ssh-ed25519,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,rsa-sha2-512,rsa-sha2-256,ssh-rsa client proposal: ciphers c2s: aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com client proposal: ciphers s2c: aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com client proposal: MACs c2s: hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1 client proposal: MACs s2c: hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1 client proposal: compression c2s: none client proposal: compression s2c: none client proposal: languages c2s: client proposal: languages s2c: kex: algorithm: curve25519-sha256 kex: host key algorithm: ssh-ed25519 kex: server->;client cipher: aes128-ctr MAC: hmac-sha2-256-etm@openssh.com compression: none kex: client->;server cipher: aes128-ctr MAC: hmac-sha2-256-etm@openssh.com compression: none SSH_MSG_KEX_ECDH_INIT sent expecting SSH_MSG_KEX_ECDH_REPLY ssh_eddsa_verify: ssh-ed25519 signature true Host 'xyz123.com' is known and matches the EDDSA host key SSH_MSG_NEWKEYS sent SSH_MSG_NEWKEYS received SSH_MSG_SERVICE_REQUEST sent SSH_MSG_EXT_INFO received server-sig-algs=<ssh-ed25519,ssh-rsa,rsa-sha2-256,rsa-sha2-512,ssh-dss,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521>; SSH_MSG_SERVICE_ACCEPT received Authentications that can continue: publickey,password Next authentication method: publickey Authentications that can continue: password Next authentication method: password Login trials exceeds 0 Disconnecting from xyz123.com port 22 </code>
|
I found the problem. The problem was caused by the value used for passPhrase containing inappropriate characters. If you configure the endpoint as follows, this problem is solved. <code>....&;privateKeyPassphrase=RAW(';+passphrase+';).to(...) </code>
|
apache-camel
|
I'm using Quarkus 3.2.6 with Apache Camel 4.0.0. When it starts up various start up information is logged. How do I disable this? I've already set <code>quarkus.banner.enabled=false</code> but the information persists. Example output <code>Bootstrap runtime: org.apache.camel.quarkus.main.CamelMainRuntime Apache Camel (Main) 4.0.0 is starting Created default XPathFactory org.apache.xpath.jaxp.XPathFactoryImpl@1eb6e1c Apache Camel 4.0.0 (camel-1) is starting Routes startup (started:1) Started Test (direct://input) Apache Camel 4.0.0 (camel-1) started in 87ms (build:0ms init:0ms start:87ms) test-lambda 1.0.0 on JVM (powered by Quarkus 3.2.6.Final) started in 4.956s. Profile prod activated. Installed features: [amazon-lambda, camel-aws2-lambda, camel-core, camel-direct, camel-http, camel-log, camel-stax, camel-xpath, camel-xslt, camel-xslt-saxon, cdi, logging-json] </code> EDIT: So far I've tried disabling them via config. Below but this did not work. <code>quarkus.log.category.';io.quarkus';.level=OFF quarkus.log.category.';org.apa.cam';.level=OFF </code>
|
There is no configuration option to specifically disable those startup messages. But you can tweak the log levels with configuration properties. <code>quarkus.log.category.';io.quarkus';.level=OFF quarkus.log.category.';org.apache.camel';.level=OFF </code> Note that will disable all log messages from those categories.
|
apache-camel
|
I have an application with CDC (Change Data Capture) implemented using Debezium Embedded and built with Apache Camel. While analyzing the pod logs, everything seemed to be functioning correctly until at one point I started receiving this warning log repeatedly. <code>2023-09-18 08:16:34.032 WARN 1 --- [rce-coordinator] .c.s.SqlServerStreamingChangeEventSource : No maximum LSN recorded in the database; please ensure that the SQL Server Agent is running </code> Do you know if this issue is stemming from the Debezium connector configurations, or if it is a problem on the SQL Server side? Has anyone encountered this before? (Note: I am using the Debezium SQL Server connector). Thank you!
|
SOLVED: I realized that the problem was that DBZ had finished capturing all the changes, and there were no more changes to capture in the db and the log misled me. I thought I had more talking log. Thank you for your attention as always.
|
apache-camel
|
I have been using camel LogListener to intercept all log messages from log EIP and massage those with some custom headers and exchange properties. All seemed to be working fine until we migrated from v2.23.x to v3.19.0. Ever since we upgraded, the LogListener has stopped working. Before migration, we only did this: <code> log.info(';Registering log listener';); getContext().addLogListener(new CustomLogListener()); </code> And then our CustomLogListener looked like: <code>public class CustomLogListener implements LogListener { @Override public String onLog(final Exchange exchange, final CamelLogger camelLogger, final String message) { return String.format(';traceId=%s TXN=%s TENANT=%s %s';,exchange.getProperty(TOP_TRACEID, String.class),exchange.getProperty(TRANSACTION_ID, String.class), exchange.getProperty(TOPUP_ENV_HEADER, String.class), message); } } </code> After migration, we no longer can do context.addLogListener(...) We tried the following: <code> TopLogListener logListener = new TopLogListener(); getContext().getRegistry().bind(';logListener';, logListener);</code> but it didn't help. Any leads would be much appreciated. P.S: Our application uses Jakarta JEE and is packaged as a war file and deployed in wildfly. It doesn't use spring boot.
|
In Camel 3.19.x you can register the <code>LogListener</code> like: <code>MyCustomLogListener logListener = new MyCustomLogListener(); getCamelContext().adapt(ExtendedCamelContext.class).addLogListener(logListener) </code> There's some more background info in the Camel 2.x - 3.x migration guide about APIs that got moved from <code>CamelContext</code> to <code>ExtendedCamelContext</code>: https://camel.apache.org/manual/camel-3-migration-guide.html#_extended_camelcontext
|
apache-camel
|
Following the clarification done in: Using a jq expression, how to return items from a json array using an intermediate mapping array? I have tried to implement the solution: <code>[.links[] | select(.from == ';product1';) | .to] as $colors | [.hits[] | select(.id | IN($colors[])) | .name] </code> However my application (Spring Boot Apache Camel) gives me this error: ';Function IN/1 does not exist';. If I use ';in'; instead of ';IN'; I get: ';has() is not applicable to STRING';. I am using Apache Camel 4.0.0 (with camel-jq with same version). How to access this function or replace it by one providing the same result?
|
Use the equivalent <code>select(IN($colors[]; .id))</code> or <code>select(any($colors[] == .id; .))</code> (this is how the filter is defined in <code>builtin.jq</code>) Or go with the <code>INDEX</code>-based solution that was also proposed under your original question :)
|
apache-camel
|
I am trying to setup spring boot application that needs to consume messages from an IBM MQ queue while ensuring that only one instance of the application receives all messages to maintain message ordering. To achieve this, I need to configure the Camel consumer to open a connection with the MQOO_INPUT_EXCLUSIVE option enabled. I have already set up the JmsComponent, MQQueueConnectionFactory and RouteBuilder in my application, but I couldn't find the property key and value to enable the MQOO_INPUT_EXCLUSIVE option for the connection via MQQueueConnectionFactory. Tried this approach by changing the Default input open option in the queue setting and it works, but is there a way to achieve this by passing this property while opening connection? I have tried searching online for information on how to set this option, but I haven't been able to find a solution,the results were either not relevant to camel based configuration or those were outdated. Can anyone help me with this? Any help would be greatly appreciated!
|
Update: I checked from on my side that setting <code>MQConstants.MQOO_INPUT_EXCLUSIVE</code> (package - com.ibm.mq.constants) in the method <code>setMQConnectionOptions(int cTagOpt)</code> from <code>MQQueueConnectionFactory</code> doesn't work at all and throws error. So, It's impossible to set the <code>MQOO_INPUT_EXCLUSIVE</code> via <code>MQQueueConnectionFactory</code>. I have some useful links which will help you to understand why it's impossible and check if this helps.Open Input exclusive option (MQC.MQOO_INPUT_EXCLUSIVE ) Setting MQ exclusive-read client properties in JMSOnly the option that's available to you is to access queue from queueManager with the openOption as <code>MQOO_INPUT_EXCLUSIVE</code> <code>MQQueue queue = queueManager.accessQueue(';name-of-the-queue';, MQConstants.MQOO_INPUT_EXCLUSIVE); </code> Refer to Java Docs on MQConstants here.
|
apache-camel
|
I am using Apache Camel to connect to an external Corba name service. The system does have STIGs (Security Technical Implementation Guide) applied, SELinux and firewall policies in place. I can successfully connect to the Corba name service but only under some folders on the Linux machine. For instance, if I deploy my camel application under my home directory or /tmp it connects fine, but when I try under /opt or /usr it fails to connect. Also, if I make a copy of the /opt folder to /opts it connects fine. I've tried adjusting the SELinux labels, as well as disabling SELinux and iptables but the connection still fails under those folders. I am using OpenJDK 11 for my application but it is just the default installation without any security measures in place yet. Any ideas or things I can look at that may be causing this odd behavior with external corba connections under specific paths?
|
Issue was a class loader problem related to two different jars having identical classes and which classes got loaded first based on the path. Removing the unneeded jar fixed the issue.
|
apache-camel
|
I have an onException block in a camel route. It looks like this: <code>... .onException(SomeException.class) .maximumRedeliveries(3) .redeliveryDelay(5000) .onRedelivery(e ->; {log()}) .retryAttemptedLogLevel(WARN) .process(e ->; {log()}) .handled(true) ... </code> The problem is that the redeliveries are executed before the process. I would like to do something before retry. Is that possible?
|
Based on the requirement in the comment to perform action immediately after exception. you can use .onExceptionOccurred() processor, which executes immediately after exception, whereas onRedelivery() executes before retry. You can refer docs for more info. <code>... .onException(SomeException.class) .onExceptionOccurred(e ->; {log()}) .maximumRedeliveries(3) .redeliveryDelay(5000) .onRedelivery(e ->; {log()}) .retryAttemptedLogLevel(WARN) .process(e ->; {log()}) .handled(true); ... </code>
|
apache-camel
|
I need to convert csv file to syslog. CSV:(From) <code>';Type';,';RowID';,';Name'; ';SecurityIncident';,';ace5c4550c76';,';MalwareInfection'; ';SecurityIncident';,';ace5c4550c77';,';MalwareInfection'; </code> Syslog: To <code><13>;1 2023-09-09T10:19:28.428851-08:00 DESKTOP-TVVB676 - - - [LOG@14506 EventReceivedTime=';2020-09-09 10:19:28'; SourceModuleName=';csv'; SourceModuleType=';file'; Type=';SecurityIncident'; RowID=';ace5c4550c76'; Name=';MalwareInfection'; <13>;1 2023-09-09T10:19:28.428851-08:00 DESKTOP-TVVB676 - - - [LOG@14506 EventReceivedTime=';2020-09-09 10:19:28'; SourceModuleName=';csv'; SourceModuleType=';file'; Type=';SecurityIncident'; RowID=';ace5c4550c77'; Name=';MalwareInfection'; </code> How to do it in Java? Is there any java library available?
|
java code for converting CSV to Syslog <code>import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.time.LocalDateTime;import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVRecord;public class Test { public static void main(String[] args) { String csvFile = ';file.csv';; // Replace with your CSV file path try { BufferedReader reader = new BufferedReader(new FileReader(csvFile)); CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT.withHeader()); for (CSVRecord csvRecord : csvParser) { String type = csvRecord.get(';Type';); String rowID = csvRecord.get(';RowID';); String name = csvRecord.get(';Name';); String timestamp = LocalDateTime.now().toString(); String hostname = ';DESKTOP-TVVB676';; String syslogEntry = String.format(';<13>;1 %s %s - - - [LOG@14506 EventReceivedTime=\';%s\'; '; + ';SourceModuleName=\';csv\'; SourceModuleType=\';file\'; Type=\';%s\'; RowID=\';%s\'; Name=\';%s\';';, timestamp, hostname, timestamp, type, rowID, name); System.out.println(syslogEntry); } csvParser.close(); } catch (IOException e) { e.printStackTrace(); } } } </code> Output: <code><13>;1 2023-09-14T19:11:52.057131900 DESKTOP-TVVB676 - - - [LOG@14506 EventReceivedTime=';2023-09-14T19:11:52.057131900'; SourceModuleName=';csv'; SourceModuleType=';file'; Type=';SecurityIncident'; RowID=';ace5c4550c76'; Name=';MalwareInfection'; <13>;1 2023-09-14T19:11:52.068649300 DESKTOP-TVVB676 - - - [LOG@14506 EventReceivedTime=';2023-09-14T19:11:52.068649300'; SourceModuleName=';csv'; SourceModuleType=';file'; Type=';SecurityIncident'; RowID=';ace5c4550c77'; Name=';MalwareInfection'; </code>
|
apache-camel
|
I had a test class which had a <code>String isMockEndpointsAndSkip() { return (';*';) }</code> for testing some stuff, and that made other classes complain with the following exception <code>java.lang.IllegalArgumentException: Cannot advice route as there are no routes</code>.<code>quarkus-core</code> version: 2.16.9.Final <code>quarkus-camel-bom</code> version: 2.16.9.FinalI started changing the class with two <code>AdviceWith</code> statements and attempted to run the tests, and one passes but the other one fails. By enabling debugging with <code>quarkus.log.category.';org.apache.camel';.level=DEBUG</code>, I see that after the first test the Camel context seems to be taken down. I have a test class that goes like this: <code>@QuarkusTest public class DispatcherProcessorTest extends CamelQuarkusTestSupport { @Inject DispatcherProcessor dispatcherProcessor; @Override public boolean isUseAdviceWith() { return true; } /** * Tests that when a ';recipient setting'; doesn't contain an RBAC group's * UUID, the exchange is sent to the {@link Routes#FETCH_USERS} route. */ @Test void testSendFetchUsers() throws Exception { // Create an exchange with an empty body. final Exchange exchange = this.createExchangeWithBody(';';); // Create a recipient settings object without the group's UUID. final RecipientSettings recipientSettings = new RecipientSettings( true, true, null, new HashSet<>;() ); // Set the property that will be grabbed in the processor. exchange.setProperty(ExchangeProperty.RECIPIENT_SETTINGS, List.of(recipientSettings)); // Assert that the exchange was sent to the correct route. AdviceWith.adviceWith(this.context(), EngineToConnectorRouteBuilder.ENGINE_TO_CONNECTOR, a ->; { a.mockEndpointsAndSkip(String.format(';direct:%s';, Routes.FETCH_USERS)); a.mockEndpointsAndSkip(String.format(';direct:%s';, Routes.FETCH_GROUP)); }); this.startCamelContext(); this.context().start(); final MockEndpoint fetchUsersEndpoint = this.getMockEndpoint(String.format(';mock:direct:%s';, Routes.FETCH_USERS)); final MockEndpoint fetchGroupEndpoint = this.getMockEndpoint(String.format(';mock:direct:%s';, Routes.FETCH_GROUP)); fetchUsersEndpoint.expectedMessageCount(1); fetchGroupEndpoint.expectedMessageCount(0); this.dispatcherProcessor.process(exchange); fetchUsersEndpoint.assertIsSatisfied(); fetchGroupEndpoint.assertIsSatisfied(); // Make sure that the exchange contains the ';RecipientSettings'; object final List<Exchange>; exchanges = fetchUsersEndpoint.getExchanges(); final Exchange sentExchange = exchanges.get(0); final RecipientSettings sentRecipientSettings = sentExchange.getProperty(ExchangeProperty.CURRENT_RECIPIENT_SETTINGS, RecipientSettings.class); Assertions.assertEquals(recipientSettings, sentRecipientSettings, ';the recipient settings object was not properly set in the dispatcher';); } /** * Tests that when a ';recipient setting'; contains an RBAC group's UUID, * the exchange is sent to the {@link Routes#FETCH_GROUP} route. */ @Test void testSendFetchGroup() throws Exception { // Create an exchange with an empty body. final Exchange exchange = this.createExchangeWithBody(';';); // Create a recipient settings object with the group's UUID. final RecipientSettings recipientSettings = new RecipientSettings( true, true, UUID.randomUUID(), new HashSet<>;() ); // Set the property that will be grabbed in the processor. exchange.setProperty(ExchangeProperty.RECIPIENT_SETTINGS, List.of(recipientSettings)); // Assert that the exchange was sent to the correct route. AdviceWith.adviceWith(this.context(), EngineToConnectorRouteBuilder.ENGINE_TO_CONNECTOR, a ->; { a.mockEndpointsAndSkip(String.format(';direct:%s';, Routes.FETCH_USERS)); a.mockEndpointsAndSkip(String.format(';direct:%s';, Routes.FETCH_GROUP)); }); this.startCamelContext(); this.context().start(); final MockEndpoint fetchUsersEndpoint = this.getMockEndpoint(String.format(';mock:direct:%s';, Routes.FETCH_USERS)); final MockEndpoint fetchGroupEndpoint = this.getMockEndpoint(String.format(';mock:direct:%s';, Routes.FETCH_GROUP)); fetchUsersEndpoint.expectedMessageCount(0); fetchGroupEndpoint.expectedMessageCount(1); this.dispatcherProcessor.process(exchange); fetchUsersEndpoint.assertIsSatisfied(); fetchGroupEndpoint.assertIsSatisfied(); // Make sure that the exchange contains the ';RecipientSettings'; object final List<Exchange>; exchanges = fetchGroupEndpoint.getExchanges(); final Exchange sentExchange = exchanges.get(0); final RecipientSettings sentRecipientSettings = sentExchange.getProperty(ExchangeProperty.CURRENT_RECIPIENT_SETTINGS, RecipientSettings.class); Assertions.assertEquals(recipientSettings, sentRecipientSettings, ';the recipient settings object was not properly set in the dispatcher';); } } </code> However, the second test fails with the same error message: <code>java.lang.IllegalArgumentException: Cannot advice route as there are no routes</code>. I thought it had to do with the fact that I was ';adviceing'; the same route twice, but I saw in How do i unit test the same route multiple times using Apache Camel that this is perfectly fine. What am I doing wrong?
|
After asking in the <code>camel-quarkus</code> Zulip chat, the user ';Christian Kalkhoff'; pointed me at the solution. Essentially, they key to using <code>AdviceWith</code> is to make sure that you are disabling the route builder: <code>@Override public boolean isUseAdviceWith() { return true; }@Override public boolean isUseRouteBuilder() { return false; } </code> According to dkulp's ';Apache Camel: Camel Test'; page, you need to disable the route builder in order to give Apache Camel time to apply the advised routes to the context: Method name: boolean isUseRouteBuilder() Description: If the route builders from returned from createRouteBuilder() or createRouteBuilders() should be added to the CamelContext used in the test should be started. If the CamelContext use in the test should be automatically started before test methods are invoked. Override when using advice with and return true. This helps in knowing the adviceWith is to be used, and the CamelContext will not be started before the advice with takes place. This delay helps by ensuring the advice with has been property setup before the CamelContext is started. I haven't been able to run <code>./mvnw clean test</code> on the project with this, though, because I end up suffering from the same error. In order to be able to do that, I still need to put <code>@TestProfile(TestClassName.class)</code> in the test class's annotation: To force Quarkus JUnit Extension to restart the application (and thus also CamelContext) for a given test class, you need to assign a unique @io.quarkus.test.junit.TestProfile to that class. Check the Quarkus documentation for how you can do that. (Note that @io.quarkus.test.common.QuarkusTestResource has a similar effect.) As stated in the documentation, the performance worsens, but at least I can run all the tests.
|
apache-camel
|
I´m using this Apache Camel feature to load a secret from AWS Secrets Manager: https://camel.apache.org/blog/2022/03/secrets-properties-functions/ That works as long as I use a test secret with no ';/'; in its name. However our secrets are named like this: ';xxx/yyy/zzz'; I understand the ';/'; is used to query json values within the secret. In my case however, the ';/'; is part of the name of the secret. Doing something like this does not work (I added ''): camel.vault.aws.secrets='name/of/the/secret' and {{aws:'name/of/the/secret':default}}. No matter what I do, it always tries to access a secret called ';name';.
|
This functionality is designed in such a way that the part before '/' is considered as key, and part after '/' is considered as subkey. So this will work correctly for secrets which does not have '/'. However you should be able to fetch the secret with '/' by using camel aws secrets manager component
|
apache-camel
|
I have defined the following route: <code>from(direct(Routes.SEND_EMAIL_BOP_SINGLE_PER_USER)) .routeId(Routes.SEND_EMAIL_BOP_SINGLE_PER_USER) // Split the usernames on an individual exchange each. This property is a Set<String>;. .split(simpleF(';${exchangeProperty.%s}';, ExchangeProperty.USERNAMES)) // Set the flag for the next route's processor. .setProperty(ExchangeProperty.SINGLE_EMAIL_PER_USER, constant(true)) .to(direct(Routes.SEND_EMAIL_BOP)) .end(); </code> And written the following test: <code>@QuarkusTest public class EmailRouteBuilderTest extends CamelQuarkusTestSupport { @Inject ProducerTemplate producerTemplate; @Override public String isMockEndpoints() { return ';*';; } @Test void testIndividualEmailPerUser() throws InterruptedException { final Set<String>; usernames = Set.of(';a';, ';b';, ';c';, ';d';, ';e';); final Exchange exchange = this.createExchangeWithBody(';';); exchange.setProperty(ExchangeProperty.USERNAMES, usernames); final MockEndpoint sendEmailBopEndpoint = this.getMockEndpoint(String.format(';mock:direct:%s';, Routes.SEND_EMAIL_BOP), false); sendEmailBopEndpoint.expectedMessageCount(5); this.producerTemplate.send(String.format(';direct:%s';, Routes.SEND_EMAIL_BOP_SINGLE_PER_USER), exchange); sendEmailBopEndpoint.assertIsSatisfied(); } } </code> However, when I run the test, I see all sorts of error messages from the <code>Routes.SEND_EMAIL_BOP</code> route, which attempts to contact the real service, and the assertion fails with ';expected 5 messages, 0 received';. The logs indicate the following: <code>2023-08-31 09:51:55,896 INFO [org.apa.cam.com.moc.InterceptSendToMockEndpointStrategy] (main) Adviced endpoint [direct://send-email-single-per-user] with mock endpoint [mock:direct:send-email-single-per-user] 2023-08-31 09:51:55,897 INFO [org.apa.cam.com.moc.InterceptSendToMockEndpointStrategy] (main) Adviced endpoint [direct://send-email-bop] with mock endpoint [mock:direct:send-email-bop] 2023-08-31 09:51:55,896 INFO [org.apa.cam.com.moc.InterceptSendToMockEndpointStrategy] (main) Adviced endpoint [http://boplocalhost:9999] with mock endpoint [mock:http:boplocalhost:9999] </code> The last line of the log corresponds to the service. I think I am understanding this whole thing wrong: I thought that mocking the endpoints made Camel not call the real services or the subsequent routes. I have tried replacing <code>isMockEndpoints</code> with <code>isMockEndpointsAndSkip</code> but then the test doesn't work as well. May you please help me understanding what I am doing wrong? Thank you very much in advance.EDIT: Updated code with ';adviceWith';: <code>@QuarkusTest public class EmailRouteBuilderTest extends CamelQuarkusTestSupport { @Inject ProducerTemplate producerTemplate; @Override public boolean isUseAdviceWith() { return true; } @Test void testIndividualEmailPerUser() throws Exception { AdviceWith.adviceWith(this.context, Routes.SEND_EMAIL_BOP, a ->; { a.mockEndpointsAndSkip(';*';); }); final Set<String>; usernames = Set.of(';a';, ';b';, ';c';, ';d';, ';e';); final Exchange exchange = this.createExchangeWithBody(';';); exchange.setProperty(ExchangeProperty.USERNAMES, usernames); final MockEndpoint sendEmailBopEndpoint = this.getMockEndpoint(String.format(';mock:direct:%s';, Routes.SEND_EMAIL_BOP), false); sendEmailBopEndpoint.expectedMessageCount(5); this.producerTemplate.send(String.format(';direct:%s';, Routes.SEND_EMAIL_BOP_SINGLE_PER_USER), exchange); sendEmailBopEndpoint.assertIsSatisfied(); } } </code> This generates the following error message: <code>2023-09-04 10:11:34,767 WARN [org.apa.cam.sup.EventHelper] (main) Error notifying event 85D6EC0051F6FCF-0000000000000000 exchange completed took: 5ms. This exception will be ignored.: java.lang.NullPointerException: Cannot invoke ';org.apache.camel.Endpoint.getEndpointUri()'; because ';endpoint'; is null </code> And makes the test fail as well: <code>java.lang.AssertionError: mock://direct:send-email-bop Received message count. Expected: <5>; but was: <0>; Expected :<5>; Actual :<0>; </code>Thanks to Vignesh's comment, I was able to make it work. Notice the route specification in the <code>AdviceWith.adviceWith</code>: <code>@QuarkusTest public class EmailRouteBuilderTest extends CamelQuarkusTestSupport { @Inject ProducerTemplate producerTemplate; @Override public boolean isUseAdviceWith() { return true; } @Test void testIndividualEmailPerUser() throws Exception { AdviceWith.adviceWith(this.context, Routes.SEND_EMAIL_BOP_SINGLE_PER_USER, a ->; { a.mockEndpointsAndSkip(String.format(';direct:%s';, Routes.SEND_EMAIL_BOP)); }); final Set<String>; usernames = Set.of(';a';, ';b';, ';c';, ';d';, ';e';); final Exchange exchange = this.createExchangeWithBody(';';); exchange.setProperty(ExchangeProperty.USERNAMES, usernames); final MockEndpoint sendEmailBopEndpoint = this.getMockEndpoint(String.format(';mock:direct:%s';, Routes.SEND_EMAIL_BOP), false); sendEmailBopEndpoint.expectedMessageCount(5); this.producerTemplate.send(String.format(';direct:%s';, Routes.SEND_EMAIL_BOP_SINGLE_PER_USER), exchange); sendEmailBopEndpoint.assertIsSatisfied(); } } </code> Initially, I was trying to mock and skip a different route from the one I was testing. With this last change, I'm saying ';from this route I'm testing, mock this particular endpoint';, which apparently makes Apache mock the endpoint I want. That makes the test pass!
|
Posting the comment as answer. ';*'; indicates to mock all routes. Specific route should be mocked instead. Ex: ';direct:send_email_bop';
|
apache-camel
|
A Camel route setup in JBoss EAP 7.4.2 that tries to concurrently receive JMS messages from external ActiveMQ Artemis servers fails with following warning. <code>2023-xx-xx 16:04:37,066 GMT WARN [org.apache.camel.component.jms.DefaultJmsMessageListenerContainer] (Camel (StandardContext) thread #12 - JmsConsumer[XXXQueue]) Setup of JMS message listener invoker failed for destination 'XXXQueue' - trying to recover. Cause: Only allowed one session per connection. See the J2EE spec, e.g. J2EE1.4 Section 6.6 </code> Camel route: <code>from(';jms:queue:XXX?concurrentConsumers=2';) // or more .process(';xyz';) .end(); </code> Environment: JBoss EAP 7.4.2 receiving JMS messages from three external ActiveMQ Artemis 2.16 servers with support for failovers/HA using default protocol, using Apache Camel 2.25.4. ActiveMQ Artemis resource adapter settings: <code> <subsystem xmlns=';urn:jboss:domain:messaging-activemq:13.0';>; <remote-connector name=';netty-artemis-sharedinternal-1'; socket-binding=';artemis-sharedinternal-1';/>; <remote-connector name=';netty-artemis-sharedinternal-2'; socket-binding=';artemis-sharedinternal-2';/>; <remote-connector name=';netty-artemis-sharedinternal-3'; socket-binding=';artemis-sharedinternal-3';/>; <pooled-connection-factory name=';org.apache.activemq'; entries=';java:/ConnectionFactory'; connectors=';netty-artemis-sharedinternal-1 netty-artemis-sharedinternal-2 netty-artemis-sharedinternal-3'; ha=';true'; failover-on-initial-connection=';true'; use-topology-for-load-balancing=';true'; transaction=';none'; user=';user'; password=';password'; min-pool-size=';24'; use-auto-recovery=';true'; max-pool-size=';256'; initial-connect-attempts=';2'; statistics-enabled=';true'; enable-amq1-prefix=';false';>; <inbound-config use-jndi=';false'; rebalance-connections=';true'; setup-attempts=';2'; setup-interval=';5000';/>; </pooled-connection-factory>; ... </code> Queries:Is there a work around to avoid warning/failure? Is it possible to create a non JCA compliant Artemis connection factory in JBoss?
|
The Camel component you're using was written for a ';normal'; JMS <code>ConnectionFactory</code>. However, you're using a JCA-based <code>ConnectionFactory</code> from <code>pooled-connection-factory</code>. The way to avoid the warning is to use a <code>connection-factory</code> rather than a <code>pooled-connection-factory</code>. Here's an example based on what you already have configured: <code><connection-factory name=';org.apache.activemq'; entries=';java:/ConnectionFactory'; connectors=';netty-artemis-sharedinternal-1 netty-artemis-sharedinternal-2 netty-artemis-sharedinternal-3'; ha=';true'; failover-on-initial-connection=';true'; use-topology-for-load-balancing=';true'; enable-amq1-prefix=';false';/>; </code>
|
apache-camel
|
Camel documentation states that property placeholder uses the format <code>{{prop_name}}</code>, however the following route doesn't return the desired output if I define it as: <code><route>; <from uri=';timer:test-timer?period=5000'; />; <setBody>; <simple>;Hello world!</simple>; </setBody>; <log message=';Body: {{body}}'; />; </route>; </code> However, it works if defined as: <code><route>; <from uri=';timer:test-timer?period=5000'; />; <setBody>; <simple>;Hello world!</simple>; </setBody>; <log message=';Body: ${body}'; />; </route>; </code> Can anybody explain why property placeholder replacement doesn't work as documented in this case? Thanks
|
I learn that the reason why <code>{{body}}</code> doesn’t work is because body is a Simple DSL property, which of course is only available in Simple DSL. <code>{{key}}</code> placeholders only work with explicitly defined properties.
|
apache-camel
|
I'm trying to do the following:Based on a nullable field of an object within an exchange property that must be accessed via a name stored within a Java constant, I need to either throttle or not.However, I have a tough time understanding how to build more complex expressions with Apache Camel and their documentation is of no great help in this regard. My preferred solution would be to not use all these expression languages like ';simple'; that Camel provides, but rather do it via plain code. Let's say this is the object carrying the value that needs to be evaluated: <code>public class MyObject { private String group; public boolean hasGroup(){ return group != null; } } </code> What I've tried so far, however, is this: 1. Via ExpressionBuilder <code>.throttle(1) .correlationExpression(ExpressionBuilder .exchangePropertyExpression(MY_OBJECT_PROPERTY_NAME_CONSTANT))</code> But then what? What does this expression say and how would I build up my conditions from there? Found no docs for the promising ExpressionBuilder at all, no clue how to work with it 2. Via custom Expression implementation <code>.throttle(1) .correlationExpression(new Expression() { @Override public<T>; T evaluate(Exchange exchange, Class<T>; type) { var myObject = exchange.getProperty(MY_OBJECT_PROPERTY_NAME_CONSTANT, MyObject.class); return null; } }) </code> But what is the return type here and how would you implement it? The documentation provides absolute no value and no examplesWhat is a reliable way to cover my conditions within one expression?
|
Found out how to work with the Expression Interface While I was confused about the return type of the evaluate method <code><T>; T evaluate(Exchange exchange, Class<T>; type); </code> it is as simple as that, just returning Object <code>.correlationExpression(new Expression() { @Override @SuppressWarnings(';unchecked';) public Object evaluate(Exchange exchange, Class asType) { return exchange.getProperty(MY_PROPERTY, MyObject.class) .getGroupId(); } }); </code>
|
apache-camel
|
I'm having a bit of confusion with camels SEDA endpoints here. Obviously there's things I don't understand, but so far I couldn't figure out what it is. Here's my setup (in the abstract): <code>from(';direct:some-entry-point';) .setBody { // Route sets a byte array myByteArray } .to(';seda:file-upload';) // The message goes on to upload the byte array .choice() .`when` { doTheOtherThing } // Under certain circumstances, something needs to be done additionally. The body can already be uploaded, however. .to(';direct:do-the-other-thing';) from(';direct:do-the-other-thing';) .setBody { // This route adds a file handle, because this one is big and won't fit into memory myFileHandle } .to(';seda:streaming-upload';) //Since this file is big, it is forwarded to another endpoint to be uploaded as a stream.from(';seda:streaming-upload?queue=#FiloBlockingQueue';) .process { // Opens a stream to the filehandle in the body and uploads from that. }from(';seda:file-upload?queue=#FiloBlockingQueue';) .process { // Uploads the byte array in the body } </code> All in all, nothing too complex I would think. But I'm having an issue. For some wild reason, when some-entry-point sends the message to the file-upload endpoint, instead it ends up at the streaming-upload endpoint, where it will crash because it was expecting a file handle and got a byte array. I have done all I can with logging and breakpoints, and for all I can tell, this is indeed what happens. The message never arrives at file-upload, and it never arrives at do-the-other-thing, even though the conditions for that to happen are given. I've also verified that do-the-other-thing is the only route that forwards to streaming-upload. The only way I can explain the behaviour is that the message forwarded to file-upload ends up at the wrong endpoint. Can anybody tell me why? EDIT: Some new insights: The behaviour of messages being sent to the wrong queue is not consistent. In fact, it appears to be entirely random. I send a messages to any SEDA-queue endpoint, it's a cointoss which one will actually receive the message. Judging by the behaviour, I suspect that I'm completely misunderstanding hte underlying architecture here. It appears that there's only one SEDA-queue instance in my application, and the endpoints are both polling the same one. The first one to poll is the one that gets the message. That is not the behaviour I'd expect intuitively from something named ';endpoint';, but it would explain a lot. Any people here that actually know camel that can explain this to me?
|
It turns out that both those endpoints were backed by the same queue. My understanding of how camel works was woefully inadequate. When sending something to a SEDA-endpoint, it gets put on the designated queue, and SEDA endpoints will poll their queue at certain intervals. If two endpoints share the same queue, you have no control over which one will be first and receive the message. So if you want two different endpoints that are actually independent endpoints, you need to give them their own queue by making a bean for it and then injecting that into camel, like so: <code>@Configuration class QueueConfig( @Value(';\${capture.queueSize}';) private val queueSize: Int, private val eventPublisher: ApplicationEventPublisher ) { @Bean(';FirstBlockingQueue';) fun createFirstQueue(): BlockingQueue<Exchange>; = TODO(';instantiate queue here';) @Bean(';SecondBlockingQueue';) fun createSecondQueue(): BlockingQueue<Exchange>; = TODO(';instantiate other queue here';)} </code> In the route builder: <code>from(';seda:first-enpoint?queue=#FirstBlockingQueue';) // do thingsfrom(';seda:second-endpoint?queue=#SecondBlockingQueue';) // do things </code> Now both endpoints are backed by their own queue, and will not steal each others messages.
|
apache-camel
|
Within a Camel route I need to connect to a service with a HTTP GET request and leave the connection open to receive events. The Camel connection never receives events from the service. I can use Postman to perform this operation successfully:successful Postman connection, so I know the service is running as expected. My Camel Route calls the service endpoint as a GET with the same parameters used in Postman in the header of this call: <code>.setHeader(Exchange.HTTP_METHOD, constant(org.apache.camel.component.http.HttpMethods.GET)) .setHeader(';Connection';, simple(';keep-alive';)) .setHeader(';Accept';, simple(';text/event-stream';)) .setHeader(';Accept-Encoding';, simple(';gzip, deflate, br';)) .setHeader(';Postman-Token';, simple(';6ec7dfb3-6a4e-46ad-9f29-329a854f2649';)) .to(';http://localhost:5000/events';) </code> I know the service receives this call and creates event messages to send back, but they're never received by the Camel route. Also, a Postman connection that's made at the same time as the Camel connection does receive the event messages. Q) What is the correct way to configure a Camel route to receive service events?
|
OkHttpClient can be used with a RealEventSource and a custom EventSourceListener to receive server side events. Steps:create a custom Listener class that extends EventSourceListener and has methods for handling events from the RealEventSource. onEvent() processes the server-side-event data received from the Service onOpen(), onClose(), onFailure() may also be useful create a Client class that instantiates your Listener creates the OkHttpClient creates the Request to send to the Service creates a RealEventSource(Request, Listener) calls realEventSource.connect(okHttpClient); create a AccessToken class for the values needed to access your Service in the camel Route class instantiate the Client Client myClient = new Client(); in Route.configure() call .process(new Processor() { public void process(Exchange exchange) throws Exception { myClient.Connect(); } }) References: OkHttpClient realeventsource
|
apache-camel
|
I am trying to configure the Apache Camel Producer component (generated by camel-archetype-component archetype) and have a question on how one of the parts works. Code for the Endpoint: <code>@UriEndpoint(firstVersion = ';1.0-SNAPSHOT';, scheme = ';xmlGenerator';, title = ';xmlGenerator';, syntax = ';xmlGenerator:testScope';, category = {Category.JAVA, Category.CORE}) public class xmlGeneratorEndpoint extends DefaultEndpoint { @UriPath @Metadata(required = true) private String testScope;</code> my question is, the ';testScope'; is never used. the default setup has the setter/getter but neither is called. using <code>.to(';xmlGenerator://hello?option=12';)</code> the ';testScope'; variable is never set. even using <code>.to(';xmlGenerator://?option=12';)</code> does not cause issues. Id assume it should. how do I get it to set that value?
|
Resolved the issue with the help of looking at the google-bigquery component (thanks Claus). the main part is you need to implement a <code>public class ProducerContractConfiguration implements Cloneable { // this is where you put your path variables (obj://__TheseValues:moreValues) } </code> in your EndPoint class add the following setup: <code> @UriParam protected final ProducerContractConfiguration configuration; public ProducerContractEndpoint(String uri, ProducerContractComponent component, ProducerContractConfiguration configuration) { super(uri, component); this.configuration = configuration; } /** * Note, this seems to be needed for Mojo to not yell at you. * @return */ public ProducerContractConfiguration getConfiguration() { return configuration; }</code> also found that if you run into build issues, clean up the ';generated'; folder then run maven command again.
|
apache-camel
|
I have a simple Apache Camel route <code> from(';spring-rabbitmq:myExchange?routingKey=foo&;bridgeErrorHandler=true';) .log(';From RabbitMQ: ${body}';); </code> The sample project is here. If the RabbitMQ server is up and running when I start the route, everything works fine. The problem is if the RabbitMQ is not available on the route start the route startup terminates with org.springframework.amqp.AmqpConnectException. Is there any way how to handle the exception and retry several times after some delay starting the route again? I tried to add <code>onException</code> but that seems to work for producer (';to'; endpoint) only. I have also found Apace Camel <code>RoutePolicy.</code> It's method onInit is triggered before the route crashes so it might be used somehow to retry the route startup but the documentation is not very exhausting and I have not found any example either.
|
Yes see supervising route controller https://camel.apache.org/manual/route-controller.html Also you may look at the rabbitmq connection factory (spring rabbitmq stuff) as it may have some kind of retry built-in as well, you can configure.
|
apache-camel
|
We are using Apache Camel on one project and we would like to use RedisAggregationRepository when we aggregate some exchanges, but I am having trouble with serialising the body which is the record that contains enum inside. So my record looks like this (simplified): <code>@Builder @Jacksonized public record NotificationData( ... @NotNull Type type, ... ) { public enum Type { INTERNAL, EXTERNAL } } </code> And I have a route where I use <code>RedisAggregationRepository</code> and the NotificationData is a body of the exchange. When adding to Redis is performed the following exception is happening: <code>Exception caught: java.lang.IllegalArgumentException: java.io.IOException: java.lang.UnsupportedOperationException: can't get field offset on a record class: private final NotificationData$Type NotificationData.type at org.redisson.command.CommandAsyncService.encodeMapValue(CommandAsyncService.java:732) at org.redisson.RedissonObject.encodeMapValue(RedissonObject.java:310) at org.redisson.RedissonMap.putOperationAsync(RedissonMap.java:1372) at org.redisson.RedissonMap.putAsync(RedissonMap.java:1358) at org.redisson.RedissonMap.put(RedissonMap.java:664) at org.apache.camel.component.redis.processor.aggregate.RedisAggregationRepository.add(RedisAggregationRepository.java:134) ... Caused by: java.lang.UnsupportedOperationException: can't get field offset on a record class: private final NotificationData$Type NotificationData.type at jdk.unsupported/sun.misc.Unsafe.objectFieldOffset(Unsafe.java:648) at org.jboss.marshalling.reflect.SerializableField.<init>;(SerializableField.java:58) at org.jboss.marshalling.reflect.SerializableClass.getSerializableFields(SerializableClass.java:121) at org.jboss.marshalling.reflect.SerializableClass.<init>;(SerializableClass.java:88) at org.jboss.marshalling.reflect.SerializableClassRegistry$1.computeValue(SerializableClassRegistry.java:62) at org.jboss.marshalling.reflect.SerializableClassRegistry$1.computeValue(SerializableClassRegistry.java:59) at java.base/java.lang.ClassValue.getFromHashMap(ClassValue.java:228) at java.base/java.lang.ClassValue.getFromBackup(ClassValue.java:210) at java.base/java.lang.ClassValue.get(ClassValue.java:116) at org.jboss.marshalling.reflect.SerializableClassRegistry.lookup(SerializableClassRegistry.java:83) at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:180) at org.jboss.marshalling.river.BlockMarshaller.doWriteObject(BlockMarshaller.java:65) at org.jboss.marshalling.river.BlockMarshaller.writeObject(BlockMarshaller.java:56) at org.jboss.marshalling.MarshallerObjectOutputStream.writeObjectOverride(MarshallerObjectOutputStream.java:50) at org.jboss.marshalling.river.RiverObjectOutputStream.writeObjectOverride(RiverObjectOutputStream.java:179) at java.base/java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:346) at java.base/java.util.CollSer.writeObject(ImmutableCollections.java:1465) at org.jboss.marshalling.reflect.JDKSpecific$SerMethods.callWriteObject(JDKSpecific.java:89) at org.jboss.marshalling.reflect.SerializableClass.callWriteObject(SerializableClass.java:193) at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1089) at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:268) at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1143) at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:1101) at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:268) at org.jboss.marshalling.AbstractObjectOutput.writeObject(AbstractObjectOutput.java:58) at org.jboss.marshalling.AbstractMarshaller.writeObject(AbstractMarshaller.java:111) at org.redisson.codec.MarshallingCodec.lambda$new$1(MarshallingCodec.java:161) ... 170 more Caused by: an exception which occurred: in field org.apache.camel.support.DefaultExchangeHolder.inBody in object org.apache.camel.support.DefaultExchangeHolder@901212 in object org.apache.camel.support.DefaultExchangeHolder@901212 </code> Am I doing something wrong or this is not supported?
|
I thought this issue is related jboss-marshalling serializer issue. On the below issue, jboss-marshalling doesn't support java records. So, they suggest to use another serializer like Kryo.https://github.com/redisson/redisson/issues/4273And you can choose another serializer by referring below redisson official document.https://github.com/redisson/redisson/wiki/4.-data-serializationThanks
|
apache-camel
|
I'm using Camel 4.0.0-RC2 and following the documentation on binding beans to a RouteTemplate. I have a simple route template to consume from a configurable <code>fromEndpointUri</code> and pass a configurable <code>foo</code> to my <code>fooConsumer</code>: <code>routeTemplate(';myTemplate';) // Define the parameters for the route template. .templateParameter (';fromEndpointUri';) .templateBean (';foo';, Foo.class) // Define the route. .from (';{{fromEndpointUri}}';) .bean (fooConsumer, ';processFoo(${body}, #{{foo}})';); </code> The route I create using the template is simply: <code>templatedRoute(';myTemplate';) .routeId (';myTemplateRoute';) .parameter (';fromEndpointUri';, ';direct:test';) .bean (';foo';, Foo.class, ignored ->; new Foo()); </code> When sending a message through this route, an error is thrown <code>No type converter available to convert from type: java.lang.String to the required type: com.example.Foo</code>. The relevant stack trace is: <code>org.apache.camel.NoTypeConversionAvailableException: No type converter available to convert from type: java.lang.String to the required type: com.example.Foo at org.apache.camel.impl.converter.CoreTypeConverterRegistry.mandatoryConvertTo(CoreTypeConverterRegistry.java:279) ~[camel-base-4.0.0-RC2.jar:4.0.0-RC2] at org.apache.camel.component.bean.MethodInfo$ParameterExpression.evaluateParameterValue(MethodInfo.java:717) ~[camel-bean-4.0.0-RC2.jar:4.0.0-RC2] ... 94 more Wrapped by: org.apache.camel.component.bean.ParameterBindingException: Error during parameter binding on method: public java.util.List com.example.FooConsumer.processFoo(java.lang.String,com.example.Foo) at parameter #1 with type: class com.example.Foo with value type: class java.lang.String and value: #foo-1 at org.apache.camel.component.bean.MethodInfo$ParameterExpression.evaluateParameterValue(MethodInfo.java:728) ~[camel-bean-4.0.0-RC2.jar:4.0.0-RC2] at org.apache.camel.component.bean.MethodInfo$ParameterExpression.evaluateParameterExpressions(MethodInfo.java:618) ~[camel-bean-4.0.0-RC2.jar:4.0.0-RC2] at org.apache.camel.component.bean.MethodInfo$ParameterExpression.evaluate(MethodInfo.java:591) ~[camel-bean-4.0.0-RC2.jar:4.0.0-RC2] at org.apache.camel.component.bean.MethodInfo.initializeArguments(MethodInfo.java:262) ~[camel-bean-4.0.0-RC2.jar:4.0.0-RC2] at org.apache.camel.component.bean.MethodInfo.createMethodInvocation(MethodInfo.java:270) ~[camel-bean-4.0.0-RC2.jar:4.0.0-RC2] at org.apache.camel.component.bean.BeanInfo.createInvocation(BeanInfo.java:266) ~[camel-bean-4.0.0-RC2.jar:4.0.0-RC2] at org.apache.camel.component.bean.AbstractBeanProcessor.process(AbstractBeanProcessor.java:128) ~[camel-bean-4.0.0-RC2.jar:4.0.0-RC2] at org.apache.camel.component.bean.BeanProcessor.process(BeanProcessor.java:81) ~[camel-bean-4.0.0-RC2.jar:4.0.0-RC2] ... </code> How do I pass the route's instance of <code>Foo</code> to my <code>FooConsumer</code>? Some variations I have tried are: Variation Error <code>.bean(fooConsumer, ';processFoo(${body}, {{foo}})';)</code> <code>No type converter available to convert from type: java.lang.String to the required type: com.example.Foo</code> <code>.to(';bean:fooConsumer?method=processFoo(${body},#{{foo}})';)</code> <code>No type converter available to convert from type: java.lang.String to the required type: com.example.Foo</code> <code>.to(';bean:fooConsumer?method=processFoo(${body},{{foo}})';)</code> <code>No type converter available to convert from type: java.lang.String to the required type: com.example.Foo</code> <code>.bean(fooConsumer, ';processFoo(${body}, ${bean:#{{foo}}})';)</code> <code>No bean could be found in the registry for: #foo-1</code> <code>.bean(fooConsumer, ';processFoo(${body}, ${bean:{{foo}}})';)</code> <code>No bean could be found in the registry for: foo-1</code> Surely it's possible to do this since the examples show passing a <code>myClient</code> bean to a <code>aws2-s3</code> endpoint using the <code>#{{myClient}}</code> syntax.
|
I've found one way of using these route templates like I'm trying to here, but it doesn't feel very clean. Perhaps I'm trying to use these in a way they aren't intended to be used. Anyhow, to get it to work, I created a inner <code>ServiceActivator</code> class in the class defining the route template: <code>private class ServiceActivator { private final Foo foo; public ServiceActivator(final RouteTemplateContext routeTemplateContext) { this.foo = ( routeTemplateContext .getLocalBeanRepository () .lookupByNameAndType (';foo';, Foo.class) ); } @Handler public void processFoo(@Body final String body) { // do something } } </code> Then, I updated the route template to:Remove the declaration of <code>foo</code> because having the definition makes Camel attempt to create a default value for it. Create this <code>ServiceActivator</code> on route creation. Reference the <code>ServiceActivator</code> in the <code>bean</code> definition of the route.<code>routeTemplate(';myTemplate';) // Define the parameters for the route template .templateParameter (';fromEndpointUri';) .templateBean (';serviceActivator, ServiceActivator.class, ServiceActivator::new) // Define the route. .from(';{{fromEndpointUri}}';) .bean(';{{serviceActivator}}';) </code> And left my templated route as: <code>templatedRoute(';myTemplate';) .routeId (';myTemplateRoute';) .parameter (';fromEndpointUri';, ';direct:test';) .bean (';foo';, Foo.class, ignored ->; new Foo()); </code> Again, it seems almost like a hack rather than using this feature of a Camel in a way that it was intended to be used. From what I could tell stepping through the code, the route template parameters and beans are only available at the time of route creation, so this was a way of capturing all of that information during route creation to be used in later executions of the route.
|
apache-camel
|
I have developed a Java-Application using Apache Camel to archive a bunch of previously sorted files based upon the name of the subfolder they have been placed in. It works as expected running in Eclipse but fails to create the Route when I attempt to run the app outside of Eclipse, producing the following Error Message every time: <code>2023-08-07 13:20:03,527 [main] ERROR MyClass - Exception occured: org.apache.camel.FailedToCreateRouteException: Failed to create route route1 at: >;>;>; Aggregate[LotName ->; [SetHeader[CamelFileName, simple{${in.header.LotName}.zip}], Log[Finished Zipping: ${file:name}], DynamicTo[file:${in.header.CreatedPath}?fileName=${file:name.noext}-2023-08-07T13-20-03-328.${file:ext}&;fileExist=Move&;moveExisting=${file:name.noext}-1.${file:ext}]]] <<< in route: Route(route1)[From[EndpointA... because of Error parsing [1000] as a java.time.Duration. org.apache.camel.FailedToCreateRouteException: Failed to create route route1 at: >;>;>; Aggregate[LotName ->; [SetHeader[CamelFileName, simple{${in.header.LotName}.zip}], Log[Finished Zipping: ${file:name}], DynamicTo[file:${in.header.CreatedPath}?fileName=${file:name.noext}-2023-08-07T13-20-03-328.${file:ext}&;fileExist=Move&;moveExisting=${file:name.noext}-1.${file:ext}]]] <<< in route: Route(route1)[From[EndpointA because of Error parsing [1000] as a java.time.Duration. at org.apache.camel.reifier.RouteReifier.doCreateRoute(RouteReifier.java:241) at org.apache.camel.reifier.RouteReifier.createRoute(RouteReifier.java:75) at org.apache.camel.impl.DefaultModelReifierFactory.createRoute(DefaultModelReifierFactory.java:49) at org.apache.camel.impl.DefaultCamelContext.startRouteDefinitions(DefaultCamelContext.java:874) at org.apache.camel.impl.DefaultCamelContext.startRouteDefinitions(DefaultCamelContext.java:764) at org.apache.camel.impl.engine.AbstractCamelContext.doInit(AbstractCamelContext.java:2862) at org.apache.camel.support.service.BaseService.init(BaseService.java:83) at org.apache.camel.impl.engine.AbstractCamelContext.init(AbstractCamelContext.java:2568) at org.apache.camel.support.service.BaseService.start(BaseService.java:111) at org.apache.camel.impl.engine.AbstractCamelContext.start(AbstractCamelContext.java:2587) at org.apache.camel.impl.DefaultCamelContext.start(DefaultCamelContext.java:253) at org.apache.camel.main.Main.doStart(Main.java:116) at org.apache.camel.support.service.BaseService.start(BaseService.java:119) at org.apache.camel.main.MainSupport.run(MainSupport.java:69) at MyClass.main(MyClass.java:80) Caused by: java.lang.IllegalArgumentException: Error parsing [1000] as a java.time.Duration. at org.apache.camel.support.CamelContextHelper.parse(CamelContextHelper.java:556) at org.apache.camel.support.CamelContextHelper.parseDuration(CamelContextHelper.java:500) at org.apache.camel.reifier.AbstractReifier.parseDuration(AbstractReifier.java:78) at org.apache.camel.reifier.AggregateReifier.createAggregator(AggregateReifier.java:203) at org.apache.camel.reifier.AggregateReifier.createProcessor(AggregateReifier.java:54) at org.apache.camel.reifier.ProcessorReifier.makeProcessor(ProcessorReifier.java:838) at org.apache.camel.reifier.ProcessorReifier.addRoutes(ProcessorReifier.java:579) at org.apache.camel.reifier.RouteReifier.doCreateRoute(RouteReifier.java:237) ... 14 more Caused by: org.apache.camel.NoTypeConversionAvailableException: No type converter available to convert from type: java.lang.String to the required type: java.time.Duration with value 1000 at org.apache.camel.impl.converter.CoreTypeConverterRegistry.mandatoryConvertTo(CoreTypeConverterRegistry.java:275) at org.apache.camel.impl.converter.CoreTypeConverterRegistry.mandatoryConvertTo(CoreTypeConverterRegistry.java:207) at org.apache.camel.support.CamelContextHelper.parse(CamelContextHelper.java:553) ... 21 more </code> I have no idea where the Duration-Object comes from, what its purpose is or why its value is 1000. My Route: <code>public void configure() throws Exception { /* Takes files from origin folder, checks for valid file names and deletes files in their source folders */ from(FILECOMPONENT + sourceFolder + ';?recursive=true&;include=RAW(';+ lotFileRegex +';)&;delete=true';) .log(LoggingLevel.INFO, ';Starting to process file: ${file:name}';) // Extract our criteria to aggregate .process(new SubfolderExtractor()) // Aggregate Files based on Header ';LotName'; .log(LoggingLevel.INFO, ';Currently aggregating: ${in.header.LotName}';) .aggregate(header(';LotName';), new ZipAggregationStrategy()) .completionFromBatchConsumer().eagerCheckCompletion() .completionOnNewCorrelationGroup() // finish our archive when the subfolder is empty // Set Header FILE_NAME to LotName.zip .setHeader(Exchange.FILE_NAME, simple(';${in.header.LotName}.zip';)) .log(LoggingLevel.INFO, ';Finished Zipping: ${file:name}';) /* Drop Zip-Archives in same location as their origin, add the current date to make it unique */ .toD(FILECOMPONENT + ';${in.header.CreatedPath}?fileName=${file:name.noext}-';+LocalDateTime.now().toString().replace(':', '-').replace('.', '-')+';.${file:ext}&;fileExist=Move&;moveExisting=${file:name.noext}-1.${file:ext}';); </code> The use of raw java code in the .toD() at the end replaced an expression in Camel's built-in ';Simple'; language, as i assumed it was causing the problem. However, it did not change the fact that this route works in Eclipse but not outside of it, in fact it produces the same Error message. I am using Java 8 and Camel 3.14.7. The routes are run using Camel's Main Class.
|
You are likely creating an uber/fat-jar, and then make sure to do this accordingly to: https://camel.apache.org/manual/camel-maven-plugin.html#_camelprepare_fatjar
|
apache-camel
|
In the project , I've been dynamically loading Apache Camel routes during runtime. Current environment includes <code>Spring 2.7.4, Apache Camel 3.18.0, and JDK 17</code> <code>private void fromFile(final Path filepath) throws Exception { final byte[] routeDefinitionBytes = Files.readAllBytes(filepath); final Resource resource = ResourceHelper.fromBytes(filepath.toString(), routeDefinitionBytes); final ExtendedCamelContext extendedCamelContext = camelContext.adapt(ExtendedCamelContext.class); extendedCamelContext.getRoutesLoader().loadRoutes(resource); }</code> Now migrating project to utilize <code>Apache Camel 4.0.0-RC1</code>, <code>Spring Boot 3.1.1</code>, and continue to use <code>JDK 17</code>. The issue facing is that the adapt() method isn't available in the newer version of Apache Camel, rendering your existing code non-functional. I'm seeking a viable solution that can allow me to continue reading route definitions from a file and inject them into an Apache Camel context at runtime in <code>Apache Camel 4.0.0-RC1</code>. Any recommendations would be much appreciated.
|
For such a need, you can rely on the utility method <code>PluginHelper#getRoutesLoader(CamelContext)</code> but behind the scenes, the new logic is to call <code>getCamelContextExtension()</code> on the camel context to get the <code>ExtendedCamelContext</code>, then get the plugin that you want to use thanks to the method <code>ExtendedCamelContext#getContextPlugin(Class)</code>. So your code would then be: <code>private void fromFile(final Path filepath) throws Exception { final byte[] routeDefinitionBytes = Files.readAllBytes(filepath); final Resource resource = ResourceHelper.fromBytes( filepath.toString(), routeDefinitionBytes ); PluginHelper.getRoutesLoader(camelContext).loadRoutes(resource); } </code>
|
apache-camel
|
I have some projects using Apache Camel 3.21.0 running on Apache Karaf 4.4.3 and currently need to start an OPC server there. I want to use the camel-milo component to achieve this. However I noticed that the camel-milo feature is not available to install. So the command <code>feature:install camel-milo</code> fails saying that the feature is unknown. I checked the karaf camel feature list in maven repo and noticed <code>camel-milo</code> is not there at all. I tried to use the <code>bundle:install -s mvn:</code> command to manually install camel-milo from maven but this leads to a chain of dependency issues which makes no sense to manually manage. It seems the required dependencies are not automatically fetched and installed. It seems like the camel-milo component is still actively developed and maintained. I don't understand why it does not work like other camel components? i have used several components like <code>camel-jdbc, camel-paho, camel-xslt, camel-http</code> all using the <code>feature:install</code> command. It would be great if someone could provide or point me to a guide on how I can install and use <code>camel-milo</code> on Apache Karaf.
|
You cannot install it, and we do not provide karaf features for stuff that does not work in OSGi or is hard to install. Also btw camel-milo has been removed in Camel v4.
|
apache-camel
|
I would like to efficiently consume events from multiple MQTT topics in a single route in Apache Camel. The Paho MQTT component seems to support only 1 topic at the moment, while I had expected that you could include multiple topics separated by a comma like with the Kafka component. Kafka Component path parameter For example, suppose you have the following topics:a/b/c0 a/b/c1 a/b/.. a/b/c40but you are interested in all topics except topic a/b/c40. One option is to use MQTT topic wildcards and drop the events from topic a/b/c40. However, the problem is that c40 takes up a lot of bandwidth (95+ %) and this extra load should be avoided. Another option is to create a consumer route for each topic and connect these routes to the same destination route. However, creating and managing 40 mqtt clients does not seem ideal to me or is the overhead negligible? A third option is to initialize the MQTT client with client.subscribe(topiclist) before starting the route and then pass the MqttClient via the advanced option 'client'. Paho Component client option But I am unsure when the client.connect(connectOptions) method should be executed. If this connect method is not executed before starting the route, I receive a 'client not connected' error. But when I execute it before starting the route, then it seemed that the route was no longer receiving all messages. Which option do you think is best? In the case of the 3rd option, when should the client.connect method be called? Before/After starting the route, in the route ... ?
|
In my case I went with the second option. It is unfortunate but yes the Paho MQTT client on Camel does not support multiple topics in the same route. I have had this exact issue few months back where I had data coming in over MQTT from multiple (10+) production lines and around 5-6 topics per line with decent sized messages (don't remember the exact size but around 2 - 3 KB per message). I created a configuration CSV and a small gawk script to generate the camel blueprint, this made the management of the routes very simple. I used one camel context per production line. This data was later processed in one destination topic. Performance was not an issue and the application was able to handle messages coming in every 10 - 15 ms. I usually keep two settings in mind when dealing with high frequency large payloads:set the maxInflight property to a high value like 500, 1000 depending on your needs. This ensures no messages are lost due to too many in flight messages. Use a lower qos, like 0 or 1. This ensures that the broker does not get backed up too much and its very rare that a message is lost/not delivered.Only draw back when having so many routes and contexts is that they take some time to start up, but that is not something you would have to do often so its acceptable.
|
apache-camel
|
I'm migrating a Spring 2.6 project from Apache Camel v2.25.4 to v3.14, the last version that is compatible with Java 8. I'm using Maven as package manager. I'm getting this error: <code>Cannot resolve symbol 'CompletionAwareAggregationStrategy', TimeoutAwareAggregationStrategy' </code> Apparently, these interfaces are removed from version 3.0.0 onwards, but I couldn't find any information about it in the migration guide. The only related step is the following: Camel Upgrade guide to 3.7 - Modularized core. They are still mentioned in the documentation for version 3.14:AGGREGATING ON TIMEOUT COMPLETIONAWAREAGGREGATIONSTRATEGYI have tried importing other packages like the ones mentioned in the migration guide:camel-core-model camel-core-reifier camel-core-processorBut I had no success finding the symbols. I have also tried implementing my classes with these related interfaces, but they don't extend 'AggregationStrategy' interface, so it's not what I'm looking for.FlexibleAggregationStrategy.TimeoutAwareMixin FlexibleAggregationStrategy.CompletionAwareMixinIf they have been removed from Apache Camel, then how do you suggest I replace the interfaces?
|
They are out of the box on <code>org.apache.camel.AggregationStrategy</code> as default methods.
|
apache-camel
|
I'm facing some issue by reading nested data from an odata api. I'm using Olingo4 with camel 3.20.5. I first have to filter a collection by key and then want to return a collection from this value. The key-filter is a string, containing a space. In the browser, everything works fine. The url looks like this: <code>http://baseOdataUrl/Customer('23 abc')/Orders</code> where <code>Customer</code> is a collection and <code>Orders</code> is a <code>NavigationProperty</code> with type <code>Collection(NAV.Orders)</code>. My camel route looks like this: <code>from(';timer:mytimer?period=1000';) .to(';olingo4://read/Customer('23 abc')/Orders?serviceUri=baseOdataUrl&;httpAsyncClientBuilder=#myHttpClientBuilder';); </code> which is failing with error: Illegal character in url which indicates, it's not being parsed properly at the position of the space. I tried several approaches: <code>from(';timer:mytimer?period=1000';) .to(';olingo4://read/Customer('23%20abc')/Orders?serviceUri=baseOdataUrl&;httpAsyncClientBuilder=#myHttpClientBuilder';); </code> which is not returning anything. <code>from(';timer:mytimer?period=1000';) .to(';olingo4://read/Customer/Orders?serviceUri=baseOdataUrl&;httpAsyncClientBuilder=#myHttpClientBuilder';); </code> failing: Orders is not allowed after a collection <code>from(';timer:mytimer?period=1000';) .setHeader(';CamelOlingo4.keyPredicate';, constant(';23 abc';)) .to(';olingo4://read/Customer/Orders?serviceUri=baseOdataUrl&;httpAsyncClientBuilder=#myHttpClientBuilder';); </code> which is trying to filter the Orders, I think, because it's generating url like <code>/Customer/Orders(23 abc)</code> <code>from(';timer:mytimer?period=1000';) .setHeader(';CamelOlingo4.keyPredicate';, constant(';'23 abc'';)) // failing like before .setHeader(';CamelOlingo4.keyPredicate';, constant(';'23%20abc'';)) // failing like before .to(';olingo4://read/Customer/Orders?serviceUri=baseOdataUrl&;httpAsyncClientBuilder=#myHttpClientBuilder';); </code> I also tried to urlencode the <code>'</code> and double them. Still no luck. This working, but not what I want, because it's just returning the customers: <code>from(';timer:mytimer?period=1000';) .setHeader(';CamelOlingo4.$filter';, constant(';Name eq '23 abc'';)) .to(';olingo4://read/Customer?serviceUri=baseOdataUrl&;httpAsyncClientBuilder=#myHttpClientBuilder';); </code> This is generating an empty node <code>Orders</code> inside of Customers: <code>from(';timer:mytimer?period=1000';) .setHeader(';CamelOlingo4.$filter';, constant(';Name eq '23 abc'';)) .setHeader(';CamelOlingo4.$expand';, constant(';Orders';)) .to(';olingo4://read/Customer?serviceUri=baseOdataUrl&;httpAsyncClientBuilder=#myHttpClientBuilder';); </code> If I'm executing this in the browser, it's producing the same wrong result. So I just want to execute the working browser query from the beginning in camel and get the same correct results there. The httpClientBuilder is only being used for the NTLM authentication. I think, it's an easy query, which is running perfectly fine in browser, so there must be an issue with my syntax in camel. UPDATE It's working now, with the following route: <code>from(';timer:mytimer?period=1000';) .setHeader(';CamelOlingo4.resourcePath';, constant(';Customer('23%20abc')/Orders';)) .to(';olingo4:read?serviceUri=baseOdataUrl&;httpAsyncClientBuilder=#myHttpClientBuilder';); </code> Probably there were some issues during encoding. But now, I'm getting the following error: <code>ODataException: ';Unsupported resource type: navigationProperty'; </code> thrown here https://github.com/apache/camel/blob/3a550051b36e2f76d39c18b927e48158de007fd0/components/camel-olingo4/camel-olingo4-api/src/main/java/org/apache/camel/component/olingo4/api/impl/Olingo4AppImpl.java#L590 Is it not possible, to process the data? Many thanks in advance, and let me know, if I need to provide more information.
|
I ended up, using the <code>http</code> component of camel, put all the attributes like <code>$filter</code> and <code>$orderby</code> in the url and unmarshal the result as json with the <code>Jackson</code> library into my POJO. Thanks anyway for reading
|
apache-camel
|
i want to generate openApi documentation based on my cxf services. i used the following resources: https://cxf.apache.org/docs/openapifeature.html when I start the service without using camel-cxfrs - everything works as it should, openapi.json is generated and swagger-ui works, but when using camel-cxfrs - apache camel intercepts the openapi url and tries to process I have the following blueprint: <code><blueprint xmlns=';http://www.osgi.org/xmlns/blueprint/v1.0.0'; xmlns:xsi=';http://www.w3.org/2001/XMLSchema-instance'; xmlns:cm=';http://aries.apache.org/blueprint/xmlns/blueprint-cm/v1.1.0'; xmlns:cxf=';http://cxf.apache.org/blueprint/core'; xmlns:jaxrs=';http://cxf.apache.org/blueprint/jaxrs'; xmlns:camelcxf=';http://camel.apache.org/schema/blueprint/cxf'; xsi:schemaLocation='; http://www.osgi.org/xmlns/blueprint/v1.0.0 https://www.osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd http://cxf.apache.org/blueprint/core http://cxf.apache.org/schemas/blueprint/core.xsd http://cxf.apache.org/blueprint/jaxrs http://cxf.apache.org/schemas/blueprint/jaxrs.xsd ';>; <!-- JAXRS providers -->; <bean id=';jsonProvider'; class=';com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider'; />; <!-- CXF OpenApiFeature -->; <bean id=';openApiFeature'; class=';org.apache.cxf.jaxrs.openapi.OpenApiFeature';/>; <camelcxf:rsServer id=';myRsServer'; address=';/service'; serviceClass=';foo.MyService';>; <camelcxf:providers>; <ref component-id=';jsonProvider'; />; </camelcxf:providers>; <camelcxf:features>; <ref component-id=';openApiFeature'; />; </camelcxf:features>; </camelcxf:rsServer>; <camelContext xmlns=';http://camel.apache.org/schema/blueprint';>; <route>; <from uri=';cxfrs:bean:myRsServer';/>; .... </route>; </camelContext>; </blueprint>;</code> stack used:karaf 4.2.4 apache camel 2.23.2 cxf 3.2.7 cxf-rs-description-openapi-v3(karaf feature) org.webjars/swagger-ui/3.23.8(bundle)is there a way to ignore certain urls (like the same cxf/service/openapi.json) in apache camel?
|
fixed in next versions of camel and cxf https://issues.apache.org/jira/browse/CAMEL-12957
|
apache-camel
|
With Apache Camel on <code>3.20</code> version I used to use the <code>setDataFormatResolver</code> method, which was from <code>ExtendedCamelContext</code>, to set a custom data format in <code>CamelContext</code>. But since <code>4.0.0-M3</code> version, this method has been removed from the class. I'm wondering, how could I replace this method to some similar? I searched at the documentation, but I didn't find the answer I'm looking for. Another question about the same subject, now that <code>ExtendedCamelContext</code> is decoupled from <code>CamelContext</code>, when <code>ExtendedCamelContext</code> is instantiated the <code>CamelContext</code> will keep being one single instance?
|
To set a specific <code>DataFormatResolver</code> in Camel 4, you need to call the method ExtendedCamelContext.html#addContextPlugin. So assuming that the name of your custom class is <code>CustomDataFormatResolver</code>, the code would look like the following code snippet: <code>context.getCamelContextExtension().addContextPlugin( DataFormatResolver.class, new CustomDataFormatResolver() ); </code> Where <code>context</code> is your Camel context instance.Another question about the same subject, now that ExtendedCamelContext is decoupled from CamelContext, when ExtendedCamelContext is instantiated the CamelContext will keep being one single instance?Yes there is only one <code>ExtendedCamelContext</code> per <code>CamelContext</code>.
|
apache-camel
|
I'm trying to connect to outlook.office365.com with Apache Camel. I was following instructions for camel component ';Mail Microsoft Oauth'; On Azure side I created ';App registration'; and in my code I use ';Application (client) ID'; from that registration as client_id, and ';Directory (tenant) ID'; as tenant_id. Then I created client secret for that registration and I use ';value'; as client_secret. Last I granted API permission ';IMAP.AccessAsApp'; and granted Admin consent. In Java I have configured MicrosoftExchangeOnlineOAuth2MailAuthenticator <code> @Bean public MicrosoftExchangeOnlineOAuth2MailAuthenticator auth() { return new MicrosoftExchangeOnlineOAuth2MailAuthenticator( <tenant_id>;, <client_id>;, <client_secret>;, ';valid@email.com';); } </code> and Camel route <code>public class MailListenerRoute extends RouteBuilder { @Override public void configure() throws Exception { from(';imaps://outlook.office365.com:993'; + ';?authenticator=#auth'; + ';&;username=valid@email.com'; + ';&;mail.imaps.auth.mechanisms=XOAUTH2'; + ';&;mail.imap.auth.plain.disable=true'; + ';&;mail.imap.auth.xoauth2.disable=false'; + ';&;debugMode=true'; + ';&;delete=false';) .tracing() .log(';>;>;>; ${body}';); } } </code> I have experimented with both putting and removing, <code>username</code>, <code>mail.imap.auth.plain.disable</code> and <code>mail.imap.auth.xoauth2.disable</code> but there was no changes in result. I have put debug point at MicrosoftExchangeOnlineOAuth2MailAuthenticator and I have decoded JWT token that is received at method getPasswordAuthentication and I have confirmed by decoding it at JWT.ms that it is valid and that it contains <code> ';roles';: [ ';IMAP.AccessAsApp'; ] </code> When starting a flow this is logs for mail component: <code>DEBUG IMAPS: AUTHENTICATE XOAUTH2 command trace suppressed DEBUG IMAPS: AUTHENTICATE XOAUTH2 command result: B1 NO AUTHENTICATE failed. 2023-07-03 10:03:34.206 WARN 16471 --- [fice365.com:993] o.a.camel.component.mail.MailConsumer : Failed polling endpoint: imaps://outlook.office365.com:993?authenticator=%23auth&;debugMode=true&;delete=false&;mail.imaps.auth.mechanisms=XOAUTH2&;username=xxxxxx. Will try again at next poll. Caused by: [javax.mail.AuthenticationFailedException - AUTHENTICATE failed.]javax.mail.AuthenticationFailedException: AUTHENTICATE failed. at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:708) ~[jakarta.mail-1.6.7.jar:1.6.7]</code>
|
I have fixed the issue by following instructions to set Service Principle I had to run commands in Windows Powers Shell because command <code>Connect-ExchangeOnline -Organization <tenantId>;</code> was failing in Azure power shell with message <code>Connect-ExchangeOnline: A parameter cannot be found that matches parameter name 'Organization</code> I have run Windows Shell on AWS EC2 machine because I had no Windows available, and there was no problems. All commands I have executed in Windows Shell: <code>Install-Module -Name ExchangeOnlineManagement -allowprerelease Import-module ExchangeOnlineManagement Connect-ExchangeOnline -Organization <tenantId>;$AADServicePrincipalDetails = Get-AzureADServicePrincipal -SearchString YourAppNameNew-ServicePrincipal -AppId $AADServicePrincipalDetails.AppId -ObjectId $AADServicePrincipalDetails.ObjectId -DisplayName ';EXO Serviceprincipal for AzureAD App $($AADServicePrincipalDetails.Displayname)';$EXOServicePrincipal = Get-ServicePrincipal -Identity ';EXO Serviceprincipal for AzureAD App YourAppName';Add-MailboxPermission -Identity ';valid@email.com'; -User $EXOServicePrincipal.Identity -AccessRights FullAccess </code>
|
apache-camel
|
Good afternoon, I am currently working with Quarkus 2.16 and Apache Camel 3.20.1, and I have the following error that happens when doing the native compilation with GraalVm and it runs in a Docker container, when I do not apply native compilation there is no problem: <code>javax.net.ssl.SSLException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty at java.base@17.0.7/sun.security.ssl.Alert.createSSLException(Alert.java:133) at java.base@17.0.7/sun.security.ssl.TransportContext.fatal(TransportContext.java:378) at java.base@17.0.7/sun.security.ssl.TransportContext.fatal(TransportContext.java:321) at java.base@17.0.7/sun.security.ssl.TransportContext.fatal(TransportContext.java:316) at java.base@17.0.7/sun.security.ssl.SSLSocketImpl.handleException(SSLSocketImpl.java:1712) at java.base@17.0.7/sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:470) at java.base@17.0.7/sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:426) at org.apache.http.conn.ssl.SSLConnectionSocketFactory.createLayeredSocket(SSLConnectionSocketFactory.java:436) at org.apache.http.conn.ssl.SSLConnectionSocketFactory.connectSocket(SSLConnectionSocketFactory.java:384) at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:142) at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:376) at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:393) at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:236) at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:186) at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:89) at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185) at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:72) at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:56) at org.apache.camel.component.http.HttpProducer.executeMethod(HttpProducer.java:445) at org.apache.camel.component.http.HttpProducer.process(HttpProducer.java:273) at org.apache.camel.support.AsyncProcessorConverterHelper$ProcessorToAsyncProcessorBridge.process(AsyncProcessorConverterHelper.java:66) at org.apache.camel.processor.SendProcessor.process(SendProcessor.java:172) 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 io.quarkus.vertx.core.runtime.VertxCoreRecorder$14.runWith(VertxCoreRecorder.java:576) 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@17.0.7/java.lang.Thread.run(Thread.java:833) at org.graalvm.nativeimage.builder/com.oracle.svm.core.thread.PlatformThreads.threadStartRoutine(PlatformThreads.java:775) at org.graalvm.nativeimage.builder/com.oracle.svm.core.posix.thread.PosixPlatformThreads.pthreadStartRoutine(PosixPlatformThreads.java:203) </code> My main Rest Route code is like the following: <code>package org.tmve.customer.ms.route; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.model.rest.RestBindingMode; import org.apache.http.conn.HttpHostConnectException; import org.eclipse.microprofile.config.inject.ConfigProperty; import org.tmve.customer.ms.beans.Customer; import org.tmve.customer.ms.exceptions.InvalidFormatException; import org.tmve.customer.ms.exceptions.RequiredValueException; import org.tmve.customer.ms.processor.*;import javax.enterprise.context.ApplicationScoped; import java.net.UnknownHostException; import java.text.SimpleDateFormat; import java.util.TimeZone;import static org.apache.camel.model.rest.RestParamType.body;@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; public ResRoute() { configureSsl = new ConfigureSsl(); } @Override public void configure() throws Exception { 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(';/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('; [';+getCurrentDate()+';]';+';User ID: ${exchangeProperty[userId]}';) .log('; [';+getCurrentDate()+';]';+';Tipo de Documento (Num): ${exchangeProperty[documentTypeNum]}';) .log('; [';+getCurrentDate()+';]';+';Tipo de Cliente: ${exchangeProperty[customerType]}';) .choice() .when(simple(';${exchangeProperty[customerType]} == 'NATURAL'';)) .process(new FindIndividualCustomerByDocIdProcessorReq()) .log('; [';+getCurrentDate()+';]';+';Entrada del microservicio FindIndividualCustomerByDocId ${exchangeProperty[findIndividualCustomerByDocIdRequest]}';) .to(configureSsl.setupSSLContext(getCamelContext(), findIndividualCustomerByDocId)) .process(new FindIndividualCustomerByDocIdProcessorRes()) .log('; [';+getCurrentDate()+';]';+';Salida del microservicio FindIndividualCustomerByDocId ${exchangeProperty[findIndividualCustomerByDocIdResponse]}';) .log('; [';+getCurrentDate()+';]';+';Salida del microservicio BSS FindCustomerByDocId ${exchangeProperty[findCustomerByDocIdResponse]}';) .when(simple(';${exchangeProperty[customerType]} == 'JURIDICO'';)) .process(new FindOrganizationCustomerByDocIdProcessorReq()) .log('; [';+getCurrentDate()+';]';+';Entrada del microservicio FindOrganizationCustomerByDocId ${exchangeProperty[findOrganizationCustomerByDocIdRequest]}';) .to(configureSsl.setupSSLContext(getCamelContext(), findOrganizacionCustomerByDocId)) .process(new FindOrganizationCustomerByDocIdProcessorRes()) .log('; [';+getCurrentDate()+';]';+';Salida del microservicio FindOrganizationCustomerByDocId ${exchangeProperty[findOrganizationCustomerByDocIdResponse]}';) .log('; [';+getCurrentDate()+';]';+';Salida del microservicio BSS FindCustomerByDocId ${exchangeProperty[findCustomerByDocIdResponse]}';) .endChoice() .endDoTry() .doCatch(RequiredValueException.class) .process(new FindCustomerByDocIdProcessorInvalidFormatException()) .log('; [';+getCurrentDate()+';]';+';Descripcion de la Exception: ${exception.message}';) .log('; [';+getCurrentDate()+';]';+';Salida del microservicio BSS FindCustomerByDocId: ${exchangeProperty[bodyRs]}';) .doCatch(HttpHostConnectException.class) .process(new FindCustomerByDocIdProcessorHttpHostConectionException()) .log('; [';+getCurrentDate()+';]';+';Descripcion de la Exception: ${exception.message}';) .log('; [';+getCurrentDate()+';]';+';Salida del microservicio BSS FindCustomerByDocId: ${exchangeProperty[bodyRs]}';) .doCatch(InvalidFormatException.class) .process(new FindCustomerByDocIdProcessorInvalidFormatException()) .log('; [';+getCurrentDate()+';]';+';Descripcion de la Exception: ${exception.message}';) .log('; [';+getCurrentDate()+';]';+';Salida del microservicio BSS FindCustomerByDocId: ${exchangeProperty[bodyRs]}';) /* .doCatch(NotFoundException.class) .process(new FindCustomerByDocIdProcessorInvalidFormatException()) .log('; [';+getCurrentDate()+';]';+';Salida del microservicio ${exchangeProperty[microserviceName]} ${exchangeProperty[boydResponse]}';) .log('; [';+getCurrentDate()+';]';+';Salida del BSS FindAccountBalance ${exchangeProperty[bodyRs]}';) */ .doCatch(UnknownHostException.class) .process(new FindCustomerByDocIdProcessorInformationSubscriber()) .log('; [';+getCurrentDate()+';]';+';Descripcion de la Exception: ${exception.message}';) .log('; [';+getCurrentDate()+';]';+';Salida del microservicio BSS FindCustomerByDocId: ${exchangeProperty[bodyRs]}';); /*.doCatch(Exception.class) .process(new FindCustomerByDocIdProcessorException()) .log('; [';+getCurrentDate()+';]';+';Descripcion de la Exception ${exception.message}';) .log('; [';+getCurrentDate()+';]';+';Salida del microservicio BSS FindCustomerByDocId ${exchangeProperty[bodyRs]}';);*/ } private String getCurrentDate() { String timeStamp =';';; SimpleDateFormat formatter = new SimpleDateFormat(';yyyy-MM-dd'T'HH:mm:ssZ';); formatter.setTimeZone(TimeZone.getTimeZone(';GMT-4';)); timeStamp= formatter.format(new java.util.Date()); return timeStamp; } } </code> The error occurs in the following line in the Class Rest Route, when it makes the call to the configuration of the ConfigureSsl class that I attach below:ConfigureSsl <code>package org.tmve.customer.ms.route;import lombok.extern.slf4j.Slf4j; import org.apache.camel.CamelContext; import org.apache.camel.Endpoint; import org.apache.camel.component.http.HttpComponent; import org.apache.camel.support.jsse.KeyManagersParameters; import org.apache.camel.support.jsse.KeyStoreParameters; import org.apache.camel.support.jsse.SSLContextParameters; import org.apache.camel.support.jsse.TrustManagersParameters; import org.apache.http.conn.ssl.AllowAllHostnameVerifier; import org.eclipse.microprofile.config.ConfigProvider;@Slf4j public class ConfigureSsl { private String password = ConfigProvider.getConfig().getValue(';client.password';, String.class); private String resource = ConfigProvider.getConfig().getValue(';client.file';, String.class); public Endpoint setupSSLContext(CamelContext camelContext, String url) throws Exception { KeyStoreParameters keyStoreParameters = new KeyStoreParameters(); /*log.info(resource);*/ /*log.info(password);*/ keyStoreParameters.setResource(resource); keyStoreParameters.setPassword(password); KeyManagersParameters keyManagersParameters = new KeyManagersParameters(); keyManagersParameters.setKeyStore(keyStoreParameters); keyManagersParameters.setKeyPassword(password); /*log.info(';keyManagersParameters ';+ keyManagersParameters);*/ TrustManagersParameters trustManagersParameters = new TrustManagersParameters(); trustManagersParameters.setKeyStore(keyStoreParameters); /*log.info(';trustManagersParameters ';+ trustManagersParameters);*/ SSLContextParameters sslContextParameters = new SSLContextParameters(); sslContextParameters.setKeyManagers(keyManagersParameters); sslContextParameters.setTrustManagers(trustManagersParameters); /*log.info(';sslContextParameters ';+ sslContextParameters);*/ HttpComponent httpComponent = camelContext.getComponent(';https';, HttpComponent.class); httpComponent.setSslContextParameters(sslContextParameters); httpComponent.setX509HostnameVerifier(new AllowAllHostnameVerifier()); /*log.info(';httpComponent ';+ httpComponent); */ return httpComponent.createEndpoint(url); }} </code> Attached my properties file: <code>#https quarkus.ssl.native=true quarkus.http.ssl-port=${PORT:8080} quarkus.http.read-timeout=${READ_TIMEOUT:30000} quarkus.http.insecure-requests=disabled quarkus.http.ssl.certificate.key-store-file=${UBICATION_CERTIFICATE_SSL:srvdevrma1.jks} quarkus.http.ssl.certificate.key-store-file-type=JKS quarkus.http.ssl.certificate.key-store-password=${PASSWORD_CERTIFICATE_SSL:service123} quarkus.http.ssl.certificate.key-store-key-alias=${ALIAS_CERTIFICATE_SSL:srvdevrma1} quarkus.http.cors=trueclient.file=srvdevrma1.jks client.password=service123#GlobalVariables server.variables.msgType=RESPONSE server.variables.msgTypeError=ERROR descripcion.servicio=MicroServicio orquestador encargado de realizar la consulta de detalle de facturas para cuentas postpago..error.400.code=INVALID_ARGUMENT error.400.message=Client specified an invalid argument, request body or query paramerror.403.code=PERMISSION_DENIED error.403.message=Authenticated user has no permission to access the requested resourceerror.404.code=NOT_FOUND error.404.message=A specified resource is not founderror.500.code=INTERNAL error.500.message=Server errorerror.503.code=UNAVAILABLE error.503.message=Service unavailableerror.504.code=TIMEOUT error.504.message=Request timeout exceeded. Try it laterdescripcion.servicio=MicroServicio que permite orquestar la busqueda de informacion asociados a clientes Naturales y Juridicos#endpoints_ms- local client.findIndividualCustomerByDocId=${UBICATION-URL-FIND-INDIVIDUAL-CUSTOMER-BY-DOC-ID:https://localhost:8081/api/FindIndividualCustomerByDocId} client.findOrganizacionCustomerByDocId=${UBICATION-URL-FIND-ORGANIZATION-CUSTOMER-BY-DOC-ID:https://localhost:8082/api/FindOrganizationCustomerByDocId} #timeZone quarkus.jackson.timezone=${TIME_ZONE:GMT-4}#Ruta OpenApi path.openapi=/users/.*/customers/openapi/swagger-ui/ quarkus.camel.openapi.expose.enabled=true #camel.rest.api-context-path = /openapi.yaml #quarkus.swagger-ui.urls.camel = /openapi.yaml #openapi quarkus.smallrye-openapi.path=/api/FindCustomerByDocId/swagger #quarkus.swagger-ui.path= /api/FindCustomerByDocId/swagger-ui/ quarkus.swagger-ui.always-include=true#opentelemetry quarkus.application.name=FindCustomerByDocId quarkus.opentelemetry.enabled=true quarkus.opentelemetry.tracer.exporter.otlp.endpoint=${URL_JAEGER:http://172.28.2.107:4317} quarkus.log.console.format=%d{HH:mm:ss} %-5p traceId=%X{traceId}, parentId=%X{parentId}, spanId=%X{spanId}, sampled=%X{sampled} [%c{2.}] (%t) %s%e%n quarkus.http.header.';X-Content-Type-Options';.value=nosniff quarkus.http.header.';X-Frame-Options';.value=DENY quarkus.http.header.';Content-Security-Policy';.value=default-src </code> My pom.xml: <code><?xml version=';1.0';?>; <project xsi:schemaLocation=';http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd'; xmlns=';http://maven.apache.org/POM/4.0.0'; xmlns:xsi=';http://www.w3.org/2001/XMLSchema-instance';>; <modelVersion>;4.0.0</modelVersion>; <groupId>;org.tmve.customer</groupId>; <artifactId>;find-customer-by-doc-id</artifactId>; <version>;1.0.0-SNAPSHOT</version>; <properties>; <compiler-plugin.version>;3.10.1</compiler-plugin.version>; <maven.compiler.release>;17</maven.compiler.release>; <project.build.sourceEncoding>;UTF-8</project.build.sourceEncoding>; <project.reporting.outputEncoding>;UTF-8</project.reporting.outputEncoding>; <quarkus.platform.artifact-id>;quarkus-bom</quarkus.platform.artifact-id>; <quarkus.platform.group-id>;io.quarkus.platform</quarkus.platform.group-id>; <quarkus.platform.version>;2.16.7.Final</quarkus.platform.version>; <skipITs>;true</skipITs>; <surefire-plugin.version>;3.0.0-M7</surefire-plugin.version>; <jacoco.version>;0.8.7</jacoco.version>; <java.version>;17</java.version>; </properties>; <dependencyManagement>; <dependencies>; <dependency>; <groupId>;${quarkus.platform.group-id}</groupId>; <artifactId>;${quarkus.platform.artifact-id}</artifactId>; <version>;${quarkus.platform.version}</version>; <type>;pom</type>; <scope>;import</scope>; </dependency>; <dependency>; <groupId>;${quarkus.platform.group-id}</groupId>; <artifactId>;quarkus-camel-bom</artifactId>; <version>;${quarkus.platform.version}</version>; <type>;pom</type>; <scope>;import</scope>; </dependency>; </dependencies>; </dependencyManagement>; <dependencies>; <dependency>; <groupId>;org.apache.camel.quarkus</groupId>; <artifactId>;camel-quarkus-rest-openapi</artifactId>; </dependency>; <dependency>; <groupId>;org.apache.camel.quarkus</groupId>; <artifactId>;camel-quarkus-bean</artifactId>; </dependency>; <dependency>; <groupId>;org.apache.camel.quarkus</groupId>; <artifactId>;camel-quarkus-direct</artifactId>; </dependency>; <dependency>; <groupId>;org.apache.camel.quarkus</groupId>; <artifactId>;camel-quarkus-http</artifactId>; </dependency>; <dependency>; <groupId>;org.apache.camel.quarkus</groupId>; <artifactId>;camel-quarkus-jackson</artifactId>; </dependency>; <dependency>; <groupId>;org.apache.camel.quarkus</groupId>; <artifactId>;camel-quarkus-jaxb</artifactId>; </dependency>; <dependency>; <groupId>;org.apache.camel.quarkus</groupId>; <artifactId>;camel-quarkus-log</artifactId>; </dependency>; <dependency>; <groupId>;org.apache.camel.quarkus</groupId>; <artifactId>;camel-quarkus-rest</artifactId>; </dependency>; <dependency>; <groupId>;io.quarkus</groupId>; <artifactId>;quarkus-resteasy-jsonb</artifactId>; </dependency>; <dependency>; <groupId>;io.quarkus</groupId>; <artifactId>;quarkus-arc</artifactId>; </dependency>; <dependency>; <groupId>;org.projectlombok</groupId>; <artifactId>;lombok</artifactId>; <version>;1.18.22</version>; </dependency>; <dependency>; <groupId>;org.apache.camel.quarkus</groupId>; <artifactId>;camel-quarkus-openapi-java</artifactId>; </dependency>; <dependency>; <groupId>;io.quarkus</groupId>; <artifactId>;quarkus-smallrye-openapi</artifactId>; </dependency>; <dependency>; <groupId>;org.webjars</groupId>; <artifactId>;swagger-ui</artifactId>; <version>;4.11.1</version>; </dependency>; <dependency>; <groupId>;org.apache.camel.quarkus</groupId>; <artifactId>;camel-quarkus-opentelemetry</artifactId>; </dependency>; <dependency>; <groupId>;io.quarkus</groupId>; <artifactId>;quarkus-opentelemetry-exporter-otlp</artifactId>; </dependency>; <dependency>; <groupId>;io.quarkus</groupId>; <artifactId>;quarkus-junit5</artifactId>; <scope>;test</scope>; </dependency>; <dependency>; <groupId>;io.quarkus</groupId>; <artifactId>;quarkus-jacoco</artifactId>; <scope>;test</scope>; </dependency>; <dependency>; <groupId>;io.rest-assured</groupId>; <artifactId>;rest-assured</artifactId>; </dependency>; </dependencies>; </code> Dockerfile.native <code>FROM registry.access.redhat.com/ubi8/ubi-minimal:8.6 WORKDIR /work/ ADD src/main/resources/srvdevrma1.jks /work/srvdevrma1.jks RUN chown 1001 /work \ &;&; chmod ';g+rwX'; /work \ &;&; chown 1001:root /work COPY --chown=1001:root target/*-runner /work/application EXPOSE 8080 USER 1001 ENV TZ=';America/Caracas'; CMD [';./application';, ';-Dquarkus.http.host=0.0.0.0';] </code> That could be happening? First time this error happens to me
|
When you see the error <code>the trustAnchors parameter must be non-empty</code>, it usually means that the <code>KeyStore</code> could not be found. What's probably happening is that Camel is trying to look up your <code>KeyStore</code> file from the classpath. For this to work in native mode, the file needs to be added as a resource on the native image. You can do that with some configuration: <code>quarkus.native.resources.includes=*.jks </code> Here's the relevant section in the Camel Quarkus user guide: https://camel.apache.org/camel-quarkus/3.0.x/user-guide/native-mode.html#embedding-resource-in-native-executable Alternatively, if you want to read directly from the filesystem then you must prefix the resource string with the <code>file:</code> scheme. E.g <code>file:/work/srvdevrma1.jks</code>. See notes in the Camel user guide here: https://camel.apache.org/manual/camel-configuration-utilities.html#CamelConfigurationUtilities-KeyStoreParameters
|
apache-camel
|
I am following a tutorial, on using SpringBoot ApacheCamel with RabbitMQ I am at the stage, where I just want to create a queue the code is as follows <code>@SpringBootApplication @ComponentScan(basePackages = {';com.cav.routes';}) public class CamelApacheMicroServiceAApplication { public static void main(String[] args) { SpringApplication.run(CamelApacheMicroServiceAApplication.class, args); }} </code> <code>@Configuration public class CamelConfiguration { // name as rabbitConnectionFactory camel will autoimport it @Bean public ConnectionFactory rabbitConnectionFactory() { ConnectionFactory factory = new ConnectionFactory(); factory.setHost(';localhost';); factory.setPort(5672); factory.setUsername(';guest';); factory.setPassword(';guest';); return factory; } }</code> <code>@Component public class WeatherRouter extends RouteBuilder{ public static final String RABBIT_URI = ';rabbitmq:amq.direct?queue=weather&;routingKey=weather&;autoDelete=false';; @Override public void configure() throws Exception { // TODO Auto-generated method stub //define camel route //rabbitmq:exchange from(RABBIT_URI) .log(ERROR, ';Got this message from RabbitMQ: ${body}';); }} </code> As I understand it the command <code>from(';rabbitmq:amq.direct?queue=weather&;routingKey=weather&;autoDelete=false';) </code> Should create a queue called weather But when I look at my rabbitmq a queue has not been created my pom is I am using java 17 with camel 3.7.3, which maybe the problem. <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.0.8</version>; <relativePath />; <!-- lookup parent from repository -->; </parent>; <groupId>;com.cav.routes</groupId>; <artifactId>;CamelApacheMicroServiceA</artifactId>; <version>;0.0.1-SNAPSHOT</version>; <name>;CamelApacheMicroServiceA</name>; <description>;Demo project for Spring Boot</description>; <properties>; <java.version>;17</java.version>; </properties>; <dependencies>; <dependency>; <groupId>;org.springframework.boot</groupId>; <artifactId>;spring-boot-starter-actuator</artifactId>; </dependency>; <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>;3.7.3</version>; </dependency>; <dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-rabbitmq</artifactId>; <version>;3.7.3</version>; </dependency>; <dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-rabbitmq</artifactId>; <version>;3.7.3</version>; </dependency>; <dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-jackson</artifactId>; <version>;3.7.3</version>; </dependency>; <dependency>; <groupId>;org.springframework.boot</groupId>; <artifactId>;spring-boot-devtools</artifactId>; <scope>;runtime</scope>; <optional>;true</optional>; </dependency>; <dependency>; <groupId>;org.springframework.boot</groupId>; <artifactId>;spring-boot-starter-test</artifactId>; <scope>;test</scope>; </dependency>; </dependencies>; <build>; <plugins>; <plugin>; <groupId>;org.springframework.boot</groupId>; <artifactId>;spring-boot-maven-plugin</artifactId>; </plugin>; </plugins>; </build>; </project>; </code> Thank you for any help
|
See on this webpage: https://github.com/apache/camel-spring-boot-examples/blob/main/rabbitmq/src/main/resources/application.properties <code># turn on auto declare so the exchange, queues are automatic created if not already present in rabbitmq broker camel.component.spring-rabbitmq.auto-declare = true </code>
|
apache-camel
|
We have an Apache Camel route consuming messages from an IBM MQ request queue and sending messages back to a response queue. It will look like below: <code>from(';jms:request.queue';) .routeId(';my-route';) .process(myProcessor) .to(';jms:response.queue';).id(';response';) .log(';work done';) </code> No need to say that the above example is heavily simplified. In reality it is relatively complex using some <code>filter</code> and <code>choice</code> constructs as well as two internal <code>direct</code> sub routes. The complexity makes you want to have unit tests in place to make sure the expected functionality is there. To avoid connecting to a JMS broker and have the test still verify the end to end flow the easiest way would be to mock the entry and the output endpoints using <code>AdviceWith</code> provided by Camel. Our environment configuration is driven from <code>yaml</code> files, and our unit tests looks like below: <code>@CamelSpringBootTest @ContextConfiguration(classes = { CamelConfig.class, JmsConfig.class ... // many other classes required to build the application context for this route }, // The initialiser below is needed to load yaml configuration initializers = ConfigDataApplicationContextInitializer.class) @EnableConfigurationProperties(value = IbmMqConfig.class) @ActiveProfiles(';test';) @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD) @UseAdviceWith class MyRouteTest { @Autowired private MyRouteBuilder myRouteBuilder; @Autowired private CamelContext camelContext; @EndpointInject(uri=';mock:response-queue';) private MockEndpoint mockResponseQueue; @Produce(';direct:start';) private ProducerTemplate producerTemplate; @Test void shouldWorkAsExpected() { AdviceWith.adviceWith(';my-route';), camelContext, new AdviceWithRouteBuilder(camelContext) { @Override public void configure() throws Exception { replaceFromWith(';direct:start';); weaveById(';response';).replace().to(mockReesponseQueue); } }); // The rest of the test goes here }} </code> In other words what I done above was to follow the Apache Camel Spring testing documentation . The only difference I had was that rather than specifying the configuration via <code>@SpringBootTest</code> annotation I used <code>@ContextConfiguration</code> instead. This was because I wanted to to be able to load <code>yaml</code> config file. My problem is that when trying to run the test the camel context is not started and the route is not configured. It is only when explicitly calling <code>camelContext.start()</code> that the route is actually started. When using jUnit 4 and the old <code>RunWith</code> approach we never had to do this and everything worked perfectly. So my question is what I am doing wrong and how can I fix it? Thank you in advance.
|
It is actually the normal behavior when you annotate your test class with <code>@UseAdviceWith</code>. Indeed by doing so, you indicate <code>camel-test-spring-junit5</code> that you want to alter the routes consequently it cannot start the context automatically as they need to be altered before starting the context. See the Javadoc of <code>UseAdviceWith</code> for more details, I quote:Indicates the use of adviceWith() within the test class. If a class is annotated with this annotation and value() returns true, any CamelContexts bootstrapped during the test through the use of Spring Test loaded application contexts will not be started automatically. The test author is responsible for injecting the Camel contexts into the test and executing CamelContextLifecycle.start() on them at the appropriate time after any advice has been applied to the routes in the Camel context(s).
|
apache-camel
|
Karaf 4.4.3, camel 3.20.5 I have a blueprint with <code> <bean id=';activemq'; class=';org.apache.camel.component.activemq.ActiveMQComponent';>; <property name=';brokerURL'; value=';tcp://localhost:61616'; />; <property name=';username'; value=';karaf'; />; <property name=';password'; value=';karaf'; />; </bean>; </code> I get error when I try to start my app inside of karaf: <code>org.osgi.service.blueprint.container.ComponentDefinitionException: Error when instantiating bean activemq of class org.apache.camel.component.activemq.ActiveMQComponent ... Caused by: java.lang.NoClassDefFoundError: javax/jms/JMSContext ... Caused by: java.lang.ClassNotFoundException: javax.jms.JMSContext not found by org.apache.geronimo.specs.geronimo-jms_1.1_spec [203] </code> My features: <code> <feature>;transaction</feature>; <feature>;jndi</feature>; <feature>;pax-jdbc-config</feature>; <feature>;pax-jdbc-postgresql</feature>; <feature>;pax-jdbc-pool-dbcp2</feature>; <feature>;jdbc</feature>; <feature>;jms</feature>; <feature>;activemq-client</feature>; <feature>;pax-jdbc</feature>; <feature dependency=';true';>;aries-blueprint</feature>; <feature>;cxf</feature>; <feature>;camel-activemq</feature>; </code> I've also tried initializing ActiveMQConnectionFactory but was getting same NoClassDeffound error. Also tried installing <code>bundle:install mvn:javax.jms/javax.jms-api/2.0.1</code>, but that didn't help. I'm guessing there is some API mismatch or I'm missing a dependency. Without the ActiveMQComponent the bundle was working fine. The activemq broker is inside the same karaf instance, I'm connecting to it via hawtio with no issues.
|
That component is wired to JMS 2.0 API jar. You need to change your feature to install a javax.jms-api jar that is 2.0 and not the geronimo-jms-api jar that supports JMS v1.1
|
apache-camel
|
I am new to Java/Camel/GCP and I'm attempting to create an Apache Camel project that integrates with Google PubSub. Basically, I have a topic and a payload and I need to be able to publish a message, queue messages, subscribe or handle any errors. Are there any good examples out there that do this or how do I approach this? Thanks!
|
To get started with the Apache camel integration with Cloud Pub/Sub, I would recommend going about implementing the unit test of the same which is mentioned in their official GitHub thread. To test it out in the local you can make use of the PubSub Emulator. All the examples for testing are available here.
|
apache-camel
|
I am running Camel inside ActiveMQ trying to connect to an Azure ServiceBus Queue, but <code>org.apache.camel.component.azure.servicebus.ServiceBusConfiguration</code> appears only to accept a <code>connectionString</code> property. Sadly I don't have and can't get a connection string. I have been allocated a ClientID, Tenant ID, Secret instead. I can't work out how to implement this with my existing xml based configuration. I have tried to craft a connection string from the details I have but I guess this is not possible. <code> <endpoint id=';azureQueueEndpoint'; uri=';azureServiceBusComponent:iris.705d3ce1-xxxx-4fdf-acb3-xxxxxx'; />; <route id=';Elexon_IRIS_Route';>; <from uri=';azureQueueEndpoint'; />; <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=';connectionString'; value=';Endpoint=https://elexon-iris.servicebus.windows.net/iris.705d3ce1-xxxx-4fdf-acb3-xxxxxx;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=?????;EntityPath=iris.705d3ce1-xxxx-4fdf-acb3-xxxxxx'; />; </bean>; </property>; </bean>; </code> I'm not great with Java and can only really understand xml based config. Currently I get the following error when starting the route; <code>WARN | {';az.sdk.message';:';Non-retryable error occurred in AMQP receive link.';,';exception';:';status-code: 401, status-description: InvalidSignature: The token has an invalid signature., errorContext[NAMESPACE: elexon-iris.servicebus.windows.net. ERROR CONTEXT: N/A, PATH: $cbs, REFERENCE_ID: cbs:receiver, LINK_CREDIT: 0]';,';linkName';:';n/a';,';entityPath';:';n/a';} ERROR | Errors occurred upstream. </code> I am trying to connect to the ServiceBus and bridge the message feed to an ActiveMQ queue. The is using data from Elexon-IRIS (free service)
|
Somehow I have been able to resolve the connection issue. In part thanks to Chat-GPT for providing an example based on the source code from the com.azure.identity jar. I will not list all the dependant .jars as there are many... <code><endpoint id=';azureQueueEndpoint'; uri=';azureServiceBusComponent:iris.705d3ce1-xxxx-4fdf-acb3-xxxxxxxx'; />;<route id=';Elexon_IRIS_Route';>; <from uri=';azureQueueEndpoint'; />; <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=';tokenCredential'; ref=';azauth'; />; <property name=';credentialType'; value=';TOKEN_CREDENTIAL'; />; <property name=';fullyQualifiedNamespace'; value=';elexon-iris.servicebus.windows.net'; />; </bean>; </property>; </bean>;<bean id=';azauth'; class=';com.azure.identity.ClientSecretCredential';>; <constructor-arg value=';AZURE_TENANT_ID';/>; <constructor-arg value=';CLIENT_ID';/>; <constructor-arg value=';CLIENT_SECRET';/>; <constructor-arg>; <bean class=';com.azure.identity.implementation.IdentityClientOptions';/>; </constructor-arg>; </bean>; </code> On connection I now get a valid token; <code> INFO | Azure Identity =>; getToken() result for scopes [https://servicebus.azure.net/.default]: SUCCESS INFO | {';az.sdk.message';:';Scheduling refresh token task.';,';scopes';:';https://servicebus.azure.net/.default';} INFO | {';az.sdk.message';:';Creating a new receiver link.';,';connectionId';:';MF_77e428_1686394354332';,';sessionName';:';iris.705d3ce1-xxxx-4fdf-acb3-xxxxxxxx';,';linkName';:';iris.705d3ce1-xxxx-4fdf-acb3-xxxxxxxx_76bf6f_1686394354961';} INFO | {';az.sdk.message';:';Setting next AMQP receive link.';,';linkName';:';iris.705d3ce1-xxxx-4fdf-acb3-0fcb836d2bc9_76bf6f_1686394354961';,';entityPath';:';iris.705d3ce1-xxxx-4fdf-acb3-xxxxxxxx';} INFO | {';az.sdk.message';:';Returning existing receive link.';,';connectionId';:';MF_77e428_1686394354332';,';linkName';:';iris.705d3ce1-690e-4fdf-acb3-0fcb836d2bc9_76bf6f_1686394354961';,';entityPath';:';iris.705d3ce1-xxxx-4fdf-acb3-xxxxxxxx';} INFO | {';az.sdk.message';:';onLinkRemoteOpen';,';connectionId';:';MF_77e428_1686394354332';,';entityPath';:';iris.705d3ce1-xxxx-4fdf-acb3-xxxxxxxx';,';linkName';:';iris.705d3ce1-xxxx-4fdf-acb3-xxxxxxxx_76bf6f_1686394354961';,';remoteSource';:';Source{address='iris.705d3ce1-xxxx-4fdf-acb3-xxxxxxxx', durable=NONE, expiryPolicy=SESSION_END, timeout=0, dynamic=false, dynamicNodeProperties=null, distributionMode=null, filter=null, defaultOutcome=null, outcomes=null, capabilities=null}';} </code> I have other problems now though; I have a conflict with the ASM packages. The azure stuff requires <code>asm-1.0.2</code> which seem to break the embedded jetty server with; <code> WARN | Failed startup of context o.e.j.w.WebAppContext@25de8898{/admin,file:///root/apache-activemq-5.18.1/webapps/admin/,UNAVAILABLE} java.lang.ExceptionInInitializerError: null at org.eclipse.jetty.annotations.AnnotationConfiguration.createAnnotationParser(AnnotationConfiguration.java:502) ~[jetty-annotations-9.4.51.v20230217.jar:9.4.51.v20230217] at org.eclipse.jetty.annotations.AnnotationConfiguration.scanForAnnotations(AnnotationConfiguration.java:416) ~[jetty-annotations-9.4.51.v20230217.jar:9.4.51.v20230217] at org.eclipse.jetty.annotations.AnnotationConfiguration.configure(AnnotationConfiguration.java:346) ~[jetty-annotations-9.4.51.v20230217.jar:9.4.51.v20230217] </code> This was fixed by removing the <code>asm-1.0.2.jar</code> and old json-smart.jar Though the broker starts. The biggest problem (for another post) is this error I now get presumably when receiving a message and trying to send it to AMQ: <code>WARN | Cannot determine specific JmsMessage type to use from body class. Will use generic JmsMessage. Body class: com.azure.core.util.BinaryData. If you want to send a POJO then your class might need to implement java.io.Serializable, or you can force a specific type by setting the jmsMessageType option on the JMS endpoint. </code> Which was fixed by adding <code><convertBodyTo type=';java.lang.String';/>;</code> to the route like and turning into valid JSON; <code><route id=';Elexon_IRIS_Route';>; <from uri=';azureQueueEndpoint'; />; <convertBodyTo type=';java.lang.String';/>; <unmarshal>;<json/>;</unmarshal>; <to uri=';localAMQ:queue:IRIS-Elexon';/>; </route>; </code>
|
apache-camel
|
According to woodstox github https://github.com/FasterXML/woodstox/issues/59 Woodstox properties can be configured through XMLInputFactory. I'm now using camel with JAVA DSL, which use woodstox-core for XML https://camel.apache.org/components/next/eips/split-eip.html#_streaming_big_xml_payloads_using_xml_tokenize_language I want to configure Woodstox property e.g. <code>WstxInputProperties.P_RETURN_NULL_FOR_DEFAULT_NAMESPACE</code> How can I configure Woodstox properties in using Apache Camel? (Java 8, Apache Camel 2.25.4) Code for reference: <code>camel: Exchange in = camelContext.getEndpoint(';direct:xxx';).createExchange(); in.getIn().setBody(xmlContent); ProducerTemplate template = camelContext.createProducerTemplate(); Exchange out = template.send(';direct:xxx';, in); --- route builder: from(';direct:xxx';) .routeId(';xxx';) .split(body().xtokenize(';//xxx:xxx';, 'i', ns), myAggregationStrategy) .process(myProcessor) .end(); </code>
|
I've reported this bug to Apache. As camel 2.25.4 is already EOL, it will be fixed at new version of camel-stax. Fix Version/s: 3.14.9, 3.18.8, 3.20.6, 3.21.0, 4.0-RC1, 4.0 https://issues.apache.org/jira/browse/CAMEL-19415 If it is not possible to upgrade the camel version, instead of using xml default namespace, adding a custom namespace on all xml tag should be a possible way to avoid this issue. i.e. <code><ns1:XX ... xmlns:ns1=';XXXX';>; <ns1:YY>;zzz</ns1:YY>; </ns1:XX>; </code>
|
apache-camel
|
I want to get whether information by city via apache camel weather api. I can get whether information from api but when I want to pass cirt and country information to rest api I got error. I couldnt find any example that shows how to pass a header information from consumer to processor. Here is my code <code> @Override public void configure() throws Exception { rest(';/api';).description(';Weather api';) .consumes(MediaType.APPLICATION_JSON_VALUE) .produces(MediaType.APPLICATION_JSON_VALUE) .get(';/weather';).description(';Get weather by city';) .param().name(';city';).type(RestParamType.header).description(';The city name';).dataType(';string';).endParam() .param().name(';country';).type(RestParamType.header).description(';The country name';).dataType(';string';).endParam() .to(';direct:weather';); from(';direct:weather';) .log(';Get weather by city';) .to(';weather:foo?location=${header.city},${header.country}&;appid=8bb3bc2e4efb92992ed3e7190&;units=metric';) .log(';Weather: ${body}';); } </code> as you can see I got 2 parameters in rest api and I want to use these parameters in ';from'; part to pass these parameters to my camel weather api have any idea
|
U must use 'toD' (to Dynamic )instead of 'to' <code>.toD(';weather:foo?location=${header.city},${header.country}&;appid=8bb3bc2e4efb92992ed3e7190&;units=metric';) </code>
|
apache-camel
|
Is there a way in Spring boot Apache camel to know if the input failed to meet the requirement in a <code>.filter()</code>? <code>@Override public void configure() throws Exception { // @formatter:off from(';file://data/inputdir';) .log(';Checking ${file:name}';) .filter(simple(';${file:ext} == 'jpg'';)) .to(';file://data/outputidr/valid';) .log(';Processed in JPG! ${file:name}';) .end() .filter(simple(';${file:ext} == 'txt'';)) .to(';file://data/outputidr/validtxt';) .log(';Processed in TXT! ${file:name}';) .end() // @formatter:on } </code> I don't know if there is any method available to see if the <code>.filter()</code> is already done checking. I want to add in the end something like <code>.log(';${file:name} is not processed';);</code>
|
You can assign to a variable of filter result there is a basic example which I write you need change ${body} as ${file:name} <code>from(';timer:hello?repeatCount=1';) .setBody(constant(';helloworld';)) .filter(simple(';${body} == 'helloworld1'';)).statusPropertyName(';anyVariable';) .log(';do something';) .end() .log(';process status of '${body}' ${exchangeProperty.anyVariable}';); </code> output is <code> (Camel (camel-15) thread #11 - timer://hello) process status of 'helloworld' false </code>
|
apache-camel
|
I'm trying to get a simple Quarkus/Camel app going, and have hit a snag. I just keep getting the same error: <code>No bean could be found in the registry for: servlet of type: org.apache.camel.spi.RestApiConsumerFactory</code> Googling comes up pretty sparce, unsure where to go from here. Camel dependencies: <code><dependency>; <groupId>;org.apache.camel.quarkus</groupId>; <artifactId>;camel-quarkus-core</artifactId>; </dependency>; <dependency>; <groupId>;org.apache.camel.quarkus</groupId>; <artifactId>;camel-quarkus-rest</artifactId>; </dependency>; <dependency>; <groupId>;org.apache.camel.quarkus</groupId>; <artifactId>;camel-quarkus-direct</artifactId>; </dependency>; <dependency>; <groupId>;org.apache.camel.quarkus</groupId>; <artifactId>;camel-quarkus-jackson</artifactId>; </dependency>; <dependency>; <groupId>;org.apache.camel.quarkus</groupId>; <artifactId>;camel-quarkus-mock</artifactId>; </dependency>; </code> Route Setup <code>public class RestRoute extends RouteBuilder { @Override public void configure() throws Exception { restConfiguration() .component(';servlet';) .bindingMode(RestBindingMode.json) .dataFormatProperty(';prettyPrint';, ';true';) .apiContextPath(';/api-doc';) .apiProperty(';api.title';, ';REST API';).apiProperty(';api.version';, ';1.0';) .apiProperty(';cors';, ';true';); rest(';/';) .consumes(';application/json';) .produces(';application/json';) .get() .outType(TestObj.class) .to(';direct:getTestObj';); from(';direct:getTestObj';) .transform() .constant( TestObj.builder().fieldOne(';Hello';).fieldTwo(';World';).build() ); }} </code> When <code>.component(';servlet';)</code> is removed, I get the following error: <code>java.lang.IllegalStateException: Cannot find RestApiProcessorFactory in Registry or classpath (such as the camel-openapi-java component)</code>
|
Java have different app and web servers like netty , jetty tomcat , glassfish etc. spring use tomcat in default and tomcat is a servlet implementation therefore spring has servlet classes , quarkus not use tomcat therefore quarkus dont have servlet , quarkus use vert.x and in background vert.x use netty. u must remove explicity component definition just delete it <code> .component(';servlet';) </code>
|
apache-camel
|
In apache camel is there a difference if I just : <code>throw new RuntimeException(); </code> or : <code>exchnage.setException(new RuntimeException()) </code> ?
|
You can use both of them , setException method works for this two case, they give the same result
|
apache-camel
|
I use <code>concurrentConsumers=20</code> property for JMS endpoint in my route, but I have got different number of consumers. My route is: <code><?xml version=';1.0'; encoding=';UTF-8';?>; <blueprint xmlns=';http://www.osgi.org/xmlns/blueprint/v1.0.0';>; <bean id=';artemisConnectionFactory'; class=';org.apache.activemq.artemis.jms.client.ActiveMQJMSConnectionFactory';>; <argument index=';0'; value=';tcp://localhost:61616';/>; <argument index=';1'; value=';karaf';/>; <argument index=';2'; value=';karaf';/>; </bean>; <bean id=';jms'; class=';org.apache.camel.component.jms.JmsComponent';>; <property name=';connectionFactory'; ref=';artemisConnectionFactory';/>; </bean>; <camelContext id=';test-jms-context'; xmlns=';http://camel.apache.org/schema/blueprint';>; <route id=';messages-consumer-route'; autoStartup=';true';>; <from uri=';jms:queue:concurrent1?concurrentConsumers=20';/>; <log loggingLevel=';INFO'; message=';start';/>; <delay>; <constant>;10000</constant>; </delay>; <log loggingLevel=';INFO'; message=';finish';/>; </route>; </camelContext>; </blueprint>; </code> But on route/context/bundle restart I have got a random number of consuming threads: from 1 to 20 (concurrent consumers value). I've tested on Camel 3.4.5 and 3.21.0.SNAPSHOT with both ActiveMQ Artemis 2.19.0 and 2.28.0. Why number of threads not matches exactly to <code>concurrentConsumers</code> property?
|
I imagine that Camel will only create as many consumers as absolutely necessary to consume the messages. This will almost certainly be impacted by the flow control on the consumers. I recommend specifying <code>consumerWindowSize=0</code> on your connection URL, e.g.: <code>tcp://localhost:61616?consumerWindowSize=0 </code> This will ensure that one consumer doesn't prefetch a lot of messages and starve other consumers. That would increase the chances that more consumers are created.
|
apache-camel
|
We are using Quarkus 2.11.3.Final along with <code>camel-quarkus-micrometer</code>, plus <code>quarkus-micrometer-registry-prometheus</code> and <code>camel-quarkus-microprofile-health</code>. The problem is that when we run the tests, the following exceptions are thrown: <code>2023-04-17 18:45:33,275 WARN [org.apa.cam.sup.EventHelper] (main) Error notifying event 9C0D3FDCA14EBDA-0000000000000000 exchange completed. This exception will be ignored.: java.lang.NullPointerException: Cannot invoke ';org.apache.camel.Endpoint.getEndpointUri()'; because ';endpoint'; is null at org.apache.camel.component.micrometer.eventnotifier.MicrometerExchangeEventNotifierNamingStrategy.getTags(MicrometerExchangeEventNotifierNamingStrategy.java:53) at org.apache.camel.component.micrometer.eventnotifier.MicrometerExchangeEventNotifier.handleDoneEvent(MicrometerExchangeEventNotifier.java:104) at org.apache.camel.component.micrometer.eventnotifier.MicrometerExchangeEventNotifier.notify(MicrometerExchangeEventNotifier.java:75) at org.apache.camel.support.EventHelper.doNotifyEvent(EventHelper.java:1351)(...) </code> Also, I see that Quarkus attempts to connect to the Kafka instance, so I ended up having to set up the Kafka devservice so at least we didn't have to see any error messages related to that. Is there any way we can disable those? Thank you in advance.
|
To disable Kafka devservices you can add configuration to <code>application.properties</code>: <code>quarkus.kafka.devservices.enabled=false </code> To disable Micrometer for testing add: <code>%test.quarkus.micrometer.enabled=false </code> Or if you want more fine grained control over Camel Micrometer, there are some additional configuration options to enable / disable specific features: https://camel.apache.org/camel-quarkus/3.0.x/reference/extensions/micrometer.html#extensions-micrometer-additional-camel-quarkus-configuration
|
apache-camel
|
I'm working on porting over an old spring boot application to Quarkus and I've found that my application is not recognising the broker.url property. I've got this in my pom along with quarkus and camel:<code><dependency>; <groupId>;org.apache.camel.quarkus</groupId>; <artifactId>;camel-quarkus-activemq</artifactId>; <version>;2.16.0</version>; </dependency>; </code> I'm looking at how to go about setting the broker URL within the properties file and any documentation I try to find on it, directs to me either AMQP or something else, but there isn't anything explicit mentioned for doing this with camel-quarkus-activemq. Can anyone confirm if there is a way to do this or do I need to specify a bean with the URI exposed? To set the context, this project will be deployed within Openshift as a native application.
|
Just set it via <code>camel.component.activemq.brokerURL=xxx</code> in the <code>application.properties</code>. You can do this kind for any of the components.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.