Advertisement
Guest User

Untitled

a guest
Jan 23rd, 2017
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5.56 KB | None | 0 0
  1. package br.edu.ifpb.memoriam.filter;
  2.  
  3. import java.io.IOException;
  4.  
  5. import javax.persistence.EntityManager;
  6. import javax.persistence.EntityManagerFactory;
  7. import javax.servlet.Filter;
  8. import javax.servlet.FilterChain;
  9. import javax.servlet.FilterConfig;
  10. import javax.servlet.ServletException;
  11. import javax.servlet.ServletRequest;
  12. import javax.servlet.ServletResponse;
  13. import javax.servlet.annotation.WebFilter;
  14. import javax.servlet.http.HttpServletRequest;
  15. import javax.servlet.http.HttpSession;
  16.  
  17. import org.apache.log4j.Logger;
  18. import org.hibernate.StaleObjectStateException;
  19.  
  20. import br.edu.ifpb.memoriam.dao.ManagedEMContext;
  21. import br.edu.ifpb.memoriam.dao.PersistenceUtil;
  22.  
  23.  
  24. /**
  25.  * Este filtro controla o EntityManager para conversa��es longas. O EM � colocado e retirado
  26.  * da HttpSession a cada request para servlets e JSPs. Quando o servlet e os JSPs utilizarem
  27.  * o EM (via DAOs, por exemplo) ele estar� dispon�vel via PersistenceUtil.getCurrentEntityManager().
  28.  * Este filtro redireciona para a p�gina principal de consulta caso a HttpSession tenha sido fechada. Ou seja,
  29.  * se ele for ativado sem que uma sess~]ao tenha sido previamente criada, ele redirecionar� para esta p�gina index.jsp.
  30.  * @author Fred
  31.  *
  32.  */
  33. @WebFilter (urlPatterns = {"*.do", "*.jsp"})
  34. public class EntityManagerConversationFilter implements Filter {
  35.     private static Logger logger = Logger.getLogger(EntityManagerConversationFilter.class);
  36.  
  37.     private EntityManagerFactory emf;
  38.  
  39.     public static final String ENTITYMANAGER_FACTORY_KEY = "currentEntityManager";
  40.  
  41.     public static final String END_OF_CONVERSATION_FLAG = "endofconversation";
  42.  
  43.     public void doFilter(ServletRequest request, ServletResponse response,
  44.             FilterChain chain) throws IOException, ServletException {
  45.  
  46.         EntityManager currentEntityManager;
  47.        
  48.         // Try to get a EntityManager from the HttpSession
  49.         HttpSession httpSession =
  50.             ((HttpServletRequest) request).getSession();
  51.         EntityManager disconnectedEM =
  52.             (EntityManager) httpSession
  53.                 .getAttribute(ENTITYMANAGER_FACTORY_KEY);
  54.  
  55.         // Context path
  56.         String context = ((HttpServletRequest) request).getServletPath();
  57.         context += ": ";
  58.         try {
  59.  
  60.             // Start a new conversation or in the middle?
  61.             if (disconnectedEM == null) {
  62.                 logger.debug(context + ">>> Nova conversa��o");
  63.                 // Define o modo manual de flush
  64.                 currentEntityManager = emf.createEntityManager();
  65.                 ((org.hibernate.Session) currentEntityManager.getDelegate())
  66.                     .setFlushMode(org.hibernate.FlushMode.MANUAL);             
  67.             } else {
  68.                 logger.debug(context + "< Continuando conversa��o");
  69.                 currentEntityManager = disconnectedEM;
  70.             }
  71.            
  72.             ManagedEMContext.bind(emf, currentEntityManager);
  73.             logger.debug(context + "Associou EntityManager ao contexto");
  74.  
  75.             logger.debug(context + "Processando servlet/JSP");
  76.             chain.doFilter(request, response);
  77.  
  78.             // End or continue the long-running conversation?
  79.             if (request.getAttribute(END_OF_CONVERSATION_FLAG) != null
  80.                     || request.getParameter(END_OF_CONVERSATION_FLAG) != null) {
  81.  
  82.                 currentEntityManager.close();
  83.                 logger.debug(context + "Fechando o EntityManager");
  84.  
  85.                 ManagedEMContext.unbind(emf);
  86.                 logger.debug(context + "Desassociou EntityManager do contexto");
  87.                
  88.                 if (((HttpServletRequest) request).isRequestedSessionIdValid()) {
  89.                     httpSession.removeAttribute(ENTITYMANAGER_FACTORY_KEY);
  90.                     logger.debug(context + "Retirou EntityManager da HttpSession");
  91.                 }
  92.  
  93.                 logger.debug(context + "<<< Fim da conversa��o");
  94.  
  95.             } else {
  96.                 ManagedEMContext.unbind(emf);
  97.                 logger.debug(context + "Desassociou EntityManager do contexto");
  98.                
  99.                 if (((HttpServletRequest) request).isRequestedSessionIdValid()) {
  100.                     httpSession.setAttribute(ENTITYMANAGER_FACTORY_KEY, currentEntityManager);
  101.                     logger.debug(context + "Associou EntityManager a HttpSession");
  102.                 }
  103.  
  104.                 logger.debug(context + "> Retornando para o usuario");
  105.             }
  106.  
  107.         } catch (StaleObjectStateException staleEx) {
  108.             logger.error(context
  109.                             + "This interceptor does not implement optimistic concurrency control!");
  110.             logger.error(context
  111.                             + "Your application will not work until you add compensation actions!");
  112.             throw staleEx;
  113.         } catch (Throwable ex) {
  114.             // Rollback only
  115.             logger.debug(context + "Original exception:", ex);
  116.             try {
  117.                 if (PersistenceUtil.getCurrentEntityManager().getTransaction().isActive()) {
  118.                     logger.debug(context
  119.                                     + "Tentando rollback da transa��o ap�s exception");
  120.                     PersistenceUtil.getCurrentEntityManager().getTransaction().rollback();
  121.                 }
  122.             } catch (Throwable rbEx) {
  123.                 logger.error(context
  124.                         + "Rollback n�o efetivado!",
  125.                         rbEx);
  126.             } finally {
  127.                 logger.error(context + "Cleanup after exception!");
  128.  
  129.                 // Cleanup
  130.                 currentEntityManager = ManagedEMContext.unbind(emf);
  131.                 logger.debug(context + "Desassociou EntityManager do contexto");
  132.  
  133.                 currentEntityManager.close();
  134.                 logger.debug(context + "Fechou EntityManager ap�s exception");
  135.                
  136.                 if (((HttpServletRequest) request).isRequestedSessionIdValid()) {
  137.                     httpSession.setAttribute(ENTITYMANAGER_FACTORY_KEY, null);
  138.                     logger.debug(context + "Removeu EntityManager da HttpSession");
  139.                 }
  140.  
  141.             }
  142.  
  143.             // Let others handle it... maybe another interceptor for exceptions?
  144.             throw new ServletException(ex);
  145.         } finally {
  146.  
  147.         }
  148.     }
  149.  
  150.     public void init(FilterConfig filterConfig) throws ServletException {
  151.         emf = PersistenceUtil.getEntityManagerFactory();
  152.     }
  153.  
  154.     public void destroy() {
  155.     }
  156.  
  157. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement