View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.commons.monitoring.jta;
18  
19  import javax.annotation.Resource;
20  import javax.interceptor.AroundInvoke;
21  import javax.interceptor.AroundTimeout;
22  import javax.interceptor.Interceptor;
23  import javax.interceptor.InvocationContext;
24  import javax.transaction.Status;
25  import javax.transaction.Synchronization;
26  import javax.transaction.TransactionSynchronizationRegistry;
27  
28  @Interceptor
29  @JTAMonitored
30  public class JTAInterceptor {
31      private static final String RESOURCE_KEY = JTAInterceptor.class.getName();
32  
33      @Resource
34      private TransactionSynchronizationRegistry transactionSynchronizationRegistry;
35  
36      @AroundInvoke
37      @AroundTimeout
38      public Object jta(final InvocationContext invocationContext) throws Throwable {
39          if (transactionSynchronizationRegistry.getResource(RESOURCE_KEY) == null) {
40              JTAGauges.ACTIVE.incrementAndGet();
41              transactionSynchronizationRegistry.putResource(RESOURCE_KEY, Boolean.TRUE);
42              transactionSynchronizationRegistry.registerInterposedSynchronization(new JTACounterSynchronization());
43          }
44          return invocationContext.proceed();
45      }
46  
47      private static class JTACounterSynchronization implements Synchronization {
48          @Override
49          public void beforeCompletion() {
50              // no-op
51          }
52  
53          @Override
54          public void afterCompletion(final int status) {
55              if (status == Status.STATUS_COMMITTED) {
56                  JTAGauges.COMMITTED.incrementAndGet();
57              } else if (status == Status.STATUS_ROLLEDBACK) {
58                  JTAGauges.ROLLBACKED.incrementAndGet();
59              }
60              JTAGauges.ACTIVE.decrementAndGet();
61          }
62      }
63  }