001/*
002 * (C) Copyright 2010 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     Nuxeo - initial API and implementation
018 */
019
020package org.nuxeo.runtime.management.metrics;
021
022import java.util.HashMap;
023import java.util.HashSet;
024
025import javax.management.MBeanServer;
026
027import org.apache.commons.logging.Log;
028import org.apache.commons.logging.LogFactory;
029import org.nuxeo.runtime.api.Framework;
030import org.nuxeo.runtime.management.ObjectNameFactory;
031import org.nuxeo.runtime.management.ResourcePublisher;
032import org.nuxeo.runtime.management.ServerLocator;
033
034public class MetricRegister {
035
036    protected static final Log log = LogFactory.getLog(MetricRegister.class);
037
038    protected final MBeanServer server = Framework.getService(ServerLocator.class).lookupServer();
039
040    protected final HashMap<String, String> cnames = new HashMap<String, String>();
041
042    protected String canonicalName(String name, String type) {
043        return ObjectNameFactory.formatMetricQualifiedName(name, type);
044    }
045
046    public void registerMXBean(Object mbean, String name, Class<?> itf, String type) {
047        ResourcePublisher srv = Framework.getService(ResourcePublisher.class);
048        String cname = canonicalName(name, type);
049        srv.registerResource(name, cname, itf, mbean);
050        cnames.put(name, cname);
051    }
052
053    public void unregisterMXBean(Object mbean) {
054        unregisterMXBean(mbean.getClass().getSimpleName());
055    }
056
057    public void unregisterMXBean(String name) {
058        ResourcePublisher srv = Framework.getService(ResourcePublisher.class);
059        if (srv == null) {
060            return;
061        }
062        String cname = cnames.remove(name);
063        if (cname != null) {
064            srv.unregisterResource(name, cname);
065        }
066    }
067
068    public void unregisterAll() {
069        HashSet<String> names = new HashSet<String>();
070        names.addAll(cnames.keySet());
071        for (String name : names) {
072            unregisterMXBean(name);
073        }
074    }
075}