Commit 2f3a8856ae76cc48a38547855a7b5dabdf3fd96e

Authored by Cleverson Sacramento
1 parent 3d44961e
Exists in master

Melhoria no tratamente de exceções

archetype/html-rest/src/main/resources/archetype-resources/src/main/java/rest/BookmarkREST.java
... ... @@ -49,7 +49,7 @@ public class BookmarkREST {
49 49 @GET
50 50 @Path("{id}")
51 51 @Produces("application/json")
52   - public Bookmark load(@PathParam("id") Long id) {
  52 + public Bookmark load(@PathParam("id") Long id) throws Exception {
53 53 Bookmark result = bc.load(id);
54 54  
55 55 if (result == null) {
... ... @@ -65,7 +65,7 @@ public class BookmarkREST {
65 65 @ValidatePayload
66 66 @Produces("application/json")
67 67 @Consumes("application/json")
68   - public Response insert(Bookmark entity, @Context UriInfo uriInfo) {
  68 + public Response insert(Bookmark entity, @Context UriInfo uriInfo) throws Exception {
69 69 checkId(entity);
70 70  
71 71 String id = bc.insert(entity).getId().toString();
... ... @@ -81,7 +81,7 @@ public class BookmarkREST {
81 81 @ValidatePayload
82 82 @Produces("application/json")
83 83 @Consumes("application/json")
84   - public void update(@PathParam("id") Long id, Bookmark entity) {
  84 + public void update(@PathParam("id") Long id, Bookmark entity) throws Exception {
85 85 checkId(entity);
86 86 load(id);
87 87  
... ... @@ -93,7 +93,7 @@ public class BookmarkREST {
93 93 @LoggedIn
94 94 @Path("{id}")
95 95 @Transactional
96   - public void delete(@PathParam("id") Long id) {
  96 + public void delete(@PathParam("id") Long id) throws Exception {
97 97 load(id);
98 98 bc.delete(id);
99 99 }
... ... @@ -101,11 +101,11 @@ public class BookmarkREST {
101 101 @DELETE
102 102 @LoggedIn
103 103 @Transactional
104   - public void delete(List<Long> ids) {
  104 + public void delete(List<Long> ids) throws Exception {
105 105 bc.delete(ids);
106 106 }
107 107  
108   - private void checkId(Bookmark entity) {
  108 + private void checkId(Bookmark entity) throws Exception {
109 109 if (entity.getId() != null) {
110 110 throw new BadRequestException();
111 111 }
... ...
archetype/html-rest/src/main/resources/archetype-resources/src/main/webapp/js/controller/bookmark-edit.js
... ... @@ -68,7 +68,7 @@ function saveOk(data) {
68 68  
69 69 function saveFailed(request) {
70 70 switch (request.status) {
71   - case 412:
  71 + case 422:
72 72 $($("form input").get().reverse()).each(function() {
73 73 var id = $(this).attr('id');
74 74 var message = null;
... ...
archetype/html-rest/src/main/resources/archetype-resources/src/main/webapp/js/controller/login.js
... ... @@ -3,14 +3,14 @@ $(function() {
3 3  
4 4 $("form").submit(function(event) {
5 5 event.preventDefault();
6   -
  6 +
7 7 $("[id$='-message']").hide();
8   -
  8 +
9 9 var form = {
10 10 'username' : $("#username").val().trim(),
11 11 'password' : $("#password").val().trim()
12 12 };
13   -
  13 +
14 14 AuthProxy.login(form).done(loginOk).fail(loginFail);
15 15 });
16 16 });
... ... @@ -32,7 +32,7 @@ function loginFail(request) {
32 32 $("#global-message").html("Usuário ou senha inválidos.").show();
33 33 break;
34 34  
35   - case 412:
  35 + case 422:
36 36 $($("form input").get().reverse()).each(function() {
37 37 var id = $(this).attr('id');
38 38 var message = null;
... ... @@ -54,4 +54,4 @@ function loginFail(request) {
54 54 });
55 55 break;
56 56 }
57   -}
58 57 \ No newline at end of file
  58 +}
... ...
archetype/html-rest/src/main/resources/archetype-resources/src/test/java/rest/BookmarkRESTTest.java
... ... @@ -35,7 +35,8 @@ import org.junit.Before;
35 35 import org.junit.Test;
36 36  
37 37 import ${package}.entity.Bookmark;
38   -import br.gov.frameworkdemoiselle.PreconditionFailedException;
  38 +import br.gov.frameworkdemoiselle.HttpViolationException;
  39 +import br.gov.frameworkdemoiselle.UnprocessableEntityException;
39 40  
40 41 public class BookmarkRESTTest {
41 42  
... ... @@ -169,8 +170,8 @@ public class BookmarkRESTTest {
169 170 HttpPost request;
170 171 CloseableHttpResponse response;
171 172 Bookmark bookmark;
172   - Set<PreconditionFailedException.Violation> violations;
173   - PreconditionFailedException expected;
  173 + Set<UnprocessableEntityException.Violation> violations;
  174 + HttpViolationException expected;
174 175  
175 176 bookmark = new Bookmark();
176 177 bookmark.setDescription("Google");
... ... @@ -191,9 +192,9 @@ public class BookmarkRESTTest {
191 192 response.close();
192 193 assertEquals(SC_PRECONDITION_FAILED, response.getStatusLine().getStatusCode());
193 194 violations = mapper.readValue(response.getEntity().getContent(),
194   - new TypeReference<Set<PreconditionFailedException.Violation>>() {
  195 + new TypeReference<Set<UnprocessableEntityException.Violation>>() {
195 196 });
196   - expected = new PreconditionFailedException();
  197 + expected = new UnprocessableEntityException();
197 198 expected.addViolation("description", "não pode ser nulo");
198 199 expected.addViolation("link", "não pode ser nulo");
199 200 assertEquals(expected.getViolations(), violations);
... ... @@ -209,9 +210,9 @@ public class BookmarkRESTTest {
209 210 response.close();
210 211 assertEquals(SC_PRECONDITION_FAILED, response.getStatusLine().getStatusCode());
211 212 violations = mapper.readValue(response.getEntity().getContent(),
212   - new TypeReference<Set<PreconditionFailedException.Violation>>() {
  213 + new TypeReference<Set<UnprocessableEntityException.Violation>>() {
213 214 });
214   - expected = new PreconditionFailedException().addViolation("link", "formato inválido");
  215 + expected = new UnprocessableEntityException().addViolation("link", "formato inválido");
215 216 assertEquals(expected.getViolations(), violations);
216 217  
217 218 bookmark = new Bookmark();
... ... @@ -266,8 +267,8 @@ public class BookmarkRESTTest {
266 267 response.close();
267 268 Long id = parseEntity(response.getEntity(), Long.class);
268 269 Bookmark bookmark;
269   - Set<PreconditionFailedException.Violation> violations;
270   - PreconditionFailedException expected;
  270 + Set<UnprocessableEntityException.Violation> violations;
  271 + HttpViolationException expected;
271 272  
272 273 bookmark = new Bookmark();
273 274 bookmark.setDescription("Google");
... ... @@ -288,9 +289,9 @@ public class BookmarkRESTTest {
288 289 response.close();
289 290 assertEquals(SC_PRECONDITION_FAILED, response.getStatusLine().getStatusCode());
290 291 violations = mapper.readValue(response.getEntity().getContent(),
291   - new TypeReference<Set<PreconditionFailedException.Violation>>() {
  292 + new TypeReference<Set<UnprocessableEntityException.Violation>>() {
292 293 });
293   - expected = new PreconditionFailedException();
  294 + expected = new UnprocessableEntityException();
294 295 expected.addViolation("description", "não pode ser nulo");
295 296 expected.addViolation("link", "não pode ser nulo");
296 297 assertEquals(expected.getViolations(), violations);
... ... @@ -306,9 +307,9 @@ public class BookmarkRESTTest {
306 307 response.close();
307 308 assertEquals(SC_PRECONDITION_FAILED, response.getStatusLine().getStatusCode());
308 309 violations = mapper.readValue(response.getEntity().getContent(),
309   - new TypeReference<Set<PreconditionFailedException.Violation>>() {
  310 + new TypeReference<Set<UnprocessableEntityException.Violation>>() {
310 311 });
311   - expected = new PreconditionFailedException().addViolation("link", "formato inválido");
  312 + expected = new UnprocessableEntityException().addViolation("link", "formato inválido");
312 313 assertEquals(expected.getViolations(), violations);
313 314  
314 315 bookmark = new Bookmark();
... ...
impl/extension/rest/src/main/java/br/gov/frameworkdemoiselle/ForbiddenException.java
... ... @@ -2,9 +2,7 @@ package br.gov.frameworkdemoiselle;
2 2  
3 3 import static javax.servlet.http.HttpServletResponse.SC_FORBIDDEN;
4 4  
5   -import javax.xml.ws.http.HTTPException;
6   -
7   -public class ForbiddenException extends HTTPException {
  5 +public class ForbiddenException extends HttpViolationException {
8 6  
9 7 private static final long serialVersionUID = 1L;
10 8  
... ...
impl/extension/rest/src/main/java/br/gov/frameworkdemoiselle/NotFoundException.java
... ... @@ -2,9 +2,7 @@ package br.gov.frameworkdemoiselle;
2 2  
3 3 import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND;
4 4  
5   -import javax.xml.ws.http.HTTPException;
6   -
7   -public class NotFoundException extends HTTPException {
  5 +public class NotFoundException extends HttpViolationException {
8 6  
9 7 private static final long serialVersionUID = 1L;
10 8  
... ...
impl/extension/rest/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/ConstraintViolationExceptionMapper.java
1 1 package br.gov.frameworkdemoiselle.internal.implementation;
2 2  
3   -import static javax.ws.rs.core.Response.Status.PRECONDITION_FAILED;
4   -
5 3 import java.util.Iterator;
6 4  
7 5 import javax.validation.ConstraintViolation;
... ... @@ -24,6 +22,7 @@ public class ConstraintViolationExceptionMapper implements ExceptionMapper&lt;Const
24 22 failed.addViolation(violation.getPropertyPath().toString(), violation.getMessage());
25 23 }
26 24  
27   - return Response.status(PRECONDITION_FAILED).entity(failed.getViolations()).build();
  25 + int status = new UnprocessableEntityException().getStatusCode();
  26 + return Response.status(status).entity(failed.getViolations()).build();
28 27 }
29 28 }
... ...
impl/extension/rest/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/HTTPExceptionMapper.java
... ... @@ -1,15 +0,0 @@
1   -package br.gov.frameworkdemoiselle.internal.implementation;
2   -
3   -import javax.ws.rs.core.Response;
4   -import javax.ws.rs.ext.ExceptionMapper;
5   -import javax.ws.rs.ext.Provider;
6   -import javax.xml.ws.http.HTTPException;
7   -
8   -@Provider
9   -public class HTTPExceptionMapper implements ExceptionMapper<HTTPException> {
10   -
11   - @Override
12   - public Response toResponse(HTTPException exception) {
13   - return Response.status(exception.getStatusCode()).build();
14   - }
15   -}
impl/extension/rest/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/HttpViolationExceptionMapper.java
1 1 package br.gov.frameworkdemoiselle.internal.implementation;
2 2  
  3 +import java.util.Set;
  4 +
3 5 import javax.ws.rs.core.Response;
4 6 import javax.ws.rs.ext.ExceptionMapper;
5 7 import javax.ws.rs.ext.Provider;
6 8  
7 9 import br.gov.frameworkdemoiselle.HttpViolationException;
  10 +import br.gov.frameworkdemoiselle.HttpViolationException.Violation;
8 11  
9 12 @Provider
10 13 public class HttpViolationExceptionMapper implements ExceptionMapper<HttpViolationException> {
11 14  
12 15 @Override
13 16 public Response toResponse(HttpViolationException exception) {
14   - return Response.status(exception.getStatusCode()).entity(exception.getViolations()).build();
  17 + Set<Violation> violations = exception.getViolations();
  18 + violations = violations.isEmpty() ? null : violations;
  19 +
  20 + return Response.status(exception.getStatusCode()).entity(violations).build();
15 21 }
16 22 }
... ...
impl/extension/rest/src/main/java/br/gov/frameworkdemoiselle/security/AbstractHTTPAuthorizationFilter.java
... ... @@ -51,9 +51,6 @@ import javax.servlet.ServletResponse;
51 51 import javax.servlet.http.HttpServletRequest;
52 52 import javax.servlet.http.HttpServletResponse;
53 53  
54   -import br.gov.frameworkdemoiselle.security.AuthenticationException;
55   -import br.gov.frameworkdemoiselle.security.InvalidCredentialsException;
56   -import br.gov.frameworkdemoiselle.security.SecurityContext;
57 54 import br.gov.frameworkdemoiselle.util.Beans;
58 55 import br.gov.frameworkdemoiselle.util.Strings;
59 56  
... ... @@ -70,7 +67,11 @@ public abstract class AbstractHTTPAuthorizationFilter implements Filter {
70 67 @Override
71 68 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
72 69 ServletException {
73   - if (request instanceof HttpServletRequest && isSupported(getAuthHeader((HttpServletRequest) request))) {
  70 +
  71 + RESTSecurityConfig config = Beans.getReference(RESTSecurityConfig.class);
  72 +
  73 + if (request instanceof HttpServletRequest && isActive(config)
  74 + && isSupported(getAuthHeader((HttpServletRequest) request))) {
74 75 try {
75 76 performLogin((HttpServletRequest) request);
76 77 chain.doFilter((HttpServletRequest) request, (HttpServletResponse) response);
... ... @@ -92,6 +93,8 @@ public abstract class AbstractHTTPAuthorizationFilter implements Filter {
92 93  
93 94 protected abstract boolean isSupported(String authHeader);
94 95  
  96 + protected abstract boolean isActive(RESTSecurityConfig config);
  97 +
95 98 protected abstract void prepareForLogin();
96 99  
97 100 private void performLogin(HttpServletRequest request) {
... ...
impl/extension/rest/src/main/java/br/gov/frameworkdemoiselle/security/BasicAuthFilter.java
... ... @@ -52,6 +52,11 @@ public class BasicAuthFilter extends AbstractHTTPAuthorizationFilter {
52 52 }
53 53  
54 54 @Override
  55 + protected boolean isActive(RESTSecurityConfig config) {
  56 + return config.isBasicFilterActive();
  57 + }
  58 +
  59 + @Override
55 60 protected void prepareForLogin() {
56 61 String[] basicCredentials = getCredentials(credentials);
57 62  
... ...
impl/extension/rest/src/main/java/br/gov/frameworkdemoiselle/security/TokenAuthFilter.java
... ... @@ -49,6 +49,11 @@ public class TokenAuthFilter extends AbstractHTTPAuthorizationFilter {
49 49 }
50 50  
51 51 @Override
  52 + protected boolean isActive(RESTSecurityConfig config) {
  53 + return config.isTokenFilterActive();
  54 + }
  55 +
  56 + @Override
52 57 protected void prepareForLogin() {
53 58 Beans.getReference(Token.class).setValue(token);
54 59 }
... ...