在 Apache Camel 中验证请求标头时如何添加自定义响应

问题描述 投票:0回答:1

下午好

我是 apache Camel 的新手,我正在使用 apache Camel 和 quarkus 来处理微服务,我目前正在尽可能自动化地实现输入字段的验证,在这种情况下,我想验证标头,并且想返回 400代码和自定义响应,但我设法做到了。

除了验证输入参数的行之外,我还在逻辑的 DSL 定义中实现了行

clientRequestValidation(true)

param().name("x-correlator").type(RestParamType.header).required(true).endParam()

通过这两行,我得到以下响应:

我想要这样的答案:

我的 RestRoure 代码如下:

@ApplicationScoped
public class RestRoute extends RouteBuilder {
    @ConfigProperty(name = "client.url.userProfile")
    String urlUserProfile;

    @ConfigProperty(name = "client.utl.getActiveSessionByIp")
    String urlGetActivateSessionByIp;

    @ConfigProperty(name = "path.openapi")
    String pathOpenapi;

    @ConfigProperty(name = "descripcion.servicio")
    String descriptionService;

    private final IGetCurrentDateTime getCurrentDateTime;

    private ConfigureSsl configureSsl;

    private static final String SALIDA_BSS_EXCEPTION = "Salida Microservicio IdentifyOrigin ${body}";
    private static final String MSG_EXCEPTION = "Descripcion de la Exception: ${exception.message}";

    private static final String DATE_LOG = "[${bean:BeanDate.getCurrentDateTime()}] ";

    public RestRoute() {
        getCurrentDateTime = new GetCurrentDateTime();
        TimeZone.setDefault(TimeZone.getTimeZone("GMT-4"));
        configureSsl= new ConfigureSsl();
    }
    @Override
    public void configure() throws Exception {

        BeanDate beanDate= new BeanDate();
        getContext().getRegistry().bind("BeanDate", beanDate);

        restConfiguration().bindingMode(RestBindingMode.json).dataFormatProperty("json.in.disableFeatures","FAIL_ON_UNKNOWN_PROPERTIES")
                .clientRequestValidation(true)
                .apiContextPath(pathOpenapi)
                .apiProperty("api.title","IdentifyOrigin")
                .apiProperty("api.description",descriptionService)
                .apiProperty("api-version","1.0.0")
                .apiProperty("cors","true");
        rest("/api/")
                .produces("application/json")
                .consumes("application/json")
                .post("/identifyOrigin/v1/info")
                .type(Request.class)
                .param().name("x-correlator").type(RestParamType.header).required(true).endParam()
                .outType(ResponseSuccess.class)
                .param().name("Response").type(RestParamType.body).description("Parametros de Salidas")
                .required(true)
                .endParam().to("direct:pipeline");

                from("direct:pipeline")
                        .doTry()
                            .to("bean-validator:validateRequest")
                            .log("["+"${bean:BeanDate.getCurrentDateTime()}"+"] "+ "Datos de Entrada del MS: ${body}")
                            .process(new GetActivateSessionByIpReqProcessor())
                            .log("\n[${bean:BeanDate.getCurrentDateTime()}] "+"Entrada Microservicio GetActivateSessionByIp: ${exchangeProperty[getActivateSessionByIpRequest]}")
                            .to(configureSsl.setupSSLContext(getCamelContext(), urlGetActivateSessionByIp))
                            .choice()
                                .when(header(Exchange.HTTP_RESPONSE_CODE).isEqualTo(200))
                                    .process(new GetActivateSessionByIpResProcessor())
                                    .log("["+"${bean:BeanDate.getCurrentDateTime()}"+"] "+ "Salida MS GetActivateSessionByIp: ${body}")
                                    .log("["+"${bean:BeanDate.getCurrentDateTime()}"+"] "+ "PhoneNumberByIp obtenido desde MS GetActivateSessionByIp: ${exchangeProperty[phoneNumberByIp]}")
                                    .process(new UserProfileReqProcessor())
                                    .to(configureSsl.setupSSLContext(getCamelContext(), urlUserProfile))
                                    .log("["+"${bean:BeanDate.getCurrentDateTime()}"+"] "+ "Datos de Salida del MS UserProfile: ${body}")
                            .otherwise()
                                .process(new ApiResponseFaultProcessor())
                            .end()
                            .process(new UserProfileReqProcessor())
                            .to(configureSsl.setupSSLContext(getCamelContext(), urlUserProfile))
                            .log("["+"${bean:BeanDate.getCurrentDateTime()}"+"] "+ "Datos de Salida del MS UserProfile: ${body}")
                            .choice()
                                .when(header(Exchange.HTTP_RESPONSE_CODE).isEqualTo(200))
                                .process(new UserProfileResProcessor())
                                .log("["+"${bean:BeanDate.getCurrentDateTime()}"+"] "+ "UserId obtenido desde UserProfile: ${exchangeProperty[userId]}")
                                .process(new IdentifyOriginResProcessor())
                                .log(DATE_LOG+"Salida MS IdentifyOrigin: ${exchangeProperty[identifyOriginResponse]}")
                            .otherwise()
                                .process(new ApiResponseFaultProcessor())
                            .end()
                        .endDoTry()
                        .doCatch(BeanValidationException.class)
                            .process(new InvalidFormatExcepctionProcessor())
                            .log(DATE_LOG+MSG_EXCEPTION)
                            .log(DATE_LOG+SALIDA_BSS_EXCEPTION)
                        .doCatch(NotFoundDataException.class)
                            .process(new NotFoundDataExceptionProcessor())
                            .log(DATE_LOG+MSG_EXCEPTION)
                            .log(DATE_LOG+SALIDA_BSS_EXCEPTION)
                        .doCatch(HttpHostConnectException.class)
                            .process(new HttpHostConnectExceptionProcessor())
                            .log(DATE_LOG+MSG_EXCEPTION)
                            .log(DATE_LOG+SALIDA_BSS_EXCEPTION)
                        .doCatch(Exception.class)
                            .process(new IdentifyOriginExceptionProcessor())
                            .log(DATE_LOG+MSG_EXCEPTION)
                            .log(DATE_LOG+SALIDA_BSS_EXCEPTION);
    }
}

我该怎么做?

java validation header apache-camel quarkus
1个回答
0
投票
from("direct:pipeline")
    .process(exchange -> {
        String xCorrelator = exchange.getIn().getHeader("x-correlator", String.class);
        // Implement your validation logic here
        if (xCorrelator == null || xCorrelator.isEmpty()) {
            throw new ValidationException("x-correlator header is missing or invalid");
        }
    })
    // Rest of your route...

.doCatch(ValidationException.class)
    .process(exchange -> {
        exchange.getIn().setHeader(Exchange.HTTP_RESPONSE_CODE, 400);
        exchange.getIn().setBody("Invalid header information provided");
    })
    .log(DATE_LOG+MSG_EXCEPTION)
    .log(DATE_LOG+SALIDA_BSS_EXCEPTION)
// Continue with other exception handling...

// Custom exception handling for validation errors
    onException(PredicateValidationException.class)
        .handled(true) // Stop the exception from propagating
        .setHeader(Exchange.HTTP_RESPONSE_CODE, constant(400)) // Set HTTP status 400
        .setBody().constant("Invalid 'x-correlator' header value"); // Custom error message

© www.soinside.com 2019 - 2024. All rights reserved.