001/*
002 * (C) Copyright 2010 Nuxeo SAS (http://nuxeo.com/) and contributors.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the GNU Lesser General Public License
006 * (LGPL) version 2.1 which accompanies this distribution, and is available at
007 * http://www.gnu.org/licenses/lgpl.html
008 *
009 * This library is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012 * Lesser General Public License for more details.
013 *
014 * Contributors:
015 *     Nuxeo - initial API and implementation
016 */
017
018package org.nuxeo.runtime.management.metrics;
019
020import java.util.HashMap;
021import java.util.HashSet;
022
023import javax.management.MBeanServer;
024
025import org.apache.commons.logging.Log;
026import org.apache.commons.logging.LogFactory;
027import org.nuxeo.runtime.api.Framework;
028import org.nuxeo.runtime.management.ObjectNameFactory;
029import org.nuxeo.runtime.management.ResourcePublisher;
030import org.nuxeo.runtime.management.ServerLocator;
031
032public class MetricRegister {
033
034    protected static final Log log = LogFactory.getLog(MetricRegister.class);
035
036    protected final MBeanServer server = Framework.getLocalService(ServerLocator.class).lookupServer();
037
038    protected final HashMap<String, String> cnames = new HashMap<String, String>();
039
040    protected String canonicalName(String name, String type) {
041        return ObjectNameFactory.formatMetricQualifiedName(name, type);
042    }
043
044    public void registerMXBean(Object mbean, String name, Class<?> itf, String type) {
045        ResourcePublisher srv = Framework.getLocalService(ResourcePublisher.class);
046        String cname = canonicalName(name, type);
047        srv.registerResource(name, cname, itf, mbean);
048        cnames.put(name, cname);
049    }
050
051    public void unregisterMXBean(Object mbean) {
052        unregisterMXBean(mbean.getClass().getSimpleName());
053    }
054
055    public void unregisterMXBean(String name) {
056        ResourcePublisher srv = Framework.getLocalService(ResourcePublisher.class);
057        if (srv == null) {
058            return;
059        }
060        String cname = cnames.remove(name);
061        if (cname != null) {
062            srv.unregisterResource(name, cname);
063        }
064    }
065
066    public void unregisterAll() {
067        HashSet<String> names = new HashSet<String>();
068        names.addAll(cnames.keySet());
069        for (String name : names) {
070            unregisterMXBean(name);
071        }
072    }
073}