001/* 002 * Copyright 2012 Atteo. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package org.atteo.moonshine.jta; 017 018import java.io.IOException; 019 020import javax.inject.Singleton; 021import javax.servlet.Filter; 022import javax.servlet.FilterChain; 023import javax.servlet.FilterConfig; 024import javax.servlet.ServletException; 025import javax.servlet.ServletRequest; 026import javax.servlet.ServletResponse; 027 028/** 029 * {@link Filter} which wraps the request handling inside JTA transaction. 030 */ 031@Singleton 032public class TransactionalFilter implements Filter { 033 034 @Override 035 public void init(FilterConfig filterConfig) throws ServletException { 036 } 037 038 @Override 039 public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) 040 throws IOException, ServletException { 041 try { 042 Transaction.require(new Transaction.ThrowingRunnable<Exception>() { 043 @Override 044 public void run() throws IOException, ServletException { 045 chain.doFilter(request, response); 046 } 047 }); 048 } catch (RuntimeException | ServletException | IOException e) { 049 throw e; 050 } catch (Exception e) { 051 throw new RuntimeException("Internal error, unexpected exception", e); 052 } 053 } 054 055 @Override 056 public void destroy() { 057 } 058}