I am building an application using Google App Engine, Jersey, Objectify, and Gson (and some other tiny library).
I would like to do validation in the resource using the @Valid annotation. However, no actual validation seems to be performed. In particular, when posting an Entry
with payee
set to "123"
to both /entries
and /entries/nocheck
, the app does not raise any exception and the entity is being saved in the datastore.
Here is a snippet of the entity:
@Entity
public class Entry {
@Id
private Long id;
private LocalDate date;
@com.sappenin.objectify.annotation.Money
private Money amount;
@NotNull @Pattern(regexp = "[a-zA-Z][a-zA-Z0-9]*") @Length(min = 5)
private String payee;
private String description;
private String note;
//...
}
Here is a snippet of the resource:
@Path("/entries")
@Produces(MediaType.APPLICATION_JSON)
public class TestApi {
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response create(@Valid Entry entry) {
OfyService.ofy().save().entities(entry).now();
return Response.ok(entry).build();
}
@POST
@Path("/nocheck")
@Consumes(MediaType.APPLICATION_JSON)
public Response createNoCheck(Entry entry) {
OfyService.ofy().save().entities(entry).now();
return Response.ok(entry).build();
}
}
Here is the application:
public class MyApplication extends ResourceConfig {
public MyApplication() {
packages(
"it.newfammulfin.model",
"it.newfammulfin.api",
"it.newfammulfin.api.util");
}
}
Note that the pom.xml includes this dependency:
<dependency>
<groupId>org.glassfish.jersey.ext</groupId>
<artifactId>jersey-bean-validation</artifactId>
<version>2.22.1</version>
</dependency>
which should cause, due to the auto-discovery feature, the validation to be enabled without further configuration.
What am I missing?
Update
I added a method in the resource which explicitly validates the entity:
@POST
@Path("validate")
@Consumes(MediaType.APPLICATION_JSON)
public Response testValidate(@Valid Entry entry) {
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
System.out.println("validator is "+validator.getClass().getName());
System.out.println(validator.validate(entry));
return Response.ok(entry).build();
}
The validation through the invocation of validate()
works. Yet, the validation before the actual invocation of testValidate()
does not.
As an aside, I had to use the Apache BVal implementation of the JSR303 Bean Validation, because of some issues between Hibernate Validator and Google App Engine.