View Javadoc
1   /*
2    * JBoss, Home of Professional Open Source
3    * Copyright 2014, Red Hat, Inc. and/or its affiliates, and individual
4    * contributors by the @authors tag. See the copyright.txt in the
5    * distribution for a full listing of individual contributors.
6    *
7    * Licensed under the Apache License, Version 2.0 (the "License");
8    * you may not use this file except in compliance with the License.
9    * You may obtain a copy of the License at
10   * http://www.apache.org/licenses/LICENSE-2.0
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.jboss.as.quickstarts.kitchensink.rest;
18  
19  import java.util.HashMap;
20  import java.util.HashSet;
21  import java.util.List;
22  import java.util.Map;
23  import java.util.Set;
24  import java.util.logging.Logger;
25  
26  import javax.enterprise.context.RequestScoped;
27  import javax.inject.Inject;
28  import javax.persistence.NoResultException;
29  import javax.validation.ConstraintViolation;
30  import javax.validation.ConstraintViolationException;
31  import javax.validation.ValidationException;
32  import javax.validation.Validator;
33  import javax.ws.rs.Consumes;
34  import javax.ws.rs.GET;
35  import javax.ws.rs.POST;
36  import javax.ws.rs.Path;
37  import javax.ws.rs.PathParam;
38  import javax.ws.rs.Produces;
39  import javax.ws.rs.WebApplicationException;
40  import javax.ws.rs.core.MediaType;
41  import javax.ws.rs.core.Response;
42  
43  import org.jboss.as.quickstarts.kitchensink.data.MemberRepository;
44  import org.jboss.as.quickstarts.kitchensink.model.Member;
45  import org.jboss.as.quickstarts.kitchensink.service.MemberRegistration;
46  
47  /**
48   * JAX-RS Example
49   * <p/>
50   * This class produces a RESTful service to read/write the contents of the members table.
51   */
52  @Path("/members")
53  @RequestScoped
54  public class MemberResourceRESTService {
55  
56      @Inject
57      private Logger log;
58  
59      @Inject
60      private Validator validator;
61  
62      @Inject
63      private MemberRepository repository;
64  
65      @Inject
66      MemberRegistration registration;
67  
68      @GET
69      @Produces(MediaType.APPLICATION_JSON)
70      public List<Member> listAllMembers() {
71          return repository.findAllOrderedByName();
72      }
73  
74      @GET
75      @Path("/{id:[0-9][0-9]*}")
76      @Produces(MediaType.APPLICATION_JSON)
77      public Member lookupMemberById(@PathParam("id") long id) {
78          Member member = repository.findById(id);
79          if (member == null) {
80              throw new WebApplicationException(Response.Status.NOT_FOUND);
81          }
82          return member;
83      }
84  
85      /**
86       * Creates a new member from the values provided. Performs validation, and will return a JAX-RS response with either 200 ok,
87       * or with a map of fields, and related errors.
88       */
89      @POST
90      @Consumes(MediaType.APPLICATION_JSON)
91      @Produces(MediaType.APPLICATION_JSON)
92      public Response createMember(Member member) {
93  
94          Response.ResponseBuilder builder = null;
95  
96          try {
97              // Validates member using bean validation
98              validateMember(member);
99  
100             registration.register(member);
101 
102             // Create an "ok" response
103             builder = Response.ok();
104         } catch (ConstraintViolationException ce) {
105             // Handle bean validation issues
106             builder = createViolationResponse(ce.getConstraintViolations());
107         } catch (ValidationException e) {
108             // Handle the unique constrain violation
109             Map<String, String> responseObj = new HashMap<String, String>();
110             responseObj.put("email", "Email taken");
111             builder = Response.status(Response.Status.CONFLICT).entity(responseObj);
112         } catch (Exception e) {
113             // Handle generic exceptions
114             Map<String, String> responseObj = new HashMap<String, String>();
115             responseObj.put("error", e.getMessage());
116             builder = Response.status(Response.Status.BAD_REQUEST).entity(responseObj);
117         }
118 
119         return builder.build();
120     }
121 
122     /**
123      * <p>
124      * Validates the given Member variable and throws validation exceptions based on the type of error. If the error is standard
125      * bean validation errors then it will throw a ConstraintValidationException with the set of the constraints violated.
126      * </p>
127      * <p>
128      * If the error is caused because an existing member with the same email is registered it throws a regular validation
129      * exception so that it can be interpreted separately.
130      * </p>
131      * 
132      * @param member Member to be validated
133      * @throws ConstraintViolationException If Bean Validation errors exist
134      * @throws ValidationException If member with the same email already exists
135      */
136     private void validateMember(Member member) throws ConstraintViolationException, ValidationException {
137         // Create a bean validator and check for issues.
138         Set<ConstraintViolation<Member>> violations = validator.validate(member);
139 
140         if (!violations.isEmpty()) {
141             throw new ConstraintViolationException(new HashSet<ConstraintViolation<?>>(violations));
142         }
143 
144         // Check the uniqueness of the email address
145         if (emailAlreadyExists(member.getEmail())) {
146             throw new ValidationException("Unique Email Violation");
147         }
148     }
149 
150     /**
151      * Creates a JAX-RS "Bad Request" response including a map of all violation fields, and their message. This can then be used
152      * by clients to show violations.
153      * 
154      * @param violations A set of violations that needs to be reported
155      * @return JAX-RS response containing all violations
156      */
157     private Response.ResponseBuilder createViolationResponse(Set<ConstraintViolation<?>> violations) {
158         log.fine("Validation completed. violations found: " + violations.size());
159 
160         Map<String, String> responseObj = new HashMap<String, String>();
161 
162         for (ConstraintViolation<?> violation : violations) {
163             responseObj.put(violation.getPropertyPath().toString(), violation.getMessage());
164         }
165 
166         return Response.status(Response.Status.BAD_REQUEST).entity(responseObj);
167     }
168 
169     /**
170      * Checks if a member with the same email address is already registered. This is the only way to easily capture the
171      * "@UniqueConstraint(columnNames = "email")" constraint from the Member class.
172      * 
173      * @param email The email to check
174      * @return True if the email already exists, and false otherwise
175      */
176     public boolean emailAlreadyExists(String email) {
177         Member member = null;
178         try {
179             member = repository.findByEmail(email);
180         } catch (NoResultException e) {
181             // ignore
182         }
183         return member != null;
184     }
185 }