rsanchez
2015-01-28 fc256f48aa7e1a378f540fc1fdbde46739ff903c
securis/src/main/java/net/curisit/securis/DefaultExceptionHandler.java
....@@ -1,5 +1,6 @@
11 package net.curisit.securis;
22
3
+import javax.persistence.EntityManager;
34 import javax.servlet.http.HttpServletRequest;
45 import javax.ws.rs.ForbiddenException;
56 import javax.ws.rs.core.Context;
....@@ -32,23 +33,22 @@
3233 HttpServletRequest request;
3334 @Context
3435 SecurityContext bsc;
36
+ @Context
37
+ EntityManager em;
3538
3639 @Override
3740 public Response toResponse(Exception e) {
41
+ releaseEntityManager();
3842 if (e instanceof ForbiddenException) {
3943 LOG.warn("Unauthorized access to {}, user: {}", request.getPathInfo(), bsc.getUserPrincipal());
40
- return Response.status(Status.UNAUTHORIZED)
41
- .header(ERROR_CODE_MESSAGE_HEADER, ErrorCodes.INVALID_CREDENTIALS)
42
- .header(ERROR_MESSAGE_HEADER, "Unathorized access to the application")
43
- .type(MediaType.APPLICATION_JSON).build();
44
+ return Response.status(Status.UNAUTHORIZED).header(ERROR_CODE_MESSAGE_HEADER, ErrorCodes.INVALID_CREDENTIALS)
45
+ .header(ERROR_MESSAGE_HEADER, "Unathorized access to the application").type(MediaType.APPLICATION_JSON).build();
4446 }
4547
4648 if (e instanceof SeCurisServiceException) {
4749 LOG.warn("SeCurisServiceException accessing to {}, user: {}", request.getPathInfo(), bsc.getUserPrincipal());
48
- return Response.status(DEFAULT_APP_ERROR_STATUS_CODE)
49
- .header(ERROR_CODE_MESSAGE_HEADER, ((SeCurisServiceException) e).getStatus())
50
- .header(ERROR_MESSAGE_HEADER, e.getMessage())
51
- .type(MediaType.APPLICATION_JSON).build();
50
+ return Response.status(DEFAULT_APP_ERROR_STATUS_CODE).header(ERROR_CODE_MESSAGE_HEADER, ((SeCurisServiceException) e).getStatus())
51
+ .header(ERROR_MESSAGE_HEADER, e.getMessage()).type(MediaType.APPLICATION_JSON).build();
5252 }
5353
5454 LOG.error("Unexpected error accesing to '{}' by user: {}", request.getPathInfo(), bsc.getUserPrincipal());
....@@ -56,4 +56,20 @@
5656 LOG.error("Request url: " + request.getRequestURL(), e);
5757 return Response.serverError().header(ERROR_MESSAGE_HEADER, "Unexpected error: " + e.toString()).type(MediaType.APPLICATION_JSON).build();
5858 }
59
+
60
+ private void releaseEntityManager() {
61
+ if (em != null && em.isOpen()) {
62
+ LOG.debug("CLOSING EM: {}, trans: {}", em, em.isJoinedToTransaction());
63
+ try {
64
+ if (em.isJoinedToTransaction()) {
65
+ em.getTransaction().rollback();
66
+ LOG.info("ROLLBACK");
67
+ }
68
+ em.close();
69
+ } catch (Exception ex) {
70
+ ex.printStackTrace();
71
+ LOG.error("Error closing EM: {}, {}", em, ex);
72
+ }
73
+ }
74
+ }
5975 }