Search code examples
javaapache-camel

Json validation date time camel


I am currently having an issue with json validation of date time fields in camel. I am using the inbuilt json validator of camel, where it takes in parameter json schema as reference for validation.
My issue is with date time fields, if the date time field in the json request doesn't have the time zone it fails.
I am trying to override the format or skip date time validation it fails unsuccessfully.
I have :

.choice()
    .when(isJsonValidationEnabled)
        .to(jsonValidator("classpath:of_json_schema.json"))
    .endChoice()
.end()

Above is the json

"date_time_field": {
    "description": "date_time_field",
    "type": "string",
    "format": "date-time"
}

When having something like this in the schema :
any request having this :

"date_time_field": "2022-10-05T07:03:19",

but having this :

"date_time_field": "2022-10-05T07:03:19Z",

is a success.

I want a way to either override date time fields validation to accept things like this : "2023-10-05T07:03:19", or skip them.

I tried json schema instantiation and a custom format, and passed it as paramer in the json validator endpoint with no luck.


Solution

  • The thing to do was to :

    1- Implement Format

    public class CustomDateTimeFormat implements Format {
    
     //implementation
    }
    

    2- Create Json schema and add to it the format

        public class CustomJsonUriSchemaLoader implements JsonUriSchemaLoader {
           //implementation 
                
            
        public JsonSchema createSchema(CamelContext camelContext, String schemaUri) throws Exception {
           //implementation
    JsonMetaSchema overrideDateTimeValidator = new JsonMetaSchema
                .Builder(jsonSchemaVersion.getInstance().getUri())
                .idKeyword("$id")
                .addKeywords(ValidatorTypeCode.getNonFormatKeywords(version))
                .addFormats(Collections.singletonList(new CustomDateTimeFormat()))
                .build();
           }
        }
    

    3- Load the schema in the json validator endpoint.

    .choice()
        .when(this::isJsonValidationEnabled)
            .to(jsonValidator(CLASSPATH_SCHEMA_JSON)
                .advanced().uriSchemaLoader(new CustomJsonUriSchemaLoader()))
        .endChoice()
     .end()
    

    Then date time validation will be overridden.