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.gauges; 018 019 import org.apache.commons.monitoring.Role; 020 import org.apache.commons.monitoring.repositories.Repository; 021 022 import java.util.LinkedList; 023 import java.util.ServiceLoader; 024 025 public interface Gauge { 026 Role role(); 027 double value(); 028 long period(); 029 030 public static class LoaderHelper { 031 private LinkedList<Gauge> gauges = new LinkedList<Gauge>(); 032 033 public LoaderHelper(final boolean excludeParent, final String... includedPrefixes) { 034 final ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); 035 036 for (final Gauge g : ServiceLoader.load(Gauge.class, classLoader)) { 037 addGaugeIfNecessary(classLoader, g, excludeParent, includedPrefixes); 038 } 039 for (final GaugeFactory gf : ServiceLoader.load(GaugeFactory.class, classLoader)) { 040 for (final Gauge g : gf.gauges()) { 041 addGaugeIfNecessary(classLoader, g, excludeParent, includedPrefixes); 042 } 043 } 044 } 045 046 private void addGaugeIfNecessary(final ClassLoader classLoader, final Gauge g, final boolean excludeParent, final String... prefixes) { 047 final Class<? extends Gauge> gaugeClass = g.getClass(); 048 if (!excludeParent || gaugeClass.getClassLoader() == classLoader) { 049 if (prefixes != null) { 050 for (final String p : prefixes) { 051 if (!gaugeClass.getName().startsWith(p)) { 052 return; 053 } 054 } 055 } 056 Repository.INSTANCE.addGauge(g); 057 gauges.add(g); 058 } 059 } 060 061 public void destroy() { 062 for (final Gauge gauge : gauges) { 063 Repository.INSTANCE.stopGauge(gauge.role()); 064 } 065 } 066 } 067 }