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.gauges;
18  
19  import org.apache.commons.monitoring.Role;
20  import org.apache.commons.monitoring.repositories.Repository;
21  
22  import java.util.LinkedList;
23  import java.util.ServiceLoader;
24  
25  public interface Gauge {
26      Role role();
27      double value();
28      long period();
29  
30      public static class LoaderHelper {
31          private LinkedList<Gauge> gauges = new LinkedList<Gauge>();
32  
33          public LoaderHelper(final boolean excludeParent, final String... includedPrefixes) {
34              final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
35  
36              for (final Gauge g : ServiceLoader.load(Gauge.class, classLoader)) {
37                  addGaugeIfNecessary(classLoader, g, excludeParent, includedPrefixes);
38              }
39              for (final GaugeFactory gf : ServiceLoader.load(GaugeFactory.class, classLoader)) {
40                  for (final Gauge g : gf.gauges()) {
41                      addGaugeIfNecessary(classLoader, g, excludeParent, includedPrefixes);
42                  }
43              }
44          }
45  
46          private void addGaugeIfNecessary(final ClassLoader classLoader, final Gauge g, final boolean excludeParent, final String... prefixes) {
47              final Class<? extends Gauge> gaugeClass = g.getClass();
48              if (!excludeParent || gaugeClass.getClassLoader() == classLoader) {
49                  if (prefixes != null) {
50                      for (final String p : prefixes) {
51                          if (!gaugeClass.getName().startsWith(p)) {
52                              return;
53                          }
54                      }
55                  }
56                  Repository.INSTANCE.addGauge(g);
57                  gauges.add(g);
58              }
59          }
60  
61          public void destroy() {
62              for (final Gauge gauge : gauges) {
63                  Repository.INSTANCE.stopGauge(gauge.role());
64              }
65          }
66      }
67  }