1

I have a DropWizard configuration class that has two properties. At least one must be set. That means, both are @Nullable and I need validation on the whole object.

    public class MessagingStreamConfiguration extends Configuration
    {
        @Nullable
        private URL baseUrl;

        @Nullable
        private LinkedHashMap<String, URL> baseUrls;
    }

This configuration class is a property of the whole application's configuration.

public class ClaConfiguration extends Configuration
{
    @Valid
    @JsonProperty("messagingStream")
    private MessagingStreamConfiguration messagingStreamConfiguration;

I set up a javax.validation for that:

/**
 * Additional validation for non-trivial cases.
 */
private boolean isValid() {
    return (this.getBaseUrl() == null
        && (this.getBaseUrls() == null || this.getBaseUrls().isEmpty()));
}


/**
 * javax.validation way of validating the whole class.
 */
public static class MessagingStreamConfigurationValidator implements ConstraintValidator<MessagingStreamConfigurationValid, MessagingStreamConfiguration>
{
    @Override
    public void initialize(MessagingStreamConfigurationValid constraintAnnotation) {

    }

    @Override
    public boolean isValid(MessagingStreamConfiguration conf, ConstraintValidatorContext context) {
        return conf.isValid();
    }
}

@Constraint(validatedBy = {MessagingStreamConfigurationValidator.class})
@Target({ElementType.TYPE})
@Retention(value = RetentionPolicy.RUNTIME)
public @interface MessagingStreamConfigurationValid
{
    String message() default "Neither baseUrl nor baseUrls is set. Set baseUrls.";
}

But the validation of the object does not happen. Only of it's individual fields.

The only relevant DropWizard tests I found, 2nd also only deals with fields.
The DW documentation doesn't talk about config validation much.

How can I make DropWizard validate the whole object?

Ondra Žižka
  • 43,948
  • 41
  • 217
  • 277

1 Answers1

3

You have two options:

  • annotate the class to be validated (ClaConfiguration) with your custom annotation (MessagingStreamConfigurationValid)
  • in your annotation, target ElementType.FIELD, and annotate your field with your custom annotation instead of @Valid

Please note that you need two more attributes in your annotation to get it to work:

  • Class<?>[] groups() default { };
  • Class<? extends Payload>[] payload() default { };
vin59
  • 148
  • 7