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.aop;
18  
19  import org.apache.commons.monitoring.Role;
20  import org.apache.commons.monitoring.counters.Counter;
21  import org.apache.commons.monitoring.repositories.Repository;
22  import org.junit.Test;
23  
24  import java.util.concurrent.TimeUnit;
25  
26  import static org.junit.Assert.assertEquals;
27  import static org.junit.Assert.assertNotNull;
28  import static org.junit.Assert.fail;
29  
30  public class MonitoringProxyFactoryTest {
31      @Test
32      public void test() {
33          final Foo foo = MonitoringProxyFactory.monitor(Foo.class, new FooImpl());
34          foo.haveARest(2000);
35  
36          final Counter perf = Repository.INSTANCE.getCounter(new Counter.Key(Role.PERFORMANCES, FooImpl.class.getName() + ".haveARest"));
37          assertNotNull(perf);
38          assertEquals(2000, TimeUnit.NANOSECONDS.toMillis((int) perf.getMax()), 200);
39  
40          try {
41              foo.throwSthg();
42          } catch (final Exception e) {
43              // normal
44          }
45  
46          Counter failures = null;
47          for (final Counter c : Repository.INSTANCE) {
48              if (c.getKey().getName().contains("UnsupportedOperationException")) {
49                  if (failures != null) {
50                      fail();
51                  }
52                  failures = c;
53              }
54          }
55  
56          assertNotNull(failures);
57          assertEquals(1, failures.getHits());
58      }
59  
60      public static interface Foo {
61          void haveARest(long ms);
62          void throwSthg();
63      }
64  
65      public static class FooImpl implements Foo {
66          @Override
67          public void haveARest(long ms) {
68              try {
69                  Thread.sleep(ms);
70              } catch (final InterruptedException e) {
71                  // no-ôp
72              }
73          }
74  
75          public void throwSthg() {
76              throw new UnsupportedOperationException();
77          }
78      }
79  }