skip to Main Content

Through a Rest API endpoint, I accept JSON and using a Kafka Producer, I publish the JSON to a topic. The JSON will have this format:

{
  "id": "uniqueIdentifier",
  "name": "PersonName",
  "age": PersonAge
}

and the send message method in my Kafka Producer looks like this:

public void sendMessage(Person p){

        LOGGER.info(String.format("Message sent -> %s", p.toString()));

        Message<Person> message = MessageBuilder
                .withPayload(p)
                .setHeader(KafkaHeaders.TOPIC, "jsonTopic")
                .build();

        kafkaTemplate.send(message);

    }

I need to check if the JSON has all the fields non-empty and if the age > 0.
How would I need to implement the verification before sending the message?

2

Answers


  1. JSON Schema is the best for this use case. There are libraries in all languages to validate an input JSON against JSON-Schema. E.g. Java, Javascript

    The schema for your requirement should look like the following:

    {
      "$schema": "http://json-schema.org/draft-07/schema#",
      "type": "object",
      "properties": {
        "id": {
          "type": "string",
          "minLength": 1
        },
        "name": {
          "type": "string",
          "minLength": 1
        },
        "age": {
          "type": "integer",
          "minimum": 1
        }
      },
      "required": ["id", "name", "age"],
      "additionalProperties": false
    }
    
    

    Here, additionalProperties ensures that you do not allow anything else apart from the declared properties.

    These validation libraries give very detailed validation errors that make the error actionable for the sender/caller:

    {
       "errors" : {
          "required" : "the field 'age' should be have a minimum value as 1"
        }
    }
    
    Login or Signup to reply.
    • For the Person POJO I would suggest the member variables to have @NotNull – to ensure the value for each member variable is provided.

    • Use @Min(1) to have a value more than 0 for age.

    • When declaring the method do as public void sendMessage(@Valid Person p) to ensure validation is done on invoking the method.

    On error handling do the following:

    • Create an exception class like below:
    public class BadRequestException extends RuntimeException {
        public BadRequestException(String message) {
            super(message);
        }
    }
    

    Above can be thrown incase any condition above is thrown. But it needs to be caught using an advice as below:

    @ControllerAdvice
    public class MyAdvice {
    @ExceptionHandler(HttpMessageNotReadableException.class)
        @ResponseStatus(HttpStatus.BAD_REQUEST)
        @ResponseBody
        public ResponseEntity<String> getHttpMessageNotReadableExceptionException(HttpMessageNotReadableException exception) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(exception.getMessage());
        }
    }
    

    Above will give you appropriate message for the malformed payload.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search