001    /*
002     * ----------------------------------------------------------------------
003     * Copyright (C) 2009 Enrique Lara (k957@68k.org)
004     *
005     * TinLizard is free software; you can redistribute it and/or
006     * modify it under the terms of the GNU Lesser General Public License
007     * as published by the Free Software Foundation; either version 3.0
008     * of the License, or (at your option) any later version.
009     *
010     * TinLizard is distributed in the hope that it will be useful,
011     * but WITHOUT ANY WARRANTY; without even the implied warranty of
012     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
013     * GNU Lesser General Public License for more details.
014     *
015     * You should have received a copy of the GNU Lesser General Public License
016     * along with TinLizard. If not, see http://www.gnu.org/licenses/.
017     * ----------------------------------------------------------------------
018     */
019    package tinlizard.dao.jpa;
020    
021    import java.io.IOException;
022    
023    import javax.servlet.Filter;
024    import javax.servlet.FilterChain;
025    import javax.servlet.FilterConfig;
026    import javax.servlet.ServletException;
027    import javax.servlet.ServletRequest;
028    import javax.servlet.ServletResponse;
029    
030    import org.apache.log4j.Logger;
031    
032    /**
033     * Servlet filter to clean up EntityManager instance at the end of a request.
034     *
035     * XXX: research http://www.redhat.com/docs/en-US/JBoss_Enterprise_Application_Platform/4.3.0.cp04/html/Entity_Manager_User_Guide/Transactions_and_Concurrency.html
036     * XXX: may be overkill for any AJaX, or make smarter, skip /resources/*
037     *
038     */
039    public final class JpaFilter implements Filter {
040        private static final Logger LOG = Logger.getLogger(JpaFilter.class);
041    
042        public void init(final FilterConfig filterConfig) throws ServletException {
043        }
044    
045        public void destroy() {
046        }
047    
048        public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
049            if (LOG.isDebugEnabled()) {
050                LOG.debug("PRE");
051            }
052    
053            chain.doFilter(request, response);
054            JpaDao.getInstance().closeEm();
055    
056            if (LOG.isDebugEnabled()) {
057                LOG.debug("POST");
058            }
059        }
060    }