#apache-camel #dsl #spring-camel
#apache-camel #dsl #spring-верблюд
Вопрос:
У меня есть сценарий, в котором мне нужно прочитать файл из местоположения с определенным интервалом, извлечь имя файла и путь к файлу, нажать 2 службы rest, которые являются вызовом Get amp; Post, используя эти входные данные, и поместить файл в соответствующее место. Я управлял псевдокодом следующим образом.
Хотел узнать, есть ли лучший способ добиться этого с помощью Camel. Ценю вашу помощь!
Поток —
- Извлеките имя файла
- Нажмите конечную точку Get (‘getAPIDetails’), используя это имя файла в качестве входных данных, чтобы проверить, существует ли это имя файла в этом реестре.
- Если ответ успешен (код состояния 200)
- Вызов конечной точки Post (‘registerFile’) с именем файла и путем к файлу в качестве RequestBody
- Переместите файл в C:/output папка (перемещение файла по-прежнему выполняется в приведенном ниже коде).
- Если файл не найден (код состояния 404)
- Переместите файл в C:/error папка.
- Если ответ успешен (код состояния 200)
Ниже приведен POJO ‘FileDetails’, состоящий из fileName amp; filePath, который будет использоваться для передачи в качестве RequestBody для вызова службы post.
@Override
public void configure() throws Exception {
restConfiguration().component("servlet").port("8080")).host("localhost")
.bindingMode(RestBindingMode.json);
from("file:C://input?noop=trueamp;scheduler=quartz2amp;scheduler.cron=0 0/1 * 1/1 * ? *")
.process(new Processor() {
public void process(Exchange msg) {
String fileName = msg.getIn().getHeader("CamelFileName").toString();
System.out.println("CamelFileName: " fileName);
FileDetails fileDetails = FileDetails.builder().build();
fileDetails.setFileName(fileName);
fileDetails.setFilePath(exchange.getIn().getBody());
}
})
// Check if this file exists in the registry.
// Question: Will the 'fileName' in URL below be picked from process() method?
.to("rest:get:getAPIDetails/fileName")
.choice()
// If the API returns true, call the post endpoint with fileName amp; filePath as input params
.when(header(Exchange.HTTP_RESPONSE_CODE).isEqualTo(constant(200)))
// Question: Will 'fileDetails' in URL below be passed as a requestbody with desired values set in process() method?
// TODO: Move the file to C:/output location after Post call
.to("rest:post:registerFile?type=fileDetails")
.otherwise()
.to("file:C://error");
}
Ответ №1:
Удалось разрешить этот вариант использования с помощью приведенного ниже подхода. Закрытие цикла. Спасибо!
PS: В этой реализации есть еще кое-что. Просто хотел изложить подход.
@Override
public void configure() throws Exception {
// Actively listen to the inbound folder for an incoming file
from("file:C://input?noop=trueamp;scheduler=quartz2amp;scheduler.cron=0 0/1 * 1/1 * ? *"")
.doTry()
.process(new Processor() {
public void process(Exchange exchange) throws Exception {
exchange.getIn().setHeader("fileName",
exchange.getIn().getHeader("CamelFileName").toString());
}
})
// Call the Get endpoint with fileName as input parameter
.setHeader(Exchange.HTTP_METHOD, simple("GET"))
.log("Consuming the GET service")
.toD("http://localhost:8090/getAPIDetails?fileName=${header.fileName}")
.choice()
// if the API returns true, move the file to the processing folder
.when(header(Exchange.HTTP_RESPONSE_CODE).isEqualTo(constant(200)))
.to("file:C:/output")
.endChoice()
// If the API's response code is other than 200, move the file to error folder
.otherwise()
.log("Moving the file to error folder")
.to("file:C:/error")
.endDoTry()
.doCatch(IOException.class)
.log("Exception handled")
.end();
// Listen to the processing folder for file arrival after it gets moved in the above step
from("file:C:/output")
.doTry()
.process(new FileDetailsProcessor())
.marshal(jsonDataFormat)
.setHeader(Exchange.HTTP_METHOD, simple("POST"))
.setHeader(Exchange.CONTENT_TYPE, constant("application/json"))
.log("Consuming the POST service")
// Call the Rest endpoint with fileName amp; filePath as RequestBody which is set in the FileDetailsProcessor class
.to("http://localhost:8090/registerFile")
.process(new MyProcessor())
.endDoTry()
.doCatch(Exception.class)
.log("Exception handled")
.end();
}