001 /*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 * http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017 package org.apache.commons.monitoring.aop;
018
019 import org.apache.commons.monitoring.Role;
020 import org.apache.commons.monitoring.counters.Counter;
021 import org.apache.commons.monitoring.repositories.Repository;
022 import org.junit.Test;
023
024 import java.util.concurrent.TimeUnit;
025
026 import static org.junit.Assert.assertEquals;
027 import static org.junit.Assert.assertNotNull;
028 import static org.junit.Assert.fail;
029
030 public class MonitoringProxyFactoryTest {
031 @Test
032 public void test() {
033 final Foo foo = MonitoringProxyFactory.monitor(Foo.class, new FooImpl());
034 foo.haveARest(2000);
035
036 final Counter perf = Repository.INSTANCE.getCounter(new Counter.Key(Role.PERFORMANCES, FooImpl.class.getName() + ".haveARest"));
037 assertNotNull(perf);
038 assertEquals(2000, TimeUnit.NANOSECONDS.toMillis((int) perf.getMax()), 200);
039
040 try {
041 foo.throwSthg();
042 } catch (final Exception e) {
043 // normal
044 }
045
046 Counter failures = null;
047 for (final Counter c : Repository.INSTANCE) {
048 if (c.getKey().getName().contains("UnsupportedOperationException")) {
049 if (failures != null) {
050 fail();
051 }
052 failures = c;
053 }
054 }
055
056 assertNotNull(failures);
057 assertEquals(1, failures.getHits());
058 }
059
060 public static interface Foo {
061 void haveARest(long ms);
062 void throwSthg();
063 }
064
065 public static class FooImpl implements Foo {
066 @Override
067 public void haveARest(long ms) {
068 try {
069 Thread.sleep(ms);
070 } catch (final InterruptedException e) {
071 // no-ôp
072 }
073 }
074
075 public void throwSthg() {
076 throw new UnsupportedOperationException();
077 }
078 }
079 }