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.commons.jcs.jcache.jmx; 020 021import javax.management.MBeanServer; 022import javax.management.MBeanServerFactory; 023import javax.management.ObjectName; 024import java.lang.management.ManagementFactory; 025 026public class JMXs 027{ 028 private static final MBeanServer SERVER = findMBeanServer(); 029 030 public static MBeanServer server() 031 { 032 return SERVER; 033 } 034 035 public static void register(final ObjectName on, final Object bean) 036 { 037 if (!SERVER.isRegistered(on)) 038 { 039 try 040 { 041 SERVER.registerMBean(bean, on); 042 } 043 catch (final Exception e) 044 { 045 throw new IllegalStateException(e.getMessage(), e); 046 } 047 } 048 } 049 050 public static void unregister(final ObjectName on) 051 { 052 if (SERVER.isRegistered(on)) 053 { 054 try 055 { 056 SERVER.unregisterMBean(on); 057 } 058 catch (final Exception e) 059 { 060 // no-op 061 } 062 } 063 } 064 065 private static MBeanServer findMBeanServer() 066 { 067 if (System.getProperty("javax.management.builder.initial") != null) 068 { 069 return MBeanServerFactory.createMBeanServer(); 070 } 071 return ManagementFactory.getPlatformMBeanServer(); 072 } 073 074 private JMXs() 075 { 076 // no-op 077 } 078}