001/*
002 *  Licensed to the Apache Software Foundation (ASF) under one
003 *  or more contributor license agreements.  See the NOTICE file
004 *  distributed with this work for additional information
005 *  regarding copyright ownership.  The ASF licenses this file
006 *  to you under the Apache License, Version 2.0 (the
007 *  "License"); you may not use this file except in compliance
008 *  with the License.  You may obtain a copy of the License at
009 *
010 *        http://www.apache.org/licenses/LICENSE-2.0
011 *
012 *  Unless required by applicable law or agreed to in writing,
013 *  software distributed under the License is distributed on an
014 *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 *  KIND, either express or implied.  See the License for the
016 *  specific language governing permissions and limitations
017 *  under the License.
018 */
019package org.apache.isis.core.commons.config;
020
021import java.lang.management.ManagementFactory;
022
023import javax.management.InstanceAlreadyExistsException;
024import javax.management.MBeanRegistrationException;
025import javax.management.MBeanServer;
026import javax.management.MalformedObjectNameException;
027import javax.management.NotCompliantMBeanException;
028import javax.management.ObjectName;
029
030import org.slf4j.Logger;
031import org.slf4j.LoggerFactory;
032
033public class JmxBeanServer {
034
035    private static final Logger LOG = LoggerFactory.getLogger(JmxBeanServer.class);
036
037    private static JmxBeanServer instance;
038    private final MBeanServer server;
039
040    private JmxBeanServer() {
041        server = ManagementFactory.getPlatformMBeanServer();
042        instance = this;
043    }
044
045    public static JmxBeanServer getInstance() {
046        if (instance == null) {
047            LOG.info("JMX bean server created");
048            instance = new JmxBeanServer();
049        }
050        return instance;
051    }
052
053    public void register(final String name, final Object object) {
054        try {
055            final ObjectName objectName = new ObjectName("Isis:name=" + name);
056            server.registerMBean(object, objectName);
057            LOG.info(name + " JMX mbean registered: " + object);
058        } catch (final MalformedObjectNameException e) {
059            throw new RuntimeException(e);
060        } catch (final NullPointerException e) {
061            throw new RuntimeException(e);
062        } catch (final InstanceAlreadyExistsException e) {
063            LOG.info(name + " JMX mbean already registered: " + object);
064        } catch (final MBeanRegistrationException e) {
065            throw new RuntimeException(e);
066        } catch (final NotCompliantMBeanException e) {
067            throw new RuntimeException(e);
068        }
069
070    }
071}
072
073// Copyright (c) Naked Objects Group Ltd.