01: package net.sourceforge.jaxor.util;
02:
03: import net.sourceforge.jaxor.JaxorSession;
04: import net.sourceforge.jaxor.api.JaxorContext;
05: import net.sourceforge.jaxor.api.JaxorContextFactory;
06: import net.sourceforge.jaxor.api.JaxorTransaction;
07:
08: import javax.servlet.*;
09: import java.io.IOException;
10:
11: /**
12: * User: mrettig
13: * Date: Jun 25, 2003
14: * Time: 5:06:07 PM
15: * Simple servlet filter that takes one parameter: factory. This parameter defines the class implementation
16: * of the jaxor context factory.
17: */
18: public class JaxorFilter implements Filter {
19:
20: private JaxorContextFactory _factory;
21:
22: public void init(FilterConfig config) throws ServletException {
23: _factory = loadFactory(config);
24: }
25:
26: public void setContextFactory(JaxorContextFactory fact) {
27: _factory = fact;
28: }
29:
30: private JaxorContextFactory loadFactory(FilterConfig config) {
31: try {
32: String factory = config.getInitParameter("factory");
33: return (JaxorContextFactory) getClass().getClassLoader()
34: .loadClass(factory).newInstance();
35: } catch (InstantiationException e) {
36: throw new SystemException(e);
37: } catch (IllegalAccessException e) {
38: throw new SystemException(e);
39: } catch (ClassNotFoundException e) {
40: throw new SystemException(e);
41: }
42: }
43:
44: public void destroy() {
45: }
46:
47: public void doFilter(ServletRequest request,
48: ServletResponse response, FilterChain chain)
49: throws ServletException, IOException {
50: JaxorSession.setJaxorContext(_factory.create());
51: try {
52: chain.doFilter(request, response);
53: JaxorSession.commit();
54: } catch (IOException e) {
55: rollback(e);
56: throw e;
57: } catch (ServletException e) {
58: rollback(e);
59: throw e;
60: } catch (RuntimeException e) {
61: rollback(e);
62: throw e;
63: } finally {
64: JaxorSession.end();
65: }
66: }
67:
68: private void rollback(Exception e) {
69: JaxorContext jaxorConnection = JaxorSession.getJaxorContext();
70: if (jaxorConnection == null)
71: return;
72: JaxorTransaction transaction = jaxorConnection.getTransaction();
73: if (transaction != null)
74: transaction.rollback(e);
75: }
76: }
|