Instruction
stringclasses 1
value | Input
stringlengths 161
22.9k
| Output
stringlengths 40
18.2k
|
---|---|---|
apache-camel | I have a CSV file that ends with a few empty lines. I would like to unmarshal each non-empty line into a Java object using BindyCsvDataFormat as follows: <code>//within my RouteBuilder class from(';{{route.from}}';) .unmarshal(new BindyCsvDataFormat(MyClass.class).)@CsvRecord(separator = ';,';, skipField = true, skipFirstLine = true, generateHeaderColumns = true, allowEmptyStream = true) @Data public class MyClass { @DataField(pos = 1, required = true) @NotEmpty private String myString; @DataField(pos = 2, required = true, pattern = ';M/d/yyyy';) @NotNull private LocalDate myDate; @DataField(pos = 3, required = false, pattern = ';M/d/yyyy';) private LocalDate notRequiredDate; } </code> When Camel attempts to unmarshal an empty line (containing only a carriage return followed by a line feed), it throws: <code>java.lang.IllegalArgumentException: The mandatory field defined at the position 1 is empty for the line: 5 </code> How do I tell Apache Camel to ignore empty lines? | I don't see that this is possible with Bindy. A potential workaround would be to split the file on line endings, then conditionally unmarshal individual lines through Bindy based on whether or not the line is empty. |
apache-camel | I have been working on 3 different projects and all of them had different way to work with Camel. First one was mostly calling couple of services per route through bean(we end up with large services that only had methods that were used in Camel routes only), like this: <code>from(';direct:someUrl';) .bean(myService, ';loadData';) .bean(myService, ';validateData';) .bean(myService, ';saveData';) .bean(myService2, ';sendEvent';) </code> and so on. Second created separate processor per each task(had to create long constructor to inject them all). Like: <code>from(';direct:someUrl';) .process(myParseProcessor) .process(myValidationProcessor) .process(mySaveToDbProcessor) .process(myPublishEventProcessor) </code> And in third one routes were calling each other(was super hard to see the full flow, because you had to jump across multiple classes). Like: <code> FisrtRoute.java from(';direct:someUrl';) .process(()->; doSmth) .to(';direct:someUrl2';) SecondRoute.java from(';direct:someUrl2';) .process(()->; doSmth) .to(';direct:someUrl3';) ThirdRoute.java from(';direct:someUrl3';) .process(()->; doSmth) .to(';direct:someUrl4';) </code> I am trying to understand what is the preferred way to work with Camel? Personally I prefer second one, as it is easier to see the whole flow in one place and to cover with tests all small processors, but on the other hand we end up with tons of processors and huge list of them being injected into our Route. | Since I had to wrap my head around that problem myself, I can give you an answer based on your description. Although I am not sure that this is the most correct answer. Your first and second solution utilize a singleton pattern within Spring Boot while maintaining route visibility and transparency. Both is good and desirable. Thus, both ways are fine as far as I can tell. Whether you should use a service layer or Processor objects depends imho a bit on their respective purpose. Thus, if you can identify shared functionalities among different processing steps those steps could be organized in a service and called by whatever route needs them. If the processing steps are pretty much isolated its probably cleaner to use the Processors. Here it pretty much comes down to this kind of evaluation or some further technical implications like testing or async processing etc. Best |
apache-camel | Though I've added a <code>username</code> and <code>password</code> still camel route is asking for a username and password in the console. Dependency - <code><dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-core</artifactId>; <version>;3.20.1</version>; </dependency>; <dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-ftp</artifactId>; <version>;3.20.1</version>; </dependency>; </code> Camel Route - <code>URI uri = new URIBuilder().setScheme(';sftp';).setHost(';HOST.com';).setPort(22) .setUser(';demo_user';, ';demo_password';).build();from(uri.toString()).to(';file://src/main/resources); </code> After running this in the console it's showing - <code>19:01:41:158 [main] WARN o.a.c.c.file.remote.SftpOperations - JSCH Kerberos username: </code> I want to run the application and the <code>username</code> &; <code>password</code> should automatically take but sadly it's not taking, any solution, please | Finally, I got the solution. I passed a parameter - <code>preferredAuthentications</code> as <code>password</code> and after that, it's working <code>URI uri = new URIBuilder().setScheme(';sftp';).setHost(';HOST.com';).setPort(22) .setUser(';demo_user';, ';demo_password';).addParameter(';preferredAuthentications';, ';password';).build(); </code> |
apache-camel | When you need to send a message to a FIFO queue in AWS SQS using Apache Camel, you'll need to put a property named ';MessageGroupId';. But, we do know that Apache Camel is not always friendly, so how to? We do have docs telling us how to implement AWS SQS in Apache Camel, such like this one Doc, but in terms of MessageGroupId, it does not explains much and don't truly tells we how to put in in the message [at least not in current date of this post]. | Since I did not found any answers anywhere, I'll put it here in case you need it too. Before send it to your queue, you'll have to put it in the .setProperty tag, e.g. just like this: <code>from(....) .... .... .setProperty(';CamelAwsMessageGroupId';, ';YOUR_VALUE';) .to(';YOUR_QUEUE_URI';); </code> |
apache-camel | Using seda endpoints I see Exchange properties are passed between endpoints. Example: <code>sedaRouteA.setProperty(';myProperty';, 1) ->; sending ->; sedaRouteB.getProperty(';myProperty';) </code> In sedaRouteB I am able to read property which was set in sedaRouteA How to disable it? | You cannot disable that. You can manually remove these properties before sending to seda. |
apache-camel | I am unable to read the file from a particular folder this is my code for routebuilder <code>@Component(';RequestFileRouteBuilder';) public class RequestFileRouteBuilder extends RouteBuilder{ @Override public void configure() throws Exception{ from(';file:files/input';) .routeId(';Myroute';) .process(Myprocessor);//processes the file input } } </code> Due to security violation I cannot share the entire pom.xml file which we are using in our project But I have included camel-file,camel-spring,camel-bean,camel-core. the error which I am getting after running my application is as below Caused by : org.apache.camel.NoSuchEndPointException : No endpoint cpould be found for : file://files/input, please check your classpath contains the needed Camel component jar. I actually added camel-file dependency later after going through this site https://camel.apache.org/components/3.20.x/file-component.html Where can I go wrong? | The piece of code seems to be working fine. Below is the code snippet which is working fine in my machine. <code>@Component(';requestFileRouteBuilder';) public class RequestFileRouteBuilder extends RouteBuilder { @Override public void configure() throws Exception{ from(';file:C:/files/input/';) .routeId(';RequestFileRouteId';) .process(exchange ->; {log.info(exchange.getIn().getBody(String.class));}); }} </code> Below are the logs from application <code>2023-04-02 12:08:59.987 INFO 7192 --- [ main] o.a.c.impl.engine.AbstractCamelContext : Started RequestFileRouteId (file://C:/files/input/)2023-04-02 12:08:59.987 INFO 7192 --- [ main] o.a.c.impl.engine.AbstractCamelContext : Apache Camel 3.14.0 (camel-1) started in 420ms (build:83ms init:313ms start:24ms) 2023-04-02 12:08:59.994 INFO 7192 --- [ main] com.example.Application : Started Application in 6.136 seconds (JVM running for 7.67) 2023-04-02 12:09:16.841 INFO 7192 --- [C:/files/input/] c.example.route.RequestFileRouteBuilder : Test Message </code> Below might be the issue that I can think of:Are you passing full path to the input directory?Have you included below dependencies in your pom xml? <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>; </dependency>; </code> Also, you need to check whether the spring boot version and camel version you are using are compatible with each other or not. |
apache-camel | I am trying to covert jwt token to Object to get access token using spring DSL <code> <to uri=';ref:oauthTokenEndpoint'; />; <log message=';Auth Token Response is ${body} '; loggingLevel=';INFO'; />; <choice>; <when>; <simple>;${header.CamelHttpResponseCode} == '200'</simple>; <to uri=';bean:getResponseCode?method=processOAuthToken'; />; <to uri=';direct:sendEventPostServiceCall'; />; </when>; <otherwise>; <log message=';[POST] Error getting token response code is ${header.CamelHttpResponseCode} '; loggingLevel=';INFO'; />; </otherwise>; </choice>; </code> Here is the process code <code> TokenResponse tokenResponse = exchange.getIn().getBody(TokenResponse.class); logger.debug(';exchange body Token Response ';+tokenResponse); exchange.getOut().setHeader(';jwt';, tokenResponse.access_token ); </code> Here is TokenResponse Class <code> public class TokenResponse { String token_type; String expires_in; String ext_expires_in; String access_token; public String getToken_type() { return token_type; } public void setToken_type(String token_type) { this.token_type = token_type; } public String getExpires_in() { return expires_in; } public void setExpires_in(String expires_in) { this.expires_in = expires_in; } public String getExt_expires_in() { return ext_expires_in; } public void setExt_expires_in(String ext_expires_in) { this.ext_expires_in = ext_expires_in; } public String getAccess_token() { return access_token; } public void setAccess_token(String access_token) { this.access_token = access_token; } } </code> I am always getting null at the process method. do i need to setup any converter or Json ObjectMapper here. | I figure out , it was problem with logging before processing the token , once i removed following logging statement,i am able to receive token in the <code>exchange.getIn().getBody...</code> |
apache-camel | I'm trying to test a camel route that makes use of Marshal EIP with Jackson however when I try to convert a LocalDate I get an InvalidDefinitionException. I already added the module ';com.fasterxml.jackson.datatype:jackson-datatype-jsr310'; to my dependencies and registered it without any success. Any suggestion what could be wrong? Also use property <code>camel.dataformat.jackson.auto-discover-object-mapper=true</code> but it doesn't work in tests Route <code>@Component public class MyRoute extends RouteBuilder { @Override public void configure() throws Exception { from(';direct:MyRoute';) .routeId(';MyRoute';) .marshal() .json(JsonLibrary.Jackson) } } </code> Test <code>@SpringBootTest() @CamelSpringBootTest @EnableRouteCoverage public class MyRouteTest { @Autowired private CamelContext camelContext; @Autowired private ProducerTemplate producerTemplate; @Test public void testMyRoute() throws Exception { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.registerModule(new JavaTimeModule()); Exchange ex = new DefaultExchange(camelContext); Map<String, Object>; map = new LinkedHashMap<>;(); map.put(';name';, ';Rick';); map.put(';birth-date';, LocalDate.of(2023, 3, 27)); exchange.getMessage().setBody(map); Exchange result = producerTemplate.send(';direct:MyRoute';, exchange); // Asserts } } </code> dependencies <code>configurations { testImplementation.extendsFrom compileOnly }buildscript { ext { springBootVersion = '3.0.2' camelVersion = '4.0.0-M1' } }dependencies{ compileOnly group: 'org.springframework.boot', name: 'spring-boot-dependencies', version: springBootVersion compileOnly group: 'org.apache.camel.springboot', name: 'camel-spring-boot-starter', version: camelVersion compileOnly group: 'org.apache.camel.springboot', name: 'camel-jackson-starter', version: camelVersion compileOnly group: 'com.fasterxml.jackson.datatype', name: 'jackson-datatype-jsr310', version: '2.14.2' testImplementation group: 'org.springframework.boot', name: 'spring-boot-starter-test', version: springBootVersion testImplementation group: 'org.apache.camel', name: 'camel-test-spring-junit5', version: camelVersion testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.1' testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.1' } </code> | To solve this I had to create an instance of <code>ObjectMapper</code> and set it to a <code>JacksonDataFormat</code> object that is finally the one used in Marshal EIP Route <code>@Component public class MyRoute extends RouteBuilder { @Override public void configure() throws Exception { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.registerModule(new JavaTimeModule()); JacksonDataFormat dataFormat = new JacksonDataFormat(); dataFormat.setObjectMapper(objectMapper); from(';direct:MyRoute';) .routeId(';MyRoute';) .marshal(dataFormat); } } </code> If you know a more elegant way to do it you can suggest it :D |
apache-camel | I have a message body. Then, I change it. Then, I want to reset it back to the original message body: <code>from(';{{route:from}}';) // step 1 .setBody(';hello world';) // step 2 .setBody(/*set body back to value produced by step 1*/); </code> How do I reset the body back to the value produced by step 1? | You can copy the body to an exchange property before the first time you change the body, and then restore it afterwards. You can also look at the claim check EIP that has push/pop actions for such behaviour. |
apache-camel | I am trying to perform a unit test for one of my routes in camel however I can't find a way to check the body I receive from my route and check if it is what is expected. How can I do this with or without mocks? Route <code>@Component public class MyRoute extends RouteBuilder { @Override public void configure() throws Exception { from(';direct:MyRoute';) .routeId(';MyRoute';) .marshal().json(JsonLibrary.Jackson) .log(';Marshal to ${body}';); } } </code> Test <code>public class MyRouteTest extends CamelTestSupport { @Override protected RouteBuilder createRouteBuilder() throws Exception { return new MyRoute(); } @Test public void testRoute() throws Exception { NotifyBuilder notify = new NotifyBuilder(context).whenDone(1).create(); Map<String,Object>; map = new LinkedHashMap<>;(); map.put(';name';,';your_name';); template.sendBody(';direct:MyRoute';, map); assertTrue(notify.matchesWaitTime()); } } </code> | With mocks You can use <code>AdviceWith</code> and <code>weaveAddLast</code> to add for example <code>mock:result</code> to end of a route. Then use the injected MockEndpoint to define assertions for the exchange. MockEndpoint comes with many handy methods that you can use to check validity of the exchange. When using AdviceWith to modify routes for tests, remember to use the @UseAdviceWith annotation and start the CamelContext manually before each test. This is to avoid unnecessary restarts of adviced routes. <code>package com.example;import org.apache.camel.CamelContext; import org.apache.camel.EndpointInject; import org.apache.camel.ProducerTemplate; import org.apache.camel.builder.AdviceWith; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.test.spring.junit5.CamelSpringBootTest; import org.apache.camel.test.spring.junit5.UseAdviceWith; import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest;@SpringBootTest @CamelSpringBootTest @UseAdviceWith public class MySpringBootApplicationTest { @Autowired private CamelContext camelContext; @Autowired private ProducerTemplate producerTemplate; @EndpointInject(uri = ';mock:result';) private MockEndpoint resulMockEndpoint; @Test public void test() throws Exception { resulMockEndpoint.expectedMessageCount(1); resulMockEndpoint.message(0) .body().isEqualTo(';Hello world';); addMockEndpointAsLast(';hello';); camelContext.start(); producerTemplate.sendBody(';direct:hello';, ';world';); resulMockEndpoint.assertIsSatisfied(); } MockEndpoint addMockEndpointAsLast(String routeId) throws Exception { AdviceWith.adviceWith(camelContext, routeId, builder ->; { builder.weaveAddLast() .to(';mock:result';) ; }); return resulMockEndpoint; } } </code> If you want to further examine the exchange, you can get it from the exchanges list of MockEndpoint. Below is example on how to get body of first exchange as String. <code>String result = resulMockEndpoint.getExchanges().get(0) .getMessage().getBody(String.class); </code> Without mocks You can use <code>ProducerTemplate.send</code> method which returns the resulting exchange. However instead of body of any type the method wants you to provide it with exchange object which you can create using <code>DefaultExchange</code> class. <code>package com.example;import static org.junit.jupiter.api.Assertions.assertEquals;import org.apache.camel.CamelContext; import org.apache.camel.Exchange; import org.apache.camel.ProducerTemplate; import org.apache.camel.support.DefaultExchange; import org.apache.camel.test.spring.junit5.CamelSpringBootTest; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest;@SpringBootTest @CamelSpringBootTest public class MySpringBootApplicationTest { @Autowired private CamelContext camelContext; @Autowired private ProducerTemplate producerTemplate; @Test void testWithoutMock(){ Exchange exchange = new DefaultExchange(camelContext); exchange.getMessage().setBody(';world';); Exchange resultExchange = producerTemplate.send(';direct:hello';, exchange); assertEquals(';Hello world';, resultExchange.getMessage().getBody()); } } </code> RouteBuilder <code>package com.example;import org.apache.camel.builder.RouteBuilder; import org.springframework.stereotype.Component;@Component public class MySpringBootRouter extends RouteBuilder { @Override public void configure() { from(';direct:hello';) .routeId(';hello';) .setBody().simple(';Hello ${body}';) .log(';${body}';) ; } } </code> Examples use Apache Camel version 3.20.2 |
apache-camel | I have a route that validates a bean. If validation fails, I want to email the validation exception and then continue processing the bean. Here's what I have so far: <code>onException(BeanValidationException.class) // the body is an instance of MyClass .setBody(simple(';${exception}';)) // Now it's a String representation of the exception. .to(';{{route.mail}}';) .continued(true); //now what? how do I get back the instance of MyClass? from(';{{route.from}}';) .unmarshal(new BindyCsvDataFormat(MyClass.class)) .to(';bean-validator:priceFeedValidator';) //continued processing of bean </code> When validation fails, the above code send the email validation exception. That's good. But when it continues processing the bean, it fails because the message body is no longer a MyClass bean but the exception string. How can I return back the bean that was there before I called setBody? Alternatively, is there a way to send the exception in email without overwriting the body of the original flow? | Yeah you can store the body in a temporary exchange property before change it to the exception message when sending the email and restore it afterwards. A related question Camel Body: body1 ->; body2 ->; body1? You can also use a bean/processor to send the email, and write a bit of Java code that grab the caused exception from the validation exception, and build the email to send (via a producer template etc) and then avoid changing the message body in the Camel route. |
apache-camel | Is it possible to retrieve what <code>RouteBuilder</code> class was used to build a Route at execution time via the <code>Exchange</code>? For example; <code>class SimplePingRoute : RouteBuilder() { override fun configure() { from(';timer://foo?fixedRate=true&;period=1000';) .routeId(';pong-demo-app';) .process({exc->; //***looking for SimplePingRoute at this point from exc*** }) .to(';log:pong';) }} </code> | Camel 3.20 onwards stores the source file:line-number of the routes for each EIP node (you need to enable this for Java DSL). This allows tooling such as the debugger to correlate the runtime debug session with the source code. And tooling like camel-jbang to output source precise information. Maybe your tool can use that also. |
apache-camel | One of our application is a Camel Spring-Boot application. The route is fairly simple: it gets a file from a FTP server using the camel-ftp component and pushes it to a JMS queue. We use Apache Artemis as broker. camel version is : 2.20.2 Spring-Boot is : 2.7.8 <code>@Component @Slf4j public class FTPListenerRoute extends RouteBuilder { @Value(';${ems.activemq.queue.name}';) private String activeMqTargetQueueName; @Value(';${ems.error-uri:error}';) private String errorUri; @Value(';${ems.max-redeliveries}';) private int maximumRetries; private final FTPConfiguration ftpConfiguration; @Autowired public FTPListenerRoute(FTPConfiguration ftpConfiguration) { this.ftpConfiguration = ftpConfiguration; } @Override public void configure() throws Exception { errorHandler( springTransactionErrorHandler() .loggingLevel(LoggingLevel.DEBUG) .maximumRedeliveries(0) .log(log).logHandled(true)); String uri = ftpConfiguration.buildUri(); from(uri) .routeId(';listener-main-route';) //.transacted() .doTry() .to(';direct:msgInTransaction';) .doCatch(RuntimeCamelException.class) .log(LoggingLevel.ERROR, log, ';caugt exception, rerouting to : {}';, errorUri) .to(errorUri) .endDoTry(); from(';direct:msgInTransaction';) .routeId(';ftplistener-transacted-route';) .log(LoggingLevel.INFO, ';Processing ${id} with headers: ${headers}';) .transacted() .to(';jms:queue:'; + activeMqTargetQueueName); } @Bean public PlatformTransactionManager jmsTransactionManager(@Qualifier(';jmsConnectionFactory';) ConnectionFactory connectionFactory) { return new JmsTransactionManager(connectionFactory); } } </code> <code>package be.fgov.minfin.esbsoa.ems.ftp.listener.configuration;import org.apache.commons.lang3.StringUtils; import org.apache.http.client.utils.URIBuilder; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component;import java.net.URISyntaxException; import java.util.Optional;@Component public class FTPConfiguration { // FTP Properties @Value(';${ems.ftp.username}';) private String ftpUsername; @Value(';${ems.ftp.password}';) private String ftpPassword; @Value(';${ems.ftp.host}';) private String ftpHost; @Value(';${ems.ftp.port:}';) private Optional<Integer>; ftpPort; @Value(';${ems.ftp.path}';) private String ftpPath; @Value(';${ems.ftp.path.error:error}';) private String ftpErrorPath; @Value(';${ems.ftp.path.completed:completed}';) private String ftpCompletedPath; @Value(';${ems.ftp.delay:30000}';) private String ftpDelay; @Value(';${ems.ftp.filter.file.name:}';) private String fileNameFilter; @Value(';${ems.ftp.deleteFile:false}';) private boolean isFilesDeletionAfterCompletion; @Value(';${ems.ftp.filter.file.size:50000000}';) private int maxFileSize; @Value(';${ems.ftp.protocol:ftp}';) private String protocol; @Value(';${ems.ftp.passiveMode:true}';) private String passiveMode; public String buildUri() throws URISyntaxException { URIBuilder ftpUriBuilder = getUri(ftpPath); ftpUriBuilder.addParameter(';moveFailed';, ftpErrorPath) .addParameter(';delay';, ftpDelay) .addParameter(';binary';, ';true';) .addParameter(';initialDelay';, ';5';) .addParameter(';filterFile';, ';${file:size} <= '; + maxFileSize) .addParameter(';readLock';, ';changed';); if (this.isFilesDeletionAfterCompletion) { ftpUriBuilder.addParameter(';delete';, ';true';); } else { ftpUriBuilder.addParameter(';move';, ftpCompletedPath); } if (StringUtils.isNotBlank(fileNameFilter)) { ftpUriBuilder.addParameter(';include';, fileNameFilter); } return ftpUriBuilder.build().toString(); } private URIBuilder getUri(String path) { URIBuilder uriBuilder = new URIBuilder() .setScheme(protocol) .setHost(ftpHost) .setUserInfo(ftpUsername, ftpPassword) .setPath(path) .addParameter(';passiveMode';, passiveMode); ftpPort.ifPresent(uriBuilder::setPort); return uriBuilder; } }</code> During maintenance week-ends, servers are often rebooted and this route fails with the following error: <code>2023-03-14 07:50:53.596 INFO 1 --- [tra/Coda_Edepo/] ftplistener-main-route : Processing 3DAABB587130ED0-000000000000026E with headers: {CamelFileAbsolute=false, CamelFileAbsolutePath=Coda_Edepo/FIL.EMPCFF.679200407454.20230313.DEP, CamelFileHost=ftphost, CamelFileLastModified=1678754100000, CamelFileLength=516516, CamelFileName=FIL.EMPCFF.679200407454.20230313.DEP, CamelFileNameConsumed=FIL.EMPCFF.679200407454.20230313.DEP, CamelFileNameOnly=FIL.EMPCFF.679200407454.20230313.DEP, CamelFileParent=Coda_Edepo, CamelFilePath=Coda_Edepo//FIL.EMPCFF.679200407454.20230313.DEP, CamelFileRelativePath=FIL.EMPCFF.679200407454.20230313.DEP, CamelFtpReplyCode=226, CamelFtpReplyString=226 Transfer complete. , CamelMessageTimestamp=1678754100000} 2023-03-14 07:50:53.617 WARN 1 --- [tra/Coda_Edepo/] o.a.c.c.file.GenericFileOnCompletion : Error during commit. Exchange[3DAABB587130ED0-000000000000026E]. Caused by: [org.apache.camel.component.file.GenericFileOperationFailedException - Cannot rename file: RemoteFile[FIL.EMPCFF.679200407454.20230313.DEP] to: RemoteFile[/Coda_Edepo//completed/FIL.EMPCFF.679200407454.20230313.DEP]]org.apache.camel.component.file.GenericFileOperationFailedException: Cannot rename file: RemoteFile[FIL.EMPCFF.679200407454.20230313.DEP] to: RemoteFile[/Coda_Edepo//completed/FIL.EMPCFF.679200407454.20230313.DEP] at org.apache.camel.component.file.strategy.GenericFileProcessStrategySupport.renameFile(GenericFileProcessStrategySupport.java:147) ~[camel-file-3.12.0.jar:3.12.0] at org.apache.camel.component.file.strategy.GenericFileRenameProcessStrategy.commit(GenericFileRenameProcessStrategy.java:121) ~[camel-file-3.12.0.jar:3.12.0] at org.apache.camel.component.file.GenericFileOnCompletion.processStrategyCommit(GenericFileOnCompletion.java:134) ~[camel-file-3.12.0.jar:3.12.0] at org.apache.camel.component.file.GenericFileOnCompletion.onCompletion(GenericFileOnCompletion.java:86) ~[camel-file-3.12.0.jar:3.12.0] at org.apache.camel.component.file.GenericFileOnCompletion.onComplete(GenericFileOnCompletion.java:60) ~[camel-file-3.12.0.jar:3.12.0] at org.apache.camel.support.UnitOfWorkHelper.doneSynchronization(UnitOfWorkHelper.java:99) ~[camel-support-3.12.0.jar:3.12.0] at org.apache.camel.support.UnitOfWorkHelper.doneSynchronizations(UnitOfWorkHelper.java:88) ~[camel-support-3.12.0.jar:3.12.0] at org.apache.camel.impl.engine.DefaultUnitOfWork.done(DefaultUnitOfWork.java:238) ~[camel-base-engine-3.12.0.jar:3.12.0] at org.apache.camel.support.UnitOfWorkHelper.doneUow(UnitOfWorkHelper.java:59) ~[camel-support-3.12.0.jar:3.12.0] at org.apache.camel.impl.engine.CamelInternalProcessor$UnitOfWorkProcessorAdvice.after(CamelInternalProcessor.java:775) ~[camel-base-engine-3.12.0.jar:3.12.0] at org.apache.camel.impl.engine.CamelInternalProcessor$UnitOfWorkProcessorAdvice.after(CamelInternalProcessor.java:710) ~[camel-base-engine-3.12.0.jar:3.12.0] at org.apache.camel.impl.engine.CamelInternalProcessor$AsyncAfterTask.done(CamelInternalProcessor.java:263) ~[camel-base-engine-3.12.0.jar:3.12.0] at org.apache.camel.AsyncCallback.run(AsyncCallback.java:44) ~[camel-api-3.12.0.jar:3.12.0] at org.apache.camel.impl.engine.DefaultReactiveExecutor$Worker.schedule(DefaultReactiveExecutor.java:179) ~[camel-base-engine-3.12.0.jar:3.12.0] at org.apache.camel.impl.engine.DefaultReactiveExecutor.schedule(DefaultReactiveExecutor.java:59) ~[camel-base-engine-3.12.0.jar:3.12.0] at org.apache.camel.impl.engine.CamelInternalProcessor$AsyncAfterTask.done(CamelInternalProcessor.java:275) ~[camel-base-engine-3.12.0.jar:3.12.0] at org.apache.camel.spring.spi.TransactionErrorHandler.process(TransactionErrorHandler.java:138) ~[camel-spring-3.12.0.jar:3.12.0] at org.apache.camel.impl.engine.CamelInternalProcessor.process(CamelInternalProcessor.java:399) ~[camel-base-engine-3.12.0.jar:3.12.0] at org.apache.camel.processor.Pipeline$PipelineTask.run(Pipeline.java:109) ~[camel-core-processor-3.12.0.jar:3.12.0] at org.apache.camel.impl.engine.DefaultReactiveExecutor$Worker.schedule(DefaultReactiveExecutor.java:179) ~[camel-base-engine-3.12.0.jar:3.12.0] at org.apache.camel.impl.engine.DefaultReactiveExecutor.scheduleMain(DefaultReactiveExecutor.java:64) ~[camel-base-engine-3.12.0.jar:3.12.0] at org.apache.camel.processor.Pipeline.process(Pipeline.java:184) ~[camel-core-processor-3.12.0.jar:3.12.0] at org.apache.camel.impl.engine.CamelInternalProcessor.process(CamelInternalProcessor.java:399) ~[camel-base-engine-3.12.0.jar:3.12.0] at org.apache.camel.component.file.GenericFileConsumer.processExchange(GenericFileConsumer.java:492) ~[camel-file-3.12.0.jar:3.12.0] at org.apache.camel.component.file.remote.RemoteFileConsumer.processExchange(RemoteFileConsumer.java:156) ~[camel-ftp-3.12.0.jar:3.12.0] at org.apache.camel.component.file.GenericFileConsumer.processBatch(GenericFileConsumer.java:245) ~[camel-file-3.12.0.jar:3.12.0] at org.apache.camel.component.file.GenericFileConsumer.poll(GenericFileConsumer.java:206) ~[camel-file-3.12.0.jar:3.12.0] at org.apache.camel.support.ScheduledPollConsumer.doRun(ScheduledPollConsumer.java:191) ~[camel-support-3.12.0.jar:3.12.0] at org.apache.camel.support.ScheduledPollConsumer.run(ScheduledPollConsumer.java:108) ~[camel-support-3.12.0.jar:3.12.0] at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) ~[na:na] at java.base/java.util.concurrent.FutureTask.runAndReset(Unknown Source) ~[na:na] at java.base/java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source) ~[na:na] at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) ~[na:na] at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) ~[na:na] at java.base/java.lang.Thread.run(Unknown Source) ~[na:na] </code> After that, the file is reprocessed again and again by camel until the rename operation succeeds. This causes a big problem with duplicates in our database. My understanding is the following:a file is put one the ftp server and is picked up by Camel a transaction is started the file is sent to the broker via JMS and is successful camel tries to ';rename'; the file to move it to the <code>completed</code> folder renaming fails and <code>GenericFileOperationFailedException</code> is thrown file is put back into the processing folder and reprocessed again from step 1.I created an integration test using the Spock Framework and MockFtpServer library. I have the following successful happy scenario: <code>def 'happy scenario'() { given: 'one original file destination, one completed file destination' fileSystem.add(new FileEntry(';/upload/mockFile.txt';, ';test';)) fileSystem.add(new FileEntry(';/upload/completed/mockFile.txt';, ';test';)) and: 'start the server' ftpServer.start() camelContext.start() when: 'the file is actually sent to the ftp server' remoteFile.storeFile(';src/test-integration/resources/files/mockFile.txt';, ';/upload/mockFile.txt';) then: 'assert that it was' // assert that the file is put on the ftp ';test'; == remoteFile.readFile(';/upload/mockFile.txt';) and: 'receive the file on the other end of the route' def receivedMessage = jmsMessagingTemplate.receive(jmsDestinationQueue) then: 'assert that that it is the correct file' ';test'; == new String(receivedMessage.getPayload()) } </code> In the error scenario, I am stubbing the RENTO ftp command to throw GenericFileOperationFailedException <code> def 'failed scenario - GenericFileOperationFailedException'() { given: 'an original file location on the FTP' fileSystem.add(new FileEntry(';/upload/mockFile.txt';, ';test';)) fileSystem.add(new FileEntry(';/upload/completed/mockFile.txt';)) and: 'a custom ERROR code for the RNTO command' ftpServer.setCommandHandler(CommandNames.RNTO, new ExceptionCommandHandler()) and: 'start the server' ftpServer.start() camelContext.start() when: 'the file is actually sent to the ftp server' remoteFile.storeFile(';src/test-integration/resources/files/mockFile.txt';, ';/upload/mockFile.txt';) then:'assert that it was' ';test'; == remoteFile.readFile(';/upload/mockFile.txt';) and: 'assert that message was received in the destination queue' def receivedFromDestinationQueue = jmsMessagingTemplate.receive(jmsQueueName) assertNotNull(receivedFromDestinationQueue.payload) and: 'try to poll DLQ, original message should be sent there' def dlq = StringUtils.substringAfterLast(errorUri, ';:';) def receivedFromDLQ = jmsMessagingTemplate.receive(dlq) assertNotNull(receivedFromDLQ) } </code> This test fails: the message is never received from the DLQ where the message should have been sent because of the GenericFileOperationFailedException. I am polling both the destinationQueue, then the errorQueue because I noticed that the file WAS sent to the destination queue and processed. What I'm trying to achieve is to be certain that the file is only delivered once to the JMS broker, in all circumstances. If there are retries or errors anywhere in the process, the messages should be sent to the DLQ. | I found a suitable solution inspired by this unit-test: https://svn.apache.org/repos/asf/camel/trunk/camel-core/src/test/java/org/apache/camel/component/file/FileConsumerCustomExceptionHandlerTest.java the idea is to reinject the exception in the route, so the error handler picks it up. Following @TacheDeChoco suggestion, I set up a custom <code>OnCompletionExceptionHandler</code> on my FTP endpoint.To use a custom org.apache.camel.spi.ExceptionHandler to handle any thrown exceptions that happens during the file on completion process where the consumer does either a commit or rollback. The default implementation will log any exception at WARN level and ignore.I also used the idempotent and idempotent-key options as I know there will be only one file sent per day. https://camel.apache.org/components/3.20.x/ftp-component.html#_endpoint_query_option_idempotent This is the final result: <code>public String buildUri() throws URISyntaxException { URIBuilder ftpUriBuilder = getUri(ftpPath); ftpUriBuilder // other connection params ... //DO NOT USE at the same time as onCompletionExceptionHandler //.addParameter(';bridgeErrorHandler';, ';true';) .addParameter(';throwExceptionOnConnectFailed';, ';true';) .addParameter(';onCompletionExceptionHandler';, ';#redirectExceptionHandler';) .addParameter(';idempotent';, ';true';) .addParameter(';idempotentKey';, ';${file:name}-${date:now:yyyyMMdd}';) ; </code> <code>@Slf4j @Component public class RedirectExceptionHandler implements ExceptionHandler { private final ProducerTemplate template; public RedirectExceptionHandler(ProducerTemplate template) { this.template = template; } @Override public void handleException(Throwable exception) { handleException(exception.getMessage(), null, exception); } @Override public void handleException(String message, Throwable exception) { handleException(message, null, exception); } @Override public void handleException(String message, Exchange exchange, Throwable exception) { exchange.setException(exception); exchange.setMessage(exchange.getIn()); // unsure if these are necessary or reset by the errorHandler exchange.setRollbackOnly(false); exchange.adapt(ExtendedExchange.class).setRedeliveryExhausted(true); // use a producerTemplate to send the exchange to the errorHandling endpoint template.send(';direct:errorHandling';, exchange); } }</code> <code> @Override public void configure() throws Exception { errorHandler(springTransactionErrorHandler().maximumRedeliveries(0)); // configure onException behaviour for all routes, disable redeliveries onException(Exception.class) .handled(true) .maximumRedeliveries(0) .to(errorUri); from(ftpConfiguration.buildUri()) .routeId(';listener-main-route';) .to(';direct:msgInTransaction';) ; // simple direct: endpoint to rethrow exceptions to the global error-handler from(';direct:errorHandling';) .throwException(new ErrorHandlingException()) ; from(';direct:msgInTransaction';) .routeId(';ftplistener-transacted-route';) .transacted() .log(LoggingLevel.INFO, ';Processing ${id} with headers: ${headers}';) .to(';jms:queue:'; + activeMqTargetQueueName) ; } </code> |
apache-camel | In a camel configuration file, I define a password that contains a less-than-sign ';<';. Then it will fail when I startup JBoss. The escape char backslash doesn't work in this situation. How can I include this sign in a string? <code><configuration xsi:type=';ProviderConfiguration'; ...........>; <provider controlName=';Whisky';>; <entry xsi:type=Simple'; name=';password'; value=';abcabc<ABC';>; </provider>; </configuration>; </code> | Thanks @TacheDeChoco. This doesn't relate to Camel but XML. replace ';<'; with <code>&;lt;</code> and it works. |
apache-camel | This is a curiosity question, recently we faced out of memory issue with one of our microservices. This memory issue happens once in a month so basically application is running for 1 month without any issue but after that it is throwing out of memory. Our guess memory is increasing after running through daily files and storing them into DB which not getting cleared by GC somehow. We tried to refactor the code wherein I suggested to use custom array list (standard size) or singly linked list to store them. This made me wonder whether we have any memory efficient dynamic list to store large volume of custom objects. Note: the list just need to store the record and access them in FIFO order, once recorded into DB it will be cleared Note 2: please share if you know any memory efficient ADT already available in Apache commons collection or anything as such. | As @knittl suggested I took a heapdump and looks like Apache camel is causing this memory issue. We are pulling files from SFTP daily and decrypt them before going through data processing and inserting into DB. It looks like Apache camel is not freeing up the memory from its jsch buffer. Can someone suggest what we can do here? Our camel is simple, sharing a sample here from(';sftpUrl';+dynamic_fileName+';.pgp';).routeId(';id';).process(isDuplicateFile).unmarshal().pgp(somekey,user,pwd).unmarshal().string().process(writeToDBProcessor).log(';Done';); |
apache-camel | I am trying to set up a REST service with Apache Camel (v3.20.0) that, among other routes, offers a POST endpoint that receives a payload in the request body. I am trying to document my REST interface using the camel-openapi-java package using Java DSL. However, when trying to specify the expected body parameter using <code>.param().name(';body';).type(body).description(';The post object that is to be published';).endParam()</code> , the parameter is not added to the resulting OpenAPI JSON document. This is the definition of my REST route: <code>rest().description(serviceConfig.getServiceName(), serviceConfig.getServiceName(), ';en';) .post(';/post';) .description(serviceConfig.getServiceName(), ';Receives a post to be published';, ';en';) .type(Post.class) .param().name(';body';).type(body).description(';The post that is to be published.';).endParam() .to(';direct:servicePipeline';); </code> My Rest Configuration is: <code>restConfiguration() .component(';servlet';) .host(';0.0.0.0';) .port(8080) .bindingMode(RestBindingMode.json) .contextPath(serviceConfig.getVersionPath() + ';/'; + serviceConfig.getAffordancePath()) .enableCORS(true) .apiContextPath(';docs';) .apiProperty(';api.title';, serviceConfig.getServiceName()) .apiProperty(';api.version';, ';1.0';) .apiProperty(';cors';, ';true';); </code> The resulting Open API JSON is generated without the request body parameter and reads as: <code>{';openapi';:';3.0.2';,';info';:{';version';:';1.0';},';servers';:[{';url';:';/api/v1/organicposts';}],';paths';:{';/post';:{';post';:{';summary';:';Receives a post to be published';,';operationId';:';verb1';,';responses';:{';200';:{}}}}},';components';:{';schemas';:{}}} </code> When I try to declare RestParamType.path and RestParamType.query parameters, it works perfectly fine for those. Any parameter of type <code>RestParamType.body</code>, however is ignored. The class <code>Post.java</code> that is expected as payload in the POST request body is implemented as: <code>@Data @NoArgsConstructor @Schema(description = ';Post Object as expected by the service';) public class Post { @Schema( name=';id';, description = ';ID by which post is stored in local database';, example=';42';, implementation = Integer.class, required = true ) Integer id; // as stored in the posts database @Schema( name=';partnerId';, description = ';ID of partner on behalf of which the post is to be published';, example=';42';, implementation = Integer.class, required = true ) Integer partnerId ; // as stored in partners table @Schema( name=';textContent';, description = ';Text content of the post.';, example=';This is a descriptive comment of the post';, implementation = String.class, required = true ) String textContent ; @Schema( name=';type';, description = ';Type of the post. Determines the expected type of media declared for the post.';, example=';VIDEO';, implementation = PostType.class, required = true ) PostType type; @ArraySchema @Schema( name=';media';, description = ';Media objects declared for the post. Single element expected for IMAGE, and VIDEO. More than one element expected for MULTI_IMAGE';, required = true) SpMedia[] media ; } </code> The pom.xml: <code> <properties>; <camel.version>;3.20.0</camel.version>; <java.version>;17</java.version>; <spring-cloud.version>;2021.0.3</spring-cloud.version>; <project.build.sourceEncoding>;UTF-8</project.build.sourceEncoding>; <project.reporting.outputEncoding>;UTF-8</project.reporting.outputEncoding>; </properties>; <dependencies>; <dependency>; <groupId>;org.springframework.boot</groupId>; <artifactId>;spring-boot-starter-actuator</artifactId>; <version>;2.7.2</version>; </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>;${camel.version}</version>; </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-configuration-processor</artifactId>; <optional>;true</optional>; </dependency>; <dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-test-spring-junit5</artifactId>; <version>;${camel.version}</version>; </dependency>; <dependency>; <groupId>;org.projectlombok</groupId>; <artifactId>;lombok</artifactId>; <version>;1.18.24</version>; </dependency>; <dependency>; <groupId>;org.apache.camel.springboot</groupId>; <artifactId>;camel-rest-starter</artifactId>; <version>;${camel.version}</version>; </dependency>; <dependency>; <groupId>;org.apache.camel.springboot</groupId>; <artifactId>;camel-servlet-starter</artifactId>; <version>;${camel.version}</version>; </dependency>; <dependency>; <groupId>;org.apache.camel.springboot</groupId>; <artifactId>;camel-jackson-starter</artifactId>; <version>;${camel.version}</version>; </dependency>; <dependency>; <groupId>;org.apache.camel.springboot</groupId>; <artifactId>;camel-http-starter</artifactId>; <version>;${camel.version}</version>; </dependency>; <!-- Swagger and OpenAPI dependencies -->; <dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-openapi-java</artifactId>; <version>;${camel.version}</version>; </dependency>; <dependency>; <groupId>;org.apache.camel.springboot</groupId>; <artifactId>;camel-springdoc-starter</artifactId>; <version>;${camel.version}</version>; </dependency>; <dependency>; <groupId>;org.springdoc</groupId>; <artifactId>;springdoc-openapi-ui</artifactId>; </dependency>; </code> What am I missing to have the request body parameter correctly included into the OpenAPI document? | You need to supply the expected media type(s) for the body payload. You can do that in the Camel REST DSL with the <code>.consumes()</code> method. For example: <code>rest().description(serviceConfig.getServiceName(), serviceConfig.getServiceName(), ';en';) .post(';/post';) .description(serviceConfig.getServiceName(), ';Receives a post to be published';, ';en';) .type(Post.class) .consumes(';application/json';) .param().name(';body';).type(body).description(';The post that is to be published.';).endParam() .to(';direct:servicePipeline';);</code> |
apache-camel | When I include org.apache.camel.springboot:camel-jms-starter:3.20.2 I get two version of the geronimo JMS specorg.apache.geronimo.specs:geronimo-jms_1.1_spec:1.1.1 (included by camel-jms-starter) org.apache.geronimo.specs:geronimo-jms_2.0_spec:1.0-alpha-2 (included by camel-jms)isn't that an error in the camel-jms-starter or is it by design, and I should just exclude the version I don't need? | I would say that that is definitely an error. Obviously, this risks getting JMS interface classes from two different jar files. The JMS 2.0 specification states that and JMS 1.X implementation or application has to be able to run without modification with the JMS 2.0 specification. I would exclude the JMS 1 specification. You will be able to run with either a JMS 1.X implementation or a JMS 2 implementation. If you are using a JMS 2 implementation (and are using JMS 2 features) then you will obviously need the JMS 2 specification jar file. |
apache-camel | I am tring to get camel component properties using java code like: <code>Configuration: Java: 11 Apache Camel: 3.18.2 </code> for Example: if pass Kafka component in java code, get all the latest properties from Apache camel: get all properties of Kafka : additionalProperties, brokers, clientId, headerFilterStrategy, reconnectBackoffMaxMs, shutdownTimeout, allowManualCommit, autoCommitEnable, autoCommitIntervalMs, autoOffsetReset, breakOnFirstError, checkCrcs, commitTimeoutMs, consumerRequestTimeoutMs, consumersCount, fetchMaxBytes, fetchMinBytes, fetchWaitMaxMs, groupId, groupInstanceId, headerDeserializer, heartbeatIntervalMs, keyDeserializer, maxPartitionFetchBytes, maxPollIntervalMs, maxPollRecords, offsetRepository, partitionAssignor, pollOnError, pollTimeoutMs, seekTo, sessionTimeoutMs, specificAvroReader, topicIsPattern, valueDeserializer, bridgeErrorHandler, exceptionHandler, exchangePattern, isolationLevel, kafkaManualCommitFactory, batchWithIndividualHeaders, bufferMemorySize, compressionCodec, connectionMaxIdleMs, deliveryTimeoutMs, enableIdempotence, headerSerializer, key, keySerializer, lingerMs, maxBlockMs, maxInFlightRequest, maxRequestSize, metadataMaxAgeMs, metricReporters, metricsSampleWindowMs, noOfMetricsSample, partitioner, partitionKey, producerBatchSize, queueBufferingMaxMessages, receiveBufferBytes, reconnectBackoffMs, recordMetadata, requestRequiredAcks, requestTimeoutMs, retries, retryBackoffMs, sendBufferBytes, valueSerializer, workerPool, workerPoolCoreSize, workerPoolMaxSize, lazyStartProducer, kafkaClientFactory, synchronous, schemaRegistryURL, interceptorClasses, kerberosBeforeReloginMinTime, kerberosInitCmd, kerberosPrincipalToLocalRules, kerberosRenewJitter, kerberosRenewWindowFactor, saslJaasConfig, saslKerberosServiceName, saslMechanism, securityProtocol, sslCipherSuites, sslContextParameters, sslEnabledProtocols, sslEndpointAlgorithm, sslKeymanagerAlgorithm, sslKeyPassword, sslKeystoreLocation, sslKeystorePassword, sslKeystoreType, sslProtocol, sslProvider, sslTrustmanagerAlgorithm, sslTruststoreLocation, sslTruststorePassword, sslTruststoreType; I have also tried the code but some classes are not found in camel 3.18.2. <code>import org.apache.camel.CamelContext; import org.apache.camel.component.kafka.KafkaComponent; import org.apache.camel.spi.ComponentConfiguration; // class not found import org.apache.camel.spi.Registry; import org.apache.camel.impl.DefaultCamelContext;import java.util.Map;public class CamelComponentProperties { public static void main(String[] args) throws Exception { CamelContext camelContext = new DefaultCamelContext(); camelContext.start(); Registry registry = camelContext.getRegistry(); KafkaComponent kafkaComponent = registry.lookupByNameAndType(';kafka';, KafkaComponent.class); ComponentConfiguration componentConfiguration = kafkaComponent.createComponentConfiguration(); // facing error this line Map<String, Object>; parameters = componentConfiguration.getParameterValues(); for (String parameterName : parameters.keySet()) { System.out.println(parameterName + '; = '; + parameters.get(parameterName)); } camelContext.stop(); } } </code> | One way to do this would be to use the <code>RuntimeCamelCatalog</code> to get a JSON description of the component. <code>RuntimeCamelCatalog catalog = context.getExtension(ExtendedCamelContext.class).getRuntimeCamelCatalog() String componentJson = catalog.componentJSonSchema(';kafka';); </code> Then you can use your preferred JSON parser to inspect the <code>properties</code> &; <code>componentProperties</code> fields. |
apache-camel | I am somewhat of a novice working with the Camel Spring DSL Routes. My experience has been mostly with Java DSL. I recently looked at a project that was based on Camel Spring DSL and noticed that the entire project consisted of just the XML Routes and a few supporting classes for special Processors. Nowhere could I found a Java class to actually Start the route(s) running. I was expecting to find a class that started with something like: <code>@SpringBootApplication public class LocalAppRunner { public static void main(String[] args) { SpringApplication springApplication = new SpringApplication(LocalAppRunner.class); springApplication.setBanner(new TraneBanner()); springApplication.setAdditionalProfiles(';local';); springApplication.setBannerMode(Banner.Mode.LOG); springApplication.run(args); } </code> But evidently there is is no need for any class ( that is overtly written as part of the project ) to fire up the Route. My guess is that the Route is started with something like mvn spring-boot:run Can anyone clarify if I am am correct in this assumption that Spring DSL does not require an overt Java ( or Groovy ) class to fire up a route but can rely on just a mvn reference as indicated above. ( of course the POM file would need the proper entries ) | It's likely that the project in question is camel-spring project and not a camel-spring-boot project. Based on the camel-archetype-spring the startup method is hidden in the org.apache.camel.spring.Main class of camel-spring-main dependency. By default camel-spring-main looks for spring xml configuration files from the <code>META-INF/spring/</code> folder. The application can be started with the camel-maven-plugin using <code>mvn camel:run</code> command. If you however want to run camel routes defined with xml with camel-spring-boot project you can place the xml files to path <code>src/main/resources/camel/</code> in your project. For more information you can look at the documentation. Example file: <code><?xml version=';1.0'; encoding=';UTF-8';?>; <!-- routes.xml -->; <routes xmlns=';http://camel.apache.org/schema/spring';>; <route id=';test';>; <from uri=';timer://trigger?period=1000'; />; <log message=';Hello from xml'; />; </route>; </routes>; </code> The file should only contain the route definition as camel-spring-boot-starter handles creating and configuring CamelContext. |
apache-camel | I have this apache camel route, I instantiate a bean and do some transformation on the incoming string but when i send it to the .to(Endpoints.SEDA_SEND_PRICING_LIFE_CYCLE_MESSAGE) it doesn't take the transformed value. It sends the original one received at the beginning of the route. in my .bean class I am returning an object value. ( have tried returning a string value as well ) <code> from(azureServicebus(AZvalue) .connectionString(connectionString) .receiverAsyncClient(serviceBusReceiverAsyncClient) .serviceBusReceiveMode(ServiceBusReceiveMode.RECEIVE_AND_DELETE) .serviceBusType( ServiceBusType.topic) .prefetchCount(100) .consumerOperation ( ServiceBusConsumerOperationDefinition.receiveMessages ) //.maxAutoLockRenewDuration(Duration.ofMinutes(10)) ) .messageHistory() // Route Name .routeId(Endpoints.SEDA_PROCESS_SB_MESSAGE_ENDPOINT ) // multicast may not need .multicast() .parallelProcessing() // create parallel threads .bean(PricingLifeCyclebService.class, ';paraMap'; ) .log(';Final :- ${body}';) .to(Endpoints.SEDA_SEND_PRICING_LIFE_CYCLE_MESSAGE) .end(); } </code> for reference below is my bean class <code>package com.sams.pricing.lifecycle.processor.services;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component;import com.fasterxml.jackson.core.JsonProcessingException; import com.sams.pricing.lifecycle.processor.dtos.LifecycleDTO; import com.sams.pricing.lifecycle.processor.mapper.LifecycleDtoMapper; import com.sams.pricing.lifecycle.processor.model.LifeCycleTopicC; import com.sams.pricing.lifecycle.processor.queueDtos.ParaDTO; import com.sams.pricing.lifecycle.processor.util.LifeCycleMapper; import com.sams.pricing.lifecycle.processor.util.LifeCycleUtility;import lombok.extern.slf4j.Slf4j;@Slf4j @Component public class PricingLifeCyclebService { @Autowired private LifecycleDtoMapper paraToLifecleDTOMapper; @Autowired private LifeCycleMapper lifecycleTopicmapper ; public LifeCycleTopicC paraMap(String object) throws JsonProcessingException { final var paraMapper = LifeCycleUtility.getObjectMapper(); final var paraDTO = paraMapper.readValue(object, ParaDTO.class); LifecycleDTO lifecycleDTO = paraToLifecleDTOMapper.mapToLifecycleDTO(paraDTO); LifeCycleTopicC obj = lifecycleTopicmapper.toLifeCycleTopicC(lifecycleDTO); log.info(';Event={}, Body={}';, ';ConvertParatoTopic';, obj); return obj; }} </code> | This is because you're transforming the body within multicast block when you should be transforming the body before multicast block. In below example the same message received by direct:example route gets sent simultaneously to endpoint 1, endpoint 2 and endpoint 3. <code>from(';direct:example';) .routeId(';example';) .multicast().parallelProcessing() .bean(HelloBean.class, ';greet'; ) // endpoint 1 .log(';Final :- ${body}';) // endpoint 2 .to(';direct:printBody';) // endpoint 3 .end(); </code> Here's how you should use multicast instead. This transforms the message using bean and sends the transformed message to endpoints <code>direct:multicastA</code>, <code>direct:multicastB</code> and <code>direct:multicastC</code> simultaneously. <code>from(';direct:example3';) .routeId(';example3';) .bean(HelloBean.class, ';greet'; ) .log(';Final :- ${body}';) .multicast().parallelProcessing() .to(';direct:multicastA';) .to(';direct:multicastB';) .to(';direct:multicastC';) .end();from(';direct:multicastA';) .delay(1000) .log(';A: ${body}';) ;from(';direct:multicastB';) .delay(1000) .log(';A: ${body}';) ;from(';direct:multicastC';) .delay(1000) .log(';A: ${body}';) ; </code> Multicast is alternative to the default pipeline behavior. The difference being that pipeline calls endpoints in a sequence and multicast sends the same message to all listed endpoints (<code>.Bean</code> and <code>.log</code> are both endpoints just like direct, seda and timer). |
apache-camel | I am migrating from Camel 2.X to 3.x. Before, I used to do the following in Java DSL: <code>rest().post().route().log().convertBodyTo().process().endRest(); </code> Essentially I can do anything I would normally do in a from, in a rest. In Camel 3, I have to split the above into two configs: one rest and one from: <code>rest().post().to(“fromRoute”); from(“fromRoute”).log().convertBodyTo().process(); </code> I was having trouble finding documentation on this change and the migration page camel gives does not mention this to my knowledge. Is the former REST route definition done in Camel 2 just not a best practice? Is splitting the routes like I did the way forward in Camel 3? Any insight on best practices here or just the correct way to define REST endpoints in camel 3 would be greatly appreciated | Since Camel 3.16.0, you cannot embed routes into the REST DSL. The change was documented in the upgrade guide here: https://camel.apache.org/manual/camel-3x-upgrade-guide-3_16.html#_removed_support_for_embedded_routes There's some brief background to the change in a Jira ticket: https://issues.apache.org/jira/browse/CAMEL-17675 The correct way to configure things is as per your code example where you link the REST DSL to a route via <code>direct</code> etc. E.g. <code>rest().post().to(';direct:start';);from(';direct:start';).log(';Got body: ${body}';); </code> |
apache-camel | I am using the Camel Main component version 3.19 with the following YAML DSL route to successfully load files from an AWS/S3 bucket to the local file system: <code>- beans: - name: IdempotentRepositoryBean type: org.apache.camel.support.processor.idempotent.MemoryIdempotentRepository- route: from: uri: ';aws2-s3:arn:aws:s3:someBucket'; parameters: # The AWS region hosting the bucket and the access credentials # are obtained from Properties file. amazonS3Client: ';#awss3SourceClient'; deleteAfterRead: ';false'; steps: - idempotent-consumer: idempotent-repository: ';IdempotentRepositoryBean'; header: ';CamelAwsS3Key'; skip-duplicate: true - set-header: name: ';CamelFileName'; simple: ';${header.CamelAwsS3Key}'; - to: uri: ';file:C:/...'; </code> However, in addition to the header <code>CamelAwsS3Key</code> I also want to include the header <code>CamelAwsS3LastModified</code> in order to enforce that files renewed on S3 while this route is running are not skipped. Using an equivalent route in Java DSL and appending the key <code>CamelAwsS3LastModified</code> as shown below works fine: <code> route = from(fromEndpoint). idempotentConsumer(header(';CamelAwsS3Key';). append(header(';CamelAwsS3LastModified';)), idempotentRepository); </code> How can I define the combined <code>header</code> as part of the <code>idempotent-consumer</code> spec in the same way in the YAML DSL route above? | I'm afraid that what you are trying to do is not possible with the YAML DSL, as workaround, you can replace your expression with the corresponding simple expression, something like: <code>... - idempotent-consumer: idempotent-repository: ';IdempotentRepositoryBean'; simple: ';${header.CamelAwsS3Key}${header.CamelAwsS3LastModified}'; skip-duplicate: true ... </code> |
apache-camel | I am using CamelTestSupport and currently have 2 unit test for 1 routes. Both unit test is to test if exception is thrown, I used AdviceWith to replace and throw Exception. The issue arises as written in the documentation it is recommended to only Advice the route once as it will cause the 2nd unit test to not match the route. What can i do to reset the route after each unit test? | The issue arises as written in the documentation it is recommended to only Advice the route once as it will cause the 2nd unit test to not match the route.Where does it read like this in the documentation? Using AdviceWith to modify same route in different unit tests seems to work just fine. You should also be able to modify the same route in the same unit tests twice or more for as long the modifications do not conflict with each other. I would however avoid or at least be very careful when using AdviceWith in methods annotated with <code>@BeforeAll</code> or <code>@BeforeEach</code> as these changes will be applied for each test. Same goes for many overridable CamelTestSupport methods. Example <code>package com.example;import org.apache.camel.RoutesBuilder; import org.apache.camel.builder.AdviceWith; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.test.junit5.CamelTestSupport; import org.junit.jupiter.api.Test;public class MultiAdviceWithExampleTests extends CamelTestSupport { class ExceptionA extends Exception {} class ExceptionB extends Exception {} @Test public void exampleThrowsExceptionA() throws Exception{ AdviceWith.adviceWith(context, ';example';, builder ->; { builder.weaveByToUri(';direct:replaceMe';) .replace() .log(';Throwing Exception A';) .throwException(new ExceptionA()); }); MockEndpoint exceptionAMockEndpoint = getMockEndpoint(';mock:exceptionA';); MockEndpoint exceptionBMockEndpoint = getMockEndpoint(';mock:exceptionB';); exceptionAMockEndpoint.expectedMessageCount(1); exceptionBMockEndpoint.expectedMessageCount(0); startCamelContext(); template.sendBody(';direct:example';, null); exceptionBMockEndpoint.assertIsSatisfied(); exceptionAMockEndpoint.assertIsSatisfied(); } @Test public void exampleThrowsExceptionB() throws Exception{ AdviceWith.adviceWith(context, ';example';, builder ->; { builder.weaveByToUri(';direct:replaceMe';) .replace() .log(';Throwing Exception B';) .throwException(new ExceptionB()); }); MockEndpoint exceptionAMockEndpoint = getMockEndpoint(';mock:exceptionA';); MockEndpoint exceptionBMockEndpoint = getMockEndpoint(';mock:exceptionB';); exceptionAMockEndpoint.expectedMessageCount(0); exceptionBMockEndpoint.expectedMessageCount(1); startCamelContext(); template.sendBody(';direct:example';, null); exceptionAMockEndpoint.assertIsSatisfied(); exceptionBMockEndpoint.assertIsSatisfied(); } @Override protected RoutesBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { from(';direct:example';) .id(';example';) .onException(ExceptionA.class) .log(';Caught exception A';) .to(';mock:exceptionA';) .handled(true) .end() .onException(ExceptionB.class) .log(';Caught exception A';) .to(';mock:exceptionB';) .handled(true) .end() .to(';direct:replaceMe';) ; from(';direct:replaceMe';) .routeId(';replaceMe';) .log(';should not be displayed.';); } }; } @Override public boolean isUseAdviceWith() { return true; } } </code> Since overriding the <code>isUseAdviceWith</code> method to return true forces one to start camel context manually for each tests I am assuming that <code>CamelTestsSupport</code> either creates separate context and routes for each tests or at least resets the routes and mock endpoints to their original states between tests.Both unit test is to test if exception is thrown, I used AdviceWith to replace and throw Exception.If you're using JUnits <code>assertThrows</code> it might not work as you expect with Apache Camel as Camel will likely throw one of it's own Exceptions instead. To get the original Exception you can use <code>template.send</code> and get the resulting exception from the resulting exchange through <code>.getException().getClass()</code>. <code>// Remove the onException blocks from route with this // or getException() will return null Exchange result = template.send(';direct:example';, new DefaultExchange(context)); assertEquals(ExceptionB.class, result.getException().getClass()); </code> |
apache-camel | I have a camel application running with Spring Boot. I want to improve resilience by letting my application start up even if one or more of the ';from'; endpoints (MQ or SMPP in my case) are not currently available - I want the application to just keep checking, and pick up messages once the endpoint becomes available. Current code: <code>// Application.java @SpringBootApplication @ConfigurationPropertiesScan public class Application { @Autowired private CamelContext context; public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Bean CommandLineRunner init(ProducerTemplate template) { return args ->; { context.addRoutes(new MQRouteBuilder()); context.addRoutes(new SMPPRouteBuilder()); }; } }// example route builder public class SMPPRouteBuilder extends RouteBuilder { public void configure() throws Exception { from(';smpp://{{camel.component.smpp.configuration.host}}';).to(';direct:processSMS';); //... } } </code> Currently, if the SMS-C defined as camel.component.smpp.configuration.host isn't available, the application fails to start:java.lang.IllegalStateException: Failed to execute CommandLineRunner at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:787) ~[spring-boot-2.2.6.RELEASE.jar:2.2.6.RELEASE] at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:768) ~[spring-boot-2.2.6.RELEASE.jar:2.2.6.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:322) ~[spring-boot-2.2.6.RELEASE.jar:2.2.6.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) ~[spring-boot-2.2.6.RELEASE.jar:2.2.6.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1215) ~[spring-boot-2.2.6.RELEASE.jar:2.2.6.RELEASE] at Application.main(Application.java:28) ~[classes/:na] Caused by: org.apache.camel.RuntimeCamelException: java.io.IOException: localhostInvalid at org.apache.camel.RuntimeCamelException.wrapRuntimeException(RuntimeCamelException.java:68) ~[camel-api-3.1.0.jar:3.1.0] at org.apache.camel.support.service.ServiceSupport.start(ServiceSupport.java:134) ~[camel-api-3.1.0.jar:3.1.0] at org.apache.camel.impl.engine.AbstractCamelContext.startService(AbstractCamelContext.java:2989) ~[camel-base-3.1.0.jar:3.1.0] at org.apache.camel.impl.engine.AbstractCamelContext.doStartOrResumeRouteConsumers(AbstractCamelContext.java:3327) ~[camel-base-3.1.0.jar:3.1.0] at org.apache.camel.impl.engine.AbstractCamelContext.doStartRouteConsumers(AbstractCamelContext.java:3258) ~[camel-base-3.1.0.jar:3.1.0] at org.apache.camel.impl.engine.AbstractCamelContext.safelyStartRouteServices(AbstractCamelContext.java:3163) ~[camel-base-3.1.0.jar:3.1.0] at org.apache.camel.impl.engine.AbstractCamelContext.safelyStartRouteServices(AbstractCamelContext.java:3189) ~[camel-base-3.1.0.jar:3.1.0] at org.apache.camel.impl.engine.AbstractCamelContext.startRouteService(AbstractCamelContext.java:3033) ~[camel-base-3.1.0.jar:3.1.0] at org.apache.camel.impl.DefaultModel.start(DefaultModel.java:358) ~[camel-core-engine-3.1.0.jar:3.1.0] at org.apache.camel.impl.DefaultModel.startRoute(DefaultModel.java:330) ~[camel-core-engine-3.1.0.jar:3.1.0] at org.apache.camel.impl.DefaultModel.startRouteDefinitions(DefaultModel.java:323) ~[camel-core-engine-3.1.0.jar:3.1.0] at org.apache.camel.impl.DefaultModel.addRouteDefinitions(DefaultModel.java:88) ~[camel-core-engine-3.1.0.jar:3.1.0] at org.apache.camel.impl.AbstractModelCamelContext.addRouteDefinitions(AbstractModelCamelContext.java:110) ~[camel-core-engine-3.1.0.jar:3.1.0] at org.apache.camel.builder.RouteBuilder.populateRoutes(RouteBuilder.java:520) ~[camel-core-engine-3.1.0.jar:3.1.0] at org.apache.camel.builder.RouteBuilder.addRoutesToCamelContext(RouteBuilder.java:437) ~[camel-core-engine-3.1.0.jar:3.1.0] at org.apache.camel.impl.engine.AbstractCamelContext.lambda$addRoutes$0(AbstractCamelContext.java:1160) ~[camel-base-3.1.0.jar:3.1.0] at org.apache.camel.impl.engine.AbstractCamelContext.doWithDefinedClassLoader(AbstractCamelContext.java:2544) ~[camel-base-3.1.0.jar:3.1.0] at org.apache.camel.impl.engine.AbstractCamelContext.addRoutes(AbstractCamelContext.java:1160) ~[camel-base-3.1.0.jar:3.1.0] at Application.lambda$0(Application.java:42) ~[classes/:na] at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:784) ~[spring-boot-2.2.6.RELEASE.jar:2.2.6.RELEASE] ... 5 common frames omitted Caused by: java.io.IOException: localhostInvalid at org.apache.camel.component.smpp.SmppConnectionFactory.createConnection(SmppConnectionFactory.java:112) ~[camel-smpp-3.1.0.jar:3.1.0] at org.jsmpp.session.SMPPSession.connectAndBind(SMPPSession.java:222) ~[jsmpp-2.3.8.jar:2.3.8] at org.jsmpp.session.SMPPSession.connectAndBind(SMPPSession.java:201) ~[jsmpp-2.3.8.jar:2.3.8] at org.apache.camel.component.smpp.SmppConsumer.createSession(SmppConsumer.java:95) ~[camel-smpp-3.1.0.jar:3.1.0] at org.apache.camel.component.smpp.SmppConsumer.doStart(SmppConsumer.java:84) ~[camel-smpp-3.1.0.jar:3.1.0] at org.apache.camel.support.service.ServiceSupport.start(ServiceSupport.java:121) ~[camel-api-3.1.0.jar:3.1.0] ... 23 common frames omitted Caused by: java.net.UnknownHostException: localhostInvalid at java.base/java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:229) ~[na:na] at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) ~[na:na] at java.base/java.net.Socket.connect(Socket.java:609) ~[na:na] at org.apache.camel.component.smpp.SmppConnectionFactory.createConnection(SmppConnectionFactory.java:99) ~[camel-smpp-3.1.0.jar:3.1.0]What I want instead, is for the application to start up, start listening on the connections it can connect to (e.g. MQ), and just periodically retry the ones it can't until they become available. | I had the same problem but with JMS component. Here is what I did:Set an id on my route (<code>.routeId(';demo';)</code>)Put my route with <code>.autostart(false)</code>Add to the context an extra system-oriented route with a <code>from(';timer:';)</code> in order to regularly monitor the health of (in my case) the JMS broker. When the broker is detected ';up';, then a Camel processor can simply (via Camel API) ask te controller to restart the involved route(s): <code>context.getRouteController().start(';demo';)</code> Hope this helps |
apache-camel | In my project, I am using apache camel + ibm mq + spring boot for messaging. I am getting a compile time err which I am not able to resolve. <code>com.ibm.mq.jms.MQConnectionFactory mqQueueConnectionFactoy = new MQQueueConnectionFactory(); // set all the properties to above mqQueueConnectionFactoy such as queue manager etc. CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory(mqQueueConnectionFactoy);</code> Now on the second line I am getting this err: <code>Now on the second line I am getting this err: 'CachingConnectionFactory(jakarta.jms.ConnectionFactory)' in 'org.springframework.jms.connection.CachingConnectionFactory' cannot be applied to '(com.ibm.mq.jms.MQConnectionFactory)' </code> I have googled a lot but not able to find any such example. Any help would be appreciate. My build.gradle has below dependencies. <code>// Camel implementation 'org.apache.camel.springboot:camel-spring-boot-starter:4.0.0-M1' implementation('org.apache.camel.springboot:camel-servlet-starter:4.0.0-M1') implementation('org.apache.camel.springboot:camel-jaxb-starter:4.0.0-M1') implementation(';org.apache.camel:camel-jms:4.0.0-M1';) implementation(';org.apache.camel:camel-core:4.0.0-M1';) // IBM MQ implementation(';javax.jms:javax.jms-api:2.0.1';) implementation(';com.ibm.mq:com.ibm.mq.allclient:9.1.0.5';) implementation(';com.ibm.ims:udb:15.1.31';) implementation(';javax.xml.bind:jaxb-api:2.4.0-b180830.0359';) </code> | You will need to replace your <code>com.ibm.mq.allclient</code> dependency with <code>com.ibm.mq.jakarta.client</code> and replace <code>javax.jms-api:2.0.1</code> with <code>jakarta.jms-api</code> Ala https://www.ibm.com/docs/en/ibm-mq/9.3?topic=umcjm-obtaining-mq-classes-jms-mq-classes-jakarta-messaging-separately See https://mvnrepository.com/artifact/com.ibm.mq/com.ibm.mq.jakarta.client and https://mvnrepository.com/artifact/jakarta.jms/jakarta.jms-api for latest versions. |
apache-camel | I am trying to transform a Json input to XML in XSLT, however when doing the transformation I only get the children without any of their parent nodes, i.e. ';Client';, ';ClientApp';, ';Payment'; and ';Bill'; nodes they don't show up in the XML output, any idea what I'm missing in the template for these nodes to show up? template <code><?xml version=';1.0'; encoding=';UTF-8'; ?>; <xsl:stylesheet version=';1.0'; xmlns:xsl=';http://www.w3.org/1999/XSL/Transform'; xmlns:xj=';http://camel.apache.org/component/xj'; exclude-result-prefixes=';xj';>;<xsl:output omit-xml-declaration=';no'; encoding=';UTF-8'; method=';xml'; indent=';yes';/>;<xsl:template match=';/';>; <xsl:apply-templates select=';//object';/>; </xsl:template>;<xsl:template match=';object[@xj:type != 'object' and @xj:type != 'array' and string-length(@xj:name) >; 0]';>; <xsl:variable name=';name'; select=';@xj:name';/>; <xsl:element name=';{$name}';>; <xsl:value-of select=';text()';/>; </xsl:element>; </xsl:template>;<xsl:template match=';@*|node()';/>; </xsl:stylesheet>; </code> Json <code>{ ';Client';: { ';Date';: ';2022-12-29T09:55:05';, ';Lang';: ';es-CO';, ';ClientApp';: { ';Org';: ';COMPANY';, ';Name';: ';NAME COMPANY';, ';Version';: 1 } }, ';Payment';: { ';PaymentId';: ';00000000-0000-0000-0000-943534532';, ';Bill';: { ';PaymentId';: ';00000000-0000-0000-0000-943534532';, ';PaymeentNumber';: 63703, ';BillId';: ';00000000-0000-0000-0000-003223439138'; } } } </code> Output XML <code><?xml version=';1.0'; encoding=';UTF-8';?>; <Date>;2022-12-29T09:55:05</Date>; <Lang>;es-CO</Lang>; <Org>;COMPANY</Org>; <Name>;NAME COMPANY</Name>; <Version>;1</Version>; <PaymentId>;00000000-0000-0000-0000-943534532</PaymentId>; <PaymentId>;00000000-0000-0000-0000-943534532</PaymentId>; <PaymeentNumber>;63703</PaymeentNumber>; <BillId>;00000000-0000-0000-0000-003223439138</BillId>; </code> XML Input <code><?xml version=';1.0'; encoding=';UTF-8';?>; <object xmlns:xj=';http://camel.apache.org/component/xj'; xj:type=';object';>; <object xj:name=';Client'; xj:type=';object';>; <object xj:name=';Date'; xj:type=';string';>;2022-12-29T09:55:05</object>; <object xj:name=';Lang'; xj:type=';string';>;es-CO</object>; <object xj:name=';ClientApp'; xj:type=';object';>; <object xj:name=';Org'; xj:type=';string';>;COMPANY</object>; <object xj:name=';Name'; xj:type=';string';>;NAME COMPANY</object>; <object xj:name=';Version'; xj:type=';int';>;1</object>; </object>; </object>; <object xj:name=';Payment'; xj:type=';object';>; <object xj:name=';PaymentId'; xj:type=';string';>;00000000-0000-0000-0000-943534532</object>; <object xj:name=';Bill'; xj:type=';object';>; <object xj:name=';PaymentId'; xj:type=';string';>;00000000-0000-0000-0000-943534532</object>; <object xj:name=';PaymeentNumber'; xj:type=';int';>;63703</object>; <object xj:name=';BillId'; xj:type=';string';>;00000000-0000-0000-0000-003223439138</object>; </object>; </object>; </code> | Your stylesheet excludes the parent elements by the <code>@xj:type != 'object'</code> predicate. Also, your method of: <code><xsl:apply-templates select=';//object';/>; </code> will flatten the result. If you want to preserve the original hierarchy then try something like: XSLT 1.0 <code><xsl:stylesheet version=';1.0'; xmlns:xsl=';http://www.w3.org/1999/XSL/Transform'; xmlns:xj=';http://camel.apache.org/component/xj'; exclude-result-prefixes=';xj';>; <xsl:output method=';xml'; version=';1.0'; encoding=';UTF-8'; indent=';yes';/>; <xsl:strip-space elements=';*';/>;<xsl:template match=';/object';>; <root>; <xsl:apply-templates/>; </root>; </xsl:template>;<xsl:template match=';object';>; <xsl:choose>; <xsl:when test=';@xj:name';>; <xsl:element name=';{@xj:name}';>; <xsl:apply-templates/>; </xsl:element>; </xsl:when>; <xsl:otherwise>; <xsl:apply-templates/>; </xsl:otherwise>; </xsl:choose>; </xsl:template>;</xsl:stylesheet>; </code> |
apache-camel | The Producer in Kafka is producing messages, but the consumer is down after consuming the 5th message. After some time the consumer is up, and I want to consume the 6th message, instead of the latest message. How can I do this? Producer.java <code>public class kafkaProducerRoute extends RouteBuilder{ @Override public void configure() throws Exception { from(';timer:time?';) // loop over the route 10 times .setBody().constant(';Hello, World!';) // set the message body to ';Hello, World!'; .to(';kafka:hello1?brokers=localhost:9092';) // send the message to a Kafka topic using the Kafka producer endpoint .log(';Message is produced';);} </code> } Consumer.java <code> from(';kafka:c1?brokers=localhost:9092';) .log(';Received message with offset: ${header.'; + KafkaConstants.OFFSET + ';} - ${body}';); </code> | when the consumer group comes up again, does it come up with the same old group_id, if yes, then it should continue from where it left, if not, then this is normal as per the default setting for <code>auto.offset.reset = latest</code> will always start from the latest offset of the topic https://kafka.apache.org/documentation/#consumerconfigs_auto.offset.reset |
apache-camel | I am not sure why i am running into the following error <code>#9 29.22 [ERROR] /src/main/java/com/nestwealth/ftpintegration/onboarding/response/OnboardingResponseRoute.java:[15,16] cannot find symbol #9 29.22 [ERROR] symbol: class HmacGenerator #9 29.22 [ERROR] location: class com.nestwealth.ftpintegration.onboarding.response.OnboardingResponseRoute </code> I have class declared that needs to used in multiple places, which is defined as following HmacGenerator.java <code>package com.example.ftpintegration;import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException;import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.json.JSONObject;@Component public class HmacGenerator { private String secretKey; public HmacGenerator(@Value(';{secret-key}';) String secretKey){ this.secretKey = secretKey; } public String generateHmacKey (String sftpResponseObj){ log.warn(';SFTP response: ('; + sftpResponseObj); String encodingType = ';HmacSHA256';; JSONObject obj = new JSONObject(sftpResponseObj); log.warn(';Stringified SFTP response: ('; + obj.toString()); return ';test';; } }</code> I am trying to consume the above method <code>generateHmacKey(...)</code> in the following class OnboardingResponseRoute.java <code>package com.example.ftpintegration.onboarding.response;import org.apache.camel.Exchange; import org.apache.camel.builder.endpoint.EndpointRouteBuilder; import org.apache.camel.processor.idempotent.jdbc.JdbcMessageIdRepository; import org.springframework.stereotype.Component; import org.springframework.beans.factory.annotation.Autowired;@Component public class OnboardingResponseRoute extends EndpointRouteBuilder { private JdbcMessageIdRepository idempotentRepository; @Autowired public HmacGenerator hmacgenerator; //fails right here public OnboardingResponseRoute(JdbcMessageIdRepository sftpOnboardingProcessor) { this.idempotentRepository = sftpOnboardingProcessor; } @Override public void configure() throws Exception { from(sftp(';{{sftp.host}}:{{sftp.port}}/{{sftp.path}}';) .username(';{{sftp.user}}';) .password(';{{sftp.password}}';) .recursive(false) .useUserKnownHostsFile(false) .delay(';{{response.sftp.delay}}';) .delete(false) .idempotent(true) .idempotentRepository(idempotentRepository) .advanced() .stepwise(false) .localWorkDirectory(';{{sftp.tmp-directory}}';)) .setHeader(Exchange.HTTP_METHOD, constant(';POST';)) .setHeader(Exchange.CONTENT_TYPE, constant(';application/json';)) .setHeader(';x-digest';) .method(hmacgenerator, ';generateHmacKey(${body})';) .log(';Started copying file: ${header.CamelFileName}';) .to(';{{response.http.url}}/account-opening-response';) .log(';Done copying file: ${header.CamelFileName}';); }} </code> My config file looks like the following pom.xml <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>;2.5.3</version>; <relativePath/>; <!-- lookup parent from repository -->; </parent>; <groupId>;com.nestwealth</groupId>; <artifactId>;ftpintegration</artifactId>; <version>;0.0.1-SNAPSHOT</version>; <name>;ftpintegration</name>; <description>;SFTP to S3 Integration</description>; <properties>; <java.version>;11</java.version>; </properties>; <dependencies>; <dependency>; <groupId>;org.apache.camel.springboot</groupId>; <artifactId>;camel-spring-boot-starter</artifactId>; <version>;3.11.1</version>; </dependency>; <dependency>; <groupId>;org.apache.camel.springboot</groupId>; <artifactId>;camel-bean-starter</artifactId>; <version>;3.11.1</version>; </dependency>; <dependency>; <groupId>;org.apache.camel.springboot</groupId>; <artifactId>;camel-ftp-starter</artifactId>; <version>;3.11.1</version>; </dependency>; <dependency>; <groupId>;org.apache.camel.springboot</groupId>; <artifactId>;camel-aws2-s3-starter</artifactId>; <version>;3.11.1</version>; </dependency>; <dependency>; <groupId>;org.apache.camel.springboot</groupId>; <artifactId>;camel-http-starter</artifactId>; <version>;3.11.1</version>; </dependency>; <dependency>; <groupId>;org.springframework.boot</groupId>; <artifactId>;spring-boot-starter-jdbc</artifactId>; </dependency>; <dependency>; <groupId>;org.springframework.boot</groupId>; <artifactId>;spring-boot-starter-data-jpa</artifactId>; </dependency>; <dependency>; <groupId>;com.vladmihalcea</groupId>; <artifactId>;hibernate-types-55</artifactId>; <version>;2.14.0</version>; </dependency>; <dependency>; <groupId>;org.apache.camel.springboot</groupId>; <artifactId>;camel-jackson-starter</artifactId>; <version>;3.11.1</version>; </dependency>; <dependency>; <groupId>;org.apache.camel.springboot</groupId>; <artifactId>;camel-jpa-starter</artifactId>; <version>;3.11.1</version>; </dependency>; <dependency>; <groupId>;org.apache.camel.springboot</groupId>; <artifactId>;camel-sql-starter</artifactId>; <version>;3.11.1</version>; </dependency>; <dependency>; <groupId>;org.postgresql</groupId>; <artifactId>;postgresql</artifactId>; <scope>;runtime</scope>; </dependency>; <dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-endpointdsl</artifactId>; <version>;3.11.1</version>; </dependency>; <dependency>; <groupId>;org.springframework.boot</groupId>; <artifactId>;spring-boot-starter-test</artifactId>; <scope>;test</scope>; </dependency>; <dependency>; <groupId>;org.json</groupId>; <artifactId>;json</artifactId>; <version>;20220924</version>; </dependency>; </dependencies>; <build>; <plugins>; <plugin>; <groupId>;org.springframework.boot</groupId>; <artifactId>;spring-boot-maven-plugin</artifactId>; </plugin>; </plugins>; </build>;</project>;</code> | please check if you added <code>@ComponentScan</code> in your main application file <code>@SpringBootApplication @ComponentScan(basePackages = { ';com.example.ftpintegration'; }) // ... </code> and check if you have imported <code>HmacGenerator</code> in <code>OnboardingResponseRoute</code>: <code>import com.example.ftpintegration.HmacGenerator; </code> |
apache-camel | as in question, I created route like: <code>@Component class AccountantPartnerRouteConfig { @Bean RoutesBuilder accountantPartnerRoute() { return new RouteBuilder() { @Override public void configure() { from(ACCOUNTANT_PARTNER.getInternalQueue()) .routeId(ACCOUNTANT_PARTNER.getInternalQueue()) .bean(BeanProcessor.of(Function.identity())) .log(';Publish partner event, idEvent: ${body.eventUuid}';) .marshal() .json(JsonLibrary.Jackson) .to(ACCOUNTANT_PARTNER.getQueue()); } }; }} </code> And for the test purpose Im sending object: <code>@Data @NoArgsConstructor @AllArgsConstructor public class BaseEvent { private UUID eventUuid = randomUUID(); private ZonedDateTime eventCreatedDate = ZonedDateTime.now(); } </code> But when Im trying to send the event to destination queue Im getting exception: <code>2023-02-22 09:29:36.922 INFO [,,] 90471 --- [#1 - seda://accountant-partner] seda:accountant-partner:166 : Publish partner event, idEvent: 60d19eb6-6790-460e-b416-edc5823e2e2a 2023-02-22 09:29:36.931 ERROR [,,] 90471 --- [#1 - seda://accountant-partner] org.apache.camel.processor.errorhandler.DefaultErrorHandler:205 : Failed delivery for (MessageId: 7EB96068202A615-0000000000000001 on ExchangeId: 7EB96068202A615-0000000000000001). Exhausted after delivery attempt: 1 caught: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Java 8 date/time type `java.time.ZonedDateTime` not supported by default: add Module ';com.fasterxml.jackson.datatype:jackson-datatype-jsr310'; to enable handling (through reference chain: pl.fenige.mms.domain.model.event.PublishEventServiceImpl$Test[';eventCreatedDate';])Message History (source location and message history is disabled) --------------------------------------------------------------------------------------------------------------------------------------- Source ID Processor Elapsed (ms) seda:accountant-partner/seda:a from[seda://accountant-partner] 3914961 ... seda:accountant-partner/marsha marshal[org.apache.camel.model.dataformat.JsonData 0Stacktrace ---------------------------------------------------------------------------------------------------------------------------------------com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Java 8 date/time type `java.time.ZonedDateTime` not supported by default: add Module ';com.fasterxml.jackson.datatype:jackson-datatype-jsr310'; to enable handling (through reference chain: pl.fenige.mms.domain.model.event.PublishEventServiceImpl$Test[';eventCreatedDate';]) at com.fasterxml.jackson.databind.exc.InvalidDefinitionException.from(InvalidDefinitionException.java:77) at com.fasterxml.jackson.databind.SerializerProvider.reportBadDefinition(SerializerProvider.java:1300) at com.fasterxml.jackson.databind.ser.impl.UnsupportedTypeSerializer.serialize(UnsupportedTypeSerializer.java:35) at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:728) at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:774) at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:178) at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider._serialize(DefaultSerializerProvider.java:480) at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:319) at com.fasterxml.jackson.databind.ObjectWriter$Prefetch.serialize(ObjectWriter.java:1518) at com.fasterxml.jackson.databind.ObjectWriter._writeValueAndClose(ObjectWriter.java:1219) at com.fasterxml.jackson.databind.ObjectWriter.writeValue(ObjectWriter.java:1044) at org.apache.camel.component.jackson.AbstractJacksonDataFormat.marshal(AbstractJacksonDataFormat.java:155) at org.apache.camel.support.processor.MarshalProcessor.process(MarshalProcessor.java:64) at org.apache.camel.processor.errorhandler.RedeliveryErrorHandler$SimpleTask.run(RedeliveryErrorHandler.java:477) 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.seda.SedaConsumer.sendToConsumers(SedaConsumer.java:269) at org.apache.camel.component.seda.SedaConsumer.doRun(SedaConsumer.java:187) at org.apache.camel.component.seda.SedaConsumer.run(SedaConsumer.java:130) at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1136) at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635) at java.base/java.lang.Thread.run(Thread.java:833)2023-02-22 09:29:36.933 WARN [,,] 90471 --- [#1 - seda://accountant-partner] org.apache.camel.component.seda.SedaConsumer:214 : Error processing exchange. Exchange[7EB96068202A615-0000000000000001]. Caused by: [com.fasterxml.jackson.databind.exc.InvalidDefinitionException - Java 8 date/time type `java.time.ZonedDateTime` not supported by default: add Module ';com.fasterxml.jackson.datatype:jackson-datatype-jsr310'; to enable handling (through reference chain: pl.fenige.mms.domain.model.event.PublishEventServiceImpl$Test[';eventCreatedDate';])]com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Java 8 date/time type `java.time.ZonedDateTime` not supported by default: add Module ';com.fasterxml.jackson.datatype:jackson-datatype-jsr310'; to enable handling (through reference chain: pl.fenige.mms.domain.model.event.PublishEventServiceImpl$Test[';eventCreatedDate';]) at com.fasterxml.jackson.databind.exc.InvalidDefinitionException.from(InvalidDefinitionException.java:77) at com.fasterxml.jackson.databind.SerializerProvider.reportBadDefinition(SerializerProvider.java:1300) at com.fasterxml.jackson.databind.ser.impl.UnsupportedTypeSerializer.serialize(UnsupportedTypeSerializer.java:35) at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:728) at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:774) at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:178) at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider._serialize(DefaultSerializerProvider.java:480) at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:319) at com.fasterxml.jackson.databind.ObjectWriter$Prefetch.serialize(ObjectWriter.java:1518) at com.fasterxml.jackson.databind.ObjectWriter._writeValueAndClose(ObjectWriter.java:1219) at com.fasterxml.jackson.databind.ObjectWriter.writeValue(ObjectWriter.java:1044) at org.apache.camel.component.jackson.AbstractJacksonDataFormat.marshal(AbstractJacksonDataFormat.java:155) at org.apache.camel.support.processor.MarshalProcessor.process(MarshalProcessor.java:64) at org.apache.camel.processor.errorhandler.RedeliveryErrorHandler$SimpleTask.run(RedeliveryErrorHandler.java:477) 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.seda.SedaConsumer.sendToConsumers(SedaConsumer.java:269) at org.apache.camel.component.seda.SedaConsumer.doRun(SedaConsumer.java:187) at org.apache.camel.component.seda.SedaConsumer.run(SedaConsumer.java:130) at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1136) at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635) at java.base/java.lang.Thread.run(Thread.java:833) </code> It seems like artifact 'com.fasterxml.jackson.datatype:jackson-datatype-jsr310' is missing but it is already added. I've also tried to create bean like: <code>@Bean ObjectMapper objectMapper() { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.registerModule(new JavaTimeModule()); return objectMapper; } </code> But it also did not help. Do somebody know what I have to do to handle this ZonedDateTime without custom serializers/deserializers? Here is my pom.xml (just without some metadata): <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';>; <properties>; <java.version>;17</java.version>; <flyway.version>;8.5.13</flyway.version>; <lombok.version>;1.18.26</lombok.version>; <querydsl.version>;5.0.0</querydsl.version>; <lombok.version>;1.18.26</lombok.version>; <quartz-scheduler.version>;2.3.2</quartz-scheduler.version>; <spock-groovy.version>;2.4-M1-groovy-4.0</spock-groovy.version>; <spring-cloud.version>;2021.0.3</spring-cloud.version>; <micrometer.version>;1.9.1</micrometer.version>; <logback.version>;1.2.9</logback.version>; <logstash.logback.encoder>;5.2</logstash.logback.encoder>; <sdnotify.version>;1.3</sdnotify.version>; <sentry.version>;1.7.30</sentry.version>; <camel.version>;3.20.2</camel.version>; </properties>; <dependencies>; <!-- Spring -->; <dependency>; <groupId>;org.springframework.boot</groupId>; <artifactId>;spring-boot-starter-actuator</artifactId>; </dependency>; <dependency>; <groupId>;org.springframework.boot</groupId>; <artifactId>;spring-boot-starter</artifactId>; </dependency>; <dependency>; <groupId>;org.springframework.cloud</groupId>; <artifactId>;spring-cloud-starter-config</artifactId>; </dependency>; <dependency>; <groupId>;org.springframework.cloud</groupId>; <artifactId>;spring-cloud-starter-bootstrap</artifactId>; </dependency>; <dependency>; <groupId>;org.springframework.boot</groupId>; <artifactId>;spring-boot-starter-data-jdbc</artifactId>; </dependency>; <dependency>; <groupId>;org.springframework.boot</groupId>; <artifactId>;spring-boot-starter-data-jpa</artifactId>; </dependency>; <dependency>; <groupId>;org.springframework.boot</groupId>; <artifactId>;spring-boot-starter-validation</artifactId>; </dependency>; <dependency>; <groupId>;org.springframework.boot</groupId>; <artifactId>;spring-boot-configuration-processor</artifactId>; </dependency>; <dependency>; <groupId>;org.springframework.cloud</groupId>; <artifactId>;spring-cloud-starter</artifactId>; </dependency>; <dependency>; <groupId>;org.springframework.cloud</groupId>; <artifactId>;spring-cloud-starter-sleuth</artifactId>; </dependency>; <dependency>; <groupId>;org.springframework.boot</groupId>; <artifactId>;spring-boot-starter-mail</artifactId>; </dependency>; <dependency>; <groupId>;org.apache.camel.springboot</groupId>; <artifactId>;camel-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.springframework.boot</groupId>; <artifactId>;spring-boot-starter-security</artifactId>; </dependency>; <dependency>; <groupId>;org.springframework.boot</groupId>; <artifactId>;spring-boot-starter-thymeleaf</artifactId>; </dependency>; <!-- Spring -->; <!-- Datasource -->; <dependency>; <groupId>;org.flywaydb</groupId>; <artifactId>;flyway-core</artifactId>; <version>;${flyway.version}</version>; </dependency>; <dependency>; <groupId>;org.postgresql</groupId>; <artifactId>;postgresql</artifactId>; <scope>;runtime</scope>; </dependency>; <dependency>; <groupId>;com.querydsl</groupId>; <artifactId>;querydsl-jpa</artifactId>; <version>;${querydsl.version}</version>; </dependency>; <dependency>; <groupId>;com.querydsl</groupId>; <artifactId>;querydsl-apt</artifactId>; <version>;${querydsl.version}</version>; <scope>;provided</scope>; </dependency>; <!-- Datasource -->; <!-- Commons -->; <dependency>; <groupId>;org.projectlombok</groupId>; <artifactId>;lombok</artifactId>; <version>;${lombok.version}</version>; <optional>;true</optional>; </dependency>; <dependency>; <groupId>;com.neovisionaries</groupId>; <artifactId>;nv-i18n</artifactId>; <version>;1.29</version>; <scope>;compile</scope>; </dependency>; <dependency>; <groupId>;com.google.code.gson</groupId>; <artifactId>;gson</artifactId>; <version>;2.9.0</version>; <scope>;compile</scope>; </dependency>; <!-- Commons -->; <!-- Quartz -->; <dependency>; <groupId>;org.quartz-scheduler</groupId>; <artifactId>;quartz</artifactId>; <version>;${quartz-scheduler.version}</version>; </dependency>; <dependency>; <groupId>;org.springframework</groupId>; <artifactId>;spring-context-support</artifactId>; </dependency>; <!-- Quartz -->; <!-- Integrations -->; <dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-rabbitmq</artifactId>; <version>;${camel.version}</version>; </dependency>; <dependency>; <groupId>;org.apache.camel.springboot</groupId>; <artifactId>;camel-jackson-starter</artifactId>; </dependency>; <dependency>; <groupId>;com.fasterxml.jackson.datatype</groupId>; <artifactId>;jackson-datatype-jsr310</artifactId>; </dependency>; <!-- Integrations -->; <!-- Logback -->; <dependency>; <groupId>;io.micrometer</groupId>; <artifactId>;micrometer-registry-prometheus</artifactId>; <version>;${micrometer.version}</version>; </dependency>; <dependency>; <groupId>;ch.qos.logback</groupId>; <artifactId>;logback-core</artifactId>; <version>;${logback.version}</version>; </dependency>; <dependency>; <groupId>;net.logstash.logback</groupId>; <artifactId>;logstash-logback-encoder</artifactId>; <version>;${logstash.logback.encoder}</version>; </dependency>; <dependency>; <groupId>;io.sentry</groupId>; <artifactId>;sentry-logback</artifactId>; <version>;${sentry.version}</version>; </dependency>; <dependency>; <groupId>;io.sentry</groupId>; <artifactId>;sentry-spring</artifactId>; <version>;${sentry.version}</version>; </dependency>; <dependency>; <groupId>;info.faljse</groupId>; <artifactId>;SDNotify</artifactId>; <version>;${sdnotify.version}</version>; </dependency>; <!-- Logback -->; <!-- Test -->; <dependency>; <groupId>;org.springframework.boot</groupId>; <artifactId>;spring-boot-starter-test</artifactId>; <scope>;test</scope>; </dependency>; <dependency>; <groupId>;org.springframework.security</groupId>; <artifactId>;spring-security-test</artifactId>; <scope>;test</scope>; </dependency>; <dependency>; <groupId>;org.spockframework</groupId>; <artifactId>;spock-core</artifactId>; <version>;${spock-groovy.version}</version>; <scope>;test</scope>; </dependency>; <!-- Test -->; </dependencies>; <dependencyManagement>; <dependencies>; <dependency>; <groupId>;org.springframework.cloud</groupId>; <artifactId>;spring-cloud-dependencies</artifactId>; <version>;${spring-cloud.version}</version>; <type>;pom</type>; <scope>;import</scope>; </dependency>; <dependency>; <groupId>;org.apache.camel.springboot</groupId>; <artifactId>;camel-spring-boot-bom</artifactId>; <version>;${camel.version}</version>; <type>;pom</type>; <scope>;import</scope>; </dependency>; </dependencies>; </dependencyManagement>; <build>; <finalName>;test</finalName>; <plugins>; <plugin>; <groupId>;org.springframework.boot</groupId>; <artifactId>;spring-boot-maven-plugin</artifactId>; <configuration>; <excludes>; <exclude>; <groupId>;org.projectlombok</groupId>; <artifactId>;lombok</artifactId>; </exclude>; </excludes>; </configuration>; </plugin>; <plugin>; <groupId>;com.mysema.maven</groupId>; <artifactId>;apt-maven-plugin</artifactId>; <version>;1.1.3</version>; <executions>; <execution>; <goals>; <goal>;process</goal>; </goals>; <configuration>; <outputDirectory>;target/generated-sources/java</outputDirectory>; <processor>;com.querydsl.apt.jpa.JPAAnnotationProcessor</processor>; </configuration>; </execution>; </executions>; </plugin>; <plugin>; <groupId>;org.apache.maven.plugins</groupId>; <artifactId>;maven-surefire-plugin</artifactId>; <version>;3.0.0-M7</version>; <configuration>; <includes>; <include>;**/*ApiTest*.java</include>; <include>;**/*Test*.java</include>; <include>;**/*ItTest*.java</include>; <include>;**/*UnitTest*.java</include>; <include>;**/*Spec.java</include>; <include>;**/*SpecTest.java</include>; </includes>; </configuration>; </plugin>; <plugin>; <groupId>;org.codehaus.gmavenplus</groupId>; <artifactId>;gmavenplus-plugin</artifactId>; <version>;1.13.1</version>; <executions>; <execution>; <goals>; <goal>;addTestSources</goal>; <goal>;compile</goal>; <goal>;compileTests</goal>; </goals>; </execution>; </executions>; <configuration>; <targetBytecode>;17</targetBytecode>; <testSources>; <testSource>; <directory>;${project.basedir}/src/test</directory>; <includes>; <include>;**/*.groovy</include>; </includes>; </testSource>; </testSources>; </configuration>; </plugin>; </plugins>; </build>; </project>; </code> | I had the same problem. I created an ObjectMapper bean and added camel.dataformat.jackson.auto-discover-object-mapper=true to the application properties. <code>@Bean public ObjectMapper objectMapper() { return new ObjectMapper().registerModule(new JavaTimeModule()); } </code> ... in application.yaml... <code>camel: dataformat: jackson: auto-discover-object-mapper: true </code> The property flagged an error in IDEA but it still worked. |
apache-camel | How can I create duplicates of some Camel messages by some header condition? For example, I have a message with header <code>key=value1,value2,value3</code>, and I want to have three copies of the same messages with keys <code>key=value1</code>, <code>key=value2</code>, <code>key=value3</code>. I tried to find some components here https://camel.apache.org/components/3.20.x/, but haven't found any suitable example. | You are using the split component of camel, then it's working. <code>from(';input:queue';) .split().method(SplitClass.class, ';splitHeaders';) .to(';output:queue';);public class SplitClass{ public List<String>; splitHeaders(@Header(';key';) String key) { List<String>; values = Arrays.asList(key.split(';,';)); List<String>; messages = new ArrayList<>;(); for (String value : values) { String message = ExchangeHelper.convertToType(exchange, String.class, exchange.getIn()); exchange.getIn().setHeader(';key';, value); messages.add(message); } return messages; } } </code> |
apache-camel | I am not finding any references on dotnet as a supported language for Camel. Though chatGPT says yes :). https://camel.apache.org/camel-k/next/languages/languages.html Is DotNet supported for handling Camelet sink and sources ? | There is no Apache Camel .Net project. Apache Camel is written in Java and runs on JVM. However you can use other languages with Camel such as JavaScript, Groovy, Kotlin, Python etc. But there is no .Net support from Apache Camel project. There could be integration frameworks written in .Net that resemble Apache Camel. |
apache-camel | I have created a custom processStrategy that is an extention of the GenericFileDeleteProcessStrategy: <code>@Component public class AlwaysDeleteProcessStrategy<T>; extends GenericFileDeleteProcessStrategy<T>; { private static final Logger LOGGER = LoggerFactory.getLogger(AlwaysDeleteProcessStrategy.class); @Override public void rollback(GenericFileOperations<T>; operations, GenericFileEndpoint<T>; endpoint, Exchange exchange, GenericFile<T>; file) throws Exception { LOGGER.info(';Deleting file despite exception';); super.commit(operations, endpoint, exchange, file); } } </code> When using this in an endpoint-dsl this works perfectly fine, but when I build the endpoint with a String it stops working: <code>//Works fine from(file(';src/test/resources/input';).advanced().processStrategy(new AlwaysDeleteProcessStrategy())) //Doesn't work from(';file://src/test/resources/input?processStrategy=#alwaysDeleteProcessStrategy';) </code> This is the exception that gets thrown when I try adding it to the String endpoint: <code>Caused by: org.apache.camel.NoSuchBeanException: No bean could be found in the registry for: alwaysDeleteProcessStrategy of type: org.apache.camel.component.file.GenericFileProcessStrategy at org.apache.camel.support.CamelContextHelper.mandatoryLookupAndConvert(CamelContextHelper.java:253) at org.apache.camel.support.EndpointHelper.resolveReferenceParameter(EndpointHelper.java:376) at org.apache.camel.support.EndpointHelper.resolveReferenceParameter(EndpointHelper.java:336) at org.apache.camel.support.component.PropertyConfigurerSupport.property(PropertyConfigurerSupport.java:55) at org.apache.camel.component.file.FileEndpointConfigurer.configure(FileEndpointConfigurer.java:131) at org.apache.camel.support.PropertyBindingSupport.setSimplePropertyViaConfigurer(PropertyBindingSupport.java:733) ... 43 common frames omitted </code> I have also tried manually creating the bean incase the @Component annotation wasn't enough, but that made no difference. How can I make both situations work? | Did you add an instance of AlwaysDeleteProcessStrategy to the registry? <code>getContext().getRegistry().bind(';alwaysDeleteProcessStrategy';, new AlwaysDeleteProcessStrategy()); </code> |
apache-camel | In a Spring Boot 2.7. Camel 3.20.x project written in Kotlin I have a REST endpoint that receives a JSON payload. I've added the Camel Jackson dependency to deal with JSON<->;POJO transformation: <code> <dependency>; <groupId>;org.apache.camel.springboot</groupId>; <artifactId>;camel-jackson-starter</artifactId>; <version>;${camel.version}</version>; </dependency>; </code> <code>data class Payment(val iban: String, val amount: Float) </code> <code> rest(';/payments';) .post(';/';) .to(';direct:processPayment';) from(';direct:processPayment';) .log(';Body \${body}';) .log(';Body \${body.getClass()}';) </code> These are the logs of the route: <code>Body {';payment';:{';iban';:';ABCD';,';amount';:150.0}} Body class org.apache.camel.converter.stream.InputStreamCache </code> As you can see the body is correctly displayed as String, however, the type is <code>InputStreamCache</code> instead of my Payment DTO. I updated the route to unmarshall the body to the Payment DTO: <code> from(';direct:processPayment';) .unmarshal().json(JsonLibrary.Jackson, Payment::class.java) .log(';Body \${body}';) .log(';Body \${body.getClass()}';) </code> This fails with: <code>com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `xxx.Payment` (no Creators, like default constructor, exist): cannot deserialize from Object value (no delegate- or property-based Creator) </code> Why isn't the conversion working? | The encountered error has nothing to see with Camel nor Spring, but is directly related to Jackson. As the error message indicates it, the reason is that the <code>Payment</code> pojo does not satisfy the requirement of having a default (parameterless) constructor. |
apache-camel | I'm using camel version 3.14.5 and I'm wondering if there's a way (I can't see one) where I can use a custom<code>BeanPropertyRowMapper</code> when using a <code>SqlEndpoint</code>. I'm using the sql endpoint like this in a route: <code>.to(';mySqlComponent:classpath:my_sql.sql?outputType=StreamList&;outputClass=com.my.project.MyCustomMappedPojo';) </code> Looking at the code it does look like a BeanPropertyRowMapper is hardcoded in the classDefaultSqlEndpoint<code> @SuppressWarnings(';unchecked';) public ResultSetIterator queryForStreamList(Connection connection, Statement statement, ResultSet rs) throws SQLException { if (outputClass == null) { RowMapper rowMapper = new ColumnMapRowMapper(); return new ResultSetIterator(connection, statement, rs, rowMapper); } else { Class<?>; outputClzz = getCamelContext().getClassResolver().resolveClass(outputClass); RowMapper rowMapper = new BeanPropertyRowMapper(outputClzz); return new ResultSetIterator(connection, statement, rs, rowMapper); } } </code> So all I'm after is a way to make use of a Custom RowMapper. The most obvious way would be to pass it to the SqlEndpoint directly, but there's no such property. Alternatively I thought about using a custom <code>SqlEndpoint</code> whilst wiring a <code>SqlComponent</code> in Spring, but I see that the <code>SqlComponent</code> uses a <code>SqlEndpoint</code> hardcoded (i.e.: doesn't allow me to inject a custom Endpoint) which in turns uses the hardcoded BeanPropertyRowMapper as per the code sample above. | Do you really have a custom <code>org.springframework.jdbc.core.BeanPropertyRowMapper</code> ? Its not possible to configure currently in camel-sql. You are welcome to create a JIRA and work on a PR to add support for this. |
apache-camel | When using the jbang cli <code>jbang RestCamelJbang.java</code> below code expose the REST endpoint successfully. Able to access the endpint at 8080 <code>///usr/bin/env jbang ';$0'; ';$0'; : exit $? // camel-k: language=java//DEPS org.apache.camel:camel-bom:3.20.1@pom //DEPS org.apache.camel:camel-core //DEPS org.apache.camel:camel-main //DEPS org.apache.camel:camel-jetty //DEPS org.slf4j:slf4j-nop:2.0.6 //DEPS org.slf4j:slf4j-api:2.0.6import org.apache.camel.*; import org.apache.camel.builder.*; import org.apache.camel.main.*; import org.apache.camel.spi.*;import static java.lang.System.*;public class RestCamelJbang{ public static void main(String ... args) throws Exception{ out.println(';Starting camel route...';); setProperty(';org.slf4j.simpleLogger.logFile';, ';System.out';); Main main = new Main(); main.configure().addRoutesBuilder(new RouteBuilder(){ public void configure() throws Exception{ out.println(';Camel configuration started...';); from(';jetty:http://localhost:8080/hello';) .transform().simple(';First Message of Camel';); } }); main.run(); } } </code>When using the Jbang Camel app <code>camel run FirstCamel.java</code> command with the jetty component, there are NO exception in the console but states 0 route started. The endpoint <code>http://localhost:8080/hello</code> there is no response.Am I missing something here, do we need some sort of server to run it? <code>///usr/bin/env jbang ';$0'; ';$0'; : exit $? // camel-k: language=javaimport org.apache.camel.*; import org.apache.camel.builder.*; import org.apache.camel.main.*; import org.apache.camel.spi.*;public class FirstCamel extends RouteBuilder{ @Override public void configure() throws Exception{ from(';jetty:http://localhost:8081/hello';) .transform().simple(';First Message of Camel';) .log(';${body}';); } } </code>Console ouput<code>2023-02-13 21:10:22.056 INFO 6884 --- [ main] org.apache.camel.main.MainSupport : Apache Camel (JBang) 3.20.1 is starting 2023-02-13 21:10:22.511 INFO 6884 --- [ main] org.apache.camel.main.MainSupport : Using Java 17.0.1 with PID 6884. Started by thirumurthi in C:\thiru\learn\camel\camel_lessons\lesson 2023-02-13 21:10:22.543 INFO 6884 --- [ main] he.camel.cli.connector.LocalCliConnector : Camel CLI enabled (local) 2023-02-13 21:10:24.180 INFO 6884 --- [ main] .main.download.MavenDependencyDownloader : Downloaded: org.apache.camel:camel-rest:3.20.1 (took: 1s55ms) 2023-02-13 21:10:24.471 INFO 6884 --- [ main] e.camel.impl.engine.AbstractCamelContext : Apache Camel 3.20.1 (CamelJBang) is starting 2023-02-13 21:10:24.893 INFO 6884 --- [ main] e.camel.impl.engine.AbstractCamelContext : Routes startup (started:0) 2023-02-13 21:10:24.893 INFO 6884 --- [ main] e.camel.impl.engine.AbstractCamelContext : Apache Camel 3.20.1 (CamelJBang) started in 950ms (build:289ms init:241ms start:420ms JVM-uptime:5s) </code>Below code works when I use the rest DSL with <code>camel run WelcomeRoute.java</code>.<code>import org.apache.camel.*; import org.apache.camel.builder.RouteBuilder;public class WelcomeRoute extends RouteBuilder { @Override public void configure() throws Exception { restConfiguration().bindingMode(';auto';); rest(';/api';) .get(';/demo/{info}';) .to(';log:info';) .to(';direct:msg';); from(';direct:msg';) .transform().simple(';msg received - ${header.info}';); } } </code> | When using Camel JBang <code>run</code> then its for running Camel routes (not Java Main classes). So the first code is not valid. Camel JBang detects Java source that are <code>RouteBuilder</code> so your class should extend this class, like the 2nd and 3rd code examples. There has been some troubles with Java 11 and older Camel releases to use .java source with java <code>imports</code>. That works with Java 17, so upgrade if you can. Otherwise you may need to use FQN classnames instead of <code>imports</code>. |
apache-camel | In my Springboot Camel microservice I integrate camel mapstruct with this dependency: <code><camel.version>;3.20.1</camel.version>; <mapstruct.version>;1.5.3.Final</mapstruct.version>;<dependency>; <groupId>;org.springframework.boot</groupId>; <artifactId>;spring-boot-starter</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-mapstruct-starter</artifactId>; <version>;${camel.version}</version>; </dependency>; <dependency>; <groupId>;org.mapstruct</groupId>; <artifactId>;mapstruct</artifactId>; <version>;${mapstruct.version}</version>; </dependency>; <dependency>; <groupId>;org.mapstruct</groupId>; <artifactId>;mapstruct-processor</artifactId>; <version>;${mapstruct.version}</version>; <scope>;provided</scope>; </dependency>; </code> I also have a mapper like this: <code>@Mapper(componentModel = ';spring';) public interface CamelTestMapper { @BeanMapping(nullValueMappingStrategy = NullValueMappingStrategy.RETURN_DEFAULT) CamelTestDto mapCamelTestEntity(CamelTestEntity camelTestEntity);} </code> and a route like this: <code>from(';direct:get-by-id';) .routeId(';db-get-by-id-route';) .transacted() .process(camelTestSampleDatabaseProcessor) .log(LoggingLevel.INFO, ';Retrieved entity from db with name: ${body.name}';) .to(';mapstruct:org.example.model.dto.CamelTestDto';) .log(LoggingLevel.INFO, ';Mapped new Dto: ${body}';); </code> I can't understand why in this way it works, and when I use <code>.convertBodyTo(CamelTestDto.class) </code> it throw this exception: <code>org.apache.camel.InvalidPayloadException: No body available of type: org.example.model.dto.CamelTestDto but has type: org.example.model.entity.CamelTestEntity on: Message[4939598FD4DFE7C-0000000000000103]. Caused by: No type converter available to convert from type: org.example.model.entity.CamelTestEntity to the required type: org.example.model.dto.CamelTestDto. Exchange[4939598FD4DFE7C-0000000000000103]. Caused by: [org.apache.camel.NoTypeConversionAvailableException - No type converter available to convert from type: org.example.model.entity.CamelTestEntity to the required type: org.example.model.dto.CamelTestDto] </code> Obviously I already set the application .yml in this way: <code>camel: component: mapstruct: mapper-package-name: org.example.mapper </code> Does anyone know how to solve it? Can you give to me some examples of how to use this integrations? Also with conversion with List please. | There was a recent bug in camel-mapstruct-starter for SB that it did not auto-configure itself correctly, when you did not use mapstruct as a component in the routes. This will be fixed in upcoming Camel releases: https://issues.apache.org/jira/browse/CAMEL-19181 |
apache-camel | I'm learning about Apache Camel routes in Spring Boot projects and I have a project that does extension from some endpoints. The endpoints are not in this project, only the extension is done here. The extension is done using @Consume from org.apache.camel in this way: <code>@Consume(uri = ';direct:products.create.validate.interceptor';) public void executeCreate(RequestWrapper<Product>; productWrapper) { ... } </code> I try to understand how this direct:products.create.validate.interceptor is mapped to an endpoint from another service. Can somebody explain me how this @Consume annotation does the mapping? Or another example is this: <code>@Consume(uri = ';direct:listAccountsPostHook';) public void executeCreate(RequestWrapper<Account>; accountWrapper) { ... } </code> Where should I look to understand how they are mapped? In the controller of the other service? I can't find any example with @Consume. Thank you! | The <code>@Consume</code> annotation in Apache Camel is used to subscribe to a Camel endpoint and consume messages from it. The endpoint can be either a direct endpoint or any other type of endpoint such as a JMS queue or a REST endpoint, depending on your use case. The endpoint URI, which is specified in the uri attribute of the <code>@Consume</code> annotation, determines where the messages are consumed from. In your example, <code>direct:products.create.validate.interceptor</code> and <code>direct:listAccountsPostHook</code> are both direct endpoints. In Apache Camel, direct endpoints are in-memory endpoints that allow you to send messages directly to another endpoint in the same JVM. The mapping between the endpoint and the method that consumes the messages is done by Camel's routing engine. More on Camel Direct endpoints you can read here. To understand how the messages are being consumed, you should look at the Camel routes that are defined in your project. In a Spring Boot project, you can define your Camel routes in a <code>RouteBuilder</code> class. This is where you would specify the mapping between the direct endpoint and the method that will consume the messages. For example, if you have a <code>RouteBuilder</code> class that looks like this: <code>public class MyRouteBuilder extends RouteBuilder { @Override public void configure() { from(';direct:products.create.validate.interceptor';) .to(';bean:myBean?method=executeCreate';); } } </code> In this example, the direct endpoint <code>direct:products.create.validate.interceptor</code> is mapped to the <code>executeCreate</code> method in the <code>myBean</code> bean. The <code>?method=executeCreate</code> part of the to URI tells Camel to call the executeCreate method on the myBean bean when a message is received at the endpoint. So, in short, you should look for the Camel routes in your project that define the mapping between the endpoint and the method that consumes the messages. |
apache-camel | I cannot access caught exception in <code>onWhen(predicate)</code> after <code>doCatch()</code>, but I can see it in the processor in <code>doCatch()</code>. This is inconvenient when I want to define a finer-grained predicate in <code>onWhen()</code>. <code>doCatch(ProcessingException.class).onWhen(predicate) // <<< here I cannot see exception .process(MyProcessor.class) // <<< here I see exception ... </code> <code>exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class)</code> returns null in the predicate. I see <code>exchange.getAllProperties()</code> does not contain the key. Any idea? Is it by design? Now I cannot decide enter catch processor or not depending on exception message. | I was struggling with this until I read the method's documentation:Sets an additional predicate that should be true before the onException is triggered. To be used for fine grained controlling whether a thrown exception should be intercepted by this exception typeor not.That may explain why you are able to see the exception details in the processor and not in the ';onWhen'; clause. Hope it helps. Regards. |
apache-camel | I have this Camel Rest Route: <code>import org.apache.camel.builder.RouteBuilder; import org.apache.camel.main.Main; import org.apache.camel.model.rest.RestBindingMode; import spark.Spark;public class MainCamel {public static void main(final String[] args) throws Exception { final Main camelMain = new Main(); camelMain.configure().addRoutesBuilder(new RouteBuilder() { @Override public void configure() throws Exception { this.getContext().getRegistry().bind(';healthcheck';, CheckUtil.class); this.restConfiguration() .bindingMode(RestBindingMode.auto) .component(';netty-http';) .host(';localhost';) .port(11010); this.rest(';/healthcheck';) .get() .description(';Healthcheck for docker';) .outType(Integer.class) .to(';bean:healthcheck?method=healthCheck';); } }); // spark Spark.port(11011); Spark.get(';/hello';, (req, res) ->; ';Hello World';); System.out.println(';ready';); camelMain.run(args); }public static class CheckUtil { public Integer healthCheck() { return 0; } } </code> } I also created a second REST server with Spark. The Camel route does NOT work if the code is executed in a Docker container. <code>Exception: org.apache.http.NoHttpResponseException: localhost:11010 failed to respond</code> The Spark server works fine. However when executing the code directly in IntelliJ both REST Servers work. Of course both ports are exposed in the container. | You are binding the Netty HTTP server to <code>localhost</code>. Meaning that it will not be able to serve requests that originate from outside of the container. Change <code>.host(';localhost';)</code> to <code>.host(';0.0.0.0';)</code> so that the sever listens on all available network interfaces. |
apache-camel | How to get HttpRequest and HttpReponse from exchange after HttpCopoment? Any hints or ideas are more than welcome Below is the code example <code> from(';direct:restendpoint';).routeId(';direct_restendpoint';) .to(';https://<URL_SERVICE>;';) .process(exchange ->; { String responseCode = exchange.getIn().getHeader(';CamelHttpResponseCode';).toString(); //How to get httpRequest and httpResponse here? }) </code> | This is explained in this JIRA: https://issues.apache.org/jira/browse/CAMEL-19077 HttpServletRequest/Response are only for servlet components, eg <code>camel-servet</code> or <code>camel-jetty</code> and not for HTTP clients. So you cannot get hold of servlet with a HTTP client. |
apache-camel | I tried to instantiate multiple routes from the same camel route template which resulted in a misbehaviour in the evaluation of several simple expressions. I am using camel 3.20.1 in a spring boot application and i am having problems creating routes from the following route template. I am using constants for the specific template parameter keys - these are also used in several expressions (simple expression etc). At one point in the route template / instantiation of a route based on the following route template, especially at the aggregate / completionSize definition, an expression (templateParameterExpression(RouteTemplateConstants.TEMPLATE_PARAMETER_FILE_CORRELATION_COMPLETION_SIZE)) evaluates to a value specified for a second route which is using this template. Route template: <code> @Override public void configure() throws Exception { routeTemplate(';generic-data-file-based-template';) .templateParameter(RouteTemplateConstants.TEMPLATE_PARAMETER_FROM_URI) .templateParameter(RouteTemplateConstants.TEMPLATE_PARAMETER_TO_URI) .templateParameter(RouteTemplateConstants.TEMPLATE_PARAMETER_GENERIC_DATA_TYPE) .templateParameter(RouteTemplateConstants.TEMPLATE_PARAMETER_FILENAME_FILTER_REGEX) .templateParameter(RouteTemplateConstants.TEMPLATE_PARAMETER_FILE_CORRELATION_REGEX) .from(templateParameterString(RouteTemplateConstants.TEMPLATE_PARAMETER_FROM_URI)) .setHeader(RouteTemplateConstants.TEMPLATE_PARAMETER_FILENAME_FILTER_REGEX, templateParameterExpression(RouteTemplateConstants.TEMPLATE_PARAMETER_FILENAME_FILTER_REGEX)) .setHeader(RouteTemplateConstants.TEMPLATE_PARAMETER_GENERIC_DATA_TYPE, templateParameterExpression(RouteTemplateConstants.TEMPLATE_PARAMETER_GENERIC_DATA_TYPE)) .setHeader(RouteTemplateConstants.TEMPLATE_PARAMETER_REFERENCE_DATE_REGEX, templateParameterExpression(RouteTemplateConstants.TEMPLATE_PARAMETER_REFERENCE_DATE_REGEX)) .setHeader(RouteTemplateConstants.TEMPLATE_PARAMETER_FILE_CORRELATION_REGEX, templateParameterExpression(RouteTemplateConstants.TEMPLATE_PARAMETER_FILE_CORRELATION_REGEX)) .setHeader(RouteTemplateConstants.TEMPLATE_PARAMETER_FILE_CORRELATION_COMPLETION_SIZE, templateParameterExpression(RouteTemplateConstants.TEMPLATE_PARAMETER_FILE_CORRELATION_COMPLETION_SIZE)) .filter(FILENAME_FILTER_PREDICATE) .aggregate(templateParameterExpression(RouteTemplateConstants.TEMPLATE_PARAMETER_FILE_CORRELATION_REGEX), new GroupedMessageAggregationStrategy()) .completionSize(templateParameterExpression(RouteTemplateConstants.TEMPLATE_PARAMETER_FILE_CORRELATION_COMPLETION_SIZE)) .log(';correlation completed by ${header.'; + Exchange.AGGREGATED_COMPLETED_BY + ';} with ${header.'; + Exchange.AGGREGATED_SIZE + ';} files';) .setHeader(INTERNAL_HEADER_REFERENCE_DATE, headerSubstring2(header(RouteTemplateConstants.TEMPLATE_PARAMETER_FILE_CORRELATION_REGEX), Exchange.FILE_NAME)) .to(templateParameterString(RouteTemplateConstants.TEMPLATE_PARAMETER_TO_URI)); }private Expression templateParameterExpression(String value) { return simple(';{{';+value+';}}';); }</code> Route I based on this template: <code> public void configure() throws Exception { templatedRoute(';generic-data-file-based-template';) .parameter(RouteTemplateConstants.TEMPLATE_PARAMETER_FROM_URI, ';sftp:localhost:22/test/application/cashflows?username=tester&;password=password';) .parameter(RouteTemplateConstants.TEMPLATE_PARAMETER_TO_URI, ';mock:cashflow-watch-mock';) .parameter(RouteTemplateConstants.TEMPLATE_PARAMETER_GENERIC_DATA_TYPE, ';CASHFLOW';) .parameter(RouteTemplateConstants.TEMPLATE_PARAMETER_FILENAME_FILTER_REGEX, ';[0-9]{8}(Flow_tot|Head_tot|IntPeriod_tot){1}.csv';) .parameter(RouteTemplateConstants.TEMPLATE_PARAMETER_FILE_CORRELATION_REGEX, ';[0-9]{8}';) .parameter(RouteTemplateConstants.TEMPLATE_PARAMETER_REFERENCE_DATE_REGEX, ';[0-9]{8}';) .parameter(RouteTemplateConstants.TEMPLATE_PARAMETER_FILE_CORRELATION_COMPLETION_SIZE, ';3';) .routeId(';file-watch-1';); }</code> Route II based on this template: <code> public void configure() throws Exception { templatedRoute(';generic-data-file-based-template';) .parameter(RouteTemplateConstants.TEMPLATE_PARAMETER_FROM_URI, ';sftp:localhost:22/test/application/bookvalues?username=tester&;password=password';) .parameter(RouteTemplateConstants.TEMPLATE_PARAMETER_TO_URI, ';mock:bookvalue-watch-mock';) .parameter(RouteTemplateConstants.TEMPLATE_PARAMETER_GENERIC_DATA_TYPE, ';BOOKVALUE';) .parameter(RouteTemplateConstants.TEMPLATE_PARAMETER_FILENAME_FILTER_REGEX, ';BW_BVA_[0-9]{8}.csv';) .parameter(RouteTemplateConstants.TEMPLATE_PARAMETER_FILE_CORRELATION_REGEX, ';BW_BVA_[0-9]{8}.csv';) .parameter(RouteTemplateConstants.TEMPLATE_PARAMETER_REFERENCE_DATE_REGEX, ';[0-9]{8}';) .parameter(RouteTemplateConstants.TEMPLATE_PARAMETER_FILE_CORRELATION_COMPLETION_SIZE, ';1';) .routeId(';file-watch-2';); }</code> It depends on the order in which these two routes are added to the camel context, to which value the expression templateParameterExpression(RouteTemplateConstants.TEMPLATE_PARAMETER_FILE_CORRELATION_COMPLETION_SIZE) evaluates for both routes. For example, if file-watch-1 was added first, then the expression in file-watch-2 will evaluate to the value 3 instead of 1. I debugged my code and saw that camel uses an expressions cache which returns the upper value for the second route - but only for the expression used in the completionSize definition. Other expressions have the right value. I already took a look on the official documentation which isn't exactly stating that this is common behaviour for the way i specified the templateParameter. So, am i doing something wrong? Is this an error in the framework? Common behaviour? Should i use templateBeans instead? Thanks in advance! | I investigated my problem further and found out that the two routes i am instantiating are using the same instance of AggregationDefinition which evaluates the simple expression in completionSize always to the same value once set (expressions cache !?). I fixed this behaviour using another signature of the method completionSize in the template itself (completionSize(String completionSize)) and used the property method to specify the size: <code> @Override public void configure() throws Exception { routeTemplate(';generic-data-file-based-template';) .templateParameter(RouteTemplateConstants.TEMPLATE_PARAMETER_FROM_URI) .templateParameter(RouteTemplateConstants.TEMPLATE_PARAMETER_TO_URI) .templateParameter(RouteTemplateConstants.TEMPLATE_PARAMETER_GENERIC_DATA_TYPE) .templateParameter(RouteTemplateConstants.TEMPLATE_PARAMETER_FILENAME_FILTER_REGEX) .templateParameter(RouteTemplateConstants.TEMPLATE_PARAMETER_FILE_CORRELATION_REGEX) .from(property(RouteTemplateConstants.TEMPLATE_PARAMETER_FROM_URI)) .setHeader(RouteTemplateConstants.TEMPLATE_PARAMETER_FILENAME_FILTER_REGEX, templateParameterExpression(RouteTemplateConstants.TEMPLATE_PARAMETER_FILENAME_FILTER_REGEX)) .setHeader(RouteTemplateConstants.TEMPLATE_PARAMETER_GENERIC_DATA_TYPE, templateParameterExpression(RouteTemplateConstants.TEMPLATE_PARAMETER_GENERIC_DATA_TYPE)) .setHeader(RouteTemplateConstants.TEMPLATE_PARAMETER_REFERENCE_DATE_REGEX, templateParameterExpression(RouteTemplateConstants.TEMPLATE_PARAMETER_REFERENCE_DATE_REGEX)) .setHeader(RouteTemplateConstants.TEMPLATE_PARAMETER_FILE_CORRELATION_REGEX, templateParameterExpression(RouteTemplateConstants.TEMPLATE_PARAMETER_FILE_CORRELATION_REGEX)) .setHeader(RouteTemplateConstants.TEMPLATE_PARAMETER_FILE_CORRELATION_COMPLETION_SIZE, templateParameterExpression(RouteTemplateConstants.TEMPLATE_PARAMETER_FILE_CORRELATION_COMPLETION_SIZE)) .filter(FILENAME_FILTER_PREDICATE) .aggregate(simple(property(RouteTemplateConstants.TEMPLATE_PARAMETER_FILE_CORRELATION_REGEX)), new GroupedMessageAggregationStrategy()) .completionSize(property(RouteTemplateConstants.TEMPLATE_PARAMETER_FILE_CORRELATION_COMPLETION_SIZE)) .log(';correlation completed by ${header.'; + Exchange.AGGREGATED_COMPLETED_BY + ';} with ${header.'; + Exchange.AGGREGATED_SIZE + ';} files';) .setHeader(INTERNAL_HEADER_REFERENCE_DATE, headerSubstring2(header(RouteTemplateConstants.TEMPLATE_PARAMETER_FILE_CORRELATION_REGEX), Exchange.FILE_NAME)) .to(property(RouteTemplateConstants.TEMPLATE_PARAMETER_TO_URI)); } </code> Now my code works as expected. |
apache-camel | I'd like to ask if there is some way to skip rest of the split route and jump directly to aggregator part, when in the exception handler I mark the split route to continue. I have a route like this:receive a message fetch config for 3 endpoints merge config and message as a tuple for each endpoint, and create a list of it <code>.split()</code>, and in the split route I convert message according to config for each endpoint(<code>s1</code>), fetch oauth token(<code>s2</code>), send to final endpoint with token(<code>s3</code>), collect response for each endpoint(<code>s4</code>), aggregate(split aggregator; splitting ends here, let's call it <code>sa</code>) return as a whole one result stopYou can see, in the split route there are 4 steps(s1-s4); if any of these step fails I want to jump to aggregation(<code>sa</code>). For example, it does not make sense to continue the split route, if s1 or s2 fails. I define an <code>onException()</code> clause to handle the exception and mark it to continue(<code>continued(true)</code>),because anyway I want to reach aggregator. Also, if I mark <code>continue(false)</code>, not only split route, but the whole route(meaning the main route even before splitting) will be rolled back. I want to decide rollback after getting all the causes/exceptions in each split branch. I have a workaround for a simple case, which is, in exception handler for errors in s2, I add a property in the exchange <code>oauth_failed</code> to be <code>true</code>, and add a condition check <code>choice().when()</code> after s2; if this prop is null, then go to <code>s3</code> (continue sending). Solely for this purpose I must isolated <code>s3</code> as a separate route(<code>direct:s3</code>). <code>.bean(S2Bean.class) .choice() .when(simple(';${exchangeProperty.oauth_failed} == null';)) // null = continue the flow .to(';direct:s3';) .endChoice() // otherwise, it will skip s3 and s4, and jump to aggregator directly .end() </code> But, what can I do if s1 throws exception? Do I need to isolate s2 as a direct endpoint too? Then each step in the pipeline should be a separate endpoint. I don't like that. | Find a solution: use <code>doTry</code> and <code>doCatch</code> in split route and don't <code>.stop()</code>. <code>from(';direct:split';) .doTry() .bean(S1Bean.class) .bean(S2Bean.class) .bean(S3Bean.class) .bean(S4Bean.class) .endDoTry() .doCatch(javax.ws.rs.ProcessingException.class) // oauth timeout .log(LoggingLevel.ERROR, ';Time out, never retry, just aggregate';) .bean(MyGenericExceptionHandler.class) .doCatch(Exception.class) .log(LoggingLevel.ERROR, ';Other exceptions, mark as failed, aggregate';) .bean(MyGenericExceptionHandler.class) .end(); </code> And in the <code>MyGenericExceptionHandler</code>, <code>exchange.getIn().setBody(xxx)</code> to set body to the expected type which my aggregator needs. The exception is in <code>exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class)</code>, response code is null. (I create a dto to contain both status code and/or exception, so that either success or failure, I aggregate with same class) Don't call <code>stop()</code>. |
apache-camel | I am beginning a new project with Quarkus and want to use MongoDB as our datastore. We want to upload/dowload large files (>; 100MB) via REST (multipart-form) and archive them in a MongoDB along with some metadata for later retrieval. I read that GridFS is perfect for this and was wondering if Quarkus supports it out of the box? All I can find is the Quarkus MongoDB Client documentation and MongoDB Panache documentation. But nothing specially saying GridFS support for large files. https://quarkus.io/guides/mongodb-panache https://quarkus.io/guides/mongodb I do see however links for 'Apache Camel Quarkus' that DOES has gridFS support. And apparently it uses the <code>Quarkus MongoDB</code> client underneath. https://camel.apache.org/camel-quarkus/2.15.x/reference/extensions/mongodb-gridfs.html I suppose I could use Quarkus-Camel and just call the component to do the work, but before I went that route I wanted to know if there was a pure Quarkus way. Any examples would be appreciated of either pure Quarkus/Panache or Apache Camel Quarkus integration. I want to go MongoDB route rather than storing on FileSystem/Database records because I don't want to worry about transactional issues and rollbacks if I can't write a file to the FS or write the meta to the DB. I want to just store everything in one location using the large file support of Mongo. Thanks! | Right now, there is no panache-repository support for gridFS. But you can access the underlying gridFS pretty straight forward: <code> @Inject public GridFSRepository( @ConfigProperty(name = ';quarkus.mongodb.database';) String databaseName, @ConfigProperty(name = ';gridfs.bucket';) String bucketName, MongoClient mongoClient) { MongoDatabase database = mongoClient.getDatabase(databaseName); gridFSBucket = GridFSBuckets.create(database, bucketName); } </code> |
apache-camel | A lot of unit tests failed when upgrading a Springboot application from Apache Camel 3.16.0 to 3.17.0 All the test that failed has the following annotation: <code>@SpringBootTest </code> All the tests that passed doesnt have @SpringBootTest annotation or has it with specific classes like: <code>@SpringBootTest(classes = {JacksonAutoConfiguration.class, CamelAutoConfiguration.class}) </code> I have following camel springboot dependencies <code>compile ';org.apache.camel.springboot:camel-spring-boot-dependencies:${camelVersion}'; compile ';org.apache.camel.springboot:camel-spring-boot-starter:${camelVersion}'; compile ';org.apache.camel.springboot:camel-core-starter:${camelVersion}'; </code> CamelContext is autowired in them <code>@Autowired CamelContext camelContext </code> I also added the following before using camelContext object, but I guess the issue is happening when Spring does autowire <code>context.setStreamCaching(false); </code> As per documentation: https://camel.apache.org/manual/camel-3x-upgrade-guide-3_17.html, StreamCahcing is enabled by default. So I disabled it using the following property in appication.properties file, but it didnt help. <code>camel.springboot.streamCachingEnabled=false </code> <code>Failed to load ApplicationContext java.lang.IllegalStateException: Failed to load ApplicationContext at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:132) at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:124) at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:190) at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:132) at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:248) at org.spockframework.spring.SpringTestContextManager.prepareTestInstance(SpringTestContextManager.java:56) at org.spockframework.spring.SpringInterceptor.interceptInitializerMethod(SpringInterceptor.java:46) at org.spockframework.runtime.extension.AbstractMethodInterceptor.intercept(AbstractMethodInterceptor.java:24) at org.spockframework.runtime.extension.MethodInvocation.proceed(MethodInvocation.java:101) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$prepare$1(NodeTestTask.java:111) at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at org.junit.platform.engine.support.hierarchical.NodeTestTask.prepare(NodeTestTask.java:111) at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:79) at java.base/java.util.ArrayList.forEach(ArrayList.java:1541) at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143) at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129) at org.spockframework.runtime.model.MethodInfo.invoke(MethodInfo.java:148) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127) at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126) at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84) at java.base/java.util.ArrayList.forEach(ArrayList.java:1541) at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143) at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129) at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127) at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126) at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84) at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32) at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57) at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51) at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:108) 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:96) at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:75) at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.processAllTestClasses(JUnitPlatformTestClassProcessor.java:99) at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.access$000(JUnitPlatformTestClassProcessor.java:79) at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor.stop(JUnitPlatformTestClassProcessor.java:75) at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.stop(SuiteTestClassProcessor.java:61) at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36) at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24) at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:33) at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:94) at org.gradle.api.internal.tasks.testing.worker.TestWorker.stop(TestWorker.java:133) at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36) at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24) at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:182) at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:164) at org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:414) at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64) at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48) at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:56) at java.base/java.lang.Thread.run(Thread.java:829) Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'handler1': Initialization of bean failed; nested exception is org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'org.apache.camel.processor.errorhandler.RedeliveryPolicy' to required type 'org.apache.camel.model.RedeliveryPolicyDefinition' for property 'redeliveryPolicy'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'org.apache.camel.processor.errorhandler.RedeliveryPolicy' to required type 'org.apache.camel.model.RedeliveryPolicyDefinition' for property 'redeliveryPolicy': no matching editors or conversion strategy found at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:628) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:953) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583) at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775) at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:448) at org.springframework.boot.SpringApplication.run(SpringApplication.java:339) at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:144) at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99) at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124) ... 62 more Caused by: org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'org.apache.camel.processor.errorhandler.RedeliveryPolicy' to required type 'org.apache.camel.model.RedeliveryPolicyDefinition' for property 'redeliveryPolicy'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'org.apache.camel.processor.errorhandler.RedeliveryPolicy' to required type 'org.apache.camel.model.RedeliveryPolicyDefinition' for property 'redeliveryPolicy': no matching editors or conversion strategy found at org.springframework.beans.AbstractNestablePropertyAccessor.convertIfNecessary(AbstractNestablePropertyAccessor.java:595) at org.springframework.beans.AbstractNestablePropertyAccessor.convertForProperty(AbstractNestablePropertyAccessor.java:609) at org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.java:219) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.convertForProperty(AbstractAutowireCapableBeanFactory.java:1756) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1712) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1452) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:619) ... 76 more Caused by: java.lang.IllegalStateException: Cannot convert value of type 'org.apache.camel.processor.errorhandler.RedeliveryPolicy' to required type 'org.apache.camel.model.RedeliveryPolicyDefinition' for property 'redeliveryPolicy': no matching editors or conversion strategy found at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:262) at org.springframework.beans.AbstractNestablePropertyAccessor.convertIfNecessary(AbstractNestablePropertyAccessor.java:590) ... 82 more</code> I appreciate any solution/suggestion. Thank you | I have the following configuration for DeadLetter channel, set the redelivery policy object. <code>deadLetterChannelBuilder = BeanDefinitionBuilder.genericBeanDefinition(DeadLetterChannelBuilder.class) .addPropertyValue(';redeliveryPolicy';, createRedeliveryPolicy(handlerProperties)) </code> I had the following method to set the required redelivery policy properties and return the RedeliveryPolicy object <code>private RedeliveryPolicy createRedeliveryPolicy(HandlerProperties handlerProperties) { RedeliveryPolicy redeliveryPolicy = new RedeliveryPolicy(); redeliveryPolicy.setMaximumRedeliveries(handlerProperties.getRedeliveryPolicy().getMaximumRedeliveries()); redeliveryPolicy.setRedeliveryDelay(handlerProperties.getRedeliveryPolicy().getRedeliveryDelay()); redeliveryPolicy.setUseCollisionAvoidance(handlerProperties.getRedeliveryPolicy().getUseCollisionAvoidance()); return redeliveryPolicy; } </code> The issue is resolved when I replaced RedeliveryPolicy with RedeliveryPolicyDefinition object as follows. <code> private RedeliveryPolicyDefinition createRedeliveryPolicy(HandlerProperties handlerProperties) { RedeliveryPolicyDefinition redeliveryPolicyDef = new RedeliveryPolicyDefinition() .maximumRedeliveries(handlerProperties.getRedeliveryPolicy().getMaximumRedeliveries()) .redeliveryDelay(handlerProperties.getRedeliveryPolicy().getRedeliveryDelay()); if(handlerProperties.getRedeliveryPolicy().getUseCollisionAvoidance()){ redeliveryPolicyDef.useCollisionAvoidance(); } return redeliveryPolicyDef; } </code> Somehow, RedeliveryPolicy object is replaced by RedeliveryPolicyDefinition when switching from Camel 3.16.0 to 3.17.0 version, but I couldnt find any mention of it in the Camel upgrade documentation. I hope it helps others facing this issue. |
apache-camel | I would use the Camel SAGA component available at https://camel.apache.org/components/3.20.x/eips/saga-eip.html I can easily understand that a ';compensation action'; is executed when the respective SAGA action fails, but it's not clear what is the meaning of ';failure';. I mean, on which basis does Camel mark a SAGA action as ';failed';? Is it considered failed when Camel throws an Exception? Thank you | Whenever Camel execution breaks for a specific route – it could be when a <code>RunTimeException</code> is thrown or you set an exception in exchange – the compensation will be triggered automatically. |
apache-camel | I have a Springboot application using Apache Camel AMQP component to comsume messages from a Solace Queue. To send a message to the Queue I use Postman and the Solace REST API. In order to differentiate the message type I add Content-Type to the header of the Http request in Postman. I used SDKPerf to check the message header consumed from solace and the message header is found under ';HTTP Content Type'; along with other headers. However, I can't seem to find a way to get this Content-Type from Camel Side. In the documentation it says <code>String header = exchange.getIn().getHeader(Exchange.CONTENT_TYPE, String.class); </code> However this always produces null. Any Ideas how to get the message properties in Camel? | EDIT: I think it's actually due to the fact that Camel is using QPid JMS, and there is no JMS API way of getting the Content Type, it's not in the spec. Even though AMQP 1.0 does support <code>content-type</code> as a property. But yeah, my suggestion of a custom property below is still probably the way I would go.https://camel.apache.org/components/3.20.x/amqp-component.html https://www.amqp.org/sites/amqp.org/files/amqp.pdf Edited for clarity &; corrections. TL/DR: use a custom user property header. The SMF Content Type header in the original (REST) message is passed through to the consumed AMQP message as a property <code>content-type</code>, however the JMS API spec does not expose this; there is no way in standard JMS to retrieve this value. It is, however, used by the broker to set the type of message (e.g. TextMessage). Check ';Content-Type Mapping to Solace Message Types'; in the Solace docs. Using Solace's SDKPerf AMQP JMS edition to dump the received message to console (note this uses QPid libraries): <code>./sdkperf_jmsamqp.sh -cip=amqp://localhost:5672 -stl=a/b/c -md -qcurl http://localhost:9000/TOPIC/a/b/c -d 'hello' -H 'Content-Type: text'^^^^^^^^^^^^^^^^^^ Start Message ^^^^^^^^^^^^^^^^^^^^^^^^^^^ JMSDeliveryMode: PERSISTENT JMSDestination: a/b/c JMSExpiration: 0 JMSPriority: 4 JMSTimestamp: 0 JMSRedelivered: false JMSCorrelationID: null JMSMessageID: null JMSReplyTo: null JMSType: null JMSProperties: {JMSXDeliveryCount:1;} Object Type: TextMessage Text: len=5 hello </code> The header does not get mapped through, but does get used to set the message type. If I remove that HTTP header, the received AMQP message is binary. But since other types of Content-Types also map to TextMessages (e.g. <code>application/json</code>, <code>application/xml</code>, etc.), the fact you're receiving a TextMessage is not enough to infer exactly what Content-Type you published your REST message with. For completeness, I used WireShark with an AMQP decoder, and you can see the header present on the received AMQP message: <code>Frame 3: 218 bytes on wire (1744 bits), 218 bytes captured (1744 bits) on interface \Device PF_Loopback, id 0 Null/Loopback Internet Protocol Version 4, Src: 127.0.0.1, Dst: 127.0.0.1 Transmission Control Protocol, Src Port: 5672, Dst Port: 60662, Seq: 2, Ack: 1, Len: 174 Advanced Message Queueing Protocol Length: 174 Doff: 2 Type: AMQP (0) Channel: 2 Performative: transfer (20) Arguments (5) Message-Header Durable: True Message-Annotations (map of 1 element) x-opt-jms-dest (byte): 1 Message-Properties To: a/b/c Content-Type: text <---------- Application-Properties (map of 1 element) AaronEncoding (str8-utf8): CustomText AMQP-Value (str32-utf8): hello </code> So my suggestion is this: Set an additional custom header, a User Property, which will get passed through to the AMQP message: <code>curl http://localhost:9000/TOPIC/a/b/c -d 'hello' -H 'Solace-User-Property-AaronEncoding: CustomText' -H 'Content-Type: text'JMSDestination: a/b/c JMSProperties: {AaronEncoding:CustomText;JMSXDeliveryCount:1;} Object Type: TextMessage Text: len=5 hello </code> My always-goto guide for Solace REST interactions: https://docs.solace.com/API/RESTMessagingPrtl/Solace-REST-Message-Encoding.htm Hope that helps! |
apache-camel | I am getting an input json string from a queue to my camel route, I need to unmarshal it to get a java object. After unmarshal I can't access my original message via Exchange object in process. If anyone faced the same issue and found solution, could you please answer this. I tried to unmarshal a json string to java object from incoming camel route. I wan to get access to original input message after unmarshal. | You can store the original body to an exchange property. Marshal by default replaces the message body but you can use exchange properties to store values for later use in the route. <code>from(';jms:queue:example';) .routeId(';receiveExampleMessage';) .convertBodyTo(String.class) .setProperty(';originalBody';, body()) .unmarshal(exampleDataFormat) // Usage: // Log original body .log(';original body ${exchangeProperty.originalBody}';) // Use exchange property with plain java .process(ex ->; { String originalBody = ex.getProperty(';originalBody';, String.class); }) // Set property value back to body .setBody().exchangeProperty(';originalBody';) ; </code> |
apache-camel | We have an XML configuration with Camel routes that includes this bean to configure spooling to disk for large messages: <code><streamCaching id=';diskSpoolConfig'; bufferSize=';16384'; spoolEnabled=';true'; spoolThreshold=';10000000';/>; </code> I'd like to configure Camel so streamCaching uses disk-spooling automatically, without having to specify this in the XML config. The Camel instance is started from a JAR with <code>Main main = new Main(); main.setApplicationContextUri(';file:routes.xml';); main.run(); </code> I found doc about <code>application.properties</code> and set <code>camel.main.streamCachingSpoolEnabled=true </code> but I'm unclear where this file needs to reside in the JAR so it gets read. I also tried with <code> Main main = new Main(); main.addMainListener(new MainListenerSupport() { public void beforeConfigure(BaseMainSupport main) { CamelContext context = main.getCamelContext(); context.setStreamCaching(true); context.getStreamCachingStrategy().setSpoolEnabled(true); context.getStreamCachingStrategy().setSpoolThreshold(10 * 1024 * 1024); } }); main.setApplicationContextUri(';file:routes.xml';); main.run(); </code> That was also ineffectual. Maybe it gets applied too late? Because for example when I set <code>context.getShutdownStrategy().setTimeout(5);</code> in <code>beforeConfigure()</code>, it has an effect. How can I start a Camel instance with disk-spooling enabled? | It is possible to create a context from multiple config files. This allows having presets inside the jar, but loading routes from outside: <code> ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( ';classpath:preset.xml';, ';file:routes.xml'; ); Main main = new Main(); main.setApplicationContext(context); main.run(); </code> |
apache-camel | I have about 10K messages in a CSV file. Each message has an associated timestamp for it. When the time is reached, I want the message delivered to an MQ. The timestamps are not uniformly spread. Is this possible with Apache Camel? | As far as I know Apache Camel by default has no consumer endpoint components that you could configure to trigger with specific messages at specified times. There is however a timer component that you can setup to trigger for example once a second. Then in the route you could use a processor to check if a list contains any messages that should be send at the given time and send them to the MQ. You could also trigger route from java code using a ProducerTemplate that you can create using the CamelContext. The list could be populated using your csv file and ordered by timestamp so you could use it like a stack and only check the first few entries instead of going through all 10K every second. The real problem here would be persistence i.e to figure out which of the messages listed on the csv have already been sent if the application closes before all 10K messages have been sent. |
apache-camel | Our system has configured to consume and send reply to the same queue, i.e., <code>JMSDestination</code> and <code>JMSReplyTo</code> are the same. I cannot change that right now. In my integration test, if I set <code>replyToSameDestinationAllowed=true</code>, Camel continues to consume the reply I sent to the queue, i.e., it ';captures'; the source and never stop and enters a loop. But, if I don't set it, Camel refuses to send the reply to the queue, saying this:JMSDestination and JMSReplyTo is the same, will skip sending a reply message to itselfThat causes problem for my integration test. I want to consume the message in a separate method and assert against it. How can I stop Camel from capturing this queue, i.e., consuming only once and ignore the rest? At the end of my route I call <code>stop()</code> to send reply automatically. When receiving the second message(the reply), I see this line:2023-01-10 14:37:22,186 DEBUG [org.apa.cam.com.jms.EndpointMessageListener]-{Camel (camel-1) thread #19 - JmsConsumer[my.queue]}-Received Message has JMSCorrelationID [ID:hostname-1673354133272-4:1:1:10:1]Can I use this to ignore the reply? Should I stop the route? Rollback? Or what should I do? | At last I filtered out messages based on the presence of <code>JMSCorrelationID</code> header. <code>from(';activemq:xxx';) .filter(simple(';${header.JMSCorrelationID} == null';)) // ignore reply .to(';direct:main';); </code> Even that I don't set it in my client side code, seems that Camel will use message id to set JMSCorrelationID when sending reply if the incoming message hasn't it. If incoming message already has JMSCorrelationID, Camel will not change it, and will copy that value to the reply.(I guess that if you manually set JMSCorrelationID in client side, Camel will stop setting it for you). So basically, message without JMSCorrelationID means it's new message which hasn't passed through my client application. I think only client side should set it, especially in my case where original message and replies are put into the same queue, where client needs a mean to filter out replies. Also, to stop Camel from ';capturing';, you need to make sure other two things:no concurrent consuming is happening the queue is empty before your test(no leftover from previous test), as all my tests are running in sequential order with <code>@Order</code>.For 1, set <code>replyTo(Max)ConcurrentConsumer</code> both to <code>1</code>, so that no concurrent consuming is happening; only one thread process this message. <code>ActiveMQComponent component = ActiveMQComponent.activeMQComponent(url); // we use request-reply mode so (max)ConcurrentConsumers are not taken into account; must set ';replyTo(Max)ConcurrentUsers';. // see https://camel.apache.org/components/3.20.x/activemq-component.html component.setReplyToConcurrentConsumers(1); component.setReplyToMaxConcurrentConsumers(1); // seems every pod will have max consumers </code> For 2, if last test rollbacked one message and put it back to the queue, I need to consume it before running the next test.At the very last, we separate the queues so even capturing is happening, it does not matter any more. |
apache-camel | I am configuring a route in Apache Camel that a single from() but multiple to() within it. My task is to create a file (works already) and either place it in some folder (works) or send it over TCP. How to define a route that does create the file and then either save it to disk or send it via TCP? I did try with a processor that creates the file, but i want to create the file only once, and then use camel to store or send. I hope somebody understands my words. Currently I am checking config properties and get into trouble when both endpoints (file and tcp) are enabled, i get a camel error. My goal is to use the camel architecture. <code>@Component public class HL7DirectImportRouteBuilder extends RouteBuilder {@Override public void configure() throws Exception { String gdtexportFolder = propertyService.getExportFolderGDT(); // inspect gdt file and create a hl7 message and send it if (propertyService.isExportMessageHl7Enabled()) { log.info(';export hl7 message (mllp) is enabled....';); throw new L7Exception(';not yet implemented';); } else { log.info(';export hl7 message (mllp) is disabled';); } // the customer wants to have the hl7 messages as file to be exchanged via a // shared network folder if (propertyService.isExportMessageFileEnabled()) { log.info(';export hl7 message file is enabled....';); from(';file:'; + padsyGdtExportFolder).log( ';File event: ${header.CamelFileEventType} occurred on file ${header.CamelFileName} at ${header.CamelFileLastModified}';) .process(new GDTFileProcessor()); } else { log.info(';export hl7 message file is disabled';); } if (propertyService.isExportPdfFileEnabled()) { log.info(';export pdf file is enabled....';); from(';file:'; + padsyGdtExportFolder).log( ';File event: ${header.CamelFileEventType} occurred on file ${header.CamelFileName} at ${header.CamelFileLastModified}';) .process(new CopyPDFFileProcessor(propertyService)); } else { log.info(';export pdf file is disabled';); } } </code> Edit: Added coded and remove confidential parts. I don't know how to chanage the route dynamically, according to the configuration of the application What i want to have in pseudocode: from(file:input).createMessage() // either place the file on disk or send it // or just copy the file | You can create a file using camels file producer endpoint eg. <code>to(file:path?filenName=example.txt)</code>. The file will have message body as its content. When you create the file can controlled with the consumer endpoint which could be a lot of things like timer, schedule, message queue event etc. Example using timer: <code>from(';timer:createFileTimer?repeatCount=1';) .routeId(';createFileTimer';) .setBody(constant(';Hello world';)) .to(';file:{{input.path}}?fileName=Hello.txt';) ; </code> This creates a file and saves it to the disk using path defined in input.path property of application.properties file used by spring boot. To move a file from one location to another you can simply use: <code>from(';file:{{input.path}}?delete=true';) .routeId(';moveFileToPath';) .to(';file:{{output.path}}';) ; </code> Note that technically this will read the file from input.path and write it to output.path. With <code>delete=true</code> this will delete the original file from input.path once done. To send file using TCP you can use FTP-component preferably with SFTP using strong RSA private key to authenticate. <code>from(';file:{{input.path}}?delete=true';) .routeId(';moveFileToPath';) .to(';sftp:{{sftp.host}}:{{sftp.port}}'; + ';?username={{sftp.username}}&;privateKeyFile={{sftp.keyfile.path}}';) ; </code> Camel-ftp maven dependency for Spring boot: <code><dependency>; <groupId>;org.apache.camel.springboot</groupId>; <artifactId>;camel-ftp-starter</artifactId>; <version>;x.x.x</version>; </dependency>; </code>or just copy the fileIf you're using file consumer endpoint (<code>from(';file:path';)</code> one key thing to understand is that it will consume the file after route has finished processing the file. This means that the file will by default be moved to hidden <code>.camel</code> folder in the input.path directory to prevent it from getting consumed again. This can lead to unexpected behavior if your goal is to copy a file. Using <code>noop=true</code> setting will prevent camel from moving or deleting the original file and use in-memory IdempotentRepository to keep track of consumed files to prevent them from being consumed again. To move processed files to custom location you can use <code>move=/some/path/for/processed/files/${file:name}</code> setting with the file consumer endpoint. |
apache-camel | I have a strange error: I can only run one Quarkus integration test in my <code>mvn verify</code> step. When I have two integration tests, the second one runs but immediately stops the application so nothing is happening and building hangs forever. The logs are different in two tests. For the 1st one, the logs are: <code>2023-01-04 15:43:04,560 INFO [org.apa.cam.imp.eng.AbstractCamelContext] (main) Routes startup (total:8 started:8) 2023-01-04 15:43:04,560 INFO [org.apa.cam.imp.eng.AbstractCamelContext] (main) Started route1 (activemq://queue:myqueue) 2023-01-04 15:43:04,560 INFO [org.apa.cam.imp.eng.AbstractCamelContext] (main) Started route2 (activemq://queue:myqueue.online) 2023-01-04 15:43:04,560 INFO [org.apa.cam.imp.eng.AbstractCamelContext] (main) Started main (direct://main) 2023-01-04 15:43:04,560 INFO [org.apa.cam.imp.eng.AbstractCamelContext] (main) Started individual-endpoint (direct://individual-endpoint) 2023-01-04 15:43:04,560 INFO [org.apa.cam.imp.eng.AbstractCamelContext] (main) Started send-and-retry (direct://send-and-retry) 2023-01-04 15:43:04,560 INFO [org.apa.cam.imp.eng.AbstractCamelContext] (main) Started mapping-response (direct://mapping-response) 2023-01-04 15:43:04,560 INFO [org.apa.cam.imp.eng.AbstractCamelContext] (main) Started reply-queue (direct://reply-queue) 2023-01-04 15:43:04,560 INFO [org.apa.cam.imp.eng.AbstractCamelContext] (main) Started route3 (direct://receive.ack.response) 2023-01-04 15:43:04,561 INFO [org.apa.cam.imp.eng.AbstractCamelContext] (main) Apache Camel 3.14.1 (camel-1) started in 593ms (build:0ms init:206ms start:387ms) 2023-01-04 15:43:04,562 DEBUG [org.apa.cam.imp.DefaultCamelContext] (main) start() took 594 millis 2023-01-04 15:43:04,567 DEBUG [org.apa.cam.mai.SimpleMainShutdownStrategy] (camel-main) Await shutdown to complete 2023-01-04 15:43:04,583 INFO [com.example.MyLogger] (main) Application is up 2023-01-04 15:43:04,583 INFO [com.example.MyLogger] (main) Application is up 2023-01-04 15:43:04,767 INFO [com.example.ShutdownController] (main) Setting pre shutdown sleep time to 10 seconds. 2023-01-04 15:43:04,767 INFO [io.quarkus] (main) my-app 0.0.1-SNAPSHOT on JVM (powered by Quarkus 2.7.5.Final) started in 3.124s. Listening on: http://0.0.0.0:8081 2023-01-04 15:43:04,768 INFO [io.quarkus] (main) Profile integration activated. ...(application runs normally; sends a message to in memory AMQ broker and Camel starts consuming from the queue) </code> And the 2nd test runs with these logs: <code>2023-01-04 15:43:59,606 INFO [org.apa.cam.imp.eng.AbstractCamelContext] (main) Routes startup (total:8 started:8) 2023-01-04 15:43:59,606 INFO [org.apa.cam.imp.eng.AbstractCamelContext] (main) Started route1 (activemq://queue:myqueue) 2023-01-04 15:43:59,606 INFO [org.apa.cam.imp.eng.AbstractCamelContext] (main) Started route2 (activemq://queue:myqueue.online) 2023-01-04 15:43:59,606 INFO [org.apa.cam.imp.eng.AbstractCamelContext] (main) Started main (direct://main) 2023-01-04 15:43:59,606 INFO [org.apa.cam.imp.eng.AbstractCamelContext] (main) Started individual-endpoint (direct://individual-endpoint) 2023-01-04 15:43:59,606 INFO [org.apa.cam.imp.eng.AbstractCamelContext] (main) Started send-and-retry (direct://send-and-retry) 2023-01-04 15:43:59,606 INFO [org.apa.cam.imp.eng.AbstractCamelContext] (main) Started mapping-response (direct://mapping-response) 2023-01-04 15:43:59,606 INFO [org.apa.cam.imp.eng.AbstractCamelContext] (main) Started reply-queue (direct://reply-queue) 2023-01-04 15:43:59,606 INFO [org.apa.cam.imp.eng.AbstractCamelContext] (main) Started route3 (direct://receive.ack.response) 2023-01-04 15:43:59,606 INFO [org.apa.cam.imp.eng.AbstractCamelContext] (main) Apache Camel 3.14.1 (camel-1) started in 452ms (build:0ms init:202ms start:250ms) 2023-01-04 15:43:59,607 DEBUG [org.apa.cam.imp.DefaultCamelContext] (main) start() took 453 millis 2023-01-04 15:43:59,631 INFO [com.example.MyLogger] (main) Application is up 2023-01-04 15:43:59,631 INFO [com.example.MyLogger] (main) Application is up 2023-01-04 15:43:59,617 DEBUG [org.apa.cam.mai.SimpleMainShutdownStrategy] (camel-main) Await shutdown to complete 2023-01-04 15:43:59,756 INFO [com.example.MyLogger] (main) Application is down 2023-01-04 15:43:59,756 INFO [com.example.MyLogger] (main) Application is down 2023-01-04 15:43:59,757 DEBUG [org.apa.cam.mai.SimpleMainShutdownStrategy] (main) Shutdown called 2023-01-04 15:43:59,757 DEBUG [org.apa.cam.mai.MainLifecycleStrategy] (main) CamelContext: camel-1 is stopping, triggering shutdown of the JVM. </code> The class <code>ShutdownController</code> listens for Quarkus shutdown event. <code>public class ShutdownController implements ShutdownListener { static final Logger LOGGER = LoggerFactory.getLogger(ShutdownController.class); private final long preShutdownSleep; public ShutdownController() { this.preShutdownSleep = (Long)ConfigProvider.getConfig().getOptionalValue(';com.example.shutdown-controller.pre-shutdown-sleep';, Long.class).orElse(ProfileManager.getLaunchMode() == LaunchMode.TEST ? 0L : 10L); LOGGER.info(';Setting pre shutdown sleep time to {} seconds.';, this.preShutdownSleep); } public ShutdownController(final int preShutdownSleep) { this.preShutdownSleep = (long)preShutdownSleep; } public void preShutdown(final ShutdownNotification notification) { LOGGER.info(';Pre shutdown received. Waiting fully functionally for {} seconds.';, this.preShutdownSleep); this.sleep(); LOGGER.info(';Continuing shutdown';); notification.done(); } private void sleep() { try { TimeUnit.SECONDS.sleep(this.preShutdownSleep); } catch (InterruptedException var2) { Thread.currentThread().interrupt(); } } } </code> Notice that Camel <code>SimpleMainShutdownStrategy</code> is called but in the second test, it does not wait for 10s. Why? I see this part in <code>SimpleMainShutdownStrategy</code> class: <code> @Override public boolean isRunAllowed() { return !completed.get(); } @Override public void addShutdownListener(ShutdownEventListener listener) { listeners.add(listener); } @Override public boolean shutdown() { if (completed.compareAndSet(false, true)) { LOG.debug(';Shutdown called';); latch.countDown(); for (ShutdownEventListener l : listeners) { try { LOG.trace(';ShutdownEventListener: {}';, l); l.onShutdown(); } catch (Throwable e) { // ignore as we must continue LOG.debug(';Error during ShutdownEventListener: {}. This exception is ignored.';, l, e); } } return true; } return false; } @Override public void await() throws InterruptedException { LOG.debug(';Await shutdown to complete';); latch.await(); } </code> So maybe it is because in the 1st case, <code>ShutdownController</code> has no instance so the constructor is called, and wait for 10s; but in the 2nd test, the instance is created so it does not call constructor. But why shutdown is called before the integration test runs? In both cases, Quarkus app starts before Camel. Both tests have similar structure: <code>@QuarkusIntegrationTest @QuarkusTestResource(value = WiremockResource.class, restrictToAnnotatedClass = true) @QuarkusTestResource(value = InMemoryAMQResource.class, restrictToAnnotatedClass = true) @TestProfile(MyIntegrationTestProfile.class) class MyOutboundMessageFormatIT extends MyIntegrationTestSupport { // the base class have a lot of fields like connetion, session, etc., which are used in @BeforeAll and @BeforeEach, etc. private static final Logger LOG = Logger.getLogger(MyOutboundMessageFormatIT.class); @InjectInMemoryAMQ protected BrokerService brokerService; @InjectWiremock protected WireMockServer wireMockServer; @Override WireMockServer getWiremock() { return wireMockServer; } @Override BrokerService getBroker() { return brokerService; } @BeforeAll protected static void start() throws Exception { LOG.debug(';Connecting to AMQ';); connectToAMQ(); } @AfterAll protected static void stop() throws Exception { LOG.debug(';Stopping AMQ';); session.close(); connection.stop(); connection.close(); } @BeforeEach protected void stub() { // global stubs stubAllFieldsOK(); stubOauthOK(); } @AfterEach protected void clearWiremockRequestsJournal() throws JMSException { // clear reply queue for next test consumeOnlineReply(); assertEmptyNonOnlineReply(); waitTillTokenExpires(); wireMockServer.resetRequests(); } ... </code> | At last, at the end of the log I see the cause: <code>2023-01-05 14:13:52,530 INFO [org.apa.cam.imp.eng.AbstractCamelContext] (main) Apache Camel 3.14.1 (camel-1) shutdown in 942ms (uptime:1s341ms) 2023-01-05 14:13:52,549 ERROR [io.qua.run.Application] (main) Port 8081 seems to be in use by another process. Quarkus may already be running or the port is used by another application. 2023-01-05 14:13:52,549 WARN [io.qua.run.Application] (main) Use 'netstat -anop | grep 8081' to identify the process occupying the port. 2023-01-05 14:13:52,549 WARN [io.qua.run.Application] (main) You can try to kill it with 'kill -9 <pid>;'. </code> So actually there cannot be 2 integration tests running; seems Quarkus application can only start once and will occupy the port.At last, I solved this by allowing duplicate message in my ActiveMQ in memory broker URL, and put all cases into one test. The original issue is that I was reusing the JSON message body between tests, and somehow ActiveMQ is ignoring the message, so no message entered the queue, so 2nd test was not running; also, changing stubbing out of Wiremock resource class seems impossible(at first I let Wiremock return 200, but in the last test I want to simulate 404 case), that's why I wanted to separate the tests. Now, I use an id to mark the stub I want to change, and in test I call <code>wiremockServer.editStub()</code> to change the stub, also I stop tests from running in parallel with <code>@TestMethodOrder(value = MethodOrderer.MethodName.class)</code>, then things start to work. So no dividing into 2 test classes is needed now. |
apache-camel | I am using Camel kamelets SFTP connect to process files in SFTP. When SFTP Source downloads the file from SFTP server we need to set the file length in the header. I have used set-header to set the values of file length and it is working except the data type, we are expecting the value of the header to be LONG but the simple expression returns the STRING data type. How can I return the LONG datatype from simple expression (or any other expressions),Is YAML DSL supports result type in simple expression? | You can use result-type However, then you need to use the verbose syntax to be able to set multiple options on the simple, something like: <code>- set-header: name: test simple: expression: ';${body}'; result-type: ';long'; </code> |
apache-camel | How can I set retry times dynamically depending on some property of the exchange? I want to send an event to destination and then process the response. If this event is <code>positive == true</code>, then I want to retry 3 times synchronously; if not, just don't retry. <code>from(RETRY_ONLINE_ENDPOINT) .routeId(RETRY_ONLINE_ROUTE_ID) .choice() .when(simple(';${exchangeProperty.positive} != true';)) .onException(HttpOperationFailedException.class) .log(LoggingLevel.INFO, ';Caught: '; + simple(';${exchangeProperty.CamelExceptionCaught}';) + ';, retried attempts: '; + simple(';${header.CamelRedeliveryCounter}';)) .maximumRedeliveries(3) .handled(true) .bean(PostRetryBean.class) .endChoice() .otherwise() .bean(PostRetryBean.class) .endChoice() .end(); </code> But I got exception <code>onException()</code> must be set at top level error. If I move <code>onException()</code> to top level, then compile does not pass. MaximizeRetryTimes cannot follow <code>when()</code>. So, how can I conditionally set maximum retry times? | Now I find it: use <code>onWhen()</code> to additionally check a condition to decide whether to use this <code>onException()</code> route. <code> /** * Sets an additional predicate that should be true before the onException is triggered. * <p/>; * To be used for fine grained controlling whether a thrown exception should be intercepted by this exception type * or not. * * @param predicate predicate that determines true or false * @return the builder */ public OnExceptionDefinition onWhen(@AsPredicate Predicate predicate) { setOnWhen(new WhenDefinition(predicate)); return this; } </code> So it becomes: <code>onException(HttpOperationFailedException.class).onWhen(simple(';${exchangeProperty.positive} == true';)) .maximumRedeliveries(3) .handled(true) .bean(RecoverableExceptionHandler.class) .to(REPLY_QUEUE_ENDPOINT);onException(HttpOperationFailedException.class).onWhen(simple(';${exchangeProperty.positive} == false';)) .handled(true) .bean(RecoverableExceptionHandler.class) .to(REPLY_QUEUE_ENDPOINT); </code> |
apache-camel | I have a Camel route which listens to an ActiveMQ queue, do some processing, and sends the result to a JMSReplyTo header queue as response. In previous version of the app, the destination needs to be explicitly set and it was sending the message with a <code>ProducerTemplate.sendBody()</code>; but I read in Camel doc that JMSReplyTo will be respected. So I want to try set no destination; however, seems that Camel expects the body to be the incoming message POJO. How can I send the modified body? https://camel.apache.org/components/3.19.x/eips/requestReply-eip.html has an illustration, where the request and reply have different color. I suppose they are different message, which makes sense; who wants the original message?In the last step of my route I did: <code>exchange.getIn().setBody(myString);</code>; also tried <code>exchange.getMessage().setBody(myString);</code> but I got error:Caused by: org.apache.camel.NoTypeConversionAvailableException: No type converter available to convert from type: java.lang.String to the required type: com.example.IncomingMessage with value {';failedEndpointsAndCauses';:{},';message';:';Message does not contain some ID field';,';status';:';ERROR';}which is exactly what I want to put into the response. <code>IncomingMessage</code> is the POJO coming in in the first place from ActiveMQ. Seems that Camel expects my outgoing response POJO to be the same type as incoming message. I cannot <code>getOut().setBody()</code>, as this is deprecated. I don't know why(maybe I know, that it's better just to <code>getIn()</code> and <code>setBody()</code>, because we need to copy everything from IN to OUT; but in the annotation of <code>@Deprecated</code> there are no explanations. ) Similar question: How exactly is JMSReplyTo handled by Apache Camel? When does camel implicitly utilises the destination? which suggests set <code>disableReplyTo</code>. But why Camel is not following the EIP of Request and Reply? I want a different body as response. Complete stacktrace(I am trying to return the POJO to <code>toD()</code> and <code>marshall()</code> but similar error, just now it's not string but POJO not matching the expected type): <code>2022-12-20 14:09:49,293 DEBUG [org.apa.cam.com.jms.DefaultJmsMessageListenerContainer] (Camel (camel-1) thread #6 - JmsConsumer[my.queue]) Initiating transaction rollback on application exception: org.apache.camel.CamelExecutionException: Exception occurred during execution on the exchange: Exchange[] at org.apache.camel.CamelExecutionException.wrapCamelExecutionException(CamelExecutionException.java:45) at org.apache.camel.support.builder.ExpressionBuilder$33.evaluate(ExpressionBuilder.java:1030) at org.apache.camel.support.ExpressionAdapter.evaluate(ExpressionAdapter.java:45) at org.apache.camel.component.bean.MethodInfo$ParameterExpression.evaluateParameterBinding(MethodInfo.java:738) at org.apache.camel.component.bean.MethodInfo$ParameterExpression.evaluateParameterExpressions(MethodInfo.java:624) at org.apache.camel.component.bean.MethodInfo$ParameterExpression.evaluate(MethodInfo.java:592) at org.apache.camel.component.bean.MethodInfo.initializeArguments(MethodInfo.java:263) at org.apache.camel.component.bean.MethodInfo.createMethodInvocation(MethodInfo.java:271) at org.apache.camel.component.bean.BeanInfo.createInvocation(BeanInfo.java:277) at org.apache.camel.component.bean.AbstractBeanProcessor.process(AbstractBeanProcessor.java:126) at org.apache.camel.component.bean.BeanProcessor.process(BeanProcessor.java:81) at org.apache.camel.processor.errorhandler.NoErrorHandler.process(NoErrorHandler.java:47) at org.apache.camel.impl.engine.CamelInternalProcessor.process(CamelInternalProcessor.java:398) at org.apache.camel.processor.Pipeline$PipelineTask.run(Pipeline.java:109) at org.apache.camel.impl.engine.DefaultReactiveExecutor$Worker.schedule(DefaultReactiveExecutor.java:187) at org.apache.camel.impl.engine.DefaultReactiveExecutor.scheduleMain(DefaultReactiveExecutor.java:64) at org.apache.camel.processor.Pipeline.process(Pipeline.java:184) at org.apache.camel.impl.engine.CamelInternalProcessor.process(CamelInternalProcessor.java:398) at org.apache.camel.impl.engine.DefaultAsyncProcessorAwaitManager.process(DefaultAsyncProcessorAwaitManager.java:83) at org.apache.camel.support.AsyncProcessorSupport.process(AsyncProcessorSupport.java:41) at org.apache.camel.component.jms.EndpointMessageListener.onMessage(EndpointMessageListener.java:132) at org.springframework.jms.listener.AbstractMessageListenerContainer.doInvokeListener(AbstractMessageListenerContainer.java:736) at org.springframework.jms.listener.AbstractMessageListenerContainer.invokeListener(AbstractMessageListenerContainer.java:696) at org.springframework.jms.listener.AbstractMessageListenerContainer.doExecuteListener(AbstractMessageListenerContainer.java:674) at org.springframework.jms.listener.AbstractPollingMessageListenerContainer.doReceiveAndExecute(AbstractPollingMessageListenerContainer.java:318) at org.springframework.jms.listener.AbstractPollingMessageListenerContainer.receiveAndExecute(AbstractPollingMessageListenerContainer.java:245) at org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.invokeListener(DefaultMessageListenerContainer.java:1237) at org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.executeOngoingLoop(DefaultMessageListenerContainer.java:1227) at org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.run(DefaultMessageListenerContainer.java:1120) at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) at java.base/java.lang.Thread.run(Thread.java:829) Caused by: org.apache.camel.InvalidPayloadException: No body available of type: com.example.IncomingMessage but has value: OutboundMessage(jobResourceId=null, status=something, message=Message does not contain some ID, failedEndpointsAndCauses={}) of type: com.example.OutboundMessage on: Message[ID:foo-40805-1671538168705-4:1:1:4:1]. Caused by: No type converter available to convert from type: com.example.OutboundMessage to the required type: com.example.IncomingMessage with value OutboundMessage(jobResourceId=null, status=something, message=Message does not contain some ID, failedEndpointsAndCauses={}). Exchange[]. Caused by: [org.apache.camel.NoTypeConversionAvailableException - No type converter available to convert from type: com.example.OutboundMessage to the required type: com.example.IncomingMessage with value OutboundMessage(jobResourceId=null, status=something, message=Message does not contain some ID, failedEndpointsAndCauses={})] at org.apache.camel.support.MessageSupport.getMandatoryBody(MessageSupport.java:125) at org.apache.camel.support.builder.ExpressionBuilder$33.evaluate(ExpressionBuilder.java:1028) ... 30 more Caused by: org.apache.camel.NoTypeConversionAvailableException: No type converter available to convert from type: com.example.OutboundMessage to the required type: com.example.IncomingMessage with value OutboundMessage(jobResourceId=null, status=something, message=Message does not contain some ID, failedEndpointsAndCauses={}) at org.apache.camel.impl.converter.CoreTypeConverterRegistry.mandatoryConvertTo(CoreTypeConverterRegistry.java:275) at org.apache.camel.support.MessageSupport.getMandatoryBody(MessageSupport.java:123) ... 31 more 2022-12-20 14:09:49,298 DEBUG [org.apa.cam.com.jms.DefaultJmsMessageListenerContainer] (Camel (camel-1) thread #6 - JmsConsumer[my.queue]) Rolling back transaction because of listener exception thrown: org.apache.camel.CamelExecutionException: Exception occurred during execution on the exchange: Exchange[] 2022-12-20 14:09:49,299 WARN [org.apa.cam.com.jms.EndpointMessageListener] (Camel (camel-1) thread #6 - JmsConsumer[my.queue]) Execution of JMS message listener failed. Caused by: [org.apache.camel.CamelExecutionException - Exception occurred during execution on the exchange: Exchange[]]: org.apache.camel.CamelExecutionException: Exception occurred during execution on the exchange: Exchange[] at org.apache.camel.CamelExecutionException.wrapCamelExecutionException(CamelExecutionException.java:45) at org.apache.camel.support.builder.ExpressionBuilder$33.evaluate(ExpressionBuilder.java:1030) at org.apache.camel.support.ExpressionAdapter.evaluate(ExpressionAdapter.java:45) at org.apache.camel.component.bean.MethodInfo$ParameterExpression.evaluateParameterBinding(MethodInfo.java:738) at org.apache.camel.component.bean.MethodInfo$ParameterExpression.evaluateParameterExpressions(MethodInfo.java:624) at org.apache.camel.component.bean.MethodInfo$ParameterExpression.evaluate(MethodInfo.java:592) at org.apache.camel.component.bean.MethodInfo.initializeArguments(MethodInfo.java:263) at org.apache.camel.component.bean.MethodInfo.createMethodInvocation(MethodInfo.java:271) at org.apache.camel.component.bean.BeanInfo.createInvocation(BeanInfo.java:277) at org.apache.camel.component.bean.AbstractBeanProcessor.process(AbstractBeanProcessor.java:126) at org.apache.camel.component.bean.BeanProcessor.process(BeanProcessor.java:81) at org.apache.camel.processor.errorhandler.NoErrorHandler.process(NoErrorHandler.java:47) at org.apache.camel.impl.engine.CamelInternalProcessor.process(CamelInternalProcessor.java:398) at org.apache.camel.processor.Pipeline$PipelineTask.run(Pipeline.java:109) at org.apache.camel.impl.engine.DefaultReactiveExecutor$Worker.schedule(DefaultReactiveExecutor.java:187) at org.apache.camel.impl.engine.DefaultReactiveExecutor.scheduleMain(DefaultReactiveExecutor.java:64) at org.apache.camel.processor.Pipeline.process(Pipeline.java:184) at org.apache.camel.impl.engine.CamelInternalProcessor.process(CamelInternalProcessor.java:398) at org.apache.camel.impl.engine.DefaultAsyncProcessorAwaitManager.process(DefaultAsyncProcessorAwaitManager.java:83) at org.apache.camel.support.AsyncProcessorSupport.process(AsyncProcessorSupport.java:41) at org.apache.camel.component.jms.EndpointMessageListener.onMessage(EndpointMessageListener.java:132) at org.springframework.jms.listener.AbstractMessageListenerContainer.doInvokeListener(AbstractMessageListenerContainer.java:736) at org.springframework.jms.listener.AbstractMessageListenerContainer.invokeListener(AbstractMessageListenerContainer.java:696) at org.springframework.jms.listener.AbstractMessageListenerContainer.doExecuteListener(AbstractMessageListenerContainer.java:674) at org.springframework.jms.listener.AbstractPollingMessageListenerContainer.doReceiveAndExecute(AbstractPollingMessageListenerContainer.java:318) at org.springframework.jms.listener.AbstractPollingMessageListenerContainer.receiveAndExecute(AbstractPollingMessageListenerContainer.java:245) at org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.invokeListener(DefaultMessageListenerContainer.java:1237) at org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.executeOngoingLoop(DefaultMessageListenerContainer.java:1227) at org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.run(DefaultMessageListenerContainer.java:1120) at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) at java.base/java.lang.Thread.run(Thread.java:829) Caused by: org.apache.camel.InvalidPayloadException: No body available of type: com.example.IncomingMessage but has value: OutboundMessage(jobResourceId=null, status=something, message=Message does not contain some ID, failedEndpointsAndCauses={}) of type: com.example.OutboundMessage on: Message[ID:foo-40805-1671538168705-4:1:1:4:1]. Caused by: No type converter available to convert from type: com.example.OutboundMessage to the required type: com.example.IncomingMessage with value OutboundMessage(jobResourceId=null, status=something, message=Message does not contain some ID, failedEndpointsAndCauses={}). Exchange[]. Caused by: [org.apache.camel.NoTypeConversionAvailableException - No type converter available to convert from type: com.example.OutboundMessage to the required type: com.example.IncomingMessage with value OutboundMessage(jobResourceId=null, status=something, message=Message does not contain some ID, failedEndpointsAndCauses={})] at org.apache.camel.support.MessageSupport.getMandatoryBody(MessageSupport.java:125) at org.apache.camel.support.builder.ExpressionBuilder$33.evaluate(ExpressionBuilder.java:1028) ... 30 more Caused by: org.apache.camel.NoTypeConversionAvailableException: No type converter available to convert from type: com.example.OutboundMessage to the required type: com.example.IncomingMessage with value OutboundMessage(jobResourceId=null, status=something, message=Message does not contain some ID, failedEndpointsAndCauses={}) at org.apache.camel.impl.converter.CoreTypeConverterRegistry.mandatoryConvertTo(CoreTypeConverterRegistry.java:275) at org.apache.camel.support.MessageSupport.getMandatoryBody(MessageSupport.java:123) ... 31 more 2022-12-20 14:09:49,873 SEVERE [org.ecl.yas.int.Unmarshaller] (awaitility-thread) Unexpected char 111 at (line no=1, column no=2, offset=1), expecting 'u' </code> | OK I fixed it myself. There are 2 things:I missed one part in the middle where some validation fails and I do an early return and send, and that bean should set the IN body to be the same POJO to return, the OutboundMessage class, which is not done. So I have to do <code>exchange.getIn().setBody(xxx)</code> there, so that when going to the reply route, the message type is the same as the normal, validation OK path. I also have to <code>.marshal().json(JsonLibrary.Jsonb, OutboundMessage.class)</code> before sending the reply to make sure the message body is a valid string message.But then, a similar error happens where it is like <code>Caused by: org.apache.camel.NoTypeConversionAvailableException: No type converter available to convert from type: byte[] to the required type: com.example.IncomingMessage with value [Bxxxxxxx</code>. I notice that it is now a byte array, meaning that it is already marshalled correctly, but Camel continues to try to process it even after sending. So, after trying all possible, I add <code>.stop()</code> after sending, and this error is gone. Notice that <code>.stop()</code> also ensures the callback(sending reply to reply queue in <code>JMSReplyTo</code> header) is executed, so you will always want to call <code>stop()</code> in request/reply mode. So, make sure you:return the same POJO at the end of each logic path/branch, especially after a short circuit/premature return one stop the route at the end, to stop Camel to do further conversion. In my case, this error is only shown in logs, and ActiveMQ side already received the message, i.e. does not affect the business flow, so it's kind of hard to detect on client side. But it should be stopped. |
apache-camel | I have a project with Apache camel, and it requires mqtt broker for connection. If I run mqtt broker (mosquitto) in docker and execute my project locally it is working totally fine but when I am running the project through Dockerfile i.e. making an executable jar and executing it on docker it says ';Unable to connect to server (32103) - java.net.ConnectException: Connection refused (Connection refused)'; even though mqtt broker is up and running. Full logs (exception): <code> [main] ERROR org.apache.camel.impl.engine.AbstractCamelContext - Error starting CamelContext (camel-1) due to exception thrown: Unable to connect to server (32103) - java.net.ConnectException: Connection refused (Connection refused) org.apache.camel.RuntimeCamelException: Unable to connect to server (32103) - java.net.ConnectException: Connection refused (Connection refused) at org.apache.camel.RuntimeCamelException.wrapRuntimeException(RuntimeCamelException.java:66) at org.apache.camel.support.service.BaseService.doFail(BaseService.java:413) at org.apache.camel.support.service.BaseService.fail(BaseService.java:342) at org.apache.camel.support.service.BaseService.start(BaseService.java:132) at org.apache.camel.support.service.ServiceHelper.startService(ServiceHelper.java:113) at org.apache.camel.impl.engine.AbstractCamelContext.startService(AbstractCamelContext.java:3597) at org.apache.camel.impl.engine.InternalRouteStartupManager.doStartOrResumeRouteConsumers(InternalRouteStartupManager.java:401) at org.apache.camel.impl.engine.InternalRouteStartupManager.doStartRouteConsumers(InternalRouteStartupManager.java:319) at org.apache.camel.impl.engine.InternalRouteStartupManager.safelyStartRouteServices(InternalRouteStartupManager.java:213) at org.apache.camel.impl.engine.InternalRouteStartupManager.doStartOrResumeRoutes(InternalRouteStartupManager.java:147) at org.apache.camel.impl.engine.AbstractCamelContext.doStartCamel(AbstractCamelContext.java:3299) at org.apache.camel.impl.engine.AbstractCamelContext.doStartContext(AbstractCamelContext.java:2951) at org.apache.camel.impl.engine.AbstractCamelContext.doStart(AbstractCamelContext.java:2902) at org.apache.camel.support.service.BaseService.start(BaseService.java:119) at org.apache.camel.impl.engine.AbstractCamelContext.start(AbstractCamelContext.java:2586) at org.apache.camel.impl.DefaultCamelContext.start(DefaultCamelContext.java:247) at basyx.components.databridge.core.component.UpdaterComponent.startRoutes(UpdaterComponent.java:68) at basyx.components.databridge.core.component.UpdaterComponent.startComponent(UpdaterComponent.java:62) at basyx.components.databridge.executable.UpdaterExecutable.main(UpdaterExecutable.java:73) Caused by: Unable to connect to server (32103) - java.net.ConnectException: Connection refused (Connection refused) at org.eclipse.paho.client.mqttv3.internal.TCPNetworkModule.start(TCPNetworkModule.java:80) at org.eclipse.paho.client.mqttv3.internal.ClientComms$ConnectBG.run(ClientComms.java:724) at java.base/java.lang.Thread.run(Thread.java:829) Caused by: java.net.ConnectException: Connection refused (Connection refused) at java.base/java.net.PlainSocketImpl.socketConnect(Native Method) at java.base/java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:412) at java.base/java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:255) at java.base/java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:237) at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) at java.base/java.net.Socket.connect(Socket.java:609) at org.eclipse.paho.client.mqttv3.internal.TCPNetworkModule.start(TCPNetworkModule.java:74) ... 2 more [main] INFO org.apache.camel.impl.engine.AbstractCamelContext - Apache Camel 3.14.0 (camel-1) shutting down (timeout:45s) [main] INFO org.apache.camel.impl.engine.AbstractCamelContext - Routes stopped (total:2 stopped:2) [main] INFO org.apache.camel.impl.engine.AbstractCamelContext - Stopped route2 (paho://PropertyB) [main] INFO org.apache.camel.impl.engine.AbstractCamelContext - Stopped route1 (paho://Properties) [main] INFO org.apache.camel.impl.engine.AbstractCamelContext - Apache Camel 3.14.0 (camel-1) shutdown in 14ms (uptime:238ms) org.apache.camel.RuntimeCamelException: Unable to connect to server (32103) - java.net.ConnectException: Connection refused (Connection refused) at org.apache.camel.RuntimeCamelException.wrapRuntimeException(RuntimeCamelException.java:66) at org.apache.camel.support.service.BaseService.doFail(BaseService.java:413) at org.apache.camel.support.service.BaseService.fail(BaseService.java:342) at org.apache.camel.support.service.BaseService.start(BaseService.java:132) at org.apache.camel.support.service.ServiceHelper.startService(ServiceHelper.java:113) at org.apache.camel.impl.engine.AbstractCamelContext.startService(AbstractCamelContext.java:3597) at org.apache.camel.impl.engine.InternalRouteStartupManager.doStartOrResumeRouteConsumers(InternalRouteStartupManager.java:401) at org.apache.camel.impl.engine.InternalRouteStartupManager.doStartRouteConsumers(InternalRouteStartupManager.java:319) at org.apache.camel.impl.engine.InternalRouteStartupManager.safelyStartRouteServices(InternalRouteStartupManager.java:213) at org.apache.camel.impl.engine.InternalRouteStartupManager.doStartOrResumeRoutes(InternalRouteStartupManager.java:147) at org.apache.camel.impl.engine.AbstractCamelContext.doStartCamel(AbstractCamelContext.java:3299) at org.apache.camel.impl.engine.AbstractCamelContext.doStartContext(AbstractCamelContext.java:2951) at org.apache.camel.impl.engine.AbstractCamelContext.doStart(AbstractCamelContext.java:2902) at org.apache.camel.support.service.BaseService.start(BaseService.java:119) at org.apache.camel.impl.engine.AbstractCamelContext.start(AbstractCamelContext.java:2586) at org.apache.camel.impl.DefaultCamelContext.start(DefaultCamelContext.java:247) at basyx.components.databridge.core.component.UpdaterComponent.startRoutes(UpdaterComponent.java:68) at basyx.components.databridge.core.component.UpdaterComponent.startComponent(UpdaterComponent.java:62) at basyx.components.databridge.executable.UpdaterExecutable.main(UpdaterExecutable.java:73) Caused by: Unable to connect to server (32103) - java.net.ConnectException: Connection refused (Connection refused) at org.eclipse.paho.client.mqttv3.internal.TCPNetworkModule.start(TCPNetworkModule.java:80) at org.eclipse.paho.client.mqttv3.internal.ClientComms$ConnectBG.run(ClientComms.java:724) at java.base/java.lang.Thread.run(Thread.java:829) Caused by: java.net.ConnectException: Connection refused (Connection refused) at java.base/java.net.PlainSocketImpl.socketConnect(Native Method) at java.base/java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:412) at java.base/java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:255) at java.base/java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:237) at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) at java.base/java.net.Socket.connect(Socket.java:609) at org.eclipse.paho.client.mqttv3.internal.TCPNetworkModule.start(TCPNetworkModule.java:74) ... 2 more </code> My docker compose file: <code>version: '3.8' services: bridge-service: image: ${IMAGE_NAME}:${IMAGE_TAG} container_name: ${CONTAINER_NAME} volumes: - C:\Users\user\temp:/usr/share/config depends_on: mqtt: condition: service_healthy mqtt: image: eclipse-mosquitto:2.0.15 ports: - 1884:1884 volumes: - C:\Users\user\temp\mosquitto:/mosquitto/config healthcheck: test: [';CMD-SHELL';, mosquitto_sub -p 1884 -t 'topic' -C 1 -E -i probe -W 3] interval: 10s retries: 2 start_period: 10s timeout: 5s </code> I am sure that this is due to docker because even if I am running jar file locally it is working fine. Please help if anyone has any clue. | After searching over internet, I added <code>network_mode: host</code> to service bridge-service and everything worked fine. So in order to communicate between two services like explained scenario in the problem above just add <code>network_mode: host</code> and everything would work. Now the updated docker compose file is: <code>version: '3.8' services: bridge-service: image: ${IMAGE_NAME}:${IMAGE_TAG} container_name: ${CONTAINER_NAME} network_mode: host volumes: - C:\Users\user\temp:/usr/share/config depends_on: mqtt: condition: service_healthy mqtt: image: eclipse-mosquitto:2.0.15 ports: - 1884:1884 volumes: - C:\Users\user\temp\mosquitto:/mosquitto/config healthcheck: test: [';CMD-SHELL';, mosquitto_sub -p 1884 -t 'topic' -C 1 -E -i probe -W 3] interval: 10s retries: 2 start_period: 10s timeout: 5s </code> |
apache-camel | I am trying to update the version of camel-saxon being used in my project from 2.13.4 to 3.14.0 while keeping the version of camel-core at 2.13.4. Also I am building with Java 1.8.265. Once I change the version of camel-saxon from 2.13.4 to 3.14.0 in my pom.xml and try building with maven clean install I get the following error: <code>java.lang.NoSuchMethodError: org.apache.camel.language.xquery.XQueryLanguage.property(Ljava/lang/Class;[Ljava/lang/Object;ILjava/lang/Object;)Ljava/lang/Object; at org.apache.camel.language.xquery.XQueryLanguage.configureBuilder(XQueryLanguage.java:85) at org.apache.camel.language.xquery.XQueryLanguage.createExpression(XQueryLanguage.java:80) at org.apache.camel.language.xquery.XQueryLanguage.createExpression(XQueryLanguage.java:67) </code> My first thought was to try to upgrade camel-core from 2.13.4 to 3.14.0 but I would like to avoid that if possible for the time being. So is there an api/jar or something else I can use to bridge the gap between camel-core and camel-saxon or is the only way to upgrade camel-saxon by updating both dependencies? If anyone is interested what error I get when trying to upgrade camel-core to 3.14.0 along with camel-saxon. I get the following error:org.apache.camel.FailedToCreateRouteException: Failed to create route route2 at: >;>;>; InOut[inOut] <<< in route: Route(route2)[From[vm:urn:myurn] ->; [ConvertBodyTo... because of Failed to resolve endpoint: xslt://path/to/file/myfile.xsl?transformerFactory=tFactory due to: Error binding property (transformerFactory=tFactory) with name: transformerFactory on bean: xslt://path/to/file/myfile.xsl?transformerFactory=tFactory with value: tFactoryand route: <code><bean id=';tFactory'; class=';net.sf.saxon.TransformerFactoryImpl';/>; <camelContext trace=';true'; xmlns=';http://camel.apache.org/schema/spring';>; <route>; <from uri=';vm:urn:myurn'; />; <convertBodyTo type=';java.lang.String';/>; <log message=';my message'; loggingLevel=';INFO'; logName=';my.logname'; />; <inOut uri=';xslt:path/to/file/myfile.xsl?transformerFactory=tFactory';/>; <convertBodyTo type=';java.lang.String';/>; <log message=';my message'; loggingLevel=';INFO'; logName=';my.log'; />; <inOut uri=';mock:processedout';/>; </route>; </camelContext>; </code> | No, your camel dependencies should always match with the version of camel you're using. Sometimes you might want/need to change version of transitive dependency if one of your camel dependencies is using version of a library that has a bug that's been patched in later (minor) version but that's about it. A lot has changed between Camel version 2.13.4 and 3.14.x including the fact that Camel 2.25.0 reached it's EOL (end of life) in January 2022 meaning that it will no longer receive updates. Your options are either to upgrade your integration to more recent camel version or implement a custom processor or camel-component that does what you do with camel-saxon in your integration but by using more recent versions of saxon related libraries. |
apache-camel | 2022-12-14 14:04:56,317 DEBUG [org.apa.cam.com.jms.EndpointMessageListener] (Camel (camel-1) thread #8 - JmsConsumer[my.queue]) activemq://queue:my.queue consumer received JMS message: ActiveMQTextMessage {commandId = 13, responseRequired = true, messageId = ID:xxxx, originalDestination = null,..., content = org.apache.activemq.util.ByteSequence@11ba49fe, ..., text = { ';foo';: ';bar';, ';x...y';: false}}Notice that text is truncated. How can I see the full text? <code>EndpointMessageListener</code> has this log line: <code>LOG.debug(';{} consumer received JMS message: {}';, this.endpoint, message); </code> And for <code>message</code> of type <code>javax.jms.Message</code>, the toString() method implementation of <code>org.apache.activemq.command.ActiveMQTextMessage</code> is: <code>public String toString() { try { String text = this.text; if (text == null) { text = this.decodeContent(this.getContent()); } if (text != null) { text = MarshallingSupport.truncate64(text); HashMap<String, Object>; overrideFields = new HashMap(); overrideFields.put(';text';, text); return super.toString(overrideFields); } } catch (JMSException var3) { } return super.toString(); } </code> where it always truncates to 60 chars. <code>public static String truncate64(String text) { if (text.length() >; 63) { String var10000 = text.substring(0, 45); text = var10000 + ';...'; + text.substring(text.length() - 12); } return text; } </code> Can I find out what the complete message was? | You could for instance test if the received JMSMessage is of type text, and if so, cast it and invoke the <code>getText()</code> method rather than the generic <code>toString()</code>: <code>if ( message instanceof javax.jms.TextMessage) { TextMessage tm = (TextMessage) message; LOG.debug(';{} consumer received JMS message: {}';, this.endpoint, tm.getText()); } </code> Beware it may also arrive as Bytes- or Stream-Message |
apache-camel | I just realized that <code>choice()</code> in Apache Camel is for dynamic routing, so every <code>choice()</code> needs a <code>to()</code>. It is not equivalent to <code>if</code> in Java. But, does that mean that I cannot conditionally set header to my camel exchange? I want to do something like this: <code>from(';direct:eventHttpChoice';) // last step returns a composite POJO with config details and the actual message and token, let's call it MyCompositePojo .log(....) // I see this message in log .setHeader(';Authorization';, simple(';Bearer ${body.token}';)) .setHeader(Exchange.HTTP_METHOD, simple(';${body.httpMethod.name}';)) .choice() .when(simple(';${body.httpMethod.name} in 'PUT,DELETE'';)) .setHeader(Exchange.HTTP_PATH, simple(';${body.newEvent.number}';)) .endChoice() .end() .choice() .when(simple(';${body.httpMethod.name} in 'POST,PUT'';)) .setHeader(HttpHeaders.CONTENT_TYPE, constant(MediaType.APPLICATION_JSON)) .setBody(simple(';${body.newEvent}';)).marshal().json(JsonLibrary.Jsonb) // marshall here as toD() needs InputStream; and I believe here it converts my message to MyMessagePojo, the actual payload to send .endChoice() .otherwise() // DELETE .when(simple(';${body.configDetail.http.deleteSomeField} == 'true' &;&; ${body.newEvent.someField} != null &;&; ${body.newEvent.someField} != ''';)) .setHeader(Exchange.HTTP_QUERY, simple(';someField=${body.newEvent.someField}&;operationId=${body.newEvent.operationId}';)) .endChoice() .otherwise() .setHeader(Exchange.HTTP_QUERY, simple(';operationId=${body.newEvent.operationId}';)) .endChoice() .endChoice() .end() .log(LoggingLevel.INFO, ';Sending to this url: ${body.configDetail.url}';) // I don't see this log .toD(';${body.configDetail.url}';, 10) // only cache at most 10 urls; I still need MyCompositePojo here </code> But I receive error:2022-12-14 10:44:49,213 ERROR [org.apa.cam.pro.err.DefaultErrorHandler] (Camel (camel-1) thread #6 - JmsConsumer[my.queue]) Failed delivery for (MessageId: A9371D97F55900C-0000000000000001 on ExchangeId: A9371D97F55900C-0000000000000001). Exhausted after delivery attempt: 1 caught: org.apache.camel.language.bean.RuntimeBeanExpressionException: Failed to invoke method: configDetail on null due to: org.apache.camel.component.bean.MethodNotFoundException: Method with name: configDetail not found on bean: [B@330cd22d of type: [B on the exchange: Exchange[A9371D97F55900C-0000000000000001]MyCompositePojo has this field. But I don't know where I get it wrong. If you think I am doing <code>marshall()</code> too early, but if not like this, how can I set body? Because without <code>.marshal()</code> I see this error:2022-12-14 12:25:41,772 ERROR [org.apa.cam.pro.err.DefaultErrorHandler] (Camel (camel-1) thread #7 - JmsConsumer[page.large.sm.provisioning.events.online]) Failed delivery for (MessageId: 65FF01C9FC61E66-0000000000000011 on ExchangeId: 65FF01C9FC61E66-0000000000000011). Exhausted after delivery attempt: 1 caught: org.apache.camel.language.bean.RuntimeBeanExpressionException: Failed to invoke method: configDetail on null due to: org.apache.camel.component.bean.MethodNotFoundException: Method with name: configDetail not found on bean: MyPojo{xxx=xxx, ...} of type: com.example.MyPojo on the exchange: Exchange[65FF01C9FC61E66-0000000000000011]So, it means without <code>.marshal()</code>, it is changing the body to my MessagePojo; but I don't want it, I just need body to be part of my original body, and when it's HTTP DELETE, I don't want to set body. And, later in the route, I still need my composite pojo. I mean, I want to set the HTTP body and only conditionally, I don't want to change the exchange body. So, how to conditionally set header and send to dynamic URL and set body? | An alternative would be to replace the (Camel) choice logic by a custom (Java) processor. <code>from(';direct:demo';) .process( e ->; setDynamicUri(e) ); .toD(';${headers.nextUri}';); private void setDynamicUri(Exchange e) { String httpMethod = e.getMessage().getHeader(';...';, String.class); String endpointUrl = ( Arrays.asList(';PUT';, ';DELETE';).contains(httpMethod) ? ';url1'; : ';url2'; ); e.getMessage().setHeader(';nextUri';, endpointUrl); } </code> |
apache-camel | I've searched for information about Apache Camel supporting the new Spring Boot 3, but with no results. My question is: Did Apache Camel announce the support for Spring Boot 3? All I can find is Apache Camel is only to version <3.0 ... | As you can see spring integration 6.0 goes General availability was announced just some days before. As you can see in the 5th iteration of that project (link), there was added some support for apache camel. You can read more about this here. So considering that you already have <code>spring-boot-starter-parent</code> in your dependencies, you now you have the following 2 dependencies to be used to enable communication channels with apache-camel. <code><dependency>; <groupId>;org.springframework.boot</groupId>; <artifactId>;spring-boot-starter-integration</artifactId>; </dependency>; <dependency>; <groupId>;org.springframework.integration</groupId>; <artifactId>;spring-integration-test</artifactId>; <scope>;test</scope>; </dependency>; </code> |
apache-camel | I have an exception handler in Camel that looks like the following. <code><camel:onException>; <camel:exception>;com.example.BadDataException</camel:exception>; <camel:handled>; <camel:constant>;true</camel:constant>; </camel:handled>; <camel:process ref=';badDataErrorProcessor'; />; <camel:setHeader headerName=';Exchange.HTTP_RESPONSE_CODE';>; <camel:constant>;400</camel:constant>; </camel:setHeader>; </camel:onException>; </code> The <code>BadDataErrorProcessor</code> is a custom bean that has two functions:Log the error. Populate a graceful error response.<code>@Component( ';badDataErrorProcessor'; ) public class BadDataErrorProcessor implements Processor { private static final Logger logger = LoggerFactory.getLogger( BadDataErrorProcessor.class ); @Override public void process( Exchange exchange ) { logger.info( ';Entering ErrorProcessor : process()'; ); orderResponse( exchange ); logger.debug( ';Error Processor setting ID for ...'; ); } public OrderFulfillmentResponse orderResponse( Exchange exchange ) { OrderFulfillmentResponse orderErrorResponse = new OrderFulfillmentResponse(); String errorCode = exchange.getIn() .getHeader( ERROR_CODE, String.class ); logger.info( ';Inside BadDataErrorProcessor with exchangeID {}:';, exchange.getExchangeId() ); Throwable throwable = exchange.getProperty( Exchange.EXCEPTION_CAUGHT, Throwable.class ); if( throwable instanceof BadDataException ) { BadDataException validationEx = (BadDataException) throwable; logger.debug( ';BadDataException, required fields were mising{} :';, validationEx.getMessage() ); } OrderGroupResponse orgpRes = new OrderGroupResponse(); orderErrorResponse.setStatus( Status.FAILED ); orderErrorResponse.setResponseCode( errorCode ); orderErrorResponse.setResponseMessage( throwable.getMessage() ); orgpRes.setStatus( Status.FAILED ); orgpRes.setResponseCode( errorCode ); orgpRes.setResponseMessage( ';400 Bad Request'; ); orderErrorResponse.addOrderGroupResponsesItem( orgpRes ); exchange.getIn() .setBody( orderErrorResponse ); exchange.getIn() .setHeaders( exchange.getIn() .getHeaders() ); return orderErrorResponse; } } </code> After the BadDataErrorProcessor finishes executing successfully, Camel does some magic itself and logs the following stacktrace in the <code>org.apache.camel.component.servlet.CamelHttpTransportServlet</code> class: <code>CamelHttpTransportServlet - Error processing request java.io.IOException: Stream closed at org.apache.catalina.connector.InputBuffer.throwIfClosed(InputBuffer.java:526) ~[tomcat-embed-core-9.0.63.jar:9.0.63] at org.apache.catalina.connector.InputBuffer.read(InputBuffer.java:337) ~[tomcat-embed-core-9.0.63.jar:9.0.63] at org.apache.catalina.connector.CoyoteInputStream.read(CoyoteInputStream.java:132) ~[tomcat-embed-core-9.0.63.jar:9.0.63] at org.apache.catalina.connector.CoyoteInputStream.read(CoyoteInputStream.java:110) ~[tomcat-embed-core-9.0.63.jar:9.0.63] at org.apache.camel.util.IOHelper.copy(IOHelper.java:205) ~[camel-core-2.25.4.jar:2.25.4] at org.apache.camel.http.common.DefaultHttpBinding.copyStream(DefaultHttpBinding.java:432) ~[camel-http-common-2.22.3.jar:2.22.3] at org.apache.camel.http.common.DefaultHttpBinding.doWriteDirectResponse(DefaultHttpBinding.java:496) ~[camel-http-common-2.22.3.jar:2.22.3] at org.apache.camel.http.common.DefaultHttpBinding.doWriteResponse(DefaultHttpBinding.java:395) ~[camel-http-common-2.22.3.jar:2.22.3] at org.apache.camel.http.common.DefaultHttpBinding.writeResponse(DefaultHttpBinding.java:322) ~[camel-http-common-2.22.3.jar:2.22.3] at org.apache.camel.http.common.CamelServlet.doService(CamelServlet.java:223) ~[camel-http-common-2.22.3.jar:2.22.3] at org.apache.camel.http.common.CamelServlet.service(CamelServlet.java:78) ~[camel-http-common-2.22.3.jar:2.22.3] at javax.servlet.http.HttpServlet.service(HttpServlet.java:764) ~[tomcat-embed-core-9.0.63.jar:4.0.FR] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227) ~[tomcat-embed-core-9.0.63.jar:9.0.63] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.63.jar:9.0.63] at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.63.jar:9.0.63] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.63.jar:9.0.63] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.63.jar:9.0.63] at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.3.20.jar:5.3.20] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.20.jar:5.3.20] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.63.jar:9.0.63] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.63.jar:9.0.63] at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.3.20.jar:5.3.20] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.20.jar:5.3.20] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.63.jar:9.0.63] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.63.jar:9.0.63] at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:96) ~[spring-boot-actuator-2.6.8.jar:2.6.8] </code> Can somebody help with this and explain what the ';Stream'; is in this case, why it got closed, and why camel tried to read it after it got closed? Please let me know if there is any additional information I can provide to help investigate. UPDATE: The problem is that as soon as the Stream is created, it's already closed. Camel has a <code>DefaultHttpBinding</code> that is responsible for writing a direct response. It has the graceful response message I expect. It then converts that into an input stream.Then it attempts to copy the Stream, and finally close it.That's when it has to read the stream, and complains it has already been closed. Which is weird because we just created the stream.Camel created the Stream, and is the one complaining it's already been closed. Which means camel is the one closing the Stream. It seems like a bug inside of Camel. The input itself is a <code>CoyoteInputStream</code> that checks if it is closed.The class has a field that indicates closed or not.The problem is that as soon as the Stream is created, it's already closed. | It turns out this was a bug with Camel 2.22.3. I resolved by upgrading to 3.2.0. As soon as a request is received by Camel, the <code>HttpHelper</code> extracts the input stream from the http request.Then it checks if stream caching is enabled, and if yes, it copies the CoyoteInputStream into a new CachedInputStream and closes the original CoyoteInputStream.But when an exception occurs, the DefaultHttpBinding uses the original CoyoteInputStream (which has already been closed) instead of the new CachedInputStream. |
apache-camel | I'm currently facing the issue, that I can not consume a SOAP webservice via camel-cxf. The exception is the following: <code> org.apache.cxf.ws.policy.PolicyException: These policy alternatives can not be satisfied: {http://schemas.xmlsoap.org/ws/2005/07/securitypolicy}TransportBinding: Received Timestamp does not match the requirements {http://schemas.xmlsoap.org/ws/2005/07/securitypolicy}IncludeTimestamp at org.apache.cxf.ws.policy.AssertionInfoMap.checkEffectivePolicy(AssertionInfoMap.java:179) ~[109:org.apache.cxf.cxf-rt-ws-policy:3.2.6] at org.apache.cxf.ws.policy.PolicyVerificationInInterceptor.handle(PolicyVerificationInInterceptor.java:102) ~[109:org.apache.cxf.cxf-rt-ws-policy:3.2.6] at org.apache.cxf.ws.policy.AbstractPolicyInterceptor.handleMessage(AbstractPolicyInterceptor.java:44) ~[109:org.apache.cxf.cxf-rt-ws-policy:3.2.6] at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:308) ~[78:org.apache.cxf.cxf-core:3.2.6] at org.apache.cxf.endpoint.ClientImpl.onMessage(ClientImpl.java:813) [78:org.apache.cxf.cxf-core:3.2.6] at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.handleResponseInternal(HTTPConduit.java:1695) [102:org.apache.cxf.cxf-rt-transports-http:3.2.6] at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream$1.run(HTTPConduit.java:1194) [102:org.apache.cxf.cxf-rt-transports-http:3.2.6] at org.apache.cxf.workqueue.AutomaticWorkQueueImpl$3.run(AutomaticWorkQueueImpl.java:421) [78:org.apache.cxf.cxf-core:3.2.6] at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [?:?] at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [?:?] at org.apache.cxf.workqueue.AutomaticWorkQueueImpl$AWQThreadFactory$1.run(AutomaticWorkQueueImpl.java:346) [78:org.apache.cxf.cxf-core:3.2.6] at java.lang.Thread.run(Thread.java:748) [?:?] </code> and the SOAP answer the following: <code> <s:Envelope xmlns:s=';http://schemas.xmlsoap.org/soap/envelope/';>;<s:Body>;<s:Fault>;<faultcode xmlns:a=';http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd';>;a:InvalidSecurity</faultcode>;<faultstring xml:lang=';de-DE';>;An error occurred when verifying security for the message.</faultstring>;</s:Fault>;</s:Body>;</s:Envelope>;</code> I used the maven <code>cxf-codegen-plugin</code> to generate the Java-classes via the <code>wsdl2java </code>goal. The security part of the wsdl looks like this: <code> <wsp:Policy wsu:Id=';BasicHttpBinding_IUserManagementService_policy';>; <wsp:ExactlyOne>; <wsp:All>; <sp:TransportBinding xmlns:sp=';http://schemas.xmlsoap.org/ws/2005/07/securitypolicy';>; <wsp:Policy>; <sp:TransportToken>; <wsp:Policy>; <sp:HttpsToken RequireClientCertificate=';false';/>; </wsp:Policy>; </sp:TransportToken>; <sp:AlgorithmSuite>; <wsp:Policy>; <sp:Basic256/>; </wsp:Policy>; </sp:AlgorithmSuite>; <sp:Layout>; <wsp:Policy>; <sp:Lax/>; </wsp:Policy>; </sp:Layout>; <sp:IncludeTimestamp/>; </wsp:Policy>; </sp:TransportBinding>; <sp:SignedSupportingTokens xmlns:sp=';http://schemas.xmlsoap.org/ws/2005/07/securitypolicy';>; <wsp:Policy>; <sp:UsernameToken sp:IncludeToken=';http://schemas.xmlsoap.org/ws/2005/07/securitypolicy/IncludeToken/AlwaysToRecipient';>; <wsp:Policy>; <sp:WssUsernameToken10/>; </wsp:Policy>; </sp:UsernameToken>; </wsp:Policy>; </sp:SignedSupportingTokens>; <sp:Wss10 xmlns:sp=';http://schemas.xmlsoap.org/ws/2005/07/securitypolicy';>; <wsp:Policy/>; </sp:Wss10>; </wsp:All>; </wsp:ExactlyOne>; </wsp:Policy>;</code> and I want to use the <code>UsernameToken</code> authentication. Maven dependencies: camel version: 2.20.3 <code> <dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-core</artifactId>; <scope>;provided</scope>; </dependency>; <dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-blueprint</artifactId>; <scope>;provided</scope>; </dependency>; <dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-cxf</artifactId>; <scope>;provided</scope>; </dependency>; <dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-soap-starter</artifactId>; <scope>;provided</scope>; </dependency>;</code> <code> <dependency>; <groupId>;org.apache.cxf</groupId>; <artifactId>;cxf-rt-ws-security</artifactId>; <version>;3.2.6</version>; <scope>;provided</scope>; </dependency>; <dependency>; <groupId>;org.apache.cxf</groupId>; <artifactId>;cxf-rt-ws-policy</artifactId>; <version>;3.2.6</version>; <scope>;provided</scope>; </dependency>;</code> I tried to connect to the api via SoapUI and everything worked well. Either with the authentication-part of SoapUI or with specifying the security part in the SoapHeader, both worked. My camel route-builder looks like this: <code> SoapJaxbDataFormat soap = new SoapJaxbDataFormat(';org.tempuri';, new ServiceInterfaceStrategy(IUserManagementService.class, true)); from(';direct:userdata.soap.requests';) // .marshal(soap) // not sure, if I need to marshal here .to(';cxf://{{SOAP_URL}}'; + ';?serviceClass=org.tempuri.IUserManagementService'; + ';&;serviceName={http://tempuri.org/}UserManagementService'; + ';&;endpointName={http://tempuri.org/}BasicHttpBinding_IUserManagementService'; + ';&;wsdlURL={{WSDL_URL}}'; + ';&;dataFormat=MESSAGE'; + ';&;username={{SOAP_USERNAME}}'; + ';&;password={{SOAP_PASSWORD}}'; + ';&;allowStreaming=false';);</code> and I'm sending to the queue like this: <code> @EndpointInject(uri = ';direct:userdata.soap.requests';) Endpoint endpoint;@Produce(uri = ';direct:userdata.soap.requests';) ProducerTemplate channel;....private Object sendRequest(Object request, String operationName) throws Exception{ Exchange inExchange = endpoint.createExchange(ExchangePattern.InOnly); inExchange.getIn().setHeader(CxfConstants.OPERATION_NAME, operationName); inExchange.getIn().setHeader(CxfConstants.OPERATION_NAMESPACE, ';http://tempuri.org/';); inExchange.getIn().setBody(request); Map<String, Object>; context = new HashMap<>;(); context.put(';ws-security.username';, soapUsername); context.put(';ws-security.password';, soapPassword); inExchange.getIn().setHeader(Client.REQUEST_CONTEXT, context); Exchange outExchange = channel.send(inExchange); log.error(outExchange.getOut().getBody(String.class)); Object result = outExchange.getIn().getBody(Object.class); if(result.getClass().equals(FaultException.class)){ throw (FaultException) result; } return result; }</code> where <code>endpoint</code> is type <code>org.apache.camel.Endpoint</code> and <code>channel</code> is type <code>org.apache.camel.ProducerTemplate</code> The <code>request</code>-Object is of type from the autogenerated classes by the plugin. I also tried, writing my own WSS4JOutInterceptor to handle the security part, but this also did not work. Please let me know, if I need to provide more information. Many thanks in advance | It turned out, there was an issue, interpreting the SOAP answer. So actually the route works like this. Just set the headers <code>ws-security.username</code> and <code>ws-security.password</code> and the cxf will take care of creating the correct header. I've also changed the dataformat to <code>PAYLOAD</code> and marshalling is not needed at this point. Thanks anyway for reading |
apache-camel | I'm trying to implement a rest callout to Salesforce using camel-salesforce component in spring boot and wanted to know if I have to make a GET call to Salesforce content api over https that downloads various types of files of sizes close to 50 MB which component option would I choose? I read the documentation here https://camel.apache.org/components/3.18.x/salesforce-component.html and got confused. I tried the below in my camel config <code>salesforce:apexCall?apexMethod=GET&;amp;apexUrl=/services/data/v49.0/connect/files/545435435/content&;amp;rawPayload=true&;amp;sObjectClass=org.apache.camel.component.salesforce.api.dto.CreateSObjectResult';/>; </code> | Try the raw operation. It returns an <code>InputStream</code> which ideally will contain the file you fetched. |
apache-camel | I am new to Camel, and my use case is as such:We receive messages from AMQ, and we want to remap this message, and sends this message to different endpoints of customereach customer has config of what fields to include, and urls of OAuth + url to send message(REST apis) + credentialsCustomers are grouped under agents, one agent can dominate several customers. We have config in a Map, organized by ';agentId'; as key, and list of ';customerConfigs'; as value.By one field in the message, we decide which agent this message should send toAnd then, we iterate all customers under that agent, checking what fields each one need, and remap message accordinglyWe also filter by checking if the message content meets customer's criteria. If yes, we do OAuth against the OAuth url of that customer, and send message to them. If not, skip. We are doing it with Camel, and by now, all steps from receiving to mapping and retrieving configs and so on, is defined in a bean.(<code>.bean(GeneralBean.class)</code>). It works. But now, we want to retry against customer endpoints, and I decide to separate steps into several Camel steps, because I don't want to retry the whole receiving/remapping/retrieving configs like now. I just want to retry last step, which is sending. Now comes the question: which Camel component should I use?I think recipient list is good, but not sure how. Maybe ';Dynamic router'; is better?When defining steps, when I am retrieving the config of each customer, one object in the exchange body(let's call it <code>RemappedMessage</code>) becomes two (<code>RemappedMessage</code> and a list of <code>CustomerConfig</code>). They have one to many relationship. How do I pass down these two objects to next bean? Or should I process them together in one bean? In the <code>Exchange</code>? In <code>@ExchangeProperties Map<String, Object>; properties</code>? The latter works, but IMO is not very Camel. Or define a tuple class to combine them? I use it a lot but think it's ugly.I don't think there is some syntax in Camel to get some properties of object in the Exchange and put it into the <code>to()</code> as url and as basic credentials username and password? In general, I want to divide the process into several steps in a Camel pipeline, but not sure how to deal with ';one object split into more objects and they need to go hand in hand to downstream'; problem. I am not using Spring, but Quarkus. Now, I am with: <code> from(';activemq:queue:'; + appConfig.getQueueName()) .bean(IncomingMessageConverter.class) // use class form so that Camel will cache the bean .bean(UserIdValidator.class) // validate and if wrong, end route here .bean(CustomerConfigRetrieverBean.class) // retrieve config of customer, by agent id. How to pass down both?? .bean(EndpointFieldsTailor.class) // remove fields if this customer is not interested. Needs CustomerConfig .recipientList(xxxxxx) // how? // what's next? </code> Because <code>RemappedMessage</code> is the return type of the step <code>.bean(IncomingMessageConverter.class)</code>, afterwards Camel can bind args to it so I can have access to the mapped message. But obviously I cannot return 2 objects together. | Recipient List is ideal when you want to send the same message to multiple endpoints and you know what those endpoints are before entering the Recipient List. The Dynamic Router can route messages to a number of endpoints, the list and order of which not necessarily known at the time the router is entered. Since you have a one-to-many situation, Dynamic Router may be a better fit. A simpler approach that might work is to prepare a List of tuples. Each tuple would contain a <code>CustomerConfig</code> and a <code>RemappedMessage</code>. You would then split the list and in the splitter send the message to the agent. For the tuple you could use something like ImmutablePair, a <code>Map</code>, or just a two-element <code>List</code>. As for setting a url and username/password, I'll assume you're using Camel's HTTP component. It's probably best to provide these values as headers since the http component allows this. The URL can be set with the CamelHttpUri header. And the HTTP component will generally pass message headers as HTTP headers, so you can set things like the <code>Authorization</code> header just by setting a message header with the same name. And there's definitely support for setting headers from values in the exchange and message. E.g. <code>// assumes the body is a List in which the first element is a CustomerConfig .setHeader(';Authorization';, simple(';${body[0].authValue}';)) </code> In reality, you'll probably have to do a little bit more work for authorization. E.g, if it's basic auth, you'll have to compute the value you want to use. I'd set that in a header or property and then refer to it like: <code>.setHeader(';Authorization';, simple(';${header.basicAuthValue}';)) // or .setHeader(';Authorization';, simple(';${exchangeProperty.basicAuthValue}';)) </code> |
apache-camel | I am trying to call an external API with an access token parameter in query, by taking it from header, however for some reason it doesn't work, API returns error <code>Access token not configured</code>. But when I'm calling log on the same string, access token from header appears to be in place. Code from configure method in my Route: <code>from(';direct:user_get';) .log(';https://api.vk.com/method/users.get?access_token=${header.access_token}&;v=5.131';) .to(';https://api.vk.com/method/users.get?access_token=${header.access_token}&;v=5.131';); </code> Call of <code>FluentProducerTemplate</code> (Actual token replaced with ';token_example';): <code>String userGetResponse = producerTemplate .to(';direct:user_get';) .withHeader(';access_token';, ';token_example';) .request(String.class); </code> When I pass token right into the <code>.to()</code> call itself, everything works fine, API returns valid response. | You need to use <code>toD</code> because it is a dynamic endpoint. So what are you sending is this string <code>${header.access_token}</code> and not the the header Token. <code>.toD(';https://api.vk.com/method/users.get?access_token=${header.access_token}&;v=5.131';); </code> Normnal to doesn't transform the uri only toD make this. Check the DocsThe to is used for sending messages to a static endpoint. In other words to sends message only to the same endpoint. The toD is used for sending message to a dynamic endpoint. The dynamic endpoint is evaluated on-demand by an Expression. By default, the Simple expression is used to compute the dynamic endpoint URI. |
apache-camel | I am using the Apache Camel Main (see https://camel.apache.org/components/next/others/main.html) component version 3.19 and have the following AWS2-S3 to AWS3-S3 route specified in my route.yaml file: <code>- route: from: uri: ';aws2-s3:arn:aws:s3:source-bucket'; parameters: region: ';eu-central-1'; accessKey: ';xxxxx'; secretKey: ';xxxxx'; deleteAfterRead: ';false'; steps: - to: uri: ';aws2-s3:arn:aws:s3:destination-bucket'; parameters: region: ';eu-central-1'; accessKey: ';xxxxx'; secretKey: ';xxxxx';</code> My app looks as follows: <code>public class MyApp { public static void main(String[] args) throws Exception { Main main = new Main(MyApp .class); main.run(args); }}</code> The purpose of the above route and app is to copy over all files from the <code>source-bucket</code> to the <code>destination-bucket</code>. When I ran the app, both buckets already existed and while the <code>source-bucket</code> contained a few files, the <code>destination-bucket</code> was empty. But instead of copying over the files into the <code>destination-bucket</code> it seems that all files have been copied back into the <code>source-bucket</code> while overwriting the existing files. Moreover, after running the app the <code>destination-bucket</code> was still empty. Is this a bug in Camel Main or is something wrong in my <code>route.yaml</code>? Thanks in advance for your help. | This is because the consumer from the original bucket source-bucket is providing an header containing the name of it. This header will override the destination-bucket in the producer to the destination bucket. Your code should look like: <code>- route: from: uri: ';aws2-s3:arn:aws:s3:source-bucket'; parameters: region: ';eu-central-1'; accessKey: ';xxxxx'; secretKey: ';xxxxx'; deleteAfterRead: ';false'; steps: - remove-header: name: ';CamelAwsS3BucketName'; - to: uri: ';aws2-s3:arn:aws:s3:destination-bucket'; parameters: region: ';eu-central-1'; accessKey: ';xxxxx'; secretKey: ';xxxxx'; </code> In this way you won't carry the header to the next endpoint. This is happening here: https://github.com/apache/camel/blob/main/components/camel-aws/camel-aws2-s3/src/main/java/org/apache/camel/component/aws2/s3/utils/AWS2S3Utils.java#L46 You could also look at the copyObject operation on the producer side: https://github.com/apache/camel/blob/main/components/camel-aws/camel-aws2-s3/src/main/java/org/apache/camel/component/aws2/s3/AWS2S3Producer.java#L403 By the way, with removing the header everything should work as expected. |
apache-camel | There are at least two popular java EIP frameworks: Spring Integration and Apache Camel. They both have fluent programming interfaces that make it easy to implement complex EIPs. Here's an example of Apache Camel using the Aggregator EIP. I'm interested in chaining together multiple EIPs. For example: Read from queue1, do some transformation, write to queue 2, read from queue 2, aggregate messages, write to queue3. Apache Camel enables this, but it requires defining multiple Routes. Something like this: <code>from(';seda:queue1';) .process(new SomeProcessor()) .to(';seda:queue2';);from(';seda:queue2';) .aggregate(new AggregationStrategy()) .to(';seda:queue3';); </code> I'm interested in a way to chain the two routes together, something like this: <code>from(';seda:queue1';) .process(new SomeProcessor()) .to(';seda:queue2';) .andThen() .aggregate(new AggregationStrategy()) .to(';seda:queue3';); </code> Is there a way to do this in Apache Camel or Spring Integration? | With Spring Integration it is possible via its Java DSL: <code>@Bean IntegrationFlow myFlow() { return IntegrationFlow.from(';queue1';) .handle(new SomeProcessor()) .channel(';queue2';) .aggregate() .channel(';queue3';) .get(); } </code> See more info in the documentation: https://docs.spring.io/spring-integration/docs/current/reference/html/dsl.html#java-dsl You really can chose whatever implementation of the <code>MessageChannel</code> you need to use in between those EIPs: https://docs.spring.io/spring-integration/docs/current/reference/html/core.html#channel-implementations |
apache-camel | I am trying to read a csv file from AWS S3 and print on console, but it is not working. <code>public class Example { public static void main(String[] args) throws Exception { var camelContext = new DefaultCamelContext(); camelContext.addRoutes(new MainRoute()); camelContext.start(); Thread.sleep(10_000); camelContext.stop(); } } public class MainRoute extends RouteBuilder { @Override public void configure() { var s3Url = String.format( ';aws2-s3://mybucket.com?'; + ';prefix=etl/hello.csv&;useDefaultCredentialsProvider=true&;deleteAfterRead=false&;maxMessagesPerPoll=1';); System.out.println(';start route';); from(s3Url).marshal().csv().log(';log message';).end(); System.out.println(';finish route';); } } </code> I tried using marshal().csv() I tried using only: from(s3Url).log(';log message';).end(); Only ';start route'; and ';finish route'; is printed, ';log message'; is never printed. Versions: Apache camel: 3.19.0, Java:17 CSV content: <code>Name,age myName,31 </code> What should I do in order to read the csv content and print in console? | I found the the cause. I had to put log libraries on the classpath in order to work to log, the default java logging was not enough to work, I do not know why. I put this in my pom file: <code><!-- logging -->; <dependency>; <groupId>;org.apache.logging.log4j</groupId>; <artifactId>;log4j-api</artifactId>; <version>;${log4j2.version}</version>; </dependency>; <dependency>; <groupId>;org.apache.logging.log4j</groupId>; <artifactId>;log4j-core</artifactId>; <version>;${log4j2.version}</version>; </dependency>; <dependency>; <groupId>;org.apache.logging.log4j</groupId>; <artifactId>;log4j-slf4j-impl</artifactId>; <version>;${log4j2.version}</version>; </dependency>; </code> |
apache-camel | I have a spring-boot application where I read data from queue and send data to transformation class using .bean() Integration.java <code>class Integration { @Value(';${someURL}';) private String someURL; //able to read someURL from property file from(';queue';) // some intermediate code .bean(new TransformationClass(), ';transformationMethod';) // other code} </code> Now, Inside TransformationClass I have @Value annotation to read values from properties file but it always returns a null. TransformationClass.java <code>@Component class TransformationClass { @Value(';${someURL}';) private String someURL; //someURL return null though there is key-value associated in props file. public void transformationMethod(Exchange exchange) { // other stuff related to someURL } } </code> Note - I am able to read values from property file in class <code>Integration.java</code> but unable to read from class <code>TransformationClass.java</code> I am using spring boot version - 2.7.2 and camel version - 3.18.1 jdk - 17 I tried to read using camel PropertiesComponent but it did not worked. | Problem here is, that <code>new TransformationClass()</code> is not a ';spring managed instance';, thus all <code>@Autowire/Value/Inject/...</code>s have no effect. Since <code>TransformationClass</code> is (singleton, spring-managed) <code>@Component</code> and is needed by <code>Integration</code>, wiring these makes sense: Via field... : <code>class Integration { @Autowired private TransformationClass trnsObject; // ... </code> Or constructor injection: <code>class Integration { private final TransformationClass trnsObject; public Integration(/*im- /explicitely @Autowired*/ TransformationClass pTrnsObject) { trnsObject = pTrnsObject; } // ... </code> <code> // then: doSomethingWith(trnsObject); // has correct @Values } </code> |
apache-camel | I am a bit confused about working with Blueprint camel and Apache Karaf. In fact, when I was developping my route, I was using this to connect to my mssql database : <code><bean id=';dbcp'; destroy-method=';close'; class=';org.apache.commons.dbcp2.BasicDataSource';>; <property name=';driverClassName'; value=';com.microsoft.sqlserver.jdbc.SQLServerDriver'; />; <property name=';url'; value=';jdbc:sqlserver://server\instance;databaseName=xxx;'; />; <property name=';username'; value=';xxxx'; />; <property name=';password'; value=';xxx'; />; </bean>; </code> This was working flawlessly and then I wanted to export it into Apache Karaf. I did so and ran into a lot of trouble because of the sqlserver driver not being found. So I tried to handle this another way by exposing the DataSource as a service on Apache Karaf. This works and I get a hold of the reference like so in my blueprint: <code><reference id=';dbcp'; interface=';javax.sql.DataSource'; filter=';(osgi.jndi.service.name=Name)'; availability=';mandatory'; />; </code> Now this works but I don't exactly know what this does behind the scenes. I've read about services and references and often to make my first example work, people use a service call and then use it in the bean. Is there a right and a wrong way? I've read on top of that, that we should a connection pool but I have only seen an example of this in the first approach (1st code sample). I guess it does the same when done with the DataSource as a service since I can call it from multiple bundles. Thanks for regarding, best regards | In Apache Karaf versions 4.2.x - 4.4.x it's generally a good practice to use OSGi Services to share DataSource type objects. This makes your bundles more loosely coupled and when making changes to connection parameters you'll only need to change them for the service instead of having to reconfigure every bundle that uses the said DataSource. You can also create your own shared resources and expose them as services using blueprints, declarative service annotations or the ';hard way'; using activator and bundle context. I also recommend to checkout features pax-jdbc-config and pax-jms-config features as they allow you to create DataSource and ConnectionFactory type services from config files. These look for config files using <code>org.ops4j.datasource</code> <code>org.ops4j.datasource</code> prefixes in their name e.g <code>org.ops4j.datasource-Example.cfg</code> Only downside for using services is that they're specific to Karaf and OSGi so if you ever need to move your integrations to non-osgi environment you'll have to figure out another way to inject data sources to your integrations. [edit] With shared resources I mean resources you might want to access from multiple bundles. These can be anything from objects that contain shared data, connection objects for cloud blob storages, data access objects, slack or discord bots, services for sending mails etc. You can publish new services using blueprints from beans using service tag. Below is example from OSGi R7 Specification <code><blueprint>; <service id=';echoService'; interface=';com.acme.Echo'; ref=';echo';/>; <bean id=';echo'; class=';com.acme.EchoImpl';>; <property name=';message'; value=';Echo: ';/>; </bean>; </blueprint>; </code> <code>public interface Echo { public String echo(String m); } public class EchoImpl implements Echo { String message; public void setMessage(String m) { this.message= m; } public void echo(String s) { return message + s; } } </code> With OSGi Declarative services (DS) / Service Component Runtime (SCR) annotations you can publish new services with java. <code>@Component public class EchoImpl implements Echo { String message; public void setMessage(String m) { this.message= m; } public void echo(String s) { return message + s; } } </code> Another example can be found from Official Karaf examples in github. |
apache-camel | I hope you are well! First, I am new to the EIP world. I am trying to do a simple request reply with:A Golang rabbitMQ client An apache Camel route in Kotlin acting as a RabbitMQ serverI have tried to read all the docs I could and search for answers but I could't find nothing. I am basically desperate. Mainly I saw this and nothing has worked yet. My goal is to do a sync request-reply as the image.My Golang client looks like this: <code>func (r *RabbitMQConn) GetQueue(name string) *amqp.Queue { ch := r.GetChannel() defer ch.Close() q, err := ch.QueueDeclare( name, false, false, true, false, nil, ) if err != nil { panic(err) } return &;q } </code> <code>func (r *RabbitMQConn) PublishAndWait(routingKey string, correlationId string, event domain.SyncEventExtSend) (domain.SyncEventExtReceive, error) { message, err := json.Marshal(event) if err != nil { return domain.SyncEventExtReceive{}, apperrors.ErrInternal } ch := r.GetChannel() defer ch.Close() q := r.GetQueue(';response';) h, err := ch.Consume( q.Name, ';';, true, false, false, false, nil, ) if err != nil { return domain.SyncEventExtReceive{}, err } ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() err = ch.PublishWithContext( ctx, ';';, routingKey, false, false, amqp.Publishing{ ContentType: ';application/json';, Body: message, CorrelationId: correlationId, ReplyTo: q.Name, }, ) if err != nil { return domain.SyncEventExtReceive{}, err } for d := range h { fmt.Println(';Received a message:';, string(d.Body)) if d.CorrelationId == correlationId { var event domain.SyncEventExtReceive err = json.Unmarshal(d.Body, &;event) return event, err } } return domain.SyncEventExtReceive{}, apperrors.ErrInternal } </code> Basically, just consuming from the default exchange with a named response queue. Also, I send the queue name as the ReplyTo parameter and I give it a correlation id. The routing-key that is sent is <code>daily-weather</code> in this case.On the server side, I tried to do the server with the default exchange, but Apache Camel forbids me to do nothing with that exchange. <code>from(';rabbitmq:?queue=daily-weather&;autoAck=true&;autoDelete=false';) </code> So, I assigned it the <code>amq.direct</code> exchange. However, that didn't also worked. <code>';rabbitmq:amq.direct?queue=daily-weather&;autoAck=true&;autoDelete=false'; </code> Then, I added a second RabbitMQ endpoint to see if it would sent it, but nothing. <code> from(';rabbitmq:amq.direct?queue=daily-weather&;autoAck=true&;autoDelete=false';) .log(LoggingLevel.INFO, ';weather-daily';, ';Received message: \${body}';) .to(';rabbitmq:amq.direct?queue=response&;autoAck=true&;autoDelete=false';)</code> I ask if anybody has any simple example to do this with Apache Camel, because I am ultra lost. Any further detail can be shared if you contact me. Thank you very much!!!! :) | SOLVED Hi! After some time I decided to take a look to the spring-rabbitmq Camel component. I realised that Camel has exchange patterns, and rabbitmq, by default, sets it to <code>inOut</code>. This way, automatically returns the information back to the <code>replyTo</code> property. <code> val RABBIMQ_ROUTE = ';spring-rabbitmq:default?queues={{rabbitmq.weather.daily.routing_key}}'; </code> <code>default</code> refers to the default exchange queue. |
apache-camel | Currently I am unable to grab ->; archive ->; decrypt a file from an SFTP server. I have tested the logic using local directories but with no success using SFTP. The connection appears to be established to the server as neglecting to pass the private key will result in a connection exception. When the key is being passed no exception is given from the route itself but no files are copied. What would be a potential solution or next steps to help in troubleshooting this issue? I am using the absolute directory's in which the files would be stored from the sftp location. <code>CamelContext camelContext = new DefaultCamelContext(); camelContext.getRegistry().bind(';SFTPPrivateKey';,Byte[].class,privateKey.getBytes()); String sftpInput = buildURISFTP(input,inputOptions,connectionConfig); String sfpOutput = buildURISFTP(output,outputOptions,connectionConfig); String sfpArchive = buildURISFTP(archive,archiveOptions,connectionConfig);camelContext.addRoutes(new RouteBuilder() { public void configure() throws Exception { PGPDataFormat pgpDataFormat = new PGPDataFormat(); pgpDataFormat.setKeyFileName(pPgpSecretKey); pgpDataFormat.setKeyUserid(pgpUserId); pgpDataFormat.setPassword(pgpPassword); pgpDataFormat.setArmored(true); from(sftpInput) .to(sfpArchive); //tested decryption local with file to file routing .unmarshal(pgpDataFormat) .to(sfpOutput); } }); camelContext.start(); Thread.sleep(timeout); camelContext.stop(); </code> <code>public String buildURISFTP(String directory, String options, ConnectionConfig connectionConfig){ StringBuilder uri = new StringBuilder(); uri.append(';sftp://';); uri.append(connectionConfig.getSftpHost()); uri.append(';:';); uri.append(connectionConfig.getSftpPort()); uri.append(directory); uri.append(';?username=';); uri.append(connectionConfig.getSftpUser()); if(!StringUtils.isEmpty(connectionConfig.getSftpPassword())){ uri.append(';&;password=';); uri.append(connectionConfig.getSftpPassword()); } uri.append(';&;privateKey=#SFTPPrivateKey';); if(!StringUtils.isEmpty(options)){ uri.append(options); } return uri.toString(); } </code> | Issue was due to lack of knowledge around FTP component https://camel.apache.org/components/3.18.x/ftp-component.html Where it is specified that absolute paths are not supported, unfortunately I did not read this page and only referenced the SFTP component page where it is not specified. https://camel.apache.org/components/3.18.x/sftp-component.html Issue was resolved by backtracking directories with /../../ before giving the absolute path. |
apache-camel | I am a beginner and I am working through Manning's Camel in Action. I am setting up the transaction manager as prescribed (in Chapter 9): <code><bean id=';jmsConnectionFactory'; class=';org.apache.activemq.ActiveMQConnectionFactory';>; <property name=';brokerURL'; value=';tcp://${activemq.host}:${activemq.port}'; />; </bean>;<bean id=';pooledConnectionFactory'; class=';org.apache.activemq.pool.PooledConnectionFactory'; init-method=';start'; destroy-method=';stop';>; <property name=';maxConnections'; value=';2'; />; <property name=';connectionFactory'; ref=';jmsConnectionFactory'; />; </bean>;<bean id=';jmsTxnManager'; class=';org.springframework.jms.connection.JmsTransactionManager';>; <property name=';connectionFactory'; ref=';pooledConnectionFactory'; />; </bean>;<bean id=';activemq'; class=';org.apache.camel.component.activemq.ActiveMQComponent';>; <property name=';connectionFactory'; ref=';pooledConnectionFactory'; />; <property name=';transacted'; value=';true'; />; <property name=';transactionManager'; ref=';jmsTxnManager';/>; </bean>; </code> I have a simple consumer route setup: <code><route id=';exAroute';>; <from uri=';activemq:{{mq.in}}';/>; <transacted/>; <log message=';${body}';/>; </route>; </code> When I run Camel I getting a set of DEBUG log messages every second on an empty queue: <code>10:54:30.873 [Camel thread #2 - JmsConsumer[TEST_IN]] DEBUG org.springframework.jms.connection.JmsTransactionManager - Creating new transaction with name [JmsConsumer[TEST_IN]]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT 10:54:30.873 [Camel thread #2 - JmsConsumer[TEST_IN]] DEBUG org.springframework.jms.connection.JmsTransactionManager - Created JMS transaction on Session [PooledSession { ActiveMQSession {id=ID:computer-60122-1666796067926-1:2:1,started=true} java.lang.Object@192cac46 }] from Connection [PooledConnection { ConnectionPool[ActiveMQConnection {id=ID:computer-60122-1666796067926-1:2,clientId=ID:computer-60122-1666796067926-0:1,started=true}] }] 10:54:31.885 [Camel thread #2 - JmsConsumer[TEST_IN]] DEBUG org.apache.activemq.ActiveMQMessageConsumer - remove: ID:computer-60122-1666796067926-1:2:1:2, lastDeliveredSequenceId: -1 10:54:31.885 [Camel thread #2 - JmsConsumer[TEST_IN]] DEBUG org.springframework.jms.connection.JmsTransactionManager - Initiating transaction commit 10:54:31.885 [Camel thread #2 - JmsConsumer[TEST_IN]] DEBUG org.springframework.jms.connection.JmsTransactionManager - Committing JMS transaction on Session [PooledSession { ActiveMQSession {id=ID:computer-60122-1666796067926-1:2:1,started=true} java.lang.Object@192cac46 }] 10:54:31.885 [Camel thread #2 - JmsConsumer[TEST_IN]] DEBUG org.apache.activemq.ActiveMQSession - ID:computer-60122-1666796067926-1:2:1 Transaction Commit :null 10:54:31.885 [Camel thread #2 - JmsConsumer[TEST_IN]] DEBUG org.apache.activemq.ActiveMQSession - ID:computer-60122-1666796067926-1:2:1 Transaction Rollback, txid:null </code> I am wondering why this is? Is my setup incorrect? I have spent 2 hours researching this without any luck. I hope you can help. Thanks in advance. PS: If I put a message a message in the queue for consumption the route executes fine: <code>10:59:21.829 [Camel thread #2 - JmsConsumer[TEST_IN]] DEBUG org.apache.activemq.TransactionContext - Begin:TX:ID:computer-60151-1666796352835-1:2:1 10:59:21.829 [Camel thread #2 - JmsConsumer[TEST_IN]] DEBUG org.apache.camel.component.jms.DefaultJmsMessageListenerContainer - Received message of type [class org.apache.activemq.command.ActiveMQTextMessage] from consumer [PooledMessageConsumer { ActiveMQMessageConsumer { value=ID:computer-60151-1666796352835-1:2:1:5, started=true } }] of transactional session [PooledSession { ActiveMQSession {id=ID:computer-60151-1666796352835-1:2:1,started=true} java.lang.Object@296def58 }] 10:59:21.829 [Camel thread #2 - JmsConsumer[TEST_IN]] DEBUG org.apache.camel.component.jms.EndpointMessageListener - activemq://TEST_IN consumer received JMS message: ActiveMQTextMessage {commandId = 5, responseRequired = true, messageId = ID:computer-60156-1666796361583-1:1:1:1:1, originalDestination = null, originalTransactionId = null, producerId = ID:computer-60156-1666796361583-1:1:1:1, destination = queue://TEST_IN, transactionId = null, expiration = 0, timestamp = 1666796361809, arrival = 0, brokerInTime = 1666796361809, brokerOutTime = 1666796361819, correlationId = null, replyTo = null, persistent = true, type = null, priority = 4, groupID = null, groupSequence = 0, targetConsumerId = null, compressed = false, userID = null, content = org.apache.activemq.util.ByteSequence@4db30c0e, marshalledProperties = null, dataStructure = null, redeliveryCounter = 0, size = 0, properties = null, readOnlyProperties = true, readOnlyBody = true, droppable = false, jmsXGroupFirstForConsumer = false, text = test} 10:59:21.859 [Camel thread #2 - JmsConsumer[TEST_IN]] DEBUG org.apache.camel.spring.spi.TransactionErrorHandler - Transaction begin (0x76adb233) redelivered(false) for (MessageId: ID:computer-60156-1666796361583-1:1:1:1:1 on ExchangeId: ID-computer-1666796353110-0-1)) 10:59:21.859 [Camel thread #2 - JmsConsumer[TEST_IN]] DEBUG org.springframework.jms.connection.JmsTransactionManager - Participating in existing transaction 10:59:21.859 [Camel thread #2 - JmsConsumer[TEST_IN]] INFO exAroute - test 10:59:21.859 [Camel thread #2 - JmsConsumer[TEST_IN]] DEBUG org.apache.camel.spring.spi.TransactionErrorHandler - Transaction commit (0x76adb233) redelivered(false) for (MessageId: ID:computer-60156-1666796361583-1:1:1:1:1 on ExchangeId: ID-computer-1666796353110-0-1)) 10:59:21.859 [Camel thread #2 - JmsConsumer[TEST_IN]] DEBUG org.springframework.jms.connection.JmsTransactionManager - Initiating transaction commit 10:59:21.859 [Camel thread #2 - JmsConsumer[TEST_IN]] DEBUG org.springframework.jms.connection.JmsTransactionManager - Committing JMS transaction on Session [PooledSession { ActiveMQSession {id=ID:computer-60151-1666796352835-1:2:1,started=true} java.lang.Object@296def58 }] 10:59:21.859 [Camel thread #2 - JmsConsumer[TEST_IN]] DEBUG org.apache.activemq.ActiveMQSession - ID:computer-60151-1666796352835-1:2:1 Transaction Commit :TX:ID:computer-60151-1666796352835-1:2:1 10:59:21.859 [Camel thread #2 - JmsConsumer[TEST_IN]] DEBUG org.apache.activemq.TransactionContext - Commit: TX:ID:computer-60151-1666796352835-1:2:1 syncCount: 2 10:59:21.869 [Camel thread #2 - JmsConsumer[TEST_IN]] DEBUG org.apache.activemq.ActiveMQMessageConsumer - remove: ID:computer-60151-1666796352835-1:2:1:5, lastDeliveredSequenceId: 844 10:59:21.869 [Camel thread #2 - JmsConsumer[TEST_IN]] DEBUG org.apache.activemq.ActiveMQSession - ID:computer-60151-1666796352835-1:2:1 Transaction Rollback, txid:null </code> | Apache Camel uses Spring JMS Template, and Spring's JMS template closes the session and connection after every message receive check loop in transacted mode. This creates a lot of thrashing on the ActiveMQ broker. Fix: Add this property to your o.a.camel.component.activemq.ActiveMQComponent bean <code> <property name=';cacheLevelName'; value=';CACHE_CONSUMER'; />; </code> ref: https://camel.apache.org/components/3.18.x/jms-component.html |
apache-camel | I have imported my Apache Camel blueprint xml bundle into Apache Karaf. When I try to start the bundle, it is complaining about dbcp2. I've tried to bundle it into my Apache Karaf but still no luck. The error I am getting: <code>Error executing command: Error executing command on bundles: Error starting bundle 129: Unable to resolve xxx.yyy [129](R 129.0): missing requirement [xxx.yyy [129](R 129.0)] osgi.wiring.package; (&; (osgi.wiring.package=org.apache.commons.dbcp2)(version>;=2.9.0)(!(version>;=3.0.0))) [caused by: Unable to resolve org.apache.commons.commons-dbcp2 [119](R 119.0): missing requirement [org.apache.commons.commons-dbcp2 [119](R 119.0)] osgi.wiring.package; (&; (osgi.wiring.package=javax.transaction)(version>;=1.1.0))] Unresolved requirements: [[xxx.yyy [129](R 129.0)] osgi.wiring.package; (&; (osgi.wiring.package=org.apache.commons.dbcp2)(version>;=2.9.0)(!(version>;=3.0.0)))] </code> I am not sure if the problem is the dbcp2 or the javax.transaction. I've bundled both into my Apache Karaf therefore as shown here: <code>119 │ Installed │ 80 │ 2.9.0 │ Apache Commons DBCP 120 │ Resolved │ 80 │ 20220320.0.0 │ JSON in Java 129 │ Installed │ 80 │ 0.0.1.SNAPSHOT │ Route for xxxxx (my bundle) 131 │ Resolved │ 80 │ 0 │ wrap_mvn_javax.transaction_jta_1.1 </code> My pom file in my bundle imports dbcp2 as shown here: <code><dependency>; <groupId>;org.apache.commons</groupId>; <artifactId>;commons-dbcp2</artifactId>; <version>;2.9.0</version>; </dependency>; </code> | After trying out a bit of different bundles, I've found out that bundle:install transaction fixed it. |
apache-camel | I am working on a project where I use a camel route (Camel-sql) to fetch data from a MariaDB database. I use apache commons dbcp2 as a Datasource in my blueprint file. It works perfectly fine when I use mvn:camel-run to run the project in development. The problem starts when I try to deploy this project on Karaf. mvn:install generates the required jar with blueprint files and manifest file correctly formed. I copy this over to the deploy folder in Karaf. The bundle installation is successful. But it does not start. I get an exception saying that the bundle was not able to detect the MariaDB java client. This does not make sense to me because I have it installed (using bundle:install -s mvn:...) on Karaf. I did this for all other dependencies like fasterxml, dbcp2 etc. My requirement is strict: I need to be able to define the data source in my blueprint file. I have found some solutions about using pax-jdbc but did not get anything clear as of yet. Attaching all relevant hints below. Exception trace <code>17:39:01.404 WARN [Camel (dbOps-context-g3) thread #10 - timer://foo] Error processing exchange. Exchange[AA8CB8C488B457B-0000000000000005]. Caused by: [org.springframework.jdbc.CannotGetJdbcConnectionException - Failed to obtain JDBC Connection; nested exception is java.sql.SQLException: Cannot load JDBC driver class 'org.mariadb.jdbc.Driver'] org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection; nested exception is java.sql.SQLException: Cannot load JDBC driver class 'org.mariadb.jdbc.Driver' at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:83) ~[!/:?] at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:646) ~[!/:?] at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:685) ~[!/:?] at org.apache.camel.component.sql.SqlProducer.processInternal(SqlProducer.java:145) ~[!/:3.19.0] at org.apache.camel.component.sql.SqlProducer.process(SqlProducer.java:132) ~[!/:3.19.0] 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.processor.errorhandler.RedeliveryErrorHandler$SimpleTask.run(RedeliveryErrorHandler.java:477) ~[?:?] 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:175) ~[?:?] at org.apache.camel.impl.engine.CamelInternalProcessor.process(CamelInternalProcessor.java:392) ~[?:?] at org.apache.camel.component.timer.TimerConsumer.sendTimerExchange(TimerConsumer.java:210) ~[?:?] at org.apache.camel.component.timer.TimerConsumer$1.run(TimerConsumer.java:76) ~[?:?] at java.util.TimerThread.mainLoop(Timer.java:556) ~[?:?] at java.util.TimerThread.run(Timer.java:506) ~[?:?] Caused by: java.sql.SQLException: Cannot load JDBC driver class 'org.mariadb.jdbc.Driver' at org.apache.commons.dbcp2.DriverFactory.createDriver(DriverFactory.java:54) ~[!/:2.9.0] at org.apache.commons.dbcp2.BasicDataSource.createConnectionFactory(BasicDataSource.java:459) ~[!/:2.9.0] at org.apache.commons.dbcp2.BasicDataSource.createDataSource(BasicDataSource.java:525) ~[!/:2.9.0] at org.apache.commons.dbcp2.BasicDataSource.getConnection(BasicDataSource.java:731) ~[!/:2.9.0] at org.springframework.jdbc.datasource.DataSourceUtils.fetchConnection(DataSourceUtils.java:159) ~[!/:?] at org.springframework.jdbc.datasource.DataSourceUtils.doGetConnection(DataSourceUtils.java:117) ~[!/:?] at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:80) ~[!/:?] ... 15 more </code> Karaf Bundles list <code>karaf@root()>; bundle:list START LEVEL 100 , List Threshold: 50 ID │ State │ Lvl │ Version │ Name ────┼──────────┼─────┼────────────────┼─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── 32 │ Active │ 80 │ 4.4.1 │ Apache Karaf :: OSGi Services :: Event 59 │ Active │ 50 │ 3.19.0 │ camel-api 60 │ Active │ 50 │ 3.19.0 │ camel-base 61 │ Active │ 50 │ 3.19.0 │ camel-base-engine 62 │ Active │ 50 │ 3.19.0 │ camel-bean 63 │ Active │ 50 │ 3.19.0 │ camel-browse 64 │ Active │ 50 │ 3.19.0 │ camel-cloud 65 │ Active │ 50 │ 3.19.0 │ camel-cluster 66 │ Active │ 50 │ 3.19.0 │ camel-console 67 │ Active │ 50 │ 3.19.0 │ camel-controlbus 68 │ Active │ 50 │ 3.19.0 │ camel-core-catalog 69 │ Active │ 50 │ 3.19.0 │ camel-core-engine 70 │ Active │ 50 │ 3.19.0 │ camel-core-languages 71 │ Active │ 50 │ 3.19.0 │ camel-core-model 72 │ Active │ 50 │ 3.19.0 │ camel-core-processor 73 │ Active │ 50 │ 3.19.0 │ camel-core-reifier 74 │ Active │ 50 │ 3.19.0 │ camel-core-xml 75 │ Active │ 50 │ 3.19.0 │ camel-dataformat 76 │ Active │ 50 │ 3.19.0 │ camel-dataset 77 │ Active │ 50 │ 3.19.0 │ camel-direct 78 │ Active │ 50 │ 3.19.0 │ camel-directvm 79 │ Active │ 50 │ 3.19.0 │ camel-file 80 │ Active │ 50 │ 3.19.0 │ camel-health 81 │ Active │ 50 │ 3.19.0 │ camel-language 82 │ Active │ 50 │ 3.19.0 │ camel-log 83 │ Active │ 50 │ 3.19.0 │ camel-main 84 │ Active │ 50 │ 3.19.0 │ camel-management 85 │ Active │ 50 │ 3.19.0 │ camel-management-api 86 │ Active │ 50 │ 3.19.0 │ camel-mock 87 │ Active │ 50 │ 3.19.0 │ camel-ref 88 │ Active │ 50 │ 3.19.0 │ camel-rest 89 │ Active │ 50 │ 3.19.0 │ camel-saga 90 │ Active │ 50 │ 3.19.0 │ camel-scheduler 91 │ Active │ 50 │ 3.19.0 │ camel-seda 92 │ Active │ 50 │ 3.19.0 │ camel-stub 93 │ Active │ 50 │ 3.19.0 │ camel-support 94 │ Active │ 50 │ 3.19.0 │ camel-timer 95 │ Active │ 50 │ 3.19.0 │ camel-tooling-model 96 │ Active │ 50 │ 3.19.0 │ camel-util 97 │ Active │ 50 │ 3.19.0 │ camel-util-json 98 │ Active │ 50 │ 3.19.0 │ camel-validator 99 │ Active │ 50 │ 3.19.0 │ camel-vm 100 │ Active │ 50 │ 3.19.0 │ camel-xml-io-util 101 │ Active │ 50 │ 3.19.0 │ camel-xml-jaxb 102 │ Active │ 50 │ 3.19.0 │ camel-xml-jaxp 103 │ Active │ 50 │ 3.19.0 │ camel-xpath 104 │ Active │ 50 │ 3.19.0 │ camel-xslt 105 │ Active │ 50 │ 3.19.0 │ camel-blueprint 106 │ Active │ 80 │ 3.19.0 │ camel-commands-core 107 │ Active │ 50 │ 3.19.0 │ camel-core-osgi 108 │ Active │ 80 │ 3.19.0 │ camel-karaf-commands 120 │ Active │ 50 │ 3.1.1.SNAPSHOT │ com.github.ben-manes.caffeine 121 │ Active │ 50 │ 3.19.0 │ camel-sql 146 │ Active │ 80 │ 2.13.0 │ Jackson-annotations 147 │ Active │ 80 │ 2.13.0 │ Jackson-core 148 │ Active │ 80 │ 2.13.0 │ jackson-databind 155 │ Active │ 80 │ 2.9.0 │ Apache Commons DBCP 156 │ Active │ 80 │ 2.9.0 │ Apache Commons Pool 159 │ Active │ 50 │ 3.19.0 │ camel-paho 160 │ Active │ 50 │ 1.2.5 │ org.eclipse.paho.client.mqttv3 177 │ Resolved │ 80 │ 1.0.0.SNAPSHOT │ camel-jdbc-to-mqtt </code> Data source section from blueprint.xml <code> <bean id=';dataSourceBean'; class=';org.apache.commons.dbcp2.BasicDataSource'; destroy-method=';close';>; <property name=';driverClassName'; value=';org.mariadb.jdbc.Driver';/>; <property name=';url'; value=';jdbc:mariadb://localhost:3306/test-db';/>; <property name=';username'; value=';demouser';/>; <property name=';password'; value=';1demo1';/>; </bean>; </code> Dependencies and plugins from POM <code> <dependencyManagement>; <dependencies>; <!-- Camel BOM -->; <dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-bom</artifactId>; <version>;3.19.0</version>; <scope>;import</scope>; <type>;pom</type>; </dependency>; <dependency>; <groupId>;org.apache.camel.karaf</groupId>; <artifactId>;camel-karaf-bom</artifactId>; <version>;3.19.0</version>; <type>;pom</type>; <scope>;import</scope>; </dependency>; </dependencies>; </dependencyManagement>; <dependencies>; <!-- DB connectivity -->; <dependency>; <groupId>;org.mariadb.jdbc</groupId>; <artifactId>;mariadb-java-client</artifactId>; <version>;3.0.8</version>; </dependency>; <dependency>; <groupId>;org.apache.commons</groupId>; <artifactId>;commons-dbcp2</artifactId>; <version>;2.9.0</version>; </dependency>; <!-- Camel -->; <dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-core</artifactId>; </dependency>; <dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-sql</artifactId>; </dependency>; <dependency>; <groupId>;org.apache.camel.karaf</groupId>; <artifactId>;camel-blueprint</artifactId>; </dependency>; <dependency>; <groupId>;org.apache.camel.karaf</groupId>; <artifactId>;camel-blueprint-main</artifactId>; </dependency>; <dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-paho</artifactId>; </dependency>; <!-- Testing -->; <dependency>; <groupId>;org.apache.camel.karaf</groupId>; <artifactId>;camel-test-blueprint</artifactId>; <scope>;test</scope>; </dependency>; <!-- logging -->; <dependency>; <groupId>;org.apache.logging.log4j</groupId>; <artifactId>;log4j-slf4j-impl</artifactId>; <scope>;runtime</scope>; </dependency>; <!-- JSON processing -->; <dependency>; <groupId>;com.fasterxml.jackson.core</groupId>; <artifactId>;jackson-databind</artifactId>; <version>;2.13.0</version>; </dependency>; <dependency>; <groupId>;com.fasterxml.jackson.core</groupId>; <artifactId>;jackson-core</artifactId>; <version>;2.13.0</version>; </dependency>; </dependencies>; <build>; <plugins>; <!-- compiler plugin -->; <plugin>; <groupId>;org.apache.maven.plugins</groupId>; <artifactId>;maven-compiler-plugin</artifactId>; <version>;3.10.1</version>; <configuration>; <release>;11</release>; </configuration>; </plugin>; <plugin>; <groupId>;org.apache.maven.plugins</groupId>; <artifactId>;maven-resources-plugin</artifactId>; <version>;3.2.0</version>; <configuration>; <encoding>;UTF-8</encoding>; </configuration>; </plugin>; <!-- to generate the MANIFEST.MF of the bundle -->; <plugin>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-bundle-plugin</artifactId>; <version>;3.19.0</version>; <extensions>;false</extensions>; <executions>; <execution>; <id>;bundle-manifest</id>; <phase>;prepare-package</phase>; <goals>; <goal>;manifest</goal>; </goals>; </execution>; </executions>; </plugin>; <!-- to include MANIFEST.MF in the bundle -->; <plugin>; <groupId>;org.apache.maven.plugins</groupId>; <artifactId>;maven-jar-plugin</artifactId>; <version>;3.2.0</version>; <configuration>; <archive>; <manifestFile>;${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>; </archive>; </configuration>; </plugin>; <!-- to run the example using mvn camel-karaf:run -->; <plugin>; <groupId>;org.apache.camel.karaf</groupId>; <artifactId>;camel-karaf-maven-plugin</artifactId>; <version>;3.19.0</version>; </plugin>; </plugins>; </build>;</code> | You need to install the driver inside karaf, the reason your route do not start up is because does not find the driver for your data source. Install the driver like <code>bundle:install -s mvn:org.mariadb.jdbc/mariadb-java-client:3.0.8 </code> Then enable the resulting bundle as dynamic import like <code>bundle:dynamic-import ${bundleId} </code> May be it should be necessary to enable dynamic import to your route. Then restart your route and it should work! hope this helps |
apache-camel | I am working with <code>camel-mail-starter</code> version <code>3.12.0</code> I have configured the route this way: <code>String from = protocol + ';://'; + host + ';:'; + port + ';?username='; + username + ';&;password='; + password + ';&;delete='; + removeAfterConsuming + ';&;mail.pop3.starttls.enable=true&;debugMode=true';; RouteBuilder emailListener = new RouteBuilder () { @Override public void configure() throws Exception { from (from) .process (new EmailProcessor (body, client)) .log(';${exchange.message}';); } }; </code> My Processor <code>public void process(Exchange exchange) throws Exception { MailMessage message = exchange.getIn(MailMessage.class); MimeMessageParser parser = new MimeMessageParser( (IMAPMessage) message.getOriginalMessage() ); try { parser.parse(); } catch (Exception e) { ApplicationException applicationException = new ApplicationException( e.getStackTrace(), Collections.singletonMap(';process';, '; Inside camel mail';), getClass(), ';33'; ); applicationException.notifyViaEmail(); } } </code> When I run this, I get the following exception <code>Caused by: org.apache.camel.component.bean.AmbiguousMethodCallException: Ambiguous method invocations possible: [public abstract org.apache.camel.Message org.apache.camel.Exchange.getMessage(), public abstract java.lang.Object org.apache.camel.Exchange.getMessage(java.lang.Class)] on the exchange: Exchange[166D4FAD964C49D-0000000000000000] </code> I don't know what I am doing wrong | Your mistake is in the simple language expression used in the log EIP, indeed the expression <code>${exchange.message}</code> asks Camel to call dynamically the method <code>getMessage</code> on the current exchange but as mentioned in the error message, there are 2 existing methods called <code>getMessage</code> in <code>Exchange</code> which are <code>getMessage()</code> and <code>getMessage(java.lang.Class)</code> and Camel has no way to know which one to call which causes this specific exception. I don't know what you wanted to log but if it is the body of your message the expected expression is rather <code>${body}</code>. Please refer to the doc about the simple language for more details. |
apache-camel | I'm currently upgrading Camel from <code>3.2.0</code> to <code>3.18.0</code>. On the <code>3.17.0</code> release, <code>camel-beanio</code> was removed (https://camel.apache.org/manual/camel-3x-upgrade-guide-3_17.html). I didn't see why it was removed nor how to replace it on https://camel.apache.org/manual. I know I can declare the dependency for <code>camel-beanio</code> in my <code>pom.xml</code> but I don't want to have a camel version of <code>3.18.0</code> and camel-beanio of <code>3.16.0</code>. Any clue ? Thanks | Since Camel 4.4 BeanIO is available again: https://camel.apache.org/components/4.4.x/dataformats/beanio-dataformat.html |
apache-camel | I'm having trouble to pass a list of string I'm getting back from my bean to my sql-component query to make a call to the database. <code><bean ref=';fo'; method=';transformTo(${body})'; />; </code> So in this upper line of code I'm taking data from the body that is an xml and transform it to json. <code><bean ref=';fot'; method=';getOTs(${body})'; />; </code> Then I'm extracting the part I want from the json and return a list of string (method signature) : <code>public List<String>; getOTs(String jsonOTs) </code> Now the part that isn't working (I'm getting that one parameter is expected but there are a couple each time) <code><to uri=';sql:insert into dbo.table_example (OT) VALUES :#body;';/>; </code> My goal is quite simple, retrieving a list of string from my bean (working) and making and an insert into query. I have only one parameter but multiple values. Example: <code>INSERT INTO table_name (column_list) VALUES (value_list_1), (value_list_2), ... (value_list_n); </code> Example taken from here | Bulk insert For a bulk insert, you need to set the query parameter <code>batch</code> to <code>true</code>, this way, Camel will understand that you want to insert several rows in one batch. Here is the corresponding <code>to</code> endpoint in your case: <code><to uri=';sql:insert into dbo.table_example (OT) VALUES (#)?batch=true';/>; </code> Miscellaneous remarks Actually, for all the use cases that you listed above, you have no need to explicitly refer to the body. Indeed, in the case of a bean, you could only specify the method to invoke, Camel is able to inject the body as a parameter of your method and automatically converts it into the expected type which is <code>String</code> in your case. Refers to https://camel.apache.org/manual/bean-binding.html#_parameter_binding for more details. Regarding the SQL producer, assuming that you did not change the default configuration, the proper way is to rather use the placeholder that is <code>#</code> by default, Camel will automatically use the content of the body as parameters of the underlying <code>PreparedStatement</code>. So you should retry with: <code><to uri=';sql:insert into dbo.table_example (OT) VALUES (#)';/>; </code> If you really want to explicitly refer to the body in your query, you can rather use <code>:#${body}</code> as next: <code><to uri=';sql:insert into dbo.table_example (OT) VALUES (:#${body})';/>; </code> Misuse of named parameter If you only use <code>#body</code> as you did, Camel interprets it as a named parameter so it will try to get the value from the body if it is a map by getting the value of the key <code>body</code> otherwise it will try to get the value of the header <code>body</code> but in your case, there are no such values, therefore, you end up with an error of type <code>Cannot find key [body] in message body or headers to use when setting named parameter in query [insert into developers (name) values :?body;] on the exchange </code> |
apache-camel | I tried unit testing Apache Camel and I started out with a real basic case where my route looks like that: <code>public class TestRoute extends RouteBuilder { @Override public void configure() throws Exception { from(';jpa:Data';).to(';jpa:Data';).id(';testId';); } } </code> Now the following approach didn't work. I tried mocking all endpoints, however I'm getting <code>mock://jpa:Data Received message count. Expected: <1>; but was: <0>;</code> <code>public class RouteTest extends CamelTestSupport { @Override @BeforeEach public void setUp() throws Exception { super.setUp(); } @Override protected RoutesBuilder createRouteBuilder() throws Exception { return new TestRoute(); } @Override public boolean isUseAdviceWith() { return true; } @Test void testRoute() throws Exception { AdviceWith.adviceWith(context, null, false, a ->; { a.replaceFromWith(';direct:start';); a.mockEndpointsAndSkip(';*';); }); context.start(); // The false here makes sure that I get an exception if I'm using a name // of a nonexistent mocked endpoint, so that shouldn't be the problem here getMockEndpoint(';mock:jpa:Data';, false).expectedMessageCount(1); var data = getSomeTestData(); template.sendBody(';direct:start';, data); assertMockEndpointsSatisfied(); } } </code> A workaround I found is replacing <code>a.mockEndpointsAndSkip(';*';);</code> with <code>a.weaveById(';testId';).replace().to(';mock:jpa:Data';);</code>. However I'm unsure what's the difference in this case, considering <code>mockEndpointsAndSkip</code> should also replace all endpoints with a mocked version. It would be a bit troublesome to replace ALL endpoints in a real scenario manually. | That is due to the fact that by using <code>*</code> as pattern for the URI of endpoints to mock, you also include your from endpoint <code>direct:start</code> which implies that it is mocked too consequently the message is not transmitted to the rest of the route, therefore <code>mock:jpa:Data</code> doesn't receive any message. Use a more specific pattern that matches only with your to endpoint like <code>jpa:Data</code>. FYI, you can simplify your code by leveraging existing methods such as <code>replaceRouteFromWith</code> and <code>isMockEndpointsAndSkip</code> as next: <code>@Override @BeforeEach public void setUp() throws Exception { // The new from endpoint for the route ';testId'; replaceRouteFromWith(';testId';, ';direct:start';); super.setUp(); }@Override protected RoutesBuilder createRouteBuilder() throws Exception { return new TestRoute(); }@Override public String isMockEndpointsAndSkip() { // The pattern of the URI of endpoints to mock return ';jpa:Data';; }@Test void testRoute() throws Exception { MockEndpoint mockEndpoint = getMockEndpoint(';mock:jpa:Data';) mockEndpoint.expectedMessageCount(1); var data = getSomeTestData(); template.sendBody(';direct:start';, data); mockEndpoint.assertIsSatisfied(); } </code> |
apache-camel | I have just started working around the Apache Camel. I have a requirement to implement an FTP/FTPS/SFTP client, which would be used to fetch the files from the respective servers. I was looking into the possibility of using Apache Camel to do this but I am still confused after going through the examples and the tutorials. The requirement is to fetch the files from the FTP/SFTP servers when the request is received from the scheduler. Following is the route created using EndPoint-DSL <code>@Component public class FtpReceiveRoute extends EndpointRouteBuilder {@Override public void configure() throws Exception { from( ftp(';localhost:2001/home/admin';) .account(';admin';) .password(';admin12345';) .recursive(true) ) .routeId(';ftpReceive';) .log(';From done!';) .to(';log:ftp-log';) .log(';To done!!';); } </code> } I am trying to use the above route by invoking it when the request is made to fetch the file like below. <code>@Override protected FtpResponse doMessage(String param, FtpRequest req) { FtpResponse response = new FtpResponse (); CamelContext ctx = new DefaultCamelContext(); ctx.addRoutes(##route); //FtpReceiveRoute, add the Routebuilder instance as EndpointRouteBuilder is acceptable. ctx.start(); //Might need to induce sleep so that all the files are downloaded ctx.stop(); return response; } </code> The confusion is around how to invoke the Camel process with the route. I have used EndpointRouteBuilder to create the route because of the type-safe creation of the endpoint URI. I am not getting an option to add this route to the CamelContext as it expects the RouteBuilder instance which is not type-safe. Further, the CamelContext is the engine and to invoke the route I would need to start and stop this engine. This I am not able to digest if I need to start and stop the engine to execute a route then I would need to induce some sleep in between so that all files are downloaded. Just to add there are more routes that I need to add with the implementation. Once the engine is started it would load and execute all the added routes which is not the requirement. Maybe I am not getting how to use this properly. Any resources aiding my situation are welcome. Thanks. | You should not create and start new camel context every time you want to fetch file from server. What you should do instead is start one when your application starts and use that for all your exchanges. You can use Spring-boot to initialize CamelContext and add annotated RouteBuilders to it automatically. Check the maven archetype camel-archetype-spring-boot for example. If you want to call camel routes from Java you can Inject CamelContext to your bean and use it to create ProducerTemplate. This can be used to invoke Routes defined in the RouteBuilder. Using <code>ProducerTemplate.send</code> you can get the resulting exchange. Using producer template Using File-component which works very similary to ftp-component. <code>package com.example;import org.apache.camel.builder.endpoint.EndpointRouteBuilder; import org.springframework.stereotype.Component;@Component public class MySpringBootRouter extends EndpointRouteBuilder { @Override public void configure() { from(direct(';fileFromFTP';)) .routeId(';fileFromFTP';) // reads files from <project>;/input using file consumer endpoint .pollEnrich(file(';input';), 1000) // If file is found, convert body to string. // Which in this case will read contents of the file to string. .filter(body().isNotNull()) .convertBodyTo(String.class) .end() ; } } </code> <code>package com.example;import org.apache.camel.CamelContext; import org.apache.camel.Exchange; import org.apache.camel.ProducerTemplate; import org.apache.camel.support.DefaultExchange; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled;import static org.apache.camel.builder.endpoint.StaticEndpointBuilders.direct;@Configuration @EnableScheduling public class MySpringBean { @Autowired CamelContext camelContext; @Scheduled(fixedRate = 1000) public void scheduledTask() { System.out.println(';Scheduled Task!';); if(camelContext.isStopped()) { System.out.println(';Camel context not ready yet!';); return; } useProducerTemplate(); } public void useProducerTemplate(){ ProducerTemplate producerTemplate = camelContext.createProducerTemplate(); Exchange inExchange = new DefaultExchange(camelContext); //synchronous call! Exchange result = producerTemplate.send(direct(';fileFromFTP';).toString(), inExchange); String resultBody = result.getMessage().getBody(String.class); String fileName = result.getMessage().getHeader(Exchange.FILE_NAME, String.class); if(resultBody != null){ System.out.println(';Consumed file: ';+ fileName + '; contents: '; + resultBody.toString()); } else{ System.out.println(';No file to consume!';); } } } </code> Depending on what you need to do with the files you could probably do that inside camel route. Then you would only need to call the producerTemplate.sendBody. <code> public void useProducerTemplate(){ ProducerTemplate producerTemplate = camelContext.createProducerTemplate(); Exchange inExchange = new DefaultExchange(camelContext); producerTemplate.sendBody(direct(';fileFromFTP';).toString(), inExchange); } </code> Starting stopping camel route If you want to start polling file consumer only for a short while you can do start the route and use for example aggregation timeout to shutdown the route when no new files have been received in any given duration. <code>@Component public class MySpringBootRouter extends EndpointRouteBuilder { @Override public void configure() { AggregationStrategy aggregateFileNamesStrategy = AggregationStrategies .flexible(String.class) .accumulateInCollection(ArrayList.class) .pick(header(Exchange.FILE_NAME)) ; from(file(';input';)) .routeId(';moveFilesRoute';) .autoStartup(false) .to(file(';output';)) .to(seda(';moveFilesRouteTimeout';)); ; from(seda(';moveFilesRouteTimeout';)) .routeId(';moveFilesRouteTimeout';) .aggregate(constant(true), aggregateFileNamesStrategy) .completionTimeout(3000) .log(';Consumed files: ${body.toString()}';) .process(exchange ->; { exchange.getContext().getRouteController().stopRoute(';moveFilesRoute';); }) .end() ; } } </code> <code>public void startMoveFilesRoute() { try { System.out.println(';Starting moveFilesRoute!';); camelContext.getRouteController().startRoute(';moveFilesRoute';); //Sending null body moveFilesRouteTimeout to trigger timeout if there are no files to transfer camelContext.createProducerTemplate().sendBody(seda(';moveFilesRouteTimeout';).toString(), null); } catch(Exception e) { System.out.println(';failed to stop route. '; + e); } } </code> |
apache-camel | I use Apache Camel 3.18.2 witch camel-main. To create a fat-jar I configured the following two plugins within my pom.xml: <code> <plugin>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-maven-plugin</artifactId>; <version>;3.18.2</version>; <executions>; <execution>; <phase>;package</phase>; <goals>; <goal>;prepare-fatjar</goal>; </goals>; </execution>; </executions>; </plugin>; <plugin>; <groupId>;org.apache.maven.plugins</groupId>; <artifactId>;maven-assembly-plugin</artifactId>; <configuration>; <archive>; <manifest>; <mainClass>;de.powerstat.camel.homeautomation.MainApp</mainClass>; </manifest>; </archive>; </configuration>; <executions>; <execution>; <id>;make-assembly</id>; <phase>;package</phase>; <goals>; <goal>;single</goal>; </goals>; </execution>; </executions>; </plugin>; </code> As dependecies I have: <code><dependencies>; <dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-core</artifactId>; </dependency>; <dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-main</artifactId>; </dependency>; <dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-test</artifactId>; <scope>;test</scope>; </dependency>; <dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-netty</artifactId>; </dependency>; <dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-stream</artifactId>; </dependency>; <dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-paho</artifactId>; </dependency>; <dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-quartz</artifactId>; </dependency>; <dependency>; <groupId>;de.powerstat.camel.component</groupId>; <artifactId>;camel-fbaha</artifactId>; <version>;1.0-SNAPSHOT</version>; </dependency>; <dependency>; <groupId>;de.powerstat.camel.component</groupId>; <artifactId>;camel-fbtr64</artifactId>; <version>;1.0-SNAPSHOT</version>; </dependency>; <dependency>; <groupId>;org.openmuc</groupId>; <artifactId>;jsml</artifactId>; <version>;1.1.2</version>; </dependency>; <dependency>; <groupId>;org.apache.logging.log4j</groupId>; <artifactId>;log4j-api</artifactId>; <version>;2.18.0</version>; <scope>;runtime</scope>; </dependency>; <dependency>; <groupId>;org.apache.logging.log4j</groupId>; <artifactId>;log4j-core</artifactId>; <version>;2.18.0</version>; <scope>;runtime</scope>; </dependency>; <dependency>; <groupId>;org.apache.logging.log4j</groupId>; <artifactId>;log4j-slf4j-impl</artifactId>; <version>;2.18.0</version>; <scope>;runtime</scope>; </dependency>;</dependencies>; </code> But durin running mvn clean install I got: <code>[INFO] --- camel-maven-plugin:3.18.2:prepare-fatjar (default) @ myhome --- [INFO] Found 5 Camel type converter loaders from project classpath [INFO] [INFO] --- maven-assembly-plugin:2.2-beta-5:single (make-assembly) @ myhome --- [INFO] ------------------------------------------------------------------------ [INFO] BUILD FAILURE [INFO] ------------------------------------------------------------------------ [ERROR] Failed to execute goal org.apache.maven.plugins:maven-assembly-plugin:2.2-beta-5:single (make-assembly) on project myhome: Error reading assemblies: No assembly descriptors found. ->; [Help 1][ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException Exception in thread ';ivy-httpclient-shutdown-handler'; java.lang.NoClassDefFoundError: org/apache/http/impl/conn/PoolingHttpClientConnectionManager$2 at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.shutdown(PoolingHttpClientConnectionManager.java:413) at org.apache.http.impl.client.HttpClientBuilder$2.close(HttpClientBuilder.java:1244) at org.apache.http.impl.client.InternalHttpClient.close(InternalHttpClient.java:201) at org.apache.ivy.util.url.HttpClientHandler.close(HttpClientHandler.java:357) at org.apache.ivy.util.url.HttpClientHandler$1.run(HttpClientHandler.java:84) at java.base/java.lang.Thread.run(Thread.java:833) Caused by: java.lang.ClassNotFoundException: org.apache.http.impl.conn.PoolingHttpClientConnectionManager$2 at org.codehaus.plexus.classworlds.strategy.SelfFirstStrategy.loadClass(SelfFirstStrategy.java:50) at org.codehaus.plexus.classworlds.realm.ClassRealm.unsynchronizedLoadClass(ClassRealm.java:271) at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass(ClassRealm.java:247) at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass(ClassRealm.java:239) ... 6 more </code> That looks to me like this is an implicit dependency that have not been added by the camel-maven-plugin. So my question is how to solve this problem? I also tried to use the maven-shade-plugin instead of maven-assembly-plugin: <code> <plugin>; <groupId>;org.apache.maven.plugins</groupId>; <artifactId>;maven-shade-plugin</artifactId>; <version>;3.4.0</version>; <executions>; <execution>; <phase>;package</phase>; <goals>; <goal>;shade</goal>; </goals>; <configuration>; <createDependencyReducedPom>;true</createDependencyReducedPom>; <filters>; <filter>; <artifact>;*:*</artifact>; <excludes>; <exclude>;META-INF/*.SF</exclude>; <exclude>;META-INF/*.DSA</exclude>; <exclude>;META-INF/*.RSA</exclude>; </excludes>; </filter>; </filters>; </configuration>; </execution>; </executions>; </plugin>; </code> Which then results in a fat-jar with the following exception during executing it: <code>[ERROR] 2022-09-30T22:04:48,426 15612/22 org.apache.camel.processor.errorhandler.DefaultErrorHandler Failed delivery for (MessageId: 08B251E5AD78E72-0000000000000000 on ExchangeId: 08B251E5AD78E72-0000000000000000). Exhausted after delivery attempt: 1 caught: org.apache.camel.InvalidPayloadException: No body available of type: java.lang.Integer but has type: java.lang.String on: Message. Caused by: No type converter available to convert from type: java.lang.String to the required type: java.lang.Integer. Exchange[]. Caused by: [org.apache.camel.NoTypeConversionAvailableException - No type converter available to convert from type: java.lang.String to the required type: java.lang.Integer] </code> So it looks the shade-plugin creates a fat-jar but missed something of camels dependencies. Maybe this could be solved in one or the other way? Last but not least the main question is how to create a Camel3 fat jar that is complete and works correctly? | Based on the error messageError reading assemblies: No assembly descriptors found.It looks like you are missing your assembly descriptor. You'll need to define a descriptor or descriptorRef <code>descriptor</code> example: <code><project>; [...] <build>; [...] <plugins>; <plugin>; <artifactId>;maven-assembly-plugin</artifactId>; <version>;3.4.2</version>; <configuration>; <descriptors>; <descriptor>;src/assembly/src.xml</descriptor>; </descriptors>; </configuration>; [...] </project>; </code> <code>descriptorRef</code> example: <code><project>; [...] <build>; [...] <plugins>; <plugin>; <!-- NOTE: We don't need a groupId specification because the group is org.apache.maven.plugins ...which is assumed by default. -->; <artifactId>;maven-assembly-plugin</artifactId>; <version>;3.4.2</version>; <configuration>; <descriptorRefs>; <descriptorRef>;jar-with-dependencies</descriptorRef>; </descriptorRefs>; </configuration>; [...] </project>; </code> If defining a <code>descriptor</code>, see the this about the descriptor format. |
apache-camel | Can we use <code>body().xtokenize</code> as predicate of <code>choice()</code> in Camel pipeline for routing when XML type matches the path we want? I tried it but doesn't filter in accordance with the predicate : This is the code snippet : <code> Namespaces ns = new Namespaces(';ns1';, ';http://standards.iso.org/iso/15143/-3';); .choice().when(body().xtokenize(';/ns1:Links';, 'i', ns)) </code> These are the type of XML content that I would like to route according to the name of the root element: <code><Links xmlns=';http://standards.iso.org/iso/15143/-3';>; <rel>;last</rel>; <href>;https://[source domain name]/public/api/aemp/v2/15143/-3/Fleet/Equipment/ID/[equipment id]/Locations/2021-01-01T00:00/2022-09-29T12:52:12.519982300/1 </href>; </Links>; </code> Or <code><Location datetime=';2022-04-05T09:52:53Z';>; <Latitude>;43.290143</Latitude>; <Longitude>;5.491987</Longitude>; <Altitude>;102.375</Altitude>; <AltitudeUnits>;metre</AltitudeUnits>; </Location>; </code> Thank you for your help. | The XML Tokenize language is not really meant to be used as a predicate, you should rather use another language like the XPath language for example. Your Content Based Router could test the local name of the root element to route your messages as next: <code>.choice() .when().xpath(';/*[local-name()='Links']';) .log(';Link detected ${body}';) .when().xpath(';/*[local-name()='Location']';) .log(';Location detected ${body}';) .otherwise() .log(';Unknown ${body}';); </code> |
apache-camel | I am trying to set up a route for ahc My requirements:the target http(s) url is passed as a previous header/property I have cases where <code>throwExceptionOnFailure</code> needs to be set to true and others to false. I want that query parameters passed in to my route remain forwarded to the target.I am setting the properties previous in other routes as follows: <code>// sample path for this case. this is built based on other factors String basePath = ';http://my.service:8080/test/api/dir'; //... .setHeader(HEADER_FOR_ROUTE_PATH, constant(basePath)) .setHeader(HEADER_FOR_THROW_EXCEPTION, declaration.is4xxResponseCodeAllowed() ? constant(';false';) : constant(';true';) </code> and I have tried the following routes to try to handle this: <code> from(';direct:myroute';) .setHeader(Exchange.HTTP_URI, simple(';${header.%s}?bridgeEndpoint=true&;throwExceptionOnFailure=${header.%s}';.formatted(HEADER_FOR_ROUTE_PATH, HEADER_FOR_THROW_EXCEPTION) .to(';ahc:http://oldhost';); </code> <code> from(';direct:myroute';) .setHeader(Exchange.HTTP_URI, simple(';${header.%s}';.formatted(HEADER_FOR_ROUTE_PATH) .setHeader(Exchange.HTTP_QUERY, simple(';bridgeEndpoint=true&;throwExceptionOnFailure=${header.%s}';formatted(HEADER_FOR_THROW_EXCEPTION)) .to(';ahc:http://oldhost';); </code> (and in this case the throwsExceptionOnFailure is hardcoded but i created separate routes to distinguish this. <code> from(';direct:myroute';) .setHeader(Exchange.HTTP_URI, simple(';${header.%s}';.formatted(HEADER_FOR_ROUTE_PATH) .to(';ahc:http://oldhost?bridgeEndpoint=true&;throwExceptionOnFailure=false';); </code> and all seem to have some issues amongst:Source query parameters not forwarded bridgeEndpoint / throwExceptionOnFailure being ignored (so it tries to go to ';oldhost'; rather than ';my.service';How can i get this scenario to work please as I'm struggling to find any information on how i can set this. | The solution was as follows: <code> from(';direct:myroute';) .setHeader(Exchange.HTTP_URI, simple(';${header.%s}';.formatted(HEADER_FOR_ROUTE_PATH) .to(';ahc:http://oldhost?bridgeEndpoint=false&;throwExceptionOnFailure=false';); </code> since in this case the HTTP_URI is ovverriden, the bridgeEndpoint flag should be false |
apache-camel | I am able to send message to a specific subscription of azure service bus topic using apache camel using example here https://camel.apache.org/components/3.18.x/azure-servicebus-component.html#_azure_servicebus_producer_operations. But i cannot get the properties set up with my code. below my code - <code> from(';direct:start';) .id(';producerId';) .marshal(new JacksonDataFormat(String.class)) .process(exchange ->; { exchange.setProperty(ServiceBusConstants.SUBJECT, constant(';test';)); }) .setProperty(';subject';, constant(';test';)) .setProperty(ServiceBusConstants.CORRELATION_ID, constant(';111111';)) .setHeader(';subject';, constant(';test';)) .setHeader(';label';, constant(';test';)) .setHeader(ServiceBusConstants.SUBJECT, constant(';test';)) .to(';azure-servicebus:testTopic?serviceBusType=topic&;subscriptionName=testTopic-subscription&;producerOperation=sendMessages&;connectionString=RAW(Endpoint=sb://blablablablbalabla';) .log(LoggingLevel.INFO, ';Message sent to test topic ${body} and ${headers}';) .setRouteProperties(propertyDefinitions); </code> as you see above i have tried with everything such as with ';setProperty'; and ';setHeader'; different way. i get below response- <code>Message sent to test topic ';{\';accountId\';: \';4471112323123\';, \';url\';: \';test.com\';, \';status\';: \';PASS\';, \';statusMessage\';: \';check if received\';}'; and {applicationProperties={label: test}, CamelAzureServiceBusApplicationProperties={Label=test, Subject=test}, CamelAzureServiceBusSubject=test, Content-Type=application/json} </code> This is my producer code- <code>Test test = new test(uuid, ';test.com';, ';PASS';, ';check if received';); ProducerTemplate producerTemplate; producerTemplate.sendBody(direct:start, test.toString()); </code> I have sent a message through azure portal(ui) and this is what looks like the properties:if you see ';subject'; is ';test'; and there is a custom property ';test'; that has value ';test';. I want to see the same thing when i use apache camel to send it. Please help. Thanks | Today it's not possible with the latest version of Camel, however it will be shipped in the next release. Relevant ticket : https://issues.apache.org/jira/browse/CAMEL-18459 Code : https://github.com/apache/camel/blob/main/components/camel-azure/camel-azure-servicebus/src/main/java/org/apache/camel/component/azure/servicebus/ServiceBusProducer.java And this is how it will look like : <code>from(';timer:foo1?period=15000&;delay=1000';) .process(new Processor() { @Override public void process(Exchange exchange) throws Exception { exchange.getIn().setBody(';{\';message\';:\';hello\';}';); exchange.getIn().setHeader(ServiceBusConstants.APPLICATION_PROPERTIES, Map.of(';prop1';, ';value1';)); } }) .to(';azure-servicebus:demo?serviceBusType=topic&;connectionString=RAW(connection-string-here';); </code> |
apache-camel | I'm trying to run a simple Camel route using Quartz component to schedule a job. In this example is like an hello word every minute. This is the example route: <code>public void configure() throws Exception { from(';quartz://myname?cron=0+ *+ *+ ?+ *+ *';) .to(';log:hello';); } </code> When I run the application I get the following error: <code> An attempt was made to call a method that does not exist. The attempt was made from the following location:org.apache.camel.component.quartz.QuartzComponent.createEndpoint(QuartzComponent.java:150) The following method did not exist:'org.quartz.Trigger org.quartz.Scheduler.getTrigger(java.lang.String, java.lang.String)' The method's class, org.quartz.Scheduler, is available from the following locations:jar:file:/C:/Users/andre/.m2/repository/org/quartz-scheduler/quartz/2.3.2/quartz-2.3.2.jar!/org/quartz/Scheduler.class The class hierarchy was loaded from the following locations:org.quartz.Scheduler: file:/C:/Users/andre/.m2/repository/org/quartz-scheduler/quartz/2.3.2/quartz-2.3.2.jar Action: Correct the classpath of your application so that it contains a single, compatible version of org.quartz.Scheduler </code> But actually I don't get how I should correct the classpath of my application. This is the pom.xml: <code><?xml version=';1.0'; encoding=';UTF-8';?>; <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.mycompany</groupId>; <artifactId>;camel-ose-springboot-xml</artifactId>; <version>;1.0.0-SNAPSHOT</version>; <name>;Fabric8 :: Quickstarts :: Spring-Boot :: Camel XML</name>; <description>;Spring Boot example running a Camel route defined in XML</description>; <properties>; <maven-surefire-plugin.version>;2.22.2</maven-surefire-plugin.version>; <project.build.sourceEncoding>;UTF-8</project.build.sourceEncoding>; <maven-compiler-plugin.version>;3.8.1</maven-compiler-plugin.version>; <docker.image.version>;1.9</docker.image.version>; <project.reporting.outputEncoding>;UTF-8</project.reporting.outputEncoding>; <fuse.version>;7.11.0.fuse-sb2-7_11_0-00028-redhat-00001</fuse.version>; </properties>; <dependencyManagement>; <dependencies>; <dependency>; <groupId>;org.jboss.redhat-fuse</groupId>; <artifactId>;fuse-springboot-bom</artifactId>; <version>;7.11.0.fuse-sb2-7_11_0-00028-redhat-00001</version>; <type>;pom</type>; <scope>;import</scope>; </dependency>; </dependencies>; </dependencyManagement>; <dependencies>; <dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-spring-boot-starter</artifactId>; </dependency>; <dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-quartz</artifactId>; <!-- use the same version as your Camel core version -->; </dependency>; <dependency>; <groupId>;com.sun.xml.bind</groupId>; <artifactId>;jaxb-impl</artifactId>; </dependency>; <dependency>; <groupId>;org.springframework.boot</groupId>; <artifactId>;spring-boot-starter-web</artifactId>; <exclusions>; <exclusion>; <groupId>;org.springframework.boot</groupId>; <artifactId>;spring-boot-starter-tomcat</artifactId>; </exclusion>; </exclusions>; </dependency>; <dependency>; <groupId>;org.springframework.boot</groupId>; <artifactId>;spring-boot-starter-undertow</artifactId>; </dependency>; <dependency>; <groupId>;org.springframework.boot</groupId>; <artifactId>;spring-boot-starter-actuator</artifactId>; </dependency>; </dependencies>; <repositories>; <repository>; <id>;red-hat-ga-repository</id>; <url>;https://maven.repository.redhat.com/ga</url>; </repository>; </repositories>; <pluginRepositories>; <pluginRepository>; <id>;red-hat-ga-repository</id>; <url>;https://maven.repository.redhat.com/ga</url>; </pluginRepository>; </pluginRepositories>; <build>; <defaultGoal>;spring-boot:run</defaultGoal>; <plugins>; <plugin>; <artifactId>;maven-compiler-plugin</artifactId>; <version>;${maven-compiler-plugin.version}</version>; <configuration>; <source>;1.8</source>; <target>;1.8</target>; </configuration>; </plugin>; <plugin>; <groupId>;org.jboss.redhat-fuse</groupId>; <artifactId>;spring-boot-maven-plugin</artifactId>; <version>;${fuse.version}</version>; <executions>; <execution>; <goals>; <goal>;repackage</goal>; </goals>; </execution>; </executions>; </plugin>; </plugins>; </build>; <profiles>; <profile>; <id>;openshift</id>; <build>; <plugins>; <plugin>; <groupId>;org.jboss.redhat-fuse</groupId>; <artifactId>;openshift-maven-plugin</artifactId>; <version>;${fuse.version}</version>; <executions>; <execution>; <goals>; <goal>;resource</goal>; <goal>;build</goal>; <goal>;apply</goal>; </goals>; </execution>; </executions>; <configuration>; <enricher>; <excludes>; <exclude>;fmp-openshift-route</exclude>; </excludes>; </enricher>; <resources>; <labels>; <pod>; <property>; <name>;com.company</name>; <value>;Red_Hat</value>; </property>; <property>; <name>;rht.prod_name</name>; <value>;Red_Hat_Integration</value>; </property>; <property>; <name>;rht.prod_ver</name>; <value>;7.9</value>; </property>; <property>; <name>;rht.comp</name>; <value>;spring-boot-camel-xml</value>; </property>; <property>; <name>;rht.comp_ver</name>; <value>;${fuse.bom.version}</value>; </property>; </pod>; </labels>; </resources>; </configuration>; </plugin>; </plugins>; </build>; <properties>; <jkube.generator.from>;registry.redhat.io/fuse7/fuse-java-openshift-rhel8:${docker.image.version}</jkube.generator.from>; </properties>; </profile>; <profile>; <id>;java11</id>; <activation>; <jdk>;[11,)</jdk>; </activation>; <properties>; <jkube.generator.from>;registry.redhat.io/fuse7/fuse-java-openshift-jdk11-rhel8:${docker.image.version}</jkube.generator.from>; </properties>; </profile>; <profile>; <id>;java17-build</id>; <activation>; <jdk>;[17,)</jdk>; </activation>; <dependencies>; <dependency>; <groupId>;com.sun.xml.bind</groupId>; <artifactId>;jaxb-impl</artifactId>; <version>;2.3.5</version>; </dependency>; </dependencies>; </profile>; </profiles>; </project>;</code> | There is a conflict in Quartz version somewhere, indeed the version of <code>camel-quartz</code> that you use (2.23.2.fuse-7_11_0-00037-redhat-00001), expects Quartz v1 while you end up with Quartz v2 which causes the issue. You have two ways to fix your problem:Keep on using Quartz v1In that case, you will have to force the version of Quartz in your pom file by adding: <code></dependency>; <dependency>; <groupId>;org.quartz-scheduler</groupId>; <artifactId>;quartz</artifactId>; <version>;1.8.6</version>; </dependency>; <dependency>; </code>Switch to Quartz v2In that case, you will have to change the <code>camel-quartz</code> artifact for <code>camel-quartz2-starter</code> as next: <code><dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-quartz2-starter</artifactId>; <!-- use the same version as your Camel core version -->; </dependency>; </code> Then change the URI of the Quartz endpoint by specifying <code>quartz2</code> instead of <code>quartz</code> as next: <code>public void configure() throws Exception { from(';quartz2://myname?cron=0+ *+ *+ ?+ *+ *';) .to(';log:hello';); } </code>The choice is up to you, but I would definitely recommend switching to Quartz v2. |
apache-camel | I have a question about <code>XMLTokenizeLanguage</code> more specifically about <code>XMLTokenExpressionIterator.java</code>:<code>this.splitpath</code> accepts multiple tokens separated by ';/';. I try to use it in this way: ==>; <code>.split(body().xtokenize(';/ns1:[some type]/ns1:[another type]'; 'i', ns)) .streaming() </code> where ns and ns1 are namespaces But no result in the pipeline Can you please share with me more content about <code>XMLTokenizeLanguage</code>. The example in Camel website is about split of XML by 1 type [JAXB java POJO], what about 2 or more types [JAXB java POJOs]? is it even possible? https://camel.apache.org/components/3.18.x/eips/split-eip.html This is my XML Content : <code><?xml version=';1.0'; encoding=';UTF-8'; standalone=';yes';?>; <LocationMessages xmlns=';http://standards.iso.org/iso/15143/-3';>; <Links>; <rel>;self</rel>; <href>;https://[source domain name ]/public/api/aemp/v2/15143/-3/Fleet/Equipment/ID/[equipement id]/Locations/2021-01-01T00:00/2022-09-28T09:34:06.439553/1</href>; </Links>; <Links>; <rel>;last</rel>; <href>;https://[source domain name]/public/api/aemp/v2/15143/-3/Fleet/Equipment/ID/[equipement id]/Locations/2021-01-01T00:00/2022-09- 28T09:34:06.439553/1</href>; </Links>; <Location datetime=';2022-04-05T09:52:53Z';>; <Latitude>;43.290143</Latitude>; <Longitude>;5.491987</Longitude>; <Altitude>;102.375</Altitude>; <AltitudeUnits>;metre</AltitudeUnits>; </Location>; <Location datetime=';2022-05-04T13:50:57Z';>; <Latitude>;43.289926</Latitude>; <Longitude>;5.492582</Longitude>; <Altitude>;77.0</Altitude>; <AltitudeUnits>;metre</AltitudeUnits>; </Location>; </LocationMessages>; </code> This is namespace declaration : <code>Namespaces ns = new Namespaces(';ns1';, ';http://standards.iso.org/iso/15143/-3';); </code> And this is the split by xtokenize language definition : <code>.split(body().xtokenize(';/ns1:Links/ns1:Location';, 'i', ns)).streaming() </code> The split xtokenize work for me when I use 1 type at a time ( Links or Location), but I don't want to use (.multicast()) to duplicate pipeline. I want tokenize by 2 types (Links and Location) and after that apply content routing EIP (choice()) to choose the route for every token type. Links and Location are JAXB pojo types generated by xjc from xsd schemas. Here a brief part of their structure :<code>@XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = ';Links';, propOrder = { ';rel';, ';href'; }) @Generated(value = ';com.sun.tools.xjc.Driver';, comments = ';JAXB RI v3.0.2';, date = ';2022-08-23T15:17:27+02:00';) public class Links { @XmlElement(required = true) @Generated(value = ';com.sun.tools.xjc.Driver';, comments = ';JAXB RI v3.0.2';, date = ';2022-08-23T15:17:27+02:00';) protected String rel; @XmlElement(required = true) @Generated(value = ';com.sun.tools.xjc.Driver';, comments = ';JAXB RI v3.0.2';, date = ';2022-08-23T15:17:27+02:00';) protected String href; </code><code>@XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = ';Location';, propOrder = { ';latitude';, ';longitude';, ';altitude';, ';altitudeUnits'; }) @Generated(value = ';com.sun.tools.xjc.Driver';, comments = ';JAXB RI v3.0.2';, date = ';2022-08-23T15:17:27+02:00';) public class Location { @XmlElement(name = ';Latitude';, required = true) @Generated(value = ';com.sun.tools.xjc.Driver';, comments = ';JAXB RI v3.0.2';, date = ';2022-08-23T15:17:27+02:00';) protected BigDecimal latitude; @XmlElement(name = ';Longitude';, required = true) @Generated(value = ';com.sun.tools.xjc.Driver';, comments = ';JAXB RI v3.0.2';, date = ';2022-08-23T15:17:27+02:00';) protected BigDecimal longitude; @XmlElement(name = ';Altitude';) @Generated(value = ';com.sun.tools.xjc.Driver';, comments = ';JAXB RI v3.0.2';, date = ';2022-08-23T15:17:27+02:00';) protected BigDecimal altitude; @XmlElement(name = ';AltitudeUnits';) @XmlSchemaType(name = ';string';) @Generated(value = ';com.sun.tools.xjc.Driver';, comments = ';JAXB RI v3.0.2';, date = ';2022-08-23T15:17:27+02:00';) protected Altitudeuom altitudeUnits; @XmlAttribute(name = ';datetime';, required = true) @XmlSchemaType(name = ';dateTime';) @Generated(value = ';com.sun.tools.xjc.Driver';, comments = ';JAXB RI v3.0.2';, date = ';2022-08-23T15:17:27+02:00';) protected XMLGregorianCalendar datetime; </code> | You need to change the <code>xtokenize</code> expression to include all its potential children which are <code>Links</code> and <code>Location</code> according to its schema definition by using the wildcard character <code>*</code>. The right code for the <code>split</code> should then be <code>.split(body().xtokenize(';/ns1:LocationMessages/ns1:*';, 'i', ns)).streaming()</code> |
apache-camel | Working with SpringBoot, Java 11. In application.properties i want to configure: <code>camel.component.rabbitmq.args</code> Documentation by camel using rabbitmq: https://camel.apache.org/components/3.18.x/rabbitmq-component.html#_message_body Note: I'm not asking about rabbit, just the configuration in application. Error i have received trying to configure by my way: <code>application.properties camel.component.rabbitmq.args={arg.queue.x-message-ttl=3600000} </code> Error: <code>Failed to bind properties under 'camel.component.rabbitmq.args' to java.util.Map<java.lang.String, java.lang.Object>;: Reason: No converter found capable of converting from type [java.lang.String] to type [java.util.Map<java.lang.String, java.lang.Object>;] </code> How is the correct way by example? Thanks!!! | In the <code>application.properties</code>, the proper syntax for a component option of type <code>Map</code> is <code>componentOptionName[mapKey]=mapValue</code> so in your case it would be: <code>camel.component.rabbitmq.args[queue.x-message-ttl]=3600000 </code> |
apache-camel | I have a camel route that reaches out to a URL and does some processing with the results: <code>from(';direct:doURL';) .routeId(';urlRouteId';) .to(';http://host:port/path';) .process(e ->; { //Do Stuff }); </code> I can run unit test on that route without making an actual call to the URL by intercepting the call in my unit test like follows: <code>AdviceWith.adviceWith(context, ';urlRouteId';, a ->; a.interceptSendToEndpoint(';http://host:port/path';).skipSendToOriginalEndpoint().to(';mock:test';) ); </code> I’m updating that route to use .serviceCall() instead to look up the actual URL of the service, something like this: <code>from(';direct:doService';) .routeId(';servcieRouteId';) .serviceCall(';myService/path';) .process(e ->; { //Do Stuff }); </code> This works great, but I don’t know how to do a similar unit test on this route. Is there some sort of LoadBalancerClient I can use for testing? What is the standard way to unit test routes with service calls? I've been googling around for awhile and haven't had much luck, any ideas? Thanks | You can give serviceCall endpoint an id and then use <code>weaveById</code>. <code>from(';direct:doURL';) .routeId(';urlRouteId';) .serviceCall(';foo';).id(';serviceCall';) .log(LoggingLevel.INFO, ';body ${body}';); </code> <code>AdviceWith.adviceWith(context(), ';urlRouteId';, a ->; { a.weaveById(';serviceCall';) .replace() .setHeader(Exchange.HTTP_RESPONSE_CODE).constant(200) .setBody().simple(';Hello from service';); }); </code> Alternatively if service is a bean in camel registry then you could probably override <code>bindToRegistry</code> method and use Mockito to create a mock service. Also instead of using <code>interceptSendToEndpoint</code> it would likely be much simpler to just use <code>weaveByToUri(';http*';).replace()</code> instead. Example generic method for replacing http-endpoints <code>private void replaceHttpEndpointWithSimpleResponse(String routeId, String simpleResponse) throws Exception { AdviceWith.adviceWith(context(), routeId, a ->; { a.weaveByToUri(';http*';) .replace() .setHeader(Exchange.HTTP_RESPONSE_CODE).constant(200) .setBody().simple(simpleResponse); }); } </code> |
apache-camel | I want to send local files to hdfs. <code>public class FileRouteBuilder extends EndpointRouteBuilder { @Override public void configure() throws Exception { from(file(';C://Users/pcn/Desktop/test';).noop(true).recursive(true)) .process(new FileProcessor()) .to(hdfs(';localhost:9000/2209212/';)) .log(LoggingLevel.DEBUG, ';completed';); } } </code> So, I wrote like this. But, when I used recursive option of file component, occured file path error. <code>java.lang.IllegalArgumentException: Illegal character in path at index 33: hdfs://localhost:9000/220922/rec\test4.txt at java.base/java.net.URI.create(URI.java:883) at org.apache.camel.component.hdfs.HdfsInfoFactory.newFileSystem(HdfsInfoFactory.java:102) at org.apache.camel.component.hdfs.HdfsInfoFactory.newHdfsInfoWithoutAuth(HdfsInfoFactory.java:63) at org.apache.camel.component.hdfs.HdfsInfoFactory.newHdfsInfoWithoutAuth(HdfsInfoFactory.java:41) at org.apache.camel.component.hdfs.HdfsOutputStream.createOutputStream(HdfsOutputStream.java:50) at org.apache.camel.component.hdfs.HdfsProducer.doProcess(HdfsProducer.java:205) at org.apache.camel.component.hdfs.HdfsProducer.process(HdfsProducer.java:188) at org.apache.camel.support.AsyncProcessorConverterHelper$ProcessorToAsyncProcessorBridge.process(AsyncProcessorConverterHelper.java:66) at org.apache.camel.processor.SendDynamicProcessor.lambda$process$0(SendDynamicProcessor.java:197) at org.apache.camel.support.cache.DefaultProducerCache.doInAsyncProducer(DefaultProducerCache.java:318) at org.apache.camel.processor.SendDynamicProcessor.process(SendDynamicProcessor.java:182) at org.apache.camel.processor.errorhandler.RedeliveryErrorHandler$SimpleTask.run(RedeliveryErrorHandler.java:469) at org.apache.camel.impl.engine.DefaultReactiveExecutor$Worker.schedule(DefaultReactiveExecutor.java:187) at org.apache.camel.impl.engine.DefaultReactiveExecutor.scheduleMain(DefaultReactiveExecutor.java:64) at org.apache.camel.processor.Pipeline.process(Pipeline.java:184) at org.apache.camel.impl.engine.CamelInternalProcessor.process(CamelInternalProcessor.java:398) at org.apache.camel.component.file.GenericFileConsumer.processExchange(GenericFileConsumer.java:492) at org.apache.camel.component.file.GenericFileConsumer.processBatch(GenericFileConsumer.java:245) at org.apache.camel.component.file.GenericFileConsumer.poll(GenericFileConsumer.java:206) at org.apache.camel.support.ScheduledPollConsumer.doRun(ScheduledPollConsumer.java:197) at org.apache.camel.support.ScheduledPollConsumer.run(ScheduledPollConsumer.java:111) at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515) at java.base/java.util.concurrent.FutureTask.runAndReset(FutureTask.java:305) at java.base/java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:305) at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) at java.base/java.lang.Thread.run(Thread.java:829) </code> because I'm working on Windows. Then, I tried to change the path using Processor implements. <code>@Service @Slf4j public class FileProcessor implements Processor { @Override public void process(Exchange exchange) throws Exception { GenericFile body = exchange.getIn().getBody(GenericFile.class); body.setEndpointPath(exchange.getIn().getBody(GenericFile.class).getEndpointPath().replace(';\\/';, ';/';)); body.setRelativeFilePath(exchange.getIn().getBody(GenericFile.class).getRelativeFilePath().replace(';\\/';, ';/';)); body.setAbsoluteFilePath(exchange.getIn().getBody(GenericFile.class).getAbsoluteFilePath().replace(';\\/';, ';/';)); exchange.getIn().setBody(body); } } </code> But, it' doesn't work. I don't think sub folders paths from an <code>Exchange</code>, when I use recursive option. How to fix it? FYI, I set property and used <code>toD</code> too. But, result was the same. | If you want to modify the relative path before injecting your file into HDFS, you can modify the header <code>CamelFileName</code> (that you can get from the constant <code>HdfsConstants.FILE_NAME</code>) to fit your requirements. So in your case, your <code>Processor</code> could rather be something like: <code>public class FileProcessor implements Processor { @Override public void process(Exchange exchange) { exchange.getIn().setHeader( HdfsConstants.FILE_NAME, exchange.getIn().getHeader(HdfsConstants.FILE_NAME, String.class) .replace('\\', '/') ); } } </code> |
apache-camel | I have called a REST api through apache camel and deserialized the same. I need to call another API with the number as the parameter that I have received from calling the previous api. I did it in the following way - <code> public Collection<String>; nos; from(';direct:further';).tracing() .log(';body: '; + body().toString()) .setBody().constant(null) .setHeader(';CamelHttpMethod';) .simple(';GET';) .setHeader(';Authorization';) .simple(';Bearer ';+';${header.jwt}';) .to(';https://call/api/that/returns/numbers';) .choice() .when().simple(';${header.CamelHttpResponseCode} == 200';).unmarshal().json(JsonLibrary.Jackson, Abc.class) .process( ex->;{ Quantity quantity = ex.getIn().getBody(Abc.class); List<Variations>; variationsList = Arrays.stream(quantity.getResources().getVariations()).toList(); nos=variationsList.stream().map(Variations::getNo).collect( Collectors.toList()); nos.forEach(s ->; { //Since nos is a collection of String I would like to iterate through it String url=';https://call/another/api/with/number';+';?';+s;//the link with the number as the parameter from(';direct:start';) //This is not working. I not able to call the url .setHeader(';CamelHttpHeader';) .simple(';GET';) .setHeader(';Authorization';) .simple(';Bearer ';+';${header.jwt}';) .log(';I did call the numbers';) //This is also not getting printed .to(url); }); }).log(';I am out of the loop'; + body()) .otherwise() .log(';Error!!!';);</code> I am unable to call another api with the number that I received adter calling the first api. How should I do it? I also tried to call it like <code> from(';rest:get:';+url).tracing() .setHeader(';CamelHttpHeader';) .simple(';GET';) .setHeader(';Authorization';) .simple(';Bearer ';+';${header.jwt}';) .log(';I did call the numbers';).to(url);</code> But unfortunately the above code also did not work inside the loop. I declared the collection nos outside the method definition. How should I call another API from the numbers stored in nos collection? Should I call another Api outside the lambda function or inside? | Instead of trying to define new routes inside a processor you should store collection of the numbers to body and use split to call dynamic producer endpoint <code>toD</code> which can use simple language to construct the uri with values from body, headers, properties etc. If you later need to collect all the responses to say list you can create custom AggregationStrategy or use Flexible ones. Simple example with Camel 3.18.2 using unit tests <code>package com.example;import java.util.ArrayList;import org.apache.camel.AggregationStrategy; import org.apache.camel.Exchange; import org.apache.camel.RoutesBuilder; import org.apache.camel.builder.AdviceWith; import org.apache.camel.builder.AggregationStrategies; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.model.dataformat.JsonLibrary; import org.apache.camel.test.junit5.CamelTestSupport; import org.junit.jupiter.api.Test; public class NumbersAPITests extends CamelTestSupport { @Test public void testAPILogic() throws Exception { replaceHttpEndpointWithSimpleResponse(';requestNumbersFromAPI';, ';[1,2,3,4,5]';); replaceHttpEndpointWithSimpleResponse(';requestDataWithIdFromAPI';, ';{ \';id\';=\';${body}\';, \';data\';:\';some data\'; }';); weaveAddMockendpointAsLast(';requestNumbersFromAPI';, ';result';); weaveAddMockendpointAsLast(';requestDataWithIdFromAPI';, ';splitResult';); MockEndpoint mockResultEndpoint = getMockEndpoint(';mock:result';); mockResultEndpoint.expectedMessageCount(1); MockEndpoint mockSplitResultEndpoint = getMockEndpoint(';mock:splitResult';); mockSplitResultEndpoint.expectedMessageCount(5); startCamelContext(); template.sendBodyAndHeader(';direct:requestNumbersFromAPI';, null, ';jwt';, ';not-valid-jwt';); mockResultEndpoint.assertIsSatisfied(); mockSplitResultEndpoint.assertIsSatisfied(); } @Override protected RoutesBuilder createRouteBuilder() throws Exception { return new RouteBuilder(){ @Override public void configure() throws Exception { AggregationStrategy aggregationStrategy = AggregationStrategies .flexible() .accumulateInCollection(ArrayList.class); from(';direct:requestNumbersFromAPI';) .routeId(';requestNumbersFromAPI';) .setBody().constant(null) .setHeader(';Authorization';) .simple(';Bearer ';+';${header.jwt}';) .to(';http://localhost:3001/api/numbers';) .unmarshal().json(JsonLibrary.Jackson, Integer[].class) .split(body(), aggregationStrategy) .to(';direct:requestDataWithIdFromAPI';) .end() .to(';log:loggerName?showAll=true';) ; from(';direct:requestDataWithIdFromAPI';) .routeId(';requestDataWithIdFromAPI';) .setHeader(';Authorization';) .simple(';Bearer ';+';${header.jwt}';) .convertBodyTo(String.class) .log(';Calling API http://localhost:3001/api/data/${body} with number: ${body}';) .toD(';http://localhost:3001/api/data/${body}';) .convertBodyTo(String.class) ; } }; } @Override public boolean isUseAdviceWith() { return true; } private void replaceHttpEndpointWithSimpleResponse(String routeId, String simpleResponse) throws Exception { AdviceWith.adviceWith(context(), routeId, a ->; { a.weaveByToUri(';http*';) .replace() .setHeader(Exchange.HTTP_RESPONSE_CODE).constant(200) .setBody().simple(simpleResponse); }); } private void weaveAddMockendpointAsLast(String routeId, String mockName) throws Exception { AdviceWith.adviceWith(context(), routeId, a ->; { a.weaveAddLast() .to(';mock:'; + mockName); }); } } </code>The request is getting generated with additional %22 at the beginning and the end of body parameter. So it is showing failed invoking status- For example - call/another/api/with/number/%228767%22= How can I avoid the %22 to get attached to the body parameter? JeetIf your data has extra quotation marks that should not get sent to the api you can remove them before calling toD html endpoint: <code>setBody().exchange(ex ->; { return ex.getMessage().getBody(String.class) .replace(';\';';, ';';); }) </code> |
apache-camel | I am trying to write a simple consumer for a rabbitMQ queue on which a DLX (binded to another queue is configured). I am using camel 3.14.5 at the moment. My camel route declaration looks like : <code>from(';spring-rabbitmq:my-exchange?connectionFactory=#rabbitMQConnectionFactory&;queues=my-queue';) .onException(Exception.class) .log(LoggingLevel.ERROR, ';Something went wrong!';) .end() .process(';myProcessor';); </code> And my connectionFactory : <code> <bean id=';rabbitMQConnectionFactory'; class=';org.springframework.amqp.rabbit.connection.CachingConnectionFactory';>; <property name=';uri'; value=';amqps://myhost:5671';/>; <property name=';username'; value=';my-user';/>; <property name=';password'; value=';my-password';/>; <property name=';virtualHost'; value=';my-virtual-host';/>; </bean>; </code> But then when my processor throw an exception I get the following logs : <code> 16:33:10,441 ERROR [org.apache.camel.component.springrabbit.CamelDirectMessageListenerContainer] (pool-4-thread-5) Failed to invoke listener: org.springframework.amqp.rabbit.support.ListenerExecutionFailedException: Retry Policy Exhausted at org.springframework.amqp.rabbit.retry.RejectAndDontRequeueRecoverer.recover(RejectAndDontRequeueRecoverer.java:76) [spring-rabbit-2.4.6.jar:2.4.6] at org.springframework.amqp.rabbit.config.StatelessRetryOperationsInterceptorFactoryBean.recover(StatelessRetryOperationsInterceptorFactoryBean.java:78) [spring-rabbit-2.4.6.jar:2.4.6] at org.springframework.retry.interceptor.RetryOperationsInterceptor$ItemRecovererCallback.recover(RetryOperationsInterceptor.java:157) [spring-retry-1.3.3.jar:] at org.springframework.retry.support.RetryTemplate.handleRetryExhausted(RetryTemplate.java:539) [spring-retry-1.3.3.jar:] at org.springframework.retry.support.RetryTemplate.doExecute(RetryTemplate.java:387) [spring-retry-1.3.3.jar:] at org.springframework.retry.support.RetryTemplate.execute(RetryTemplate.java:225) [spring-retry-1.3.3.jar:] at org.springframework.retry.interceptor.RetryOperationsInterceptor.invoke(RetryOperationsInterceptor.java:122) [spring-retry-1.3.3.jar:] at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) [spring-aop-5.3.22.jar:5.3.22] at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:215) [spring-aop-5.3.22.jar:5.3.22] at org.springframework.amqp.rabbit.listener.$Proxy52.invokeListener(Unknown Source) [:2.4.6] at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.invokeListener(AbstractMessageListenerContainer.java:1577) [spring-rabbit-2.4.6.jar:2.4.6] at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.doExecuteListener(AbstractMessageListenerContainer.java:1568) [spring-rabbit-2.4.6.jar:2.4.6] at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.executeListener(AbstractMessageListenerContainer.java:1512) [spring-rabbit-2.4.6.jar:2.4.6] at org.springframework.amqp.rabbit.listener.DirectMessageListenerContainer$SimpleConsumer.callExecuteListener(DirectMessageListenerContainer.java:1108) [spring-rabbit-2.4.6.jar:2.4.6] at org.springframework.amqp.rabbit.listener.DirectMessageListenerContainer$SimpleConsumer.handleDelivery(DirectMessageListenerContainer.java:1068) [spring-rabbit-2.4.6.jar:2.4.6] at com.rabbitmq.client.impl.ConsumerDispatcher$5.run(ConsumerDispatcher.java:149) [amqp-client-5.13.1.jar:5.13.1] at com.rabbitmq.client.impl.ConsumerWorkService$WorkPoolRunnable.run(ConsumerWorkService.java:104) [amqp-client-5.13.1.jar:5.13.1] at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [rt.jar:1.8.0_342] at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [rt.jar:1.8.0_342] at java.lang.Thread.run(Thread.java:750) [rt.jar:1.8.0_342] Caused by: org.springframework.amqp.AmqpRejectAndDontRequeueException ... 20 more Caused by: org.springframework.amqp.rabbit.support.ListenerExecutionFailedException: Listener threw exception at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.wrapToListenerExecutionFailedExceptionIfNeeded(AbstractMessageListenerContainer.java:1784) [spring-rabbit-2.4.6.jar:2.4.6] at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.doInvokeListener(AbstractMessageListenerContainer.java:1674) [spring-rabbit-2.4.6.jar:2.4.6] at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.actualInvokeListener(AbstractMessageListenerContainer.java:1589) [spring-rabbit-2.4.6.jar:2.4.6] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.8.0_342] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) [rt.jar:1.8.0_342] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) [rt.jar:1.8.0_342] at java.lang.reflect.Method.invoke(Method.java:498) [rt.jar:1.8.0_342] at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:344) [spring-aop-5.3.22.jar:5.3.22] at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:198) [spring-aop-5.3.22.jar:5.3.22] at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) [spring-aop-5.3.22.jar:5.3.22] at org.springframework.retry.interceptor.RetryOperationsInterceptor$1.doWithRetry(RetryOperationsInterceptor.java:97) [spring-retry-1.3.3.jar:] at org.springframework.retry.support.RetryTemplate.doExecute(RetryTemplate.java:329) [spring-retry-1.3.3.jar:] ... 15 more Caused by: org.apache.camel.RuntimeCamelException: my processing exception </code> How should I configure the queue/connection factory for this message to be nack and send to the DLX configure on the rabbitMQ broker ? | I don't know camel, but from a Spring perspective, you could use a <code>DeadLetterPublishingRecoverer</code> instead of a <code>RejectAndDontRequeueRecoverer</code>; this will re-publish the failed message to the DLQ with exception information in the headers. If you just want the original message moved to the DLQ by the broker, you must configure the queue with a dead-letter-exchange and routing key. See <code>QueueBuilder</code>. <code> /** * Set the dead-letter exchange to which to route expired or rejected messages. * @param dlx the dead-letter exchange. * @return the builder. * @since 2.2 * @see #deadLetterRoutingKey(String) */ public QueueBuilder deadLetterExchange(String dlx) { return withArgument(';x-dead-letter-exchange';, dlx); } /** * Set the routing key to use when routing expired or rejected messages to the * dead-letter exchange. * @param dlrk the dead-letter routing key. * @return the builder. * @since 2.2 * @see #deadLetterExchange(String) */ public QueueBuilder deadLetterRoutingKey(String dlrk) { return withArgument(';x-dead-letter-routing-key';, dlrk); } </code> |
apache-camel | When upgrading from: https://camel.apache.org/components/2.x/spring-batch-component.html to: https://camel.apache.org/components/3.18.x/spring-batch-component.html query parameter ';synchronous'; is dropped. Can I assume ';synchronous=true';, for camel-spring-batch 3.18.2 ? | Looking at the apache-camel project on github it was removed due to lack of components that supported a flag of that ilk. The default job launcher in spring batch launches jobs synchronously. If you wanted to run a job asynchonously you would have to configure your own job launcher and use use an asynctaskexecutor like below <code>@Bean(name = ';asyncJobLauncher';) public JobLauncher asyncJobLauncher() throws Exception { SimpleJobLauncher jobLauncher = new SimpleJobLauncher(); jobLauncher.setJobRepository(jobRepository); jobLauncher.setTaskExecutor(new SimpleAsyncTaskExecutor()); jobLauncher.afterPropertiesSet(); return jobLauncher; } </code> |
apache-camel | <code>//Model class MyClass{ String name; //getters and setters }ProcessorClass implements Processor{ process(Exchange exchange){ MyClass myClass = exchange.getIn().getBody(MyClass.class); print(myClass.getName()); }}//Inside xyzClass extends RouteBuilder{ configure() { from() .unmarshal(new JacksonDataFormat(MyClass.class)) .process(processorClass) .to() .end(); </code> I am using camel route for the first time and was unable to understand few thingswhere the data (MyClass object and its values) gets stored once unmarshalling (of json payload) happens ? (at this point I am assuming json payload is already present in exchange.body) why is it required to initialize myClass variable inside ProcessorClass to map json data to our model class (MyClass) ? what exactly .unmarshal() does in that case ? to access the value present in MyClass.name, we have to do myClass.getName() inside ProcessorClass. Is this the only way to access model class data after unmarshalling ? or is there any other way as well to access model class data, after unmarshalling and before assigning it to myClass variable ? | Where the data (MyClass object and its values) gets stored once unmarshalling (of json payload) happens ?It gets stored to the message body of the ongoing exchange. Instead of <code>exchange.getIn()</code> you might want to use <code>exchange.getMessage()</code> instead.why is it required to initialize myClass variable inside ProcessorClass to map json data to our model class (MyClass) ?Mapping has already been done during <code>.unmarshal(new JacksonDataFormat(MyClass.class))</code> step. The type of message body is of type java.lang.Object so in order to access <code>getName</code> method of your <code>MyClass</code> you need to cast the body to MyClass. You don't really need extra variable for this but it's often cleaner to store the result of cast to a separate variable and do whatever with the variable after. Otherwise you'd have to do something like this every time you want access public methods and variables of the object: <code>// Using getBody(Class) (exchange.getMessage().getBody(MyClass.class)).getName();// Using basic Java syntax for casting ((MyClass)exchange.getMessage().getBody()).getName(); </code>to access the value present in MyClass.name, we have to do myClass.getName() inside ProcessorClass. Is this the only way to access model class data after unmarshalling ?No, you could also use bean with method with MyClass as parameter and camel will do the casting automatically when the method gets called. <code> from(';timer:timerName?period=3000';) .setBody(constant(new MyClass(';Bob';))) .bean(new MyBean());class MyBean { public void someMethod(MyClass myClass) { if(myClass != null) { System.out.println(myClass.getName()); } else { System.out.println(';Given MyClass instance was null..';); } } }class MyClass { private String name; public MyClass(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } } </code> You could also access it using simple-language. Alternatively you could also access it with lamda + casting <code>.setHeader(';name';).exchange(ex ->; { return ex.getMessage().getBody(MyClass.class).getName(); }) </code> Casting is pretty basic stuff when it comes to Object oriented programming so you might want to do a refresher on that before continuing with Apache Camel. Since message body of an exchange can hold pretty much anything you'll always need to cast it to actually use it. Either you do it in processor or camel does it automatically in background as with many of the examples above. Same goes for headers and exchange properties. |
apache-camel | I have an Apache Camel exchange that, as result of some processing, contains a <code>Pair<List<Message>;</code>, <code>List<Error>;>;</code>. I want to split my Camel route into two paths, one only processing the <code>Message</code>s, and one only processing the <code>Error</code>s. Using a pseudo-DSL, I am looking for something like this: <code>split(MyPairSplitter::Class) .to(';direct:process-messages';) .to(';direct:process-errors';) </code> Now, this is not how the splitter EIP works. To my understanding, the splitter creates a sequence of exchanges that all have the same data type as body and that are all fed into a single route; but I would like to have two routes that process different data types. What is the best way to do this? | The Splitter doesn't really care what the type of the thing being split is. I think what you're looking for is the Composed Message Processor pattern. <code>split(body()) .when(simple(';${body.class.name == 'Message'';)) .to(';direct:process-messages';) .otherwise() .to(';direct:process-errors';) .end() .end() </code> |
apache-camel | I am using a route builder in my Camel Context like this: <code><bean class=';mypackage.MyRouteBuilder'; id=';MyRouteBuilder';/>; <camelContext id=';mypackage.camelcontext'; xmlns=';http://camel.apache.org/schema/spring';>; <routeBuilder ref=';MyRouteBuilder';/>; </camelContext>; </code> I have implemented a RouteBuilder like this: <code>public class MyRouteBuilder extends RouteBuilder{ @Override public void configure() { from(';direct:MyRouteBuilder';) .log(';Route Builder: ${body}';); } } </code> Is it possible to implement more routes in the same route builder? | yes you can implement a lot of routes in the same route builder like this, I advise you to use routeId for identify the route in the logs and use the .end() to finish the block <code> from(';direct:route1';) .routeId(';route1';) .log(';Route Builder: ${body}';) .end(); from(';direct:route2';) .routeId(';route2';) .log(';Route Builder: ${body}';) .end(); from(';direct:route3';) .routeId(';route3';) .log(';Route Builder: ${body}';) .end(); </code> |
apache-camel | I'm running HawtIO (version 2.14.3) within Apache Karaf. I very frequently use the ActiveMQ table view to inspect the queue sizes etc. In this version however, the table refreshes so fast that it's hard to use. It goes like:Blank screen for 2 seconds Display the table for 0.5 seconds Blank screen for 2 seconds and repeat...Is there a way to set the refresh interval(or maybe disable it entirely)? I know that in older versions of HawtIO this was a setting in the UI. | Check out jbertram's comment on disable web console refreshing. Probably it's the same setting for you. |
apache-camel | I have an FTP route which processes an inbound text file and call's a company API to load that data into an internal Company table. All works perfect. I now have a case where when the FTP route is invoked, I first need to remove all the existing data from the Company table... there is a company API to handle that case. The problem I have is that the Company API which removes data from the Company table also returns some information relative to the delete operation. In this special case, I would normally want to first delete all records in the Company table ( using this Company API call ) and THEN process the inbound FTP data file. The issue is that if I begin the ftp processing ( Step 1 ) and then call the company API ( Step 2 ) to first delete the exiting data in the table, the inbound data from the file associated with the FTP operation is lost prior to executing Step 3 ...what is in the context appears to be the data returned from Step 2. Ideally, I would like the route to start ( Step 1 ) and be able to call Step 2 without destroying the data inbound from the FTP file ...is there a way to accomplish this ? I know how to call one route from another, just not how to prevent the FTP data from being lost when I do make the call to the other route. <code><route id=';import-data-from-ftp';>; <from uri=';ftp: .............................';>; Step 1 <to uri=';api:deleteData .............................'; >; Step 2 <to uri=';api:loadData .............................'; >; Step 3 </code> | I'm gonna comment this because I don't have the 50 reputation for comment, but is better use properties, this is because the headers can be lost every time you call an api and the properties will not be delete, so you can save the body inside a property for example <code><route id=';import-data-from-ftp';>; <from uri=';ftp: .............................';>; Step 1 <setProperty name=';preservedbody';>; <simple>;${bodyAs(String)}</simple>; </setProperty>; <to uri=';api:deleteData .............................'; >; Step 2 <setBody>; <exchangeProperty>;preservedbody</exchangeProperty>; </setBody>; <to uri=';api:loadData .............................'; >; Step 3 </code> |
apache-camel | I want to download the <code>.jar</code> file of a java framework. That <code>.jar</code> should of course contain all the <code>.class</code> files that I need for my project. I tried downloading from here: https://mvnrepository.com/artifact/org.apache.camel/camel-core/3.18.2 But the <code>.jar</code> file is only 4KB big and contains only meta information, but no java classes. I found <code>jar</code> files with java classes in them in older versions, but in newer versions they seem to upload only meta information. So I don't know how to get to the <code>.jar</code> file with all <code>.class</code> files inside. I don't want to work with <code>maven</code> or <code>gradle</code> for now. And you can't just download jars with maven or gradle you have to build your entire project with it. I also searched the github (https://github.com/apache/camel) and source code of the ';Apache Camel'; project and did not encounter <code>jar</code> files. Is there any other popular place where open source java frameworks/libraries with <code>jar</code> files can be found? | The apache camel module doesn't contain any code. It just declares a list of dependencies, in the <code>/META-INF/maven/org.apache.camel/camel-core/pom.xml</code> file:camel-core-engine camel-core-languages camel-bean camel-browse camel-cluster camel-controlbus camel-dataformat camel-dataset camel-direct camel-directvm camel-file camel-health camel-language camel-log camel-mock camel-ref camel-rest camel-saga camel-scheduler camel-seda camel-stub camel-timer camel-validator camel-vm camel-xpath camel-xslt camel-xml-jaxb camel-xml-jaxp slf4j-apiYou have to download the jars that you need in this list of dependencies. All jars can be found on https://mvnrepository.com/. This is why everyone will recommend you to use maven or gradle, as those tools will manage the dependencies for you. |
apache-camel | I am trying to implement an aggregate on Apache Camel (Version: 2.18.0) with the following route: <code><route id=';AggregateExtraRoute';>; <from uri=';direct:AggregateExtraRoute';/>; <aggregate strategyRef=';CustomAggregationStrategy';>; <correlationExpression>; <simple>;header.AggregationHeader</simple>; </correlationExpression>; <log message=';Route After Aggregate: ${body}'; loggingLevel=';INFO';/>; </aggregate>; </route>; </code> I have also tried: <code><header>;AggregationHeader</header>; </code> The error above appears when i am trying to deploy to JBoss. | Looks like you're missing completion criteria. You must provide at least one. |
apache-camel | I am given to understand both Aggregator and Enrich components combine messages based on an Aggregation Strategy. I don't see much of a difference between the components though. How can i know which one to use? | Thinking Aggregator and Enrich as components can be a bit misleading. They're implementations for enterprise integration patterns in camel and as such very integral to how Apache camel works. For example pipeline pattern and content enricher are things that you're likely already using all the time with Apache camel without even realizing it. With Apache camel you're almost constantly enriching messages using components, translators, beans and processors. Aggregation Strategy is used to configure how you want camel to combine one or more exchanges. This means it can be used to combine current exchange to a incoming exchange with enrich or to group multiple exchanges in to one when when using split or aggregate.How can i know which one to use?They're completely different patterns, one is for enriching exchanges with new data and one grouping exchanges together. In terms of defining routes with Camel Java-DSL use of <code>.enrich()</code> is pretty uncommon as generally it's enough to call the endpoint directly with <code>to(';uri';)</code>. More common is <code>.pollEnrich(';uri';)</code> as with it one can use consumer endpoints like file, ftp or jms to enrich the exchange. Meaning if you need data from two or more files on a route you can use it to do so. When it comes to <code>.aggregate()</code> it's mainly used to group exchanges together and handle them as a group after some pre-determined condition has been met like for example every 100 exchanges or after 10 seconds of no new exchanges. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.