Path: blob/master/src/java.management/share/classes/javax/management/MBeanInfo.java
41154 views
/*1* Copyright (c) 1999, 2021, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package javax.management;2627import java.io.IOException;28import java.io.StreamCorruptedException;29import java.io.Serializable;30import java.io.ObjectOutputStream;31import java.io.ObjectInputStream;32import java.lang.reflect.Method;33import java.util.Arrays;34import java.util.Map;35import java.util.WeakHashMap;36import java.security.AccessController;37import java.security.PrivilegedAction;38import java.util.Objects;3940import static javax.management.ImmutableDescriptor.nonNullDescriptor;4142/**43* <p>Describes the management interface exposed by an MBean; that is,44* the set of attributes and operations which are available for45* management operations. Instances of this class are immutable.46* Subclasses may be mutable but this is not recommended.</p>47*48* <p id="info-changed">Usually the {@code MBeanInfo} for any given MBean does49* not change over the lifetime of that MBean. Dynamic MBeans can change their50* {@code MBeanInfo} and in that case it is recommended that they emit a {@link51* Notification} with a {@linkplain Notification#getType() type} of {@code52* "jmx.mbean.info.changed"} and a {@linkplain Notification#getUserData()53* userData} that is the new {@code MBeanInfo}. This is not required, but54* provides a conventional way for clients of the MBean to discover the change.55* See also the <a href="Descriptor.html#immutableInfo">immutableInfo</a> and56* <a href="Descriptor.html#infoTimeout">infoTimeout</a> fields in the {@code57* MBeanInfo} {@link Descriptor}.</p>58*59* <p>The contents of the {@code MBeanInfo} for a Dynamic MBean60* are determined by its {@link DynamicMBean#getMBeanInfo61* getMBeanInfo()} method. This includes Open MBeans and Model62* MBeans, which are kinds of Dynamic MBeans.</p>63*64* <p>The contents of the {@code MBeanInfo} for a Standard MBean65* are determined by the MBean server as follows:</p>66*67* <ul>68*69* <li>{@link #getClassName()} returns the Java class name of the MBean70* object;71*72* <li>{@link #getConstructors()} returns the list of all public73* constructors in that object;74*75* <li>{@link #getAttributes()} returns the list of all attributes76* whose existence is deduced from the presence in the MBean interface77* of a <code>get<i>Name</i></code>, <code>is<i>Name</i></code>, or78* <code>set<i>Name</i></code> method that conforms to the conventions79* for Standard MBeans;80*81* <li>{@link #getOperations()} returns the list of all methods in82* the MBean interface that do not represent attributes;83*84* <li>{@link #getNotifications()} returns an empty array if the MBean85* does not implement the {@link NotificationBroadcaster} interface,86* otherwise the result of calling {@link87* NotificationBroadcaster#getNotificationInfo()} on it;88*89* <li>{@link #getDescriptor()} returns a descriptor containing the contents90* of any descriptor annotations in the MBean interface (see91* {@link DescriptorKey @DescriptorKey}).92*93* </ul>94*95* <p>The description returned by {@link #getDescription()} and the96* descriptions of the contained attributes and operations are not specified.</p>97*98* <p>The remaining details of the {@code MBeanInfo} for a99* Standard MBean are not specified. This includes the description of100* any contained constructors, and notifications; the names101* of parameters to constructors and operations; and the descriptions of102* constructor parameters.</p>103*104* @since 1.5105*/106public class MBeanInfo implements Cloneable, Serializable, DescriptorRead {107108/* Serial version */109static final long serialVersionUID = -6451021435135161911L;110111/**112* @serial The Descriptor for the MBean. This field113* can be null, which is equivalent to an empty Descriptor.114*/115private transient Descriptor descriptor;116117/**118* @serial The human readable description of the class.119*/120private final String description;121122/**123* @serial The MBean qualified name.124*/125private final String className;126127/**128* @serial The MBean attribute descriptors.129*/130private final MBeanAttributeInfo[] attributes;131132/**133* @serial The MBean operation descriptors.134*/135private final MBeanOperationInfo[] operations;136137/**138* @serial The MBean constructor descriptors.139*/140private final MBeanConstructorInfo[] constructors;141142/**143* @serial The MBean notification descriptors.144*/145private final MBeanNotificationInfo[] notifications;146147private transient int hashCode;148149/**150* <p>True if this class is known not to override the array-valued151* getters of MBeanInfo. Obviously true for MBeanInfo itself, and true152* for a subclass where we succeed in reflecting on the methods153* and discover they are not overridden.</p>154*155* <p>The purpose of this variable is to avoid cloning the arrays156* when doing operations like {@link #equals} where we know they157* will not be changed. If a subclass overrides a getter, we158* cannot access the corresponding array directly.</p>159*/160private final transient boolean arrayGettersSafe;161162/**163* Constructs an {@code MBeanInfo}.164*165* @param className The name of the Java class of the MBean described166* by this {@code MBeanInfo}. This value may be any167* syntactically legal Java class name. It does not have to be a168* Java class known to the MBean server or to the MBean's169* ClassLoader. If it is a Java class known to the MBean's170* ClassLoader, it is recommended but not required that the171* class's public methods include those that would appear in a172* Standard MBean implementing the attributes and operations in173* this MBeanInfo.174* @param description A human readable description of the MBean (optional).175* @param attributes The list of exposed attributes of the MBean.176* This may be null with the same effect as a zero-length array.177* @param constructors The list of public constructors of the178* MBean. This may be null with the same effect as a zero-length179* array.180* @param operations The list of operations of the MBean. This181* may be null with the same effect as a zero-length array.182* @param notifications The list of notifications emitted. This183* may be null with the same effect as a zero-length array.184*/185public MBeanInfo(String className,186String description,187MBeanAttributeInfo[] attributes,188MBeanConstructorInfo[] constructors,189MBeanOperationInfo[] operations,190MBeanNotificationInfo[] notifications)191throws IllegalArgumentException {192this(className, description, attributes, constructors, operations,193notifications, null);194}195196/**197* Constructs an {@code MBeanInfo}.198*199* @param className The name of the Java class of the MBean described200* by this {@code MBeanInfo}. This value may be any201* syntactically legal Java class name. It does not have to be a202* Java class known to the MBean server or to the MBean's203* ClassLoader. If it is a Java class known to the MBean's204* ClassLoader, it is recommended but not required that the205* class's public methods include those that would appear in a206* Standard MBean implementing the attributes and operations in207* this MBeanInfo.208* @param description A human readable description of the MBean (optional).209* @param attributes The list of exposed attributes of the MBean.210* This may be null with the same effect as a zero-length array.211* @param constructors The list of public constructors of the212* MBean. This may be null with the same effect as a zero-length213* array.214* @param operations The list of operations of the MBean. This215* may be null with the same effect as a zero-length array.216* @param notifications The list of notifications emitted. This217* may be null with the same effect as a zero-length array.218* @param descriptor The descriptor for the MBean. This may be null219* which is equivalent to an empty descriptor.220*221* @since 1.6222*/223public MBeanInfo(String className,224String description,225MBeanAttributeInfo[] attributes,226MBeanConstructorInfo[] constructors,227MBeanOperationInfo[] operations,228MBeanNotificationInfo[] notifications,229Descriptor descriptor)230throws IllegalArgumentException {231232this.className = className;233234this.description = description;235236if (attributes == null)237attributes = MBeanAttributeInfo.NO_ATTRIBUTES;238this.attributes = attributes;239240if (operations == null)241operations = MBeanOperationInfo.NO_OPERATIONS;242this.operations = operations;243244if (constructors == null)245constructors = MBeanConstructorInfo.NO_CONSTRUCTORS;246this.constructors = constructors;247248if (notifications == null)249notifications = MBeanNotificationInfo.NO_NOTIFICATIONS;250this.notifications = notifications;251252if (descriptor == null)253descriptor = ImmutableDescriptor.EMPTY_DESCRIPTOR;254this.descriptor = descriptor;255256this.arrayGettersSafe =257arrayGettersSafe(this.getClass(), MBeanInfo.class);258}259260/**261* <p>Returns a shallow clone of this instance.262* The clone is obtained by simply calling {@code super.clone()},263* thus calling the default native shallow cloning mechanism264* implemented by {@code Object.clone()}.265* No deeper cloning of any internal field is made.</p>266*267* <p>Since this class is immutable, the clone method is chiefly of268* interest to subclasses.</p>269*/270@Override271public Object clone () {272try {273return super.clone() ;274} catch (CloneNotSupportedException e) {275// should not happen as this class is cloneable276return null;277}278}279280281/**282* Returns the name of the Java class of the MBean described by283* this {@code MBeanInfo}.284*285* @return the class name.286*/287public String getClassName() {288return className;289}290291/**292* Returns a human readable description of the MBean.293*294* @return the description.295*/296public String getDescription() {297return description;298}299300/**301* Returns the list of attributes exposed for management.302* Each attribute is described by an {@code MBeanAttributeInfo} object.303*304* The returned array is a shallow copy of the internal array,305* which means that it is a copy of the internal array of306* references to the {@code MBeanAttributeInfo} objects307* but that each referenced {@code MBeanAttributeInfo} object is not copied.308*309* @return An array of {@code MBeanAttributeInfo} objects.310*/311public MBeanAttributeInfo[] getAttributes() {312MBeanAttributeInfo[] as = nonNullAttributes();313if (as.length == 0)314return as;315else316return as.clone();317}318319private MBeanAttributeInfo[] fastGetAttributes() {320if (arrayGettersSafe)321return nonNullAttributes();322else323return getAttributes();324}325326/**327* Return the value of the attributes field, or an empty array if328* the field is null. This can't happen with a329* normally-constructed instance of this class, but can if the330* instance was deserialized from another implementation that331* allows the field to be null. It would be simpler if we enforced332* the class invariant that these fields cannot be null by writing333* a readObject() method, but that would require us to define the334* various array fields as non-final, which is annoying because335* conceptually they are indeed final.336*/337private MBeanAttributeInfo[] nonNullAttributes() {338return (attributes == null) ?339MBeanAttributeInfo.NO_ATTRIBUTES : attributes;340}341342/**343* Returns the list of operations of the MBean.344* Each operation is described by an {@code MBeanOperationInfo} object.345*346* The returned array is a shallow copy of the internal array,347* which means that it is a copy of the internal array of348* references to the {@code MBeanOperationInfo} objects349* but that each referenced {@code MBeanOperationInfo} object is not copied.350*351* @return An array of {@code MBeanOperationInfo} objects.352*/353public MBeanOperationInfo[] getOperations() {354MBeanOperationInfo[] os = nonNullOperations();355if (os.length == 0)356return os;357else358return os.clone();359}360361private MBeanOperationInfo[] fastGetOperations() {362if (arrayGettersSafe)363return nonNullOperations();364else365return getOperations();366}367368private MBeanOperationInfo[] nonNullOperations() {369return (operations == null) ?370MBeanOperationInfo.NO_OPERATIONS : operations;371}372373/**374* <p>Returns the list of the public constructors of the MBean.375* Each constructor is described by an376* {@code MBeanConstructorInfo} object.</p>377*378* <p>The returned array is a shallow copy of the internal array,379* which means that it is a copy of the internal array of380* references to the {@code MBeanConstructorInfo} objects but381* that each referenced {@code MBeanConstructorInfo} object382* is not copied.</p>383*384* <p>The returned list is not necessarily exhaustive. That is,385* the MBean may have a public constructor that is not in the386* list. In this case, the MBean server can construct another387* instance of this MBean's class using that constructor, even388* though it is not listed here.</p>389*390* @return An array of {@code MBeanConstructorInfo} objects.391*/392public MBeanConstructorInfo[] getConstructors() {393MBeanConstructorInfo[] cs = nonNullConstructors();394if (cs.length == 0)395return cs;396else397return cs.clone();398}399400private MBeanConstructorInfo[] fastGetConstructors() {401if (arrayGettersSafe)402return nonNullConstructors();403else404return getConstructors();405}406407private MBeanConstructorInfo[] nonNullConstructors() {408return (constructors == null) ?409MBeanConstructorInfo.NO_CONSTRUCTORS : constructors;410}411412/**413* Returns the list of the notifications emitted by the MBean.414* Each notification is described by an {@code MBeanNotificationInfo} object.415*416* The returned array is a shallow copy of the internal array,417* which means that it is a copy of the internal array of418* references to the {@code MBeanNotificationInfo} objects419* but that each referenced {@code MBeanNotificationInfo} object is not copied.420*421* @return An array of {@code MBeanNotificationInfo} objects.422*/423public MBeanNotificationInfo[] getNotifications() {424MBeanNotificationInfo[] ns = nonNullNotifications();425if (ns.length == 0)426return ns;427else428return ns.clone();429}430431private MBeanNotificationInfo[] fastGetNotifications() {432if (arrayGettersSafe)433return nonNullNotifications();434else435return getNotifications();436}437438private MBeanNotificationInfo[] nonNullNotifications() {439return (notifications == null) ?440MBeanNotificationInfo.NO_NOTIFICATIONS : notifications;441}442443/**444* Get the descriptor of this MBeanInfo. Changing the returned value445* will have no affect on the original descriptor.446*447* @return a descriptor that is either immutable or a copy of the original.448*449* @since 1.6450*/451public Descriptor getDescriptor() {452return (Descriptor) nonNullDescriptor(descriptor).clone();453}454455@Override456public String toString() {457return458getClass().getName() + "[" +459"description=" + getDescription() + ", " +460"attributes=" + Arrays.asList(fastGetAttributes()) + ", " +461"constructors=" + Arrays.asList(fastGetConstructors()) + ", " +462"operations=" + Arrays.asList(fastGetOperations()) + ", " +463"notifications=" + Arrays.asList(fastGetNotifications()) + ", " +464"descriptor=" + getDescriptor() +465"]";466}467468/**469* <p>Compare this MBeanInfo to another. Two MBeanInfo objects470* are equal if and only if they return equal values for {@link471* #getClassName()}, for {@link #getDescription()}, and for472* {@link #getDescriptor()}, and the473* arrays returned by the two objects for {@link474* #getAttributes()}, {@link #getOperations()}, {@link475* #getConstructors()}, and {@link #getNotifications()} are476* pairwise equal. Here "equal" means {@link477* Object#equals(Object)}, not identity.</p>478*479* <p>If two MBeanInfo objects return the same values in one of480* their arrays but in a different order then they are not equal.</p>481*482* @param o the object to compare to.483*484* @return true if and only if {@code o} is an MBeanInfo that is equal485* to this one according to the rules above.486*/487@Override488public boolean equals(Object o) {489if (o == this)490return true;491if (!(o instanceof MBeanInfo))492return false;493MBeanInfo p = (MBeanInfo) o;494if (!isEqual(getClassName(), p.getClassName()) ||495!isEqual(getDescription(), p.getDescription()) ||496!getDescriptor().equals(p.getDescriptor())) {497return false;498}499500return501(Arrays.equals(p.fastGetAttributes(), fastGetAttributes()) &&502Arrays.equals(p.fastGetOperations(), fastGetOperations()) &&503Arrays.equals(p.fastGetConstructors(), fastGetConstructors()) &&504Arrays.equals(p.fastGetNotifications(), fastGetNotifications()));505}506507@Override508public int hashCode() {509/* Since computing the hashCode is quite expensive, we cache it.510If by some terrible misfortune the computed value is 0, the511caching won't work and we will recompute it every time.512513We don't bother synchronizing, because, at worst, n different514threads will compute the same hashCode at the same time. */515if (hashCode != 0)516return hashCode;517518hashCode = Objects.hash(getClassName(), getDescriptor())519^ Arrays.hashCode(fastGetAttributes())520^ Arrays.hashCode(fastGetOperations())521^ Arrays.hashCode(fastGetConstructors())522^ Arrays.hashCode(fastGetNotifications());523524return hashCode;525}526527/**528* Cached results of previous calls to arrayGettersSafe. This is529* a WeakHashMap so that we don't prevent a class from being530* garbage collected just because we know whether it's immutable.531*/532private static final Map<Class<?>, Boolean> arrayGettersSafeMap =533new WeakHashMap<Class<?>, Boolean>();534535/**536* Return true if {@code subclass} is known to preserve the537* immutability of {@code immutableClass}. The class538* {@code immutableClass} is a reference class that is known539* to be immutable. The subclass {@code subclass} is540* considered immutable if it does not override any public method541* of {@code immutableClass} whose name begins with "get".542* This is obviously not an infallible test for immutability,543* but it works for the public interfaces of the MBean*Info classes.544*/545@SuppressWarnings("removal")546static boolean arrayGettersSafe(Class<?> subclass, Class<?> immutableClass) {547if (subclass == immutableClass)548return true;549synchronized (arrayGettersSafeMap) {550Boolean safe = arrayGettersSafeMap.get(subclass);551if (safe == null) {552try {553ArrayGettersSafeAction action =554new ArrayGettersSafeAction(subclass, immutableClass);555safe = AccessController.doPrivileged(action);556} catch (Exception e) { // e.g. SecurityException557/* We don't know, so we assume it isn't. */558safe = false;559}560arrayGettersSafeMap.put(subclass, safe);561}562return safe;563}564}565566/*567* The PrivilegedAction stuff is probably overkill. We can be568* pretty sure the caller does have the required privileges -- a569* JMX user that can't do reflection can't even use Standard570* MBeans! But there's probably a performance gain by not having571* to check the whole call stack.572*/573private static class ArrayGettersSafeAction574implements PrivilegedAction<Boolean> {575576private final Class<?> subclass;577private final Class<?> immutableClass;578579ArrayGettersSafeAction(Class<?> subclass, Class<?> immutableClass) {580this.subclass = subclass;581this.immutableClass = immutableClass;582}583584public Boolean run() {585Method[] methods = immutableClass.getMethods();586for (int i = 0; i < methods.length; i++) {587Method method = methods[i];588String methodName = method.getName();589if (methodName.startsWith("get") &&590method.getParameterTypes().length == 0 &&591method.getReturnType().isArray()) {592try {593Method submethod =594subclass.getMethod(methodName);595if (!submethod.equals(method))596return false;597} catch (NoSuchMethodException e) {598return false;599}600}601}602return true;603}604}605606private static boolean isEqual(String s1, String s2) {607boolean ret;608609if (s1 == null) {610ret = (s2 == null);611} else {612ret = s1.equals(s2);613}614615return ret;616}617618/**619* Serializes an {@link MBeanInfo} to an {@link ObjectOutputStream}.620* @serialData621* For compatibility reasons, an object of this class is serialized as follows.622* <p>623* The method {@link ObjectOutputStream#defaultWriteObject defaultWriteObject()}624* is called first to serialize the object except the field {@code descriptor}625* which is declared as transient. The field {@code descriptor} is serialized626* as follows:627* <ul>628* <li> If {@code descriptor} is an instance of the class629* {@link ImmutableDescriptor}, the method {@link ObjectOutputStream#write630* write(int val)} is called to write a byte with the value {@code 1},631* then the method {@link ObjectOutputStream#writeObject writeObject(Object obj)}632* is called twice to serialize the field names and the field values of the633* {@code descriptor}, respectively as a {@code String[]} and an634* {@code Object[]};</li>635* <li> Otherwise, the method {@link ObjectOutputStream#write write(int val)}636* is called to write a byte with the value {@code 0}, then the method637* {@link ObjectOutputStream#writeObject writeObject(Object obj)} is called638* to serialize the field {@code descriptor} directly.639* </ul>640*641* @since 1.6642*/643private void writeObject(ObjectOutputStream out) throws IOException {644out.defaultWriteObject();645646if (descriptor.getClass() == ImmutableDescriptor.class) {647out.write(1);648649final String[] names = descriptor.getFieldNames();650651out.writeObject(names);652out.writeObject(descriptor.getFieldValues(names));653} else {654out.write(0);655656out.writeObject(descriptor);657}658}659660/**661* Deserializes an {@link MBeanInfo} from an {@link ObjectInputStream}.662* @serialData663* For compatibility reasons, an object of this class is deserialized as follows.664* <p>665* The method {@link ObjectInputStream#defaultReadObject defaultReadObject()}666* is called first to deserialize the object except the field667* {@code descriptor}, which is not serialized in the default way. Then the method668* {@link ObjectInputStream#read read()} is called to read a byte, the field669* {@code descriptor} is deserialized according to the value of the byte value:670* <ul>671* <li>1. The method {@link ObjectInputStream#readObject readObject()}672* is called twice to obtain the field names (a {@code String[]}) and673* the field values (an {@code Object[]}) of the {@code descriptor}.674* The two obtained values then are used to construct675* an {@link ImmutableDescriptor} instance for the field676* {@code descriptor};</li>677* <li>0. The value for the field {@code descriptor} is obtained directly678* by calling the method {@link ObjectInputStream#readObject readObject()}.679* If the obtained value is null, the field {@code descriptor} is set to680* {@link ImmutableDescriptor#EMPTY_DESCRIPTOR EMPTY_DESCRIPTOR};</li>681* <li>-1. This means that there is no byte to read and that the object is from682* an earlier version of the JMX API. The field {@code descriptor} is set to683* {@link ImmutableDescriptor#EMPTY_DESCRIPTOR EMPTY_DESCRIPTOR}.</li>684* <li>Any other value. A {@link StreamCorruptedException} is thrown.</li>685* </ul>686*687* @since 1.6688*/689690private void readObject(ObjectInputStream in)691throws IOException, ClassNotFoundException {692693in.defaultReadObject();694695switch (in.read()) {696case 1:697final String[] names = (String[])in.readObject();698699final Object[] values = (Object[]) in.readObject();700descriptor = (names.length == 0) ?701ImmutableDescriptor.EMPTY_DESCRIPTOR :702new ImmutableDescriptor(names, values);703704break;705case 0:706descriptor = (Descriptor)in.readObject();707708if (descriptor == null) {709descriptor = ImmutableDescriptor.EMPTY_DESCRIPTOR;710}711712break;713case -1: // from an earlier version of the JMX API714descriptor = ImmutableDescriptor.EMPTY_DESCRIPTOR;715716break;717default:718throw new StreamCorruptedException("Got unexpected byte.");719}720}721}722723724