mskager
mskager

Reputation: 51

Dropwizard Validate @FormParam

How do I validate that @FormParams, for a POST request, are not empty? We are using Dropwizard version 0.9.3.

@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response addCard(@FormParam("title") @NotEmpty String title,
                        @FormParam("latitude") @NotNull Double latitude,
                        @FormParam("longitude") @NotNull Double longitude,
                        @FormParam("public") @NotNull Boolean publicCard,
                        @FormParam("user_id") @NotNull Integer userId) {

Sending a POST request without the title param yields this server error:

!org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException: MessageBodyWriter not found for media type=text/html, type=class io.dropwizard.jersey.validation.ValidationErrorMessage, genericType=class io.dropwizard.jersey.validation.ValidationErrorMessage.

And the client receives:

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <title>Error 500 Request failed.</title>
</head>
<body>
    <h2>HTTP ERROR 500</h2>
    <p>Problem accessing /cards. Reason:

        <pre>    Request failed.</pre>
    </p>
    <hr>
        <i>
            <small>Powered by Jetty://</small>
        </i>
        <hr/>
    </body>
</html>

Previously I've used @NotEmpty for @QueryParam and that worked fine. I want the client to receive something like (400 Bad request):

{
"errors": [
    "query param title may not be null",
]
}

I've tried with using NonEmptyStringParam introduced in dropwizard 0.9.0 but that didn't work. Any suggestions?

EDIT:

The documentation states the following: "If you have an Optional field or parameter that needs validation, add the @UnwrapValidatedValue annotation on it." and "If you want q to evaluate to Optional.absent() in this situation, change the type to NonEmptyStringParam". I've tried this but the parameter is not beeing evaluated.

Upvotes: 1

Views: 1049

Answers (1)

gaganbm
gaganbm

Reputation: 2843

You want the response to come in json form. You need to add produces on top of your method.

@Produces(MediaType.APPLICATION_JSON) 

This should resolve your problem.

Upvotes: 2

Related Questions