001/* 
002 * Copyright (c) 2006-2011 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the Eclipse Public License v1.0
006 * which accompanies this distribution, and is available at
007 * http://www.eclipse.org/legal/epl-v10.html
008 *
009 * Contributors:
010 *     bstefanescu
011 */
012package org.nuxeo.ecm.webengine.jaxrs.tx;
013
014import java.io.IOException;
015
016import javax.servlet.FilterChain;
017import javax.servlet.FilterConfig;
018import javax.servlet.ServletException;
019import javax.servlet.http.HttpServletRequest;
020import javax.servlet.http.HttpServletResponse;
021
022import org.nuxeo.ecm.webengine.jaxrs.HttpFilter;
023import org.nuxeo.runtime.transaction.TransactionHelper;
024
025/**
026 * Filter using the {@link SimpleLoginModule} to authenticate a request.
027 *
028 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
029 */
030public class TransactionFilter extends HttpFilter {
031
032    @Override
033    public void init(FilterConfig filterConfig) throws ServletException {
034    }
035
036    @Override
037    public void run(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException,
038            ServletException {
039        boolean txStarted = false;
040        if (!TransactionHelper.isTransactionActive()) {
041            if (TransactionHelper.startTransaction()) {
042                txStarted = true;
043            }
044        }
045        try {
046            chain.doFilter(request, response);
047        } finally {
048            if (txStarted) {
049                TransactionHelper.commitOrRollbackTransaction();
050            }
051        }
052    }
053
054    @Override
055    public void destroy() {
056    }
057
058}