1 /***
2 *
3 */
4 package hu.elte.tribus.sf;
5
6 import java.io.IOException;
7
8 import javax.servlet.Filter;
9 import javax.servlet.FilterChain;
10 import javax.servlet.FilterConfig;
11 import javax.servlet.ServletContext;
12 import javax.servlet.ServletException;
13 import javax.servlet.ServletRequest;
14 import javax.servlet.ServletResponse;
15
16 import org.apache.log4j.Logger;
17 import org.springframework.context.ApplicationContext;
18 import org.springframework.transaction.PlatformTransactionManager;
19 import org.springframework.transaction.TransactionStatus;
20 import org.springframework.transaction.support.TransactionCallback;
21 import org.springframework.transaction.support.TransactionTemplate;
22 import org.springframework.web.context.support.WebApplicationContextUtils;
23
24 /***
25 * @author kocka
26 *
27 */
28 public class TransactionFilter implements Filter {
29
30 private ServletContext context = null;
31 private final static Logger logger = Logger.getLogger(TransactionFilter.class);
32
33
34
35
36
37
38 public void destroy() {
39
40
41 }
42
43
44
45
46
47
48
49 public void doFilter(final ServletRequest request,
50 final ServletResponse response, final FilterChain chain)
51 throws IOException, ServletException {
52 ApplicationContext applicationContext = WebApplicationContextUtils
53 .getWebApplicationContext(this.context);
54 PlatformTransactionManager transactionManager = (PlatformTransactionManager) applicationContext
55 .getBean("txManager");
56 TransactionTemplate template = new TransactionTemplate(
57 transactionManager);
58 Object res = template.execute(new TransactionCallback() {
59
60 public Object doInTransaction(TransactionStatus arg0) {
61 try {
62 chain.doFilter(request, response);
63 } catch (IOException e) {
64 return e;
65 } catch (ServletException e) {
66 return e;
67 }
68 return null;
69 }
70 });
71 if(res != null) {
72 logger.info("Transaction error",(Throwable)res);
73 }
74 }
75
76
77
78
79
80
81 public void init(FilterConfig config) throws ServletException {
82 context = config.getServletContext();
83 }
84
85 }