View Javadoc

1   package com.atlassian.plugins.rest.common.transaction;
2   
3   import com.atlassian.plugins.rest.common.interceptor.MethodInvocation;
4   import com.atlassian.plugins.rest.common.interceptor.ResourceInterceptor;
5   import com.atlassian.sal.api.transaction.TransactionCallback;
6   import com.atlassian.sal.api.transaction.TransactionTemplate;
7   
8   import java.lang.reflect.InvocationTargetException;
9   
10  /**
11   * Wraps the resource method call in a transaction via SAL's {@link TransactionTemplate}.
12   *
13   * @since 2.0
14   */
15  public class TransactionInterceptor implements ResourceInterceptor {
16      private final TransactionTemplate transactionTemplate;
17  
18      public TransactionInterceptor(TransactionTemplate transactionTemplate) {
19          this.transactionTemplate = transactionTemplate;
20      }
21  
22      public void intercept(final MethodInvocation invocation) throws IllegalAccessException, InvocationTargetException {
23          try {
24              transactionTemplate.execute(new TransactionCallback() {
25                  public Object doInTransaction() {
26                      try {
27                          invocation.invoke();
28                      } catch (IllegalAccessException e) {
29                          throw new TransactionException(e);
30                      } catch (InvocationTargetException e) {
31                          throw new TransactionException(e);
32                      }
33                      return null;
34                  }
35              });
36          } catch (TransactionException ex) {
37              Throwable t = ex.getCause();
38              if (t instanceof IllegalAccessException) {
39                  throw (IllegalAccessException) t;
40              } else if (t instanceof InvocationTargetException) {
41                  throw (InvocationTargetException) t;
42              } else {
43                  throw new RuntimeException("This should not be possible");
44              }
45          }
46      }
47  
48      private static final class TransactionException extends RuntimeException {
49          private TransactionException(Throwable throwable) {
50              super(throwable);
51          }
52      }
53  }