Skip to content

Instantly share code, notes, and snippets.

@recursivecodes
Created July 1, 2019 15:15
Show Gist options
  • Save recursivecodes/4a67fb87443afd515bd4b2334cb1fb7c to your computer and use it in GitHub Desktop.
Save recursivecodes/4a67fb87443afd515bd4b2334cb1fb7c to your computer and use it in GitHub Desktop.
UserResource.java
@Path("/save")
@POST
@Produces(MediaType.APPLICATION_JSON)
public Response saveUser(User user) {
    Set<ConstraintViolation<User>> violations = userRepository.validate(user);
    if( violations.size() == 0 ) {
        userRepository.save(user);
        return Response.created(
                uriInfo.getBaseUriBuilder()
                        .path("/user/{id}")
                        .build(user.getId())
        ).build();
    }
    else {
        List<HashMap<String, String>> errors = new ArrayList<>();
        violations.stream()
                .forEach( (violation) -> {
                            Object invalidValue = violation.getInvalidValue();
                            HashMap<String, String> errorMap = new HashMap<>();
                            errorMap.put("field", violation.getPropertyPath().toString());
                            errorMap.put("message", violation.getMessage());
                            errorMap.put("currentValue", invalidValue == null ? null : invalidValue.toString());
                            errors.add(errorMap);
                        }
                );
        return Response.status(422)
                .entity(Map.of( "validationErrors", errors ))
                .build();
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment