Instruction
stringclasses 1
value | Input
stringlengths 161
22.9k
| Output
stringlengths 40
18.2k
|
---|---|---|
apache-camel | I have a spring boot application that publish a rest endpoint to receives xml messages using apache camel, below the relevant part of the code corresponding to the configuration of the route: <code> restConfiguration() .component(';servlet';) .bindingMode(RestBindingMode.auto); rest(';/api/';).description(';REST Message Endpoint Service';) .id(';rest-producer-route';) // Accept post requests at /api/message .post(';/message';) // request in xml format .consumes(';application/xml';) .to(';direct:remoteService';); from(';direct:remoteService';) // RABBIT_URI = ';spring-rabbitmq:%s?routingKey=%s&;arg.queue.autoDelete=false';; .to(String.format(CamelConfiguration.RABBIT_URI, ';coreEngine';, ';coreEngine';)) .setHeader(Exchange.HTTP_RESPONSE_CODE, constant(201)); </code> When trying to send a message in xml format using Postman, after about 30 seconds I get a 500 error, with the following exception: <code>org.springframework.amqp.core.AmqpReplyTimeoutException: Reply timed out at org.springframework.amqp.rabbit.AsyncRabbitTemplate$RabbitFuture$TimeoutTask.run(AsyncRabbitTemplate.java:762) ~[spring-rabbit-2.4.6.jar:2.4.6] at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54) ~[spring-context-5.3.22.jar:5.3.22] at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515) ~[na:na] at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) ~[na:na] at java.base/java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:304) ~[na:na] at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) ~[na:na] at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) ~[na:na] at java.base/java.lang.Thread.run(Thread.java:829) ~[na:na]</code> However on the rabbitmq server the message was successfully saved to the coreEngine queue. I don't need any transformation to be done, the goal of the endpoint is simply to receive messages in xml format and store them in a rabbitmq queue. From what I could see, an AsyncRabbitTemplate is used, would that be the cause of the problem? What should I do to configure it correctly? | This is because the exchange pattern by default is expecting a reply, hence camel is using the <code>AsyncRabbitTemplate.sendAndReceive</code>. If you just want to fire and forget, set the exchange pattern to <code>ExchangePattern.InOnly</code> for Camel to use <code>RabbitTemplate.send</code>. You code should be changed to, <code>from(';direct:remoteService';) // RABBIT_URI = ';spring-rabbitmq:%s?routingKey=%s&;arg.queue.autoDelete=false';; .to(ExchangePattern.InOnly, String.format(CamelConfiguration.RABBIT_URI, ';coreEngine';, ';coreEngine';)) .setHeader(Exchange.HTTP_RESPONSE_CODE, constant(201)); </code> Refer the Apache Camel SpringRabbitMQProducer source code SpringRabbitMQProducer |
apache-camel | Good Morning! These days I'm trying to learn how to use Apache Camel. With a course on Udemy it was pretty simple to learn how to do standard operation in route. Now I wish to learn the use of the Rest integration, but I don't understand the differences between the exposition of an endpoint with <code>rest(';/someRoute';) .consumes(';application/json';).produces(';application/json';) .get().outType(String.class); </code> or <code>from(';rest:get:/rest-route/get-route';) .routeId(';ReceiverRoute';) .transform().constant(';Bye World';) .log(';${body}';); </code> Can anyone explain which are the differences between them and which is the best way to expose the endpoint? Why? I can't understand neither the construction of the rest() route and how to use the route() instruction. I tried to work on this example in another stackoverflow post: In Apache Camel what does ';route()'; do in a restful declaration? but the same route in my class is not correct and I can't understand why. <code> rest(';/someRoute';) .id(';someRoute';) .description(';Some description';) .post() .consumes(';text/plain';) .produces(';text/plain';) .route() //HERE I have the error: Cannot resolve method 'route' in 'RestDefinition' .routeId(';someRoutePost';) .to(';direct:toSomewhere';) .end() .endRest() .get() .route() .routeId(';someRouteGet';) .setHeader(Exchange.HTTP_RESPONSE_CODE, constant(405)) .setBody(constant(';GET not allowed on this route';)) .end() .endRest(); </code> I'm working with Springboot 2.7.3 and Camel 3.18.1 with these dependencies: <code> <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-http-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-rest-starter</artifactId>; <version>;${camel.version}</version>; </dependency>; </code> | Can anyone explain which are the differences between them and which is the best way to expose the endpoint? Why?The method above uses Camel Rest-DSL which allows you to define rest endpoints using java instead of fiddling URI Strings. The method below uses camel-rest component which works almost identically except for the fact that you use URI strings to configure it. It's possible that Rest-DSL uses this under the hood. The example you're referring to used camel version 3.14.0 but it seems both <code>.route()</code> and <code>endRest()</code> methods have been quietly removed from RestDefitinion which causes the exception <code>Cannot resolve method 'route' in 'RestDefinition</code>. Instead of <code>route()</code> you should use <code>to(';direct:endpointName';)</code> instead. My guess is that developers wanted to move most of the routing logic away from the RestDSL to keep it clean. Here's example for Camel 3.18.1 <code> // What I used to test this restConfiguration() .component(';undertow';) .host(';localhost';) .port(8091);// http://localhost:8091/api/hello rest(';/api';) .description(';Some description';) .post(';/hello';) .consumes(';text/plain';) .produces(';text/plain';) .to(';direct:someRoutePost';) .get(';/hello';) .produces(';text/plain';) .to(';direct:someRouteGet';);from(';direct:someRouteGet';) .routeId(';someRouteGet';) .setHeader(Exchange.HTTP_RESPONSE_CODE, constant(200)) .setBody(constant(';Hello world';));from(';direct:someRoutePost';) .routeId(';someRoutePost';) .setHeader(Exchange.HTTP_RESPONSE_CODE, constant(405)) .setBody(constant(';POST not allowed on this route';)); </code> Tested by generating project using maven <code>camel-archetype-spring-boot</code> archetype version <code>3.18.1</code>, added in following dependency. <code><dependency>; <groupId>;org.apache.camel.springboot</groupId>; <artifactId>;camel-undertow-starter</artifactId>; </dependency>; </code> |
apache-camel | I'm trying to use the camel-bean-validator dependency in my project but I have a problem with group validation. I'm using a springboot project with spring-boot-starter-parent 2.7.3 and these dependencies in pom.xml: <code><dependency>; <groupId>;org.apache.camel.springboot</groupId>; <artifactId>;camel-spring-boot-starter</artifactId>; <version>;3.18.1</version>; </dependency>; <dependency>; <groupId>;org.apache.camel.springboot</groupId>; <artifactId>;camel-jackson-starter</artifactId>; <version>;3.18.1</version>; </dependency>; <dependency>; <groupId>;org.apache.camel.springboot</groupId>; <artifactId>;camel-bean-validator-starter</artifactId>; <version>;3.18.1</version>; </dependency>; </code> My SimpleDto is: <code>@Data public class SimpleDto { @NotNull(groups = BasicValidation.class) private Long id; @NotBlank(groups = AdvancedValidation.class) private String name; @NotBlank private String value;} </code> And I created two interfaces for validation: <code> public interface AdvancedValidation { } </code> <code> public interface AdvancedValidation { } </code> When I want to use a standard validation like this in my route the application starts without problem: <code>@Component public class ValidationRoute extends RouteBuilder { @Override public void configure() throws Exception { from(';timer:val-timer?period=5000';) .process(new Processor() { @Override public void process(Exchange exchange) throws Exception { SimpleDto simpleDto = new SimpleDto(); exchange.getIn().setBody(simpleDto); } }) .log(';Setted body: ${body}';) .to(';bean-validator://x';) .log(';Validated message';); } }</code> but when I change the validation endpoint in: <code>.to(';bean-validator://x?group=AdvancedValidation';) </code> like in the example in Apache Camel documentation, here: https://camel.netlify.app/components/latest/bean-validator-component.html the application stop working and this is the error I have starting it: <code>org.apache.camel.FailedToStartRouteException: Failed to start route route1 because of null at org.apache.camel.impl.engine.RouteService.warmUp(RouteService.java:123) at org.apache.camel.impl.engine.InternalRouteStartupManager.doWarmUpRoutes(InternalRouteStartupManager.java:306) at org.apache.camel.impl.engine.InternalRouteStartupManager.safelyStartRouteServices(InternalRouteStartupManager.java:189) at org.apache.camel.impl.engine.InternalRouteStartupManager.doStartOrResumeRoutes(InternalRouteStartupManager.java:147) at org.apache.camel.impl.engine.AbstractCamelContext.doStartCamel(AbstractCamelContext.java:3365) at org.apache.camel.impl.engine.AbstractCamelContext.doStartContext(AbstractCamelContext.java:3033) at org.apache.camel.impl.engine.AbstractCamelContext.doStart(AbstractCamelContext.java:2988) at org.apache.camel.spring.boot.SpringBootCamelContext.doStart(SpringBootCamelContext.java:43) at org.apache.camel.support.service.BaseService.start(BaseService.java:119) at org.apache.camel.impl.engine.AbstractCamelContext.start(AbstractCamelContext.java:2649) at org.apache.camel.impl.DefaultCamelContext.start(DefaultCamelContext.java:262) at org.apache.camel.spring.SpringCamelContext.start(SpringCamelContext.java:119) at org.apache.camel.spring.SpringCamelContext.onApplicationEvent(SpringCamelContext.java:151) at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:176) at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:169) at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:143) at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:421) at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:378) at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:938) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:586) at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:147) at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:734) at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:408) at org.springframework.boot.SpringApplication.run(SpringApplication.java:308) at it.ale.CamelArchetypeTestApplication.main(CamelArchetypeTestApplication.java:16) Caused by: org.apache.camel.RuntimeCamelException: java.lang.ClassNotFoundException: AdvancedValidation 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.support.service.ServiceHelper.startService(ServiceHelper.java:130) at org.apache.camel.processor.errorhandler.RedeliveryErrorHandler.doStart(RedeliveryErrorHandler.java:1670) at org.apache.camel.support.ChildServiceSupport.start(ChildServiceSupport.java:60) at org.apache.camel.support.service.ServiceHelper.startService(ServiceHelper.java:113) at org.apache.camel.support.service.ServiceHelper.startService(ServiceHelper.java:130) at org.apache.camel.impl.engine.DefaultChannel.doStart(DefaultChannel.java:126) at org.apache.camel.support.service.BaseService.start(BaseService.java:119) at org.apache.camel.support.service.ServiceHelper.startService(ServiceHelper.java:113) at org.apache.camel.support.service.ServiceHelper.startService(ServiceHelper.java:116) at org.apache.camel.support.service.ServiceHelper.startService(ServiceHelper.java:130) at org.apache.camel.processor.Pipeline.doStart(Pipeline.java:224) at org.apache.camel.support.service.BaseService.start(BaseService.java:119) at org.apache.camel.support.service.ServiceHelper.startService(ServiceHelper.java:113) at org.apache.camel.support.processor.DelegateAsyncProcessor.doStart(DelegateAsyncProcessor.java:89) at org.apache.camel.support.service.BaseService.start(BaseService.java:119) at org.apache.camel.support.service.ServiceHelper.startService(ServiceHelper.java:113) at org.apache.camel.impl.engine.RouteService.startChildServices(RouteService.java:396) at org.apache.camel.impl.engine.RouteService.doWarmUp(RouteService.java:193) at org.apache.camel.impl.engine.RouteService.warmUp(RouteService.java:121) ... 24 common frames omitted Caused by: java.lang.ClassNotFoundException: AdvancedValidation at org.apache.camel.impl.engine.DefaultClassResolver.resolveMandatoryClass(DefaultClassResolver.java:103) at org.apache.camel.component.bean.validator.BeanValidatorEndpoint.createProducer(BeanValidatorEndpoint.java:73) at org.apache.camel.support.DefaultEndpoint.createAsyncProducer(DefaultEndpoint.java:200) at org.apache.camel.processor.SendProcessor.doStart(SendProcessor.java:242) at org.apache.camel.support.service.BaseService.start(BaseService.java:119) ... 44 common frames omittedProcess finished with exit code 1 </code> I already tried to change the endpoint with: <code>.to(';bean-validator://x?group=AdvancedValidation.class';) </code> and this time the error was: <code>Caused by: org.apache.camel.RuntimeCamelException: java.lang.ClassNotFoundException: AdvancedValidation.class </code> Also adding the annotation @Component to the interface I haven't solved the problem. Does anyone know why it is not working and how to solve it? I followed the documentation and there it seem work. Using the same interfaces and the same project in a RestController and validating it with @Valid or @Validated(AdvancedValidation.class) worked correctly, so this is a Camel issue | I probably solved it by using all the class path related to group: <code>.to(';bean-validator://x?group=com.application.dto.validation.group.AdvancedValidation';) </code> |
apache-camel | I am new to using Apache camel with Spring boot and try to implement a basic route in which, I want to filter out first whether the file has json contents or xml contents and based upon it, I want to save the file in some specific folder. I make my service instance up and then hit its post endpoint using postman with JSON content. My service saves that file to some folder location with txt extension. I have created the route in the service which picks up the file and checks if it is not empty, it will transform the contents in to XML format and store it to some folder. Route for this thing is below: <code>public class OutboundRoute extends RouteBuilder { Predicate p1=body().isNotNull(); Predicate p2=body().isNotEqualTo(';';); Predicate predicateGroup=PredicateBuilder.and(p1,p2); String inputFilePath=';file:C:\\Users\\StorageFolder\\Input?noop=true';; String outputFilePathForJson=';file:C:\\Users\\StorageFolder\\JsonFolderOutput?delete=true';; @Override public void configure() throws Exception { from(inputFilePath) .routeId(';readingJsonFromFile';) .choice() .when(predicateGroup) .log(';Before converting to XML: ${body}';) .unmarshal().json(JsonLibrary.Jackson, Message.class) .marshal().jacksonXml(true) .log(LoggingLevel.INFO, ';Payload after converting to xml = ${body}';) .to(outputFilePathForJson) .otherwise() .log(';Body is Empty!!';) .end(); } } </code> Now I want to implement this thing for xml also for better understanding. I want that I can hit my service using postman with either XML or JSON content. The route should pick the file and check it. If it has XML contents, route should convert its contents to JSON and store it to JSON folder but if it has JSON contents, route should convert its contents to XML and store it to XML folder. I need help with this thing. Main thing is that when I hit the service using postman, service will always store the file with txt extension only. So, I need help with a way to find that content of file is of JSON format or XML format. Also, I tried finding some content about learning apache camel but everywhere found basic tutorials only. Can someone recommend some platform where I can learn how to write complex routes? | I won't say its a good answer but an easy alternative I would say. What I did is, I created a processor which will check first character of file and if its ';{';, then its json and if its ';<';, then its XML. So, after detecting, I would add a header to camel route exchange as ';Type';: json or xml or unknown And using camel's ';simple'; language,I will check the header and based on that, in the route, I will do the processing. I am adding below files for better reference. Predicates used in route: <code>private Predicate notNull=body().isNotNull(); private Predicate notEmpty=body().isNotEqualTo(';';); private Predicate checkEmptyFile=PredicateBuilder.and(notNull,notEmpty); private Predicate checkIfJsonContents=header(';Type';).isEqualTo(';json';); private Predicate checkIfXmlContents=header(';Type';).isEqualTo(';xml';); private Predicate checkIfFileHasJsonContents=PredicateBuilder.and(checkEmptyFile,checkIfJsonContents); private Predicate checkIfFileHasXmlContents=PredicateBuilder.and(checkEmptyFile,checkIfXmlContents);</code> Route: <code>from(inputFilePath) .routeId(';readingJsonFromFile';) .routeDescription(';This route will assign a file type to file based on contents and then save it in different folder based on contents.';) .process(fileTypeDetectionProcessor) .log(';Added file type to header as: ${header.Type}';) .choice() .when(checkIfFileHasJsonContents) .log(';Payload before converting to XML: ${body}';) .unmarshal().json(JsonLibrary.Jackson, Message.class) .marshal().jacksonXml(true) .log(LoggingLevel.INFO, ';Payload after converting to xml = ${body}';) .to(outputFilePathForXml) .when(checkIfFileHasXmlContents) .log(';Payload before converting to JSON: ${body}';) .unmarshal().jacksonXml(Message.class,true) .marshal().json(true) .log(LoggingLevel.INFO, ';Payload after converting to JSON = ${body}';) .to(outputFilePathForJson) .otherwise() .log(';Unreadable format or empty file!!';) .to(outputFilePathForBadFile) .end(); </code> Processor: <code>public class FileTypeDetectionProcessor implements Processor { @Override public void process(Exchange exchange) throws Exception { if(exchange.getIn().getBody(String.class).startsWith(';{';)) exchange.getIn().setHeader(';Type';,';json';); else if(exchange.getIn().getBody(String.class).startsWith(';<';)) exchange.getIn().setHeader(';Type';,';xml';); else exchange.getIn().setHeader(';Type';,';unknown';); } } </code> |
apache-camel | I am new to Apache Camel. I need to split a file line by line and to do some operation on each lines. At the end I need a footer line with information from previous lines (number of lines and sum of the values of a column) My understanding is that I should be using an aggregation strategy, so I tried something like that: <code>.split(body().tokenize(';\r | ';), sumAggregationStrategy) .process(';fileProcessor';) </code> In my aggregation strategy I just set two headers with the incremented values: <code>newExchange.getIn().setHeader(';sum';, sum); newExchange.getIn().setHeader(';numberOfLines';, numberOfLines); </code> And in the processor I try to access those headers: <code>int sum = inMessage.getIn().getHeader(';sum';, Integer.class); int numberOfLines = inMessage.getIn().getHeader(';numberOfLines';, Integer.class); </code> There are two problems. First of all the aggregation strategy seem to be called after the first iteration of the processor. Second, my headers don't exist in the processors, so I can't access the information I need when I am at the last line of the file. The headers do exist in the oldExchange of the aggregators though. I think I can still do it, but I would have to create a new processor just for the purpose of making the last line of the file. Is there something I'm missing with the aggregation strategies ? Is there a better way to do this ? | An aggregator will be called for every iteration of the split. This is how they are supposed to work. The reason you don't see the headers within the processor is, headers live and die with the message and not visible outside. You need to set the 'sum' and 'numberOfLines' as exchange properties instead. Because every iteration within a split results in an exchange, you need get the property from old exchange and set them again in the new exchange to pass them to subsequent components in the route. This is how you could do, AggregationStrategy: <code>public class SumAggregationStrategy implements AggregationStrategy { public Exchange aggregate(Exchange oldExchange, Exchange newExchange) { long sum = 0; long numberOfLines = 0; if(oldExchange != null) { sum = (Long) oldExchange.getProperty(';sum';); numberOfLines = oldExchange.getProperty(';numberOfLines ';); } sum = sum + ((Line)newExchange.getIn().getBody()).getColumnValue(); numberOfLines ++; newExchange.setProperty(';sum';, sum); newExchange.setProperty(';numberOfLines';,numberOfLines); oldExchange.setProperty(';CamelSplitComplete';, newExchange.getProperty(';CamelSplitComplete';)); //This is for the completion predicate return newExchange; } } </code> Route: <code> .split(body().tokenize(';\r | ';),sumAggregationStrategy) .completionPredicate(simple(';${exchangeProperty.CamelSplitComplete} == true';)) .process(';fileProcessor';).to(';file:your_file_name?fileExist=Append';); </code> Processor: <code>public class FileProcessor implements Processor { public void process(Exchange exchange) throws Exception { long sum = exchange.getProperty(';sum';); long numberOfLines = exchange.getProperty(';numberOfLines';); String footer = ';Your Footer String';; exchange.getIn().setBody(footer); } } </code> |
apache-camel | How could I read JSON data from here: http://data.foli.fi/siri/vm using Jackson for example, so it returns the data filtered like this: <code>[{ ';latitude';: 60.4827, ';name';: ';14';, ';description';: ';14: Saramäki ->; Erikvalla';, ';id';: ';550018';, ';longitude';: 22.31275 }, { ';latitude';: 60.45902, ';name';: ';20';, ';description';: ';20: Puutori ->; Muhkuri';, ';id';: ';110416';, ';longitude';: 22.26783 }] </code> I've tried to use a bean like this but it doesn't seem to work.. <code>public class ItemsBean{ private double latitude; @JsonProperty(';name';) private String publishedlinename; @JsonProperty(';id';) private String originname; private String destinationname; private String vehicleref; private double longitude; @JsonIgnore public String sys; public int servertime; public int responsetimestamp; public String producerref; public String responsemessageidentifier; public boolean status; public boolean moredata; public int recordedattime; public int validuntiltime; public int linkdistance; public double percentage; public String lineref; public String directionref; public String operatorref; public String originref; public String destinationref; public int originaimeddeparturetime; public int destinationaimedarrivaltime; public boolean monitored; public boolean incongestion; public boolean inpanic; public String delay; public int delaysecs; public String blockref; public String next_stoppointref; public int next_visitnumber; public String next_stoppointname; public boolean vehicleatstop; public String next_destinationdisplay; public int next_aimedarrivaltime; public int next_expectedarrivaltime; public int next_aimeddeparturetime; public String destinationname_sv; public String next_stoppointname_sv; public String __tripref; public String __routeref; public String __directionid; public String originname_sv; public String next_destinationdisplay_sv; public ItemsBean(){} public ItemsBean(double latitude, String publishedlinename, String originname, String destinationname, String vehicleref, double longitude) { this.latitude = latitude; this.publishedlinename = publishedlinename; this.originname = originname; this.destinationname = destinationname; this.vehicleref = vehicleref; this.longitude = longitude; } public double getLatitude() { return latitude; } public void setLatitude(double latitude) { this.latitude = latitude; } public String getPublishedlinename() { return publishedlinename; } public void setPublishedlinename(String publishedlinename) { this.publishedlinename = publishedlinename; } public String getOriginname() { return originname; } public void setOriginname(String originname) { this.originname = originname; } public String getNext_destinationdisplay() { return destinationname; } public void setDestinationname(String destinationname) { this.destinationname = destinationname; } public String getVehicleref() { return vehicleref; } public void setVehicleref(String vehicleref) { this.vehicleref = vehicleref; } public double getLongitude() { return longitude; } public void setLongitude(double longitude) { this.longitude = longitude; } @Override public String toString() { return ';\';'; + ';[{ '; + ';latitude: '; + latitude + ';, '; + ';name: '; + publishedlinename + ';, '; + ';description: '; + publishedlinename + ';: '; + originname + '; ->; '; + destinationname + ';, '; + ';id: '; + vehicleref + ';, '; + ';longitude: '; + longitude + '; }]'; + ';\';';; } } </code> I've tried using a reader, but the result is always null. 2022-08-17 11:43:34,714 INFO [get-map-data] (vert.x-worker-thread-1) null 2022-08-17 11:43:34,715 INFO [get-map-data] (vert.x-worker-thread-1) Data for the map: http://data.foli.fi/siri/vm 2022-08-17 11:43:34,716 INFO [get-map-data] (vert.x-worker-thread-1) [{ latitude: 0.0, name: null, description: null: null ->; null, id: null, longitude: 0.0 }] | For filtering you could just use Jackson ObjectMapper and JsonNode to manually filter and map out the fields from the json response to list of FilteredResult objects. <code>package com.example;import java.util.ArrayList;import org.apache.camel.RoutesBuilder; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.model.dataformat.JsonLibrary; import org.apache.camel.test.junit4.CamelTestSupport; import org.junit.Test; import com.example.utilities.files.FileReadUtility;import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper;public class FoliFilter extends CamelTestSupport { @Test public void testRunFilter() { String json = FileReadUtility.readResourceAsString(';responses/foli.json';); template.sendBody(';direct:filterJson';, json); } @Override protected RoutesBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { from(';direct:filterJson';) .routeId(';filterJson';) .process(ex ->; { ObjectMapper objectMapper = new ObjectMapper(); JsonNode tree = objectMapper.readTree(ex.getMessage().getBody(String.class)); JsonNode vehicles = tree.path(';result';).path(';vehicles';); if (!vehicles.isMissingNode()) { ArrayList<FilteredResult>; filtered = new ArrayList<>;(); for (JsonNode jsonNode : vehicles) { //Many nodes seem to be missing most of the data, so using this to skip those entries. if(!jsonNode.has(';originname';)){ continue; } FilteredResult newFilteredResult = new FilteredResult(); newFilteredResult.setId(jsonNode.path(';originname';).asText(';Missing';)); newFilteredResult.setName(jsonNode.path(';publishedlinename';).asText(';Missing';)); String description = jsonNode.path(';publishedlinename';).asText(';Missing';) + ';: '; + jsonNode.path(';destinationname';).asText(';Missing';) + '; ->; '; + jsonNode.path(';originname';).asText(';Missing';); newFilteredResult.setDescription(description); newFilteredResult.setLongitude(jsonNode.path(';longitude';).asDouble(0.0)); newFilteredResult.setLatitude(jsonNode.path(';latitude';).asDouble(0.0)); filtered.add(newFilteredResult); } ex.getMessage().setBody(filtered); } }) .marshal().json(JsonLibrary.Jackson) .log(';${body}';); } }; } }class FilteredResult { private String id; private String name; private String description; private double latitude; private double longitude; public double getLatitude() { return latitude; } public void setLatitude(double latitude) { this.latitude = latitude; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getId() { return id; } public void setId(String id) { this.id = id; } public double getLongitude() { return longitude; } public void setLongitude(double longitude) { this.longitude = longitude; } } </code> There are probably ways to do this more elegantly in Camel and would also be interested to see how. I've also tried using JsonPath for stuff like this with mixed results. The FileReadUtility is just a utility class for loading text-files as strings from resources folder. <code>package com.example.utilities.files;import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets;import org.apache.commons.io.FileUtils;public final class FileReadUtility { private FileReadUtility(){} public static String readResourceAsString(String pathInResources) throws IOException{ ClassLoader classLoader = FileReadUtility.class.getClassLoader(); File file = new File(classLoader.getResource(pathInResources).getFile()); return FileUtils.readFileToString(file, StandardCharsets.UTF_8.name()); } public static byte[] readResourceAsBytes(String pathInResources) throws IOException{ ClassLoader classLoader = FileReadUtility.class.getClassLoader(); File file = new File(classLoader.getResource(pathInResources).getFile()); return FileUtils.readFileToByteArray(file); } } </code> Maven depedency for Apache Commons IO <code><dependency>; <groupId>;commons-io</groupId>; <artifactId>;commons-io</artifactId>; <version>;2.11.0</version>; </dependency>; </code> |
apache-camel | I'm trying to get in touch with Apache Camel, but it's behaviour is so far confusing. For example, I'm using platformHttp and declare a route under which my endpoint should be available. <code>from(platformHttp(';/api/test';)) .to(';https:google.com?bridgeEndpoint=true';) .setBody(simple(';${body}';)); </code> Calling it will call the sub-route https://google.com/api/test instead of https://google.com Why is that and how would I prevent Apache Camel from taking the route and appending it to the called route in my .to() ? | To prevent the HTTP exchange headers (I.e ones with names prefixed with <code>CamelHttp</code>) being propagated from the <code>platform-http</code> endpoint to the <code>http</code> endpoint, you can remove them like this. <code>from(platformHttp(';/api/test';)) .removeHeaders(';CamelHttp*';) .to(';https:google.com?bridgeEndpoint=true';) .setBody(simple(';${body}';)); </code> There's an FAQ article for this topic on the Camel website: https://camel.apache.org/manual/faq/how-to-remove-the-http-protocol-headers-in-the-camel-message.html |
apache-camel | I have a camel route that goes through a series of processors which each call some service. If processor 1 fails gracefully, I no longer want to call processors 2-5, but I do want to call <code>consolidateResponse</code>. The same for all the other processors. Is there a best practices way of achieving this without throwing an exception on failures? <code><camel:routeContext id=';myRouteRouteContext';>; <camel:route id=';my-route-route';>; <camel:from uri=';{{camel.uri.myRoute}}'; />; <camel:process ref=';{{bean.processor.processor1}}'; />; <camel:process ref=';{{bean.processor.processor21}}'; />; <camel:process ref=';{{bean.processor.processor3}}'; />; <camel:process ref=';{{bean.processor.processor4}}'; />; <camel:process ref=';{{bean.processor.processor5}}'; />; <!-- Stringfy response object into a JSon text response -->; <camel:process ref=';{{bean.processor.consolidateResponse}}'; />; <!-- All catch exception handler -->; <camel:onException>; <camel:exception>;java.lang.Exception</camel:exception>; <camel:handled>; <camel:constant>;true</camel:constant>; </camel:handled>; <camel:to uri=';{{camel.uri.error}}'; />; </camel:onException>; </camel:route>; </camel:routeContext>; </code> | I think try catch is best solution also it is common programming solution also camel also has stop https://camel.apache.org/manual/try-catch-finally.html <code>from(';direct:start';) .choice() .when(body().contains(';Hello';)).to(';mock:hello';) .when(body().contains(';Bye';)).to(';mock:bye';).stop() .otherwise().to(';mock:other';) .end() .to(';mock:result';); </code> |
apache-camel | How can I stop a thread in apache camel when I use jms for consuming an Ibm Mq? I'm consuming a jms and later I have to consume and Rest api, but I got errors of time out because the thread of jms continues, when is not necessary for the consume of the rest api. This is my route: <code>from(Rutas.CONSUME_CUENTA_DETALLE) .routeId(';CONSUME_CUENTA_DETALLE';) .removeHeaders(';*';) .setHeader(';CamelJmsDestinationName';, constant(';queue:///';+colaCuentaDetalle+';?targetClient=1';)) .to(';jms://queue:'; + colaCuentaDetalle +';?exchangePattern=InOut'; +';&;useMessageIDAsCorrelationID=true'; +';&;replyToType=Temporary'; +';&;requestTimeout=3s'; +';&;asyncStopListener=true'; +';&;cacheLevelName=CACHE_CONSUMER';) .id(';Cuenta_detalle';) .removeHeader(';*';) .to(Rutas.VALIDATE_RESPONSE_CUENTA_DETALLE) .end(); </code> | I can't see what type of consumer is at <code>Rutas.VALIDATE_RESPONSE_CUENTA_DETALLE</code>, but if you make it a <code>SEDA</code> consumer, it will use its own thread pool to handle messages, returning the JMS consumer thread back to its own pool. |
apache-camel | I've recently been working on setting up a project to use Azure and part of that involves requesting a token to access a REST API. I've been told that the token will expire in 30 minutes, but calling the API to get a new token isn't particularly expensive. I can do all this without any issue, but I'm curious if Camel has anything built in that can handle this for me without having to explicitly call to get a new token? | I don't know of anything built in, but you could have a timer route that runs every 25 minutes that requests a token and puts it in some kind of global state. <code>from(';timer:getAuthToken?period=1500000';) .to(';http:myKeyServer/getKey';) .process(new MyKeyProcessor()) // store in global state, static, spring, etc. </code> Then any route that needs the key can get it from global state and set it in a header or exchange property. |
apache-camel | I am facing an issue while trying to use Camel Debezium SQL server connector. I am trying to capture data changes in SQL server db table using camel Debezium SQL server connector and sink them to message broker. I know the JDBC SQL server connection has the option to make encrypt false to prevent this issue. But I can't find a similar way in Camel Debezium SQL server connector. To use Camel Debezium SQL server connector, I was following this documentation: https://camel.apache.org/components/3.18.x/debezium-sqlserver-component.html#_samples When I run the app it shows me following error:ERROR io.debezium.embedded.EmbeddedEngine - Error while trying to run connector class 'io.debezium.connector.sqlserver.SqlServerConnector' Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: The driver could not establish a secure connection to SQL Server by using Secure Sockets Layer (SSL) encryption. Error: ';PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target';.My POM is as follows: <code><dependencyManagement>; <dependencies>; <dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-parent</artifactId>; <version>;3.18.1-SNAPSHOT</version>; <scope>;import</scope>; <type>;pom</type>; </dependency>; </dependencies>; </dependencyManagement>; <dependencies>; <dependency>; <groupId>;org.springframework.boot</groupId>; <artifactId>;spring-boot-starter</artifactId>; </dependency>; <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-debezium-sqlserver</artifactId>; </dependency>; <dependency>; <groupId>;com.microsoft.sqlserver</groupId>; <artifactId>;mssql-jdbc</artifactId>; <version>;11.2.0.jre11</version>; </dependency>; <dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-jackson</artifactId>; </dependency>; <dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-kafka</artifactId>; </dependency>; </dependencies>; </code> I am using: spring-boot:2.7.2 SQL Server:docker image: mcr.microsoft.com/mssql/server:2022-latest Kafka image: confluentinc/cp-zookeeper:latest Can anyone help me to resolve this issue? | <code><dependency>; <groupId>;com.microsoft.sqlserver</groupId>; <artifactId>;mssql-jdbc</artifactId>; <version>;9.2.1.jre11</version>; </dependency>; </code> Finally I was able to solve the issue by downgrading the mssql-jdbc driver to the above one. |
apache-camel | I have the following service.Spring boot 2.5.13 Camel 3.18.0 JMSI want to use an embedded ActiveMQ Artemis, standalone ActiveMQ Artemis, and IBM MQ. I've managed to get all 3 running and connecting, but one thing I cant figure out is the JMSReplyTo option. Running locally with embedded broker: This runs fine. I can write a message to the queue and a response is send to the JMSReplyTo: <code>public void sendRequest(){ ActiveMQQueue activeMQQueue = new ActiveMQQueue(';RESPONSE_QUEUE';); jmsTemplate.convertAndSend(';REQUEST_QUEUE';, ';Hello';, pp ->; { pp.setJMSReplyTo(activeMQQueue); return pp; }); } </code> Via ActiveMQ Artemis console: This is where the inconstancy comes as the <code>Object</code> received is an <code>ActiveMQDestination</code> which makes setting the <code>CamelJmsDestination</code> much more involved. Am I wasting my time here? Should I just grab the queue name and construct the uri manually? Or I am missing some logic as to how this works? Or maybe I'm not using the Artemis console in the correct way? <code>.setExchangePattern(ExchangePattern.InOut) .setHeader(';CamelJmsDestination';, header(';JMSReplyTo';)) </code> | When using <code>javax.jms.Message#setJMSReplyTo(Destination)</code> you have to pass a <code>javax.jms.Destination</code> which must implement one of the following:<code>javax.jms.Queue</code> <code>javax.jms.TemporaryQueue</code> <code>javax.jms.Topic</code> <code>javax.jms.TemporaryTopic</code>In order to reproduce this semantic via text in the web console of ActiveMQ Artemis you need to prefix your destination's name with one of the following respectively:<code>queue://</code> <code>temp-queue://</code> <code>topic://</code> <code>temp-topic://</code>So when you set the <code>JMSReplyTo</code> header try using <code>queue://RESPONSE_QUEUE</code>. When your application then receives this message and invokes <code>getJMSReplyTo()</code> it will receive a <code>javax.jms.Queue</code> implementation (i.e. <code>ActiveMQQueue</code>) and then you can use <code>getQueueName()</code> to get the <code>String</code> name of the queue if necessary. |
apache-camel | I am using Spring Boot and Apache Camel in my application and deploying in JBoss EAP 7.3.0 as war files. Previously the startup logs and logs from the application were getting logged to the log file when I was using log4j 1.x and the below log4j.properties: <code>log4j.rootLogger = INFO, out, FILElog4j.appender.out=org.apache.log4j.ConsoleAppender log4j.appender.out.layout=org.apache.log4j.PatternLayout log4j.appender.out.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p %c{1}:%L - %m%nlog4j.appender.FILE=org.apache.log4j.DailyRollingFileAppender log4j.appender.FILE.File=fileName.log log4j.appender.FILE.DatePattern='.'yyyy-MM-dd log4j.appender.FILE.MaxFileSize=200MB log4j.appender.FILE.MaxBackupIndex=20 log4j.appender.FILE.layout=org.apache.log4j.PatternLayout log4j.appender.FILE.layout.conversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p %c{1}:%L - %m%n </code> Now I have shifted to log4j 2.17.1 and using the below lg4j2.properties: <code>rootLogger.level = INFO property.filename = fileName.log appenders = FILE, consoleappender.console.type = Console appender.console.name = STDOUT appender.console.layout.type = PatternLayout appender.console.layout.pattern = %d %5p [%t] (%F:%L) - %m%nappender.FILE.type = RollingFile appender.FILE.name = File appender.FILE.fileName = ${filename} appender.FILE.filePattern = ${filename}.%d{yyyy-MM-dd} appender.FILE.layout.type = PatternLayout appender.FILE.layout.pattern = %d{yyyy-MM-dd HH:mm:ss} %c{1} [%p] %m%n appender.FILE.policies.type = Policies appender.FILE.policies.time.type = TimeBasedTriggeringPolicy appender.FILE.policies.time.interval = 1rootLogger.appenderRefs = FILE, consolerootLogger.appenderRef.console.ref = STDOUT rootLogger.appenderRef.FILE.ref = File </code> But now only the below logs are coming during application startup and no logs are gettig logged from the application: 2022-08-13 00:52:12 ContextLoader [INFO] Root WebApplicationContext: initialization started 2022-08-13 00:52:31 ContextLoader [INFO] Root WebApplicationContext initialized in 19250 ms Can anyone please suggest what am I doing wrong? To add, I can see the logs from Spring Boot ApplicationContext during startup, but not the logs which are logged by the application. This is kind of strange. | Also I don't know how exactly you have it configured and packaged, but you may need to exclude the logging subsystem via jboss-deployment-structure.xml (located in war/WEB-INF or ear/META-INF): <code><?xml version=';1.0'; encoding=';UTF-8';?>; <jboss-deployment-structure xmlns=';urn:jboss:deployment-structure:1.3';>; <deployment>; <exclude-subsystems>; <!-- disable the logging subsystem because the application manages its own logging independently -->; <subsystem name=';logging'; />; </exclude-subsystems>; </deployment>; </jboss-deployment-structure>; </code> In the case of ear you'll also need to handle exclusions for any included modules via the sub-deployment elements, or try to use ear-exclusions-cascaded-to-subdeployments (available since jboss-deployment-structure:1.3): <code><?xml version=';1.0'; encoding=';UTF-8';?>; <jboss-deployment-structure xmlns=';urn:jboss:deployment-structure:1.3';>; <ear-exclusions-cascaded-to-subdeployments>;true</ear-exclusions-cascaded-to-subdeployments>; <deployment>; <exclude-subsystems>; <!-- disable the logging subsystem because the application manages its own logging independently -->; <subsystem name=';logging'; />; </exclude-subsystems>; </deployment>; </jboss-deployment-structure>; </code> |
apache-camel | I am able to trigger my job using <code>delay</code> but I am not able to trigger using <code>schedule</code> parameter. Here's my attempt (not triggering - I also tried to replace empty spaces for ';+'; and also tried to use <code>schedule</code> instead of <code>scheduler.cron</code>): <code>fromF(';master:.../...:scheduler:MyJob?scheduler.cron=0/1 * * * *';) .routeId(';JobTimer';) .toF(';direct:%s';, JOB_NAME) .end(); </code> If I stop using <code>scheduler.cron</code> and start using the following uri, it works: <code>fromF(';master:.../...:scheduler:MyJob?delay=...';) </code> My version: <code>api group: 'org.apache.camel.springboot', name: 'camel-spring-boot', version: camelVersion camelVersion = 3.9.0 </code> Any ideas? Thank you! | For some reason it's not triggering when using the 5 parts cron but I am able to trigger using 6 or 7 parts cron. Triggering everyday at 8 AM for example: <code>0 0 8 * * ?</code> Reference: http://www.quartz-scheduler.org/documentation/quartz-2.3.0/tutorials/crontrigger.html#examples |
apache-camel | I have a Quarkus app that uses Apache-Camel and runs fine locally. When I build it and try to run the docker container then I get the following error: <code>ERROR [io.qua.run.Application] (main) Failed to start application (with profile prod): java.lang.ClassNotFoundException: org.apache.camel.http.base.HttpOperationFailedException at org.apache.camel.quarkus.core.CamelQuarkusClassResolver.resolveMandatoryClass(CamelQuarkusClassResolver.java:68) at org.apache.camel.reifier.errorhandler.ErrorHandlerReifier.createExceptionClasses(ErrorHandlerReifier.java:197) at org.apache.camel.reifier.errorhandler.ErrorHandlerReifier.addExceptionPolicy(ErrorHandlerReifier.java:177) at org.apache.camel.reifier.errorhandler.ErrorHandlerReifier.configure(ErrorHandlerReifier.java:220) at org.apache.camel.reifier.errorhandler.DefaultErrorHandlerReifier.createErrorHandler(DefaultErrorHandlerReifier.java:53) at org.apache.camel.impl.DefaultModelReifierFactory.createErrorHandler(DefaultModelReifierFactory.java:65) at org.apache.camel.reifier.errorhandler.ErrorHandlerRefReifier.createErrorHandler(ErrorHandlerRefReifier.java:36) at org.apache.camel.impl.DefaultModelReifierFactory.createErrorHandler(DefaultModelReifierFactory.java:65) at org.apache.camel.reifier.ProcessorReifier.wrapInErrorHandler(ProcessorReifier.java:751) at org.apache.camel.reifier.ProcessorReifier.wrapChannelInErrorHandler(ProcessorReifier.java:732) at org.apache.camel.reifier.ProcessorReifier.wrapChannel(ProcessorReifier.java:711) at org.apache.camel.reifier.ProcessorReifier.wrapChannel(ProcessorReifier.java:617) at org.apache.camel.reifier.ProcessorReifier.wrapProcessor(ProcessorReifier.java:613) at org.apache.camel.reifier.ProcessorReifier.makeProcessor(ProcessorReifier.java:860) at org.apache.camel.reifier.ProcessorReifier.addRoutes(ProcessorReifier.java:585) at org.apache.camel.reifier.RouteReifier.doCreateRoute(RouteReifier.java:236) at org.apache.camel.reifier.RouteReifier.createRoute(RouteReifier.java:74) at org.apache.camel.impl.DefaultModelReifierFactory.createRoute(DefaultModelReifierFactory.java:49) at org.apache.camel.impl.DefaultCamelContext.startRouteDefinitions(DefaultCamelContext.java:887) at org.apache.camel.impl.DefaultModel.addRouteDefinitions(DefaultModel.java:190) at org.apache.camel.impl.DefaultCamelContext.addRouteDefinitions(DefaultCamelContext.java:344) at org.apache.camel.builder.RouteBuilder.populateRoutes(RouteBuilder.java:676) at org.apache.camel.builder.RouteBuilder.addRoutesToCamelContext(RouteBuilder.java:529) at org.apache.camel.impl.engine.AbstractCamelContext.addRoutes(AbstractCamelContext.java:1175) at io.quarkus.arc.impl.EventImpl$Notifier.notifyObservers(EventImpl.java:323) at io.quarkus.arc.impl.EventImpl$Notifier.notify(EventImpl.java:305) at io.quarkus.arc.impl.EventImpl.fire(EventImpl.java:73) at io.quarkus.arc.runtime.ArcRecorder.fireLifecycleEvent(ArcRecorder.java:130) at io.quarkus.arc.runtime.ArcRecorder.handleLifecycleEvents(ArcRecorder.java:99) at io.quarkus.deployment.steps.LifecycleEventsBuildStep$startupEvent1144526294.deploy_0(Unknown Source) at io.quarkus.deployment.steps.LifecycleEventsBuildStep$startupEvent1144526294.deploy(Unknown Source) at io.quarkus.runner.ApplicationImpl.doStart(Unknown Source) at io.quarkus.runtime.Application.start(Application.java:101) at io.quarkus.runtime.ApplicationLifecycleManager.run(ApplicationLifecycleManager.java:103) at io.quarkus.runtime.Quarkus.run(Quarkus.java:67) at io.quarkus.runtime.Quarkus.run(Quarkus.java:41) at io.quarkus.runtime.Quarkus.run(Quarkus.java:120) at io.quarkus.runner.GeneratedMain.main(Unknown Source) </code> My gradle dependencies are <code>dependencies { implementation 'io.quarkus:quarkus-container-image-docker' implementation enforcedPlatform(';${quarkusPlatformGroupId}:${quarkusPlatformArtifactId}:${quarkusPlatformVersion}';) implementation enforcedPlatform(';${quarkusPlatformGroupId}:quarkus-camel-bom:${quarkusPlatformVersion}';) implementation 'io.quarkus:quarkus-arc' implementation 'io.quarkus:quarkus-config-yaml'implementation 'io.quarkus:quarkus-smallrye-jwt' implementation 'io.quarkus:quarkus-smallrye-health' implementation 'io.quarkus:quarkus-smallrye-metrics' implementation 'io.quarkus:quarkus-smallrye-openapi' implementation 'io.quarkus:quarkus-smallrye-jwt-build'implementation 'io.quarkus:quarkus-jackson' implementation 'io.quarkus:quarkus-resteasy-jackson' implementation 'io.quarkus:quarkus-resteasy'implementation 'org.apache.camel.quarkus:camel-quarkus-file' implementation 'org.apache.camel.quarkus:camel-quarkus-core' implementation 'org.apache.camel.quarkus:camel-quarkus-base64' implementation 'org.apache.camel.quarkus:camel-quarkus-ahc' implementation 'org.apache.camel.quarkus:camel-quarkus-jackson' implementation 'org.apache.camel.quarkus:camel-quarkus-ftp' implementation 'org.apache.camel.quarkus:camel-quarkus-rest' implementation 'org.apache.camel.quarkus:camel-quarkus-http'implementation group: 'org.apache.httpcomponents', name: 'httpmime', version: '4.3.1'testImplementation 'io.quarkus:quarkus-junit5' testImplementation 'io.rest-assured:rest-assured'compileOnly 'org.projectlombok:lombok:1.18.16' </code> } When I run it with ';quarkus dev'; in IntelliJ Terminal I have no problems. Do I try to run the container I get the error. Why does it happen? I have no clue how to solve it. Edit: Where the HttpException ist handled: <code> onException(HttpOperationFailedException.class) .process(new HttpExceptionHandler()) .maximumRedeliveries(5) .redeliveryDelay(1000L) .backOffMultiplier(2) .retryAttemptedLogLevel(LoggingLevel.WARN) .handled(true) .stop(); </code> The Handler itself: <code>import org.apache.camel.Exchange; import org.apache.camel.component.file.FileConstants; import org.apache.camel.http.base.HttpOperationFailedException; import org.jboss.logging.Logger;public class HttpExceptionHandler implements org.apache.camel.Processor {private static final Logger LOG = Logger.getLogger(HttpExceptionHandler.class);@Override public void process(Exchange exchange) { HttpOperationFailedException failedException = exchange.getProperty( Exchange.EXCEPTION_CAUGHT, HttpOperationFailedException.class); ...} </code> } | When using <code>onException</code> in your routes, the class that you define needs to be registered for reflection in order for it to work in native mode. So if you have <code>.onException(HttpOperationFailedException.class)</code>, then <code>HttpOperationFailedException</code> needs to be registered for reflection. For example: <code>@RegisterForReflection(targets = HttpOperationFailedException.class) public class Routes extends RouteBuilder { public void configure() { // Route configuration goes here } } </code> There's some more information in the Camel Quarkus user guide about this: https://camel.apache.org/camel-quarkus/2.11.x/user-guide/native-mode.html#using-onexception-clause-in-native-mode I opened an issue to improve things for the future so that <code>HttpOperationFailedException</code> does not need to be manually registered. https://github.com/apache/camel-quarkus/issues/3971 |
apache-camel | I am reading and processing 2 files from 2 different file locations and comparing the content. If 2nd file is not available , the rest of the process execute with 1st file. If 2nd file is available, comparison process should happen. For this I am using camel pollEnrich, but here the problem is that, camel is picking the 2nd file at first time only. Without restarting the camel route 2nd file is not getting picked up even if it is present there. After restarting the camel route it is working fine, but after that its not picking the 2nd file. I am moving the files to different locations after processing it. Below is my piece of code, <code>from(';sftp:'; + firstFileLocation + ';?privateKeyFile='; + ppkFileLocation + ';&;username='; + sftpUsername + ';&;readLock=changed&;idempotent=true&;move='; + firstFileArchiveLocation) .pollEnrich(';sftp:'; + secondFileLocation + ';?privateKeyFile='; + ppkFileLocation + ';&;username='; + sftpUsername + ';&;readLock=changed&;idempotent=true&;fileExist=Ignore&;move=';+ secondFileLocationArchive ,10000,new FileAggregationStrategy()) .routeId(';READ_INPUT_FILE_ROUTE';) </code> Need help. | You're setting <code>idempotent=true</code> in the sftp consumer, which means camel will not process the same file name twice. Since you're moving the files, it would make sense to set <code>idempotent=false</code>. Quoted from camel documentationOption to use the Idempotent Consumer EIP pattern to let Camel skip already processed files. Will by default use a memory based LRUCache that holds 1000 entries. If noop=true then idempotent will be enabled as well to avoid consuming the same files over and over again. |
apache-camel | Essentially - how is it possible to use Camel's Aggregator with a File based input? By default, when an Exchange created using the File component's input completes its Route the file is moved to <code>$inputLocation/.camel/</code>. However, when using an Aggregator, after the Exchange goes through the aggregation step it goes on to complete the remainder of the Route outside of the Aggregation step (which there may or may not be). This means that the Exchange finishes the Route and if a File Consumer was used it causes the file to be moved to <code>$inputLocation/.camel/</code>. At some later time the Aggregator will complete and when it does so the aggregated File references will be invalid, because the file was moved on disk when the regular Exchange completed the Route. The following depicts a simple Route that shows the issue. The referenced Processor <code>doSomethingWithTheAggregatedFiles</code> will find that the files in question do not exist at their stated location (as they have already been moved (to <code>workdirs/in/.camel/</code>): <code> @Override public void configure() throws Exception { from(';file:workdirs/in/';) .aggregate(constant(true), AggregationStrategies.groupedExchange()) .completionTimeout(10*1000) // 10 seconds .process(';doSomethingWithTheAggregatedFiles';) .end() .log(';file completed route: $simple{header[CamelFileName]}';) .end(); } </code> Is there something missing here? Is there no way to get it to ';wait'; until the aggregated exchange completes? Looking at the <code>ZipAggregationStrategy</code> I see that it doesn't suffer this issue because it reads the content of the files during the aggregation step and adds it into the ZIP file - essentially taking a copy of the data as the aggregation step occurs. Preferably I do not want to take a copy, as my input may be large. | You could set the file consumer's noop to <code>true</code> and implement a simple processor to move the files after your aggregation is complete. <code>.process(e ->; { String name = e.getIn().getHeader(';CamelFileNameConsumed';, String.class); Files.move( Path.of(name), Path.of(';.camel';).resolve(';name';)); }) </code> Another solution that might work for you is to force the Aggregator to run in the same thread as its caller: <code>.aggregate(constant(true), AggregationStrategies.groupedExchange()) .executorService(new SynchronousExecutorService()) ... </code> This results in all aggregations completing prior to the File component being notified that the route is complete. |
apache-camel | I am new to apache camel features. So I have a problem with the DefaultErrorHandler in our project. There are some errors in which we are not using any custom error handler. Whenever an exception occurs, apache camel logs it and this log level is ERROR. Apache camel is handling failure through DefaultErrorHandler which propagates exceptions back to the caller since there isn’t any custom error handler. This errors are like ';User not found'; so this shouldn't be a ERROR, this can be a WARN or INFO. Since we are not handling it, DefaultErrorHandler by Apache Camel handles it. The error log like this on the server: <code> main 2022-08-05 15:24:43.537 ERROR [user-manager] 1 --- [nio-8080-exec-5] o.a.c.p.e.DefaultErrorHandler : Failed delivery for (MessageId:-0000000 on Exc │ │ │ main +[ │ │ │ main +[ Message History (complete message history is disabled) │ │ │ main +[ --------------------------------------------------------------------------------------------------------------------------------------- │ │ │ main +[ RouteId ProcessorId Processor Elapsed (ms) │ │ │ main +[ [PostUserToIdentity] [PostUserToIdentity] [from[direct://business.postUserToIdentity] ] [ 27] │ │ │ main +[ ... │ │ │ main +[ [PostUserToIdentity] [to58 ] [direct:postUserToIdentityRequestedInternal ] [ 0] │ │ │ main +[ │ │ │ main +[ Stacktrace │ │ │ main +[ --------------------------------------------------------------------------------------------------------------------------------------- │ │ │ main +[ │ │ │ main │ │ │ main com.user.manager.exception.ConflictException: User already exists </code> So, I wrote a Custom Handler and a RouteClass which extends the RouteBuilder with the proper Camel OnException clause. OnConflictExceptionRoute Class <code>@Component public class OnConflictExceptionRoute extends RouteBuilder { @Override public void configure() { log.info(';Configuring extended create user by context route';); onException(ConflictException.class) .process(new ConflictExceptionHandler()) .handled(true); from(';direct:business.postUserToIdentity';) .routeId(';PostUserToIdentity';) .onException(ConflictException.class) .process(new ConflictExceptionHandler()); } } </code> Custom Error Handler <code>@Slf4j public class ConflictExceptionHandler implements Processor { @Override public void process(Exchange exchange) { log.info(';USER ALREADY EXISTS!';); throw new ConflictException().withMessage(';USER ALREADY EXISTS!';); } } </code> At the application startup, I could see that the Configure method in the RouteClass is triggered. But when I am triggering the flow, I am still seeing the same error is handling by the DefaultErrorHandler. Why it is not working? Is there any missing configuration? Thanks. | So after a deep analysis, I found that I'd to resolve this issue with the service that we called in the application by extending the RouteBuilder class like this. <code> @Override protected ErrorHandlerFactory createErrorHandlerBuilder() { DefaultErrorHandlerBuilder errorHandlerBuilder = super.defaultErrorHandler(); // Changed from ERROR because it is expected that the service handles the exception. errorHandlerBuilder.setLevel(LoggingLevel.INFO.toString()); RedeliveryPolicyDefinition policy = new RedeliveryPolicyDefinition(); policy.setDisableRedelivery(';false';); policy.setRetriesExhaustedLogLevel(getRetriesExhaustedLogLevel().toString()); errorHandlerBuilder.setRedeliveryPolicy(policy); return errorHandlerBuilder; } </code> Note : ExhaustedLogLevel is setted as DEBUG. |
apache-camel | I use Apache Camel in a Spring Boot Java project. I have to parse a csv and split the lines with a separator. I use camel bindy to parse the csv and read it as a pojo bean class. Here is how I configure the camel bindy <code>@CsvRecord( separator = ';,'; ) public Class MyClass { } </code> Here is my question: how can I change the separator value dynamically, reading it from a property? I've tried <code>@CsvRecord( separator = ';${my-prop.separator}'; )</code> but it did not work. | Not that I know of. If you have a known set of delimiters, you could have a separate DTO class (w/ @CsvRecord annotation) for each one, i.e. MyClassComma, MyClassSemicolon, etc. Then at runtime choose the correct DTO class based on a spring property that specifies the delimiter. |
apache-camel | I've found here that the default behaviour for FromXmlParser.Feature.EMPTY_ELEMENT_AS_NULL has changed from true (2.9 - 2.11) to false (2.12 onwards), so from that version no automatic coercion is done from empty elements like into null. I was using Apache Camel 2.25 and that version had this feature enabled by default but now, with this change, is disabled in Camel 3.x. How can I enable it in back in Camel 3 using XML DSL? I know using XMLMapper is easy enough: <code>XmlMapper xmlMapper = new XmlMapper(); xmlMapper.configure(FromXmlParser.Feature.EMPTY_ELEMENT_AS_NULL, true); </code> But in Camel XML DSL the allowed enums are only the ones from SerializationFeature, DeserializationFeature and MapperFeature. I've tried with some of them but with no luck. <code><unmarshal>; <jacksonxml disableFeatures=';FAIL_ON_UNKNOWN_PROPERTIES'; enableFeatures=';ACCEPT_EMPTY_STRING_AS_NULL_OBJECT,ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT'; unmarshalTypeName=';com.my.class.Result'; include=';NON_NULL'; />; </unmarshal>; </code> | You can set a custom xmlMapper on the jacksonxml element, the attribute is called ';xmlMapper'; you can then reference your custom XmlMapper which should be declared as a bean, but this is important, you must include a # before the bean name or else the object mapper will not be looked up and will be set to null and a default one will be created. <code> @Bean public XmlMapper customXMLMapper(){ return XmlMapper.builder() .configure(EMPTY_ELEMENT_AS_NULL, true) .configure(FAIL_ON_UNKNOWN_PROPERTIES, false) .build(); } </code> <code><unmarshal>; <jacksonxml unmarshalTypeName=';com.myclass.Result'; xmlMapper=';#customXMLMapper';/>; </unmarshal>; </code> |
apache-camel | For my Kotlin application with Spring-Boot 2.7.0 and Apache Camel 3.17.0, I am running into a rather surprising issue: I have a set of JUnit 5 test cases that individually run fine (using <code>mvn test -DTest=';MyTest';</code>); but when run in batch via <code>mvn test</code> or in IntelliJ IDEA, some test cases fail with <code>org.apache.camel.FailedToCreateRouteException... because of Cannot set tracer on a started CamelContext</code>. The funny thing is, that these test cases do not have tracing enabled. My test setup looks like the following for most of the tests: <code>@CamelSpringBootTest @SpringBootTest( classes = [TestApplication::class], properties = [';camel.springboot.java-routes-include-pattern=**/SProcessingTestRoute';] ) @TestConstructor(autowireMode = TestConstructor.AutowireMode.ALL) @UseAdviceWith internal class ProcessingTest( val template: FluentProducerTemplate, @Value(';classpath:test-resource';) private val TestResource: Resource, val camelContext: CamelContext ) { @EndpointInject(';mock:result';) lateinit var resultMock: MockEndpoint @Test fun `test my route`() { AdviceWith.adviceWith(camelContext, ';processing-route';) { route ->; route.weaveAddLast().to(';mock:result';) } resultMock.expectedCount = 1 camelContext.start() // ... // here comes the actual test } } </code> There are a couple of tests where I do not advice routes; i.e., these test cases do not have the <code>@AdviceWith</code> annotation, and these test cases do not fail during the batch run. Debugging this issue is hard; therefore, I would highly appreciate any pointers, hints, or hypothesis for potential causes, and ideas on what to try to narrow down the problem! | You probably need a fresh camel context for each test. Try adding <code>@DirtiesContext</code> to each test class. If that doesn't work, add it to each test method. |
apache-camel | In camel version 3.16.0 embedded routes were removed from the rest definition: https://issues.apache.org/jira/browse/CAMEL-17675 This introduces this problem: Parsing Multipart as a Stream We expose a rest endpoint where a user can upload a <code>multipart/form-data</code> request which has metadata and files alike. Until now we used apache to parse the request and save the file parts into a temporary folder: <code>Message message = exchange.getMessage(); HttpServletRequest request = message.getBody(HttpServletRequest.class); ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory()); List<FileItem>; items = servletFileUpload.parseRequest(request); // Iterate over items, save files, parse meta-data etc. </code> This now throws an exception because the InputStream of the Request is closed. Using a different way of parsing the multipart request is unfortunatelly not really an option because we potentially receive very big files, that we just have to read via a Stream. The fact that its closed means all the content has been read and all that file data is in the ram which will not go well. | I found the solution. In order for the stream to stay open you have to tell camel to not use stream caching: <code>getCamelContext().setStreamCaching(false); </code> When using spring Boot the alternative is setting it via the config: <code>camel: springboot: stream-caching-enabled: false </code> Both will disable stream caching globally. I have not found a way to diable it for just one rest endpoint, but it will do the trick |
apache-camel | My project need a split then aggregate operation rather than the integrated split+aggregate but I don't have any clue about how propagate an exception to stop further processing. In the example below I'll need to be able to not make the last log if an exception was thrown in post aggregation. <code>@RunWith(SpringJUnit4ClassRunner.class) public class AggregationExceptionTest extends CamelTestSupport { private final Logger LOGGER = LoggerFactory.getLogger(AggregationExceptionTest.class); @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { from(';direct:start';) .split(body()).streaming().stopOnException().parallelProcessing() .aggregate(new AggregationStrategy() { @Override public Exchange aggregate(Exchange oldExchange, Exchange newExchange) { if (newExchange.getException() != null) { LOGGER.info(';exception propagated';); } return oldExchange==null?newExchange:oldExchange; } }).constant(true) .completionSize(1).completionTimeout(500) .log(LoggingLevel.INFO, LOGGER, ';Aggreg ${body}';) .throwException(Exception.class, ';propagate plz';) .end() .end() .process(e ->; { LOGGER.info(';I don't want to be seen, because of {}';, e.getException()); }); } }; } @Test public void test1() throws InterruptedException { template.sendBody(';direct:start';, Arrays.asList(';A';, ';B';, ';C';, ';D';)); Thread.sleep(5000); } } </code> The exception thrown is never visible in the aggregate method. | I'm not sure this is possible. Aggregator output is completely separated from the route that invokes it. It also operates in its own thread, unless you supply it a <code>SynchronousExecutorService</code> instance. You might try the <code>SynchronousExecutorService</code> option: <code>.aggregate(constant(1), new YourAggregator()) .executorService(new SynchronousExecutorService()) </code> Before your split, set a <code>Map</code> instance in the header with a key called <code>exception</code>, value null initially. Then in the aggregator output, if an exception occurs, update that Map key with the exception. Then in your split, you can check the Map key for an Exception instance, and do whatever you want, e.g., splitter's <code>stopOnException</code> option. |
apache-camel | I am trying to search for a regex in the text and seperate the substrings by the delimiter ';, ';. Currently I am facing the problem that the second delimiter character '; '; space is being trimed after passing it to the bean. Regarding the Apache Camel docu there is 5 bean method options (ref, method, beanType, scope and trim) to use. How can I set the trim option to prevent removing the space character from the delimiter in the bean? DSL code <code>static final String DELIMITER = ';, ';; .setProperty(';regex';, simple(REGEX)) .setProperty(';delimiter';, simple(DELIMITER)) .bean(';regexAgrsMessageBean';, ';searchRegexInText';) //how can I set the trim option here </code> Bean <code>@Component public class RegexAgrsMessageBean { public static String searchRegexInText(@Body String text, @ExchangeProperty(';regex';) String regex, @ExchangeProperty(';delimiter';) String delimiter) { LOGGER.info(';delimiter: '';+delimiter+';'';); return ';';; } } </code> https://camel.apache.org/components/3.15.x/languages/bean-language.html enter image description here camel.version: 3.15.0 | Have you tried <code>// 2nd param to constant() is trim .setProperty(';delimiter';, constant(DELIMITER, false)) </code> |
apache-camel | I'm new to Apache Camel and learning its basics. I'm using Yaml DSL I have a TGZ file which includes 2 small CSV files. I am trying to decompress the file using gzipDeflater, but when I print the body after the extraction, it includes some data about the CSV (filename, my username, some numbers) - that is preventing me from parsing the CSV only by its known columns. since the extracted file includes lines that were not included in the original CSV, whenever one of those lines is processed, i get an exception. Is there a way for me to ';ignore'; those lines, or perhaps another functionality of Apache Camel that will let me access only the content of those CSV's? Thanks! | You probably have a gzipped tar file, which is a slightly different thing than just a deflate compressed file. Try this (convert to YAML if you'd like): <code>from(';file:filedir';) .unmarshal().gzip() .split(new TarSplitter()) // process/unmarshal CSV </code> |
apache-camel | I'm facing a problem retrieving an Object from MinIO Server through Apache Camel . I'm using a ';third party'; library (that I cannot change directly) which use the following approach to connect to camel and download objects: <code>ConsumerTemplate template = context.createConsumerTemplate(); byte[] content = template.receiveBody(uri, timeout, byte[].class); </code> To this code i pass my ';camel flavored'; uri for MinIO with the following format: <code> String camelUri = ';minio://myBucketName?prefix=hello.txt';); </code> I'm configuring the Apache Camel component like this for MinIO: <code>@Bean public MinioClient minioClient() { return new MinioClient.Builder() .credentials(accessKey, secretKey) .endpoint(url) .build(); } @Bean public CamelContext camelContext(MinioClient client) { CamelContext context = new DefaultCamelContext(); context.setTracing(true); context.start(); MinioComponentBuilder minioCompBuilder = ComponentsBuilderFactory.minio().minioClient(client).secure(true); minioCompBuilder.register(context, ';minio';); return context; } </code> Enabling the TRACE level I can see that camel is able to establish a connection, by first verifing that the bucket already exists,but nothing is returned. Following the configuration options to be passed as query string I did try as well the option : <code>String camelUri = ';minio://myBucketName?objectName=hello.txt; </code> Still nothing is returned. In the log : <code>';message';:';Starting service: minio://myBucketName?prefix=hello.txt&;startScheduler=false'; ';message';:';Querying whether bucket myBucketName already exists...'; ';message';:';Bucket myBucketName already exists'; ';message';:';Started service: minio://myBucketName?prefix=hello.txt&;startScheduler=false'; ';message';:';<<<< minio://myBucketName?prefix=hello.txt&;startScheduler=false'; ';message';:';Creating service from endpoint: minio://myBucketName?prefix=hello.txt&;startScheduler=false'; ';message';:';Creating EventDrivenPollingConsumer with queueSize: 1000 blockWhenFull: true blockTimeout: 0 copy: false'; ';message';:';Building service: PollingConsumer on minio://myBucketName?prefix=hello.txt&;startScheduler=false'; ';message';:';Built service: PollingConsumer on minio://myBucketName?prefix=hello.txt&;startScheduler=false'; ';message';:';Initializing service: PollingConsumer on minio://myBucketName?prefix=hello.txt&;startScheduler=false'; ';message';:';Building service: MinioConsumer[minio://myBucketName?prefix=hello.txt&;startScheduler=false]'; ';message';:';Build consumer: MinioConsumer[minio://myBucketName?prefix=hello.txt&;startScheduler=false]'; ';message';:';Building service: org.apache.camel.impl.engine.PrototypeExchangeFactory@427e563c'; ';message';:';Warming up PrototypeExchangeFactory loaded class: org.apache.camel.support.DefaultExchange'; ';message';:';Built service: org.apache.camel.impl.engine.PrototypeExchangeFactory@427e563c'; ';message';:';Warming up DefaultConsumer loaded class: org.apache.camel.support.DefaultConsumer$DefaultConsumerCallback'; ';message';:';Built service: MinioConsumer[minio://myBucketName?prefix=hello.txt&;startScheduler=false]'; ';message';:';Initializing service: MinioConsumer[minio://myBucketName?prefix=hello.txt&;startScheduler=false]'; ';message';:';Init consumer: MinioConsumer[minio://myBucketName?prefix=hello.txt&;startScheduler=false]'; ';message';:';Initializing service: org.apache.camel.impl.engine.PrototypeExchangeFactory@427e563c'; ';message';:';Initialized service: org.apache.camel.impl.engine.PrototypeExchangeFactory@427e563c'; ';message';:';Initialized service: MinioConsumer[minio://myBucketName?prefix=hello.txt&;startScheduler=false]'; ';message';:';Initialized service: PollingConsumer on minio://myBucketName?prefix=hello.txt&;startScheduler=false'; ';message';:';Starting service: PollingConsumer on minio://myBucketName?prefix=hello.txt&;startScheduler=false'; ';message';:';Started service: PollingConsumer on minio://myBucketName?prefix=hello.txt&;startScheduler=false'; ';message';:';Acquired service: PollingConsumer on minio://myBucketName?prefix=hello.txt&;startScheduler=false'; ';message';:';Before poll minio://myBucketName?prefix=hello.txt&;startScheduler=false'; ';message';:';Starting service: MinioConsumer[minio://myBucketName?prefix=hello.txt&;startScheduler=false]'; ';message';:';Starting consumer: MinioConsumer[minio://myBucketName?prefix=hello.txt&;startScheduler=false]'; ';message';:';Starting service: org.apache.camel.impl.engine.PrototypeExchangeFactory@427e563c'; ';message';:';Started service: org.apache.camel.impl.engine.PrototypeExchangeFactory@427e563c'; ';message';:';Service: PollingConsumer on minio://myBucketName?prefix=hello.txt&;startScheduler=false already started'; ';message';:';Building service: org.apache.camel.support.DefaultScheduledPollConsumerScheduler@1c0e57e4'; ';message';:';Built service: org.apache.camel.support.DefaultScheduledPollConsumerScheduler@1c0e57e4'; ';message';:';Initializing service: org.apache.camel.support.DefaultScheduledPollConsumerScheduler@1c0e57e4'; ';message';:';Initialized service: org.apache.camel.support.DefaultScheduledPollConsumerScheduler@1c0e57e4'; ';message';:';Starting service: org.apache.camel.support.DefaultScheduledPollConsumerScheduler@1c0e57e4'; ';message';:';Created new ScheduledThreadPool for source: MinioConsumer[minio://myBucketName?prefix=hello.txt&;startScheduler=false] with name: minio://myBucketName?prefix=hello.txt&;startScheduler=false ->; org.apache.camel.util.concurrent.SizedScheduledExecutorService@1eef6e57[minio://myBucketName?prefix=hello.txt&;startScheduler=false]'; ';message';:';Started service: org.apache.camel.support.DefaultScheduledPollConsumerScheduler@1c0e57e4'; ';message';:';Scheduling 1 consumers poll (fixed delay) with initialDelay: 1000, delay: 500 (milliseconds) for: minio://myBucketName?prefix=hello.txt&;startScheduler=false'; ';message';:';canScheduleOrExecute 0 < 1000 ->; true'; ';message';:';Created thread[Camel (camel-1) thread #1 - minio://myBucketName] ->; Thread[Camel (camel-1) thread #1 - minio://myBucketName,5,main]'; ';message';:';Started service: MinioConsumer[minio://myBucketName?prefix=hello.txt&;startScheduler=false]'; ';message';:';After poll minio://myBucketName?prefix=hello.txt&;startScheduler=false'; ';message';:';Suspending service MinioConsumer[minio://myBucketName?prefix=hello.txt&;startScheduler=false]'; ';message';:';Suspending service: MinioConsumer[minio://myBucketName?prefix=hello.txt&;startScheduler=false]'; ';message';:';Suspended service: MinioConsumer[minio://myBucketName?prefix=hello.txt&;startScheduler=false]'; ';message';:';Released service: PollingConsumer on minio://myBucketName?prefix=hello.txt&;startScheduler=false'; ,';message';:';Scheduled task started on: minio://myBucketName?prefix=hello.txt&;startScheduler=false';} ,';message';:';Cannot start to poll: minio://myBucketName?prefix=hello.txt&;startScheduler=false as its suspended';} ,';message';:';Scheduled task completed on: minio://myBucketName?prefix=hello.txt&;startScheduler=false';} ,';message';:';Scheduled task started on: minio://myBucketName?prefix=hello.txt&;startScheduler=false';} ,';message';:';Cannot start to poll: minio://myBucketName?prefix=hello.txt&;startScheduler=false as its suspended';} ,';message';:';Scheduled task completed on: minio://myBucketName?prefix=hello.txt&;startScheduler=false';} ,';message';:';Scheduled task started on: minio://myBucketName?prefix=hello.txt&;startScheduler=false';} ,';message';:';Cannot start to poll: minio://myBucketName?prefix=hello.txt&;startScheduler=false as its suspended';} ,';message';:';Scheduled task completed on: minio://myBucketName?prefix=hello.txt&;startScheduler=false';} ,';message';:';Scheduled task started on: minio://myBucketName?prefix=hello.txt&;startScheduler=false';} ,';message';:';Cannot start to poll: minio://myBucketName?prefix=hello.txt&;startScheduler=false as its suspended';} ..... and goes on with this util i stop the application. </code> I'm new to camel and I don't understand why it creates as well a PollingConsumer and the scheduler (which I did try to stop passing startScheduler=false) by default, and the polling after is continuously trying to start but fails. Probably this should ends in another question, I don't think is related to my problem. My dependencies : <code><dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-minio</artifactId>; <version>;3.14.4</version>; </dependency>; <dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-componentdsl</artifactId>; <version>;3.14.4</version>; </dependency>; <dependency>; <groupId>;io.minio</groupId>; <artifactId>;minio</artifactId>; <version>;8.4.1</version>; </dependency>; </code> In the MinIo Server the file is right under the Bucket: myBucketName/hello.txt Moreover I tested with direct calls using MinioClient (the same injected into MinioComponentBuilder): <code> GetObjectResponse getObj = minioClient.getObject(GetObjectArgs.builder() .bucket(';myBucketName';) .object(';hello.txt';).build()); String input = new String(getObj.readAllBytes()); log.info(';TXT CONTENT: {}';,input); </code> And it works just fine, printing the content of the txt. I'm probably doing something wrong with the uri syntax and how I compose it but cannot figure it out. | I'm working with Stefano, the issue is related to camel implementation with minio component. The solution is the following. The recevivedBody is an interface with overloaded methods if the timeout is required set the minimum timeout to 1100 millis or the result will be null, if is not required just use the method without timeout. With Timeout <code>ConsumerTemplate template = context.createConsumerTemplate(); byte[] content = template.receiveBody(uri, 1100, byte[].class); </code> Without timeOut <code>ConsumerTemplate template = context.createConsumerTemplate(); byte[] content = template.receiveBody(uri, byte[].class); </code> |
apache-camel | I'm using Camel JPA endpoints to poll a database and copy the data to a second one. To not poll duplicates, I'm planning to save the highest ID of the copied data and only poll data with an ID higher than that one. To save a few database writes, I want to write back the highest ID after the current polling / copying run is over, not for every single data element. I can access the element (and its ID) in the Camel Route class: <code> private Long startId = 0L; private Long lastId = 0L; from(';jpa://Data';).routeId(';dataRoute';) .onCompletion().onCompleteOnly().process(ex ->; { if (lastId >; startId) { startId = lastId; logger.info(';New highest ID: {}';, startId); } }).end() .process(ex ->; { Data data = ex.getIn().getBody(Data.class); lastId = data.getId(); NewData newData = (NewData) convertData(data); ex.getMessage().setBody(newData); }).to(';jpa://NewData';) </code> Now I want to save <code>startId</code> after the current polling is over. To do so, I overrode the <code>PollingConsumerPollStrategy</code> with my custom one where I want to access <code>lastId</code> inside the <code>commit</code> method (which gets executed exactly when I want it to, after the current polling is complete). However, I can't access the route there. I tried via the route ID: <code> @Override public void commit(Consumer consumer, Endpoint endpoint, int polledMessages) { var route = (MyRoute) endpoint.getCamelContext().getRoute(';dataRoute';); var lastId = route.getLastId(); log.debug(';LastID: {}';, lastId); } </code> However I'm getting a class cast exception: <code>DefaultRoute</code> to <code>MyRoute</code>. Is it something about handing the ID to my route? | I would do it a bit differently. Instead of using RouteBuilder instance vars for storing <code>startId</code> and <code>lastId</code>, you may also put these values as GlobalOptions (which is basically a map of key-value pairs) of current CamelContext. This way, you can easily obtain their value using: <code>public void commit(Consumer consumer, Endpoint endpoint, int polledMessages) { String lastId = endpoint.getCamelContext().getGlobalOption(';lastId';); } </code> It is also (theoretically) a better implementation because it also supports potential concurrent executions, as the id are shared for all instances running in the context. |
apache-camel | My application has been using org.apache.camel.component.cxf.common.header.CxfHeaderFilterStrategy org.apache.camel.spi.HeaderFilterStrategy.Direction org.apache.camel.component.cxf.CxfOperationException defined by camel-cxf. But my build fails when using Camel 3.18.0. What dependencies changes do I need for these classes in 3.18.0? | Copying from the Camel 3.18 upgrade guide: https://camel.apache.org/manual/camel-3x-upgrade-guide-3_18.html#_camel_cxf The <code>camel-cxf</code> JAR has been split up into SOAP vs REST and Spring and non Spring JARs.<code>camel-cxf-soap</code> <code>camel-cxf-spring-soap</code> <code>camel-cxf-rest</code> <code>camel-cxf-spring-rest</code> <code>camel-cxf-transport</code> <code>camel-cxf-spring-transport</code>When using Spring Boot then you need to migrate from <code>camel-cxf-starter</code> to use SOAP or REST:<code>camel-cxf-soap-starter</code> <code>camel-cxf-rest-starter</code> |
apache-camel | I'm following the documentation procedure and enabling the registration add-on in minikube. So I'm running <code>minikube start --addons registry kamel install </code> to start the cluster and install Camel K into it. But when I run <code>kubectl get pod</code> I get <code>CrashLoopBackOff</code> as the <code>camel-k-operator</code> status. <code>kubectl get events</code> gave me the following: <code>LAST SEEN TYPE REASON OBJECT MESSAGE 7m9s Normal Scheduled pod/camel-k-operator-848fd8785b-cr9pp Successfully assigned default/camel-k-operator-848fd8785b-cr9pp to minikube 7m5s Normal Pulling pod/camel-k-operator-848fd8785b-cr9pp Pulling image ';docker.io/apache/camel-k:1.9.2'; 2m23s Normal Pulled pod/camel-k-operator-848fd8785b-cr9pp Successfully pulled image ';docker.io/apache/camel-k:1.9.2'; in 4m45.3178036s 42s Normal Created pod/camel-k-operator-848fd8785b-cr9pp Created container camel-k-operator 42s Normal Started pod/camel-k-operator-848fd8785b-cr9pp Started container camel-k-operator 43s Normal Pulled pod/camel-k-operator-848fd8785b-cr9pp Container image ';docker.io/apache/camel-k:1.9.2'; already present on machine 55s Warning BackOff pod/camel-k-operator-848fd8785b-cr9pp Back-off restarting failed container 7m9s Normal SuccessfulCreate replicaset/camel-k-operator-848fd8785b Created pod: camel-k-operator-848fd8785b-cr9pp 7m9s Normal ScalingReplicaSet deployment/camel-k-operator Scaled up replica set camel-k-operator-848fd8785b to 1 </code> Running <code>kubectl logs [podname] -p</code> I get <code>{ ';level';: ';error';, ';ts';: 1658235623.4016757, ';logger';: ';cmd';, ';msg';: ';failed to set GOMAXPROCS from cgroups';, ';error';: ';path \';/docker/ec4a100d598f3529dbcc3a9364c8caceb32abd8c11632456d58c7948bb756d36\'; is not a descendant of mount point root \';/docker/ec4a100d598f3529dbcc3a9364c8caceb32abd8c11632456d58c7948bb756d36/kubelet\'; and cannot be exposed from \';/sys/fs/cgroup/rdma/kubelet\';';, ';stacktrace';: ';github.com/apache/camel-k/pkg/cmd.(*operatorCmdOptions).run \tgithub.com/apache/camel-k/pkg/cmd/operator.go:57 github.com/spf13/cobra.(*Command).execute \tgithub.com/spf13/cobra@v1.4.0/command.go:860 github.com/spf13/cobra.(*Command).ExecuteC \tgithub.com/spf13/cobra@v1.4.0/command.go:974 github.com/spf13/cobra.(*Command).Execute \tgithub.com/spf13/cobra@v1.4.0/command.go:902 main.main \tcommand-line-arguments/main.go:47 runtime.main \truntime/proc.go:225'; } </code> Formatting the stacktrace we get: <code>github.com/apache/camel-k/pkg/cmd.(*operatorCmdOptions).run github.com/apache/camel-k/pkg/cmd/operator.go:57 github.com/spf13/cobra.(*Command).execute github.com/spf13/cobra@v1.4.0/command.go:860 github.com/spf13/cobra.(*Command).ExecuteC github.com/spf13/cobra@v1.4.0/command.go:974 github.com/spf13/cobra.(*Command).Execute github.com/spf13/cobra@v1.4.0/command.go:902 main.main command-line-arguments/main.go:47 runtime.main runtime/proc.go:225 </code>Camel K Client 1.9.2 minikube v1.25.2 | It's probably a bug with the docker driver. A workaround is to use the hyperv driver instead: <code>minikube start --addons registry --driver hyperv </code> |
apache-camel | I'm using apache camel for consuming an IBM Mq, I use jms for that, everything is ok that works fine, but in the performance testing the api create a lot of dynamic queues but just use once, I've used a lot of properties for solve this problem but I didn't get it yet. my api use a pattern InOut so the responses are in queue in a dynamic queue, when exist a lot of them, for example my api create 50 dynamic queues, but just use 3 of them. Here are the properties I used to solve it, but didn´t work for me: -maxConcurrentConsumers -conccurrentConsumers -threads | I found a solution for this and is this. this is my consume to mq <code>.setHeader(';CamelJmsDestinationName';, constant(';queue:///';+queue+';?targetClient=1';)) .to(';jms://queue:'; + queue +';?exchangePattern=InOut'; +';&;replyToType=Temporary'; +';&;requestTimeout=10s'; +';&;useMessageIDAsCorrelationID=true'; +';&;replyToConcurrentConsumers=40'; +';&;replyToMaxConcurrentConsumers=90'; +';&;cacheLevelName=CACHE_CONSUMER';) .id(';idJms';) </code> and this is the properties to connect the mq <code>ibm.mq.queueManager=${MQ_QUEUE_MANAGER} ibm.mq.channel=${MQ_CHANNEL} ibm.mq.connName=${MQ_HOST_NAME} ibm.mq.user=${MQ_USER_NAME} ibm.mq.additionalProperties.WMQ_SHARE_CONV_ALLOWED_YES=${MQ_SHARECNV} ibm.mq.defaultReconnect=${MQ_RECONNECT} # Config SSL ibm.mq.ssl-f-i-p-s-required=false ibm.mq.user-authentication-m-q-c-s-p=${MQ_AUTHENTICATION_MQCSP:false} ibm.mq.tempModel=MQMODEL </code> the issue was in the MQ Model, the MQModel has to be shared if you are using the pattern inOut, this is because the concurrent create dynamic queues using the mqModel |
apache-camel | Problem I have a route ( Spring DSL ) which needs to take a JSON list from the api call in the route, render the JSON list as object(s), and pass the objects to a Processor for further action. So far, I have ( I think ) most of the pieces of the puzzle as indicated below. Assuming this is an appropriate strategy for accomplishing my goal, what I am stuck on is the proper way to reference the Order class in the unmarshal line... thoughts ? Route definition<code><route id=';rod-marshal-to-bean';>; <from uri=';timer://fetchData?repeatCount=1';/>; <to uri=';api:fetch1?filter=Rod_Filter1&;amp;batchSize=5&;amp;connection={{connection-info}}';/>; <split>; <simple>;${body}</simple>; <log message=';Body is : ${body}';/>; <unmarshal ..../>; <--- stuck here <process id=';process1'; ref=';customProcessor';/>; </split>; </route>; </code>Sample return value from Log message - JSON Array [ {version=1, sku=HT-0001, label=NextGen-Rack ProSeries 1 Server}, {version=1, sku=HT-0002, label=NextGen-Rack ProSeries 2 Server, } ] Class to handle the JSON Objects <code>import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonSetter; import com.fasterxml.jackson.annotation.JsonIgnore;import java.util.HashMap; import java.util.Map; import java.util.Objects;class Order { @JsonProperty(';version';) private String version; @JsonProperty(';sku';) private String sku; @JsonProperty(';label';) private String label; String getVersion() { return version } void setVersion(String version) { this.version = version println ';**** Setting version ';+version } String getSku() { return sku } void setSku(String sku) { this.sku = sku println ';**** Setting sku ';+sku } String getLabel() { return label } void setLabel(String label) { this.label = label println ';**** Setting label ';+label } } </code> Custom Processor <code>import org.apache.camel.Exchange import org.apache.camel.Processorclass CustomProcessor implements Processor { @Override void process(Exchange exchange) throws Exception { Order order = exchange.getIn().getBody(Order.class); . . Do some custom processing . }} </code> | for xml dsl create a bean and pass this bean name to unmarshall method <code>@Bean(';orderJacksonDataFormat';) public JacksonDataFormat depositResponseFormatter() { return new ListJacksonDataFormat(Order.class); } </code> for java dsl unmarshall it <code>// fetch data .unmarshal(new ListJacksonDataFormat(Order.class)) .process(customProcessor) </code> use in processor <code>class CustomProcessor implements Processor { @Override void process(Exchange exchange) throws Exception { List<Order>; order = (List<Order>;)exchange.getIn().getBody(List.class); . . Do some custom processing . }} </code> |
apache-camel | I am trying to understand the cardinality between Messages and Exchanges. In the following route, by the time one message makes it to the final log how many Exchanges are created? <code>from(';timer:one-second-timer';) .bean(messageTransformer, ';transformMessage';) .to(';log:logging-end-point';); </code> Since a Message can hold only one ';in'; message, I imagine there will be one Message for each end-point the message hops on. Is this true? | You can consider an <code>Exchange</code> as being the envelope containing the <code>Message</code> + some meta-data (the <code>Properties</code>), allowing this message to be transported between endpoints. The javadoc says:An Exchange is the message container holding the information during the entire routing of a Message received by a Consumer.So, in your example, if the timer is fired 10 times, this will result in 10 distinct exchanges of one message. |
apache-camel | I am working on Spring Boot application with Apache Camel REST API. It works as I expect, except when I send HTTP GET request without ';application/json'; attribute in Accept Header the application raises an error and returns HTTP response with code 200 and empty body. I would expect that application send correct response anyway. I am not able to find the way where to manage this behavior in Spring Boot. BaseRoute class: <code>import io.patriot_framework.virtual_smart_home.AppConfig; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.model.rest.RestBindingMode; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.stereotype.Component;/** * Routing configuration for localhost:8080. */ @Component public class BaseRoute extends RouteBuilder { private AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); @Override public void configure() throws Exception { restConfiguration() .component(';servlet';) .host(';localhost';).port(8080) .bindingMode(RestBindingMode.auto); } } </code> HouseRoute: <code>import io.patriot_framework.virtual_smart_home.house.House; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.stereotype.Component;/** * House endpoint which allows HTTP GET request only and returns information * about the whole {@code House} object. */ @Component public class HouseRoute extends BaseRoute { @Autowired House house; @Override public void configure() throws Exception { rest(getRoute()) .get() .produces(MediaType.APPLICATION_JSON_VALUE) .route() .process(exchange ->; exchange.getMessage().setBody(house)) .endRest(); } protected String getRoute() { return ';house/';; } } </code> Error: <code>2022-07-01 09:45:04.057 ERROR 8403 --- [nio-8080-exec-2] o.a.c.c.s.CamelHttpTransportServlet : Error processing requestjava.io.IOException: Stream closed at org.apache.catalina.connector.InputBuffer.throwIfClosed(InputBuffer.java:527) ~[tomcat-embed-core-9.0.46.jar!/:na] at org.apache.catalina.connector.InputBuffer.read(InputBuffer.java:338) ~[tomcat-embed-core-9.0.46.jar!/:na] at org.apache.catalina.connector.CoyoteInputStream.read(CoyoteInputStream.java:132) ~[tomcat-embed-core-9.0.46.jar!/:na] at org.apache.catalina.connector.CoyoteInputStream.read(CoyoteInputStream.java:110) ~[tomcat-embed-core-9.0.46.jar!/:na] at org.apache.camel.util.IOHelper.copy(IOHelper.java:180) ~[camel-util-3.9.0.jar!/:3.9.0] at org.apache.camel.util.IOHelper.copy(IOHelper.java:148) ~[camel-util-3.9.0.jar!/:3.9.0] at org.apache.camel.http.common.DefaultHttpBinding.copyStream(DefaultHttpBinding.java:493) ~[camel-http-common-3.9.0.jar!/:3.9.0] at org.apache.camel.http.common.DefaultHttpBinding.doWriteDirectResponse(DefaultHttpBinding.java:559) ~[camel-http-common-3.9.0.jar!/:3.9.0] at org.apache.camel.http.common.DefaultHttpBinding.doWriteResponse(DefaultHttpBinding.java:432) ~[camel-http-common-3.9.0.jar!/:3.9.0] at org.apache.camel.http.common.DefaultHttpBinding.writeResponse(DefaultHttpBinding.java:355) ~[camel-http-common-3.9.0.jar!/:3.9.0] at org.apache.camel.http.common.CamelServlet.afterProcess(CamelServlet.java:349) ~[camel-http-common-3.9.0.jar!/:3.9.0] at org.apache.camel.http.common.CamelServlet.doExecute(CamelServlet.java:327) ~[camel-http-common-3.9.0.jar!/:3.9.0] at org.apache.camel.http.common.CamelServlet.doService(CamelServlet.java:214) ~[camel-http-common-3.9.0.jar!/:3.9.0] at org.apache.camel.http.common.CamelServlet.service(CamelServlet.java:130) ~[camel-http-common-3.9.0.jar!/:3.9.0] at javax.servlet.http.HttpServlet.service(HttpServlet.java:733) ~[tomcat-embed-core-9.0.46.jar!/:na] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227) ~[tomcat-embed-core-9.0.46.jar!/:na] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.46.jar!/:na] at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.46.jar!/:na] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.46.jar!/:na] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.46.jar!/:na] at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.3.5.jar!/:5.3.5] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.5.jar!/:5.3.5] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.46.jar!/:na] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.46.jar!/:na] at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.3.5.jar!/:5.3.5] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.5.jar!/:5.3.5] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.46.jar!/:na] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.46.jar!/:na] at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:97) ~[spring-boot-actuator-2.4.7.jar!/:2.4.7] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.5.jar!/:5.3.5] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.46.jar!/:na] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.46.jar!/:na] at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.3.5.jar!/:5.3.5] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.5.jar!/:5.3.5] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.46.jar!/:na] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.46.jar!/:na] at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.46.jar!/:na] at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) ~[tomcat-embed-core-9.0.46.jar!/:na] at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542) ~[tomcat-embed-core-9.0.46.jar!/:na] at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143) ~[tomcat-embed-core-9.0.46.jar!/:na] at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) ~[tomcat-embed-core-9.0.46.jar!/:na] at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) ~[tomcat-embed-core-9.0.46.jar!/:na] at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357) ~[tomcat-embed-core-9.0.46.jar!/:na] at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374) ~[tomcat-embed-core-9.0.46.jar!/:na] at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) ~[tomcat-embed-core-9.0.46.jar!/:na] at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893) ~[tomcat-embed-core-9.0.46.jar!/:na] at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1707) ~[tomcat-embed-core-9.0.46.jar!/:na] at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.46.jar!/:na] at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1136) ~[na:na] at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635) ~[na:na] at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.46.jar!/:na] at java.base/java.lang.Thread.run(Thread.java:833) ~[na:na] </code> | For some reason it helped when i changed <code>bindingMode</code> from <code>RestBindingMode.auto</code> to <code>RestBindingMode.json</code> |
apache-camel | In start.spring.io, when Spring Boot 2.7.1 is selected it reports that Apache Camel ';Requires Spring Boot >;= 2.0.0.M1 and < 2.7.0-M1'; (see screenshot below).Is there a specific reason for this or where can I find more information on this? | The Camel team have not yet indicated that <code>camel-spring-boot-starter</code> supports Spring Boot 2.7. Until they're ready to support 2.7, the combination is disabled. Support for Spring Boot 2.7 seems to be part of Camel 3.18 which, at the time of writing, has not been released. |
apache-camel | I have a route Producer ->; Split ->; Processor and in the processor, I am trying to find out if the current exchange being processed is the last one to get split. According to the camel split docs, three properties are put into every camel exchange that has been split. CamelSplitIndex, CamelSplitSize and CamelSplitComplete. When using camel 3.0.0-RC3, I am able to see these properties being populated and available in the processor class. But when using version 3.11.1 or 3.17.0, I do not see these values being populated in the exchange. Am I missing something here or is this a camel bug. Main Class:SpringApplication.run(CamelTestMain.class, args);Routes: <code>from(';timer://simpleSplitTimer?period=1000000';).process(new Processor() { @Override public void process(Exchange exchange) throws Exception { Trade trade1 = new Trade(1L, 15.4, 200, ';WF';); Trade trade2 = new Trade(2L, 75.1, 100, ';GS';); Trade trade3 = new Trade(3L, 20.0, 15, ';JP';); List<Trade>; tradeList = new ArrayList<>;(); tradeList.add(trade1); tradeList.add(trade2); tradeList.add(trade3); exchange.getIn().setHeader(';GUITrade';, ';Y';); exchange.getIn().setBody(tradeList); } }) .to(';direct:toSplit';); from(';direct:toSplit';).split(body()).to(';direct:afterSplit1';); from(';direct:afterSplit1';).process(postSplitProcessor); </code> Dependencies: <code><parent>; <groupId>;org.springframework.boot</groupId>; <artifactId>;spring-boot-starter-parent</artifactId>; <version>;2.1.11.RELEASE</version>; </parent>; <dependencies>; <dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-spring-boot-starter</artifactId>; <version>;3.0.0-RC3</version>; </dependency>; <dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-jms</artifactId>; <version>;3.0.0-RC3</version>; </dependency>; </dependencies>; </code> | Since you haven't posted the code snippet where you are accessing the <code>Exchange</code> properties, I would guess you are using <code>Exchange#getProperties</code> to access the different properties which has been optimized / refactored in version 3.9.0 of Apache Camel:The properties on Exchange have been optimized to separate into two: internal state vs user properties. The method getProperties() now only returns user properties. To include internal properties as well, then use getAllProperties(). The other APIs such as getProperty(String) works the same way as before, being able to lookup a property regardless if its internal or custom.You should be able to access the split related properties:Either switching to use <code>Exchange#getAllProperties</code>: <code> exchange.getAllProperties().get(';CamelSplitIndex';); </code>Or better use the safer <code>Exchange#getProperty(ExchangePropertyKey)</code>: <code> exchange.getProperty(ExchangePropertyKey.SPLIT_INDEX); </code> |
apache-camel | I have a situation where I pull a file from a folder via a Camel SFTP route. There are 3 other Camel routes which need to process the same file which I am pulling... the other routes monitor the same SFTP server. Currently, we are thinking that we should make that file which I pull, available to the 3 other routes by placing a copy of the file in 3 separate folders where each folder is monitored by one of those other 3 routes... one unique folder for each of the 3 routes. When the other routes detect the presence of the file I would copy, they would fire up and proceed as required. The first question is whether this is a reasonable means of handling the scenario I just described or whether there is a better way. Secondly, assuming the scenario is reasonable, the question is what is the best way to handle propagating the file I pull to 3 different folders on the same SFTP server. For what it's worth, we are using Spring XML DSL. | I think you should decouple the scanning of the files from the processing of the files. In particular, there is maybe no real need to read a same file multiple times on the SFTP server, but only to process its content multiple times. This could end up to something like: <code>from(';sftp://server/folder1';) .to(';direct:processing1';);from(';sftp://server/folder2';) .to(';direct:processing2';);from(';sftp://server/folder3';) .to(';direct:processing3';);from(';sftp://server/toplevel';) .multicast().parallelProcessing() .to(';direct:processing1';) .to(';direct:processing2';) .to(';direct:processing3';) .end(); </code> |
apache-camel | I need to convert this gradle-java (gradle 6.3, java 8, camel 3.4.2), <code>plugins { id 'java-library' }repositories { jcenter() }dependencies { compile group: 'org.apache.camel', name: 'camel-rest', version: '3.4.2' } </code> To this (gradle 7.3.3, java 8, camel 3.14.3 springboot 2.7.0), <code>plugins { id 'java-library' id 'org.springframework.boot' version '2.7.0' id 'io.spring.dependency-management' version '1.0.11.RELEASE' id 'java' id 'war' }repositories { mavenCentral() }targetCompatibility = '1.8'dependencies { implementation 'org.springframework.boot:spring-boot-starter-data-rest' implementation 'org.springframework.boot:spring-boot-starter-web' implementation 'org.apache.camel:camel-rest::3.14.3' } </code> But I get this error, What went wrong: Execution failed for task ':compileJava'.Could not resolve all files for configuration ':compileClasspath'. Could not find org.apache.camel:camel-rest:. Required by:What should I do? Thanks Ric | The double colon, <code>:camel-rest::3.14.3' </code> |
apache-camel | I am trying to get tweets from my Twitter timeline with <code>ConsumerTemplate</code> (Camel) in a Quarkus app. I don't understand how it should be done correctly while using rate limits (my free account has rate 15 polls in 5 min). The Camel setup has property count which I set to <code>10</code>, and expect to get <code>10</code> new tweets in one poll, but the problem is that template offers only one tweet per Camel request: <code>for (int i = 0; i < 15; i++) { // I would expect here List or stream, but I can get only single `Status` final Status tweets = consumerTemplate.receiveBodyNoWait(String.format(';twitter-timeline://home?sinceId=%s&;count=10';, sinceId), Status.class); // just to show that I change that property if (nonNull(tweets)) { sinceId = tweets.getId(); }} </code> So my question is why I get only one tweet per poll even if count is set (a value more than <code>1</code>). Is there any better way or running that template, or something I can use instead while respecting downstream Twitter rate limits? | The <code>ConsumerTemplate</code> is based on a <code>PollingConsumer</code> under the hood, which as the name implies, pulls <code>Exchage</code>s one at a time hence why you are receiving only 1 <code>Status</code> (== 1 <code>Exchange</code>) even while setting a <code>count</code> endpoint option. It is almost hard (and error-prone) to implement tweets (or other <code>Exchange</code>s) consumption the right way. Indeed this is already offered out-of-the-box with the Apache Camel Twitter Component consumer. Here down a sample of a route to consume user public activity (timeline) using the twitter-timeline component: <code><routes xmlns:xsi=';http://www.w3.org/2001/XMLSchema-instance'; xmlns=';http://camel.apache.org/schema/spring'; xsi:schemaLocation='; http://camel.apache.org/schema/spring https://camel.apache.org/schema/spring/camel-spring.xsd';>; <route id=';twitter-timeline'; autoStartup=';true';>; <from uri=';twitter-timeline:USER?user=some-user&;amp;consumerKey=your-app-key&;amp;consumerSecret=your-app-key-secret&;amp;accessToken=your-app-access-token&;amp;accessTokenSecret=your-app-access-token-secret';/>; <log message=';${body}';/>; </route>;</routes>; </code> This will leverage the default polling configured delays which you can tweak based on your preferences to address any rate-limits. In your case for example, to respect 15 requests per 5 mins, you can set the consumer to poll each 20 seconds for one page: <code><from uri=';twitter-timeline:USER?user=some-user&;amp;count=100&;amp;numberOfPage=1&;amp;delay=20000';/>; </code> |
apache-camel | I am using the camel-jaxb component to unmarshall xml zipped in the Artemis queue, but jaxb in my local is not able to find the <code>jaxb.index</code> file. I debugged and noticed, the <code>ContextFactory.java</code>, <code>loadIndexedClasses()</code>. Locally the <code>resourceAsStream</code> is null, though the path is correct in this case <code>org/example/dataformat/jaxb.index</code> <code>private static List<Class>; loadIndexedClasses(String pkg, ClassLoader classLoader) throws IOException, JAXBException { final String resource = pkg.replace('.', '/') + ';/jaxb.index';; final InputStream resourceAsStream = classLoader.getResourceAsStream(resource); if (resourceAsStream == null) { return null; } </code>Exception message<code>Caused by: org.apache.camel.RuntimeCamelException: javax.xml.bind.JAXBException: ';org.example.dataformat'; doesnt contain ObjectFactory.class or jaxb.index </code> Is there any issuses in the project configuration? Below is the complete code build using the camel java maven artifact. <code><?xml version=';1.0'; encoding=';UTF-8';?>; <message id=';1';>; <to>;ORDER_DEP</to>; <from>;customer1</from>; <status>;APPROVED</status>; <description>;validated</description>; </message>; </code> <code><?xml version=';1.0'; encoding=';UTF-8';?>; <beans xmlns=';http://www.springframework.org/schema/beans'; xmlns:xsi=';http://www.w3.org/2001/XMLSchema-instance'; xsi:schemaLocation=';http://www.springframework.org/schema/aop http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd';>; <bean id=';jmsConnectionFactory'; class=';org.apache.qpid.jms.JmsConnectionFactory'; >; <property name=';username'; value=';admin';/>; <property name=';password'; value=';admin';/>; <property name=';remoteURI'; value=';amqp://localhost:5672'; />; </bean>; <bean id=';jmsPooledConnectionFactory'; class=';org.messaginghub.pooled.jms.JmsPoolConnectionFactory'; init-method=';start'; destroy-method=';stop';>; <property name=';maxConnections'; value=';5'; />; <property name=';connectionFactory'; ref=';jmsConnectionFactory'; />; </bean>; <bean id=';jmsConfig'; class=';org.apache.camel.component.jms.JmsConfiguration';>; <property name=';connectionFactory'; ref=';jmsPooledConnectionFactory'; />; <property name=';concurrentConsumers'; value=';5'; />; </bean>; <!-- using the AMQP component -->; <bean id=';jms'; class=';org.apache.camel.component.amqp.AMQPComponent';>; <property name=';configuration'; ref=';jmsConfig'; />; <property name=';connectionFactory'; ref=';jmsPooledConnectionFactory';/>; </bean>; <bean id=';demoBean'; class=';org.example.Demo';>;</bean>; <camelContext id=';testConsumer'; xmlns=';http://camel.apache.org/schema/spring'; autoStartup=';true'; allowUseOriginalMessage=';true';>; <packageScan>; <package>;org.example.dataformat</package>; </packageScan>; <!-- not able to create the ref in the dataformats. <dataFormats >; <jaxb id=';customConverter'; contextPath=';org.example.dataformat'; filterNonXmlChars=';true';/>; </dataFormats>; -->; <route id=';testroute'; autoStartup=';true';>; <from uri=';jms:queue:content_queue?selector=messageType LIKE 'ORDER%'';/>; <log loggingLevel=';DEBUG'; message=';info ${header.fileName}';/>; <unmarshal>; <zipFile/>; </unmarshal>; <choice>; <when>; <simple>;${header.messageType} == 'ORDER' </simple>; <wireTap uri=';file:data/output/consumed/';/>; <to uri=';seda:processOrder';/>; </when>; </choice>; </route>; <route id=';processFile'; autoStartup=';true';>; <from uri=';seda:processOrder';/>; <unmarshal allowNullBody=';true';>; <jaxb prettyPrint=';true'; contextPath=';org.example.dataformat'; filterNonXmlChars=';true';/>; </unmarshal>; <bean ref=';org.example.Demo'; method=';processOrder';/>; </route>; </camelContext>; </beans>; </code>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 http://maven.apache.org/maven-v4_0_0.xsd';>; <modelVersion>;4.0.0</modelVersion>; <groupId>;org.example</groupId>; <artifactId>;SimpleCamelConsumer</artifactId>; <packaging>;jar</packaging>; <version>;1.0-SNAPSHOT</version>; <name>;A Camel Route</name>; <properties>; <project.build.sourceEncoding>;UTF-8</project.build.sourceEncoding>; <project.reporting.outputEncoding>;UTF-8</project.reporting.outputEncoding>; <log4j2-version>;2.13.3</log4j2-version>; <pooled-jms-version>;2.0.5</pooled-jms-version>; <qpid-jms-client-version>;1.6.0</qpid-jms-client-version>; </properties>; <dependencyManagement>; <dependencies>; <!-- Camel BOM -->; <dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-bom</artifactId>; <version>;3.17.0</version>; <scope>;import</scope>; <type>;pom</type>; </dependency>; </dependencies>; </dependencyManagement>; <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-spring-main</artifactId>; </dependency>; <dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-spring</artifactId>; </dependency>; <dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-jms</artifactId>; </dependency>; <dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-spring-xml</artifactId>; </dependency>; <dependency>; <groupId>;org.messaginghub</groupId>; <artifactId>;pooled-jms</artifactId>; <version>;${pooled-jms-version}</version>; </dependency>; <dependency>; <groupId>;org.apache.qpid</groupId>; <artifactId>;qpid-jms-client</artifactId>; <version>;${qpid-jms-client-version}</version>; </dependency>; <dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-xstream</artifactId>; </dependency>; <dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-jaxb</artifactId>; </dependency>; <dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-amqp</artifactId>; </dependency>; <dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-zipfile</artifactId>; </dependency>; <!-- logging -->; <dependency>; <groupId>;org.apache.logging.log4j</groupId>; <artifactId>;log4j-slf4j-impl</artifactId>; <scope>;runtime</scope>; <version>;${log4j2-version}</version>; </dependency>; <!-- testing -->; <dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-test</artifactId>; <scope>;test</scope>; </dependency>; </dependencies>; <build>; <defaultGoal>;install</defaultGoal>; <plugins>; <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>; <plugin>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-maven-plugin</artifactId>; <version>;3.17.0</version>; <configuration>; <logClasspath>;true</logClasspath>; <mainClass>;org.example.MainApp</mainClass>; </configuration>; </plugin>; </plugins>; </build>; </project>; </code>Demo.java<code>package org.example;import org.example.dataformat.Message;public class Demo { public void processOrder(Message message){ System.out.println(';message value ';+message.getId()+'; ';+message.getFrom()); } } </code>Message.java<code>package org.example.dataformat;import javax.xml.bind.annotation.*;@XmlAccessorType(XmlAccessType.FIELD) @XmlRootElement public class Message { @XmlAttribute Integer id; @XmlElement(name=';to';) String to; @XmlElement(name=';from';) String from; @XmlElement(name=';status';) String status; @XmlElement(name=';description';) String description; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getTo() { return to; } public void setTo(String to) { this.to = to; } public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } } </code>jaxb.index<code>Message </code>MainSpringContextApp.java<code>package org.example;import org.apache.camel.spring.Main; public class MainSpringContextApp { public static void main(String... args) throws Exception { Main main = new Main(); main.run(args); } } </code>When i execute the code in Intellij Idea Community IDE, I get below exception<code>Exception in thread ';main'; org.apache.camel.FailedToStartRouteException: Failed to start route processFile because of null at org.apache.camel.impl.engine.RouteService.warmUp(RouteService.java:123) at org.apache.camel.impl.engine.InternalRouteStartupManager.doWarmUpRoutes(InternalRouteStartupManager.java:306) at org.apache.camel.impl.engine.InternalRouteStartupManager.safelyStartRouteServices(InternalRouteStartupManager.java:189) ... Caused by: org.apache.camel.RuntimeCamelException: javax.xml.bind.JAXBException: ';org.example.dataformat'; doesnt contain ObjectFactory.class or jaxb.index 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) ... Caused by: javax.xml.bind.JAXBException: ';org.example.dataformat'; doesnt contain ObjectFactory.class or jaxb.index at com.sun.xml.bind.v2.ContextFactory.createContext(ContextFactory.java:260) at com.sun.xml.bind.v2.JAXBContextFactory.createContext(JAXBContextFactory.java:48) at javax.xml.bind.ContextFinder.find(ContextFinder.java:302) at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:478) at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:435) at org.apache.camel.converter.jaxb.JaxbDataFormat.createContext(JaxbDataFormat.java:552) at org.apache.camel.converter.jaxb.JaxbDataFormat.doStart(JaxbDataFormat.java:516) at org.apache.camel.support.service.BaseService.start(BaseService.java:119) ... 53 more </code> | I had to create the jaxb class and use that contextpath Step 1:Use the xml, to create the xsd (in this case i used Intellij IDE community edition)Step 2:udpated the xs:schema to xsd:schema, since this is what the <code>cfx-xjc</code> plugin uses.Step 3:in <code>pom.xml</code> update the I created as folder schema under the project level, and placed the <code>simpleOrder.xsd</code><code> <plugin>; <groupId>;org.apache.cxf</groupId>; <artifactId>;cxf-xjc-plugin</artifactId>; <version>;3.2.3</version>; <configuration>; <extensions>; <extension>;org.apache.cxf.xjcplugins:cxf-xjc-dv:3.2.3</extension>; </extensions>; </configuration>; <executions>; <execution>; <id>;generate-sources</id>; <phase>;generate-sources</phase>; <goals>; <goal>;xsdtojava</goal>; </goals>; <configuration>; <sourceRoot>;${basedir}/target/generated/src/main/java</sourceRoot>; <xsdOptions>; <xsdOption>; <xsd>;${basedir}/schema/simpleOrder.xsd</xsd>; </xsdOption>; </xsdOptions>; </configuration>; </execution>; </executions>; </plugin>; </code> Step 4:Running the <code>mvn:install</code> generated the source under the specified location. Note, there will be a compilation error, I ignored it.Copied the generated file under the <code>org.example.dataformat</code> which intern updates the package of the class. Note:By default the ObjectFactory.java and the MessageType.java (in my case) used jakarta.xml in package. Which I need to replace with <code>javax.xml</code>.Refer INFO below, since using <code>jakarta.xml</code> package in the JAXB classes, there is an exception during unmarshalling with camel-jaxb. Step 5:Finally running the <code>MainSpringContextApp.java</code> started the route without any exception.INFOIf I I use the <code>jakarata.xml</code> package on the JAXB classes, I need to add dependency <code>jakarta.xml</code> bind api to support jaxb classes<code> <dependency>; <groupId>;jakarta.xml.bind</groupId>; <artifactId>;jakarta.xml.bind-api</artifactId>; <version>;3.0.1</version>; </dependency>; </code>With the above when I receive xml input, below exception message is displayed. So had to use the <code>javax.xml</code>.<code>java.io.IOException: javax.xml.bind.UnmarshalException - with linked exception: [com.sun.istack.SAXParseException2; lineNumber: 1; columnNumber: 1; unexpected element (uri:';';, local:';message';). Expected elements are (none)] at org.apache.camel.converter.jaxb.JaxbDataFormat.unmarshal(JaxbDataFormat.java:308) ~[camel-jaxb-3.17.0.jar:3.17.0] at org.apache.camel.support.processor.UnmarshalProcessor.process(UnmarshalProcessor.java:76) [camel-support-3.17.0.jar:3.17.0] at org.apache.camel.processor.errorhandler.RedeliveryErrorHandler$SimpleTask.run(RedeliveryErrorHandler.java:471) [camel-core-processor-3.17.0.jar:3.17.0] at org.apache.camel.impl.engine.DefaultReactiveExecutor$Worker.schedule(DefaultReactiveExecutor.java:189) [camel-base-engine-3.17.0.jar:3.17.0] at org.apache.camel.impl.engine.DefaultReactiveExecutor.scheduleMain(DefaultReactiveExecutor.java:61) [camel-base-engine-3.17.0.jar:3.17.0] at org.apache.camel.processor.Pipeline.process(Pipeline.java:184) [camel-core-processor-3.17.0.jar:3.17.0] at org.apache.camel.impl.engine.CamelInternalProcessor.process(CamelInternalProcessor.java:399) [camel-base-engine-3.17.0.jar:3.17.0] at org.apache.camel.component.seda.SedaConsumer.sendToConsumers(SedaConsumer.java:269) [camel-seda-3.17.0.jar:3.17.0] at org.apache.camel.component.seda.SedaConsumer.doRun(SedaConsumer.java:187) [camel-seda-3.17.0.jar:3.17.0] at org.apache.camel.component.seda.SedaConsumer.run(SedaConsumer.java:130) [camel-seda-3.17.0.jar:3.17.0] at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) [?:?] at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) [?:?] at java.lang.Thread.run(Thread.java:834) [?:?] Caused by: javax.xml.bind.UnmarshalException at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.handleStreamException(UnmarshallerImpl.java:453) ~[jaxb-impl-2.3.3.jar:2.3.3] at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:387) ~[jaxb-impl-2.3.3.jar:2.3.3] at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:356) ~[jaxb-impl-2.3.3.jar:2.3.3] at org.apache.camel.converter.jaxb.JaxbDataFormat.unmarshal(JaxbDataFormat.java:300) ~[camel-jaxb-3.17.0.jar:3.17.0] ... 12 more Caused by: com.sun.istack.SAXParseException2: unexpected element (uri:';';, local:';message';). Expected elements are (none) at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext.handleEvent(UnmarshallingContext.java:712) ~[jaxb-impl-2.3.3.jar:2.3.3] at com.sun.xml.bind.v2.runtime.unmarshaller.Loader.reportError(Loader.java:232) ~[jaxb-impl-2.3.3.jar:2.3.3] at com.sun.xml.bind.v2.runtime.unmarshaller.Loader.reportError(Loader.java:227) ~[jaxb-impl-2.3.3.jar:2.3.3] at com.sun.xml.bind.v2.runtime.unmarshaller.Loader.reportUnexpectedChildElement(Loader.java:94) ~[jaxb-impl-2.3.3.jar:2.3.3] at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext$DefaultRootLoader.childElement(UnmarshallingContext.java:1117) ~[jaxb-impl-2.3.3.jar:2.3.3] at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext._startElement(UnmarshallingContext.java:542) ~[jaxb-impl-2.3.3.jar:2.3.3] at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext.startElement(UnmarshallingContext.java:524) ~[jaxb-impl-2.3.3.jar:2.3.3] at com.sun.xml.bind.v2.runtime.unmarshaller.StAXStreamConnector.handleStartElement(StAXStreamConnector.java:216) ~[jaxb-impl-2.3.3.jar:2.3.3] at com.sun.xml.bind.v2.runtime.unmarshaller.StAXStreamConnector.bridge(StAXStreamConnector.java:150) ~[jaxb-impl-2.3.3.jar:2.3.3] at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:385) ~[jaxb-impl-2.3.3.jar:2.3.3] at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:356) ~[jaxb-impl-2.3.3.jar:2.3.3] at org.apache.camel.converter.jaxb.JaxbDataFormat.unmarshal(JaxbDataFormat.java:300) ~[camel-jaxb-3.17.0.jar:3.17.0] ... 12 more Caused by: javax.xml.bind.UnmarshalException: unexpected element (uri:';';, local:';message';). Expected elements are (none) at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext.handleEvent(UnmarshallingContext.java:712) ~[jaxb-impl-2.3.3.jar:2.3.3] at com.sun.xml.bind.v2.runtime.unmarshaller.Loader.reportError(Loader.java:232) ~[jaxb-impl-2.3.3.jar:2.3.3] at com.sun.xml.bind.v2.runtime.unmarshaller.Loader.reportError(Loader.java:227) ~[jaxb-impl-2.3.3.jar:2.3.3] at com.sun.xml.bind.v2.runtime.unmarshaller.Loader.reportUnexpectedChildElement(Loader.java:94) ~[jaxb-impl-2.3.3.jar:2.3.3] at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext$DefaultRootLoader.childElement(UnmarshallingContext.java:1117) ~[jaxb-impl-2.3.3.jar:2.3.3] at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext._startElement(UnmarshallingContext.java:542) ~[jaxb-impl-2.3.3.jar:2.3.3] at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext.startElement(UnmarshallingContext.java:524) ~[jaxb-impl-2.3.3.jar:2.3.3] at com.sun.xml.bind.v2.runtime.unmarshaller.StAXStreamConnector.handleStartElement(StAXStreamConnector.java:216) ~[jaxb-impl-2.3.3.jar:2.3.3] at com.sun.xml.bind.v2.runtime.unmarshaller.StAXStreamConnector.bridge(StAXStreamConnector.java:150) ~[jaxb-impl-2.3.3.jar:2.3.3] at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:385) ~[jaxb-impl-2.3.3.jar:2.3.3] at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:356) ~[jaxb-impl-2.3.3.jar:2.3.3] at org.apache.camel.converter.jaxb.JaxbDataFormat.unmarshal(JaxbDataFormat.java:300) ~[camel-jaxb-3.17.0.jar:3.17.0] ... 12 more </code> |
apache-camel | Trying to use the <code>jakarta.jms</code> Apache Qpid AMQP client to process messages. I am trying to use poolable connection factory using <code>org.messagehub</code>. Standlone java code works, refer the java changes. When I try use the same in Spring XML DSL in Camel, the AMQP component doesn't support the <code>jakarta.jmx</code> connection factory. Does the apache-amqp component support JMS 2.0 from Apache Qpid client yet? <code>package org.example; import jakarta.jms.Connection; import jakarta.jms.ConnectionFactory; import jakarta.jms.DeliveryMode; import jakarta.jms.Destination; import jakarta.jms.ExceptionListener; import jakarta.jms.JMSException; import jakarta.jms.Message; import jakarta.jms.MessageConsumer; import jakarta.jms.MessageProducer; import jakarta.jms.Session; import jakarta.jms.TextMessage; import org.apache.camel.component.jms.JmsConfiguration; import org.messaginghub.pooled.jms.JmsPoolConnectionFactory;import javax.naming.Context; import javax.naming.InitialContext;public class AMQPArtemisClient { public static void main(String[] args) throws Exception { try { // The configuration for the Qpid InitialContextFactory has been supplied in // a jndi.properties file in the classpath, which results in it being picked // up automatically by the InitialContext constructor. Context context = new InitialContext(); ConnectionFactory factory = (ConnectionFactory) context.lookup(';myFactoryLookup';); Destination queue = (Destination) context.lookup(';myQueueLookup';); System.setProperty(';USER';,';admin';); System.setProperty(';PASSWORD';,';admin';); //added for poolable connection JmsPoolConnectionFactory poolConnectionFactory = new JmsPoolConnectionFactory(); poolConnectionFactory.setMaxConnections(5); poolConnectionFactory.setConnectionFactory(factory); // Connection connection = factory.createConnection(System.getProperty(';USER';), System.getProperty(';PASSWORD';)); Connection connection = poolConnectionFactory.createConnection(System.getProperty(';USER';), System.getProperty(';PASSWORD';)); connection.setExceptionListener(new MyExceptionListener()); connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer messageProducer = session.createProducer(queue); MessageConsumer messageConsumer = session.createConsumer(queue); TextMessage message = session.createTextMessage(';Hello world!';); messageProducer.send(message, DeliveryMode.NON_PERSISTENT, Message.DEFAULT_PRIORITY, Message.DEFAULT_TIME_TO_LIVE); TextMessage receivedMessage = (TextMessage) messageConsumer.receive(2000L); if (receivedMessage != null) { System.out.println(receivedMessage.getText()); } else { System.out.println(';No message received within the given timeout!';); } connection.close(); } catch (Exception exp) { System.out.println(';Caught exception, exiting.';); exp.printStackTrace(System.out); System.exit(1); } } private static class MyExceptionListener implements ExceptionListener { @Override public void onException(JMSException exception) { System.out.println(';Connection ExceptionListener fired, exiting.';); exception.printStackTrace(System.out); System.exit(1); } } } </code>resources/jndi.properties<code>java.naming.factory.initial = org.apache.qpid.jms.jndi.JmsInitialContextFactory connectionfactory.myFactoryLookup = amqp://localhost:5672 queue.myQueueLookup = queue topic.myTopicLookup = topic </code>pom.xml<code> <dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-amqp</artifactId>; <!--version 3.17.0 is used-->; </dependency>;<dependency>; <groupId>;org.messaginghub</groupId>; <artifactId>;pooled-jms</artifactId>; <version>;3.0.0</version>; <!-- supports jakarta.jms connecton factory -->; </dependency>; <dependency>; <groupId>;org.apache.qpid</groupId>; <artifactId>;qpid-jms-client</artifactId>; <version>;2.0.0</version>; </dependency>; </code>Camel component I tried to configure the AMPQ component<code> <bean id=';jmsConnectionFactory'; class=';org.apache.qpid.jms.JmsConnectionFactory'; >; <property name=';username'; value=';admin';/>; <property name=';password'; value=';secret';/>; <property name=';remoteURI'; value=';amqp://localhost:5672'; />; </bean>; <bean id=';jmsPooledConnectionFactory'; class=';org.messaginghub.pooled.jms.JmsPoolConnectionFactory'; init-method=';start'; destroy-method=';stop';>; <property name=';maxConnections'; value=';5'; />; <property name=';connectionFactory'; ref=';jmsConnectionFactory'; />; </bean>; <bean id=';jmsConfig'; class=';org.apache.camel.component.jms.JmsConfiguration';>; <property name=';connectionFactory'; ref=';jmsPooledConnectionFactory'; />; <property name=';concurrentConsumers'; value=';5'; />; </bean>; <!-- uses the AMQP component -->; <bean id=';jms'; class=';org.apache.camel.component.amqp.AMQPComponent';>; <property name=';configuration'; ref=';jmsConfig'; />; <property name=';connectionFactory'; ref=';jmsPooledConnectionFactory';/>; </bean>; </code> When I try configuration like below I get exception <code>jakarta.jms</code> exception where it expects <code>javax.jms</code>, for now i had to lower the version of messaging hub to 2.0.5 and use qpid-jms-client jar to 1.6.0. <code><bean id=';amqp'; class=';org.apache.camel.component.amqp.AmqpComponent';>; <property name=';connectionFactory';>; <bean class=';org.apache.qpid.jms.JmsConnectionFactory'; factory-method=';createFromURL';>; <property name=';remoteURI'; value=';amqp://localhost:5672'; />; <property name=';topicPrefix'; value=';topic://'; />; <!-- only necessary when connecting to ActiveMQ over AMQP 1.0 -->; </bean>; </property>; </bean>; </code> | The Camel AMQP component you are using doesn't support Jakarta JMS an so you must revert to older versions of the Qpid JMS client and the Pooled JMS wrapper in order to make it work. This is your only options until there is a version of the Camel bits that supports Jakarta and you move on to it. |
apache-camel | I have 2 routes which intends to filter user's messages coming from kafka based on a blacklist of user's ids stored in caffeine cache. The first route that loads a txt file containing ids of blacklisted users at startup, is defined as follow : <code>from(file(...)) .id(getRouteId()) .split().tokenize('; ';) .stopOnException() .aggregate(constant(true), new GroupedBodyAggregationStrategy()) .completionTimeout(500) .setHeader(CaffeineConstants.ACTION, constant(CaffeineConstants.ACTION_PUT)) .setHeader(CaffeineConstants.KEY, constant(';blacklistedIds';)) .toF(';caffeine-cache://%s';, ';blacklistedIds';) </code> Note: the blacklist consist of a <code>List<String>; blacklistedIds</code> and it's stored in caffeine cache (which get initialised at startup of the application). The second route which get user's messages from kafka (<code>User properties : id,firstname,lastname</code>), and it's defined as follow: <code>from(kafka(...)) .id(getRouteId()) .unmarshal().json(JsonLibrary.Jackson, UserMessage.class) // filter here (based on cache) to only let go authorized users //.filter(method(UserMessageFilterService.class, ';isAuthorizedUser';)) .to(output()) </code> My question is how can I do to filter the incoming message by using the blacklistIds stored in caffeine cache ? How can I get the cache in <code>UserMessageFilterService#isAuthorizedUser</code> bean's method ? Is there a better/simple way to achieve this ? | You can pass the message body and arbitrary headers to <code>isAuthorizedUser()</code> <code>from(kafka(...)) ... // save the UserMessage in a header .setHeader(';userMessage';, body()) // retrieve the cached list of blacklisted Ids .setHeader(CaffeineConstants.CamelCaffeineAction, CaffeineConstants.GET) .setHeader(CaffeineConstants.CamelCaffeineKey, constant(';blacklistedIds';)) .to(';caffeine-cache:blacklistedIds) .filter(method(UserMessageFilterService.class, ';isAuthorizedUser';)) // restore the original body .setBody(header(';userMessage';)) </code> UserMessageFilterService.java <code>public boolean isAuthorizedUser(List<String>; blacklistedIds, @Header(';userMessage';) UserMessage userMessage) { return !blacklistedIds.contains(userMessage.getUserId()); } </code> |
apache-camel | In Apache Camel 3.17+, is there a way to include xml DSL route definition directly, so I can run it in standalone. With JAVA DSL the java route configuration can be added to the Main() context using <code>addRoutesBuilders()</code>, like in below example. I wanted to add the xml context directly to the Main(). <code>public class MainApp { public static void main(String... args) throws Exception { Main main = new Main(); main.configure().addRoutesBuilder(new MyRouteBuilder()); main.run(args); } } </code> <code>public class MyRouteBuilder extends RouteBuilder { public void configure() { from(';direct:start';) .to(';mock:result';); } } </code> Is it possible to use <code>camel-main</code> for routes defined in xml based DSL using camelContext tags? Below is the sample xml <code><!-- spring xmlns added removed here for make the xml brief -->; <?xml version=';1.0'; encoding=';UTF-8';?>; <beans xmlns=';http://www.springframework.org/schema/beans'; xmlns:xsi=';http://www.w3.org/2001/XMLSchema-instance';....<camelContext xmlns = ';http://camel.apache.org/schema/spring';>; <route>; <from uri = ';direct:input';/>; <log message = ';log message for demo';/>; <to uri = ';file:src/main/resources/data/';/>; </route>; </camelContext>; </code> | we can use below dependency in <code>pom.xml</code>.<code>camel-spring-xml</code> &; <code>camel-spring-main</code><code> <dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-spring-main</artifactId>; </dependency>; <dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-spring</artifactId>; </dependency>; </code>MainApp.java<code> import org.apache.camel.spring.Main;public class MainApp { public static void main(String... args) throws Exception { Main main = new Main(); main.run(args); }} </code>To scan the spring bean based configuration automatically, by creating the xml in <code>resources/META-INF/spring/*.xml</code>. |
apache-camel | I am developing a sample routeFROM: SOURCE ENDPOINT URI TO: TRANS ENDPOINT URI // Error or Exception occurred at this TRANS endpoint TO: TARGET ENDPOINT URINow I want to catch the Error Occured endpoint and pass it to my processor. Could anyone please help me with this?
<code> <route>; <from uri="file:C:/MINTS/Source/"/>; <to uri="file:C:/MINTS/TRANS/"/>; <!-- EXCPECTION OCCURED -->; <to uri="file:C:/MINTS/TARGET/"/>; <onException>; <exception>;java.lang.Exception</exception>; <handled>; <constant>;true</constant>; </handled>; <!-- NEED TO CATCH FAILURE ENDPOINT URI AND PASS TO MY PROCESSOR BELOW-->; <process ref="MyExceptionProcessor" />; </onException>; </route>;</code>
| You can use exchange properties:CamelFailureEndpointexample xml-dsl: <code><exchangeProperty>;CamelFailureEndpoint</exchangeProperty>;</code> example java: <code>exchange.getProperty(Exchange.FAILURE_ENDPOINT, String.class);</code> CamelToEndpointexample xml-dsl: <code><exchangeProperty>;CamelToEndpoint</exchangeProperty>;</code> example java: <code>exchange.getProperty(Exchange.TO_ENDPOINT, String.class)</code>The first one should print uri for the consumer endpoint (from) that failed and the second one should show the previously called producer (to) endpoint. One handy way to debug contexts of an failed exchange is to use:<code><to uri=';log:loggerName?showAll=true'; />;</code>This will log all exchange properties, headers, body and exception which can help to understand what information is available within exchange. Be careful where you use it as it might also log secrets and passwords if they're within the exchange so better use it only locally during development. For more information you'd probably need to access CamelMessageHistory exchange property through processor, bean or something. |
apache-camel | I have installed Camel plugin for IntelliJ. To start debugging, we must create an ad-hoc applicationHow do you know exactly at what port application is locally loaded? How can I change it? I have found no configurations about... | You do not need to provide a port. The debugger is attaching directly to the application using its pid. You need to be sure that the camel-debug dependency is added. I recommened to add it through a profile like shown here https://github.com/apache/camel-examples/blob/d1e5022bb1b43565903359aefaf91bcf23fc9c78/examples/main/pom.xml#L105-L120 Please note that you need a recent version of Camel (3.16 I think) |
apache-camel | I am trying to use Apache Camel File-Watch feature. However I notice all example are used along with Spring. Is there anyway to make use of this feature without Spring ? Thank you for any potential input. Best regards. | Apache Camel is a standalone integration framework to easily integrate different systems using well know and established EIP (Enterprise Integration Patterns). It is not tied to Spring in any way at its core and has different deployment / integration models out of which is Spring / Spring Boot for the sake of easing its adoption and configuration for Spring framework users. Out of the runtime contexts, you can use for example Camel Main component to run your application having a File Watch component setup to watch the <code>/tmp/</code> directory change events: The main application would look like the following: <code>public class FileWatchApplication { private FileWatchApplication() { } public static void main(String[] args) throws Exception { // use Camels Main class Main main = new Main(FileWatchApplication.class); // now keep the application running until the JVM is terminated (ctrl + c or sigterm) main.run(args); } } </code> A simple <code>RouteBuilder</code> setting up your File Watch component would look like the following (note that it must be within the same (or child) package of the <code>FileWatchApplication</code> class): <code>public class FileWatchRouteBuilder extends RouteBuilder { @Override public void configure() throws Exception { // snippet configuration from the official documentation from(';file-watch:///tmp/';) .log(';File event: ${header.CamelFileEventType} occurred on file ${header.CamelFileName} at ${header.CamelFileLastModified}';); } } </code> |
apache-camel | I have a very simple camel route that makes soap to soap calls. Everything work fine, but if one of the @Oneway operation throws SaopFault, I cannot catch the fault onException. How can I catch soapFault onException to set message to setBody(soapFault)? Thank you for your help. This method throws SaopFault from targetService <code> @WebMethod(operationName = ';OneWayOperation';) @Oneway public void onewayOperation( @WebParam(partName = ';OneWayOperationRequest';, name = ';OneWayOperationRequest';, targetNamespace = ';http://xxx.xxx.com/xmlschema/api';) com.xxx.xxx.xmlschema.api.OneWayOperationRequest oneWayOperationRequest );</code> <code> @Bean(name = ';sourceBean';) public CxfEndpoint buildCxfSoapEndpoint() { CxfEndpoint cxf = new CxfEndpoint(); cxf.setAddress(';http://0.0.0.0:9090/api';); cxf.setServiceClass(com.xxx.Service.class); cxf.setWsdlURL(';wsdl/xxx.wsdl';); return cxf; } @Bean(name = ';targetBean';) public CxfEndpoint buildCxfSoapEndpoint() { CxfEndpoint cxf = new CxfEndpoint(); cxf.setAddress(';https://xxxx.com:443/api';); cxf.setServiceClass(com.xxx.Service.class); cxf.setWsdlURL(';wsdl/xxx.wsdl';); return cxf; } from(';cxf:bean:sourceBean';) .to(';cxf:bean:targetBean';) .onException(SoapFault.class) .process(new Processor() { @Override public void process(Exchange exchange) throws Exception { SoapFault fault = exchange.getProperty(ExchangePropertyKey.EXCEPTION_CAUGHT, SoapFault.class); // ** OneWay methods never comes here but the others ! ** } }) </code> | I've added ?dataFormat=MESSAGE and problem solved. <code>from(';cxf:bean:sourceBean?dataFormat=MESSAGE';) .to(';cxf:bean:targetBean?dataFormat=MESSAGE';) </code> |
apache-camel | I am trying to upgrade camel from 2 to 3. I had previously had camel-quartz2 from camel 2 included in my pom.xml, but because quartz2 is apparently called quartz now, I have added this to my pom.xml: <code><dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-quartz</artifactId>; <version>;3.17.0</version>; </dependency>; </code> I removed quartz2. The problem is that I now receive this error. <code>Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'startDelayedSeconds' of bean class [org.apache.camel.component.quartz.QuartzComponent]: Bean property 'startDelayedSeconds' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter? </code> I looked and saw that the the StartDelayedSeconds method is not part of quartz as it was with quartz2. Does this mean that they are really not the same? If this is the case, then why is the newest version of quartz2 so far behind the newest version of quartz. Is there some sort of workaround that I could do, or some part of quartz that I should use? | From the Came 3 migration guide:The quartz2 component has been renamed to quartz, and it’s corresponding component package from org.apache.camel.component.quartz2 to org.apache.camel.component.quartz. The supported scheme is now quartz. Source: https://camel.apache.org/manual/camel-3-migration-guide.htmlWhen I run command <code>mvn dependency:tree</code> with project that contains camel-quartz dependency I get the following: <code>[INFO] +- org.apache.camel:camel-quartz:jar:3.4.4:compile [INFO] | +- org.quartz-scheduler:quartz:jar:2.3.2:compile [INFO] | | +- com.mchange:mchange-commons-java:jar:0.2.15:compile [INFO] | | \- com.zaxxer:HikariCP-java7:jar:2.4.13:compile [INFO] | \- com.mchange:c3p0:jar:0.9.5.5:compile </code> Based on that I would say its safe to assume that camel-quartz in camel 3.x uses quartz scheduler version 2.x. The option <code>StartDelayedSeconds</code> has likely been moved or changed during one of the major or minor version changes. A lot of components have gone through some changes to use more up to date libraries and to make them easier to use or just consistent with other components. [Edit] Regarding the StartDelayedSeconds option found this from one of the many Apache Camel upgrade guides.UPGRADING CAMEL 3.14 TO 3.15 Removed the option startDelaySeconds as this does not work correctly and causes problems if in use. Source: Upgrading camel 3.14 TO 3.15 |
apache-camel | I have a spring project using apache camel. I want to try the services provided in camel-context.xml using a postman request. How can I infer the path variables and endpoint? The method I want to use is specified like below on camel-context.xml and I have parameters providing the contains conditions. <code> <route>; <from uri=';netty:udp://{{camel.netty.server}}:{{camel.netty.udp.port}}?sync=false&;amp;allowDefaultCodec=true;'; />; <convertBodyTo type=';java.lang.String'; charset=';ISO-8859-9'; />; <choice>; <when>; <simple trim=';true';>;${bodyAs(String)} contains '';ISN';:';90';'</simple>; <bean ref=';Feaser'; method=';run'; cache=';false';>;</bean>; <to uri=';mock:result'; />; </when>; ... </code> | Postman doesn't support sending on UDP. |
apache-camel | I am trying to run a postgresql select query to fetch json payload from database. Json payload in database column is. <code>{ ';transactionId';: ';a9S4Y044545F71UAE';, ';results';: { ';overall';: ';PASS';, ';documents';: [ { ';documentId';: ';4d7cad3165a6-ce0d-49ae-bfd8-4d7cad3165a6';, ';document';: { ';country';: ';Australia';, ';type';: ';Driver Licence';, ';typeLabel';: ';Driver Licence'; }, ';extractedData';: { ';firstName';: ';ABC';, ';lastName';: ';YUZ';, ';cardType';: ';Driver Licence';, }, } ] } } </code> My query is like <code>SELECT doc_payload from DB.doc_payload where jsonb_path_match(identity_verification,'exists($.results.documents[*].confirmedData.firstName ? (@ == ';ABC';))') and jsonb_path_match(identity_verification,'exists($.results.documents[*].document.type ? (@ == ';Driver Licence';))') </code> Error <code>Caused by: org.apache.camel.ResolveEndpointFailedException There are 1 parameters that couldn't be set on the endpoint. Check the uri if the parameters are spelt correctly and that they are properties of the endpoint. Unknown parameters=[{ (@/'; == ';ABC';))') and jsonb_path_match(identity_verification,'exists($.results.documents[*].document.type ? (@/'; == ';Driver Licence';))') </code> | <code>SELECT doc_payload::text from DB.doc_payload where jsonb_path_match(doc_payload,'($.results.documents[*]. extractedData.firstName == ';$simple{exchangeProperty.firstname}';)') and jsonb_path_match(doc_payload,'($.results.documents[*].document.type == ';$simple{exchangeProperty.doctype}';)') </code> |
apache-camel | I have two routes: <code>.from(';A';) .to(';C';) .to(';B';);.from(';C';) *some processing logic* .to(';D';); </code> Is it possible to build the second route such that:when the message comes from the first route, some or all parts of the logic are ommited; when the message comes to the second route directly, the logic is used? | You can set exchange properties on route(s). Then you can evaluate the values inside filter or choice to branch or alter the routing logic. I would advice against anything more complex than this to avoid unnecessary coupling between routes. Example: <code>package org.example;import org.apache.camel.RoutesBuilder; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.test.junit4.CamelTestSupport; import org.junit.Test;public class ExampleRouteTests extends CamelTestSupport { @Test public void shouldReturnSentBody() throws Exception { final String testMessage = ';AAAA';; MockEndpoint resultMockEndpoint = getMockEndpoint(';mock:result';); resultMockEndpoint.expectedMessageCount(1); resultMockEndpoint.message(0).body().isEqualTo(testMessage); template.sendBody(';direct:a';, testMessage); resultMockEndpoint.assertIsSatisfied(); } @Test public void shouldReturnBBBB() throws Exception { MockEndpoint resultMockEndpoint = getMockEndpoint(';mock:result';); resultMockEndpoint.expectedMessageCount(1); resultMockEndpoint.message(0).body().isEqualTo(';BBBB';); template.sendBody(';direct:b';, null); resultMockEndpoint.assertIsSatisfied(); } @Override protected RoutesBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { from(';direct:a';) .setProperty(';From';, constant(';A';)) .to(';direct:c';); from(';direct:b';) .setProperty(';From';, constant(';B';)) .to(';direct:c';); from(';direct:c';) .filter(exchangeProperty(';From';).isNotEqualTo(';A';)) .log(';Processing message';) .setBody(constant(';BBBB';)) .end() .log(';body: ${body}';) .to(';mock:result';); } }; } } </code> |
apache-camel | Into a camel processor, I have set two static vars with property names: <code> public static final String CI_PROPERTY = ';ci';; public static final String IS_PDF_PROPERTY = ';isPdf';; </code> and I assign like: <code> exchange.setProperty(CI_PROPERTY, documentProperties.get(MAP_PARAMETER_ATTACHMENT_URI)); exchange.setProperty(IS_PDF_PROPERTY, documentProperties.get(MAP_PARAMETER_IS_PDF)); </code> These names should be used in other processors to retrieve properties. The question is: other processors have access to these names? Or I should move them to another class? In case, where? | Yes, you can do that as you can be seen below: <code>import org.apache.camel.Exchange; import org.apache.camel.Processor;public class FooProcessor implements Processor { public static final String FOO_PROPERTY = ';FOO';; @Override public void process(Exchange exchange) throws Exception { exchange.setProperty(FOO_PROPERTY, ';This is a Foo property.';); } } </code> <code>import org.apache.camel.Exchange; import org.apache.camel.Processor;public class BarProcessor implements Processor { @Override public void process(Exchange exchange) throws Exception { exchange.getMessage().setBody(exchange.getProperty(FooProcessor.FOO_PROPERTY, String.class)); } } </code> <code>from(';direct:mainRoute';) .routeId(';MainRoute';) .log(';MainRoute BEGINS: BODY: ${body}';) .process(new FooProcessor()) .process(new BarProcessor()) .log(';MainRoute ENDS: BODY: ${body}';) .end() ; </code> When the route above will be run the following is logged as expected: <code>MainRoute BEGINS: BODY: MainRoute ENDS: BODY: This is a Foo property. </code> However I don't think processors should have compile time (nor runtime) dependencies to other processors. As usual refactor the common parts to another class which is used by the processors. |
apache-camel | I'm running a Camel route that reads a flag record from database. If flag is NOT there then insert it and perform some additional stuff. I expect being able to check if resultset from query is empty or not but conditions I use on route (choice) seem to be ignored, so it's working like it's always finding something in the database even if I'm certain it's not (in fact logging ${body} shows empty. I'm using spring XML DSL and this is the route: <code> <from uri=';file:/D:/LOCAL/?include=(?i).*.zip&;amp;moveFailed=ErrorFiles&;amp;move=D:/LOCAL/WRK/';/>; <!--Catch a zip file as trigger for route-->; <to uri=';sql:SELECT LOAD_DATE FROM IMPORT_CUSTOMER_CTRL WHERE LOAD_DATE = CURRENT_DATE?datasource=#customerDS&;amp;routeEmptyResultSet=true&;amp;outputType=SelectOne';/>; <!-- Read a flag record from db -->; <log message=';Query result: ${body}'; loggingLevel=';INFO';/>; <choice>; <when>; <simple>;${body)} == null</simple>; <!--IF RESULTSET IS EMPTY THEN DO SOMETHING. THIS CONDITION FAILS AND ALWAYS GOES BY OTHERWISE BRANCH-->;**strong text** <log message=';Do something'; loggingLevel=';INFO';/>; <!--Insert flag record -->; <to uri=';sql:INSERT INTO IMPORT_CUSTOMER_CTRL (LOAD_DATE) VALUES(CURRENT_DATE)?dataSource=#customerDS'; />; </when>; <otherwise>; <log message=';Flag record already exists, ignoring:${body}'; loggingLevel=';INFO';/>; </otherwise>; </choice>; </code> For the when condition I've tried ${body)} == null and ${body)} == '' and even ${bodyAs(String)} == '' but yet choice behaves as it's always filled and goes by otherwise route. I know cause I always get the ';Flag record already exists..'; message in log. What's the correct way to evaluate whether the resultset is empty? | would you post your comment as answer so I can mark it as accepted answerAs explained here above, a generic solution, working whatever the output type (I mean a list as well as a single tuple) is to analyse the various ';meta-data'; published as headers by Camel : https://camel.apache.org/components/3.17.x/sql-component.html#_message_headers You should especially have a look at <code>CamelSqlRowCount</code> which, as its name indicates it, will give you information about the number of records returned by your SQL query. |
apache-camel | I am writing unit test for Camel route. I need to use @SpringBootTest so that I can also use @TestPropertySource. I have several property file mapped property classes. My test code looks like this <code>@SpringBootTest(classes = {CamelAutoConfiguration.class}) @RunWith(CamelSpringBootRunner.class) @BootstrapWith(CamelTestContextBootstrapper.class) @ActiveProfiles(';test';) @TestPropertySource(locations = ';classpath:application-test.yml';) @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD) @ContextConfiguration(classes = {ApplicationConfig.class, SFTPConfig.class, CamelTestContextBootstrapper.class}) @EnableConfigurationProperties public class RouteBuilderTest { @Autowired private CamelContext camelContext; </code> I have added below dependency also as I am using junit4 in project. <code><dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-test-spring</artifactId>; <scope>;test</scope>; </dependency>; </code> Autowiring of CamelContext fails. With standard spring error. <code>No qualifying bean of type 'org.apache.camel.CamelContext' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} </code> Please help. Badly stuck on this. | You have multiple misused annotations in your test. Try this way: <code>@RunWith(CamelSpringBootRunner.class) @SpringBootTest(classes = {ApplicationConfig.class, SFTPConfig.class}) @ActiveProfiles(';test';) @TestPropertySource(locations = ';classpath:application-test.yml';) @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD) public class RouteBuilderTest { @Autowired private CamelContext camelContext; </code> |
apache-camel | I have a project using quarkus, camel which builds fine locally however when i try to build it on my CI environment (either through my jenkins environment or on bitbucket) I get a weird failure. I can't really track the source however and am quite stumped as to what can be causing this. My kubernetes storage does not have any readonly flags enabled. This fails only in kubernetes not even inside just a docker container started locally <code> [INFO] Building jar: /home/jenkins/agent/workspace/Build Jobs/Build Gateway Service Starter/target/gateway-service-starter-1.5.1.jar [INFO] [INFO] --- quarkus-maven-plugin:2.9.0.CR1:build (default) @ gateway-service-starter --- [INFO] No Git Properties File Url Defined. Attempting with default: git.properties [ERROR] Unable to load default git properties file git.properties [INFO] [io.quarkus.deployment.QuarkusAugmentor] Quarkus augmentation completed in 10087ms [INFO] [INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ gateway-service-starter --- [INFO] Using 'UTF-8' encoding to copy filtered resources. [INFO] Copying 2 resources [INFO] [INFO] --- quarkus-maven-plugin:2.9.0.CR1:generate-code (default) @ gateway-service-starter --- [INFO] [INFO] --- maven-compiler-plugin:3.10.1:compile (default-compile) @ gateway-service-starter --- [INFO] Changes detected - recompiling the module! [INFO] Compiling 54 source files to /home/jenkins/agent/workspace/Build Jobs/Build Gateway Service Starter/target/classes [INFO] [INFO] --- quarkus-maven-plugin:2.9.0.CR1:generate-code-tests (default) @ gateway-service-starter --- [INFO] [INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ gateway-service-starter --- [INFO] Using 'UTF-8' encoding to copy filtered resources. [INFO] Copying 2 resources [INFO] [INFO] --- maven-compiler-plugin:3.10.1:testCompile (default-testCompile) @ gateway-service-starter --- [INFO] Changes detected - recompiling the module! [INFO] Compiling 22 source files to /home/jenkins/agent/workspace/Build Jobs/Build Gateway Service Starter/target/test-classes [INFO] [INFO] --- maven-surefire-plugin:3.0.0-M6:test (default-test) @ gateway-service-starter --- [INFO] Skipping execution of surefire because it has already been run for this configuration [INFO] [INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ gateway-service-starter --- [INFO] Building jar: /home/jenkins/agent/workspace/Build Jobs/Build Gateway Service Starter/target/gateway-service-starter-1.5.1.jar [INFO] [INFO] --- quarkus-maven-plugin:2.9.0.CR1:build (default) @ gateway-service-starter --- [INFO] No Git Properties File Url Defined. Attempting with default: git.properties [ERROR] Unable to load default git properties file git.properties [INFO] ------------------------------------------------------------------------ [INFO] BUILD FAILURE [INFO] ------------------------------------------------------------------------ [INFO] Total time: 02:14 min [INFO] Finished at: 2022-05-30T13:34:00Z [INFO] ------------------------------------------------------------------------ [ERROR] Failed to execute goal io.quarkus.platform:quarkus-maven-plugin:2.9.0.CR1:build (default) on project gateway-service-starter: Failed to build quarkus application: io.quarkus.builder.BuildException: Build failure: Build failed due to errors [ERROR] [error]: Build step org.apache.camel.quarkus.core.deployment.CamelNativeImageProcessor#camelRuntimeCatalog threw an exception: java.nio.file.ClosedFileSystemException [ERROR] at jdk.zipfs/jdk.nio.zipfs.ZipFileSystem.ensureOpen(ZipFileSystem.java:1619) [ERROR] at jdk.zipfs/jdk.nio.zipfs.ZipFileSystem.getFileAttributes(ZipFileSystem.java:531) [ERROR] at jdk.zipfs/jdk.nio.zipfs.ZipPath.readAttributes(ZipPath.java:767) [ERROR] at jdk.zipfs/jdk.nio.zipfs.ZipPath.readAttributes(ZipPath.java:777) [ERROR] at jdk.zipfs/jdk.nio.zipfs.ZipFileSystemProvider.readAttributes(ZipFileSystemProvider.java:276) [ERROR] at java.base/java.nio.file.Files.readAttributes(Files.java:1851) [ERROR] at java.base/java.nio.file.Files.isDirectory(Files.java:2322) [ERROR] at org.apache.camel.quarkus.core.deployment.util.CamelSupport.services(CamelSupport.java:71) [ERROR] at org.apache.camel.quarkus.core.deployment.CamelNativeImageProcessor.camelRuntimeCatalog(CamelNativeImageProcessor.java:170) [ERROR] at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [ERROR] at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) [ERROR] at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) [ERROR] at java.base/java.lang.reflect.Method.invoke(Method.java:568) [ERROR] at io.quarkus.deployment.ExtensionLoader$3.execute(ExtensionLoader.java:925) [ERROR] at io.quarkus.builder.BuildContext.run(BuildContext.java:277) [ERROR] at org.jboss.threads.ContextHandler$1.runWith(ContextHandler.java:18) [ERROR] at org.jboss.threads.EnhancedQueueExecutor$Task.run(EnhancedQueueExecutor.java:2449) [ERROR] at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1478) [ERROR] at java.base/java.lang.Thread.run(Thread.java:833) [ERROR] at org.jboss.threads.JBossThread.run(JBossThread.java:501) [ERROR] [ERROR] [error]: Build step org.apache.camel.quarkus.core.deployment.CamelProcessor#camelServices threw an exception: java.nio.file.ClosedFileSystemException [ERROR] at jdk.zipfs/jdk.nio.zipfs.ZipFileSystem.ensureOpen(ZipFileSystem.java:1619) [ERROR] at jdk.zipfs/jdk.nio.zipfs.ZipFileSystem.getFileAttributes(ZipFileSystem.java:531) [ERROR] at jdk.zipfs/jdk.nio.zipfs.ZipPath.readAttributes(ZipPath.java:767) [ERROR] at jdk.zipfs/jdk.nio.zipfs.ZipPath.readAttributes(ZipPath.java:777) [ERROR] at jdk.zipfs/jdk.nio.zipfs.ZipFileSystemProvider.readAttributes(ZipFileSystemProvider.java:276) [ERROR] at java.base/java.nio.file.Files.readAttributes(Files.java:1851) [ERROR] at java.base/java.nio.file.Files.isDirectory(Files.java:2322) [ERROR] at org.apache.camel.quarkus.core.deployment.util.CamelSupport.services(CamelSupport.java:71) [ERROR] at org.apache.camel.quarkus.core.deployment.CamelProcessor.camelServices(CamelProcessor.java:213) [ERROR] at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [ERROR] at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) [ERROR] at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) [ERROR] at java.base/java.lang.reflect.Method.invoke(Method.java:568) [ERROR] at io.quarkus.deployment.ExtensionLoader$3.execute(ExtensionLoader.java:925) [ERROR] at io.quarkus.builder.BuildContext.run(BuildContext.java:277) [ERROR] at org.jboss.threads.ContextHandler$1.runWith(ContextHandler.java:18) [ERROR] at org.jboss.threads.EnhancedQueueExecutor$Task.run(EnhancedQueueExecutor.java:2449) [ERROR] at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1478) [ERROR] at java.base/java.lang.Thread.run(Thread.java:833) [ERROR] at org.jboss.threads.JBossThread.run(JBossThread.java:501) [ERROR] ->; [Help 1] [ERROR] [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch. [ERROR] Re-run Maven using the -X switch to enable full debug logging. [ERROR] [ERROR] For more information about the errors and possible solutions, please read the following articles: [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException </code> | Weirdly, the solution for us was to use <code>mvn clean install</code> rather than <code>mvn clean verify package</code> Theoretically, shouldn't make the difference but it did. |
apache-camel | I am new to Apache Camel and I would like to ask a few things. Basically, I want to call the API based on the resource ID list I have and combine all the responses from the API into one message. I have already tried AggregationStrategy, but it doesn't seem to be working. The message body always returns the last response from API and it doesn't keep the old list. I would be very grateful if you could give me some examples. Route <code>from(';file:C:\\Inbound';) //Get resourceID list and split it to call the API .split(simple(';${body}';)) .aggregationStrategy(new ArrayListAggregationStrategy()) .toD(';{{api_url}}${body.resourceID}';) .log(';After API call ${body}';) .end(); </code> AggregationStrategy <code>public Exchange aggregate(Exchange oldExchange, Exchange newExchange) {Object newBody = newExchange.getIn().getBody();ArrayList<Object>; list = null;if (oldExchange == null) { list = new ArrayList<Object>;(); list.add(newBody); newExchange.getIn().setBody(list); return newExchange; } else { list = oldExchange.getIn().getBody(ArrayList.class); list.add(newBody); return oldExchange; }}} </code> | Below you'll find a basic example how to implement <code>.split</code> with <code>AggregationStrategy</code> that returns a Java <code>List</code>. It should be straightforward to apply to your specific scenario. <code>Routes.java</code> <code>import org.apache.camel.builder.RouteBuilder;public class Routes { public static RouteBuilder routes() { return new RouteBuilder() { public void configure() { from(';timer:mainRouteTrigger?repeatCount=1';) .routeId(';MainRouteTrigger';) .setBody(constant(';100 200 300';)) .to(';direct:mainRoute';) .end() ; from(';direct:mainRoute';) .routeId(';MainRoute';) .log(';MainRoute BEGINS: BODY: ${body}';) .split(body().tokenize('; ';), new Aggregator()) .to(';direct:singleRoute';) .end() .log(';MainRoute ENDS: BODY: ${body}';) .end() ; from(';direct:singleRoute';) .routeId(';SingleRoute';) .log(';SingleRoute BEGINS: BODY: ${body}';) .setBody(simple(';this is a response for id ${body}';)) .log(';SingleRoute ENDS: BODY: ${body}';) .end() ; } }; } } </code> <code>Aggregator.java</code> <code>import org.apache.camel.AggregationStrategy; import org.apache.camel.Exchange;import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream;public class Aggregator implements AggregationStrategy { @Override public Exchange aggregate(Exchange oldExchange, Exchange newExchange) { // first iteration // oldExchange is null // body of newExchange is String if (oldExchange == null) { List<String>; newList = buildListFrom(newExchange); newExchange.getMessage().setBody(newList, List.class); return newExchange; } // second and subsequent iterations // body of oldExchange is List<String>; // body of newExchange is String List<String>; oldList = oldExchange.getMessage().getBody(List.class); List<String>; newList = buildListFrom(newExchange); List<String>; combined = Stream.concat(oldList.stream(), newList.stream()).collect(Collectors.toList()); oldExchange.getMessage().setBody(combined); return oldExchange; } private List<String>; buildListFrom(Exchange exchange) { String body = exchange.getMessage().getBody(String.class); List<String>; list = new ArrayList<String>;(); list.add(body); return list; } } </code> When executed the following expected outcome is logged: <code>AbstractCamelContext INFO Routes startup (total:3 started:3) AbstractCamelContext INFO Started MainRouteTrigger (timer://mainRouteTrigger) AbstractCamelContext INFO Started MainRoute (direct://mainRoute) AbstractCamelContext INFO Started SingleRoute (direct://singleRoute) AbstractCamelContext INFO Apache Camel 3.14.2 (camel-1) started in 133ms (build:14ms init:105ms start:14ms) MainSupport INFO Waiting until complete: Duration max 5 seconds MainRoute INFO MainRoute BEGINS: BODY: 100 200 300 SingleRoute INFO SingleRoute BEGINS: BODY: 100 SingleRoute INFO SingleRoute ENDS: BODY: this is a response for id 100 SingleRoute INFO SingleRoute BEGINS: BODY: 200 SingleRoute INFO SingleRoute ENDS: BODY: this is a response for id 200 SingleRoute INFO SingleRoute BEGINS: BODY: 300 SingleRoute INFO SingleRoute ENDS: BODY: this is a response for id 300 MainRoute INFO MainRoute ENDS: BODY: [this is a response for id 100, this is a response for id 200, this is a response for id 300] MainSupport INFO Duration max seconds triggering shutdown of the JVM AbstractCamelContext INFO Apache Camel 3.14.2 (camel-1) shutting down (timeout:45s) AbstractCamelContext INFO Routes stopped (total:3 stopped:3) AbstractCamelContext INFO Stopped SingleRoute (direct://singleRoute) AbstractCamelContext INFO Stopped MainRoute (direct://mainRoute) AbstractCamelContext INFO Stopped MainRouteTrigger (timer://mainRouteTrigger) AbstractCamelContext INFO Apache Camel 3.14.2 (camel-1) shutdown in 34ms (uptime:5s54ms) </code> Note that <code>[this is a response for id 100, this is a response for id 200, this is a response for id 300] </code> Is a Java <code>List</code> that has been converted to a string automatically by <code>.log</code>. |
apache-camel | I have an Apache Camel application, which uses a Choice with a Predicate. How can I test the predicate without an integration test? Code <code>@SpringBootApplication public class TestApplication { public static void main(String[] args) { SpringApplication.run(TestApplication.class, args); } @Bean public EndpointRouteBuilder route() { return new EndpointRouteBuilder() { @Override public void configure() throws Exception { from(file(';d:/tmp/camel/';)) .choice() .when(jsonpath(';$[?(@.status == 0)]';)) .log(';ok';) .otherwise() .log(';not ok';); } }; } } </code> ResearchI read Test JUnit5, but it looks like an integration test. However, I don't want to test a full route.I read Test Spring JUnit5, but it is an integration test. Question How can I extract the predicate <code>jsonpath(';$[?(@.status == 0)]';)</code> and test it isolated in an unit test with JUnit 5? | Might be hard to accomplish this without a CamelContext. I'd probably approach this with Camel's excellent mocking and stubbing utilities. But if you really just want to isolate the jsonpath expression, you could try something like this: <code>JsonPathExpression exp = new JsonPathExpression(';$[?(@.status == 0)]';); Exchange exchange = new DefaultExchange(context); final Predicate predicate = exp.createPredicate(context); exchange.getIn().setBody(';{ \';status\';: 0 }';); final boolean matches = predicate.matches(exchange); assertTrue(matches); </code> Note that you'll still need a CamelContext for this. Typically you'd get it by having the test class extend CamelTestSupport, or if you're in a spring environment, spring can autowire it: <code>@Autowired CamelContext camelContext;</code> Edit: If you just want to test the JsonPath expression outside of Camel: <code>String jsonPath = ';$[?(@.status == 0)]';; String json = ';{ \';status\';: 0 }';;DocumentContext jsonContext = JsonPath.parse(json); JSONArray result = jsonContext.read(jsonPath); assertEquals(1, result.size()); </code> |
apache-camel | Current behaviour: When I'm running a Quarkus App with Camel it automatically starts all the RouteBuilder Extensions as Routes. What I want to achieve: On startup only the Routes that I configured are started. What I tried:With the following snippet it's possible to explicitly start the CamelMainApplication but I dont know how to get control over e.g. the CamelContext at this point where I would be able to configure my routes.<code>@QuarkusMain public class Main { public static void main(String[] args) throws Exception { Quarkus.run(CamelMainApplication.class, args); } } </code>On the Route I can use .noAutoStartup() to disable the route on startup. But this means that it's not the default for all routes to be disabled at first and second I don't know where to activate them as I don't know where in a Quarkus App I can get a hand on the Camel Context to activate the route.With the following in my application.yml I can disable the automatic route discovery but then the remaining question is how I can manually start the route, e.g. in my QuarkusMain class. <code>quarkus: camel: routes-discovery: enabled: false </code> | I think it is best way. Quarkus has properties for include and exclude route as pattern. this properties is List You can add one to N <code>quarkus.camel.routes-discovery.exclude-patterns=tes.Comp,tes.package.MyRoute quarkus.camel.routes-discovery.include-patterns=test.mypackage.XX </code> |
apache-camel | I have seen a bunch of explaination, even on this site, about the error above... but no one was sufficiently clear about this two points:Why appears this error? How can I correct it exactly? What must I change in Camel/Spring boot project to make things work (what files, what configurations, what import of xsd? I must change POM? Where? Etc) | The Apache Camel metamodel has been modified. You need to adapt the model or to point to the version of the xsd matching the version of your model. if you are migrating from a 2.x to 3.x version, see https://camel.apache.org/manual/camel-3-migration-guide.html#_setheader_and_setproperty_in_xml_dsl So migrate <code><setHeader headerName=';foo';>;<simple>;Hello ${body}</simple>;</setHeader>; </code> To <code><setHeader name=';foo';>;<simple>;Hello ${body}</simple>;</setHeader>; </code> To adapt to the correct version of xsd, you need to change the xsi:schemaLocation and point to a specific version instead of the ';generic one';. So replace something like https://camel.apache.org/schema/spring/camel-spring.xsd by https://camel.apache.org/schema/spring/camel-spring-2.25.4.xsd or https://camel.apache.org/schema/spring/camel-spring-3.17.0.xsd |
apache-camel | I have this errororg/apache/camel/CamelContextAware has been compiled by a more recent version of the Java Runtime (class file version 55.0), this version of the Java Runtime only recognizes class file versions up to 52.0When I am trying to compile maven in a Spring Boot Camel application. There is no trace of explanation of this error in documentation, the only thing I found is a very short javadoc. Can you help me? | The problem was here <code> <dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-test-spring-junit5</artifactId>; <version>;3.15.0</version>; <scope>;test</scope>; </dependency>; </code> Setting version at <code>3.12.0</code> solved for me. |
apache-camel | Is it possible to set a response body to an object and pass in a camel header property. I can achieve this in a processor but I'd rather do it in line of the route. <code>.setBody(constant( new Foo() .withOne(';HelloWorld';) .withTwo(simple(';Header property is ${header.uniqueProperty}';).toString()) )) </code> With the above code I get a response of: <code><foo>; <one>;HelloWorld</one>; <two>;Header property is ${header.uniqueProperty}</two>; </foo>; </code> Here is my POJO <code>@XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class Foo { private String one; private String two; public String getOne() { return one; } public void setOne(final String one) { this.one = one; } public String getTwo() { return two; } public void setTwo(final String two) { this.two = two; } public Foo withOne(final String one) { setOne(one); return this; } public Foo withTwo(final String two) { setTwo(two); return this; } } </code> | <code>constant()</code> probably won't work for you, since you probably want this dynamically evaluated for every exchange that passes through. Since you need to set the body to a newly instantiated object, you need a mechanism that's capable of this. You mentioned you want to avoid a processor, but I'd like to point out how simple this could be done in the route: <code>.setBody(exchange ->; new Foo() .withOne(';HelloWorld';) .withTwo(simple(';Header property is '; + exchange.getIn().getHeader(';uniqueProperty';))) ) </code> Edit: Actually this is not a processor. We're just passing a lambda (<code>Function</code>) to <code>setBody()</code>. If you're in a Spring environment, you could use spring expression language: <code>.setBody().spel(';#{new Foo()'; + ';.withOne('HelloWorld')'; + ';.withTwo(simple('Header property is ' + request.headers.uniqueProperty))}';); </code> |
apache-camel | I am trying to compound conditions with the PredicateBuilder and saving it to the header to access the predicate from the when() function. At the beginning I set the body to <code>Hello World</code>. Also the body is not null or not equal to <code>AUTHENTICATE failed</code> but I getting into the when block and <code>process_no_mail_or_failed</code> is being logged. I do not understand what I am doing wrong. How can I compound predicates in Apache Camel and use them in the when() function? In case I have to check the body at some step. Therefore I did it in the way. I apreciate any help! Apache Camel route: <code>import org.apache.camel.Exchange; import org.apache.camel.Message; import org.apache.camel.Predicate; import org.apache.camel.Processor; import org.apache.camel.builder.PredicateBuilder; import org.apache.camel.builder.RouteBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component;@Component public class TestRoute extends RouteBuilder { static final Logger LOGGER = LoggerFactory.getLogger(EmailPollingRoute.class); static final String AUTHENTICATE_FAILED = ';AUTHENTICATE failed.';; @Override public void configure() throws Exception { from(';quartz://emailTimer?cron=0/30+*+*+*+*+?+*';) .log(';TestRoute - Before calling transform';) .process(new Processor() { @Override public void process(Exchange exchange) throws Exception { Message message = exchange.getIn(); message.setBody(';Hello World';); String body = message.getBody(String.class); LOGGER.info(';body: '; + body); Predicate p1 = body().isNull(); Predicate p2 = body().isEqualTo(AUTHENTICATE_FAILED); Predicate predicate_result12 = PredicateBuilder.or(p1, p2); message.setHeader(';process_no_mail_or_failed';, predicate_result12); } }) .choice() .when(header(';process_no_mail_or_failed';).convertTo(Predicate.class)) //.when(simple(';${body} == null || ${body} == 'AUTHENTICATE failed.'';)) //This works for me. I am getting into the otherwise block .log(';when: ${body}';) .otherwise() .log(';otherwise: ${body}';); } } </code> | Predicates have matches method which you can use to evaluate the predicate with If you want to get the result for Predicate you can use the matches-method to evaluate the predicate. <code>from(';direct:example';) .routeId(';example';) .process(exchange ->; { Predicate bodyNotNullOrEmpty = PredicateBuilder.and( body().isNotEqualTo(null), body().isNotEqualTo(';';) ); Boolean result = bodyNotNullOrEmpty.matches(exchange); exchange.getMessage().setHeader(';bodyNotNullOrEmpty';, result); }) .choice().when(header(';bodyNotNullOrEmpty';)) .log(';body: ${body}';) .otherwise() .log(';Body is null or empty';) .end() .to(';mock:result';); </code> You could also just import static methods from the Predicate builder and use them within choice without having to store the result to exchange property. This trick of importing the static methods from Predicate builder can be easy to miss due to it being only mentioned in negate predicates section of the documentation. <code>import static org.apache.camel.builder.PredicateBuilder.not; import static org.apache.camel.builder.PredicateBuilder.and;...from(';direct:example';) .routeId(';example';) .choice() .when(and(body().isNotNull(), body().isNotEqualTo(';';))) .log(';body: ${body}';) .otherwise() .log(';Body is null or empty';) .end() .to(';mock:result';); </code> |
apache-camel | I read in the Camel documentation that we can use looping with a <code>doWhile</code> construct. But it is not clear to me: does the Camel's <code>doWhile</code> behaves like a classic <code>do-while</code> (executing at least once without condition), or it is more like the <code>while</code> construct (executing only if condition is true)? | I have tested, and it seems equivalent to the <code>while</code> construct. |
apache-camel | I am using Apache Camel DSL route and want to check if the body is not <code>null</code> and body does not contains substring like <code>authenticate failed</code>. In java something like: <code> if(body != null &;&; !body.contains(';authenticate failed';)) { //Do something. } </code> Apache Camel DSL: <code> .choice() .when(body().contains(';authenticate failed';)) .log(';after choice body().contains('authenticate failed') body: ${body}';) .when(body().isNotNull()) //Here I want to add the addiontional condition to this when `body not contains authenticate failed`. </code> How can I write a condition like this? predicates objects in the process method and write tin my case? | You can use PredicateBuilder to create pretty composite predicates. Here's example how to do simple Body is not null or empty check with PredicateBuilder. <code>package com.example;import org.apache.camel.Predicate; import org.apache.camel.RoutesBuilder; import org.apache.camel.builder.PredicateBuilder; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.test.junit4.CamelTestSupport; import org.junit.Test;public class ExampleTests extends CamelTestSupport { @Test public void testValidBody() throws Exception { MockEndpoint resultMockEndpoint = getMockEndpoint(';mock:notNull';); resultMockEndpoint.expectedMessageCount(1); template.sendBody(';direct:predicateExample';, ';Hello world!';); resultMockEndpoint.assertIsSatisfied(); } @Test public void testEmptyBody() throws Exception { MockEndpoint resultMockEndpoint = getMockEndpoint(';mock:nullOrEmpty';); resultMockEndpoint.expectedMessageCount(1); template.sendBody(';direct:predicateExample';, null); resultMockEndpoint.assertIsSatisfied(); } @Test public void testNullBody() throws Exception { MockEndpoint resultMockEndpoint = getMockEndpoint(';mock:nullOrEmpty';); resultMockEndpoint.expectedMessageCount(1); template.sendBody(';direct:predicateExample';, null); resultMockEndpoint.assertIsSatisfied(); } @Override protected RoutesBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { Predicate bodyNotNullOrEmpty = PredicateBuilder.and( body().isNotNull(), body().isNotEqualTo(';';) ); from(';direct:predicateExample';) .routeId(';predicateExample';) .choice().when(bodyNotNullOrEmpty) .log(';Received body: ${body}';) .to(';mock:notNull';) .otherwise() .log(';Body was null or empty!';) .to(';mock:nullOrEmpty';) .end() .log(';done';); } }; } } </code> Not and Or can take lists of predicates as arguments or even other composite predicates which allows one to make some fairly complex composite predicates. However when using PredicateBuilder starts to get overly verbose it's good to just use processor or bean instead to abstract away some of the complexity. |
apache-camel | I have an spring boot application which have routes.xml being loaded on startup On the routes.xml, i have a MQ queue source that contains sample message <code>SOH{123}{345}{4 5 6 }ETXSOH{111}{222}{3 3 3 }ETX </code> where SOH = \u0001 and ETX = \u0003 When i receive this message, i want to split the message to two <code>{123}{345}{4 5 6 } </code> and <code>{111}{222}{3 3 3 } </code> Currently i am trying to split using <code><split>; <tokenize token=';(?s)(?&;lt;=\u0001)(.*?)(?=\u0003)'; regex=';true';/>; <to uri=';jms:queue:TEST.OUT.Q'; />; </split>; </code> I have tested this regex using online regex tester and it was matching. https://regex101.com/r/fU5VVj/1 But when runnning the code what i am geting is #1 <code>SOH </code> #2 <code>ETXSOH </code> #3 <code>ETX </code> Also tried the token and endToken but not working for my case <code><tokenize token=';\u0001'; endToken=';\u0003'; />; </code> Is my case possible using camel route xml? If yes, can you point me to correct regex or start and end token. Thanks | Seems camel regex is different with java regex, just created a new process using sample code below <code> Pattern p = Pattern.compile(';(?s)(?<=\\u0001).*?(?=\\u0003)';); Matcher m = p.matcher(items); List<String>; tokens = new LinkedList<>;(); while (m.find()) { String token = m.group(); System.out.println(';item = ';+token); tokens.add(token); } </code> |
apache-camel | I have a job that looks like this: <code>@Named public class MyCamelRouteBuilder extends RouteBuilder { private static final String JOB_NAME = ';abc';; private static final String JOB_METHOD_NAME = ';xyz';; private final MyJob myJob; @Inject public MyCamelRouteBuilder(MyJob myJob) { super(); this.myJob = myJob; } @Override public void configure() { fromF(';direct:%s';, JOB_NAME) .routeId(JOB_NAME) .bean(myJob, JOB_METHOD_NAME) .end(); fromF(';master:some_name_1/some_name_2:scheduler:%s?delay=%s';, JOB_NAME, 1234) .routeId(';JobTimer';) .toF(';direct:%s';, JOB_NAME) .end(); } } </code> A very simplified version of the job class: <code>@Named public class MyJob { private MyJob() {} } public void xyz() { } } </code> This does work and it does gets triggered as expected. The problem starts here: Now, I also want to create a REST controller that will be able to trigger the exact same job. Something like this: <code>@Named @RestController @RequestMapping @Validated public class MyController { private static final String JOB_NAME = ';abc';; private final ProducerTemplate producerTemplate; @Inject public MyController( ProducerTemplate producerTemplate ) { this.producerTemplate = producerTemplate; } @PostMapping(path = ';/my_endpoint';) public String run() throws Exception { producerTemplate.requestBody(';direct:'; + JOB_NAME); return ';ok';; } } </code> But once it reaches this line, the job is not triggered and the request call keeps hanging. <code>producerTemplate.requestBody(';direct:'; + JOB_NAME); </code> Any ideas? | The fix for my problem: <code>@Named @RestController @RequestMapping @Validated public class MyController { private static final String JOB_NAME = ';abc';; @Produce(';direct:'; + JOB_NAME) private final ProducerTemplate producerTemplate; private final CamelContext context; @Inject public MyController( ProducerTemplate producerTemplate, CamelContext context ) { this.producerTemplate = producerTemplate; this.context = context; } @PostMapping(path = ';/my_endpoint';) public String run() throws Exception { Exchange exchange = new DefaultExchange(context); producerTemplate.send(exchange); return ';ok';; } } </code> |
apache-camel | I try following a video tutorial for Apache Camel education and trying aggregate queue objects in a next way: <code>@Component public class AggregationRoute extends RouteBuilder { @Override public void configure() throws Exception { from(';file:files/json';) .unmarshal().json(JsonLibrary.Jackson, CurrencyExchange.class) .aggregate(simple(';${body.to}';), new ArrayListAggregationStrategy()) // <--- (1) .completionSize(3)// <----- (2) .to(';log:aggregation';); } } </code> CurrencyExchange model: <code>@Getter @Setter @AllArgsConstructor @NoArgsConstructor @ToString public class CurrencyExchange { public int id; public String from; public String to; public BigDecimal conversionMultiple; } </code> Aggregation implementation: <code>public class ArrayListAggregationStrategy implements AggregationStrategy { @Override public Exchange aggregate(Exchange oldExchange, Exchange newExchange) { Object newObject = newExchange.getIn().getBody(); ArrayList<Object>; list = new ArrayList<>;(); if(oldExchange == null){ list.add(newObject); newExchange.getIn().setBody(list); return newExchange; } else { oldExchange.getIn().getBody(list.getClass()).add(newObject); return oldExchange; } } } </code> First of all - the code works correctly without (1) and (2) lines. When I uncommented these lines, I get the error: <code> >; 2022-05-12 12:34:26.913 ERROR 82201 --- [le://files/json] >; o.a.c.p.e.DefaultErrorHandler : Failed delivery for >; (MessageId: F948EB377E1DB38-0000000000000000 on ExchangeId: >; F948EB377E1DB38-0000000000000000). Exhausted after delivery attempt: 1 >; caught: org.apache.camel.language.bean.RuntimeBeanExpressionException: >; Failed to invoke method: to on null due to: >; org.apache.camel.component.bean.MethodNotFoundException: Method with >; name: to not found on bean: >; com.education.camelmicroservicea.model.CurrencyExchange@301f4095 of >; type: com.education.camelmicroservicea.model.CurrencyExchange on the >; exchange: Exchange[F948EB377E1DB38-0000000000000000]</code> Stacktrace: <code> >; org.apache.camel.language.bean.RuntimeBeanExpressionException: Failed >; to invoke method: to on null due to: >; org.apache.camel.component.bean.MethodNotFoundException: Method with >; name: to not found on bean: >; com.education.camelmicroservicea.model.CurrencyExchange@301f4095 of >; type: com.education.camelmicroservicea.model.CurrencyExchange on the >; exchange: Exchange[F948EB377E1DB38-0000000000000000] at >; org.apache.camel.language.bean.BeanExpression.invokeOgnlMethod(BeanExpression.java:453) >; ~[camel-bean-3.16.0.jar:3.16.0] at >; org.apache.camel.language.bean.BeanExpression.evaluate(BeanExpression.java:199) >; ~[camel-bean-3.16.0.jar:3.16.0] .....</code>Please note, that the error message: <code>Failed to invoke method: to on null due to:</code> means method <code>to</code>, so it can sound like Failed to invoke method: <code>to()</code> on null due to: Why the <code>simple</code> through this exception, if I receive the body in the correct way? | You just don't need to trust Lombok when u use reflection. After I added getter handly, all works fine: <code>@Getter @Setter @AllArgsConstructor @NoArgsConstructor @ToString public class CurrencyExchange { private int id; private String from; private String to; private BigDecimal conversionMultiple; public String getTo(){ return this.to; } } </code> |
apache-camel | I have a system that distributes Kafka stream data to MQTT topics. The Apache Camel routes looks like that: <code><?xml version=';1.0'; encoding=';UTF-8';?>; <routes xmlns=';http://camel.apache.org/schema/spring';>; <route id=';KafkaToMQTT';>; <from uri=';kafka://mqtt?brokers=localhost:9092'; />; <to uri=';micrometer:timer:camel.proxy.kafka.mqtt.stream?action=start'; />; <toD uri=';mqtt:mqtt?host=tcp://localhost:1883&;amp;publishTopicName=${header.kafka.KEY}'; />; <to uri=';log://camel.proxy?groupInterval=100&;amp;level=INFO'; />; <to uri=';micrometer:timer:camel.proxy.kafka.mqtt.stream?action=stop'; />; </route>; </routes>; </code> And since the data steam starts, for 7 topics of 10 everything is ok, but for messages that should fall into 3 other topics (different between the different runs, but the same at the same camel route run) I'm getting the error message with the stacktrace like below: <code>19:19:34.195 [Camel (camel-1) thread #4 - KafkaConsumer[mqtt]] ERROR o.a.c.processor.DefaultErrorHandler - Failed delivery for (MessageId: ID-camel-proxy-586888f9b6-dfnwp-1652296571794-0-14406 on ExchangeId: ID-camel-proxy-586888f9b6-dfnwp-1652296571794-0-14404). Exhausted after delivery attempt: 1 caught: java.lang.IllegalStateException: Already connectedMessage History --------------------------------------------------------------------------------------------------------------------------------------- RouteId ProcessorId Processor Elapsed (ms) [KafkaToMQTT ] [KafkaToMQTT ] [kafka://mqtt?brokers=kafka%3A9092&;groupId=mqtt ] [ 0] [KafkaToMQTT ] [to85 ] [micrometer:timer:camel.proxy.kafka.mqtt.stream?action=start ] [ 0] [KafkaToMQTT ] [toD1 ] [ ] [ 0]Stacktrace --------------------------------------------------------------------------------------------------------------------------------------- java.lang.IllegalStateException: Already connected at org.fusesource.mqtt.client.CallbackConnection.connect(CallbackConnection.java:135) at org.apache.camel.component.mqtt.MQTTEndpoint.connect(MQTTEndpoint.java:315) at org.apache.camel.component.mqtt.MQTTProducer.ensureConnected(MQTTProducer.java:108) at org.apache.camel.component.mqtt.MQTTProducer.process(MQTTProducer.java:39) at org.apache.camel.processor.SendDynamicProcessor$1.doInAsyncProducer(SendDynamicProcessor.java:178) at org.apache.camel.impl.ProducerCache.doInAsyncProducer(ProducerCache.java:445) at org.apache.camel.processor.SendDynamicProcessor.process(SendDynamicProcessor.java:160) at org.apache.camel.processor.RedeliveryErrorHandler.process(RedeliveryErrorHandler.java:548) at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:201) at org.apache.camel.processor.Pipeline.process(Pipeline.java:138) at org.apache.camel.processor.Pipeline.process(Pipeline.java:101) at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:201) at org.apache.camel.processor.DelegateAsyncProcessor.process(DelegateAsyncProcessor.java:97) at org.apache.camel.component.kafka.KafkaConsumer$KafkaFetchRecords.doRun(KafkaConsumer.java:326) at org.apache.camel.component.kafka.KafkaConsumer$KafkaFetchRecords.run(KafkaConsumer.java:215) at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515) at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) 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> For me it is unclear what kind of interaction is inerrupted and if it is just the resource bottleneck like the insufficient connections pool or what else, what can be configured to increase the resources? | It looks like this is <code><toD/>;</code>-related issue because of dynamic nature. Doing the explicit switch with pre-defined value check makes everything working: <code><routes xmlns=';http://camel.apache.org/schema/spring';>; <route id=';KafkaToMQTT';>; <from uri=';kafka://mqtt?brokers=kafka:9092';/>; <to uri=';micrometer:timer:camel.proxy.kafka.mqtt.stream?action=start';/>; <when>; <simple>;${header.kafka.KEY} == ';ExpectedValue1';</simple>; <to uri=';mqtt:mqtt?host=tcp://mqtt:1883&;amp;publishTopicName=ExpectedValue1';/>; </when>; <when>; <simple>;${header.kafka.KEY} == ';ExpectedValue2';</simple>; <to uri=';mqtt:mqtt?host=tcp://mqtt:1883&;amp;publishTopicName=ExpectedValue2';/>; </when>; <to uri=';log://camel.proxy?groupInterval=100&;amp;level=INFO';/>; <to uri=';micrometer:timer:camel.proxy.kafka.mqtt.stream?action=stop';/>; </route>; </routes>; </code> That isn't so universal, but worked for my goal.s |
apache-camel | So what I'm trying to do here is to create a zoom meeting through camel apache. I keep getting the error whenever I run the program and the line causing the error is when I start the camel context <code>c.start()</code> Here is the code that I run: <code> package com.example.demo; import com.google.gson.Gson; import com.google.gson.JsonObject; import org.apache.camel.*; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.impl.DefaultCamelContext; import org.apache.camel.model.dataformat.JsonLibrary; import static org.springframework.http.converter.json.Jackson2ObjectMapperBuilder.json;public class Test { private String token = ';sample token';; public static void main(String[] args) throws Exception { CamelContext c = new DefaultCamelContext(); settings set = new settings(true, true, false, false, true,';voip';,';cloud';); recurrence rec = new recurrence(1,1); c.addRoutes(new RouteBuilder() { @Override public void configure() throws Exception { from(';direct:start';) .process(exchange ->; exchange.getIn().setBody(new ZoomSetting( ';Testing zoom api';, 2, ';2022-05-09T14: 00: 00';, 45, ';America/New_York';, ';testing';, rec, set ))) .marshal().json(JsonLibrary.Gson) .setHeader(Exchange.HTTP_METHOD, constant(';POST';)) .setHeader(Exchange.CONTENT_TYPE, constant(';application/json';)) .setHeader(';Authorization';, simple(';Bearer';+ token)) .to(';https://api.zoom.us/v2/users/me/meetings';) .process(exchange ->; log.info(';The response code is: {}';, exchange.getIn().getHeader(Exchange.HTTP_RESPONSE_CODE))); } }); c.start(); } } </code> I tried to include the dependency in the pom.xml file, but that didn't really help. Here is the dependencies that I included in the pom.xml: <code><dependencies>; <dependency>; <groupId>;org.springframework.boot</groupId>; <artifactId>;spring-boot-starter-web</artifactId>; </dependency>; <dependency>; <groupId>;org.apache.camel.springboot</groupId>; <artifactId>;camel-spring-boot-starter</artifactId>; <version>;3.16.0</version>; </dependency>; <!-- https://mvnrepository.com/artifact/org.apache.camel/camel-http-starter -->; <dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-http-starter</artifactId>; <version>;3.0.0-RC3</version>; </dependency>; <dependency>; <groupId>;org.springframework.boot</groupId>; <artifactId>;spring-boot-starter-test</artifactId>; <scope>;test</scope>; </dependency>; <dependency>; <groupId>;com.auth0</groupId>; <artifactId>;java-jwt</artifactId>; <version>;3.19.2</version>; </dependency>; <dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-rest</artifactId>; <version>;3.16.0</version>; </dependency>; <dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-gson</artifactId>; <version>;3.16.0</version>; </dependency>; <dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-direct</artifactId>; <version>;3.16.0</version>; </dependency>; <dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-http</artifactId>; <version>;3.16.0</version>; <scope>;test</scope>; </dependency>; <dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-core</artifactId>; <version>;3.16.0</version>; </dependency>; <dependency>; <groupId>;org.apache.camel</groupId>; <artifactId>;camel-context</artifactId>; <version>;2.25.4</version>; </dependency>; </dependencies>;<build>; <plugins>; <plugin>; <groupId>;org.springframework.boot</groupId>; <artifactId>;spring-boot-maven-plugin</artifactId>; </plugin>; </plugins>; </build>; </code>The error I keep getting is this: Exception in thread ';main'; java.lang.AbstractMethodError: Receiver class org.apache.camel.management.JmxManagementLifecycleStrategy does not define or inherit an implementation of the resolved method abstract onRouteContextCreate(Lorg/apache/camel/Route;)V of interface org.apache.camel.spi.LifecycleStrategy. at org.apache.camel.reifier.RouteReifier.doCreateRoute(RouteReifier.java:213) at org.apache.camel.reifier.RouteReifier.createRoute(RouteReifier.java:74) at org.apache.camel.impl.DefaultModelReifierFactory.createRoute(DefaultModelReifierFactory.java:49) at org.apache.camel.impl.DefaultCamelContext.startRouteDefinitions(DefaultCamelContext.java:887) at org.apache.camel.impl.DefaultCamelContext.startRouteDefinitions(DefaultCamelContext.java:775) at org.apache.camel.impl.engine.AbstractCamelContext.doInit(AbstractCamelContext.java:2937) at org.apache.camel.support.service.BaseService.init(BaseService.java:83) at org.apache.camel.impl.engine.AbstractCamelContext.init(AbstractCamelContext.java:2620) at org.apache.camel.support.service.BaseService.start(BaseService.java:111) at org.apache.camel.impl.engine.AbstractCamelContext.start(AbstractCamelContext.java:2639) at org.apache.camel.impl.DefaultCamelContext.start(DefaultCamelContext.java:255) at com.example.demo.Test.main(Test.java:42) | If you want to run camel using main method you should use camel-main which is for running standalone camel applications. What you're trying to do there is running camel as standalone application but using camel-spring-boot dependencies. You can use maven archetype camel-archetype-main to generate new standalone camel application project and use that as reference on how to setup your project. <code>mvn archetype:generate -DarchetypeGroupId=';org.apache.camel.archetypes'; -DarchetypeArtifactId=';camel-archetype-main'; -DarchetypeVersion=';3.14.3'; </code> If you want to use spring-framework and spring-boot to run camel then you can use camel-archetype-spring-boot archetype to generate example camel spring-boot project. I would recommend getting familiar with basics of Spring-framework and Spring-boot before bringing camel to the mix to avoid unnecessary confusion. <code>mvn archetype:generate -DarchetypeGroupId=';org.apache.camel.archetypes'; -DarchetypeArtifactId=';camel-archetype-spring-boot'; -DarchetypeVersion=';3.14.3'; </code>Camel - Archetypes Camel - main Camel - spring-boot |
apache-camel | I didn't manage to customize transacted route with rollback/commit post-processing. Any help on how to write this kind of transacted route will be really appreciated. Based on some example code, I wrote something like this : <code>from(direct(';global';) .log(';anything before that doesn't need transaction context';) .to(direct(';transacted';) .log(';anything after that doesn't need transaction context';) ;from(direct(';transacted';)) .onCompletion().onCompleteOnly() .validate().simple(';${body.state} == 'MOVE_SUCCESS'';) .log(';success, with commit ';) .end() .onCompletion().onFailureOnly() .validate().simple(';${body.state} == 'WAITING_MOVE'';) .bean(DbService.class, ';documentInError(${body}, ${exception})';) .bean(FileService.class, ';moveFileToError';) .log(';error, with rollback';) .end() .transacted() .bean(DbService.class, ';updateDocument';) .bean(FileService.class, ';moveFileToTarget';) ; </code> but don't know why, I still have this kind of error :Caused by: java.lang.IllegalArgumentException: The output must be added as top-level on the route. Try moving onCompletion[[]] to the top of route. at camel.core.model@3.15.0/org.apache.camel.model.ProcessorDefinition.addOutput(ProcessorDefinition.java:209) ~[camel-core-model-3.15.0.jar:na] at camel.core.model@3.15.0/org.apache.camel.model.ProcessorDefinition.onCompletion(ProcessorDefinition.java:3637) ~[camel-core-model-3.15.0.jar:na]I'm permitted to declare those onCompletion only ';outside'; any route, but that doesn't correspond to what I want. Beacause then the onCompletion processing is hold in both global and transacted route, leading to other issues. I already have onException application wise configured, with retry policy on FileService errors (handling redelivery of processor nodes). And would prefere to keep them configured application wise. thanks, | We finally achieved kind of route scope of onCompletion and onException, by separating global route and transacted route in two distinct route builders. But we decided to handle a transaction in java (spring) rather than in camel. Mainly because the transaction scope is difficult to figure out in camel. the transaction error handler, taking the lead once redelevery policy are exhausted, and somehow seems to happen within onException without clear demarcation : for example : <code>onException(IOException) // the ';following'; (whatever holds behind the scene) happens inside transaction .maximumRedeliveries(3) .retryAttemptedLogLevel(WARN) .retriesExhaustedLogLevel(ERROR) .onExceptionOccurred(exceptionOccurredProcessor) // then on redelivery exhaustion the transaction is rolledback // the following happens after rollback .log(...) .to(...) </code> We had to make database operation support retries (due to some autonomous transactions), but this is simplier than structuring for camel transacted route. Furthermore, it just happens that transacted route main purpose is the rollback of the message in the jms as well, but we don't want this because we handle errors with DLQs. with_spring_transaction |
apache-camel | I'm trying to transform a simple JSON-file to a POJO in Apache Camel, but I cannot get it to work. Routes.java <code>package org.acme.bindy.ftp;import org.apache.camel.Exchange; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.model.dataformat.BindyType; import org.apache.camel.processor.aggregate.GroupedBodyAggregationStrategy; import org.apache.camel.model.dataformat.JsonLibrary; import org.apache.camel.model.dataformat.JsonDataFormat; import org.apache.camel.Processor; public class Routes extends RouteBuilder { @Override public void configure() throws Exception { from(';file:{{json.temp}}?delay=1000';) .unmarshal().json(JsonLibrary.Jackson, WeatherForecast[].class) .to(';file:{{json.processed}}';); .... .... } } </code> WeatherForecast.java <code>package org.acme.bindy.ftp;import java.util.Objects;import io.quarkus.runtime.annotations.RegisterForReflection; import java.util.HashMap; import java.util.Map;import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonSetter; import com.fasterxml.jackson.annotation.JsonIgnore; public class WeatherForecast { @JsonProperty(';date';) private String date; @JsonProperty(';temperatureC';) private int temperatureC; @JsonProperty(';temperatureF';) private int temperatureF; @JsonProperty(';summary';) private String summary; public String getDate() { return date; } public void setDate(String date) { this.date = date; } public int getTemperatureC() { return temperatureC; } public void setTemperatureC(int temperatureC) { this.temperatureC = temperatureC; } public int getTemperatureF() { return temperatureF; } public void setTemperatureF(int temperatureF) { this.temperatureF = temperatureF; } public String getSummary() { return summary; } public void setSummary(String summary) { this.summary = summary; } } </code> WeatherForecast-json <code>[{';date';:';2022-05-07T13:49:22.0517663+02:00';,';temperatureC';:36,';temperatureF';:96,';summary';:';Mild';},{';date';:';2022-05-08T13:49:22.052558+02:00';,';temperatureC';:21,';temperatureF';:69,';summary';:';Mild';},{';date';:';2022-05-09T13:49:22.0525661+02:00';,';temperatureC';:13,';temperatureF';:55,';summary';:';Hot';},{';date';:';2022-05-10T13:49:22.0525665+02:00';,';temperatureC';:-2,';temperatureF';:29,';summary';:';Warm';},{';date';:';2022-05-11T13:49:22.0525668+02:00';,';temperatureC';:49,';temperatureF';:120,';summary';:';Scorching';}] </code> The error that I'm recieving is: No body available of type: java.io.InputStream but has type: org.acme.bindy.ftp.WeatherForecast[] on: weather.json. Caused by: No type converter available to convert from type: org.acme.bindy.ftp.WeatherForecast[] to the required type: java.io.InputStream. Exchange[]. Caused by: [org.apache.camel.NoTypeConversionAvailableException - No type converter available to convert from type: org.acme.bindy.ftp.WeatherForecast[] to the required type: java.io.InputStream] Any help would be greatly appreciated | The error seems to occur after the (successful) unmarshalling to an array of <code>WeatherForecast</code> classes, when the obtained array of POJOs needs to be written to the filesystem: <code>.unmarshal().json(JsonLibrary.Jackson, WeatherForecast[].class) .to(';file:{{json.processed}}';); </code> It's not surprising that Camel is expecting a converter to turn your body (an array of beans) into an inputstream in order to be able write it on disk <code>...to convert from type: org.acme.bindy.ftp.WeatherForecast[] to the required type: java.io.InputStream </code> |
apache-camel | I'm using Apache Camel with the aws2-s3 module to access an S3 bucket. I'm using endpoint-dsl to program my routes. I can connect to and read from the bucket, but I get Access Denied when trying to upload. I need to enable SSE-S3. I've seen other posts that state that the x-amz-server-side-encryption header needs to be set, but how do I do that? In the documentation for the aws-s3 component, it states: <code>CamelAwsS3ServerSideEncryption</code> Sets the server-side encryption algorithm when encrypting the object using AWS-managed keys. For example use AES256. I can't find any other reference to AWS-managed keys in the documentation unless it's referring to KMS or customer keys. I've tried <code>.setHeader(AWS2S3Constants.SERVER_SIDE_ENCRYPTION, constant(';AES256';))</code> which doesn't seem to actually enable SSE-S3. I've also tried setting the header in these other ways: <code>Map<String,Object>; headers = new HashMap<>;(); headers.put(';x-amz-server-side-encryption';, ';AES256';); ... .process(exchange ->; { exchange.getIn().setHeader(';x-amz-server-side-encryption';, ';AES256';); }) .setHeader(AWS2S3Constants.SERVER_SIDE_ENCRYPTION, constant(';AES256';)) .setHeader(AWS2S3Constants.METADATA, () ->; headers) .setHeader(';CamelAwsS3Headers';, () ->; headers) </code> | This should be resolved through this: https://issues.apache.org/jira/browse/CAMEL-18064 Available in the upcoming release 3.17.0. I fixed it this morning. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.