1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
| /*
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.*;
import javax.ejb.LocalBean;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.inject.Any;
import javax.inject.Inject;
import javax.persistence.NoResultException;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import javax.validation.Validator;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.http.HttpStatus;
import com.fluxon.iflux.ithink.data.UserRepository;
import com.fluxon.iflux.ithink.model.User;
import com.fluxon.iflux.ithink.service.UserRegistration;
/**
* JAX-RS Example
* <p/>
* This class produces a RESTful service to read/write the contents of the users table.
*/
@Path("/users")
@RequestScoped
public class UserResourceRESTService {
@Inject
private Logger log;
@Inject
private Validator validator;
@Inject
private UserRepository repository;
@Inject
UserRegistration registration;
@GET
@Path("/test")
@Produces(MediaType.TEXT_PLAIN)
public Response helloWorld() {
return Response.status(HttpStatus.SC_OK).entity("Hello World").build();
}
@GET
@Path("/listAllUsers")
@Produces(MediaType.APPLICATION_JSON)
public List<User> listAllUsers() {
return repository.findAllOrderedByName();
}
@GET
@Path("/{id:[0-9][0-9]*}")
@Produces(MediaType.APPLICATION_JSON)
public User lookupUserById(@PathParam("id") long id) {
User user = repository.findById(id);
if (user == null) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
return user;
}
/**
* Creates a new user from the values provided. Performs validation, and will return a JAX-RS response with either 200 ok,
* or with a map of fields, and related errors.
*/
@POST
@Path("/create")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response createUser(User user) {
Response.ResponseBuilder builder = null;
try {
// Validates user using bean validation
validateUser(user);
registration.register(user);
// Create an "ok" response
builder = Response.ok();
} catch (ConstraintViolationException ce) {
// Handle bean validation issues
builder = createViolationResponse(ce.getConstraintViolations());
} catch (ValidationException e) {
// Handle the unique constrain violation
Map<String, String> responseObj = new HashMap<>();
responseObj.put("email", "Email taken");
builder = Response.status(Response.Status.CONFLICT).entity(responseObj);
} catch (Exception e) {
// Handle generic exceptions
Map<String, String> responseObj = new HashMap<>();
responseObj.put("error", e.getMessage());
builder = Response.status(Response.Status.BAD_REQUEST).entity(responseObj);
}
return builder.build();
}
/**
* <p>
* Validates the given User variable and throws validation exceptions based on the type of error. If the error is standard
* bean validation errors then it will throw a ConstraintValidationException with the set of the constraints violated.
* </p>
* <p>
* If the error is caused because an existing user with the same email is registered it throws a regular validation
* exception so that it can be interpreted separately.
* </p>
*
* @param user User to be validated
* @throws ConstraintViolationException If Bean Validation errors exist
* @throws ValidationException If user with the same email already exists
*/
private void validateUser(User user) throws ConstraintViolationException, ValidationException {
// Create a bean validator and check for issues.
Set<ConstraintViolation<User>> violations = validator.validate(user);
if (!violations.isEmpty()) {
throw new ConstraintViolationException(new HashSet<ConstraintViolation<?>>(violations));
}
// Check the uniqueness of the email address
if (emailAlreadyExists(user.getEmail())) {
throw new ValidationException("Unique Email Violation");
}
}
/**
* Creates a JAX-RS "Bad Request" response including a map of all violation fields, and their message. This can then be used
* by clients to show violations.
*
* @param violations A set of violations that needs to be reported
* @return JAX-RS response containing all violations
*/
private Response.ResponseBuilder createViolationResponse(Set<ConstraintViolation<?>> violations) {
log.fine("Validation completed. violations found: " + violations.size());
Map<String, String> responseObj = new HashMap<>();
for (ConstraintViolation<?> violation : violations) {
responseObj.put(violation.getPropertyPath().toString(), violation.getMessage());
}
return Response.status(Response.Status.BAD_REQUEST).entity(responseObj);
}
/**
* Checks if a user with the same email address is already registered. This is the only way to easily capture the
* "@UniqueConstraint(columnNames = "email")" constraint from the User class.
*
* @param email The email to check
* @return True if the email already exists, and false otherwise
*/
public boolean emailAlreadyExists(String email) {
User user = null;
try {
user = repository.findByEmail(email);
} catch (NoResultException e) {
// ignore
}
return user != null;
}
} |
Partager