001 /***************************************************************************** 002 * Copyright (C) NanoContainer Organization. All rights reserved. * 003 * ------------------------------------------------------------------------- * 004 * The software in this package is published under the terms of the BSD * 005 * style license a copy of which has been included with this distribution in * 006 * the LICENSE.txt file. * 007 * * 008 * Original code by Joerg Schaible * 009 *****************************************************************************/ 010 011 package org.picocontainer.gems.jmx; 012 013 import javax.management.DynamicMBean; 014 import javax.management.MalformedObjectNameException; 015 import javax.management.ObjectName; 016 017 import org.picocontainer.ComponentAdapter; 018 import org.picocontainer.PicoContainer; 019 020 021 /** 022 * DynamicMBeanProvider, that will provide a component directly if it is already a {@link DynamicMBean}. 023 * @author Jörg Schaible 024 */ 025 public class DynamicMBeanComponentProvider implements DynamicMBeanProvider { 026 027 private final ObjectNameFactory objectNameFactory; 028 029 /** 030 * Construct a DynamicMBeanComponentProvider. This instance will use a {@link TypedObjectNameFactory} and register 031 * all MBeans in the default domain of the {@link javax.management.MBeanServer}. 032 */ 033 public DynamicMBeanComponentProvider() { 034 this(new TypedObjectNameFactory()); 035 } 036 037 /** 038 * Construct a DynamicMBeanComponentProvider with a specified ObjectNameFactory. 039 * @param factory The {@link ObjectNameFactory}. 040 */ 041 public DynamicMBeanComponentProvider(final ObjectNameFactory factory) { 042 if (factory == null) { 043 throw new NullPointerException("ObjectFactoryName is null"); 044 } 045 objectNameFactory = factory; 046 } 047 048 /** 049 * Provide the component itself as {@link DynamicMBean} if it is one and if an {@link ObjectName} can be created. 050 * @see org.picocontainer.gems.jmx.DynamicMBeanProvider#provide(org.picocontainer.PicoContainer, 051 * org.picocontainer.ComponentAdapter) 052 */ 053 public JMXRegistrationInfo provide(final PicoContainer picoContainer, final ComponentAdapter componentAdapter) { 054 if (DynamicMBean.class.isAssignableFrom(componentAdapter.getComponentImplementation())) { 055 final DynamicMBean mBean = (DynamicMBean)componentAdapter.getComponentInstance(picoContainer,null); 056 try { 057 final ObjectName objectName = objectNameFactory.create(componentAdapter.getComponentKey(), mBean); 058 if (objectName != null) { 059 return new JMXRegistrationInfo(objectName, mBean); 060 } 061 } catch (final MalformedObjectNameException e) { 062 throw new JMXRegistrationException("Cannot create ObjectName for component '" 063 + componentAdapter.getComponentKey() 064 + "'", e); 065 } 066 } 067 return null; 068 } 069 }