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 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;
030
031public class MetricRegister {
032
033    protected static final Log log = LogFactory.getLog(MetricRegister.class);
034
035    protected final HashMap<String, String> cnames = new HashMap<>();
036
037    protected String canonicalName(String name, String type) {
038        return ObjectNameFactory.formatMetricQualifiedName(name, type);
039    }
040
041    public void registerMXBean(Object mbean, String name, Class<?> itf, String type) {
042        ResourcePublisher srv = Framework.getService(ResourcePublisher.class);
043        String cname = canonicalName(name, type);
044        srv.registerResource(name, cname, itf, mbean);
045        cnames.put(name, cname);
046    }
047
048    public void unregisterMXBean(Object mbean) {
049        unregisterMXBean(mbean.getClass().getSimpleName());
050    }
051
052    public void unregisterMXBean(String name) {
053        ResourcePublisher srv = Framework.getService(ResourcePublisher.class);
054        if (srv == null) {
055            return;
056        }
057        String cname = cnames.remove(name);
058        if (cname != null) {
059            srv.unregisterResource(name, cname);
060        }
061    }
062
063    public void unregisterAll() {
064        HashSet<String> names = new HashSet<>();
065        names.addAll(cnames.keySet());
066        for (String name : names) {
067            unregisterMXBean(name);
068        }
069    }
070}