KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jboss > aspects > tx > TxPolicy


1 /*
2   * JBoss, Home of Professional Open Source
3   * Copyright 2005, JBoss Inc., and individual contributors as indicated
4   * by the @authors tag. See the copyright.txt in the distribution for a
5   * full listing of individual contributors.
6   *
7   * This is free software; you can redistribute it and/or modify it
8   * under the terms of the GNU Lesser General Public License as
9   * published by the Free Software Foundation; either version 2.1 of
10   * the License, or (at your option) any later version.
11   *
12   * This software is distributed in the hope that it will be useful,
13   * but WITHOUT ANY WARRANTY; without even the implied warranty of
14   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15   * Lesser General Public License for more details.
16   *
17   * You should have received a copy of the GNU Lesser General Public
18   * License along with this software; if not, write to the Free
19   * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
20   * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
21   */

22 package org.jboss.aspects.tx;
23
24 import java.util.ArrayList JavaDoc;
25 import java.util.Random JavaDoc;
26 import java.util.StringTokenizer JavaDoc;
27 import javax.transaction.HeuristicMixedException JavaDoc;
28 import javax.transaction.HeuristicRollbackException JavaDoc;
29 import javax.transaction.RollbackException JavaDoc;
30 import javax.transaction.Status JavaDoc;
31 import javax.transaction.SystemException JavaDoc;
32 import javax.transaction.Transaction JavaDoc;
33 import javax.transaction.TransactionManager JavaDoc;
34 import org.jboss.aop.joinpoint.Invocation;
35 import org.jboss.logging.Logger;
36 import org.jboss.util.deadlock.ApplicationDeadlockException;
37
38
39 /**
40  * TxSupport.java encapsulates the transaction handling possibilities
41  * from the ejb spec. The Tx interceptors call the clientInvoke and
42  * serverInvoke methods on the subclass determined by the method's
43  * transaction support.
44  * <p/>
45  * <p/>
46  * Created: Sun Feb 2 23:25:09 2003
47  *
48  * @author <a HREF="mailto:d_jencks@users.sourceforge.net">David Jencks</a>
49  * @author <a HREF="mailto:bill@jboss.org">Bill Burke</a>
50  */

51
52 public class TxPolicy
53 {
54    protected final static Logger log = Logger.getLogger(TxPolicy.class);
55
56    public static int MAX_RETRIES = 5;
57    public static Random JavaDoc random = new Random JavaDoc();
58
59    public void throwMandatory(Invocation invocation)
60    {
61       throw new RuntimeException JavaDoc("Transaction is mandatory.");
62    }
63
64    public Object JavaDoc invokeInNoTx(Invocation invocation) throws Throwable JavaDoc
65    {
66       return invocation.invokeNext();
67    }
68
69    public Object JavaDoc invokeInOurTx(Invocation invocation, TransactionManager JavaDoc tm) throws Throwable JavaDoc
70    {
71       for (int i = 0; i < MAX_RETRIES; i++)
72       {
73          tm.begin();
74          Transaction JavaDoc tx = tm.getTransaction();
75          try
76          {
77             try
78             {
79                return invocation.invokeNext();
80             }
81             catch (Throwable JavaDoc t)
82             {
83                handleExceptionInOurTx(invocation, t, tx);
84             }
85             finally
86             {
87                endTransaction(tm, tx);
88             }
89          }
90          catch (Exception JavaDoc ex)
91          {
92             ApplicationDeadlockException deadlock = ApplicationDeadlockException.isADE(ex);
93             if (deadlock != null)
94             {
95                if (!deadlock.retryable() ||
96                    i + 1 >= MAX_RETRIES)
97                {
98                   throw deadlock;
99                }
100                log.warn(deadlock.getMessage() + " retrying " + (i + 1));
101
102                Thread.sleep(random.nextInt(1 + i), random.nextInt(1000));
103             }
104             else
105             {
106                throw ex;
107             }
108          }
109       }
110       throw new RuntimeException JavaDoc("UNREACHABLE");
111    }
112
113    public void handleExceptionInOurTx(Invocation invocation, Throwable JavaDoc t, Transaction JavaDoc tx)
114            throws Throwable JavaDoc
115    {
116       // if this is an ApplicationException, just rethrow it
117
rethrowApplicationException(invocation, t);
118       setRollbackOnly(tx);
119       throw t;
120    }
121
122    public Object JavaDoc invokeInCallerTx(Invocation invocation, Transaction JavaDoc tx) throws Throwable JavaDoc
123    {
124       try
125       {
126          return invocation.invokeNext();
127       }
128       catch (Throwable JavaDoc t)
129       {
130          handleInCallerTx(invocation, t, tx);
131       }
132       throw new RuntimeException JavaDoc("UNREACHABLE");
133    }
134
135    public void handleInCallerTx(Invocation invocation, Throwable JavaDoc t, Transaction JavaDoc tx)
136            throws Throwable JavaDoc
137    {
138       rethrowApplicationException(invocation, t);
139       setRollbackOnly(tx);
140       throw t;
141    }
142
143    /**
144     * The <code>endTransaction</code> method ends a transaction and
145     * translates any exceptions into
146     * TransactionRolledBack[Local]Exception or SystemException.
147     *
148     * @param invocation an <code>Invocation</code> value
149     * @param tm a <code>TransactionManager</code> value
150     * @param tx a <code>Transaction</code> value
151     * @throws javax.transaction.TransactionRolledbackException
152     * if an error occurs
153     * @throws javax.transaction.SystemException
154     * if an error occurs
155     */

156    public void endTransaction(TransactionManager JavaDoc tm, Transaction JavaDoc tx)
157    {
158       try
159       {
160          if (tx != tm.getTransaction())
161          {
162             throw new IllegalStateException JavaDoc("Wrong tx on thread: expected " + tx + ", actual " + tm.getTransaction());
163          }
164
165          if (tx.getStatus() == Status.STATUS_MARKED_ROLLBACK)
166          {
167             tm.rollback();
168          }
169          else
170          {
171             // Commit tx
172
// This will happen if
173
// a) everything goes well
174
// b) app. exception was thrown
175
tm.commit();
176          }
177       }
178       catch (RollbackException JavaDoc e)
179       {
180          handleEndTransactionException(e);
181       }
182       catch (HeuristicMixedException JavaDoc e)
183       {
184          handleEndTransactionException(e);
185       }
186       catch (HeuristicRollbackException JavaDoc e)
187       {
188          handleEndTransactionException(e);
189       }
190       catch (SystemException JavaDoc e)
191       {
192          handleEndTransactionException(e);
193       }
194    }
195
196    public void handleEndTransactionException(Exception JavaDoc e)
197    {
198       throw new RuntimeException JavaDoc(e);
199    }
200
201    /**
202     * The <code>setRollbackOnly</code> method calls setRollbackOnly()
203     * on the invocation's transaction and logs any exceptions than may
204     * occur.
205     *
206     * @param invocation an <code>Invocation</code> value
207     */

208    public void setRollbackOnly(Transaction JavaDoc tx)
209    {
210       try
211       {
212          tx.setRollbackOnly();
213       }
214       catch (SystemException JavaDoc ex)
215       {
216          log.error("SystemException while setting transaction " +
217                    "for rollback only", ex);
218       }
219       catch (IllegalStateException JavaDoc ex)
220       {
221          log.error("IllegalStateException while setting transaction " +
222                    "for rollback only", ex);
223       }
224    }
225
226    /**
227     * The <code>rethrowApplicationException</code> method determines
228     * if the supplied Throwable is an application exception and
229     * rethrows it if it is.
230     *
231     * @param e a <code>Throwable</code> value
232     * @throws Exception if an error occurs
233     */

234    public void rethrowApplicationException(Invocation inv, Throwable JavaDoc e) throws Throwable JavaDoc
235    {
236       Object JavaDoc applicationExceptions = inv.getMetaData("transaction", "application-exceptions");
237       if (applicationExceptions == null) return;
238       Class JavaDoc[] applicationExceptionsList;
239       if (applicationExceptions instanceof String JavaDoc)
240       {
241          ArrayList JavaDoc tmpList = new ArrayList JavaDoc();
242          String JavaDoc aes = (String JavaDoc) applicationExceptions;
243          aes = aes.trim();
244          StringTokenizer JavaDoc tokenizer = new StringTokenizer JavaDoc(aes, ",");
245          while (tokenizer.hasMoreTokens())
246          {
247             String JavaDoc token = tokenizer.nextToken().trim();
248             Class JavaDoc excClass = Thread.currentThread().getContextClassLoader().loadClass(token);
249             tmpList.add(excClass);
250          }
251          applicationExceptionsList = (Class JavaDoc[]) tmpList.toArray(new Class JavaDoc[tmpList.size()]);
252       }
253       else
254       {
255          applicationExceptionsList = (Class JavaDoc[]) applicationExceptions;
256       }
257       for (int i = 0; i < applicationExceptionsList.length; i++)
258       {
259          if (applicationExceptionsList[i].isInstance(e)) throw e;
260       }
261
262    }
263
264 }
265
Popular Tags