0

I have a number of Integers that I validate, but it is written as a series of if statements which are failing in SonarQube report. As you can see from below I want to check that if (for example) channel 0 is not null and also if the integer is not present in my repository then map to some error message I have defined. I have tried removing the != null check below and have implemented the @NullOrNotBlank annotation defined in the top rated answer, and assigned it to my field, but this only works for String I believe: Java annotation for Null but neither Empty nor Blank

When I include any other field which is not the channel in a test message, I get a NullpointerException error for the channel field.

How can I update the custom annotation to include integers in validation? Or is there a more suitable annotation I should be using? Or perhaps there is a better way to write the if statement?

Example - "channel": 0,

if (updateCaseDataVO.getChannel() != null
                && !(channelRepository.findById(updateCaseDataVO.getChannel().getChannel()).isPresent())) {
            map.put(ErrorConstants.CHANNEL, ErrorConstants.CHANNEL_ERROR_MESSAGE);
        }

 @ConstraintComposition(CompositionType.OR)
    @Null
    @NotBlank
    @ReportAsSingleViolation
    @Target({ ElementType.FIELD })
    @Retention(RetentionPolicy.RUNTIME)
    @Constraint(validatedBy = {})
    public @interface NullOrNotBlank {
String message() default "{org.hibernate.validator.constraints.NullOrNotBlank.message}";

Class<?>[] groups() default {};

Class<? extends Payload>[] payload() default {};
}
Coder
  • 197
  • 1
  • 17

1 Answers1

0

You could create a custom validator which uses the repository (or any other bean). Here is a simple demo I've made as answer to a similar question.

Alternatively (if the use of a third-party dependency is acceptable) I would recommend Jakub Jirutka's Bean Validator utilizing Spring Expression Language (SpEL) which allows things like:

public class Sample {

    @SpELAssert("@myService.calculate(#this) > 42")
    private int value;
}
MartinBG
  • 1,500
  • 13
  • 22