ManagementFactory.java 34.4 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
7
 * published by the Free Software Foundation.  Oracle designates this
D
duke 已提交
8
 * particular file as subject to the "Classpath" exception as provided
9
 * by Oracle in the LICENSE file that accompanied this code.
D
duke 已提交
10 11 12 13 14 15 16 17 18 19 20
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
21 22 23
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
D
duke 已提交
24 25 26
 */

package java.lang.management;
27
import javax.management.DynamicMBean;
D
duke 已提交
28 29
import javax.management.MBeanServer;
import javax.management.MBeanServerConnection;
30
import javax.management.MBeanServerFactory;
D
duke 已提交
31
import javax.management.MBeanServerPermission;
32 33
import javax.management.NotificationEmitter;
import javax.management.ObjectInstance;
D
duke 已提交
34
import javax.management.ObjectName;
35
import javax.management.InstanceAlreadyExistsException;
D
duke 已提交
36 37
import javax.management.InstanceNotFoundException;
import javax.management.MalformedObjectNameException;
38 39 40 41 42
import javax.management.MBeanRegistrationException;
import javax.management.NotCompliantMBeanException;
import javax.management.StandardEmitterMBean;
import javax.management.StandardMBean;
import java.util.Collections;
D
duke 已提交
43
import java.util.List;
44
import java.util.Set;
45
import java.util.HashMap;
46
import java.util.HashSet;
47
import java.util.Map;
D
duke 已提交
48 49 50
import java.security.AccessController;
import java.security.Permission;
import java.security.PrivilegedAction;
51 52
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
D
duke 已提交
53
import javax.management.JMX;
54
import sun.management.ManagementFactoryHelper;
D
duke 已提交
55 56

/**
57
 * The {@code ManagementFactory} class is a factory class for getting
D
duke 已提交
58 59
 * managed beans for the Java platform.
 * This class consists of static methods each of which returns
60
 * one or more <i>platform MXBeans</i> representing
D
duke 已提交
61 62
 * the management interface of a component of the Java virtual
 * machine.
R
rriggs 已提交
63
 *
64
 * <h3><a name="MXBean">Platform MXBeans</a></h3>
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
 * <p>
 * A platform MXBean is a <i>managed bean</i> that
 * conforms to the <a href="../../../javax/management/package-summary.html">JMX</a>
 * Instrumentation Specification and only uses a set of basic data types.
 * A JMX management application and the {@linkplain
 * #getPlatformMBeanServer platform MBeanServer}
 * can interoperate without requiring classes for MXBean specific
 * data types.
 * The data types being transmitted between the JMX connector
 * server and the connector client are
 * {@linkplain javax.management.openmbean.OpenType open types}
 * and this allows interoperation across versions.
 * See <a href="../../../javax/management/MXBean.html#MXBean-spec">
 * the specification of MXBeans</a> for details.
 *
 * <a name="MXBeanNames"></a>
 * <p>Each platform MXBean is a {@link PlatformManagedObject}
 * and it has a unique
 * {@link javax.management.ObjectName ObjectName} for
 * registration in the platform {@code MBeanServer} as returned by
 * by the {@link PlatformManagedObject#getObjectName getObjectName}
 * method.
D
duke 已提交
87 88 89
 *
 * <p>
 * An application can access a platform MXBean in the following ways:
90
 * <h4>1. Direct access to an MXBean interface</h4>
91
 * <blockquote>
D
duke 已提交
92
 * <ul>
93 94 95 96
 *     <li>Get an MXBean instance by calling the
 *         {@link #getPlatformMXBean(Class) getPlatformMXBean} or
 *         {@link #getPlatformMXBeans(Class) getPlatformMXBeans} method
 *         and access the MXBean locally in the running
D
duke 已提交
97 98 99 100
 *         virtual machine.
 *         </li>
 *     <li>Construct an MXBean proxy instance that forwards the
 *         method calls to a given {@link MBeanServer MBeanServer} by calling
101 102 103 104 105
 *         the {@link #getPlatformMXBean(MBeanServerConnection, Class)} or
 *         {@link #getPlatformMXBeans(MBeanServerConnection, Class)} method.
 *         The {@link #newPlatformMXBeanProxy newPlatformMXBeanProxy} method
 *         can also be used to construct an MXBean proxy instance of
 *         a given {@code ObjectName}.
D
duke 已提交
106 107 108
 *         A proxy is typically constructed to remotely access
 *         an MXBean of another running virtual machine.
 *         </li>
109
 * </ul>
110
 * <h4>2. Indirect access to an MXBean interface via MBeanServer</h4>
111 112 113
 * <ul>
 *     <li>Go through the platform {@code MBeanServer} to access MXBeans
 *         locally or a specific <tt>MBeanServerConnection</tt> to access
D
duke 已提交
114 115 116 117 118 119 120
 *         MXBeans remotely.
 *         The attributes and operations of an MXBean use only
 *         <em>JMX open types</em> which include basic data types,
 *         {@link javax.management.openmbean.CompositeData CompositeData},
 *         and {@link javax.management.openmbean.TabularData TabularData}
 *         defined in
 *         {@link javax.management.openmbean.OpenType OpenType}.
121 122 123
 *         The mapping is specified in
 *         the {@linkplain javax.management.MXBean MXBean} specification
 *         for details.
D
duke 已提交
124 125
 *        </li>
 * </ul>
126
 * </blockquote>
D
duke 已提交
127 128
 *
 * <p>
129 130 131 132
 * The {@link #getPlatformManagementInterfaces getPlatformManagementInterfaces}
 * method returns all management interfaces supported in the Java virtual machine
 * including the standard management interfaces listed in the tables
 * below as well as the management interfaces extended by the JDK implementation.
D
duke 已提交
133 134 135 136 137
 * <p>
 * A Java virtual machine has a single instance of the following management
 * interfaces:
 *
 * <blockquote>
138
 * <table border summary="The list of Management Interfaces and their single instances">
D
duke 已提交
139 140 141 142 143 144 145
 * <tr>
 * <th>Management Interface</th>
 * <th>ObjectName</th>
 * </tr>
 * <tr>
 * <td> {@link ClassLoadingMXBean} </td>
 * <td> {@link #CLASS_LOADING_MXBEAN_NAME
146
 *             java.lang:type=ClassLoading}</td>
D
duke 已提交
147 148 149 150
 * </tr>
 * <tr>
 * <td> {@link MemoryMXBean} </td>
 * <td> {@link #MEMORY_MXBEAN_NAME
151
 *             java.lang:type=Memory}</td>
D
duke 已提交
152 153 154 155
 * </tr>
 * <tr>
 * <td> {@link ThreadMXBean} </td>
 * <td> {@link #THREAD_MXBEAN_NAME
156
 *             java.lang:type=Threading}</td>
D
duke 已提交
157 158 159 160
 * </tr>
 * <tr>
 * <td> {@link RuntimeMXBean} </td>
 * <td> {@link #RUNTIME_MXBEAN_NAME
161
 *             java.lang:type=Runtime}</td>
D
duke 已提交
162 163 164 165
 * </tr>
 * <tr>
 * <td> {@link OperatingSystemMXBean} </td>
 * <td> {@link #OPERATING_SYSTEM_MXBEAN_NAME
166 167 168 169 170 171
 *             java.lang:type=OperatingSystem}</td>
 * </tr>
 * <tr>
 * <td> {@link PlatformLoggingMXBean} </td>
 * <td> {@link java.util.logging.LogManager#LOGGING_MXBEAN_NAME
 *             java.util.logging:type=Logging}</td>
D
duke 已提交
172 173 174 175 176 177 178 179 180
 * </tr>
 * </table>
 * </blockquote>
 *
 * <p>
 * A Java virtual machine has zero or a single instance of
 * the following management interfaces.
 *
 * <blockquote>
181
 * <table border summary="The list of Management Interfaces and their single instances">
D
duke 已提交
182 183 184 185 186 187 188
 * <tr>
 * <th>Management Interface</th>
 * <th>ObjectName</th>
 * </tr>
 * <tr>
 * <td> {@link CompilationMXBean} </td>
 * <td> {@link #COMPILATION_MXBEAN_NAME
189
 *             java.lang:type=Compilation}</td>
D
duke 已提交
190 191 192 193 194 195 196 197
 * </tr>
 * </table>
 * </blockquote>
 *
 * <p>
 * A Java virtual machine may have one or more instances of the following
 * management interfaces.
 * <blockquote>
198
 * <table border summary="The list of Management Interfaces and their single instances">
D
duke 已提交
199 200 201 202 203 204 205
 * <tr>
 * <th>Management Interface</th>
 * <th>ObjectName</th>
 * </tr>
 * <tr>
 * <td> {@link GarbageCollectorMXBean} </td>
 * <td> {@link #GARBAGE_COLLECTOR_MXBEAN_DOMAIN_TYPE
206
 *             java.lang:type=GarbageCollector}<tt>,name=</tt><i>collector's name</i></td>
D
duke 已提交
207 208 209 210
 * </tr>
 * <tr>
 * <td> {@link MemoryManagerMXBean} </td>
 * <td> {@link #MEMORY_MANAGER_MXBEAN_DOMAIN_TYPE
211
 *             java.lang:type=MemoryManager}<tt>,name=</tt><i>manager's name</i></td>
D
duke 已提交
212 213 214 215
 * </tr>
 * <tr>
 * <td> {@link MemoryPoolMXBean} </td>
 * <td> {@link #MEMORY_POOL_MXBEAN_DOMAIN_TYPE
216 217 218 219 220
 *             java.lang:type=MemoryPool}<tt>,name=</tt><i>pool's name</i></td>
 * </tr>
 * <tr>
 * <td> {@link BufferPoolMXBean} </td>
 * <td> {@code java.nio:type=BufferPool,name=}<i>pool name</i></td>
D
duke 已提交
221 222 223 224 225
 * </tr>
 * </table>
 * </blockquote>
 *
 * @see <a href="../../../javax/management/package-summary.html">
226
 *      JMX Specification</a>
D
duke 已提交
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
 * @see <a href="package-summary.html#examples">
 *      Ways to Access Management Metrics</a>
 * @see javax.management.MXBean
 *
 * @author  Mandy Chung
 * @since   1.5
 */
public class ManagementFactory {
    // A class with only static fields and methods.
    private ManagementFactory() {};

    /**
     * String representation of the
     * <tt>ObjectName</tt> for the {@link ClassLoadingMXBean}.
     */
    public final static String CLASS_LOADING_MXBEAN_NAME =
        "java.lang:type=ClassLoading";

    /**
     * String representation of the
     * <tt>ObjectName</tt> for the {@link CompilationMXBean}.
     */
    public final static String COMPILATION_MXBEAN_NAME =
        "java.lang:type=Compilation";

    /**
     * String representation of the
     * <tt>ObjectName</tt> for the {@link MemoryMXBean}.
     */
    public final static String MEMORY_MXBEAN_NAME =
        "java.lang:type=Memory";

    /**
     * String representation of the
     * <tt>ObjectName</tt> for the {@link OperatingSystemMXBean}.
     */
    public final static String OPERATING_SYSTEM_MXBEAN_NAME =
        "java.lang:type=OperatingSystem";

    /**
     * String representation of the
     * <tt>ObjectName</tt> for the {@link RuntimeMXBean}.
     */
    public final static String RUNTIME_MXBEAN_NAME =
        "java.lang:type=Runtime";

    /**
     * String representation of the
     * <tt>ObjectName</tt> for the {@link ThreadMXBean}.
     */
    public final static String THREAD_MXBEAN_NAME =
        "java.lang:type=Threading";

    /**
     * The domain name and the type key property in
     * the <tt>ObjectName</tt> for a {@link GarbageCollectorMXBean}.
     * The unique <tt>ObjectName</tt> for a <tt>GarbageCollectorMXBean</tt>
     * can be formed by appending this string with
     * "<tt>,name=</tt><i>collector's name</i>".
     */
    public final static String GARBAGE_COLLECTOR_MXBEAN_DOMAIN_TYPE =
        "java.lang:type=GarbageCollector";

    /**
     * The domain name and the type key property in
     * the <tt>ObjectName</tt> for a {@link MemoryManagerMXBean}.
     * The unique <tt>ObjectName</tt> for a <tt>MemoryManagerMXBean</tt>
     * can be formed by appending this string with
     * "<tt>,name=</tt><i>manager's name</i>".
     */
    public final static String MEMORY_MANAGER_MXBEAN_DOMAIN_TYPE=
        "java.lang:type=MemoryManager";

    /**
     * The domain name and the type key property in
     * the <tt>ObjectName</tt> for a {@link MemoryPoolMXBean}.
     * The unique <tt>ObjectName</tt> for a <tt>MemoryPoolMXBean</tt>
     * can be formed by appending this string with
     * <tt>,name=</tt><i>pool's name</i>.
     */
    public final static String MEMORY_POOL_MXBEAN_DOMAIN_TYPE=
        "java.lang:type=MemoryPool";

    /**
     * Returns the managed bean for the class loading system of
     * the Java virtual machine.
     *
     * @return a {@link ClassLoadingMXBean} object for
     * the Java virtual machine.
     */
    public static ClassLoadingMXBean getClassLoadingMXBean() {
318
        return ManagementFactoryHelper.getClassLoadingMXBean();
D
duke 已提交
319 320 321 322 323 324 325 326 327
    }

    /**
     * Returns the managed bean for the memory system of
     * the Java virtual machine.
     *
     * @return a {@link MemoryMXBean} object for the Java virtual machine.
     */
    public static MemoryMXBean getMemoryMXBean() {
328
        return ManagementFactoryHelper.getMemoryMXBean();
D
duke 已提交
329 330 331 332 333 334 335 336 337
    }

    /**
     * Returns the managed bean for the thread system of
     * the Java virtual machine.
     *
     * @return a {@link ThreadMXBean} object for the Java virtual machine.
     */
    public static ThreadMXBean getThreadMXBean() {
338
        return ManagementFactoryHelper.getThreadMXBean();
D
duke 已提交
339 340 341 342 343 344 345 346 347 348
    }

    /**
     * Returns the managed bean for the runtime system of
     * the Java virtual machine.
     *
     * @return a {@link RuntimeMXBean} object for the Java virtual machine.

     */
    public static RuntimeMXBean getRuntimeMXBean() {
349
        return ManagementFactoryHelper.getRuntimeMXBean();
D
duke 已提交
350 351 352 353 354 355 356 357 358 359 360 361
    }

    /**
     * Returns the managed bean for the compilation system of
     * the Java virtual machine.  This method returns <tt>null</tt>
     * if the Java virtual machine has no compilation system.
     *
     * @return a {@link CompilationMXBean} object for the Java virtual
     *   machine or <tt>null</tt> if the Java virtual machine has
     *   no compilation system.
     */
    public static CompilationMXBean getCompilationMXBean() {
362
        return ManagementFactoryHelper.getCompilationMXBean();
D
duke 已提交
363 364 365 366 367 368 369 370 371 372
    }

    /**
     * Returns the managed bean for the operating system on which
     * the Java virtual machine is running.
     *
     * @return an {@link OperatingSystemMXBean} object for
     * the Java virtual machine.
     */
    public static OperatingSystemMXBean getOperatingSystemMXBean() {
373
        return ManagementFactoryHelper.getOperatingSystemMXBean();
D
duke 已提交
374 375 376 377 378 379 380 381 382 383 384 385
    }

    /**
     * Returns a list of {@link MemoryPoolMXBean} objects in the
     * Java virtual machine.
     * The Java virtual machine can have one or more memory pools.
     * It may add or remove memory pools during execution.
     *
     * @return a list of <tt>MemoryPoolMXBean</tt> objects.
     *
     */
    public static List<MemoryPoolMXBean> getMemoryPoolMXBeans() {
386
        return ManagementFactoryHelper.getMemoryPoolMXBeans();
D
duke 已提交
387 388 389 390 391 392 393 394 395 396 397 398
    }

    /**
     * Returns a list of {@link MemoryManagerMXBean} objects
     * in the Java virtual machine.
     * The Java virtual machine can have one or more memory managers.
     * It may add or remove memory managers during execution.
     *
     * @return a list of <tt>MemoryManagerMXBean</tt> objects.
     *
     */
    public static List<MemoryManagerMXBean> getMemoryManagerMXBeans() {
399
        return ManagementFactoryHelper.getMemoryManagerMXBeans();
D
duke 已提交
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
    }


    /**
     * Returns a list of {@link GarbageCollectorMXBean} objects
     * in the Java virtual machine.
     * The Java virtual machine may have one or more
     * <tt>GarbageCollectorMXBean</tt> objects.
     * It may add or remove <tt>GarbageCollectorMXBean</tt>
     * during execution.
     *
     * @return a list of <tt>GarbageCollectorMXBean</tt> objects.
     *
     */
    public static List<GarbageCollectorMXBean> getGarbageCollectorMXBeans() {
415
        return ManagementFactoryHelper.getGarbageCollectorMXBeans();
D
duke 已提交
416 417 418 419 420 421
    }

    private static MBeanServer platformMBeanServer;
    /**
     * Returns the platform {@link javax.management.MBeanServer MBeanServer}.
     * On the first call to this method, it first creates the platform
422
     * {@code MBeanServer} by calling the
D
duke 已提交
423 424
     * {@link javax.management.MBeanServerFactory#createMBeanServer
     * MBeanServerFactory.createMBeanServer}
425 426 427
     * method and registers each platform MXBean in this platform
     * {@code MBeanServer} with its
     * {@link PlatformManagedObject#getObjectName ObjectName}.
D
duke 已提交
428
     * This method, in subsequent calls, will simply return the
429
     * initially created platform {@code MBeanServer}.
D
duke 已提交
430 431 432 433 434
     * <p>
     * MXBeans that get created and destroyed dynamically, for example,
     * memory {@link MemoryPoolMXBean pools} and
     * {@link MemoryManagerMXBean managers},
     * will automatically be registered and deregistered into the platform
435
     * {@code MBeanServer}.
D
duke 已提交
436
     * <p>
437 438
     * If the system property {@code javax.management.builder.initial}
     * is set, the platform {@code MBeanServer} creation will be done
D
duke 已提交
439 440 441 442 443 444
     * by the specified {@link javax.management.MBeanServerBuilder}.
     * <p>
     * It is recommended that this platform MBeanServer also be used
     * to register other application managed beans
     * besides the platform MXBeans.
     * This will allow all MBeans to be published through the same
445
     * {@code MBeanServer} and hence allow for easier network publishing
D
duke 已提交
446 447 448
     * and discovery.
     * Name conflicts with the platform MXBeans should be avoided.
     *
449 450
     * @return the platform {@code MBeanServer}; the platform
     *         MXBeans are registered into the platform {@code MBeanServer}
D
duke 已提交
451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467
     *         at the first time this method is called.
     *
     * @exception SecurityException if there is a security manager
     * and the caller does not have the permission required by
     * {@link javax.management.MBeanServerFactory#createMBeanServer}.
     *
     * @see javax.management.MBeanServerFactory
     * @see javax.management.MBeanServerFactory#createMBeanServer
     */
    public static synchronized MBeanServer getPlatformMBeanServer() {
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            Permission perm = new MBeanServerPermission("createMBeanServer");
            sm.checkPermission(perm);
        }

        if (platformMBeanServer == null) {
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
            platformMBeanServer = MBeanServerFactory.createMBeanServer();
            for (PlatformComponent pc : PlatformComponent.values()) {
                List<? extends PlatformManagedObject> list =
                    pc.getMXBeans(pc.getMXBeanInterface());
                for (PlatformManagedObject o : list) {
                    // Each PlatformComponent represents one management
                    // interface. Some MXBean may extend another one.
                    // The MXBean instances for one platform component
                    // (returned by pc.getMXBeans()) might be also
                    // the MXBean instances for another platform component.
                    // e.g. com.sun.management.GarbageCollectorMXBean
                    //
                    // So need to check if an MXBean instance is registered
                    // before registering into the platform MBeanServer
                    if (!platformMBeanServer.isRegistered(o.getObjectName())) {
                        addMXBean(platformMBeanServer, o);
                    }
                }
            }
487 488 489 490 491
            HashMap<ObjectName, DynamicMBean> dynmbeans =
                    ManagementFactoryHelper.getPlatformDynamicMBeans();
            for (Map.Entry<ObjectName, DynamicMBean> e : dynmbeans.entrySet()) {
                addDynamicMBean(platformMBeanServer, e.getValue(), e.getKey());
            }
D
duke 已提交
492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
        }
        return platformMBeanServer;
    }

    /**
     * Returns a proxy for a platform MXBean interface of a
     * given <a href="#MXBeanNames">MXBean name</a>
     * that forwards its method calls through the given
     * <tt>MBeanServerConnection</tt>.
     *
     * <p>This method is equivalent to:
     * <blockquote>
     * {@link java.lang.reflect.Proxy#newProxyInstance
     *        Proxy.newProxyInstance}<tt>(mxbeanInterface.getClassLoader(),
     *        new Class[] { mxbeanInterface }, handler)</tt>
     * </blockquote>
     *
     * where <tt>handler</tt> is an {@link java.lang.reflect.InvocationHandler
     * InvocationHandler} to which method invocations to the MXBean interface
     * are dispatched. This <tt>handler</tt> converts an input parameter
     * from an MXBean data type to its mapped open type before forwarding
     * to the <tt>MBeanServer</tt> and converts a return value from
     * an MXBean method call through the <tt>MBeanServer</tt>
     * from an open type to the corresponding return type declared in
     * the MXBean interface.
     *
     * <p>
     * If the MXBean is a notification emitter (i.e.,
     * it implements
     * {@link javax.management.NotificationEmitter NotificationEmitter}),
     * both the <tt>mxbeanInterface</tt> and <tt>NotificationEmitter</tt>
     * will be implemented by this proxy.
     *
     * <p>
     * <b>Notes:</b>
     * <ol>
     * <li>Using an MXBean proxy is a convenience remote access to
     * a platform MXBean of a running virtual machine.  All method
     * calls to the MXBean proxy are forwarded to an
     * <tt>MBeanServerConnection</tt> where
     * {@link java.io.IOException IOException} may be thrown
     * when the communication problem occurs with the connector server.
     * An application remotely accesses the platform MXBeans using
     * proxy should prepare to catch <tt>IOException</tt> as if
     * accessing with the <tt>MBeanServerConnector</tt> interface.</li>
     *
     * <li>When a client application is designed to remotely access MXBeans
     * for a running virtual machine whose version is different than
     * the version on which the application is running,
     * it should prepare to catch
     * {@link java.io.InvalidObjectException InvalidObjectException}
     * which is thrown when an MXBean proxy receives a name of an
     * enum constant which is missing in the enum class loaded in
     * the client application. </li>
     *
     * <li>{@link javax.management.MBeanServerInvocationHandler
     * MBeanServerInvocationHandler} or its
     * {@link javax.management.MBeanServerInvocationHandler#newProxyInstance
     * newProxyInstance} method cannot be used to create
     * a proxy for a platform MXBean. The proxy object created
     * by <tt>MBeanServerInvocationHandler</tt> does not handle
     * the properties of the platform MXBeans described in
     * the <a href="#MXBean">class specification</a>.
     *</li>
     * </ol>
     *
     * @param connection the <tt>MBeanServerConnection</tt> to forward to.
     * @param mxbeanName the name of a platform MXBean within
     * <tt>connection</tt> to forward to. <tt>mxbeanName</tt> must be
     * in the format of {@link ObjectName ObjectName}.
     * @param mxbeanInterface the MXBean interface to be implemented
     * by the proxy.
564 565 566 567 568 569
     * @param <T> an {@code mxbeanInterface} type parameter
     *
     * @return a proxy for a platform MXBean interface of a
     * given <a href="#MXBeanNames">MXBean name</a>
     * that forwards its method calls through the given
     * <tt>MBeanServerConnection</tt>, or {@code null} if not exist.
D
duke 已提交
570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
     *
     * @throws IllegalArgumentException if
     * <ul>
     * <li><tt>mxbeanName</tt> is not with a valid
     *     {@link ObjectName ObjectName} format, or</li>
     * <li>the named MXBean in the <tt>connection</tt> is
     *     not a MXBean provided by the platform, or</li>
     * <li>the named MXBean is not registered in the
     *     <tt>MBeanServerConnection</tt>, or</li>
     * <li>the named MXBean is not an instance of the given
     *     <tt>mxbeanInterface</tt></li>
     * </ul>
     *
     * @throws java.io.IOException if a communication problem
     * occurred when accessing the <tt>MBeanServerConnection</tt>.
     */
    public static <T> T
        newPlatformMXBeanProxy(MBeanServerConnection connection,
                               String mxbeanName,
                               Class<T> mxbeanInterface)
            throws java.io.IOException {

        // Only allow MXBean interfaces from rt.jar loaded by the
        // bootstrap class loader
594 595
        final Class<?> cls = mxbeanInterface;
        ClassLoader loader =
D
duke 已提交
596 597
            AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
                public ClassLoader run() {
598
                    return cls.getClassLoader();
D
duke 已提交
599 600
                }
            });
601
        if (!sun.misc.VM.isSystemDomainLoader(loader)) {
D
duke 已提交
602 603 604 605 606 607
            throw new IllegalArgumentException(mxbeanName +
                " is not a platform MXBean");
        }

        try {
            final ObjectName objName = new ObjectName(mxbeanName);
608
            // skip the isInstanceOf check for LoggingMXBean
609
            String intfName = mxbeanInterface.getName();
610
            if (!connection.isInstanceOf(objName, intfName)) {
D
duke 已提交
611
                throw new IllegalArgumentException(mxbeanName +
612
                    " is not an instance of " + mxbeanInterface);
D
duke 已提交
613 614 615 616 617 618 619 620 621
            }

            final Class[] interfaces;
            // check if the registered MBean is a notification emitter
            boolean emitter = connection.isInstanceOf(objName, NOTIF_EMITTER);

            // create an MXBean proxy
            return JMX.newMXBeanProxy(connection, objName, mxbeanInterface,
                                      emitter);
622 623
        } catch (InstanceNotFoundException|MalformedObjectNameException e) {
            throw new IllegalArgumentException(e);
D
duke 已提交
624 625 626
        }
    }

627
    /**
628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643
     * Returns the platform MXBean implementing
     * the given {@code mxbeanInterface} which is specified
     * to have one single instance in the Java virtual machine.
     * This method may return {@code null} if the management interface
     * is not implemented in the Java virtual machine (for example,
     * a Java virtual machine with no compilation system does not
     * implement {@link CompilationMXBean});
     * otherwise, this method is equivalent to calling:
     * <pre>
     *    {@link #getPlatformMXBeans(Class)
     *      getPlatformMXBeans(mxbeanInterface)}.get(0);
     * </pre>
     *
     * @param mxbeanInterface a management interface for a platform
     *     MXBean with one single instance in the Java virtual machine
     *     if implemented.
644
     * @param <T> an {@code mxbeanInterface} type parameter
645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670
     *
     * @return the platform MXBean that implements
     * {@code mxbeanInterface}, or {@code null} if not exist.
     *
     * @throws IllegalArgumentException if {@code mxbeanInterface}
     * is not a platform management interface or
     * not a singleton platform MXBean.
     *
     * @since 1.7
     */
    public static <T extends PlatformManagedObject>
            T getPlatformMXBean(Class<T> mxbeanInterface) {
        PlatformComponent pc = PlatformComponent.getPlatformComponent(mxbeanInterface);
        if (pc == null)
            throw new IllegalArgumentException(mxbeanInterface.getName() +
                " is not a platform management interface");
        if (!pc.isSingleton())
            throw new IllegalArgumentException(mxbeanInterface.getName() +
                " can have zero or more than one instances");

        return pc.getSingletonMXBean(mxbeanInterface);
    }

    /**
     * Returns the list of platform MXBeans implementing
     * the given {@code mxbeanInterface} in the Java
671 672 673 674
     * virtual machine.
     * The returned list may contain zero, one, or more instances.
     * The number of instances in the returned list is defined
     * in the specification of the given management interface.
675 676
     * The order is undefined and there is no guarantee that
     * the list returned is in the same order as previous invocations.
677 678 679
     *
     * @param mxbeanInterface a management interface for a platform
     *                        MXBean
680
     * @param <T> an {@code mxbeanInterface} type parameter
681
     *
682
     * @return the list of platform MXBeans that implement
683 684 685
     * {@code mxbeanInterface}.
     *
     * @throws IllegalArgumentException if {@code mxbeanInterface}
686
     * is not a platform management interface.
687 688 689 690 691
     *
     * @since 1.7
     */
    public static <T extends PlatformManagedObject> List<T>
            getPlatformMXBeans(Class<T> mxbeanInterface) {
692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717
        PlatformComponent pc = PlatformComponent.getPlatformComponent(mxbeanInterface);
        if (pc == null)
            throw new IllegalArgumentException(mxbeanInterface.getName() +
                " is not a platform management interface");
        return Collections.unmodifiableList(pc.getMXBeans(mxbeanInterface));
    }

    /**
     * Returns the platform MXBean proxy for
     * {@code mxbeanInterface} which is specified to have one single
     * instance in a Java virtual machine and the proxy will
     * forward the method calls through the given {@code MBeanServerConnection}.
     * This method may return {@code null} if the management interface
     * is not implemented in the Java virtual machine being monitored
     * (for example, a Java virtual machine with no compilation system
     * does not implement {@link CompilationMXBean});
     * otherwise, this method is equivalent to calling:
     * <pre>
     *     {@link #getPlatformMXBeans(MBeanServerConnection, Class)
     *        getPlatformMXBeans(connection, mxbeanInterface)}.get(0);
     * </pre>
     *
     * @param connection the {@code MBeanServerConnection} to forward to.
     * @param mxbeanInterface a management interface for a platform
     *     MXBean with one single instance in the Java virtual machine
     *     being monitored, if implemented.
718
     * @param <T> an {@code mxbeanInterface} type parameter
719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746
     *
     * @return the platform MXBean proxy for
     * forwarding the method calls of the {@code mxbeanInterface}
     * through the given {@code MBeanServerConnection},
     * or {@code null} if not exist.
     *
     * @throws IllegalArgumentException if {@code mxbeanInterface}
     * is not a platform management interface or
     * not a singleton platform MXBean.
     * @throws java.io.IOException if a communication problem
     * occurred when accessing the {@code MBeanServerConnection}.
     *
     * @see #newPlatformMXBeanProxy
     * @since 1.7
     */
    public static <T extends PlatformManagedObject>
            T getPlatformMXBean(MBeanServerConnection connection,
                                Class<T> mxbeanInterface)
        throws java.io.IOException
    {
        PlatformComponent pc = PlatformComponent.getPlatformComponent(mxbeanInterface);
        if (pc == null)
            throw new IllegalArgumentException(mxbeanInterface.getName() +
                " is not a platform management interface");
        if (!pc.isSingleton())
            throw new IllegalArgumentException(mxbeanInterface.getName() +
                " can have zero or more than one instances");
        return pc.getSingletonMXBean(connection, mxbeanInterface);
747 748 749 750 751 752 753 754 755
    }

    /**
     * Returns the list of the platform MXBean proxies for
     * forwarding the method calls of the {@code mxbeanInterface}
     * through the given {@code MBeanServerConnection}.
     * The returned list may contain zero, one, or more instances.
     * The number of instances in the returned list is defined
     * in the specification of the given management interface.
756 757
     * The order is undefined and there is no guarantee that
     * the list returned is in the same order as previous invocations.
758 759 760 761
     *
     * @param connection the {@code MBeanServerConnection} to forward to.
     * @param mxbeanInterface a management interface for a platform
     *                        MXBean
762
     * @param <T> an {@code mxbeanInterface} type parameter
763 764 765 766 767 768
     *
     * @return the list of platform MXBean proxies for
     * forwarding the method calls of the {@code mxbeanInterface}
     * through the given {@code MBeanServerConnection}.
     *
     * @throws IllegalArgumentException if {@code mxbeanInterface}
769
     * is not a platform management interface.
770 771 772 773
     *
     * @throws java.io.IOException if a communication problem
     * occurred when accessing the {@code MBeanServerConnection}.
     *
774
     * @see #newPlatformMXBeanProxy
775 776 777
     * @since 1.7
     */
    public static <T extends PlatformManagedObject>
778 779
            List<T> getPlatformMXBeans(MBeanServerConnection connection,
                                       Class<T> mxbeanInterface)
780 781
        throws java.io.IOException
    {
782 783 784 785
        PlatformComponent pc = PlatformComponent.getPlatformComponent(mxbeanInterface);
        if (pc == null) {
            throw new IllegalArgumentException(mxbeanInterface.getName() +
                " is not a platform management interface");
786
        }
787
        return Collections.unmodifiableList(pc.getMXBeans(connection, mxbeanInterface));
788 789 790
    }

    /**
791
     * Returns the set of {@code Class} objects, subinterface of
792 793 794 795
     * {@link PlatformManagedObject}, representing
     * all management interfaces for
     * monitoring and managing the Java platform.
     *
796
     * @return the set of {@code Class} objects, subinterface of
797 798 799 800 801 802
     * {@link PlatformManagedObject} representing
     * the management interfaces for
     * monitoring and managing the Java platform.
     *
     * @since 1.7
     */
803 804 805 806
    public static Set<Class<? extends PlatformManagedObject>>
           getPlatformManagementInterfaces()
    {
        Set<Class<? extends PlatformManagedObject>> result =
807
            new HashSet<>();
808 809 810
        for (PlatformComponent component: PlatformComponent.values()) {
            result.add(component.getMXBeanInterface());
        }
811
        return Collections.unmodifiableSet(result);
812 813
    }

D
duke 已提交
814 815
    private static final String NOTIF_EMITTER =
        "javax.management.NotificationEmitter";
816 817 818 819 820 821 822 823 824 825 826

    /**
     * Registers an MXBean.
     */
    private static void addMXBean(final MBeanServer mbs, final PlatformManagedObject pmo) {
        // Make DynamicMBean out of MXBean by wrapping it with a StandardMBean
        try {
            AccessController.doPrivileged(new PrivilegedExceptionAction<Void>() {
                public Void run() throws InstanceAlreadyExistsException,
                                         MBeanRegistrationException,
                                         NotCompliantMBeanException {
D
dfuchs 已提交
827 828 829 830 831 832 833 834 835
                    final DynamicMBean dmbean;
                    if (pmo instanceof DynamicMBean) {
                        dmbean = DynamicMBean.class.cast(pmo);
                    } else if (pmo instanceof NotificationEmitter) {
                        dmbean = new StandardEmitterMBean(pmo, null, true, (NotificationEmitter) pmo);
                    } else {
                        dmbean = new StandardMBean(pmo, null, true);
                    }

836 837 838 839 840 841 842 843 844
                    mbs.registerMBean(dmbean, pmo.getObjectName());
                    return null;
                }
            });
        } catch (PrivilegedActionException e) {
            throw new RuntimeException(e.getException());
        }
    }

845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864
    /**
     * Registers a DynamicMBean.
     */
    private static void addDynamicMBean(final MBeanServer mbs,
                                        final DynamicMBean dmbean,
                                        final ObjectName on) {
        try {
            AccessController.doPrivileged(new PrivilegedExceptionAction<Void>() {
                @Override
                public Void run() throws InstanceAlreadyExistsException,
                                         MBeanRegistrationException,
                                         NotCompliantMBeanException {
                    mbs.registerMBean(dmbean, on);
                    return null;
                }
            });
        } catch (PrivilegedActionException e) {
            throw new RuntimeException(e.getException());
        }
    }
D
duke 已提交
865
}