How to create an interceptor for Apache Camel Route in Spring boot application
I have a simple route defined and for this route I want to define an outgoing interceptor so that on any request done, I would invoke an enricher that sets specific header.
from("direct:remoteService")
.routeId("direct-route")
.tracing()
.log(">>> ${body.id}")
.log(">>> ${body.name}")
.process(new Processor() {
@Override
public void process(Exchange exchange) throws Exception {
MyBean bodyIn = (MyBean) exchange.getIn().getBody();
ExampleServices.example(bodyIn);
exchange.getIn().setBody(bodyIn);
}
})
.setHeader(Exchange.HTTP_RESPONSE_CODE, constant(200));
I've tried to define an implementation of AbstractPhaseInterceptor but it is not invoked. What am I doing wrong?
@OutInterceptors
public class HeaderEnricherInterceptor extends AbstractPhaseInterceptor<Message> {
public HeaderEnricherInterceptor() {
super(Phase.POST_PROTOCOL);
}
@Override
public void handleMessage(Message message) {
log.debug("Message interceptor start enrichment...");
}
}
1 answer
-
answered 2022-05-05 06:31
eray_p1
You are using an interceptor used by apache cxf, I don't think there is such a use in camel. can you check out https://camel.apache.org/components/3.16.x/eips/intercept.html
do you know?
how many words do you know
See also questions close to this topic
-
Read each name in Array list to create seperate object for
I have a file that has student names, age, and an id number. I have a student class that holds the everything above for each student object. I stored all the names, id numbers. and age separately in an array list. Now im trying to assign the info to create a student object.
public class Student { private String lName; private int idNumber; private int age; public Student() { lName = ""; idNumber = 0; age = 0; } public Student(String l, int i, int a) { lName = l; idNumber = i; age = a; } public void setName(String last) { lName = last; } public String getName() { return lName; } public void setIdNum(int num) { idNumber = num; } public int getIdNum() { return idNumber; } public void setAge(int a) { age = a; } public int getAge() { return age; } }
My Text File looks something like this: This info is stored in parallel array lists. I don't quite get how to implement this into an object to pass it into my second contractor method.
Josh 2134 19 Smith 5256 21 Rogers 9248 19 Andrew 7742 20
Here's what I've tried;
public static void main(String[] args) { String file = "studentData.txt"; Scanner reader = new Scanner(file); ArrayList<String> lastNames = lNames(file); ArrayList<Integer> idNumbers = idNum(file); ArrayList<Integer> ageList = ages(file); Scanner input = new Scanner(System.in); Student s1 = new Student(); // confused about how to implement this constructor with the textile info for (int i = 0; i<idNumbers.size(); i++) { Student user = new Student(lastNames.get(i), idNumbers.get(i), ageList.get(i)); } //user enters idNumber to display age System.out.println("Enter ID Number"); //exception handling to be added int idNum = input.nextInt(); for (int i = 0; i<idNumbers.size(); i++) { if (idNum == idNumbers.get(i)) { s1.setAge(ageList.get(i)); System.out.println(s1.getAge()); } } }
-
Using EdittextPreference for Goto search
sorry for my poor English. I want to use EditTextPreference in my bottom nav like the pic below, ![screenshot][1]
I have recycleview xml in my project with in many sub cardview layouts(which is scrollable) and I want to create item in the bottom nav which is called "Goto". When the "Goto" item is clicked i want it to pop-up like the screenshot. And when user enters a number(according to the cardviews i.e if the number of cardview is 40 user must enter 1-40) I want to search the cardview by its ID. Thank you and I hope u got it, If u have any questions let me know [1]: https://i.stack.imgur.com/grK8P.jpg
My xml format look like this. As you see in the blow since the cardviews are huge in number it is not cool to scroll all the way down that is why i need Goto item in the bottom nav to search it by its ID when the user click number in the EditTextPreference as u see in the screenshot. i.e The screenshot is not from my app
<LinearLayout> <LinearLayout> <androidx.cardview.widget.CardView> <RealtiveLayout> <Textview/> <RealtiveLayout> </androidx.cardview.widget.CardView> </LinearLayout> <LinearLayout> <androidx.cardview.widget.CardView> <RealtiveLayout> <Textview/> <RealtiveLayout> </androidx.cardview.widget.CardView> </LinearLayout> <LinearLayout> <androidx.cardview.widget.CardView> <RealtiveLayout> <Textview/> <RealtiveLayout> </androidx.cardview.widget.CardView> </LinearLayout> <LinearLayout> <androidx.cardview.widget.CardView> <RealtiveLayout> <Textview/> <RealtiveLayout> </androidx.cardview.widget.CardView> </LinearLayout> .. .. .. .. many more..
-
How to get remaining time of the day in java?
I would like to calculate the time remaining for next day 00:00:00 from the current date time.
For e.g. time difference between 2
022-05-07T05:49:41.883807900Z
and2022-05-08T00:00:00Z
Expected answer:
18:10:19
or 65419 (in seconds).How can I achieve this with efficiently using java 8?
-
best way to add a spring boot web application with JSPs to a docker container?
so i have a spring boot web application, it uses JSPs, and im supposed to put it in a container .
my question is what is the best way ? ive tried to copy the project and then run it there using a wmvn like so : dockerfile:FROM openjdk:8-jdk-alpine ADD . /input-webapp WORKDIR /input-webapp EXPOSE 8080:8080 ENTRYPOINT ./mvnw spring-boot:run
which works, but it takes a long time getting the dependencies and feels messy .
and ive tried to package it into a jar, and then copy the jar only, and run it : dockerfile:
FROM openjdk:8-jdk-alpine ADD target/input-webapp-0.0.1-SNAPSHOT.jar input-webapp-0.0.1-SNAPSHOT.jar EXPOSE 8080:8080 ENTRYPOINT ["java","-jar","input-webapp-0.0.1-SNAPSHOT.jar"]
but this way it cant see the JSPs, or at least i think this is the problem, as i get a 404.
so is there a better way ? can i copy the jsps plus the jar to make it work? thanks
-
build spring boot (mvnw) with docker can not use cache
Spring Boot Docker Experimental Features Docker 18.06 comes with some “experimental” features, including a way to cache build dependencies. To switch them on, you need a flag in the daemon (dockerd) and an environment variable when you run the client. With the experimental features, you get different output on the console, but you can see that a Maven build now only takes a few seconds instead of minutes, provided the cache is warm.
my dockerfile can not use cache.
dockerfile
# syntax=docker/dockerfile:experimental FROM openjdk:8-jdk-alpine as build WORKDIR /workspace/app COPY mvnw . COPY .mvn .mvn COPY pom.xml . COPY src src RUN --mount=type=cache,target=/root/.m2 ./mvnw install -DskipTests -s .mvn/wrapper/settings.xml RUN mkdir -p target/extracted && java -Djarmode=layertools -jar target/*.jar extract --destination target/extracted FROM openjdk:8-jre-alpine ENV TZ Asia/Shanghai RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone RUN addgroup -S spring && adduser -S spring -G spring USER spring:spring ARG EXTRACTED=/workspace/app/target/extracted ARG JAVA_OPTS="-Xmx100m -Xms100m" COPY --from=build ${EXTRACTED}/dependencies/ ./ COPY --from=build ${EXTRACTED}/spring-boot-loader/ ./ COPY --from=build ${EXTRACTED}/snapshot-dependencies/ ./ COPY --from=build ${EXTRACTED}/application/ ./ ENTRYPOINT ["sh", "-c","java ${JAVA_OPTS} org.springframework.boot.loader.JarLauncher"]
run shell
DOCKER_BUILDKIT=1 docker build -t org/spring-boot .
every time use many minutes
-
How can I delete a row by its SKU instead of its ID?
I try to delete the row using the sku of the product. I'm using spring boot and angular. I got an error when I added the sku on my button like this one
(click)="onDeleteProductBySku(deleteClick?.sku)"
it said that theProperty 'sku' does not exist on type '(product: Product) => void'.
. On my command prompt, I got this error. How can I solve this problem?Error: product/product.component.html:50:109 - error TS2339: Property 'sku' does not exist on type '(product: Product) => void'. 50 <button class="btn btn-outline-danger btn-sm me-2" (click)="onDeleteProductBySku(deleteClick?.sku)">Delete</button> product/product.component.ts:12:16 12 templateUrl: './product.component.html', ~~~~~~~~~~~~~~~~~~~~~~~~~~ Error occurs in the template of component ProductComponent.
ProductsController.java --> This is working on the postman.
//Delete a product record using sku //http://localhost:8080/products/deletebysku?sku=12345678 @DeleteMapping("/products/deletebysku") @ResponseBody private void deleteProductBySku(@RequestParam String sku){ productsService.deleteProductBySku(sku); }
product.component.ts
public deleteProduct!: Product; public onDeleteProductBySku(sku: string): void { this.productServive.deleteProductBySku(sku).subscribe( (response: void) => { this.messageShow(); console.log(response); this.getAllProduct(); }, (error: HttpErrorResponse) => { this.errorMessage(error.message); } ); } public deleteClick(product: Product) { this.deleteProduct = product; console.log("delete by sku"); }
product.service.ts
public deleteProductBySku(sku: string): Observable<void> { return this.http.delete<void>(`${this.apiServerUrl}/products/deletebysku?sku=${sku}`); }
product.component.html
<button class="btn btn-outline-danger btn-sm me-2" (click)="onDeleteProductBySku(deleteClick?.sku)">Delete</button>
-
Make response part of body instead of header in SOAP response
I have requirements where I have to add response details in Body tag instead of Header. For now details are added in Header tag of soap response.
@XmlType public class CheckBalanceResponse { private String checkBalanceResult; @XmlElement(name="CheckBalanceResult") public String getCheckBalanceResult() { return checkBalanceResult; } public void setCheckBalanceResult(String checkBalanceResult) { this.checkBalanceResult = checkBalanceResult; } }
Generated response is below:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Header> <CheckBalanceResponse xmlns="http://charginggw.org/"> <CheckBalanceResult>Incorrect PIN</CheckBalanceResult> </CheckBalanceResponse> </soap:Header> <soap:Body/> </soap:Envelope>
I want CheckBalanceResponse tag to be in Body instead of Header. Please suggest what should be done?
-
WSO2 EI get attachement filename in SOAP request
I need to get the filename of the attachment given in a SOAP request. The SOAP request looks like this :
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:type="http://some.type/types"> <soap:Header/> <soap:Body> <type:RequestName> <type:Data>...</type:Data> <!--Optional:--> <type:myAttachement>cid:AAA</type:myAttachement> </type:RequestName> </soap:Body> </soap:Envelope>
When MTOM is enabled in SOAP UI, I can see the following in the log Wire :
DEBUG {wire} - HTTP-Listener I/O dispatcher-2 >> " <type:myAttachement><inc:Include href="cid:AAA" xmlns:inc="http://www.w3.org/2004/08/xop/include"/></type:myAttachement> DEBUG {wire} - HTTP-Listener I/O dispatcher-2 >> " </type:RequestName> DEBUG {wire} - HTTP-Listener I/O dispatcher-2 >> " </soap:Body>[\n]" DEBUG {wire} - HTTP-Listener I/O dispatcher-2 >> "</soap:Envelope>" DEBUG {wire} - HTTP-Listener I/O dispatcher-2 >> "[\r][\n]" DEBUG {wire} - HTTP-Listener I/O dispatcher-2 >> "------=_Part_2_1904033954.1651826827378[\r][\n]" DEBUG {wire} - HTTP-Listener I/O dispatcher-2 >> "Content-Type: text/plain; charset=us-ascii; name=test.txt[\r][\n]" DEBUG {wire} - HTTP-Listener I/O dispatcher-2 >> "Content-Transfer-Encoding: 7bit[\r][\n]" DEBUG {wire} - HTTP-Listener I/O dispatcher-2 >> "Content-ID: <AAA>[\r][\n]" DEBUG {wire} - HTTP-Listener I/O dispatcher-2 >> "Content-Disposition: attachment; name="test.txt"; filename="test.txt"[\r][\n]" DEBUG {wire} - HTTP-Listener I/O dispatcher-2 >> "[\r][\n]" DEBUG {wire} - HTTP-Listener I/O dispatcher-2 >> "AAABBBCCCDDD[\r][\n]" DEBUG {wire} - HTTP-Listener I/O dispatcher-2 >> "------=_Part_2_1904033954.1651826827378--[\r][\n]"
I can see the filename, Content-Type.. When I Debug the request in the sequence, the file content is inline the SOAP Payload :
<type:myAttachment>QUFBQkJCQ0NDRERE</type:myAttachment> </type:RequestName> </soap:Body></soap:Envelope>
How can I get in script mediator the attachment filename or at least the Content-Type of the attachment ?
-
Branded Fare - Amadeus SOAP/XML
Amadeus is offering to search branded fares from hundreds of top carriers with Branded Fares Upsell, now available in the Self-Service and Enterprise catalogs. Built for integration in your REST/JSON booking engine.
Is there anything similar to it but with SOAP/XML engine?
-
Can you listen for SpringCamelContext status?
Using EventNotifierSupport, I can listen for CamelContextStartedEvent. However, I need to add one more root to the context, after all the other routes have already been initialized. Currently, the event occurs after camelcontext have been initialized, but after that we have hundreds of SpringCamelContext routes added, and as I understand, there is no "SpringCamelContextStartedEvent", so I have no idea of how to add route after all other routes are already initialized. I suspect that there is fundamental error in my logic, please correct me if I am wrong somewhere.
@Override public void notify(EventObject event) throws Exception { if (event instanceof CamelContextStartedEvent) { log.info("CamelContextStartedEvent for {}", event.getSource()); startWarmupThread(); } }
-
Clustered Apache Camel to run Jira routes
Background: We have written a Spring Boot Apache Camel based ingestion service which runs Camel routes that ingest data from shared directory (Excel files) and Jira (API calls). Jira based routes are fired using Scheduler at pre-defined frequency. User configures multiple integrations in the system and each integration maps to one Camel route. In production, there shall be 10 instances of the ingestion service running.
Problem Statement: For each integration using Jira, only one ingestion instance should fire a route, process it and rest should not if there is already a running instance for that specific route.
Question: How to make sure only one ingestion instance processes a route and rest ignore it (i.e. may start but stop after doing nothing)?
Analysis: It seems Camel Cluster component can be used but not sure if it can be used in conjunction with scheduler component. In addition, since cluster component can rely on standalone components such as cache, file etc., preferred solution would be to use something that does not require any new components in the architecture. Also it may be possible to use a custom solution but preference is to use an out-of-box solution.
-
How to send response back from server to client using Apache camel netty , spring boot
I have two modules as client and server. I am currently sending echo messages from client to server using netty server routes from(netty:tcp://0.0.0.0:21005). Now the message is getting send to server but how to send response back from server to client. Is it possible using same route. Any help much appreciated. Thanks in advance.
-
How to use WS-Addressing and get messageId
I'm stuck on WS-Addressing with Apache CXF. I tried everything I found on the Web but without good results. There are two applications, a server and a client, that communicate through WS-Addressing. What I want to do is to obtain the "messageId" field with the server, so I can output it on logs.
Can you help me, please? I tried two different solutions but without results
- Using EndpointImpl
public static void main(String[] args) { ChangeStudentDetailsImpl implementor = new ChangeStudentDetailsImpl(); EndpointImpl ep = (EndpointImpl) Endpoint.create(implementor); ep.getFeatures().add(new WSAddressingFeature()); ep.publish("http://localhost:8087/MidtermServer/Implementor"); }
- Using Apache CXF
I really don't understand how to get params passed using WS Addressing Feature, using a client application or SoapUI
Any help is appreciated
-
java.lang.ClassNotFoundException: org.apache.cxf.jaxrs.client.JAXRSClientFactoryBean And NoClassDefFoundError org/apache/cxf/jaxrs/client/WebClient
Hi I have upgraded the spring version to 5.2.20.RELEASE . And upgraded the cxf dependencies to latest versions as older versions were not compatible with the this new spring version. But while starting tomcat im getting the below exception.
Caused by: java.lang.NoClassDefFoundError: org/apache/cxf/jaxrs/client/JAXRSClientFactoryBean at java.lang.Class.getDeclaredMethods0(Native Method) at java.lang.Class.privateGetDeclaredMethods(Class.java:2701) at java.lang.Class.getDeclaredMethods(Class.java:1975) at org.springframework.util.ReflectionUtils.getDeclaredMethods(ReflectionUtils.java:463) ... 64 more Caused by: java.lang.ClassNotFoundException: org.apache.cxf.jaxrs.client.JAXRSClientFactoryBean at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1714) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1559) ... 68 more
I have following cxf dependencies
<cxf.version>3.5.2</cxf.version> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-ws-policy</artifactId> <version>${cxf.version}</version> <exclusions> <exclusion> <groupId>org.springframework</groupId> <artifactId>*</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-frontend-jaxrs</artifactId> <version>${cxf.version}</version> <exclusions> <exclusion> <groupId>org.springframework</groupId> <artifactId>*</artifactId> </exclusion> </exclusions> </dependency> <dependency> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-api</artifactId> <version>2.7.18</version> <exclusions> <exclusion> <groupId>javax.ws.rs</groupId> <artifactId>javax.ws.rs-api</artifactId> </exclusion> <exclusion> <groupId>org.springframework</groupId> <artifactId>*</artifactId> </exclusion> </exclusions> </dependency>