Created
July 1, 2019 15:15
-
-
Save recursivecodes/4a67fb87443afd515bd4b2334cb1fb7c to your computer and use it in GitHub Desktop.
UserResource.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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