1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package com.isenshi.util.extlib;
17
18 import javax.transaction.HeuristicMixedException;
19 import javax.transaction.HeuristicRollbackException;
20 import javax.transaction.NotSupportedException;
21 import javax.transaction.RollbackException;
22 import javax.transaction.SystemException;
23 import javax.transaction.TransactionManager;
24
25 import org.aopalliance.intercept.MethodInterceptor;
26 import org.aopalliance.intercept.MethodInvocation;
27 import org.apache.slide.common.NamespaceAccessToken;
28 import org.seasar.framework.container.factory.SingletonS2ContainerFactory;
29
30 public class SlideRequiredInterceptor implements MethodInterceptor {
31
32 private NamespaceAccessToken namespace;
33
34 public static void init(NamespaceAccessToken namespace) {
35 SlideRequiredInterceptor interceptor = (SlideRequiredInterceptor) SingletonS2ContainerFactory
36 .getContainer().getComponent(SlideRequiredInterceptor.class);
37 interceptor.setNamespace(namespace);
38 }
39
40 public SlideRequiredInterceptor() {
41 }
42
43 public void setNamespace(NamespaceAccessToken namespace) {
44 this.namespace = namespace;
45 }
46
47 private boolean hasTransaction() throws SystemException {
48 TransactionManager manager = namespace.getTransactionManager();
49 return manager.getTransaction() != null;
50 }
51
52 private void begin() throws NotSupportedException, SystemException {
53 namespace.begin();
54 }
55
56 private void commit() throws SecurityException, IllegalStateException,
57 RollbackException, HeuristicMixedException,
58 HeuristicRollbackException, SystemException {
59 namespace.commit();
60 }
61
62 private void complete(Throwable t) throws IllegalStateException,
63 SecurityException, SystemException {
64 rollback();
65 }
66
67 private void rollback() throws IllegalStateException, SecurityException,
68 SystemException {
69 if (hasTransaction()) {
70 namespace.rollback();
71 }
72 }
73
74 public Object invoke(MethodInvocation invocation) throws Throwable {
75 boolean began = false;
76 if (!hasTransaction()) {
77 begin();
78 began = true;
79 }
80 Object ret = null;
81 try {
82 ret = invocation.proceed();
83 if (began) {
84 commit();
85 }
86 return ret;
87 } catch (Throwable t) {
88 if (began) {
89 complete(t);
90 }
91 throw t;
92 }
93 }
94 }