code
stringlengths
3
1.18M
language
stringclasses
1 value
/* * Copyright (c) 2000, 2003, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management.relation; /** {@collect.stats} * This exception is raised when an access is done to the Relation Service and * that one is not registered. * * @since 1.5 */ public class RelationServiceNotRegisteredException extends RelationException { /* Serial version */ private static final long serialVersionUID = 8454744887157122910L; /** {@collect.stats} * Default constructor, no message put in exception. */ public RelationServiceNotRegisteredException() { super(); } /** {@collect.stats} * Constructor with given message put in exception. * * @param message the detail message. */ public RelationServiceNotRegisteredException(String message) { super(message); } }
Java
/* * Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management.relation; import com.sun.jmx.mbeanserver.GetPropertyAction; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.ObjectStreamField; import java.io.Serializable; import java.security.AccessController; import javax.management.MBeanServer; import javax.management.NotCompliantMBeanException; /** {@collect.stats} * A RoleInfo object summarises a role in a relation type. * * <p>The <b>serialVersionUID</b> of this class is <code>2504952983494636987L</code>. * * @since 1.5 */ @SuppressWarnings("serial") // serialVersionUID not constant public class RoleInfo implements Serializable { // Serialization compatibility stuff: // Two serial forms are supported in this class. The selected form depends // on system property "jmx.serial.form": // - "1.0" for JMX 1.0 // - any other value for JMX 1.1 and higher // // Serial version for old serial form private static final long oldSerialVersionUID = 7227256952085334351L; // // Serial version for new serial form private static final long newSerialVersionUID = 2504952983494636987L; // // Serializable fields in old serial form private static final ObjectStreamField[] oldSerialPersistentFields = { new ObjectStreamField("myName", String.class), new ObjectStreamField("myIsReadableFlg", boolean.class), new ObjectStreamField("myIsWritableFlg", boolean.class), new ObjectStreamField("myDescription", String.class), new ObjectStreamField("myMinDegree", int.class), new ObjectStreamField("myMaxDegree", int.class), new ObjectStreamField("myRefMBeanClassName", String.class) }; // // Serializable fields in new serial form private static final ObjectStreamField[] newSerialPersistentFields = { new ObjectStreamField("name", String.class), new ObjectStreamField("isReadable", boolean.class), new ObjectStreamField("isWritable", boolean.class), new ObjectStreamField("description", String.class), new ObjectStreamField("minDegree", int.class), new ObjectStreamField("maxDegree", int.class), new ObjectStreamField("referencedMBeanClassName", String.class) }; // // Actual serial version and serial form private static final long serialVersionUID; /** {@collect.stats} * @serialField name String Role name * @serialField isReadable boolean Read access mode: <code>true</code> if role is readable * @serialField isWritable boolean Write access mode: <code>true</code> if role is writable * @serialField description String Role description * @serialField minDegree int Minimum degree (i.e. minimum number of referenced MBeans in corresponding role) * @serialField maxDegree int Maximum degree (i.e. maximum number of referenced MBeans in corresponding role) * @serialField referencedMBeanClassName String Name of class of MBean(s) expected to be referenced in corresponding role */ private static final ObjectStreamField[] serialPersistentFields; private static boolean compat = false; static { try { GetPropertyAction act = new GetPropertyAction("jmx.serial.form"); String form = AccessController.doPrivileged(act); compat = (form != null && form.equals("1.0")); } catch (Exception e) { // OK : Too bad, no compat with 1.0 } if (compat) { serialPersistentFields = oldSerialPersistentFields; serialVersionUID = oldSerialVersionUID; } else { serialPersistentFields = newSerialPersistentFields; serialVersionUID = newSerialVersionUID; } } // // END Serialization compatibility stuff // // Public constants // /** {@collect.stats} * To specify an unlimited cardinality. */ public static final int ROLE_CARDINALITY_INFINITY = -1; // // Private members // /** {@collect.stats} * @serial Role name */ private String name = null; /** {@collect.stats} * @serial Read access mode: <code>true</code> if role is readable */ private boolean isReadable; /** {@collect.stats} * @serial Write access mode: <code>true</code> if role is writable */ private boolean isWritable; /** {@collect.stats} * @serial Role description */ private String description = null; /** {@collect.stats} * @serial Minimum degree (i.e. minimum number of referenced MBeans in corresponding role) */ private int minDegree; /** {@collect.stats} * @serial Maximum degree (i.e. maximum number of referenced MBeans in corresponding role) */ private int maxDegree; /** {@collect.stats} * @serial Name of class of MBean(s) expected to be referenced in corresponding role */ private String referencedMBeanClassName = null; // // Constructors // /** {@collect.stats} * Constructor. * * @param roleName name of the role. * @param mbeanClassName name of the class of MBean(s) expected to * be referenced in corresponding role. If an MBean <em>M</em> is in * this role, then the MBean server must return true for * {@link MBeanServer#isInstanceOf isInstanceOf(M, mbeanClassName)}. * @param read flag to indicate if the corresponding role * can be read * @param write flag to indicate if the corresponding role * can be set * @param min minimum degree for role, i.e. minimum number of * MBeans to provide in corresponding role * Must be less than or equal to <tt>max</tt>. * (ROLE_CARDINALITY_INFINITY for unlimited) * @param max maximum degree for role, i.e. maximum number of * MBeans to provide in corresponding role * Must be greater than or equal to <tt>min</tt> * (ROLE_CARDINALITY_INFINITY for unlimited) * @param descr description of the role (can be null) * * @exception IllegalArgumentException if null parameter * @exception InvalidRoleInfoException if the minimum degree is * greater than the maximum degree. * @exception ClassNotFoundException As of JMX 1.2, this exception * can no longer be thrown. It is retained in the declaration of * this class for compatibility with existing code. * @exception NotCompliantMBeanException if the class mbeanClassName * is not a MBean class. */ public RoleInfo(String roleName, String mbeanClassName, boolean read, boolean write, int min, int max, String descr) throws IllegalArgumentException, InvalidRoleInfoException, ClassNotFoundException, NotCompliantMBeanException { init(roleName, mbeanClassName, read, write, min, max, descr); return; } /** {@collect.stats} * Constructor. * * @param roleName name of the role * @param mbeanClassName name of the class of MBean(s) expected to * be referenced in corresponding role. If an MBean <em>M</em> is in * this role, then the MBean server must return true for * {@link MBeanServer#isInstanceOf isInstanceOf(M, mbeanClassName)}. * @param read flag to indicate if the corresponding role * can be read * @param write flag to indicate if the corresponding role * can be set * * <P>Minimum and maximum degrees defaulted to 1. * <P>Description of role defaulted to null. * * @exception IllegalArgumentException if null parameter * @exception ClassNotFoundException As of JMX 1.2, this exception * can no longer be thrown. It is retained in the declaration of * this class for compatibility with existing code. * @exception NotCompliantMBeanException As of JMX 1.2, this * exception can no longer be thrown. It is retained in the * declaration of this class for compatibility with existing code. */ public RoleInfo(String roleName, String mbeanClassName, boolean read, boolean write) throws IllegalArgumentException, ClassNotFoundException, NotCompliantMBeanException { try { init(roleName, mbeanClassName, read, write, 1, 1, null); } catch (InvalidRoleInfoException exc) { // OK : Can never happen as the minimum // degree equals the maximum degree. } return; } /** {@collect.stats} * Constructor. * * @param roleName name of the role * @param mbeanClassName name of the class of MBean(s) expected to * be referenced in corresponding role. If an MBean <em>M</em> is in * this role, then the MBean server must return true for * {@link MBeanServer#isInstanceOf isInstanceOf(M, mbeanClassName)}. * * <P>IsReadable and IsWritable defaulted to true. * <P>Minimum and maximum degrees defaulted to 1. * <P>Description of role defaulted to null. * * @exception IllegalArgumentException if null parameter * @exception ClassNotFoundException As of JMX 1.2, this exception * can no longer be thrown. It is retained in the declaration of * this class for compatibility with existing code. * @exception NotCompliantMBeanException As of JMX 1.2, this * exception can no longer be thrown. It is retained in the * declaration of this class for compatibility with existing code. */ public RoleInfo(String roleName, String mbeanClassName) throws IllegalArgumentException, ClassNotFoundException, NotCompliantMBeanException { try { init(roleName, mbeanClassName, true, true, 1, 1, null); } catch (InvalidRoleInfoException exc) { // OK : Can never happen as the minimum // degree equals the maximum degree. } return; } /** {@collect.stats} * Copy constructor. * * @param roleInfo the <tt>RoleInfo</tt> instance to be copied. * * @exception IllegalArgumentException if null parameter */ public RoleInfo(RoleInfo roleInfo) throws IllegalArgumentException { if (roleInfo == null) { // Revisit [cebro] Localize message String excMsg = "Invalid parameter."; throw new IllegalArgumentException(excMsg); } try { init(roleInfo.getName(), roleInfo.getRefMBeanClassName(), roleInfo.isReadable(), roleInfo.isWritable(), roleInfo.getMinDegree(), roleInfo.getMaxDegree(), roleInfo.getDescription()); } catch (InvalidRoleInfoException exc3) { // OK : Can never happen as the minimum degree and the maximum // degree were already checked at the time the roleInfo // instance was created. } } // // Accessors // /** {@collect.stats} * Returns the name of the role. * * @return the name of the role. */ public String getName() { return name; } /** {@collect.stats} * Returns read access mode for the role (true if it is readable). * * @return true if the role is readable. */ public boolean isReadable() { return isReadable; } /** {@collect.stats} * Returns write access mode for the role (true if it is writable). * * @return true if the role is writable. */ public boolean isWritable() { return isWritable; } /** {@collect.stats} * Returns description text for the role. * * @return the description of the role. */ public String getDescription() { return description; } /** {@collect.stats} * Returns minimum degree for corresponding role reference. * * @return the minimum degree. */ public int getMinDegree() { return minDegree; } /** {@collect.stats} * Returns maximum degree for corresponding role reference. * * @return the maximum degree. */ public int getMaxDegree() { return maxDegree; } /** {@collect.stats} * <p>Returns name of type of MBean expected to be referenced in * corresponding role.</p> * * @return the name of the referenced type. */ public String getRefMBeanClassName() { return referencedMBeanClassName; } /** {@collect.stats} * Returns true if the <tt>value</tt> parameter is greater than or equal to * the expected minimum degree, false otherwise. * * @param value the value to be checked * * @return true if greater than or equal to minimum degree, false otherwise. */ public boolean checkMinDegree(int value) { if (value >= ROLE_CARDINALITY_INFINITY && (minDegree == ROLE_CARDINALITY_INFINITY || value >= minDegree)) { return true; } else { return false; } } /** {@collect.stats} * Returns true if the <tt>value</tt> parameter is lower than or equal to * the expected maximum degree, false otherwise. * * @param value the value to be checked * * @return true if lower than or equal to maximum degree, false otherwise. */ public boolean checkMaxDegree(int value) { if (value >= ROLE_CARDINALITY_INFINITY && (maxDegree == ROLE_CARDINALITY_INFINITY || (value != ROLE_CARDINALITY_INFINITY && value <= maxDegree))) { return true; } else { return false; } } /** {@collect.stats} * Returns a string describing the role info. * * @return a description of the role info. */ public String toString() { StringBuilder result = new StringBuilder(); result.append("role info name: " + name); result.append("; isReadable: " + isReadable); result.append("; isWritable: " + isWritable); result.append("; description: " + description); result.append("; minimum degree: " + minDegree); result.append("; maximum degree: " + maxDegree); result.append("; MBean class: " + referencedMBeanClassName); return result.toString(); } // // Misc // // Initialization private void init(String roleName, String mbeanClassName, boolean read, boolean write, int min, int max, String descr) throws IllegalArgumentException, InvalidRoleInfoException { if (roleName == null || mbeanClassName == null) { // Revisit [cebro] Localize message String excMsg = "Invalid parameter."; throw new IllegalArgumentException(excMsg); } name = roleName; isReadable = read; isWritable = write; if (descr != null) { description = descr; } boolean invalidRoleInfoFlg = false; StringBuilder excMsgStrB = new StringBuilder(); if (max != ROLE_CARDINALITY_INFINITY && (min == ROLE_CARDINALITY_INFINITY || min > max)) { // Revisit [cebro] Localize message excMsgStrB.append("Minimum degree "); excMsgStrB.append(min); excMsgStrB.append(" is greater than maximum degree "); excMsgStrB.append(max); invalidRoleInfoFlg = true; } else if (min < ROLE_CARDINALITY_INFINITY || max < ROLE_CARDINALITY_INFINITY) { // Revisit [cebro] Localize message excMsgStrB.append("Minimum or maximum degree has an illegal value, must be [0, ROLE_CARDINALITY_INFINITY]."); invalidRoleInfoFlg = true; } if (invalidRoleInfoFlg) { throw new InvalidRoleInfoException(excMsgStrB.toString()); } minDegree = min; maxDegree = max; referencedMBeanClassName = mbeanClassName; return; } /** {@collect.stats} * Deserializes a {@link RoleInfo} from an {@link ObjectInputStream}. */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { if (compat) { // Read an object serialized in the old serial form // ObjectInputStream.GetField fields = in.readFields(); name = (String) fields.get("myName", null); if (fields.defaulted("myName")) { throw new NullPointerException("myName"); } isReadable = fields.get("myIsReadableFlg", false); if (fields.defaulted("myIsReadableFlg")) { throw new NullPointerException("myIsReadableFlg"); } isWritable = fields.get("myIsWritableFlg", false); if (fields.defaulted("myIsWritableFlg")) { throw new NullPointerException("myIsWritableFlg"); } description = (String) fields.get("myDescription", null); if (fields.defaulted("myDescription")) { throw new NullPointerException("myDescription"); } minDegree = fields.get("myMinDegree", 0); if (fields.defaulted("myMinDegree")) { throw new NullPointerException("myMinDegree"); } maxDegree = fields.get("myMaxDegree", 0); if (fields.defaulted("myMaxDegree")) { throw new NullPointerException("myMaxDegree"); } referencedMBeanClassName = (String) fields.get("myRefMBeanClassName", null); if (fields.defaulted("myRefMBeanClassName")) { throw new NullPointerException("myRefMBeanClassName"); } } else { // Read an object serialized in the new serial form // in.defaultReadObject(); } } /** {@collect.stats} * Serializes a {@link RoleInfo} to an {@link ObjectOutputStream}. */ private void writeObject(ObjectOutputStream out) throws IOException { if (compat) { // Serializes this instance in the old serial form // ObjectOutputStream.PutField fields = out.putFields(); fields.put("myName", name); fields.put("myIsReadableFlg", isReadable); fields.put("myIsWritableFlg", isWritable); fields.put("myDescription", description); fields.put("myMinDegree", minDegree); fields.put("myMaxDegree", maxDegree); fields.put("myRefMBeanClassName", referencedMBeanClassName); out.writeFields(); } else { // Serializes this instance in the new serial form // out.defaultWriteObject(); } } }
Java
/* * Copyright (c) 2000, 2003, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management.relation; /** {@collect.stats} * This exception is raised when, in a role info, its minimum degree is greater * than its maximum degree. * * @since 1.5 */ public class InvalidRoleInfoException extends RelationException { /* Serial version */ private static final long serialVersionUID = 7517834705158932074L; /** {@collect.stats} * Default constructor, no message put in exception. */ public InvalidRoleInfoException() { super(); } /** {@collect.stats} * Constructor with given message put in exception. * * @param message the detail message. */ public InvalidRoleInfoException(String message) { super(message); } }
Java
/* * Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management; // java import import java.io.Serializable; /** {@collect.stats} * <p>Represents relational constraints that can be used in database * query "where clauses". Instances of QueryExp are returned by the * static methods of the {@link Query} class.</p> * * <p>It is possible, but not * recommended, to create custom queries by implementing this * interface. In that case, it is better to extend the {@link * QueryEval} class than to implement the interface directly, so that * the {@link #setMBeanServer} method works correctly. * * @since 1.5 */ public interface QueryExp extends Serializable { /** {@collect.stats} * Applies the QueryExp on an MBean. * * @param name The name of the MBean on which the QueryExp will be applied. * * @return True if the query was successfully applied to the MBean, false otherwise * * @exception BadStringOperationException * @exception BadBinaryOpValueExpException * @exception BadAttributeValueExpException * @exception InvalidApplicationException */ public boolean apply(ObjectName name) throws BadStringOperationException, BadBinaryOpValueExpException, BadAttributeValueExpException, InvalidApplicationException ; /** {@collect.stats} * Sets the MBean server on which the query is to be performed. * * @param s The MBean server on which the query is to be performed. */ public void setMBeanServer(MBeanServer s) ; }
Java
/* * Copyright (c) 1999, 2006, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management; /** {@collect.stats} * Describes an argument of an operation exposed by an MBean. * Instances of this class are immutable. Subclasses may be mutable * but this is not recommended. * * @since 1.5 */ public class MBeanParameterInfo extends MBeanFeatureInfo implements Cloneable { /* Serial version */ static final long serialVersionUID = 7432616882776782338L; /* All zero-length arrays are interchangeable. */ static final MBeanParameterInfo[] NO_PARAMS = new MBeanParameterInfo[0]; /** {@collect.stats} * @serial The type or class name of the data. */ private final String type; /** {@collect.stats} * Constructs an <CODE>MBeanParameterInfo</CODE> object. * * @param name The name of the data * @param type The type or class name of the data * @param description A human readable description of the data. Optional. */ public MBeanParameterInfo(String name, String type, String description) { this(name, type, description, (Descriptor) null); } /** {@collect.stats} * Constructs an <CODE>MBeanParameterInfo</CODE> object. * * @param name The name of the data * @param type The type or class name of the data * @param description A human readable description of the data. Optional. * @param descriptor The descriptor for the operation. This may be null * which is equivalent to an empty descriptor. * * @since 1.6 */ public MBeanParameterInfo(String name, String type, String description, Descriptor descriptor) { super(name, description, descriptor); this.type = type; } /** {@collect.stats} * <p>Returns a shallow clone of this instance. * The clone is obtained by simply calling <tt>super.clone()</tt>, * thus calling the default native shallow cloning mechanism * implemented by <tt>Object.clone()</tt>. * No deeper cloning of any internal field is made.</p> * * <p>Since this class is immutable, cloning is chiefly of * interest to subclasses.</p> */ public Object clone () { try { return super.clone() ; } catch (CloneNotSupportedException e) { // should not happen as this class is cloneable return null; } } /** {@collect.stats} * Returns the type or class name of the data. * * @return the type string. */ public String getType() { return type; } public String toString() { return getClass().getName() + "[" + "description=" + getDescription() + ", " + "name=" + getName() + ", " + "type=" + getType() + ", " + "descriptor=" + getDescriptor() + "]"; } /** {@collect.stats} * Compare this MBeanParameterInfo to another. * * @param o the object to compare to. * * @return true if and only if <code>o</code> is an MBeanParameterInfo such * that its {@link #getName()}, {@link #getType()}, * {@link #getDescriptor()}, and {@link * #getDescription()} values are equal (not necessarily identical) * to those of this MBeanParameterInfo. */ public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof MBeanParameterInfo)) return false; MBeanParameterInfo p = (MBeanParameterInfo) o; return (p.getName().equals(getName()) && p.getType().equals(getType()) && p.getDescription().equals(getDescription()) && p.getDescriptor().equals(getDescriptor())); } public int hashCode() { return getName().hashCode() ^ getType().hashCode(); } }
Java
/* * Copyright (c) 2002, 2007, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management; import com.sun.jmx.mbeanserver.MXBeanProxy; import java.lang.ref.WeakReference; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.Arrays; import java.util.WeakHashMap; /** {@collect.stats} * <p>{@link InvocationHandler} that forwards methods in an MBean's * management interface through the MBean server to the MBean.</p> * * <p>Given an {@link MBeanServerConnection}, the {@link ObjectName} * of an MBean within that MBean server, and a Java interface * <code>Intf</code> that describes the management interface of the * MBean using the patterns for a Standard MBean or an MXBean, this * class can be used to construct a proxy for the MBean. The proxy * implements the interface <code>Intf</code> such that all of its * methods are forwarded through the MBean server to the MBean.</p> * * <p>If the {@code InvocationHandler} is for an MXBean, then the parameters of * a method are converted from the type declared in the MXBean * interface into the corresponding mapped type, and the return value * is converted from the mapped type into the declared type. For * example, with the method<br> * {@code public List<String> reverse(List<String> list);}<br> * and given that the mapped type for {@code List<String>} is {@code * String[]}, a call to {@code proxy.reverse(someList)} will convert * {@code someList} from a {@code List<String>} to a {@code String[]}, * call the MBean operation {@code reverse}, then convert the returned * {@code String[]} into a {@code List<String>}.</p> * * <p>The method Object.toString(), Object.hashCode(), or * Object.equals(Object), when invoked on a proxy using this * invocation handler, is forwarded to the MBean server as a method on * the proxied MBean only if it appears in one of the proxy's * interfaces. For a proxy created with {@link * JMX#newMBeanProxy(MBeanServerConnection, ObjectName, Class) * JMX.newMBeanProxy} or {@link * JMX#newMXBeanProxy(MBeanServerConnection, ObjectName, Class) * JMX.newMXBeanProxy}, this means that the method must appear in the * Standard MBean or MXBean interface. Otherwise these methods have * the following behavior: * <ul> * <li>toString() returns a string representation of the proxy * <li>hashCode() returns a hash code for the proxy such * that two equal proxies have the same hash code * <li>equals(Object) * returns true if and only if the Object argument is of the same * proxy class as this proxy, with an MBeanServerInvocationHandler * that has the same MBeanServerConnection and ObjectName; if one * of the {@code MBeanServerInvocationHandler}s was constructed with * a {@code Class} argument then the other must have been constructed * with the same {@code Class} for {@code equals} to return true. * </ul> * * @since 1.5 */ public class MBeanServerInvocationHandler implements InvocationHandler { /** {@collect.stats} * <p>Invocation handler that forwards methods through an MBean * server to a Standard MBean. This constructor may be called * instead of relying on {@link * JMX#newMBeanProxy(MBeanServerConnection, ObjectName, Class) * JMX.newMBeanProxy}, for instance if you need to supply a * different {@link ClassLoader} to {@link Proxy#newProxyInstance * Proxy.newProxyInstance}.</p> * * <p>This constructor is not appropriate for an MXBean. Use * {@link #MBeanServerInvocationHandler(MBeanServerConnection, * ObjectName, boolean)} for that. This constructor is equivalent * to {@code new MBeanServerInvocationHandler(connection, * objectName, false)}.</p> * * @param connection the MBean server connection through which all * methods of a proxy using this handler will be forwarded. * * @param objectName the name of the MBean within the MBean server * to which methods will be forwarded. */ public MBeanServerInvocationHandler(MBeanServerConnection connection, ObjectName objectName) { this(connection, objectName, false); } /** {@collect.stats} * <p>Invocation handler that can forward methods through an MBean * server to a Standard MBean or MXBean. This constructor may be called * instead of relying on {@link * JMX#newMXBeanProxy(MBeanServerConnection, ObjectName, Class) * JMX.newMXBeanProxy}, for instance if you need to supply a * different {@link ClassLoader} to {@link Proxy#newProxyInstance * Proxy.newProxyInstance}.</p> * * @param connection the MBean server connection through which all * methods of a proxy using this handler will be forwarded. * * @param objectName the name of the MBean within the MBean server * to which methods will be forwarded. * * @param isMXBean if true, the proxy is for an {@link MXBean}, and * appropriate mappings will be applied to method parameters and return * values. * * @since 1.6 */ public MBeanServerInvocationHandler(MBeanServerConnection connection, ObjectName objectName, boolean isMXBean) { if (connection == null) { throw new IllegalArgumentException("Null connection"); } if (objectName == null) { throw new IllegalArgumentException("Null object name"); } this.connection = connection; this.objectName = objectName; this.isMXBean = isMXBean; } /** {@collect.stats} * <p>The MBean server connection through which the methods of * a proxy using this handler are forwarded.</p> * * @return the MBean server connection. * * @since 1.6 */ public MBeanServerConnection getMBeanServerConnection() { return connection; } /** {@collect.stats} * <p>The name of the MBean within the MBean server to which methods * are forwarded. * * @return the object name. * * @since 1.6 */ public ObjectName getObjectName() { return objectName; } /** {@collect.stats} * <p>If true, the proxy is for an MXBean, and appropriate mappings * are applied to method parameters and return values. * * @return whether the proxy is for an MXBean. * * @since 1.6 */ public boolean isMXBean() { return isMXBean; } /** {@collect.stats} * <p>Return a proxy that implements the given interface by * forwarding its methods through the given MBean server to the * named MBean. As of 1.6, the methods {@link * JMX#newMBeanProxy(MBeanServerConnection, ObjectName, Class)} and * {@link JMX#newMBeanProxy(MBeanServerConnection, ObjectName, Class, * boolean)} are preferred to this method.</p> * * <p>This method is equivalent to {@link Proxy#newProxyInstance * Proxy.newProxyInstance}<code>(interfaceClass.getClassLoader(), * interfaces, handler)</code>. Here <code>handler</code> is the * result of {@link #MBeanServerInvocationHandler new * MBeanServerInvocationHandler(connection, objectName)}, and * <code>interfaces</code> is an array that has one element if * <code>notificationBroadcaster</code> is false and two if it is * true. The first element of <code>interfaces</code> is * <code>interfaceClass</code> and the second, if present, is * <code>NotificationEmitter.class</code>. * * @param connection the MBean server to forward to. * @param objectName the name of the MBean within * <code>connection</code> to forward to. * @param interfaceClass the management interface that the MBean * exports, which will also be implemented by the returned proxy. * @param notificationBroadcaster make the returned proxy * implement {@link NotificationEmitter} by forwarding its methods * via <code>connection</code>. A call to {@link * NotificationBroadcaster#addNotificationListener} on the proxy will * result in a call to {@link * MBeanServerConnection#addNotificationListener(ObjectName, * NotificationListener, NotificationFilter, Object)}, and likewise * for the other methods of {@link NotificationBroadcaster} and {@link * NotificationEmitter}. * * @param <T> allows the compiler to know that if the {@code * interfaceClass} parameter is {@code MyMBean.class}, for example, * then the return type is {@code MyMBean}. * * @return the new proxy instance. * * @see JMX#newMBeanProxy(MBeanServerConnection, ObjectName, Class) */ public static <T> T newProxyInstance(MBeanServerConnection connection, ObjectName objectName, Class<T> interfaceClass, boolean notificationBroadcaster) { final InvocationHandler handler = new MBeanServerInvocationHandler(connection, objectName); final Class[] interfaces; if (notificationBroadcaster) { interfaces = new Class[] {interfaceClass, NotificationEmitter.class}; } else interfaces = new Class[] {interfaceClass}; Object proxy = Proxy.newProxyInstance(interfaceClass.getClassLoader(), interfaces, handler); return interfaceClass.cast(proxy); } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { final Class methodClass = method.getDeclaringClass(); if (methodClass.equals(NotificationBroadcaster.class) || methodClass.equals(NotificationEmitter.class)) return invokeBroadcasterMethod(proxy, method, args); // local or not: equals, toString, hashCode if (shouldDoLocally(proxy, method)) return doLocally(proxy, method, args); try { if (isMXBean) { MXBeanProxy p = findMXBeanProxy(methodClass); return p.invoke(connection, objectName, method, args); } else { final String methodName = method.getName(); final Class[] paramTypes = method.getParameterTypes(); final Class returnType = method.getReturnType(); /* Inexplicably, InvocationHandler specifies that args is null when the method takes no arguments rather than a zero-length array. */ final int nargs = (args == null) ? 0 : args.length; if (methodName.startsWith("get") && methodName.length() > 3 && nargs == 0 && !returnType.equals(Void.TYPE)) { return connection.getAttribute(objectName, methodName.substring(3)); } if (methodName.startsWith("is") && methodName.length() > 2 && nargs == 0 && (returnType.equals(Boolean.TYPE) || returnType.equals(Boolean.class))) { return connection.getAttribute(objectName, methodName.substring(2)); } if (methodName.startsWith("set") && methodName.length() > 3 && nargs == 1 && returnType.equals(Void.TYPE)) { Attribute attr = new Attribute(methodName.substring(3), args[0]); connection.setAttribute(objectName, attr); return null; } final String[] signature = new String[paramTypes.length]; for (int i = 0; i < paramTypes.length; i++) signature[i] = paramTypes[i].getName(); return connection.invoke(objectName, methodName, args, signature); } } catch (MBeanException e) { throw e.getTargetException(); } catch (RuntimeMBeanException re) { throw re.getTargetException(); } catch (RuntimeErrorException rre) { throw rre.getTargetError(); } /* The invoke may fail because it can't get to the MBean, with one of the these exceptions declared by MBeanServerConnection.invoke: - RemoteException: can't talk to MBeanServer; - InstanceNotFoundException: objectName is not registered; - ReflectionException: objectName is registered but does not have the method being invoked. In all of these cases, the exception will be wrapped by the proxy mechanism in an UndeclaredThrowableException unless it happens to be declared in the "throws" clause of the method being invoked on the proxy. */ } private static MXBeanProxy findMXBeanProxy(Class<?> mxbeanInterface) { synchronized (mxbeanProxies) { WeakReference<MXBeanProxy> proxyRef = mxbeanProxies.get(mxbeanInterface); MXBeanProxy p = (proxyRef == null) ? null : proxyRef.get(); if (p == null) { p = new MXBeanProxy(mxbeanInterface); mxbeanProxies.put(mxbeanInterface, new WeakReference<MXBeanProxy>(p)); } return p; } } private static final WeakHashMap<Class<?>, WeakReference<MXBeanProxy>> mxbeanProxies = new WeakHashMap<Class<?>, WeakReference<MXBeanProxy>>(); private Object invokeBroadcasterMethod(Object proxy, Method method, Object[] args) throws Exception { final String methodName = method.getName(); final int nargs = (args == null) ? 0 : args.length; if (methodName.equals("addNotificationListener")) { /* The various throws of IllegalArgumentException here should not happen, since we know what the methods in NotificationBroadcaster and NotificationEmitter are. */ if (nargs != 3) { final String msg = "Bad arg count to addNotificationListener: " + nargs; throw new IllegalArgumentException(msg); } /* Other inconsistencies will produce ClassCastException below. */ NotificationListener listener = (NotificationListener) args[0]; NotificationFilter filter = (NotificationFilter) args[1]; Object handback = args[2]; connection.addNotificationListener(objectName, listener, filter, handback); return null; } else if (methodName.equals("removeNotificationListener")) { /* NullPointerException if method with no args, but that shouldn't happen because removeNL does have args. */ NotificationListener listener = (NotificationListener) args[0]; switch (nargs) { case 1: connection.removeNotificationListener(objectName, listener); return null; case 3: NotificationFilter filter = (NotificationFilter) args[1]; Object handback = args[2]; connection.removeNotificationListener(objectName, listener, filter, handback); return null; default: final String msg = "Bad arg count to removeNotificationListener: " + nargs; throw new IllegalArgumentException(msg); } } else if (methodName.equals("getNotificationInfo")) { if (args != null) { throw new IllegalArgumentException("getNotificationInfo has " + "args"); } MBeanInfo info = connection.getMBeanInfo(objectName); return info.getNotifications(); } else { throw new IllegalArgumentException("Bad method name: " + methodName); } } private boolean shouldDoLocally(Object proxy, Method method) { final String methodName = method.getName(); if ((methodName.equals("hashCode") || methodName.equals("toString")) && method.getParameterTypes().length == 0 && isLocal(proxy, method)) return true; if (methodName.equals("equals") && Arrays.equals(method.getParameterTypes(), new Class[] {Object.class}) && isLocal(proxy, method)) return true; return false; } private Object doLocally(Object proxy, Method method, Object[] args) { final String methodName = method.getName(); if (methodName.equals("equals")) { if (this == args[0]) { return true; } if (!(args[0] instanceof Proxy)) { return false; } final InvocationHandler ihandler = Proxy.getInvocationHandler(args[0]); if (ihandler == null || !(ihandler instanceof MBeanServerInvocationHandler)) { return false; } final MBeanServerInvocationHandler handler = (MBeanServerInvocationHandler)ihandler; return connection.equals(handler.connection) && objectName.equals(handler.objectName) && proxy.getClass().equals(args[0].getClass()); } else if (methodName.equals("toString")) { return (isMXBean ? "MX" : "M") + "BeanProxy(" + connection + "[" + objectName + "])"; } else if (methodName.equals("hashCode")) { return objectName.hashCode()+connection.hashCode(); } throw new RuntimeException("Unexpected method name: " + methodName); } private static boolean isLocal(Object proxy, Method method) { final Class<?>[] interfaces = proxy.getClass().getInterfaces(); if(interfaces == null) { return true; } final String methodName = method.getName(); final Class<?>[] params = method.getParameterTypes(); for (Class<?> intf : interfaces) { try { intf.getMethod(methodName, params); return false; // found method in one of our interfaces } catch (NoSuchMethodException nsme) { // OK. } } return true; // did not find in any interface } private final MBeanServerConnection connection; private final ObjectName objectName; private final boolean isMXBean; }
Java
/* * Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management; /** {@collect.stats} * Represents exceptions thrown in the MBean server when using the * java.lang.reflect classes to invoke methods on MBeans. It "wraps" the * actual java.lang.Exception thrown. * * @since 1.5 */ public class ReflectionException extends JMException { /* Serial version */ private static final long serialVersionUID = 9170809325636915553L; /** {@collect.stats} * @serial The wrapped {@link Exception} */ private java.lang.Exception exception ; /** {@collect.stats} * Creates a <CODE>ReflectionException</CODE> that wraps the actual <CODE>java.lang.Exception</CODE>. * * @param e the wrapped exception. */ public ReflectionException(java.lang.Exception e) { super() ; exception = e ; } /** {@collect.stats} * Creates a <CODE>ReflectionException</CODE> that wraps the actual <CODE>java.lang.Exception</CODE> with * a detail message. * * @param e the wrapped exception. * @param message the detail message. */ public ReflectionException(java.lang.Exception e, String message) { super(message) ; exception = e ; } /** {@collect.stats} * Returns the actual {@link Exception} thrown. * * @return the wrapped {@link Exception}. */ public java.lang.Exception getTargetException() { return exception ; } /** {@collect.stats} * Returns the actual {@link Exception} thrown. * * @return the wrapped {@link Exception}. */ public Throwable getCause() { return exception; } }
Java
/* * Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management; /** {@collect.stats} * The MBean is already registered in the repository. * * @since 1.5 */ public class InstanceAlreadyExistsException extends OperationsException { /* Serial version */ private static final long serialVersionUID = 8893743928912733931L; /** {@collect.stats} * Default constructor. */ public InstanceAlreadyExistsException() { super(); } /** {@collect.stats} * Constructor that allows a specific error message to be specified. * * @param message the detail message. */ public InstanceAlreadyExistsException(String message) { super(message); } }
Java
/* * Copyright (c) 1999, 2005, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management; /** {@collect.stats} * <p>Constructs query object constraints. The static methods provided * return query expressions that may be used in listing and * enumerating MBeans. Individual constraint construction methods * allow only appropriate types as arguments. Composition of calls can * construct arbitrary nestings of constraints, as the following * example illustrates:</p> * * <pre> * QueryExp exp = Query.and(Query.gt(Query.attr("age"),Query.value(5)), * Query.match(Query.attr("name"), * Query.value("Smith"))); * </pre> * * @since 1.5 */ public class Query extends Object { /** {@collect.stats} * A code representing the {@link Query#gt} query. This is chiefly * of interest for the serialized form of queries. */ public static final int GT = 0; /** {@collect.stats} * A code representing the {@link Query#lt} query. This is chiefly * of interest for the serialized form of queries. */ public static final int LT = 1; /** {@collect.stats} * A code representing the {@link Query#geq} query. This is chiefly * of interest for the serialized form of queries. */ public static final int GE = 2; /** {@collect.stats} * A code representing the {@link Query#leq} query. This is chiefly * of interest for the serialized form of queries. */ public static final int LE = 3; /** {@collect.stats} * A code representing the {@link Query#eq} query. This is chiefly * of interest for the serialized form of queries. */ public static final int EQ = 4; /** {@collect.stats} * A code representing the {@link Query#plus} expression. This * is chiefly of interest for the serialized form of queries. */ public static final int PLUS = 0; /** {@collect.stats} * A code representing the {@link Query#minus} expression. This * is chiefly of interest for the serialized form of queries. */ public static final int MINUS = 1; /** {@collect.stats} * A code representing the {@link Query#times} expression. This * is chiefly of interest for the serialized form of queries. */ public static final int TIMES = 2; /** {@collect.stats} * A code representing the {@link Query#div} expression. This is * chiefly of interest for the serialized form of queries. */ public static final int DIV = 3; /** {@collect.stats} * Basic constructor. */ public Query() { } /** {@collect.stats} * Returns a query expression that is the conjunction of two other query * expressions. * * @param q1 A query expression. * @param q2 Another query expression. * * @return The conjunction of the two arguments. The returned object * will be serialized as an instance of the non-public class {@link * <a href="../../serialized-form.html#javax.management.AndQueryExp"> * javax.management.AndQueryExp</a>}. */ public static QueryExp and(QueryExp q1, QueryExp q2) { return new AndQueryExp(q1, q2); } /** {@collect.stats} * Returns a query expression that is the disjunction of two other query * expressions. * * @param q1 A query expression. * @param q2 Another query expression. * * @return The disjunction of the two arguments. The returned object * will be serialized as an instance of the non-public class {@link * <a href="../../serialized-form.html#javax.management.OrQueryExp"> * javax.management.OrQueryExp</a>}. */ public static QueryExp or(QueryExp q1, QueryExp q2) { return new OrQueryExp(q1, q2); } /** {@collect.stats} * Returns a query expression that represents a "greater than" constraint on * two values. * * @param v1 A value expression. * @param v2 Another value expression. * * @return A "greater than" constraint on the arguments. The * returned object will be serialized as an instance of the * non-public class {@link <a * href="../../serialized-form.html#javax.management.BinaryRelQueryExp"> * javax.management.BinaryRelQueryExp</a>} with a {@code relOp} equal * to {@link #GT}. */ public static QueryExp gt(ValueExp v1, ValueExp v2) { return new BinaryRelQueryExp(GT, v1, v2); } /** {@collect.stats} * Returns a query expression that represents a "greater than or equal * to" constraint on two values. * * @param v1 A value expression. * @param v2 Another value expression. * * @return A "greater than or equal to" constraint on the * arguments. The returned object will be serialized as an * instance of the non-public class {@link <a * href="../../serialized-form.html#javax.management.BinaryRelQueryExp"> * javax.management.BinaryRelQueryExp</a>} with a {@code relOp} equal * to {@link #GE}. */ public static QueryExp geq(ValueExp v1, ValueExp v2) { return new BinaryRelQueryExp(GE, v1, v2); } /** {@collect.stats} * Returns a query expression that represents a "less than or equal to" * constraint on two values. * * @param v1 A value expression. * @param v2 Another value expression. * * @return A "less than or equal to" constraint on the arguments. * The returned object will be serialized as an instance of the * non-public class {@link <a * href="../../serialized-form.html#javax.management.BinaryRelQueryExp"> * javax.management.BinaryRelQueryExp</a>} with a {@code relOp} equal * to {@link #LE}. */ public static QueryExp leq(ValueExp v1, ValueExp v2) { return new BinaryRelQueryExp(LE, v1, v2); } /** {@collect.stats} * Returns a query expression that represents a "less than" constraint on * two values. * * @param v1 A value expression. * @param v2 Another value expression. * * @return A "less than" constraint on the arguments. The * returned object will be serialized as an instance of the * non-public class {@link <a * href="../../serialized-form.html#javax.management.BinaryRelQueryExp"> * javax.management.BinaryRelQueryExp</a>} with a {@code relOp} equal * to {@link #LT}. */ public static QueryExp lt(ValueExp v1, ValueExp v2) { return new BinaryRelQueryExp(LT, v1, v2); } /** {@collect.stats} * Returns a query expression that represents an equality constraint on * two values. * * @param v1 A value expression. * @param v2 Another value expression. * * @return A "equal to" constraint on the arguments. The * returned object will be serialized as an instance of the * non-public class {@link <a * href="../../serialized-form.html#javax.management.BinaryRelQueryExp"> * javax.management.BinaryRelQueryExp</a>} with a {@code relOp} equal * to {@link #EQ}. */ public static QueryExp eq(ValueExp v1, ValueExp v2) { return new BinaryRelQueryExp(EQ, v1, v2); } /** {@collect.stats} * Returns a query expression that represents the constraint that one * value is between two other values. * * @param v1 A value expression that is "between" v2 and v3. * @param v2 Value expression that represents a boundary of the constraint. * @param v3 Value expression that represents a boundary of the constraint. * * @return The constraint that v1 lies between v2 and v3. The * returned object will be serialized as an instance of the * non-public class {@link <a * href="../../serialized-form.html#javax.management.BetweenQueryExp"> * javax.management.BetweenQueryExp</a>}. */ public static QueryExp between(ValueExp v1, ValueExp v2, ValueExp v3) { return new BetweenQueryExp(v1, v2, v3); } /** {@collect.stats} * Returns a query expression that represents a matching constraint on * a string argument. The matching syntax is consistent with file globbing: * supports "<code>?</code>", "<code>*</code>", "<code>[</code>", * each of which may be escaped with "<code>\</code>"; * character classes may use "<code>!</code>" for negation and * "<code>-</code>" for range. * (<code>*</code> for any character sequence, * <code>?</code> for a single arbitrary character, * <code>[...]</code> for a character sequence). * For example: <code>a*b?c</code> would match a string starting * with the character <code>a</code>, followed * by any number of characters, followed by a <code>b</code>, * any single character, and a <code>c</code>. * * @param a An attribute expression * @param s A string value expression representing a matching constraint * * @return A query expression that represents the matching * constraint on the string argument. The returned object will * be serialized as an instance of the non-public class {@link <a * href="../../serialized-form.html#javax.management.MatchQueryExp"> * javax.management.MatchQueryExp</a>}. */ public static QueryExp match(AttributeValueExp a, StringValueExp s) { return new MatchQueryExp(a, s); } /** {@collect.stats} * <p>Returns a new attribute expression.</p> * * <p>Evaluating this expression for a given * <code>objectName</code> includes performing {@link * MBeanServer#getAttribute MBeanServer.getAttribute(objectName, * name)}.</p> * * @param name The name of the attribute. * * @return An attribute expression for the attribute named name. */ public static AttributeValueExp attr(String name) { return new AttributeValueExp(name); } /** {@collect.stats} * <p>Returns a new qualified attribute expression.</p> * * <p>Evaluating this expression for a given * <code>objectName</code> includes performing {@link * MBeanServer#getObjectInstance * MBeanServer.getObjectInstance(objectName)} and {@link * MBeanServer#getAttribute MBeanServer.getAttribute(objectName, * name)}.</p> * * @param className The name of the class possessing the attribute. * @param name The name of the attribute. * * @return An attribute expression for the attribute named name. * The returned object will be serialized as an instance of the * non-public class {@link <a * href="../../serialized-form.html#javax.management.QualifiedAttributeValueExp"> * javax.management.QualifiedAttributeValueExp</a>}. */ public static AttributeValueExp attr(String className, String name) { return new QualifiedAttributeValueExp(className, name); } /** {@collect.stats} * <p>Returns a new class attribute expression which can be used in any * Query call that expects a ValueExp.</p> * * <p>Evaluating this expression for a given * <code>objectName</code> includes performing {@link * MBeanServer#getObjectInstance * MBeanServer.getObjectInstance(objectName)}.</p> * * @return A class attribute expression. The returned object * will be serialized as an instance of the non-public class * {@link <a * href="../../serialized-form.html#javax.management.ClassAttributeValueExp"> * javax.management.ClassAttributeValueExp</a>}. */ public static AttributeValueExp classattr() { return new ClassAttributeValueExp(); } /** {@collect.stats} * Returns a constraint that is the negation of its argument. * * @param queryExp The constraint to negate. * * @return A negated constraint. The returned object will be * serialized as an instance of the non-public class {@link <a * href="../../serialized-form.html#javax.management.NotQueryExp"> * javax.management.NotQueryExp</a>}. */ public static QueryExp not(QueryExp queryExp) { return new NotQueryExp(queryExp); } /** {@collect.stats} * Returns an expression constraining a value to be one of an explicit list. * * @param val A value to be constrained. * @param valueList An array of ValueExps. * * @return A QueryExp that represents the constraint. The * returned object will be serialized as an instance of the * non-public class {@link <a * href="../../serialized-form.html#javax.management.InQueryExp"> * javax.management.InQueryExp</a>}. */ public static QueryExp in(ValueExp val, ValueExp valueList[]) { return new InQueryExp(val, valueList); } /** {@collect.stats} * Returns a new string expression. * * @param val The string value. * * @return A ValueExp object containing the string argument. */ public static StringValueExp value(String val) { return new StringValueExp(val); } /** {@collect.stats} * Returns a numeric value expression that can be used in any Query call * that expects a ValueExp. * * @param val An instance of Number. * * @return A ValueExp object containing the argument. The * returned object will be serialized as an instance of the * non-public class {@link <a * href="../../serialized-form.html#javax.management.NumericValueExp"> * javax.management.NumericValueExp</a>}. */ public static ValueExp value(Number val) { return new NumericValueExp(val); } /** {@collect.stats} * Returns a numeric value expression that can be used in any Query call * that expects a ValueExp. * * @param val An int value. * * @return A ValueExp object containing the argument. The * returned object will be serialized as an instance of the * non-public class {@link <a * href="../../serialized-form.html#javax.management.NumericValueExp"> * javax.management.NumericValueExp</a>}. */ public static ValueExp value(int val) { return new NumericValueExp((long) val); } /** {@collect.stats} * Returns a numeric value expression that can be used in any Query call * that expects a ValueExp. * * @param val A long value. * * @return A ValueExp object containing the argument. The * returned object will be serialized as an instance of the * non-public class {@link <a * href="../../serialized-form.html#javax.management.NumericValueExp"> * javax.management.NumericValueExp</a>}. */ public static ValueExp value(long val) { return new NumericValueExp(val); } /** {@collect.stats} * Returns a numeric value expression that can be used in any Query call * that expects a ValueExp. * * @param val A float value. * * @return A ValueExp object containing the argument. The * returned object will be serialized as an instance of the * non-public class {@link <a * href="../../serialized-form.html#javax.management.NumericValueExp"> * javax.management.NumericValueExp</a>}. */ public static ValueExp value(float val) { return new NumericValueExp((double) val); } /** {@collect.stats} * Returns a numeric value expression that can be used in any Query call * that expects a ValueExp. * * @param val A double value. * * @return A ValueExp object containing the argument. The * returned object will be serialized as an instance of the * non-public class {@link <a * href="../../serialized-form.html#javax.management.NumericValueExp"> * javax.management.NumericValueExp</a>}. */ public static ValueExp value(double val) { return new NumericValueExp(val); } /** {@collect.stats} * Returns a boolean value expression that can be used in any Query call * that expects a ValueExp. * * @param val A boolean value. * * @return A ValueExp object containing the argument. The * returned object will be serialized as an instance of the * non-public class {@link <a * href="../../serialized-form.html#javax.management.BooleanValueExp"> * javax.management.BooleanValueExp</a>}. */ public static ValueExp value(boolean val) { return new BooleanValueExp(val); } /** {@collect.stats} * Returns a binary expression representing the sum of two numeric values, * or the concatenation of two string values. * * @param value1 The first '+' operand. * @param value2 The second '+' operand. * * @return A ValueExp representing the sum or concatenation of * the two arguments. The returned object will be serialized as * an instance of the non-public class {@link <a * href="../../serialized-form.html#javax.management.BinaryOpValueExp"> * javax.management.BinaryOpValueExp</a>} with an {@code op} equal to * {@link #PLUS}. */ public static ValueExp plus(ValueExp value1, ValueExp value2) { return new BinaryOpValueExp(PLUS, value1, value2); } /** {@collect.stats} * Returns a binary expression representing the product of two numeric values. * * * @param value1 The first '*' operand. * @param value2 The second '*' operand. * * @return A ValueExp representing the product. The returned * object will be serialized as an instance of the non-public * class {@link <a * href="../../serialized-form.html#javax.management.BinaryOpValueExp"> * javax.management.BinaryOpValueExp</a>} with an {@code op} equal to * {@link #TIMES}. */ public static ValueExp times(ValueExp value1,ValueExp value2) { return new BinaryOpValueExp(TIMES, value1, value2); } /** {@collect.stats} * Returns a binary expression representing the difference between two numeric * values. * * @param value1 The first '-' operand. * @param value2 The second '-' operand. * * @return A ValueExp representing the difference between two * arguments. The returned object will be serialized as an * instance of the non-public class {@link <a * href="../../serialized-form.html#javax.management.BinaryOpValueExp"> * javax.management.BinaryOpValueExp</a>} with an {@code op} equal to * {@link #MINUS}. */ public static ValueExp minus(ValueExp value1, ValueExp value2) { return new BinaryOpValueExp(MINUS, value1, value2); } /** {@collect.stats} * Returns a binary expression representing the quotient of two numeric * values. * * @param value1 The first '/' operand. * @param value2 The second '/' operand. * * @return A ValueExp representing the quotient of two arguments. * The returned object will be serialized as an instance of the * non-public class {@link <a * href="../../serialized-form.html#javax.management.BinaryOpValueExp"> * javax.management.BinaryOpValueExp</a>} with an {@code op} equal to * {@link #DIV}. */ public static ValueExp div(ValueExp value1, ValueExp value2) { return new BinaryOpValueExp(DIV, value1, value2); } /** {@collect.stats} * Returns a query expression that represents a matching constraint on * a string argument. The value must start with the given literal string * value. * * @param a An attribute expression. * @param s A string value expression representing the beginning of the * string value. * * @return The constraint that a matches s. The returned object * will be serialized as an instance of the non-public class * {@link <a * href="../../serialized-form.html#javax.management.MatchQueryExp"> * javax.management.MatchQueryExp</a>}. */ public static QueryExp initialSubString(AttributeValueExp a, StringValueExp s) { return new MatchQueryExp(a, new StringValueExp(escapeString(s.getValue()) + "*")); } /** {@collect.stats} * Returns a query expression that represents a matching constraint on * a string argument. The value must contain the given literal string * value. * * @param a An attribute expression. * @param s A string value expression representing the substring. * * @return The constraint that a matches s. The returned object * will be serialized as an instance of the non-public class * {@link <a * href="../../serialized-form.html#javax.management.MatchQueryExp"> * javax.management.MatchQueryExp</a>}. */ public static QueryExp anySubString(AttributeValueExp a, StringValueExp s) { return new MatchQueryExp(a, new StringValueExp("*" + escapeString(s.getValue()) + "*")); } /** {@collect.stats} * Returns a query expression that represents a matching constraint on * a string argument. The value must end with the given literal string * value. * * @param a An attribute expression. * @param s A string value expression representing the end of the string * value. * * @return The constraint that a matches s. The returned object * will be serialized as an instance of the non-public class * {@link <a * href="../../serialized-form.html#javax.management.MatchQueryExp"> * javax.management.MatchQueryExp</a>}. */ public static QueryExp finalSubString(AttributeValueExp a, StringValueExp s) { return new MatchQueryExp(a, new StringValueExp("*" + escapeString(s.getValue()))); } /** {@collect.stats} * Returns a query expression that represents an inheritance constraint * on an MBean class. * <p>Example: to find MBeans that are instances of * {@link NotificationBroadcaster}, use * {@code Query.isInstanceOf(Query.value(NotificationBroadcaster.class.getName()))}. * </p> * <p>Evaluating this expression for a given * <code>objectName</code> includes performing {@link * MBeanServer#isInstanceOf MBeanServer.isInstanceOf(objectName, * ((StringValueExp)classNameValue.apply(objectName)).getValue()}.</p> * * @param classNameValue The {@link StringValueExp} returning the name * of the class of which selected MBeans should be instances. * @return a query expression that represents an inheritance * constraint on an MBean class. The returned object will be * serialized as an instance of the non-public class {@link <a * href="../../serialized-form.html#javax.management.InstanceOfQueryExp"> * javax.management.InstanceOfQueryExp</a>}. * @since 1.6 */ public static QueryExp isInstanceOf(StringValueExp classNameValue) { return new InstanceOfQueryExp(classNameValue); } /** {@collect.stats} * Utility method to escape strings used with * Query.{initial|any|final}SubString() methods. */ private static String escapeString(String s) { if (s == null) return null; s = s.replace("\\", "\\\\"); s = s.replace("*", "\\*"); s = s.replace("?", "\\?"); s = s.replace("[", "\\["); return s; } }
Java
/* * Copyright (c) 1999, 2006, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management; import com.sun.jmx.mbeanserver.GetPropertyAction; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.ObjectStreamField; import java.security.AccessController; /** {@collect.stats} * This class represents numbers that are arguments to relational constraints. * A NumericValueExp may be used anywhere a ValueExp is required. * * <p>The <b>serialVersionUID</b> of this class is <code>-4679739485102359104L</code>. * * @serial include * * @since 1.5 */ @SuppressWarnings("serial") // serialVersionUID not constant class NumericValueExp extends QueryEval implements ValueExp { // Serialization compatibility stuff: // Two serial forms are supported in this class. The selected form depends // on system property "jmx.serial.form": // - "1.0" for JMX 1.0 // - any other value for JMX 1.1 and higher // // Serial version for old serial form private static final long oldSerialVersionUID = -6227876276058904000L; // // Serial version for new serial form private static final long newSerialVersionUID = -4679739485102359104L; // // Serializable fields in old serial form private static final ObjectStreamField[] oldSerialPersistentFields = { new ObjectStreamField("longVal", Long.TYPE), new ObjectStreamField("doubleVal", Double.TYPE), new ObjectStreamField("valIsLong", Boolean.TYPE) }; // // Serializable fields in new serial form private static final ObjectStreamField[] newSerialPersistentFields = { new ObjectStreamField("val", Number.class) }; // // Actual serial version and serial form private static final long serialVersionUID; /** {@collect.stats} * @serialField val Number The numeric value * * <p>The <b>serialVersionUID</b> of this class is <code>-4679739485102359104L</code>. */ private static final ObjectStreamField[] serialPersistentFields; private Number val = new Double(0); private static boolean compat = false; static { try { GetPropertyAction act = new GetPropertyAction("jmx.serial.form"); String form = AccessController.doPrivileged(act); compat = (form != null && form.equals("1.0")); } catch (Exception e) { // OK: exception means no compat with 1.0, too bad } if (compat) { serialPersistentFields = oldSerialPersistentFields; serialVersionUID = oldSerialVersionUID; } else { serialPersistentFields = newSerialPersistentFields; serialVersionUID = newSerialVersionUID; } } // // END Serialization compatibility stuff /** {@collect.stats} * Basic constructor. */ public NumericValueExp() { } /** {@collect.stats} Creates a new NumericValue representing the numeric literal <val>.*/ NumericValueExp(Number val) { this.val = val; } /** {@collect.stats} * Returns a double numeric value */ public double doubleValue() { if (val instanceof Long || val instanceof Integer) { return (double)(val.longValue()); } return val.doubleValue(); } /** {@collect.stats} * Returns a long numeric value */ public long longValue() { if (val instanceof Long || val instanceof Integer) { return val.longValue(); } return (long)(val.doubleValue()); } /** {@collect.stats} * Returns true is if the numeric value is a long, false otherwise. */ public boolean isLong() { return (val instanceof Long || val instanceof Integer); } /** {@collect.stats} * Returns the string representing the object */ public String toString() { if (val instanceof Long || val instanceof Integer) { return String.valueOf(val.longValue()); } return String.valueOf(val.doubleValue()); } /** {@collect.stats} * Applies the ValueExp on a MBean. * * @param name The name of the MBean on which the ValueExp will be applied. * * @return The <CODE>ValueExp</CODE>. * * @exception BadStringOperationException * @exception BadBinaryOpValueExpException * @exception BadAttributeValueExpException * @exception InvalidApplicationException */ public ValueExp apply(ObjectName name) throws BadStringOperationException, BadBinaryOpValueExpException, BadAttributeValueExpException, InvalidApplicationException { return this; } /** {@collect.stats} * Deserializes a {@link NumericValueExp} from an {@link ObjectInputStream}. */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { if (compat) { // Read an object serialized in the old serial form // double doubleVal; long longVal; boolean isLong; ObjectInputStream.GetField fields = in.readFields(); doubleVal = fields.get("doubleVal", (double)0); if (fields.defaulted("doubleVal")) { throw new NullPointerException("doubleVal"); } longVal = fields.get("longVal", (long)0); if (fields.defaulted("longVal")) { throw new NullPointerException("longVal"); } isLong = fields.get("valIsLong", false); if (fields.defaulted("valIsLong")) { throw new NullPointerException("valIsLong"); } if (isLong) { this.val = new Long(longVal); } else { this.val = new Double(doubleVal); } } else { // Read an object serialized in the new serial form // in.defaultReadObject(); } } /** {@collect.stats} * Serializes a {@link NumericValueExp} to an {@link ObjectOutputStream}. */ private void writeObject(ObjectOutputStream out) throws IOException { if (compat) { // Serializes this instance in the old serial form // ObjectOutputStream.PutField fields = out.putFields(); fields.put("doubleVal", doubleValue()); fields.put("longVal", longValue()); fields.put("valIsLong", isLong()); out.writeFields(); } else { // Serializes this instance in the new serial form // out.defaultWriteObject(); } } }
Java
/* * Copyright (c) 2001, 2007, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management; import java.io.IOException; import java.io.ObjectInputStream; import java.security.BasicPermission; import java.security.Permission; import java.security.PermissionCollection; import java.util.Collections; import java.util.Enumeration; import java.util.Set; import java.util.StringTokenizer; /** {@collect.stats} A Permission to perform actions related to MBeanServers. The <em>name</em> of the permission specifies the operation requested or granted by the permission. For a granted permission, it can be <code>*</code> to allow all of the MBeanServer operations specified below. Otherwise, for a granted or requested permission, it must be one of the following: <dl> <dt>createMBeanServer</dt> <dd>Create a new MBeanServer object using the method {@link MBeanServerFactory#createMBeanServer()} or {@link MBeanServerFactory#createMBeanServer(java.lang.String)}. <dt>findMBeanServer</dt> <dd>Find an MBeanServer with a given name, or all MBeanServers in this JVM, using the method {@link MBeanServerFactory#findMBeanServer}. <dt>newMBeanServer</dt> <dd>Create a new MBeanServer object without keeping a reference to it, using the method {@link MBeanServerFactory#newMBeanServer()} or {@link MBeanServerFactory#newMBeanServer(java.lang.String)}. <dt>releaseMBeanServer</dt> <dd>Remove the MBeanServerFactory's reference to an MBeanServer, using the method {@link MBeanServerFactory#releaseMBeanServer}. </dl> The <em>name</em> of the permission can also denote a list of one or more comma-separated operations. Spaces are allowed at the beginning and end of the <em>name</em> and before and after commas. <p> <code>MBeanServerPermission("createMBeanServer")</code> implies <code>MBeanServerPermission("newMBeanServer")</code>. * * @since 1.5 */ public class MBeanServerPermission extends BasicPermission { private static final long serialVersionUID = -5661980843569388590L; private final static int CREATE = 0, FIND = 1, NEW = 2, RELEASE = 3, N_NAMES = 4; private final static String[] names = { "createMBeanServer", "findMBeanServer", "newMBeanServer", "releaseMBeanServer", }; private final static int CREATE_MASK = 1<<CREATE, FIND_MASK = 1<<FIND, NEW_MASK = 1<<NEW, RELEASE_MASK = 1<<RELEASE, ALL_MASK = CREATE_MASK|FIND_MASK|NEW_MASK|RELEASE_MASK; /* * Map from permission masks to canonical names. This array is * filled in on demand. * * This isn't very scalable. If we have more than five or six * permissions, we should consider doing this differently, * e.g. with a Map. */ private final static String[] canonicalNames = new String[1 << N_NAMES]; /* * The target names mask. This is not private to avoid having to * generate accessor methods for accesses from the collection class. * * This mask includes implied bits. So if it has CREATE_MASK then * it necessarily has NEW_MASK too. */ transient int mask; /** {@collect.stats} <p>Create a new MBeanServerPermission with the given name.</p> <p>This constructor is equivalent to <code>MBeanServerPermission(name,null)</code>.</p> @param name the name of the granted permission. It must respect the constraints spelt out in the description of the {@link MBeanServerPermission} class. @exception NullPointerException if the name is null. @exception IllegalArgumentException if the name is not <code>*</code> or one of the allowed names or a comma-separated list of the allowed names. */ public MBeanServerPermission(String name) { this(name, null); } /** {@collect.stats} <p>Create a new MBeanServerPermission with the given name.</p> @param name the name of the granted permission. It must respect the constraints spelt out in the description of the {@link MBeanServerPermission} class. @param actions the associated actions. This parameter is not currently used and must be null or the empty string. @exception NullPointerException if the name is null. @exception IllegalArgumentException if the name is not <code>*</code> or one of the allowed names or a comma-separated list of the allowed names, or if <code>actions</code> is a non-null non-empty string. * * @throws NullPointerException if <code>name</code> is <code>null</code>. * @throws IllegalArgumentException if <code>name</code> is empty or * if arguments are invalid. */ public MBeanServerPermission(String name, String actions) { super(getCanonicalName(parseMask(name)), actions); /* It's annoying to have to parse the name twice, but since Permission.getName() is final and since we can't access "this" until after the call to the superclass constructor, there isn't any very clean way to do this. MBeanServerPermission objects aren't constructed very often, luckily. */ mask = parseMask(name); /* Check that actions is a null empty string */ if (actions != null && actions.length() > 0) throw new IllegalArgumentException("MBeanServerPermission " + "actions must be null: " + actions); } MBeanServerPermission(int mask) { super(getCanonicalName(mask)); this.mask = impliedMask(mask); } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); mask = parseMask(getName()); } static int simplifyMask(int mask) { if ((mask & CREATE_MASK) != 0) mask &= ~NEW_MASK; return mask; } static int impliedMask(int mask) { if ((mask & CREATE_MASK) != 0) mask |= NEW_MASK; return mask; } static String getCanonicalName(int mask) { if (mask == ALL_MASK) return "*"; mask = simplifyMask(mask); synchronized (canonicalNames) { if (canonicalNames[mask] == null) canonicalNames[mask] = makeCanonicalName(mask); } return canonicalNames[mask]; } private static String makeCanonicalName(int mask) { final StringBuilder buf = new StringBuilder(); for (int i = 0; i < N_NAMES; i++) { if ((mask & (1<<i)) != 0) { if (buf.length() > 0) buf.append(','); buf.append(names[i]); } } return buf.toString().intern(); /* intern() avoids duplication when the mask has only one bit, so is equivalent to the string constants we have for the names[] array. */ } /* Convert the string into a bitmask, including bits that are implied by the permissions in the string. */ private static int parseMask(String name) { /* Check that target name is a non-null non-empty string */ if (name == null) { throw new NullPointerException("MBeanServerPermission: " + "target name can't be null"); } name = name.trim(); if (name.equals("*")) return ALL_MASK; /* If the name is empty, nameIndex will barf. */ if (name.indexOf(',') < 0) return impliedMask(1 << nameIndex(name.trim())); int mask = 0; StringTokenizer tok = new StringTokenizer(name, ","); while (tok.hasMoreTokens()) { String action = tok.nextToken(); int i = nameIndex(action.trim()); mask |= (1 << i); } return impliedMask(mask); } private static int nameIndex(String name) throws IllegalArgumentException { for (int i = 0; i < N_NAMES; i++) { if (names[i].equals(name)) return i; } final String msg = "Invalid MBeanServerPermission name: \"" + name + "\""; throw new IllegalArgumentException(msg); } public int hashCode() { return mask; } /** {@collect.stats} * <p>Checks if this MBeanServerPermission object "implies" the specified * permission.</p> * * <p>More specifically, this method returns true if:</p> * * <ul> * <li> <i>p</i> is an instance of MBeanServerPermission,</li> * <li> <i>p</i>'s target names are a subset of this object's target * names</li> * </ul> * * <p>The <code>createMBeanServer</code> permission implies the * <code>newMBeanServer</code> permission.</p> * * @param p the permission to check against. * @return true if the specified permission is implied by this object, * false if not. */ public boolean implies(Permission p) { if (!(p instanceof MBeanServerPermission)) return false; MBeanServerPermission that = (MBeanServerPermission) p; return ((this.mask & that.mask) == that.mask); } /** {@collect.stats} * Checks two MBeanServerPermission objects for equality. Checks that * <i>obj</i> is an MBeanServerPermission, and represents the same * list of allowable actions as this object. * <P> * @param obj the object we are testing for equality with this object. * @return true if the objects are equal. */ public boolean equals(Object obj) { if (obj == this) return true; if (! (obj instanceof MBeanServerPermission)) return false; MBeanServerPermission that = (MBeanServerPermission) obj; return (this.mask == that.mask); } public PermissionCollection newPermissionCollection() { return new MBeanServerPermissionCollection(); } } /** {@collect.stats} * Class returned by {@link MBeanServerPermission#newPermissionCollection()}. * * @serial include */ /* * Since every collection of MBSP can be represented by a single MBSP, * that is what our PermissionCollection does. We need to define a * PermissionCollection because the one inherited from BasicPermission * doesn't know that createMBeanServer implies newMBeanServer. * * Though the serial form is defined, the TCK does not check it. We do * not require independent implementations to duplicate it. Even though * PermissionCollection is Serializable, instances of this class will * hardly ever be serialized, and different implementations do not * typically exchange serialized permission collections. * * If we did require that a particular form be respected here, we would * logically also have to require it for * MBeanPermission.newPermissionCollection, which would preclude an * implementation from defining a PermissionCollection there with an * optimized "implies" method. */ class MBeanServerPermissionCollection extends PermissionCollection { /** {@collect.stats} @serial Null if no permissions in collection, otherwise a single permission that is the union of all permissions that have been added. */ private MBeanServerPermission collectionPermission; private static final long serialVersionUID = -5661980843569388590L; public synchronized void add(Permission permission) { if (!(permission instanceof MBeanServerPermission)) { final String msg = "Permission not an MBeanServerPermission: " + permission; throw new IllegalArgumentException(msg); } if (isReadOnly()) throw new SecurityException("Read-only permission collection"); MBeanServerPermission mbsp = (MBeanServerPermission) permission; if (collectionPermission == null) collectionPermission = mbsp; else if (!collectionPermission.implies(permission)) { int newmask = collectionPermission.mask | mbsp.mask; collectionPermission = new MBeanServerPermission(newmask); } } public synchronized boolean implies(Permission permission) { return (collectionPermission != null && collectionPermission.implies(permission)); } public synchronized Enumeration<Permission> elements() { Set<Permission> set; if (collectionPermission == null) set = Collections.emptySet(); else set = Collections.singleton((Permission) collectionPermission); return Collections.enumeration(set); } }
Java
/* * Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management; /** {@collect.stats} * The specified MBean listener does not exist in the repository. * * @since 1.5 */ public class ListenerNotFoundException extends OperationsException { /* Serial version */ private static final long serialVersionUID = -7242605822448519061L; /** {@collect.stats} * Default constructor. */ public ListenerNotFoundException() { super(); } /** {@collect.stats} * Constructor that allows a specific error message to be specified. * * @param message the detail message. */ public ListenerNotFoundException(String message) { super(message); } }
Java
/* * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management.loading; // Java import import com.sun.jmx.defaults.JmxProperties; import com.sun.jmx.defaults.ServiceName; import com.sun.jmx.remote.util.EnvHelp; import java.io.Externalizable; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.lang.reflect.Constructor; import java.net.MalformedURLException; import java.net.URL; import java.net.URLStreamHandlerFactory; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.logging.Level; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; import javax.management.InstanceAlreadyExistsException; import javax.management.InstanceNotFoundException; import javax.management.MBeanException; import javax.management.MBeanRegistration; import javax.management.MBeanRegistrationException; import javax.management.MBeanServer; import javax.management.NotCompliantMBeanException; import javax.management.ObjectInstance; import javax.management.ObjectName; import javax.management.ReflectionException; import static com.sun.jmx.defaults.JmxProperties.MLET_LIB_DIR; import static com.sun.jmx.defaults.JmxProperties.MLET_LOGGER; import com.sun.jmx.defaults.ServiceName; import javax.management.ServiceNotFoundException; /** {@collect.stats} * Allows you to instantiate and register one or several MBeans in the MBean server * coming from a remote URL. M-let is a shortcut for management applet. The m-let service does this * by loading an m-let text file, which specifies information on the MBeans to be obtained. * The information on each MBean is specified in a single instance of a tag, called the MLET tag. * The location of the m-let text file is specified by a URL. * <p> * The <CODE>MLET</CODE> tag has the following syntax: * <p> * &lt;<CODE>MLET</CODE><BR> * <CODE>CODE = </CODE><VAR>class</VAR><CODE> | OBJECT = </CODE><VAR>serfile</VAR><BR> * <CODE>ARCHIVE = &quot;</CODE><VAR>archiveList</VAR><CODE>&quot;</CODE><BR> * <CODE>[CODEBASE = </CODE><VAR>codebaseURL</VAR><CODE>]</CODE><BR> * <CODE>[NAME = </CODE><VAR>mbeanname</VAR><CODE>]</CODE><BR> * <CODE>[VERSION = </CODE><VAR>version</VAR><CODE>]</CODE><BR> * &gt;<BR> * <CODE>[</CODE><VAR>arglist</VAR><CODE>]</CODE><BR> * &lt;<CODE>/MLET</CODE>&gt; * <p> * where: * <DL> * <DT><CODE>CODE = </CODE><VAR>class</VAR></DT> * <DD> * This attribute specifies the full Java class name, including package name, of the MBean to be obtained. * The compiled <CODE>.class</CODE> file of the MBean must be contained in one of the <CODE>.jar</CODE> files specified by the <CODE>ARCHIVE</CODE> * attribute. Either <CODE>CODE</CODE> or <CODE>OBJECT</CODE> must be present. * </DD> * <DT><CODE>OBJECT = </CODE><VAR>serfile</VAR></DT> * <DD> * This attribute specifies the <CODE>.ser</CODE> file that contains a serialized representation of the MBean to be obtained. * This file must be contained in one of the <CODE>.jar</CODE> files specified by the <CODE>ARCHIVE</CODE> attribute. If the <CODE>.jar</CODE> file contains a directory hierarchy, specify the path of the file within this hierarchy. Otherwise a match will not be found. Either <CODE>CODE</CODE> or <CODE>OBJECT</CODE> must be present. * </DD> * <DT><CODE>ARCHIVE = &quot;</CODE><VAR>archiveList</VAR><CODE>&quot;</CODE></DT> * <DD> * This mandatory attribute specifies one or more <CODE>.jar</CODE> files * containing MBeans or other resources used by * the MBean to be obtained. One of the <CODE>.jar</CODE> files must contain the file specified by the <CODE>CODE</CODE> or <CODE>OBJECT</CODE> attribute. * If archivelist contains more than one file: * <UL> * <LI>Each file must be separated from the one that follows it by a comma (,). * <LI><VAR>archivelist</VAR> must be enclosed in double quote marks. * </UL> * All <CODE>.jar</CODE> files in <VAR>archivelist</VAR> must be stored in the directory specified by the code base URL. * </DD> * <DT><CODE>CODEBASE = </CODE><VAR>codebaseURL</VAR></DT> * <DD> * This optional attribute specifies the code base URL of the MBean to be obtained. It identifies the directory that contains * the <CODE>.jar</CODE> files specified by the <CODE>ARCHIVE</CODE> attribute. Specify this attribute only if the <CODE>.jar</CODE> files are not in the same * directory as the m-let text file. If this attribute is not specified, the base URL of the m-let text file is used. * </DD> * <DT><CODE>NAME = </CODE><VAR>mbeanname</VAR></DT> * <DD> * This optional attribute specifies the object name to be assigned to the * MBean instance when the m-let service registers it. If * <VAR>mbeanname</VAR> starts with the colon character (:), the domain * part of the object name is the default domain of the MBean server, * as returned by {@link javax.management.MBeanServer#getDefaultDomain()}. * </DD> * <DT><CODE>VERSION = </CODE><VAR>version</VAR></DT> * <DD> * This optional attribute specifies the version number of the MBean and * associated <CODE>.jar</CODE> files to be obtained. This version number can * be used to specify that the <CODE>.jar</CODE> files are loaded from the * server to update those stored locally in the cache the next time the m-let * text file is loaded. <VAR>version</VAR> must be a series of non-negative * decimal integers each separated by a period from the one that precedes it. * </DD> * <DT><VAR>arglist</VAR></DT> * <DD> * This optional attribute specifies a list of one or more parameters for the * MBean to be instantiated. This list describes the parameters to be passed the MBean's constructor. * Use the following syntax to specify each item in * <VAR>arglist</VAR>:</DD> * <DL> * <P> * <DT>&lt;<CODE>ARG TYPE=</CODE><VAR>argumentType</VAR> <CODE>VALUE=</CODE><VAR>value</VAR>&gt;</DT> * <P> * <DD>where:</DD> * <UL> * <LI><VAR>argumentType</VAR> is the type of the argument that will be passed as parameter to the MBean's constructor.</UL> * </DL> * <P>The arguments' type in the argument list should be a Java primitive type or a Java basic type * (<CODE>java.lang.Boolean, java.lang.Byte, java.lang.Short, java.lang.Long, java.lang.Integer, java.lang.Float, java.lang.Double, java.lang.String</CODE>). * </DL> * * When an m-let text file is loaded, an * instance of each MBean specified in the file is created and registered. * <P> * The m-let service extends the <CODE>java.net.URLClassLoader</CODE> and can be used to load remote classes * and jar files in the VM of the agent. * <p><STRONG>Note - </STRONG> The <CODE>MLet</CODE> class loader uses the {@link javax.management.MBeanServerFactory#getClassLoaderRepository(javax.management.MBeanServer)} * to load classes that could not be found in the loaded jar files. * * @since 1.5 */ public class MLet extends java.net.URLClassLoader implements MLetMBean, MBeanRegistration, Externalizable { private static final long serialVersionUID = 3636148327800330130L; /* * ------------------------------------------ * PRIVATE VARIABLES * ------------------------------------------ */ /** {@collect.stats} * The reference to the MBean server. * @serial */ private MBeanServer server = null; /** {@collect.stats} * The list of instances of the <CODE>MLetContent</CODE> * class found at the specified URL. * @serial */ private List<MLetContent> mletList = new ArrayList<MLetContent>(); /** {@collect.stats} * The directory used for storing libraries locally before they are loaded. */ private String libraryDirectory; /** {@collect.stats} * The object name of the MLet Service. * @serial */ private ObjectName mletObjectName = null; /** {@collect.stats} * The URLs of the MLet Service. * @serial */ private URL[] myUrls = null; /** {@collect.stats} * What ClassLoaderRepository, if any, to use if this MLet * doesn't find an asked-for class. */ private transient ClassLoaderRepository currentClr; /** {@collect.stats} * True if we should consult the {@link ClassLoaderRepository} * when we do not find a class ourselves. */ private transient boolean delegateToCLR; /** {@collect.stats} * objects maps from primitive classes to primitive object classes. */ private Map<String,Class<?>> primitiveClasses = new HashMap<String,Class<?>>(8) ; { primitiveClasses.put(Boolean.TYPE.toString(), Boolean.class); primitiveClasses.put(Character.TYPE.toString(), Character.class); primitiveClasses.put(Byte.TYPE.toString(), Byte.class); primitiveClasses.put(Short.TYPE.toString(), Short.class); primitiveClasses.put(Integer.TYPE.toString(), Integer.class); primitiveClasses.put(Long.TYPE.toString(), Long.class); primitiveClasses.put(Float.TYPE.toString(), Float.class); primitiveClasses.put(Double.TYPE.toString(), Double.class); } /* * ------------------------------------------ * CONSTRUCTORS * ------------------------------------------ */ /* * The constructor stuff would be considerably simplified if our * parent, URLClassLoader, specified that its one- and * two-argument constructors were equivalent to its * three-argument constructor with trailing null arguments. But * it doesn't, which prevents us from having all the constructors * but one call this(...args...). */ /** {@collect.stats} * Constructs a new MLet using the default delegation parent ClassLoader. */ public MLet() { this(new URL[0]); } /** {@collect.stats} * Constructs a new MLet for the specified URLs using the default * delegation parent ClassLoader. The URLs will be searched in * the order specified for classes and resources after first * searching in the parent class loader. * * @param urls The URLs from which to load classes and resources. * */ public MLet(URL[] urls) { this(urls, true); } /** {@collect.stats} * Constructs a new MLet for the given URLs. The URLs will be * searched in the order specified for classes and resources * after first searching in the specified parent class loader. * The parent argument will be used as the parent class loader * for delegation. * * @param urls The URLs from which to load classes and resources. * @param parent The parent class loader for delegation. * */ public MLet(URL[] urls, ClassLoader parent) { this(urls, parent, true); } /** {@collect.stats} * Constructs a new MLet for the specified URLs, parent class * loader, and URLStreamHandlerFactory. The parent argument will * be used as the parent class loader for delegation. The factory * argument will be used as the stream handler factory to obtain * protocol handlers when creating new URLs. * * @param urls The URLs from which to load classes and resources. * @param parent The parent class loader for delegation. * @param factory The URLStreamHandlerFactory to use when creating URLs. * */ public MLet(URL[] urls, ClassLoader parent, URLStreamHandlerFactory factory) { this(urls, parent, factory, true); } /** {@collect.stats} * Constructs a new MLet for the specified URLs using the default * delegation parent ClassLoader. The URLs will be searched in * the order specified for classes and resources after first * searching in the parent class loader. * * @param urls The URLs from which to load classes and resources. * @param delegateToCLR True if, when a class is not found in * either the parent ClassLoader or the URLs, the MLet should delegate * to its containing MBeanServer's {@link ClassLoaderRepository}. * */ public MLet(URL[] urls, boolean delegateToCLR) { super(urls); init(delegateToCLR); } /** {@collect.stats} * Constructs a new MLet for the given URLs. The URLs will be * searched in the order specified for classes and resources * after first searching in the specified parent class loader. * The parent argument will be used as the parent class loader * for delegation. * * @param urls The URLs from which to load classes and resources. * @param parent The parent class loader for delegation. * @param delegateToCLR True if, when a class is not found in * either the parent ClassLoader or the URLs, the MLet should delegate * to its containing MBeanServer's {@link ClassLoaderRepository}. * */ public MLet(URL[] urls, ClassLoader parent, boolean delegateToCLR) { super(urls, parent); init(delegateToCLR); } /** {@collect.stats} * Constructs a new MLet for the specified URLs, parent class * loader, and URLStreamHandlerFactory. The parent argument will * be used as the parent class loader for delegation. The factory * argument will be used as the stream handler factory to obtain * protocol handlers when creating new URLs. * * @param urls The URLs from which to load classes and resources. * @param parent The parent class loader for delegation. * @param factory The URLStreamHandlerFactory to use when creating URLs. * @param delegateToCLR True if, when a class is not found in * either the parent ClassLoader or the URLs, the MLet should delegate * to its containing MBeanServer's {@link ClassLoaderRepository}. * */ public MLet(URL[] urls, ClassLoader parent, URLStreamHandlerFactory factory, boolean delegateToCLR) { super(urls, parent, factory); init(delegateToCLR); } private void init(boolean delegateToCLR) { this.delegateToCLR = delegateToCLR; try { libraryDirectory = System.getProperty(MLET_LIB_DIR); if (libraryDirectory == null) libraryDirectory = getTmpDir(); } catch (SecurityException e) { // OK : We don't do AccessController.doPrivileged, but we don't // stop the user from creating an MLet just because they // can't read the MLET_LIB_DIR or java.io.tmpdir properties // either. } } /* * ------------------------------------------ * PUBLIC METHODS * ------------------------------------------ */ /** {@collect.stats} * Appends the specified URL to the list of URLs to search for classes and * resources. */ public void addURL(URL url) { if (!Arrays.asList(getURLs()).contains(url)) super.addURL(url); } /** {@collect.stats} * Appends the specified URL to the list of URLs to search for classes and * resources. * @exception ServiceNotFoundException The specified URL is malformed. */ public void addURL(String url) throws ServiceNotFoundException { try { URL ur = new URL(url); if (!Arrays.asList(getURLs()).contains(ur)) super.addURL(ur); } catch (MalformedURLException e) { if (MLET_LOGGER.isLoggable(Level.FINEST)) { MLET_LOGGER.logp(Level.FINEST, MLet.class.getName(), "addUrl", "Malformed URL: " + url, e); } throw new ServiceNotFoundException("The specified URL is malformed"); } } /** {@collect.stats} Returns the search path of URLs for loading classes and resources. * This includes the original list of URLs specified to the constructor, * along with any URLs subsequently appended by the addURL() method. */ public URL[] getURLs() { return super.getURLs(); } /** {@collect.stats} * Loads a text file containing MLET tags that define the MBeans to * be added to the MBean server. The location of the text file is specified by * a URL. The MBeans specified in the MLET file will be instantiated and * registered in the MBean server. * * @param url The URL of the text file to be loaded as URL object. * * @return A set containing one entry per MLET tag in the m-let text file loaded. * Each entry specifies either the ObjectInstance for the created MBean, or a throwable object * (that is, an error or an exception) if the MBean could not be created. * * @exception ServiceNotFoundException One of the following errors has occurred: The m-let text file does * not contain an MLET tag, the m-let text file is not found, a mandatory * attribute of the MLET tag is not specified, the value of url is * null. * @exception IllegalStateException MLet MBean is not registered with an MBeanServer. */ public Set<Object> getMBeansFromURL(URL url) throws ServiceNotFoundException { if (url == null) { throw new ServiceNotFoundException("The specified URL is null"); } return getMBeansFromURL(url.toString()); } /** {@collect.stats} * Loads a text file containing MLET tags that define the MBeans to * be added to the MBean server. The location of the text file is specified by * a URL. The MBeans specified in the MLET file will be instantiated and * registered in the MBean server. * * @param url The URL of the text file to be loaded as String object. * * @return A set containing one entry per MLET tag in the m-let * text file loaded. Each entry specifies either the * ObjectInstance for the created MBean, or a throwable object * (that is, an error or an exception) if the MBean could not be * created. * * @exception ServiceNotFoundException One of the following * errors has occurred: The m-let text file does not contain an * MLET tag, the m-let text file is not found, a mandatory * attribute of the MLET tag is not specified, the url is * malformed. * @exception IllegalStateException MLet MBean is not registered * with an MBeanServer. * */ public Set<Object> getMBeansFromURL(String url) throws ServiceNotFoundException { String mth = "getMBeansFromURL"; if (server == null) { throw new IllegalStateException("This MLet MBean is not " + "registered with an MBeanServer."); } // Parse arguments if (url == null) { MLET_LOGGER.logp(Level.FINER, MLet.class.getName(), mth, "URL is null"); throw new ServiceNotFoundException("The specified URL is null"); } else { url = url.replace(File.separatorChar,'/'); } if (MLET_LOGGER.isLoggable(Level.FINER)) { MLET_LOGGER.logp(Level.FINER, MLet.class.getName(), mth, "<URL = " + url + ">"); } // Parse URL try { MLetParser parser = new MLetParser(); mletList = parser.parseURL(url); } catch (Exception e) { final String msg = "Problems while parsing URL [" + url + "], got exception [" + e.toString() + "]"; MLET_LOGGER.logp(Level.FINER, MLet.class.getName(), mth, msg); throw EnvHelp.initCause(new ServiceNotFoundException(msg), e); } // Check that the list of MLets is not empty if (mletList.size() == 0) { final String msg = "File " + url + " not found or MLET tag not defined in file"; MLET_LOGGER.logp(Level.FINER, MLet.class.getName(), mth, msg); throw new ServiceNotFoundException(msg); } // Walk through the list of MLets Set<Object> mbeans = new HashSet<Object>(); for (MLetContent elmt : mletList) { // Initialize local variables String code = elmt.getCode(); if (code != null) { if (code.endsWith(".class")) { code = code.substring(0, code.length() - 6); } } String name = elmt.getName(); URL codebase = elmt.getCodeBase(); String version = elmt.getVersion(); String serName = elmt.getSerializedObject(); String jarFiles = elmt.getJarFiles(); URL documentBase = elmt.getDocumentBase(); // Display debug information if (MLET_LOGGER.isLoggable(Level.FINER)) { final StringBuilder strb = new StringBuilder() .append("\n\tMLET TAG = ").append(elmt.getAttributes()) .append("\n\tCODEBASE = ").append(codebase) .append("\n\tARCHIVE = ").append(jarFiles) .append("\n\tCODE = ").append(code) .append("\n\tOBJECT = ").append(serName) .append("\n\tNAME = ").append(name) .append("\n\tVERSION = ").append(version) .append("\n\tDOCUMENT URL = ").append(documentBase); MLET_LOGGER.logp(Level.FINER, MLet.class.getName(), mth, strb.toString()); } // Load classes from JAR files StringTokenizer st = new StringTokenizer(jarFiles, ",", false); while (st.hasMoreTokens()) { String tok = st.nextToken().trim(); if (MLET_LOGGER.isLoggable(Level.FINER)) { MLET_LOGGER.logp(Level.FINER, MLet.class.getName(), mth, "Load archive for codebase <" + codebase + ">, file <" + tok + ">"); } // Check which is the codebase to be used for loading the jar file. // If we are using the base MLet implementation then it will be // always the remote server but if the service has been extended in // order to support caching and versioning then this method will // return the appropriate one. // try { codebase = check(version, codebase, tok, elmt); } catch (Exception ex) { MLET_LOGGER.logp(Level.FINEST, MLet.class.getName(), mth, "Got unexpected exception", ex); mbeans.add(ex); continue; } // Appends the specified JAR file URL to the list of // URLs to search for classes and resources. try { if (!Arrays.asList(getURLs()) .contains(new URL(codebase.toString() + tok))) { addURL(codebase + tok); } } catch (MalformedURLException me) { // OK : Ignore jar file if its name provokes the // URL to be an invalid one. } } // Instantiate the class specified in the // CODE or OBJECT section of the MLet tag // Object o = null; ObjectInstance objInst = null; if (code != null && serName != null) { final String msg = "CODE and OBJECT parameters cannot be specified at the " + "same time in tag MLET"; MLET_LOGGER.logp(Level.FINER, MLet.class.getName(), mth, msg); mbeans.add(new Error(msg)); continue; } if (code == null && serName == null) { final String msg = "Either CODE or OBJECT parameter must be specified in " + "tag MLET"; MLET_LOGGER.logp(Level.FINER, MLet.class.getName(), mth, msg); mbeans.add(new Error(msg)); continue; } try { if (code != null) { List<String> signat = elmt.getParameterTypes(); List<String> stringPars = elmt.getParameterValues(); List<Object> objectPars = new ArrayList<Object>(); for (int i = 0; i < signat.size(); i++) { objectPars.add(constructParameter(stringPars.get(i), signat.get(i))); } if (signat.isEmpty()) { if (name == null) { objInst = server.createMBean(code, null, mletObjectName); } else { objInst = server.createMBean(code, new ObjectName(name), mletObjectName); } } else { Object[] parms = objectPars.toArray(); String[] signature = new String[signat.size()]; signat.toArray(signature); if (MLET_LOGGER.isLoggable(Level.FINEST)) { final StringBuilder strb = new StringBuilder(); for (int i = 0; i < signature.length; i++) { strb.append("\n\tSignature = ") .append(signature[i]) .append("\t\nParams = ") .append(parms[i]); } MLET_LOGGER.logp(Level.FINEST, MLet.class.getName(), mth, strb.toString()); } if (name == null) { objInst = server.createMBean(code, null, mletObjectName, parms, signature); } else { objInst = server.createMBean(code, new ObjectName(name), mletObjectName, parms, signature); } } } else { o = loadSerializedObject(codebase,serName); if (name == null) { server.registerMBean(o, null); } else { server.registerMBean(o, new ObjectName(name)); } objInst = new ObjectInstance(name, o.getClass().getName()); } } catch (ReflectionException ex) { MLET_LOGGER.logp(Level.FINER, MLet.class.getName(), mth, "ReflectionException", ex); mbeans.add(ex); continue; } catch (InstanceAlreadyExistsException ex) { MLET_LOGGER.logp(Level.FINER, MLet.class.getName(), mth, "InstanceAlreadyExistsException", ex); mbeans.add(ex); continue; } catch (MBeanRegistrationException ex) { MLET_LOGGER.logp(Level.FINER, MLet.class.getName(), mth, "MBeanRegistrationException", ex); mbeans.add(ex); continue; } catch (MBeanException ex) { MLET_LOGGER.logp(Level.FINER, MLet.class.getName(), mth, "MBeanException", ex); mbeans.add(ex); continue; } catch (NotCompliantMBeanException ex) { MLET_LOGGER.logp(Level.FINER, MLet.class.getName(), mth, "NotCompliantMBeanException", ex); mbeans.add(ex); continue; } catch (InstanceNotFoundException ex) { MLET_LOGGER.logp(Level.FINER, MLet.class.getName(), mth, "InstanceNotFoundException", ex); mbeans.add(ex); continue; } catch (IOException ex) { MLET_LOGGER.logp(Level.FINER, MLet.class.getName(), mth, "IOException", ex); mbeans.add(ex); continue; } catch (SecurityException ex) { MLET_LOGGER.logp(Level.FINER, MLet.class.getName(), mth, "SecurityException", ex); mbeans.add(ex); continue; } catch (Exception ex) { MLET_LOGGER.logp(Level.FINER, MLet.class.getName(), mth, "Exception", ex); mbeans.add(ex); continue; } catch (Error ex) { MLET_LOGGER.logp(Level.FINER, MLet.class.getName(), mth, "Error", ex); mbeans.add(ex); continue; } mbeans.add(objInst); } return mbeans; } /** {@collect.stats} * Gets the current directory used by the library loader for * storing native libraries before they are loaded into memory. * * @return The current directory used by the library loader. * * @see #setLibraryDirectory * * @throws UnsupportedOperationException if this implementation * does not support storing native libraries in this way. */ public synchronized String getLibraryDirectory() { return libraryDirectory; } /** {@collect.stats} * Sets the directory used by the library loader for storing * native libraries before they are loaded into memory. * * @param libdir The directory used by the library loader. * * @see #getLibraryDirectory * * @throws UnsupportedOperationException if this implementation * does not support storing native libraries in this way. */ public synchronized void setLibraryDirectory(String libdir) { libraryDirectory = libdir; } /** {@collect.stats} * Allows the m-let to perform any operations it needs before * being registered in the MBean server. If the ObjectName is * null, the m-let provides a default name for its registration * &lt;defaultDomain&gt;:type=MLet * * @param server The MBean server in which the m-let will be registered. * @param name The object name of the m-let. * * @return The name of the m-let registered. * * @exception java.lang.Exception This exception should be caught by the MBean server and re-thrown *as an MBeanRegistrationException. */ public ObjectName preRegister(MBeanServer server, ObjectName name) throws Exception { // Initialize local pointer to the MBean server setMBeanServer(server); // If no name is specified return a default name for the MLet if (name == null) { name = new ObjectName(server.getDefaultDomain() + ":" + ServiceName.MLET); } this.mletObjectName = name; return this.mletObjectName; } /** {@collect.stats} * Allows the m-let to perform any operations needed after having been * registered in the MBean server or after the registration has failed. * * @param registrationDone Indicates whether or not the m-let has * been successfully registered in the MBean server. The value * false means that either the registration phase has failed. * */ public void postRegister (Boolean registrationDone) { } /** {@collect.stats} * Allows the m-let to perform any operations it needs before being unregistered * by the MBean server. * * @exception java.langException This exception should be caught * by the MBean server and re-thrown as an * MBeanRegistrationException. */ public void preDeregister() throws java.lang.Exception { } /** {@collect.stats} * Allows the m-let to perform any operations needed after having been * unregistered in the MBean server. */ public void postDeregister() { } /** {@collect.stats} * <p>Save this MLet's contents to the given {@link ObjectOutput}. * Not all implementations support this method. Those that do not * throw {@link UnsupportedOperationException}. A subclass may * override this method to support it or to change the format of * the written data.</p> * * <p>The format of the written data is not specified, but if * an implementation supports {@link #writeExternal} it must * also support {@link #readExternal} in such a way that what is * written by the former can be read by the latter.</p> * * @param out The object output stream to write to. * * @exception IOException If a problem occurred while writing. * @exception UnsupportedOperationException If this * implementation does not support this operation. */ public void writeExternal(ObjectOutput out) throws IOException, UnsupportedOperationException { throw new UnsupportedOperationException("MLet.writeExternal"); } /** {@collect.stats} * <p>Restore this MLet's contents from the given {@link ObjectInput}. * Not all implementations support this method. Those that do not * throw {@link UnsupportedOperationException}. A subclass may * override this method to support it or to change the format of * the read data.</p> * * <p>The format of the read data is not specified, but if an * implementation supports {@link #readExternal} it must also * support {@link #writeExternal} in such a way that what is * written by the latter can be read by the former.</p> * * @param in The object input stream to read from. * * @exception IOException if a problem occurred while reading. * @exception ClassNotFoundException if the class for the object * being restored cannot be found. * @exception UnsupportedOperationException if this * implementation does not support this operation. */ public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException, UnsupportedOperationException { throw new UnsupportedOperationException("MLet.readExternal"); } /* * ------------------------------------------ * PACKAGE METHODS * ------------------------------------------ */ /** {@collect.stats} * <p>Load a class, using the given {@link ClassLoaderRepository} if * the class is not found in this MLet's URLs. The given * ClassLoaderRepository can be null, in which case a {@link * ClassNotFoundException} occurs immediately if the class is not * found in this MLet's URLs.</p> * * @param name The name of the class we want to load. * @param clr The ClassLoaderRepository that will be used to search * for the given class, if it is not found in this * ClassLoader. May be null. * @return The resulting Class object. * @exception ClassNotFoundException The specified class could not be * found in this ClassLoader nor in the given * ClassLoaderRepository. * */ public synchronized Class<?> loadClass(String name, ClassLoaderRepository clr) throws ClassNotFoundException { final ClassLoaderRepository before=currentClr; try { currentClr = clr; return loadClass(name); } finally { currentClr = before; } } /* * ------------------------------------------ * PROTECTED METHODS * ------------------------------------------ */ /** {@collect.stats} * This is the main method for class loaders that is being redefined. * * @param name The name of the class. * * @return The resulting Class object. * * @exception ClassNotFoundException The specified class could not be * found. */ protected Class<?> findClass(String name) throws ClassNotFoundException { /* currentClr is context sensitive - used to avoid recursion in the class loader repository. (This is no longer necessary with the new CLR semantics but is kept for compatibility with code that might have called the two-parameter loadClass explicitly.) */ return findClass(name, currentClr); } /** {@collect.stats} * Called by {@link MLet#findClass(java.lang.String)}. * * @param name The name of the class that we want to load/find. * @param clr The ClassLoaderRepository that can be used to search * for the given class. This parameter is * <code>null</code> when called from within the * {@link javax.management.MBeanServerFactory#getClassLoaderRepository(javax.management.MBeanServer) Class Loader Repository}. * @exception ClassNotFoundException The specified class could not be * found. * **/ Class<?> findClass(String name, ClassLoaderRepository clr) throws ClassNotFoundException { Class<?> c = null; MLET_LOGGER.logp(Level.FINER, MLet.class.getName(), "findClass", name); // Try looking in the JAR: try { c = super.findClass(name); if (MLET_LOGGER.isLoggable(Level.FINER)) { MLET_LOGGER.logp(Level.FINER, MLet.class.getName(), "findClass", "Class " + name + " loaded through MLet classloader"); } } catch (ClassNotFoundException e) { // Drop through if (MLET_LOGGER.isLoggable(Level.FINEST)) { MLET_LOGGER.logp(Level.FINEST, MLet.class.getName(), "findClass", "Class " + name + " not found locally"); } } // if we are not called from the ClassLoaderRepository if (c == null && delegateToCLR && clr != null) { // Try the classloader repository: // try { if (MLET_LOGGER.isLoggable(Level.FINEST)) { MLET_LOGGER.logp(Level.FINEST, MLet.class.getName(), "findClass", "Class " + name + " : looking in CLR"); } c = clr.loadClassBefore(this, name); // The loadClassBefore method never returns null. // If the class is not found we get an exception. if (MLET_LOGGER.isLoggable(Level.FINER)) { MLET_LOGGER.logp(Level.FINER, MLet.class.getName(), "findClass", "Class " + name + " loaded through " + "the default classloader repository"); } } catch (ClassNotFoundException e) { // Drop through if (MLET_LOGGER.isLoggable(Level.FINEST)) { MLET_LOGGER.logp(Level.FINEST, MLet.class.getName(), "findClass", "Class " + name + " not found in CLR"); } } } if (c == null) { MLET_LOGGER.logp(Level.FINEST, MLet.class.getName(), "findClass", "Failed to load class " + name); throw new ClassNotFoundException(name); } return c; } /** {@collect.stats} * Returns the absolute path name of a native library. The VM * invokes this method to locate the native libraries that belong * to classes loaded with this class loader. Libraries are * searched in the JAR files using first just the native library * name and if not found the native library name together with * the architecture-specific path name * (<code>OSName/OSArch/OSVersion/lib/nativelibname</code>), i.e. * <p> * the library stat on Solaris SPARC 5.7 will be searched in the JAR file as: * <OL> * <LI>libstat.so * <LI>SunOS/sparc/5.7/lib/libstat.so * </OL> * the library stat on Windows NT 4.0 will be searched in the JAR file as: * <OL> * <LI>stat.dll * <LI>WindowsNT/x86/4.0/lib/stat.dll * </OL> * * <p>More specifically, let <em>{@code nativelibname}</em> be the result of * {@link System#mapLibraryName(java.lang.String) * System.mapLibraryName}{@code (libname)}. Then the following names are * searched in the JAR files, in order:<br> * <em>{@code nativelibname}</em><br> * {@code <os.name>/<os.arch>/<os.version>/lib/}<em>{@code nativelibname}</em><br> * where {@code <X>} means {@code System.getProperty(X)} with any * spaces in the result removed, and {@code /} stands for the * file separator character ({@link File#separator}). * <p> * If this method returns <code>null</code>, i.e. the libraries * were not found in any of the JAR files loaded with this class * loader, the VM searches the library along the path specified * as the <code>java.library.path</code> property. * * @param libname The library name. * * @return The absolute path of the native library. */ protected String findLibrary(String libname) { String abs_path; String mth = "findLibrary"; // Get the platform-specific string representing a native library. // String nativelibname = System.mapLibraryName(libname); // // See if the native library is accessible as a resource through the JAR file. // if (MLET_LOGGER.isLoggable(Level.FINER)) { MLET_LOGGER.logp(Level.FINER, MLet.class.getName(), mth, "Search " + libname + " in all JAR files"); } // First try to locate the library in the JAR file using only // the native library name. e.g. if user requested a load // for "foo" on Solaris SPARC 5.7 we try to load "libfoo.so" // from the JAR file. // if (MLET_LOGGER.isLoggable(Level.FINER)) { MLET_LOGGER.logp(Level.FINER, MLet.class.getName(), mth, "loadLibraryAsResource(" + nativelibname + ")"); } abs_path = loadLibraryAsResource(nativelibname); if (abs_path != null) { if (MLET_LOGGER.isLoggable(Level.FINER)) { MLET_LOGGER.logp(Level.FINER, MLet.class.getName(), mth, nativelibname + " loaded, absolute path = " + abs_path); } return abs_path; } // Next try to locate it using the native library name and // the architecture-specific path name. e.g. if user // requested a load for "foo" on Solaris SPARC 5.7 we try to // load "SunOS/sparc/5.7/lib/libfoo.so" from the JAR file. // nativelibname = removeSpace(System.getProperty("os.name")) + File.separator + removeSpace(System.getProperty("os.arch")) + File.separator + removeSpace(System.getProperty("os.version")) + File.separator + "lib" + File.separator + nativelibname; if (MLET_LOGGER.isLoggable(Level.FINER)) { MLET_LOGGER.logp(Level.FINER, MLet.class.getName(), mth, "loadLibraryAsResource(" + nativelibname + ")"); } abs_path = loadLibraryAsResource(nativelibname); if (abs_path != null) { if (MLET_LOGGER.isLoggable(Level.FINER)) { MLET_LOGGER.logp(Level.FINER, MLet.class.getName(), mth, nativelibname + " loaded, absolute path = " + abs_path); } return abs_path; } // // All paths exhausted, library not found in JAR file. // if (MLET_LOGGER.isLoggable(Level.FINER)) { MLET_LOGGER.logp(Level.FINER, MLet.class.getName(), mth, libname + " not found in any JAR file"); MLET_LOGGER.logp(Level.FINER, MLet.class.getName(), mth, "Search " + libname + " along the path " + "specified as the java.library.path property"); } // Let the VM search the library along the path // specified as the java.library.path property. // return null; } /* * ------------------------------------------ * PRIVATE METHODS * ------------------------------------------ */ private String getTmpDir() { // JDK 1.4 String tmpDir = System.getProperty("java.io.tmpdir"); if (tmpDir != null) return tmpDir; // JDK < 1.4 File tmpFile = null; try { // Try to guess the system temporary dir... tmpFile = File.createTempFile("tmp","jmx"); if (tmpFile == null) return null; final File tmpDirFile = tmpFile.getParentFile(); if (tmpDirFile == null) return null; return tmpDirFile.getAbsolutePath(); } catch (Exception x) { MLET_LOGGER.logp(Level.FINEST, MLet.class.getName(), "getTmpDir", "Failed to determine system temporary dir"); return null; } finally { // Cleanup ... if (tmpFile!=null) try { tmpFile.delete(); } catch (Exception x) { MLET_LOGGER.logp(Level.FINEST, MLet.class.getName(), "getTmpDir", "Failed to delete temporary file", x); } } } /** {@collect.stats} * Search the specified native library in any of the JAR files * loaded by this classloader. If the library is found copy it * into the library directory and return the absolute path. If * the library is not found then return null. */ private synchronized String loadLibraryAsResource(String libname) { try { InputStream is = getResourceAsStream(libname.replace(File.separatorChar,'/')); if (is != null) { File directory = new File(libraryDirectory); directory.mkdirs(); File file = File.createTempFile(libname + ".", null, directory); file.deleteOnExit(); FileOutputStream fileOutput = new FileOutputStream(file); int c; while ((c = is.read()) != -1) { fileOutput.write(c); } is.close(); fileOutput.close(); if (file.exists()) { return file.getAbsolutePath(); } } } catch (Exception e) { MLET_LOGGER.logp(Level.FINEST, MLet.class.getName(), "loadLibraryAsResource", "Failed to load library : " + libname, e); return null; } return null; } /** {@collect.stats} * Removes any white space from a string. This is used to * convert strings such as "Windows NT" to "WindowsNT". */ private String removeSpace(String s) { s = s.trim(); int j = s.indexOf(' '); if (j == -1) { return s; } String temp = ""; int k = 0; while (j != -1) { s = s.substring(k); j = s.indexOf(' '); if (j != -1) { temp = temp + s.substring(0, j); } else { temp = temp + s.substring(0); } k = j + 1; } return temp; } /** {@collect.stats} * <p>This method is to be overridden when extending this service to * support caching and versioning. It is called from {@link * #getMBeansFromURL getMBeansFromURL} when the version, * codebase, and jarfile have been extracted from the MLet file, * and can be used to verify that it is all right to load the * given MBean, or to replace the given URL with a different one.</p> * * <p>The default implementation of this method returns * <code>codebase</code> unchanged.</p> * * @param version The version number of the <CODE>.jar</CODE> * file stored locally. * @param codebase The base URL of the remote <CODE>.jar</CODE> file. * @param jarfile The name of the <CODE>.jar</CODE> file to be loaded. * @param mlet The <CODE>MLetContent</CODE> instance that * represents the <CODE>MLET</CODE> tag. * * @return the codebase to use for the loaded MBean. The returned * value should not be null. * * @exception Exception if the MBean is not to be loaded for some * reason. The exception will be added to the set returned by * {@link #getMBeansFromURL getMBeansFromURL}. * */ protected URL check(String version, URL codebase, String jarfile, MLetContent mlet) throws Exception { return codebase; } /** {@collect.stats} * Loads the serialized object specified by the <CODE>OBJECT</CODE> * attribute of the <CODE>MLET</CODE> tag. * * @param codebase The <CODE>codebase</CODE>. * @param filename The name of the file containing the serialized object. * @return The serialized object. * @exception ClassNotFoundException The specified serialized * object could not be found. * @exception IOException An I/O error occurred while loading * serialized object. */ private Object loadSerializedObject(URL codebase, String filename) throws IOException, ClassNotFoundException { if (filename != null) { filename = filename.replace(File.separatorChar,'/'); } if (MLET_LOGGER.isLoggable(Level.FINER)) { MLET_LOGGER.logp(Level.FINER, MLet.class.getName(), "loadSerializedObject", codebase.toString() + filename); } InputStream is = getResourceAsStream(filename); if (is != null) { try { ObjectInputStream ois = new MLetObjectInputStream(is, this); Object serObject = ois.readObject(); ois.close(); return serObject; } catch (IOException e) { if (MLET_LOGGER.isLoggable(Level.FINEST)) { MLET_LOGGER.logp(Level.FINEST, MLet.class.getName(), "loadSerializedObject", "Exception while deserializing " + filename, e); } throw e; } catch (ClassNotFoundException e) { if (MLET_LOGGER.isLoggable(Level.FINEST)) { MLET_LOGGER.logp(Level.FINEST, MLet.class.getName(), "loadSerializedObject", "Exception while deserializing " + filename, e); } throw e; } } else { if (MLET_LOGGER.isLoggable(Level.FINEST)) { MLET_LOGGER.logp(Level.FINEST, MLet.class.getName(), "loadSerializedObject", "Error: File " + filename + " containing serialized object not found"); } throw new Error("File " + filename + " containing serialized object not found"); } } /** {@collect.stats} * Converts the String value of the constructor's parameter to * a basic Java object with the type of the parameter. */ private Object constructParameter(String param, String type) { // check if it is a primitive type Class<?> c = primitiveClasses.get(type); if (c != null) { try { Constructor<?> cons = c.getConstructor(new Class[] {String.class}); Object[] oo = new Object[1]; oo[0]=param; return(cons.newInstance(oo)); } catch (Exception e) { MLET_LOGGER.logp(Level.FINEST, MLet.class.getName(), "constructParameter", "Got unexpected exception", e); } } if (type.compareTo("java.lang.Boolean") == 0) return Boolean.valueOf(param); if (type.compareTo("java.lang.Byte") == 0) return new Byte(param); if (type.compareTo("java.lang.Short") == 0) return new Short(param); if (type.compareTo("java.lang.Long") == 0) return new Long(param); if (type.compareTo("java.lang.Integer") == 0) return new Integer(param); if (type.compareTo("java.lang.Float") == 0) return new Float(param); if (type.compareTo("java.lang.Double") == 0) return new Double(param); if (type.compareTo("java.lang.String") == 0) return param; return param; } private synchronized void setMBeanServer(final MBeanServer server) { this.server = server; PrivilegedAction<ClassLoaderRepository> act = new PrivilegedAction<ClassLoaderRepository>() { public ClassLoaderRepository run() { return server.getClassLoaderRepository(); } }; currentClr = AccessController.doPrivileged(act); } }
Java
/* * Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management.loading; // java import import java.io.*; import java.lang.reflect.Array; /** {@collect.stats} * This subclass of ObjectInputStream delegates loading of classes to * an existing MLetClassLoader. * * @since 1.5 */ class MLetObjectInputStream extends ObjectInputStream { private MLet loader; /** {@collect.stats} * Loader must be non-null; */ public MLetObjectInputStream(InputStream in, MLet loader) throws IOException, StreamCorruptedException { super(in); if (loader == null) { throw new IllegalArgumentException("Illegal null argument to MLetObjectInputStream"); } this.loader = loader; } private Class primitiveType(char c) { switch(c) { case 66: /* 'B' */ return Byte.TYPE; case 67: /* 'C' */ return Character.TYPE; case 68: /* 'D' */ return Double.TYPE; case 70: /* 'F' */ return Float.TYPE; case 73: /* 'I' */ return Integer.TYPE; case 74: /* 'J' */ return Long.TYPE; case 83: /* 'S' */ return Short.TYPE; case 90: /* 'Z' */ return Boolean.TYPE; } return null; } /** {@collect.stats} * Use the given ClassLoader rather than using the system class */ protected Class resolveClass(ObjectStreamClass objectstreamclass) throws IOException, ClassNotFoundException { String s = objectstreamclass.getName(); if (s.startsWith("[")) { int i; for (i = 1; s.charAt(i) == '['; i++); Class class1; if (s.charAt(i) == 'L') { class1 = loader.loadClass(s.substring(i + 1, s.length() - 1)); } else { if (s.length() != i + 1) throw new ClassNotFoundException(s); class1 = primitiveType(s.charAt(i)); } int ai[] = new int[i]; for (int j = 0; j < i; j++) ai[j] = 0; return Array.newInstance(class1, ai).getClass(); } else { return loader.loadClass(s); } } /** {@collect.stats} * Returns the ClassLoader being used */ public ClassLoader getClassLoader() { return loader; } }
Java
/* * Copyright (c) 2002, 2007, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management.loading; import java.net.URL; import java.net.URLStreamHandlerFactory; /** {@collect.stats} * An MLet that is not added to the {@link ClassLoaderRepository}. * This class acts exactly like its parent class, {@link MLet}, with * one exception. When a PrivateMLet is registered in an MBean * server, it is not added to that MBean server's {@link * ClassLoaderRepository}. This is true because this class implements * the interface {@link PrivateClassLoader}. * * @since 1.5 */ public class PrivateMLet extends MLet implements PrivateClassLoader { private static final long serialVersionUID = 2503458973393711979L; /** {@collect.stats} * Constructs a new PrivateMLet for the specified URLs using the * default delegation parent ClassLoader. The URLs will be * searched in the order specified for classes and resources * after first searching in the parent class loader. * * @param urls The URLs from which to load classes and resources. * @param delegateToCLR True if, when a class is not found in * either the parent ClassLoader or the URLs, the MLet should delegate * to its containing MBeanServer's {@link ClassLoaderRepository}. * */ public PrivateMLet(URL[] urls, boolean delegateToCLR) { super(urls, delegateToCLR); } /** {@collect.stats} * Constructs a new PrivateMLet for the given URLs. The URLs will * be searched in the order specified for classes and resources * after first searching in the specified parent class loader. * The parent argument will be used as the parent class loader * for delegation. * * @param urls The URLs from which to load classes and resources. * @param parent The parent class loader for delegation. * @param delegateToCLR True if, when a class is not found in * either the parent ClassLoader or the URLs, the MLet should delegate * to its containing MBeanServer's {@link ClassLoaderRepository}. * */ public PrivateMLet(URL[] urls, ClassLoader parent, boolean delegateToCLR) { super(urls, parent, delegateToCLR); } /** {@collect.stats} * Constructs a new PrivateMLet for the specified URLs, parent * class loader, and URLStreamHandlerFactory. The parent argument * will be used as the parent class loader for delegation. The * factory argument will be used as the stream handler factory to * obtain protocol handlers when creating new URLs. * * @param urls The URLs from which to load classes and resources. * @param parent The parent class loader for delegation. * @param factory The URLStreamHandlerFactory to use when creating URLs. * @param delegateToCLR True if, when a class is not found in * either the parent ClassLoader or the URLs, the MLet should delegate * to its containing MBeanServer's {@link ClassLoaderRepository}. * */ public PrivateMLet(URL[] urls, ClassLoader parent, URLStreamHandlerFactory factory, boolean delegateToCLR) { super(urls, parent, factory, delegateToCLR); } }
Java
/* * Copyright (c) 1999, 2006, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management.loading; import static com.sun.jmx.defaults.JmxProperties.MLET_LOGGER; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; /** {@collect.stats} * This class is used for parsing URLs. * * @since 1.5 */ class MLetParser { /* * ------------------------------------------ * PRIVATE VARIABLES * ------------------------------------------ */ /** {@collect.stats} * The current character */ private int c; /** {@collect.stats} * Tag to parse. */ private static String tag = "mlet"; /* * ------------------------------------------ * CONSTRUCTORS * ------------------------------------------ */ /** {@collect.stats} * Create an MLet parser object */ public MLetParser() { } /* * ------------------------------------------ * PUBLIC METHODS * ------------------------------------------ */ /** {@collect.stats} * Scan spaces. */ public void skipSpace(Reader in) throws IOException { while ((c >= 0) && ((c == ' ') || (c == '\t') || (c == '\n') || (c == '\r'))) { c = in.read(); } } /** {@collect.stats} * Scan identifier */ public String scanIdentifier(Reader in) throws IOException { StringBuilder buf = new StringBuilder(); while (true) { if (((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z')) || ((c >= '0') && (c <= '9')) || (c == '_')) { buf.append((char)c); c = in.read(); } else { return buf.toString(); } } } /** {@collect.stats} * Scan tag */ public Map<String,String> scanTag(Reader in) throws IOException { Map<String,String> atts = new HashMap<String,String>(); skipSpace(in); while (c >= 0 && c != '>') { if (c == '<') throw new IOException("Missing '>' in tag"); String att = scanIdentifier(in); String val = ""; skipSpace(in); if (c == '=') { int quote = -1; c = in.read(); skipSpace(in); if ((c == '\'') || (c == '\"')) { quote = c; c = in.read(); } StringBuilder buf = new StringBuilder(); while ((c > 0) && (((quote < 0) && (c != ' ') && (c != '\t') && (c != '\n') && (c != '\r') && (c != '>')) || ((quote >= 0) && (c != quote)))) { buf.append((char)c); c = in.read(); } if (c == quote) { c = in.read(); } skipSpace(in); val = buf.toString(); } atts.put(att.toLowerCase(), val); skipSpace(in); } return atts; } /** {@collect.stats} * Scan an html file for <mlet> tags */ public List<MLetContent> parse(URL url) throws IOException { String mth = "parse"; // Warning Messages String requiresTypeWarning = "<arg type=... value=...> tag requires type parameter."; String requiresValueWarning = "<arg type=... value=...> tag requires value parameter."; String paramOutsideWarning = "<arg> tag outside <mlet> ... </mlet>."; String requiresCodeWarning = "<mlet> tag requires either code or object parameter."; String requiresJarsWarning = "<mlet> tag requires archive parameter."; URLConnection conn; conn = url.openConnection(); Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); // The original URL may have been redirected - this // sets it to whatever URL/codebase we ended up getting // url = conn.getURL(); List<MLetContent> mlets = new ArrayList<MLetContent>(); Map<String,String> atts = null; List<String> types = new ArrayList<String>(); List<String> values = new ArrayList<String>(); // debug("parse","*** Parsing " + url ); while(true) { c = in.read(); if (c == -1) break; if (c == '<') { c = in.read(); if (c == '/') { c = in.read(); String nm = scanIdentifier(in); if (c != '>') throw new IOException("Missing '>' in tag"); if (nm.equalsIgnoreCase(tag)) { if (atts != null) { mlets.add(new MLetContent(url, atts, types, values)); } atts = null; types = new ArrayList<String>(); values = new ArrayList<String>(); } } else { String nm = scanIdentifier(in); if (nm.equalsIgnoreCase("arg")) { Map<String,String> t = scanTag(in); String att = t.get("type"); if (att == null) { MLET_LOGGER.logp(Level.FINER, MLetParser.class.getName(), mth, requiresTypeWarning); throw new IOException(requiresTypeWarning); } else { if (atts != null) { types.add(att); } else { MLET_LOGGER.logp(Level.FINER, MLetParser.class.getName(), mth, paramOutsideWarning); throw new IOException(paramOutsideWarning); } } String val = t.get("value"); if (val == null) { MLET_LOGGER.logp(Level.FINER, MLetParser.class.getName(), mth, requiresValueWarning); throw new IOException(requiresValueWarning); } else { if (atts != null) { values.add(val); } else { MLET_LOGGER.logp(Level.FINER, MLetParser.class.getName(), mth, paramOutsideWarning); throw new IOException(paramOutsideWarning); } } } else { if (nm.equalsIgnoreCase(tag)) { atts = scanTag(in); if (atts.get("code") == null && atts.get("object") == null) { MLET_LOGGER.logp(Level.FINER, MLetParser.class.getName(), mth, requiresCodeWarning); atts = null; throw new IOException(requiresCodeWarning); } if (atts.get("archive") == null) { MLET_LOGGER.logp(Level.FINER, MLetParser.class.getName(), mth, requiresJarsWarning); atts = null; throw new IOException(requiresJarsWarning); } } } } } } in.close(); return mlets; } /** {@collect.stats} * Parse the document pointed by the URL urlname */ public List<MLetContent> parseURL(String urlname) throws IOException { // Parse the document // URL url = null; if (urlname.indexOf(':') <= 1) { String userDir = System.getProperty("user.dir"); String prot; if (userDir.charAt(0) == '/' || userDir.charAt(0) == File.separatorChar) { prot = "file:"; } else { prot = "file:/"; } url = new URL(prot + userDir.replace(File.separatorChar, '/') + "/"); url = new URL(url, urlname); } else { url = new URL(urlname); } // Return list of parsed MLets // return parse(url); } }
Java
/* * Copyright (c) 1999, 2006, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management.loading; // java import import java.net.URL; import java.net.MalformedURLException; import java.util.Collections; import java.util.List; import java.util.Map; /** {@collect.stats} * This class represents the contents of the <CODE>MLET</CODE> tag. * It can be consulted by a subclass of {@link MLet} that overrides * the {@link MLet#check MLet.check} method. * * @since 1.6 */ public class MLetContent { /** {@collect.stats} * A map of the attributes of the <CODE>MLET</CODE> tag * and their values. */ private Map<String,String> attributes; /** {@collect.stats} * An ordered list of the TYPE attributes that appeared in nested * &lt;PARAM&gt; tags. */ private List<String> types; /** {@collect.stats} * An ordered list of the VALUE attributes that appeared in nested * &lt;PARAM&gt; tags. */ private List<String> values; /** {@collect.stats} * The MLet text file's base URL. */ private URL documentURL; /** {@collect.stats} * The base URL. */ private URL baseURL; /** {@collect.stats} * Creates an <CODE>MLet</CODE> instance initialized with attributes read * from an <CODE>MLET</CODE> tag in an MLet text file. * * @param url The URL of the MLet text file containing the * <CODE>MLET</CODE> tag. * @param attributes A map of the attributes of the <CODE>MLET</CODE> tag. * The keys in this map are the attribute names in lowercase, for * example <code>codebase</code>. The values are the associated attribute * values. * @param types A list of the TYPE attributes that appeared in nested * &lt;PARAM&gt; tags. * @param values A list of the VALUE attributes that appeared in nested * &lt;PARAM&gt; tags. */ public MLetContent(URL url, Map<String,String> attributes, List<String> types, List<String> values) { this.documentURL = url; this.attributes = Collections.unmodifiableMap(attributes); this.types = Collections.unmodifiableList(types); this.values = Collections.unmodifiableList(values); // Initialize baseURL // String att = getParameter("codebase"); if (att != null) { if (!att.endsWith("/")) { att += "/"; } try { baseURL = new URL(documentURL, att); } catch (MalformedURLException e) { // OK : Move to next block as baseURL could not be initialized. } } if (baseURL == null) { String file = documentURL.getFile(); int i = file.lastIndexOf('/'); if (i >= 0 && i < file.length() - 1) { try { baseURL = new URL(documentURL, file.substring(0, i + 1)); } catch (MalformedURLException e) { // OK : Move to next block as baseURL could not be initialized. } } } if (baseURL == null) baseURL = documentURL; } // GETTERS AND SETTERS //-------------------- /** {@collect.stats} * Gets the attributes of the <CODE>MLET</CODE> tag. The keys in * the returned map are the attribute names in lowercase, for * example <code>codebase</code>. The values are the associated * attribute values. * @return A map of the attributes of the <CODE>MLET</CODE> tag * and their values. */ public Map<String,String> getAttributes() { return attributes; } /** {@collect.stats} * Gets the MLet text file's base URL. * @return The MLet text file's base URL. */ public URL getDocumentBase() { return documentURL; } /** {@collect.stats} * Gets the code base URL. * @return The code base URL. */ public URL getCodeBase() { return baseURL; } /** {@collect.stats} * Gets the list of <CODE>.jar</CODE> files specified by the <CODE>ARCHIVE</CODE> * attribute of the <CODE>MLET</CODE> tag. * @return A comma-separated list of <CODE>.jar</CODE> file names. */ public String getJarFiles() { return getParameter("archive"); } /** {@collect.stats} * Gets the value of the <CODE>CODE</CODE> * attribute of the <CODE>MLET</CODE> tag. * @return The value of the <CODE>CODE</CODE> * attribute of the <CODE>MLET</CODE> tag. */ public String getCode() { return getParameter("code"); } /** {@collect.stats} * Gets the value of the <CODE>OBJECT</CODE> * attribute of the <CODE>MLET</CODE> tag. * @return The value of the <CODE>OBJECT</CODE> * attribute of the <CODE>MLET</CODE> tag. */ public String getSerializedObject() { return getParameter("object"); } /** {@collect.stats} * Gets the value of the <CODE>NAME</CODE> * attribute of the <CODE>MLET</CODE> tag. * @return The value of the <CODE>NAME</CODE> * attribute of the <CODE>MLET</CODE> tag. */ public String getName() { return getParameter("name"); } /** {@collect.stats} * Gets the value of the <CODE>VERSION</CODE> * attribute of the <CODE>MLET</CODE> tag. * @return The value of the <CODE>VERSION</CODE> * attribute of the <CODE>MLET</CODE> tag. */ public String getVersion() { return getParameter("version"); } /** {@collect.stats} * Gets the list of values of the <code>TYPE</code> attribute in * each nested &lt;PARAM&gt; tag within the <code>MLET</code> * tag. * @return the list of types. */ public List<String> getParameterTypes() { return types; } /** {@collect.stats} * Gets the list of values of the <code>VALUE</code> attribute in * each nested &lt;PARAM&gt; tag within the <code>MLET</code> * tag. * @return the list of values. */ public List<String> getParameterValues() { return values; } /** {@collect.stats} * Gets the value of the specified * attribute of the <CODE>MLET</CODE> tag. * * @param name A string representing the name of the attribute. * @return The value of the specified * attribute of the <CODE>MLET</CODE> tag. */ private String getParameter(String name) { return attributes.get(name.toLowerCase()); } }
Java
/* * Copyright (c) 2002, 2007, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management.loading; /** {@collect.stats} * Marker interface indicating that a ClassLoader should not be added * to the {@link ClassLoaderRepository}. When a ClassLoader is * registered as an MBean in the MBean server, it is added to the * MBean server's ClassLoaderRepository unless it implements this * interface. * * @since 1.5 */ public interface PrivateClassLoader {}
Java
/* * Copyright (c) 1999, 2006, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management.loading; import java.net.URL; import java.io.InputStream; import java.io.IOException; import java.util.Set; import java.util.Enumeration; import javax.management.*; /** {@collect.stats} * Exposes the remote management interface of the MLet * MBean. * * @since 1.5 */ public interface MLetMBean { /** {@collect.stats} * Loads a text file containing MLET tags that define the MBeans * to be added to the MBean server. The location of the text file is * specified by a URL. The text file is read using the UTF-8 * encoding. The MBeans specified in the MLET file will be * instantiated and registered in the MBean server. * * @param url The URL of the text file to be loaded as String object. * * @return A set containing one entry per MLET tag in the m-let * text file loaded. Each entry specifies either the * ObjectInstance for the created MBean, or a throwable object * (that is, an error or an exception) if the MBean could not be * created. * * @exception ServiceNotFoundException One of the following errors * has occurred: The m-let text file does not contain an MLET tag, * the m-let text file is not found, a mandatory attribute of the * MLET tag is not specified, the value of url is malformed. */ public Set<Object> getMBeansFromURL(String url) throws ServiceNotFoundException; /** {@collect.stats} * Loads a text file containing MLET tags that define the MBeans * to be added to the MBean server. The location of the text file is * specified by a URL. The text file is read using the UTF-8 * encoding. The MBeans specified in the MLET file will be * instantiated and registered in the MBean server. * * @param url The URL of the text file to be loaded as URL object. * * @return A set containing one entry per MLET tag in the m-let * text file loaded. Each entry specifies either the * ObjectInstance for the created MBean, or a throwable object * (that is, an error or an exception) if the MBean could not be * created. * * @exception ServiceNotFoundException One of the following errors * has occurred: The m-let text file does not contain an MLET tag, * the m-let text file is not found, a mandatory attribute of the * MLET tag is not specified, the value of url is null. */ public Set<Object> getMBeansFromURL(URL url) throws ServiceNotFoundException; /** {@collect.stats} * Appends the specified URL to the list of URLs to search for classes and * resources. * * @param url the URL to add. */ public void addURL(URL url) ; /** {@collect.stats} * Appends the specified URL to the list of URLs to search for classes and * resources. * * @param url the URL to add. * * @exception ServiceNotFoundException The specified URL is malformed. */ public void addURL(String url) throws ServiceNotFoundException; /** {@collect.stats} * Returns the search path of URLs for loading classes and resources. * This includes the original list of URLs specified to the constructor, * along with any URLs subsequently appended by the addURL() method. * * @return the list of URLs. */ public URL[] getURLs(); /** {@collect.stats} Finds the resource with the given name. * A resource is some data (images, audio, text, etc) that can be accessed by class code in a way that is * independent of the location of the code. * The name of a resource is a "/"-separated path name that identifies the resource. * * @param name The resource name * * @return An URL for reading the resource, or null if the resource could not be found or the caller doesn't have adequate privileges to get the * resource. */ public URL getResource(String name); /** {@collect.stats} Returns an input stream for reading the specified resource. The search order is described in the documentation for * getResource(String). * * @param name The resource name * * @return An input stream for reading the resource, or null if the resource could not be found * */ public InputStream getResourceAsStream(String name); /** {@collect.stats} * Finds all the resources with the given name. A resource is some * data (images, audio, text, etc) that can be accessed by class * code in a way that is independent of the location of the code. * The name of a resource is a "/"-separated path name that * identifies the resource. * * @param name The resource name. * * @return An enumeration of URL to the resource. If no resources * could be found, the enumeration will be empty. Resources that * cannot be accessed will not be in the enumeration. * * @exception IOException if an I/O exception occurs when * searching for resources. */ public Enumeration<URL> getResources(String name) throws IOException; /** {@collect.stats} * Gets the current directory used by the library loader for * storing native libraries before they are loaded into memory. * * @return The current directory used by the library loader. * * @see #setLibraryDirectory * * @throws UnsupportedOperationException if this implementation * does not support storing native libraries in this way. */ public String getLibraryDirectory(); /** {@collect.stats} * Sets the directory used by the library loader for storing * native libraries before they are loaded into memory. * * @param libdir The directory used by the library loader. * * @see #getLibraryDirectory * * @throws UnsupportedOperationException if this implementation * does not support storing native libraries in this way. */ public void setLibraryDirectory(String libdir); }
Java
/* * Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management.loading; import static com.sun.jmx.defaults.JmxProperties.MBEANSERVER_LOGGER; import java.util.Iterator; import java.util.List; import java.util.logging.Level; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; /** {@collect.stats} * <p>Keeps the list of Class Loaders registered in the MBean Server. * It provides the necessary methods to load classes using the registered * Class Loaders.</p> * * <p>This deprecated class is maintained for compatibility. In * previous versions of JMX, there was one * <code>DefaultLoaderRepository</code> shared by all MBean servers. * As of JMX 1.2, that functionality is approximated by using {@link * MBeanServerFactory#findMBeanServer} to find all known MBean * servers, and consulting the {@link ClassLoaderRepository} of each * one. It is strongly recommended that code referencing * <code>DefaultLoaderRepository</code> be rewritten.</p> * * @deprecated Use * {@link javax.management.MBeanServer#getClassLoaderRepository()}} * instead. * * @since 1.5 */ @Deprecated public class DefaultLoaderRepository { /** {@collect.stats} * Go through the list of class loaders and try to load the requested * class. * The method will stop as soon as the class is found. If the class * is not found the method will throw a <CODE>ClassNotFoundException</CODE> * exception. * * @param className The name of the class to be loaded. * * @return the loaded class. * * @exception ClassNotFoundException The specified class could not be * found. */ public static Class loadClass(String className) throws ClassNotFoundException { MBEANSERVER_LOGGER.logp(Level.FINEST, DefaultLoaderRepository.class.getName(), "loadClass", className); return load(null, className); } /** {@collect.stats} * Go through the list of class loaders but exclude the given * class loader, then try to load * the requested class. * The method will stop as soon as the class is found. If the class * is not found the method will throw a <CODE>ClassNotFoundException</CODE> * exception. * * @param className The name of the class to be loaded. * @param loader The class loader to be excluded. * * @return the loaded class. * * @exception ClassNotFoundException The specified class could not be * found. */ public static Class loadClassWithout(ClassLoader loader, String className) throws ClassNotFoundException { MBEANSERVER_LOGGER.logp(Level.FINEST, DefaultLoaderRepository.class.getName(), "loadClassWithout", className); return load(loader, className); } private static Class load(ClassLoader without, String className) throws ClassNotFoundException { final List mbsList = MBeanServerFactory.findMBeanServer(null); for (Iterator it = mbsList.iterator(); it.hasNext(); ) { MBeanServer mbs = (MBeanServer) it.next(); ClassLoaderRepository clr = mbs.getClassLoaderRepository(); try { return clr.loadClassWithout(without, className); } catch (ClassNotFoundException e) { // OK : Try with next one... } } throw new ClassNotFoundException(className); } }
Java
/* * Copyright (c) 2002, 2007, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management.loading; import javax.management.MBeanServer; // for Javadoc /** {@collect.stats} * <p>Instances of this interface are used to keep the list of ClassLoaders * registered in an MBean Server. * They provide the necessary methods to load classes using the registered * ClassLoaders.</p> * * <p>The first ClassLoader in a <code>ClassLoaderRepository</code> is * always the MBean Server's own ClassLoader.</p> * * <p>When an MBean is registered in an MBean Server, if it is of a * subclass of {@link java.lang.ClassLoader} and if it does not * implement the interface {@link PrivateClassLoader}, it is added to * the end of the MBean Server's <code>ClassLoaderRepository</code>. * If it is subsequently unregistered from the MBean Server, it is * removed from the <code>ClassLoaderRepository</code>.</p> * * <p>The order of MBeans in the <code>ClassLoaderRepository</code> is * significant. For any two MBeans <em>X</em> and <em>Y</em> in the * <code>ClassLoaderRepository</code>, <em>X</em> must appear before * <em>Y</em> if the registration of <em>X</em> was completed before * the registration of <em>Y</em> started. If <em>X</em> and * <em>Y</em> were registered concurrently, their order is * indeterminate. The registration of an MBean corresponds to the * call to {@link MBeanServer#registerMBean} or one of the {@link * MBeanServer}<code>.createMBean</code> methods.</p> * * @see javax.management.MBeanServerFactory * * @since 1.5 */ public interface ClassLoaderRepository { /** {@collect.stats} * <p>Load the given class name through the list of class loaders. * Each ClassLoader in turn from the ClassLoaderRepository is * asked to load the class via its {@link * ClassLoader#loadClass(String)} method. If it successfully * returns a {@link Class} object, that is the result of this * method. If it throws a {@link ClassNotFoundException}, the * search continues with the next ClassLoader. If it throws * another exception, the exception is propagated from this * method. If the end of the list is reached, a {@link * ClassNotFoundException} is thrown.</p> * * @param className The name of the class to be loaded. * * @return the loaded class. * * @exception ClassNotFoundException The specified class could not be * found. */ public Class<?> loadClass(String className) throws ClassNotFoundException; /** {@collect.stats} * <p>Load the given class name through the list of class loaders, * excluding the given one. Each ClassLoader in turn from the * ClassLoaderRepository, except <code>exclude</code>, is asked to * load the class via its {@link ClassLoader#loadClass(String)} * method. If it successfully returns a {@link Class} object, * that is the result of this method. If it throws a {@link * ClassNotFoundException}, the search continues with the next * ClassLoader. If it throws another exception, the exception is * propagated from this method. If the end of the list is * reached, a {@link ClassNotFoundException} is thrown.</p> * * <p>Be aware that if a ClassLoader in the ClassLoaderRepository * calls this method from its {@link ClassLoader#loadClass(String) * loadClass} method, it exposes itself to a deadlock if another * ClassLoader in the ClassLoaderRepository does the same thing at * the same time. The {@link #loadClassBefore} method is * recommended to avoid the risk of deadlock.</p> * * @param className The name of the class to be loaded. * @param exclude The class loader to be excluded. May be null, * in which case this method is equivalent to {@link #loadClass * loadClass(className)}. * * @return the loaded class. * * @exception ClassNotFoundException The specified class could not * be found. */ public Class<?> loadClassWithout(ClassLoader exclude, String className) throws ClassNotFoundException; /** {@collect.stats} * <p>Load the given class name through the list of class loaders, * stopping at the given one. Each ClassLoader in turn from the * ClassLoaderRepository is asked to load the class via its {@link * ClassLoader#loadClass(String)} method. If it successfully * returns a {@link Class} object, that is the result of this * method. If it throws a {@link ClassNotFoundException}, the * search continues with the next ClassLoader. If it throws * another exception, the exception is propagated from this * method. If the search reaches <code>stop</code> or the end of * the list, a {@link ClassNotFoundException} is thrown.</p> * * <p>Typically this method is called from the {@link * ClassLoader#loadClass(String) loadClass} method of * <code>stop</code>, to consult loaders that appear before it * in the <code>ClassLoaderRepository</code>. By stopping the * search as soon as <code>stop</code> is reached, a potential * deadlock with concurrent class loading is avoided.</p> * * @param className The name of the class to be loaded. * @param stop The class loader at which to stop. May be null, in * which case this method is equivalent to {@link #loadClass(String) * loadClass(className)}. * * @return the loaded class. * * @exception ClassNotFoundException The specified class could not * be found. * */ public Class<?> loadClassBefore(ClassLoader stop, String className) throws ClassNotFoundException; }
Java
/* * Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management; /** {@collect.stats} * Defines the methods that should be implemented by * a Dynamic MBean (MBean that exposes a dynamic management interface). * * @since 1.5 */ public interface DynamicMBean { /** {@collect.stats} * Obtain the value of a specific attribute of the Dynamic MBean. * * @param attribute The name of the attribute to be retrieved * * @return The value of the attribute retrieved. * * @exception AttributeNotFoundException * @exception MBeanException Wraps a <CODE>java.lang.Exception</CODE> thrown by the MBean's getter. * @exception ReflectionException Wraps a <CODE>java.lang.Exception</CODE> thrown while trying to invoke the getter. * * @see #setAttribute */ public Object getAttribute(String attribute) throws AttributeNotFoundException, MBeanException, ReflectionException; /** {@collect.stats} * Set the value of a specific attribute of the Dynamic MBean. * * @param attribute The identification of the attribute to * be set and the value it is to be set to. * * @exception AttributeNotFoundException * @exception InvalidAttributeValueException * @exception MBeanException Wraps a <CODE>java.lang.Exception</CODE> thrown by the MBean's setter. * @exception ReflectionException Wraps a <CODE>java.lang.Exception</CODE> thrown while trying to invoke the MBean's setter. * * @see #getAttribute */ public void setAttribute(Attribute attribute) throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException ; /** {@collect.stats} * Get the values of several attributes of the Dynamic MBean. * * @param attributes A list of the attributes to be retrieved. * * @return The list of attributes retrieved. * * @see #setAttributes */ public AttributeList getAttributes(String[] attributes); /** {@collect.stats} * Sets the values of several attributes of the Dynamic MBean. * * @param attributes A list of attributes: The identification of the * attributes to be set and the values they are to be set to. * * @return The list of attributes that were set, with their new values. * * @see #getAttributes */ public AttributeList setAttributes(AttributeList attributes); /** {@collect.stats} * Allows an action to be invoked on the Dynamic MBean. * * @param actionName The name of the action to be invoked. * @param params An array containing the parameters to be set when the action is * invoked. * @param signature An array containing the signature of the action. The class objects will * be loaded through the same class loader as the one used for loading the * MBean on which the action is invoked. * * @return The object returned by the action, which represents the result of * invoking the action on the MBean specified. * * @exception MBeanException Wraps a <CODE>java.lang.Exception</CODE> thrown by the MBean's invoked method. * @exception ReflectionException Wraps a <CODE>java.lang.Exception</CODE> thrown while trying to invoke the method */ public Object invoke(String actionName, Object params[], String signature[]) throws MBeanException, ReflectionException ; /** {@collect.stats} * Provides the exposed attributes and actions of the Dynamic MBean using an MBeanInfo object. * * @return An instance of <CODE>MBeanInfo</CODE> allowing all attributes and actions * exposed by this Dynamic MBean to be retrieved. * */ public MBeanInfo getMBeanInfo(); }
Java
/* * Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management; /** {@collect.stats} * When a <CODE>java.lang.Error</CODE> occurs in the agent it should be caught and * re-thrown as a <CODE>RuntimeErrorException</CODE>. * * @since 1.5 */ public class RuntimeErrorException extends JMRuntimeException { /* Serial version */ private static final long serialVersionUID = 704338937753949796L; /** {@collect.stats} * @serial The encapsulated {@link Error} */ private java.lang.Error error ; /** {@collect.stats} * Default constructor. * * @param e the wrapped error. */ public RuntimeErrorException(java.lang.Error e) { super(); error = e ; } /** {@collect.stats} * Constructor that allows a specific error message to be specified. * * @param e the wrapped error. * @param message the detail message. */ public RuntimeErrorException(java.lang.Error e, String message) { super(message); error = e ; } /** {@collect.stats} * Returns the actual {@link Error} thrown. * * @return the wrapped {@link Error}. */ public java.lang.Error getTargetError() { return error ; } /** {@collect.stats} * Returns the actual {@link Error} thrown. * * @return the wrapped {@link Error}. */ public Throwable getCause() { return error; } }
Java
/* * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management; /** {@collect.stats} * This class is used by the query building mechanism for isInstanceOf expressions. * @serial include * * @since 1.6 */ class InstanceOfQueryExp extends QueryEval implements QueryExp { /* Serial version */ private static final long serialVersionUID = -1081892073854801359L; /** {@collect.stats} * @serial The {@link StringValueExp} returning the name of the class * of which selected MBeans should be instances. */ private StringValueExp classNameValue; /** {@collect.stats} * Creates a new InstanceOfExp with a specific class name. * @param classNameValue The {@link StringValueExp} returning the name of * the class of which selected MBeans should be instances. */ // We are using StringValueExp here to be consistent with other queries, // although we should actually either use a simple string (the classname) // or a ValueExp - which would allow more complex queries - like for // instance evaluating the class name from an AttributeValueExp. // As it stands - using StringValueExp instead of a simple constant string // doesn't serve any useful purpose besides offering a consistent // look & feel. public InstanceOfQueryExp(StringValueExp classNameValue) { if (classNameValue == null) { throw new IllegalArgumentException("Null class name."); } this.classNameValue = classNameValue; } /** {@collect.stats} * Returns the class name. * @returns The {@link StringValueExp} returning the name of * the class of which selected MBeans should be instances. */ public StringValueExp getClassNameValue() { return classNameValue; } /** {@collect.stats} * Applies the InstanceOf on a MBean. * * @param name The name of the MBean on which the InstanceOf will be applied. * * @return True if the MBean specified by the name is instance of the class. * @exception BadAttributeValueExpException * @exception InvalidApplicationException * @exception BadStringOperationException * @exception BadBinaryOpValueExpException */ public boolean apply(ObjectName name) throws BadStringOperationException, BadBinaryOpValueExpException, BadAttributeValueExpException, InvalidApplicationException { // Get the class name value final StringValueExp val; try { val = (StringValueExp) classNameValue.apply(name); } catch (ClassCastException x) { // Should not happen - unless someone wrongly implemented // StringValueExp.apply(). final BadStringOperationException y = new BadStringOperationException(x.toString()); y.initCause(x); throw y; } // Test whether the MBean is an instance of that class. try { return getMBeanServer().isInstanceOf(name, val.getValue()); } catch (InstanceNotFoundException infe) { return false; } } /** {@collect.stats} * Returns a string representation of this InstanceOfQueryExp. * @return a string representation of this InstanceOfQueryExp. */ public String toString() { return "InstanceOf " + classNameValue.toString(); } }
Java
/* * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management; /** {@collect.stats} * <p>An MBean whose management interface is determined by reflection * on a Java interface, and that emits notifications.</p> * * <p>The following example shows how to use the public constructor * {@link #StandardEmitterMBean(Object, Class, NotificationEmitter) * StandardEmitterMBean(implementation, mbeanInterface, emitter)} to * create an MBean emitting notifications with any * implementation class name <i>Impl</i>, with a management * interface defined (as for current Standard MBeans) by any interface * <i>Intf</i>, and with any implementation of the interface * {@link NotificationEmitter}. The example uses the class * {@link NotificationBroadcasterSupport} as an implementation * of the interface {@link NotificationEmitter}.</p> * * <pre> * MBeanServer mbs; * ... * final String[] types = new String[] {"sun.disc.space","sun.disc.alarm"}; * final MBeanNotificationInfo info = new MBeanNotificationInfo( * types, * Notification.class.getName(), * "Notification about disc info."); * final NotificationEmitter emitter = * new NotificationBroadcasterSupport(info); * * final Intf impl = new Impl(...); * final Object mbean = new StandardEmitterMBean( * impl, Intf.class, emitter); * mbs.registerMBean(mbean, objectName); * </pre> * * @see StandardMBean * * @since 1.6 */ public class StandardEmitterMBean extends StandardMBean implements NotificationEmitter { private final NotificationEmitter emitter; private final MBeanNotificationInfo[] notificationInfo; /** {@collect.stats} * <p>Make an MBean whose management interface is specified by * {@code mbeanInterface}, with the given implementation and * where notifications are handled by the given {@code NotificationEmitter}. * The resultant MBean implements the {@code NotificationEmitter} interface * by forwarding its methods to {@code emitter}. It is legal and useful * for {@code implementation} and {@code emitter} to be the same object.</p> * * <p>If {@code emitter} is an instance of {@code * NotificationBroadcasterSupport} then the MBean's {@link #sendNotification * sendNotification} method will call {@code emitter.}{@link * NotificationBroadcasterSupport#sendNotification sendNotification}.</p> * * <p>The array returned by {@link #getNotificationInfo()} on the * new MBean is a copy of the array returned by * {@code emitter.}{@link NotificationBroadcaster#getNotificationInfo * getNotificationInfo()} at the time of construction. If the array * returned by {@code emitter.getNotificationInfo()} later changes, * that will have no effect on this object's * {@code getNotificationInfo()}.</p> * * @param implementation the implementation of the MBean interface. * @param mbeanInterface a Standard MBean interface. * @param emitter the object that will handle notifications. * * @throws IllegalArgumentException if the {@code mbeanInterface} * does not follow JMX design patterns for Management Interfaces, or * if the given {@code implementation} does not implement the * specified interface, or if {@code emitter} is null. */ public <T> StandardEmitterMBean(T implementation, Class<T> mbeanInterface, NotificationEmitter emitter) { super(implementation, mbeanInterface, false); if (emitter == null) throw new IllegalArgumentException("Null emitter"); this.emitter = emitter; this.notificationInfo = emitter.getNotificationInfo(); } /** {@collect.stats} * <p>Make an MBean whose management interface is specified by * {@code mbeanInterface}, with the given implementation and where * notifications are handled by the given {@code * NotificationEmitter}. This constructor can be used to make * either Standard MBeans or MXBeans. The resultant MBean * implements the {@code NotificationEmitter} interface by * forwarding its methods to {@code emitter}. It is legal and * useful for {@code implementation} and {@code emitter} to be the * same object.</p> * * <p>If {@code emitter} is an instance of {@code * NotificationBroadcasterSupport} then the MBean's {@link #sendNotification * sendNotification} method will call {@code emitter.}{@link * NotificationBroadcasterSupport#sendNotification sendNotification}.</p> * * <p>The array returned by {@link #getNotificationInfo()} on the * new MBean is a copy of the array returned by * {@code emitter.}{@link NotificationBroadcaster#getNotificationInfo * getNotificationInfo()} at the time of construction. If the array * returned by {@code emitter.getNotificationInfo()} later changes, * that will have no effect on this object's * {@code getNotificationInfo()}.</p> * * @param implementation the implementation of the MBean interface. * @param mbeanInterface a Standard MBean interface. * @param isMXBean If true, the {@code mbeanInterface} parameter * names an MXBean interface and the resultant MBean is an MXBean. * @param emitter the object that will handle notifications. * * @throws IllegalArgumentException if the {@code mbeanInterface} * does not follow JMX design patterns for Management Interfaces, or * if the given {@code implementation} does not implement the * specified interface, or if {@code emitter} is null. */ public <T> StandardEmitterMBean(T implementation, Class<T> mbeanInterface, boolean isMXBean, NotificationEmitter emitter) { super(implementation, mbeanInterface, isMXBean); if (emitter == null) throw new IllegalArgumentException("Null emitter"); this.emitter = emitter; this.notificationInfo = emitter.getNotificationInfo(); } /** {@collect.stats} * <p>Make an MBean whose management interface is specified by * {@code mbeanInterface}, and * where notifications are handled by the given {@code NotificationEmitter}. * The resultant MBean implements the {@code NotificationEmitter} interface * by forwarding its methods to {@code emitter}.</p> * * <p>If {@code emitter} is an instance of {@code * NotificationBroadcasterSupport} then the MBean's {@link #sendNotification * sendNotification} method will call {@code emitter.}{@link * NotificationBroadcasterSupport#sendNotification sendNotification}.</p> * * <p>The array returned by {@link #getNotificationInfo()} on the * new MBean is a copy of the array returned by * {@code emitter.}{@link NotificationBroadcaster#getNotificationInfo * getNotificationInfo()} at the time of construction. If the array * returned by {@code emitter.getNotificationInfo()} later changes, * that will have no effect on this object's * {@code getNotificationInfo()}.</p> * * <p>This constructor must be called from a subclass that implements * the given {@code mbeanInterface}.</p> * * @param mbeanInterface a StandardMBean interface. * @param emitter the object that will handle notifications. * * @throws IllegalArgumentException if the {@code mbeanInterface} * does not follow JMX design patterns for Management Interfaces, or * if {@code this} does not implement the specified interface, or * if {@code emitter} is null. */ protected StandardEmitterMBean(Class<?> mbeanInterface, NotificationEmitter emitter) { super(mbeanInterface, false); if (emitter == null) throw new IllegalArgumentException("Null emitter"); this.emitter = emitter; this.notificationInfo = emitter.getNotificationInfo(); } /** {@collect.stats} * <p>Make an MBean whose management interface is specified by * {@code mbeanInterface}, and where notifications are handled by * the given {@code NotificationEmitter}. This constructor can be * used to make either Standard MBeans or MXBeans. The resultant * MBean implements the {@code NotificationEmitter} interface by * forwarding its methods to {@code emitter}.</p> * * <p>If {@code emitter} is an instance of {@code * NotificationBroadcasterSupport} then the MBean's {@link #sendNotification * sendNotification} method will call {@code emitter.}{@link * NotificationBroadcasterSupport#sendNotification sendNotification}.</p> * * <p>The array returned by {@link #getNotificationInfo()} on the * new MBean is a copy of the array returned by * {@code emitter.}{@link NotificationBroadcaster#getNotificationInfo * getNotificationInfo()} at the time of construction. If the array * returned by {@code emitter.getNotificationInfo()} later changes, * that will have no effect on this object's * {@code getNotificationInfo()}.</p> * * <p>This constructor must be called from a subclass that implements * the given {@code mbeanInterface}.</p> * * @param mbeanInterface a StandardMBean interface. * @param isMXBean If true, the {@code mbeanInterface} parameter * names an MXBean interface and the resultant MBean is an MXBean. * @param emitter the object that will handle notifications. * * @throws IllegalArgumentException if the {@code mbeanInterface} * does not follow JMX design patterns for Management Interfaces, or * if {@code this} does not implement the specified interface, or * if {@code emitter} is null. */ protected StandardEmitterMBean(Class<?> mbeanInterface, boolean isMXBean, NotificationEmitter emitter) { super(mbeanInterface, isMXBean); if (emitter == null) throw new IllegalArgumentException("Null emitter"); this.emitter = emitter; this.notificationInfo = emitter.getNotificationInfo(); } public void removeNotificationListener(NotificationListener listener) throws ListenerNotFoundException { emitter.removeNotificationListener(listener); } public void removeNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback) throws ListenerNotFoundException { emitter.removeNotificationListener(listener, filter, handback); } public void addNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback) { emitter.addNotificationListener(listener, filter, handback); } public MBeanNotificationInfo[] getNotificationInfo() { return notificationInfo; } /** {@collect.stats} * <p>Sends a notification.</p> * * <p>If the {@code emitter} parameter to the constructor was an * instance of {@code NotificationBroadcasterSupport} then this * method will call {@code emitter.}{@link * NotificationBroadcasterSupport#sendNotification * sendNotification}.</p> * * @param n the notification to send. * * @throws ClassCastException if the {@code emitter} parameter to the * constructor was not a {@code NotificationBroadcasterSupport}. */ public void sendNotification(Notification n) { if (emitter instanceof NotificationBroadcasterSupport) ((NotificationBroadcasterSupport) emitter).sendNotification(n); else { final String msg = "Cannot sendNotification when emitter is not an " + "instance of NotificationBroadcasterSupport: " + emitter.getClass().getName(); throw new ClassCastException(msg); } } /** {@collect.stats} * <p>Get the MBeanNotificationInfo[] that will be used in the * MBeanInfo returned by this MBean.</p> * * <p>The default implementation of this method returns * {@link #getNotificationInfo()}.</p> * * @param info The default MBeanInfo derived by reflection. * @return the MBeanNotificationInfo[] for the new MBeanInfo. */ MBeanNotificationInfo[] getNotifications(MBeanInfo info) { return getNotificationInfo(); } }
Java
/* * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management; import java.util.Collections; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.Executor; import com.sun.jmx.remote.util.ClassLogger; /** {@collect.stats} * <p>Provides an implementation of {@link * javax.management.NotificationEmitter NotificationEmitter} * interface. This can be used as the super class of an MBean that * sends notifications.</p> * * <p>By default, the notification dispatch model is synchronous. * That is, when a thread calls sendNotification, the * <code>NotificationListener.handleNotification</code> method of each listener * is called within that thread. You can override this default * by overriding <code>handleNotification</code> in a subclass, or by passing an * Executor to the constructor.</p> * * <p>If the method call of a filter or listener throws an {@link Exception}, * then that exception does not prevent other listeners from being invoked. However, * if the method call of a filter or of {@code Executor.execute} or of * {@code handleNotification} (when no {@code Excecutor} is specified) throws an * {@link Error}, then that {@code Error} is propagated to the caller of * {@link #sendNotification sendNotification}.</p> * * <p>Remote listeners added using the JMX Remote API (see JMXConnector) are not * usually called synchronously. That is, when sendNotification returns, it is * not guaranteed that any remote listeners have yet received the notification.</p> * * @since 1.5 */ public class NotificationBroadcasterSupport implements NotificationEmitter { /** {@collect.stats} * Constructs a NotificationBroadcasterSupport where each listener is invoked by the * thread sending the notification. This constructor is equivalent to * {@link NotificationBroadcasterSupport#NotificationBroadcasterSupport(Executor, * MBeanNotificationInfo[] info) NotificationBroadcasterSupport(null, null)}. */ public NotificationBroadcasterSupport() { this(null, (MBeanNotificationInfo[]) null); } /** {@collect.stats} * Constructs a NotificationBroadcasterSupport where each listener is invoked using * the given {@link java.util.concurrent.Executor}. When {@link #sendNotification * sendNotification} is called, a listener is selected if it was added with a null * {@link NotificationFilter}, or if {@link NotificationFilter#isNotificationEnabled * isNotificationEnabled} returns true for the notification being sent. The call to * <code>NotificationFilter.isNotificationEnabled</code> takes place in the thread * that called <code>sendNotification</code>. Then, for each selected listener, * {@link Executor#execute executor.execute} is called with a command * that calls the <code>handleNotification</code> method. * This constructor is equivalent to * {@link NotificationBroadcasterSupport#NotificationBroadcasterSupport(Executor, * MBeanNotificationInfo[] info) NotificationBroadcasterSupport(executor, null)}. * @param executor an executor used by the method <code>sendNotification</code> to * send each notification. If it is null, the thread calling <code>sendNotification</code> * will invoke the <code>handleNotification</code> method itself. * @since 1.6 */ public NotificationBroadcasterSupport(Executor executor) { this(executor, (MBeanNotificationInfo[]) null); } /** {@collect.stats} * <p>Constructs a NotificationBroadcasterSupport with information * about the notifications that may be sent. Each listener is * invoked by the thread sending the notification. This * constructor is equivalent to {@link * NotificationBroadcasterSupport#NotificationBroadcasterSupport(Executor, * MBeanNotificationInfo[] info) * NotificationBroadcasterSupport(null, info)}.</p> * * <p>If the <code>info</code> array is not empty, then it is * cloned by the constructor as if by {@code info.clone()}, and * each call to {@link #getNotificationInfo()} returns a new * clone.</p> * * @param info an array indicating, for each notification this * MBean may send, the name of the Java class of the notification * and the notification type. Can be null, which is equivalent to * an empty array. * * @since 1.6 */ public NotificationBroadcasterSupport(MBeanNotificationInfo... info) { this(null, info); } /** {@collect.stats} * <p>Constructs a NotificationBroadcasterSupport with information about the notifications that may be sent, * and where each listener is invoked using the given {@link java.util.concurrent.Executor}.</p> * * <p>When {@link #sendNotification sendNotification} is called, a * listener is selected if it was added with a null {@link * NotificationFilter}, or if {@link * NotificationFilter#isNotificationEnabled isNotificationEnabled} * returns true for the notification being sent. The call to * <code>NotificationFilter.isNotificationEnabled</code> takes * place in the thread that called * <code>sendNotification</code>. Then, for each selected * listener, {@link Executor#execute executor.execute} is called * with a command that calls the <code>handleNotification</code> * method.</p> * * <p>If the <code>info</code> array is not empty, then it is * cloned by the constructor as if by {@code info.clone()}, and * each call to {@link #getNotificationInfo()} returns a new * clone.</p> * * @param executor an executor used by the method * <code>sendNotification</code> to send each notification. If it * is null, the thread calling <code>sendNotification</code> will * invoke the <code>handleNotification</code> method itself. * * @param info an array indicating, for each notification this * MBean may send, the name of the Java class of the notification * and the notification type. Can be null, which is equivalent to * an empty array. * * @since 1.6 */ public NotificationBroadcasterSupport(Executor executor, MBeanNotificationInfo... info) { this.executor = (executor != null) ? executor : defaultExecutor; notifInfo = info == null ? NO_NOTIFICATION_INFO : info.clone(); } /** {@collect.stats} * Adds a listener. * * @param listener The listener to receive notifications. * @param filter The filter object. If filter is null, no * filtering will be performed before handling notifications. * @param handback An opaque object to be sent back to the * listener when a notification is emitted. This object cannot be * used by the Notification broadcaster object. It should be * resent unchanged with the notification to the listener. * * @exception IllegalArgumentException thrown if the listener is null. * * @see #removeNotificationListener */ public void addNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback) { if (listener == null) { throw new IllegalArgumentException ("Listener can't be null") ; } listenerList.add(new ListenerInfo(listener, filter, handback)); } public void removeNotificationListener(NotificationListener listener) throws ListenerNotFoundException { ListenerInfo wildcard = new WildcardListenerInfo(listener); boolean removed = listenerList.removeAll(Collections.singleton(wildcard)); if (!removed) throw new ListenerNotFoundException("Listener not registered"); } public void removeNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback) throws ListenerNotFoundException { ListenerInfo li = new ListenerInfo(listener, filter, handback); boolean removed = listenerList.remove(li); if (!removed) { throw new ListenerNotFoundException("Listener not registered " + "(with this filter and " + "handback)"); // or perhaps not registered at all } } public MBeanNotificationInfo[] getNotificationInfo() { if (notifInfo.length == 0) return notifInfo; else return notifInfo.clone(); } /** {@collect.stats} * Sends a notification. * * If an {@code Executor} was specified in the constructor, it will be given one * task per selected listener to deliver the notification to that listener. * * @param notification The notification to send. */ public void sendNotification(Notification notification) { if (notification == null) { return; } boolean enabled; for (ListenerInfo li : listenerList) { try { enabled = li.filter == null || li.filter.isNotificationEnabled(notification); } catch (Exception e) { if (logger.debugOn()) { logger.debug("sendNotification", e); } continue; } if (enabled) { executor.execute(new SendNotifJob(notification, li)); } } } /** {@collect.stats} * <p>This method is called by {@link #sendNotification * sendNotification} for each listener in order to send the * notification to that listener. It can be overridden in * subclasses to change the behavior of notification delivery, * for instance to deliver the notification in a separate * thread.</p> * * <p>The default implementation of this method is equivalent to * <pre> * listener.handleNotification(notif, handback); * </pre> * * @param listener the listener to which the notification is being * delivered. * @param notif the notification being delivered to the listener. * @param handback the handback object that was supplied when the * listener was added. * */ protected void handleNotification(NotificationListener listener, Notification notif, Object handback) { listener.handleNotification(notif, handback); } // private stuff private static class ListenerInfo { NotificationListener listener; NotificationFilter filter; Object handback; ListenerInfo(NotificationListener listener, NotificationFilter filter, Object handback) { this.listener = listener; this.filter = filter; this.handback = handback; } public boolean equals(Object o) { if (!(o instanceof ListenerInfo)) return false; ListenerInfo li = (ListenerInfo) o; if (li instanceof WildcardListenerInfo) return (li.listener == listener); else return (li.listener == listener && li.filter == filter && li.handback == handback); } } private static class WildcardListenerInfo extends ListenerInfo { WildcardListenerInfo(NotificationListener listener) { super(listener, null, null); } public boolean equals(Object o) { assert (!(o instanceof WildcardListenerInfo)); return o.equals(this); } } private List<ListenerInfo> listenerList = new CopyOnWriteArrayList<ListenerInfo>(); // since 1.6 private final Executor executor; private final MBeanNotificationInfo[] notifInfo; private final static Executor defaultExecutor = new Executor() { // DirectExecutor using caller thread public void execute(Runnable r) { r.run(); } }; private static final MBeanNotificationInfo[] NO_NOTIFICATION_INFO = new MBeanNotificationInfo[0]; private class SendNotifJob implements Runnable { public SendNotifJob(Notification notif, ListenerInfo listenerInfo) { this.notif = notif; this.listenerInfo = listenerInfo; } public void run() { try { handleNotification(listenerInfo.listener, notif, listenerInfo.handback); } catch (Exception e) { if (logger.debugOn()) { logger.debug("SendNotifJob-run", e); } } } private final Notification notif; private final ListenerInfo listenerInfo; } private static final ClassLogger logger = new ClassLogger("javax.management", "NotificationBroadcasterSupport"); }
Java
/* * Copyright (c) 1999, 2006, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management; /** {@collect.stats} * Should be implemented by an object that wants to receive notifications. * * @since 1.5 */ public interface NotificationListener extends java.util.EventListener { /** {@collect.stats} * Invoked when a JMX notification occurs. * The implementation of this method should return as soon as possible, to avoid * blocking its notification broadcaster. * * @param notification The notification. * @param handback An opaque object which helps the listener to associate information * regarding the MBean emitter. This object is passed to the MBean during the * addListener call and resent, without modification, to the listener. The MBean object * should not use or modify the object. * */ public void handleNotification(Notification notification, Object handback) ; }
Java
/* * Copyright (c) 1999, 2006, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management; import java.io.IOException; import java.io.StreamCorruptedException; import java.io.Serializable; import java.io.ObjectOutputStream; import java.io.ObjectInputStream; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Map; import java.util.WeakHashMap; import java.security.AccessController; import java.security.PrivilegedAction; import static javax.management.ImmutableDescriptor.nonNullDescriptor; /** {@collect.stats} * <p>Describes the management interface exposed by an MBean; that is, * the set of attributes and operations which are available for * management operations. Instances of this class are immutable. * Subclasses may be mutable but this is not recommended.</p> * * <p>The contents of the <code>MBeanInfo</code> for a Dynamic MBean * are determined by its {@link DynamicMBean#getMBeanInfo * getMBeanInfo()} method. This includes Open MBeans and Model * MBeans, which are kinds of Dynamic MBeans.</p> * * <p>The contents of the <code>MBeanInfo</code> for a Standard MBean * are determined by the MBean server as follows:</p> * * <ul> * * <li>{@link #getClassName()} returns the Java class name of the MBean * object; * * <li>{@link #getConstructors()} returns the list of all public * constructors in that object; * * <li>{@link #getAttributes()} returns the list of all attributes * whose existence is deduced from the presence in the MBean interface * of a <code>get<i>Name</i></code>, <code>is<i>Name</i></code>, or * <code>set<i>Name</i></code> method that conforms to the conventions * for Standard MBeans; * * <li>{@link #getOperations()} returns the list of all methods in * the MBean interface that do not represent attributes; * * <li>{@link #getNotifications()} returns an empty array if the MBean * does not implement the {@link NotificationBroadcaster} interface, * otherwise the result of calling {@link * NotificationBroadcaster#getNotificationInfo()} on it; * * <li>{@link #getDescriptor()} returns a descriptor containing the contents * of any descriptor annotations in the MBean interface. * * </ul> * * <p>The description returned by {@link #getDescription()} and the * descriptions of the contained attributes and operations are determined * by the corresponding <!-- link here --> Description annotations if any; * otherwise their contents are not specified.</p> * * <p>The remaining details of the <code>MBeanInfo</code> for a * Standard MBean are not specified. This includes the description of * any contained constructors, and notifications; the names * of parameters to constructors and operations; and the descriptions of * constructor parameters.</p> * * @since 1.5 */ public class MBeanInfo implements Cloneable, Serializable, DescriptorRead { /* Serial version */ static final long serialVersionUID = -6451021435135161911L; /** {@collect.stats} * @serial The Descriptor for the MBean. This field * can be null, which is equivalent to an empty Descriptor. */ private transient Descriptor descriptor; /** {@collect.stats} * @serial The human readable description of the class. */ private final String description; /** {@collect.stats} * @serial The MBean qualified name. */ private final String className; /** {@collect.stats} * @serial The MBean attribute descriptors. */ private final MBeanAttributeInfo[] attributes; /** {@collect.stats} * @serial The MBean operation descriptors. */ private final MBeanOperationInfo[] operations; /** {@collect.stats} * @serial The MBean constructor descriptors. */ private final MBeanConstructorInfo[] constructors; /** {@collect.stats} * @serial The MBean notification descriptors. */ private final MBeanNotificationInfo[] notifications; private transient int hashCode; /** {@collect.stats} * <p>True if this class is known not to override the array-valued * getters of MBeanInfo. Obviously true for MBeanInfo itself, and true * for a subclass where we succeed in reflecting on the methods * and discover they are not overridden.</p> * * <p>The purpose of this variable is to avoid cloning the arrays * when doing operations like {@link #equals} where we know they * will not be changed. If a subclass overrides a getter, we * cannot access the corresponding array directly.</p> */ private final transient boolean arrayGettersSafe; /** {@collect.stats} * Constructs an <CODE>MBeanInfo</CODE>. * * @param className The name of the Java class of the MBean described * by this <CODE>MBeanInfo</CODE>. This value may be any * syntactically legal Java class name. It does not have to be a * Java class known to the MBean server or to the MBean's * ClassLoader. If it is a Java class known to the MBean's * ClassLoader, it is recommended but not required that the * class's public methods include those that would appear in a * Standard MBean implementing the attributes and operations in * this MBeanInfo. * @param description A human readable description of the MBean (optional). * @param attributes The list of exposed attributes of the MBean. * This may be null with the same effect as a zero-length array. * @param constructors The list of public constructors of the * MBean. This may be null with the same effect as a zero-length * array. * @param operations The list of operations of the MBean. This * may be null with the same effect as a zero-length array. * @param notifications The list of notifications emitted. This * may be null with the same effect as a zero-length array. */ public MBeanInfo(String className, String description, MBeanAttributeInfo[] attributes, MBeanConstructorInfo[] constructors, MBeanOperationInfo[] operations, MBeanNotificationInfo[] notifications) throws IllegalArgumentException { this(className, description, attributes, constructors, operations, notifications, null); } /** {@collect.stats} * Constructs an <CODE>MBeanInfo</CODE>. * * @param className The name of the Java class of the MBean described * by this <CODE>MBeanInfo</CODE>. This value may be any * syntactically legal Java class name. It does not have to be a * Java class known to the MBean server or to the MBean's * ClassLoader. If it is a Java class known to the MBean's * ClassLoader, it is recommended but not required that the * class's public methods include those that would appear in a * Standard MBean implementing the attributes and operations in * this MBeanInfo. * @param description A human readable description of the MBean (optional). * @param attributes The list of exposed attributes of the MBean. * This may be null with the same effect as a zero-length array. * @param constructors The list of public constructors of the * MBean. This may be null with the same effect as a zero-length * array. * @param operations The list of operations of the MBean. This * may be null with the same effect as a zero-length array. * @param notifications The list of notifications emitted. This * may be null with the same effect as a zero-length array. * @param descriptor The descriptor for the MBean. This may be null * which is equivalent to an empty descriptor. * * @since 1.6 */ public MBeanInfo(String className, String description, MBeanAttributeInfo[] attributes, MBeanConstructorInfo[] constructors, MBeanOperationInfo[] operations, MBeanNotificationInfo[] notifications, Descriptor descriptor) throws IllegalArgumentException { this.className = className; this.description = description; if (attributes == null) attributes = MBeanAttributeInfo.NO_ATTRIBUTES; this.attributes = attributes; if (operations == null) operations = MBeanOperationInfo.NO_OPERATIONS; this.operations = operations; if (constructors == null) constructors = MBeanConstructorInfo.NO_CONSTRUCTORS; this.constructors = constructors; if (notifications == null) notifications = MBeanNotificationInfo.NO_NOTIFICATIONS; this.notifications = notifications; if (descriptor == null) descriptor = ImmutableDescriptor.EMPTY_DESCRIPTOR; this.descriptor = descriptor; this.arrayGettersSafe = arrayGettersSafe(this.getClass(), MBeanInfo.class); } /** {@collect.stats} * <p>Returns a shallow clone of this instance. * The clone is obtained by simply calling <tt>super.clone()</tt>, * thus calling the default native shallow cloning mechanism * implemented by <tt>Object.clone()</tt>. * No deeper cloning of any internal field is made.</p> * * <p>Since this class is immutable, the clone method is chiefly of * interest to subclasses.</p> */ public Object clone () { try { return super.clone() ; } catch (CloneNotSupportedException e) { // should not happen as this class is cloneable return null; } } /** {@collect.stats} * Returns the name of the Java class of the MBean described by * this <CODE>MBeanInfo</CODE>. * * @return the class name. */ public String getClassName() { return className; } /** {@collect.stats} * Returns a human readable description of the MBean. * * @return the description. */ public String getDescription() { return description; } /** {@collect.stats} * Returns the list of attributes exposed for management. * Each attribute is described by an <CODE>MBeanAttributeInfo</CODE> object. * * The returned array is a shallow copy of the internal array, * which means that it is a copy of the internal array of * references to the <CODE>MBeanAttributeInfo</CODE> objects * but that each referenced <CODE>MBeanAttributeInfo</CODE> object is not copied. * * @return An array of <CODE>MBeanAttributeInfo</CODE> objects. */ public MBeanAttributeInfo[] getAttributes() { MBeanAttributeInfo[] as = nonNullAttributes(); if (as.length == 0) return as; else return as.clone(); } private MBeanAttributeInfo[] fastGetAttributes() { if (arrayGettersSafe) return nonNullAttributes(); else return getAttributes(); } /** {@collect.stats} * Return the value of the attributes field, or an empty array if * the field is null. This can't happen with a * normally-constructed instance of this class, but can if the * instance was deserialized from another implementation that * allows the field to be null. It would be simpler if we enforced * the class invariant that these fields cannot be null by writing * a readObject() method, but that would require us to define the * various array fields as non-final, which is annoying because * conceptually they are indeed final. */ private MBeanAttributeInfo[] nonNullAttributes() { return (attributes == null) ? MBeanAttributeInfo.NO_ATTRIBUTES : attributes; } /** {@collect.stats} * Returns the list of operations of the MBean. * Each operation is described by an <CODE>MBeanOperationInfo</CODE> object. * * The returned array is a shallow copy of the internal array, * which means that it is a copy of the internal array of * references to the <CODE>MBeanOperationInfo</CODE> objects * but that each referenced <CODE>MBeanOperationInfo</CODE> object is not copied. * * @return An array of <CODE>MBeanOperationInfo</CODE> objects. */ public MBeanOperationInfo[] getOperations() { MBeanOperationInfo[] os = nonNullOperations(); if (os.length == 0) return os; else return os.clone(); } private MBeanOperationInfo[] fastGetOperations() { if (arrayGettersSafe) return nonNullOperations(); else return getOperations(); } private MBeanOperationInfo[] nonNullOperations() { return (operations == null) ? MBeanOperationInfo.NO_OPERATIONS : operations; } /** {@collect.stats} * <p>Returns the list of the public constructors of the MBean. * Each constructor is described by an * <CODE>MBeanConstructorInfo</CODE> object.</p> * * <p>The returned array is a shallow copy of the internal array, * which means that it is a copy of the internal array of * references to the <CODE>MBeanConstructorInfo</CODE> objects but * that each referenced <CODE>MBeanConstructorInfo</CODE> object * is not copied.</p> * * <p>The returned list is not necessarily exhaustive. That is, * the MBean may have a public constructor that is not in the * list. In this case, the MBean server can construct another * instance of this MBean's class using that constructor, even * though it is not listed here.</p> * * @return An array of <CODE>MBeanConstructorInfo</CODE> objects. */ public MBeanConstructorInfo[] getConstructors() { MBeanConstructorInfo[] cs = nonNullConstructors(); if (cs.length == 0) return cs; else return cs.clone(); } private MBeanConstructorInfo[] fastGetConstructors() { if (arrayGettersSafe) return nonNullConstructors(); else return getConstructors(); } private MBeanConstructorInfo[] nonNullConstructors() { return (constructors == null) ? MBeanConstructorInfo.NO_CONSTRUCTORS : constructors; } /** {@collect.stats} * Returns the list of the notifications emitted by the MBean. * Each notification is described by an <CODE>MBeanNotificationInfo</CODE> object. * * The returned array is a shallow copy of the internal array, * which means that it is a copy of the internal array of * references to the <CODE>MBeanNotificationInfo</CODE> objects * but that each referenced <CODE>MBeanNotificationInfo</CODE> object is not copied. * * @return An array of <CODE>MBeanNotificationInfo</CODE> objects. */ public MBeanNotificationInfo[] getNotifications() { MBeanNotificationInfo[] ns = nonNullNotifications(); if (ns.length == 0) return ns; else return ns.clone(); } private MBeanNotificationInfo[] fastGetNotifications() { if (arrayGettersSafe) return nonNullNotifications(); else return getNotifications(); } private MBeanNotificationInfo[] nonNullNotifications() { return (notifications == null) ? MBeanNotificationInfo.NO_NOTIFICATIONS : notifications; } /** {@collect.stats} * Get the descriptor of this MBeanInfo. Changing the returned value * will have no affect on the original descriptor. * * @return a descriptor that is either immutable or a copy of the original. * * @since 1.6 */ public Descriptor getDescriptor() { return (Descriptor) nonNullDescriptor(descriptor).clone(); } public String toString() { return getClass().getName() + "[" + "description=" + getDescription() + ", " + "attributes=" + Arrays.asList(fastGetAttributes()) + ", " + "constructors=" + Arrays.asList(fastGetConstructors()) + ", " + "operations=" + Arrays.asList(fastGetOperations()) + ", " + "notifications=" + Arrays.asList(fastGetNotifications()) + ", " + "descriptor=" + getDescriptor() + "]"; } /** {@collect.stats} * <p>Compare this MBeanInfo to another. Two MBeanInfo objects * are equal if and only if they return equal values for {@link * #getClassName()}, for {@link #getDescription()}, and for * {@link #getDescriptor()}, and the * arrays returned by the two objects for {@link * #getAttributes()}, {@link #getOperations()}, {@link * #getConstructors()}, and {@link #getNotifications()} are * pairwise equal. Here "equal" means {@link * Object#equals(Object)}, not identity.</p> * * <p>If two MBeanInfo objects return the same values in one of * their arrays but in a different order then they are not equal.</p> * * @param o the object to compare to. * * @return true if and only if <code>o</code> is an MBeanInfo that is equal * to this one according to the rules above. */ public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof MBeanInfo)) return false; MBeanInfo p = (MBeanInfo) o; if (!isEqual(getClassName(), p.getClassName()) || !isEqual(getDescription(), p.getDescription()) || !getDescriptor().equals(p.getDescriptor())) { return false; } return (Arrays.equals(p.fastGetAttributes(), fastGetAttributes()) && Arrays.equals(p.fastGetOperations(), fastGetOperations()) && Arrays.equals(p.fastGetConstructors(), fastGetConstructors()) && Arrays.equals(p.fastGetNotifications(), fastGetNotifications())); } public int hashCode() { /* Since computing the hashCode is quite expensive, we cache it. If by some terrible misfortune the computed value is 0, the caching won't work and we will recompute it every time. We don't bother synchronizing, because, at worst, n different threads will compute the same hashCode at the same time. */ if (hashCode != 0) return hashCode; hashCode = getClassName().hashCode() ^ getDescriptor().hashCode() ^ arrayHashCode(fastGetAttributes()) ^ arrayHashCode(fastGetOperations()) ^ arrayHashCode(fastGetConstructors()) ^ arrayHashCode(fastGetNotifications()); return hashCode; } private static int arrayHashCode(Object[] array) { int hash = 0; for (int i = 0; i < array.length; i++) hash ^= array[i].hashCode(); return hash; } /** {@collect.stats} * Cached results of previous calls to arrayGettersSafe. This is * a WeakHashMap so that we don't prevent a class from being * garbage collected just because we know whether it's immutable. */ private static final Map<Class, Boolean> arrayGettersSafeMap = new WeakHashMap<Class, Boolean>(); /** {@collect.stats} * Return true if <code>subclass</code> is known to preserve the * immutability of <code>immutableClass</code>. The class * <code>immutableClass</code> is a reference class that is known * to be immutable. The subclass <code>subclass</code> is * considered immutable if it does not override any public method * of <code>immutableClass</code> whose name begins with "get". * This is obviously not an infallible test for immutability, * but it works for the public interfaces of the MBean*Info classes. */ static boolean arrayGettersSafe(Class subclass, Class immutableClass) { if (subclass == immutableClass) return true; synchronized (arrayGettersSafeMap) { Boolean safe = arrayGettersSafeMap.get(subclass); if (safe == null) { try { ArrayGettersSafeAction action = new ArrayGettersSafeAction(subclass, immutableClass); safe = AccessController.doPrivileged(action); } catch (Exception e) { // e.g. SecurityException /* We don't know, so we assume it isn't. */ safe = false; } arrayGettersSafeMap.put(subclass, safe); } return safe; } } /* * The PrivilegedAction stuff is probably overkill. We can be * pretty sure the caller does have the required privileges -- a * JMX user that can't do reflection can't even use Standard * MBeans! But there's probably a performance gain by not having * to check the whole call stack. */ private static class ArrayGettersSafeAction implements PrivilegedAction<Boolean> { private final Class<?> subclass; private final Class<?> immutableClass; ArrayGettersSafeAction(Class<?> subclass, Class<?> immutableClass) { this.subclass = subclass; this.immutableClass = immutableClass; } public Boolean run() { Method[] methods = immutableClass.getMethods(); for (int i = 0; i < methods.length; i++) { Method method = methods[i]; String methodName = method.getName(); if (methodName.startsWith("get") && method.getParameterTypes().length == 0 && method.getReturnType().isArray()) { try { Method submethod = subclass.getMethod(methodName); if (!submethod.equals(method)) return false; } catch (NoSuchMethodException e) { return false; } } } return true; } } private static boolean isEqual(String s1, String s2) { boolean ret; if (s1 == null) { ret = (s2 == null); } else { ret = s1.equals(s2); } return ret; } /** {@collect.stats} * Serializes an {@link MBeanInfo} to an {@link ObjectOutputStream}. * @serialData * For compatibility reasons, an object of this class is serialized as follows. * <ul> * The method {@link ObjectOutputStream#defaultWriteObject defaultWriteObject()} * is called first to serialize the object except the field {@code descriptor} * which is declared as transient. The field {@code descriptor} is serialized * as follows: * <ul> * <li> If {@code descriptor} is an instance of the class * {@link ImmutableDescriptor}, the method {@link ObjectOutputStream#write * write(int val)} is called to write a byte with the value {@code 1}, * then the method {@link ObjectOutputStream#writeObject writeObject(Object obj)} * is called twice to serialize the field names and the field values of the * {@code descriptor}, respectively as a {@code String[]} and an * {@code Object[]};</li> * <li> Otherwise, the method {@link ObjectOutputStream#write write(int val)} * is called to write a byte with the value {@code 0}, then the method * {@link ObjectOutputStream#writeObject writeObject(Object obj)} is called * to serialize the field {@code descriptor} directly. * </ul> * </ul> * @since 1.6 */ private void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); if (descriptor.getClass() == ImmutableDescriptor.class) { out.write(1); final String[] names = descriptor.getFieldNames(); out.writeObject(names); out.writeObject(descriptor.getFieldValues(names)); } else { out.write(0); out.writeObject(descriptor); } } /** {@collect.stats} * Deserializes an {@link MBeanInfo} from an {@link ObjectInputStream}. * @serialData * For compatibility reasons, an object of this class is deserialized as follows. * <ul> * The method {@link ObjectInputStream#defaultReadObject defaultReadObject()} * is called first to deserialize the object except the field * {@code descriptor}, which is not serialized in the default way. Then the method * {@link ObjectInputStream#read read()} is called to read a byte, the field * {@code descriptor} is deserialized according to the value of the byte value: * <ul> * <li>1. The method {@link ObjectInputStream#readObject readObject()} * is called twice to obtain the field names (a {@code String[]}) and * the field values (a {@code Object[]}) of the {@code descriptor}. * The two obtained values then are used to construct * an {@link ImmutableDescriptor} instance for the field * {@code descriptor};</li> * <li>0. The value for the field {@code descriptor} is obtained directly * by calling the method {@link ObjectInputStream#readObject readObject()}. * If the obtained value is null, the field {@code descriptor} is set to * {@link ImmutableDescriptor#EMPTY_DESCRIPTOR EMPTY_DESCRIPTOR};</li> * <li>-1. This means that there is no byte to read and that the object is from * an earlier version of the JMX API. The field {@code descriptor} is set to * {@link ImmutableDescriptor#EMPTY_DESCRIPTOR EMPTY_DESCRIPTOR}.</li> * <li>Any other value. A {@link StreamCorruptedException} is thrown.</li> * </ul> * </ul> * @since 1.6 */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); switch (in.read()) { case 1: final String[] names = (String[])in.readObject(); if (names.length == 0) { descriptor = ImmutableDescriptor.EMPTY_DESCRIPTOR; } else { final Object[] values = (Object[])in.readObject(); descriptor = new ImmutableDescriptor(names, values); } break; case 0: descriptor = (Descriptor)in.readObject(); if (descriptor == null) { descriptor = ImmutableDescriptor.EMPTY_DESCRIPTOR; } break; case -1: // from an earlier version of the JMX API descriptor = ImmutableDescriptor.EMPTY_DESCRIPTOR; break; default: throw new StreamCorruptedException("Got unexpected byte."); } } }
Java
/* * Copyright (c) 1999, 2004, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management; /** {@collect.stats} * Can be implemented by an MBean in order to * carry out operations before and after being registered or unregistered from * the MBean server. * * @since 1.5 */ public interface MBeanRegistration { /** {@collect.stats} * Allows the MBean to perform any operations it needs before * being registered in the MBean server. If the name of the MBean * is not specified, the MBean can provide a name for its * registration. If any exception is raised, the MBean will not be * registered in the MBean server. * * @param server The MBean server in which the MBean will be registered. * * @param name The object name of the MBean. This name is null if * the name parameter to one of the <code>createMBean</code> or * <code>registerMBean</code> methods in the {@link MBeanServer} * interface is null. In that case, this method must return a * non-null ObjectName for the new MBean. * * @return The name under which the MBean is to be registered. * This value must not be null. If the <code>name</code> * parameter is not null, it will usually but not necessarily be * the returned value. * * @exception java.lang.Exception This exception will be caught by * the MBean server and re-thrown as an {@link * MBeanRegistrationException}. */ public ObjectName preRegister(MBeanServer server, ObjectName name) throws java.lang.Exception; /** {@collect.stats} * Allows the MBean to perform any operations needed after having been * registered in the MBean server or after the registration has failed. * * @param registrationDone Indicates whether or not the MBean has * been successfully registered in the MBean server. The value * false means that the registration phase has failed. */ public void postRegister(Boolean registrationDone); /** {@collect.stats} * Allows the MBean to perform any operations it needs before * being unregistered by the MBean server. * * @exception java.lang.Exception This exception will be caught by * the MBean server and re-thrown as an {@link * MBeanRegistrationException}. */ public void preDeregister() throws java.lang.Exception ; /** {@collect.stats} * Allows the MBean to perform any operations needed after having been * unregistered in the MBean server. */ public void postDeregister(); }
Java
/* * Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management; /** {@collect.stats} * The format of the string does not correspond to a valid ObjectName. * * @since 1.5 */ public class MalformedObjectNameException extends OperationsException { /* Serial version */ private static final long serialVersionUID = -572689714442915824L; /** {@collect.stats} * Default constructor. */ public MalformedObjectNameException() { super(); } /** {@collect.stats} * Constructor that allows a specific error message to be specified. * * @param message the detail message. */ public MalformedObjectNameException(String message) { super(message); } }
Java
/* * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management; // java import import java.io.Serializable; // RI import import javax.management.MBeanServer; /** {@collect.stats} * Allows a query to be performed in the context of a specific MBean server. * * @since 1.5 */ public abstract class QueryEval implements Serializable { /* Serial version */ private static final long serialVersionUID = 2675899265640874796L; private static ThreadLocal<MBeanServer> server = new InheritableThreadLocal<MBeanServer>(); /** {@collect.stats} * <p>Sets the MBean server on which the query is to be performed. * The setting is valid for the thread performing the set. * It is copied to any threads created by that thread at the moment * of their creation.</p> * * <p>For historical reasons, this method is not static, but its * behavior does not depend on the instance on which it is * called.</p> * * @param s The MBean server on which the query is to be performed. * * @see #getMBeanServer */ public void setMBeanServer(MBeanServer s) { server.set(s); } /** {@collect.stats} * <p>Return the MBean server that was most recently given to the * {@link #setMBeanServer setMBeanServer} method by this thread. * If this thread never called that method, the result is the * value its parent thread would have obtained from * <code>getMBeanServer</code> at the moment of the creation of * this thread, or null if there is no parent thread.</p> * * @return the MBean server. * * @see #setMBeanServer * */ public static MBeanServer getMBeanServer() { return server.get(); } }
Java
/* * Copyright (c) 1999, 2006, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.io.StreamCorruptedException; /** {@collect.stats} * <p>Provides general information for an MBean descriptor object. * The feature described can be an attribute, an operation, a * parameter, or a notification. Instances of this class are * immutable. Subclasses may be mutable but this is not * recommended.</p> * * @since 1.5 */ public class MBeanFeatureInfo implements Serializable, DescriptorRead { /* Serial version */ static final long serialVersionUID = 3952882688968447265L; /** {@collect.stats} * The name of the feature. It is recommended that subclasses call * {@link #getName} rather than reading this field, and that they * not change it. * * @serial The name of the feature. */ protected String name; /** {@collect.stats} * The human-readable description of the feature. It is * recommended that subclasses call {@link #getDescription} rather * than reading this field, and that they not change it. * * @serial The human-readable description of the feature. */ protected String description; /** {@collect.stats} * @serial The Descriptor for this MBeanFeatureInfo. This field * can be null, which is equivalent to an empty Descriptor. */ private transient Descriptor descriptor; /** {@collect.stats} * Constructs an <CODE>MBeanFeatureInfo</CODE> object. This * constructor is equivalent to {@code MBeanFeatureInfo(name, * description, (Descriptor) null}. * * @param name The name of the feature. * @param description A human readable description of the feature. */ public MBeanFeatureInfo(String name, String description) { this(name, description, null); } /** {@collect.stats} * Constructs an <CODE>MBeanFeatureInfo</CODE> object. * * @param name The name of the feature. * @param description A human readable description of the feature. * @param descriptor The descriptor for the feature. This may be null * which is equivalent to an empty descriptor. * * @since 1.6 */ public MBeanFeatureInfo(String name, String description, Descriptor descriptor) { this.name = name; this.description = description; this.descriptor = descriptor; } /** {@collect.stats} * Returns the name of the feature. * * @return the name of the feature. */ public String getName() { return name; } /** {@collect.stats} * Returns the human-readable description of the feature. * * @return the human-readable description of the feature. */ public String getDescription() { return description; } /** {@collect.stats} * Returns the descriptor for the feature. Changing the returned value * will have no affect on the original descriptor. * * @return a descriptor that is either immutable or a copy of the original. * * @since 1.6 */ public Descriptor getDescriptor() { return (Descriptor) ImmutableDescriptor.nonNullDescriptor(descriptor).clone(); } /** {@collect.stats} * Compare this MBeanFeatureInfo to another. * * @param o the object to compare to. * * @return true if and only if <code>o</code> is an MBeanFeatureInfo such * that its {@link #getName()}, {@link #getDescription()}, and * {@link #getDescriptor()} * values are equal (not necessarily identical) to those of this * MBeanFeatureInfo. */ public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof MBeanFeatureInfo)) return false; MBeanFeatureInfo p = (MBeanFeatureInfo) o; return (p.getName().equals(getName()) && p.getDescription().equals(getDescription()) && p.getDescriptor().equals(getDescriptor())); } public int hashCode() { return getName().hashCode() ^ getDescription().hashCode() ^ getDescriptor().hashCode(); } /** {@collect.stats} * Serializes an {@link MBeanFeatureInfo} to an {@link ObjectOutputStream}. * @serialData * For compatibility reasons, an object of this class is serialized as follows. * <ul> * The method {@link ObjectOutputStream#defaultWriteObject defaultWriteObject()} * is called first to serialize the object except the field {@code descriptor} * which is declared as transient. The field {@code descriptor} is serialized * as follows: * <ul> * <li>If {@code descriptor} is an instance of the class * {@link ImmutableDescriptor}, the method {@link ObjectOutputStream#write * write(int val)} is called to write a byte with the value {@code 1}, * then the method {@link ObjectOutputStream#writeObject writeObject(Object obj)} * is called twice to serialize the field names and the field values of the * {@code descriptor}, respectively as a {@code String[]} and an * {@code Object[]};</li> * <li>Otherwise, the method {@link ObjectOutputStream#write write(int val)} * is called to write a byte with the value {@code 0}, then the method * {@link ObjectOutputStream#writeObject writeObject(Object obj)} is called * to serialize directly the field {@code descriptor}. * </ul> * </ul> * @since 1.6 */ private void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); if (descriptor != null && descriptor.getClass() == ImmutableDescriptor.class) { out.write(1); final String[] names = descriptor.getFieldNames(); out.writeObject(names); out.writeObject(descriptor.getFieldValues(names)); } else { out.write(0); out.writeObject(descriptor); } } /** {@collect.stats} * Deserializes an {@link MBeanFeatureInfo} from an {@link ObjectInputStream}. * @serialData * For compatibility reasons, an object of this class is deserialized as follows. * <ul> * The method {@link ObjectInputStream#defaultReadObject defaultReadObject()} * is called first to deserialize the object except the field * {@code descriptor}, which is not serialized in the default way. Then the method * {@link ObjectInputStream#read read()} is called to read a byte, the field * {@code descriptor} is deserialized according to the value of the byte value: * <ul> * <li>1. The method {@link ObjectInputStream#readObject readObject()} * is called twice to obtain the field names (a {@code String[]}) and * the field values (a {@code Object[]}) of the {@code descriptor}. * The two obtained values then are used to construct * an {@link ImmutableDescriptor} instance for the field * {@code descriptor};</li> * <li>0. The value for the field {@code descriptor} is obtained directly * by calling the method {@link ObjectInputStream#readObject readObject()}. * If the obtained value is null, the field {@code descriptor} is set to * {@link ImmutableDescriptor#EMPTY_DESCRIPTOR EMPTY_DESCRIPTOR};</li> * <li>-1. This means that there is no byte to read and that the object is from * an earlier version of the JMX API. The field {@code descriptor} is set * to {@link ImmutableDescriptor#EMPTY_DESCRIPTOR EMPTY_DESCRIPTOR}</li> * <li>Any other value. A {@link StreamCorruptedException} is thrown.</li> * </ul> * </ul> * @since 1.6 */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); switch (in.read()) { case 1: final String[] names = (String[])in.readObject(); if (names.length == 0) { descriptor = ImmutableDescriptor.EMPTY_DESCRIPTOR; } else { final Object[] values = (Object[])in.readObject(); descriptor = new ImmutableDescriptor(names, values); } break; case 0: descriptor = (Descriptor)in.readObject(); if (descriptor == null) { descriptor = ImmutableDescriptor.EMPTY_DESCRIPTOR; } break; case -1: // from an earlier version of the JMX API descriptor = ImmutableDescriptor.EMPTY_DESCRIPTOR; break; default: throw new StreamCorruptedException("Got unexpected byte."); } } }
Java
/* * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management; import static com.sun.jmx.defaults.JmxProperties.JMX_INITIAL_BUILDER; import static com.sun.jmx.defaults.JmxProperties.MBEANSERVER_LOGGER; import com.sun.jmx.interceptor.DefaultMBeanServerInterceptor; import com.sun.jmx.mbeanserver.GetPropertyAction; import java.security.AccessController; import java.security.Permission; import java.util.ArrayList; import java.util.logging.Level; import javax.management.loading.ClassLoaderRepository; /** {@collect.stats} * <p>Provides MBean server references. There are no instances of * this class.</p> * * <p>Since JMX 1.2 this class makes it possible to replace the default * MBeanServer implementation. This is done using the * {@link javax.management.MBeanServerBuilder} class. * The class of the initial MBeanServerBuilder to be * instantiated can be specified through the * <b>javax.management.builder.initial</b> system property. * The specified class must be a public subclass of * {@link javax.management.MBeanServerBuilder}, and must have a public * empty constructor. * <p>By default, if no value for that property is specified, an instance of * {@link * javax.management.MBeanServerBuilder javax.management.MBeanServerBuilder} * is created. Otherwise, the MBeanServerFactory attempts to load the * specified class using * {@link java.lang.Thread#getContextClassLoader() * Thread.currentThread().getContextClassLoader()}, or if that is null, * {@link java.lang.Class#forName(java.lang.String) Class.forName()}. Then * it creates an initial instance of that Class using * {@link java.lang.Class#newInstance()}. If any checked exception * is raised during this process (e.g. * {@link java.lang.ClassNotFoundException}, * {@link java.lang.InstantiationException}) the MBeanServerFactory * will propagate this exception from within a RuntimeException.</p> * * <p>The <b>javax.management.builder.initial</b> system property is * consulted every time a new MBeanServer needs to be created, and the * class pointed to by that property is loaded. If that class is different * from that of the current MBeanServerBuilder, then a new MBeanServerBuilder * is created. Otherwise, the MBeanServerFactory may create a new * MBeanServerBuilder or reuse the current one.</p> * * <p>If the class pointed to by the property cannot be * loaded, or does not correspond to a valid subclass of MBeanServerBuilder * then an exception is propagated, and no MBeanServer can be created until * the <b>javax.management.builder.initial</b> system property is reset to * valid value.</p> * * <p>The MBeanServerBuilder makes it possible to wrap the MBeanServers * returned by the default MBeanServerBuilder implementation, for the purpose * of e.g. adding an additional security layer.</p> * * @since 1.5 */ public class MBeanServerFactory { /* * There are no instances of this class so don't generate the * default public constructor. */ private MBeanServerFactory() { } /** {@collect.stats} * The builder that will be used to construct MBeanServers. * **/ private static MBeanServerBuilder builder = null; /** {@collect.stats} * Provide a new {@link javax.management.MBeanServerBuilder}. * @param builder The new MBeanServerBuilder that will be used to * create {@link javax.management.MBeanServer}s. * @exception IllegalArgumentException if the given builder is null. * * @exception SecurityException if there is a SecurityManager and * the caller's permissions do not include or imply <code>{@link * MBeanServerPermission}("setMBeanServerBuilder")</code>. * **/ // public static synchronized void // setMBeanServerBuilder(MBeanServerBuilder builder) { // checkPermission("setMBeanServerBuilder"); // MBeanServerFactory.builder = builder; // } /** {@collect.stats} * Get the current {@link javax.management.MBeanServerBuilder}. * * @return the current {@link javax.management.MBeanServerBuilder}. * * @exception SecurityException if there is a SecurityManager and * the caller's permissions do not include or imply <code>{@link * MBeanServerPermission}("getMBeanServerBuilder")</code>. * **/ // public static synchronized MBeanServerBuilder getMBeanServerBuilder() { // checkPermission("getMBeanServerBuilder"); // return builder; // } /** {@collect.stats} * Remove internal MBeanServerFactory references to a created * MBeanServer. This allows the garbage collector to remove the * MBeanServer object. * * @param mbeanServer the MBeanServer object to remove. * * @exception java.lang.IllegalArgumentException if * <code>mbeanServer</code> was not generated by one of the * <code>createMBeanServer</code> methods, or if * <code>releaseMBeanServer</code> was already called on it. * * @exception SecurityException if there is a SecurityManager and * the caller's permissions do not include or imply <code>{@link * MBeanServerPermission}("releaseMBeanServer")</code>. */ public static void releaseMBeanServer(MBeanServer mbeanServer) { checkPermission("releaseMBeanServer"); removeMBeanServer(mbeanServer); } /** {@collect.stats} * <p>Return a new object implementing the MBeanServer interface * with a standard default domain name. The default domain name * is used as the domain part in the ObjectName of MBeans when the * domain is specified by the user is null.</p> * * <p>The standard default domain name is * <code>DefaultDomain</code>.</p> * * <p>The MBeanServer reference is internally kept. This will * allow <CODE>findMBeanServer</CODE> to return a reference to * this MBeanServer object.</p> * * <p>This method is equivalent to <code>createMBeanServer(null)</code>. * * @return the newly created MBeanServer. * * @exception SecurityException if there is a SecurityManager and the * caller's permissions do not include or imply <code>{@link * MBeanServerPermission}("createMBeanServer")</code>. * * @exception JMRuntimeException if the property * <code>javax.management.builder.initial</code> exists but the * class it names cannot be instantiated through a public * no-argument constructor; or if the instantiated builder returns * null from its {@link MBeanServerBuilder#newMBeanServerDelegate * newMBeanServerDelegate} or {@link * MBeanServerBuilder#newMBeanServer newMBeanServer} methods. * * @exception ClassCastException if the property * <code>javax.management.builder.initial</code> exists and can be * instantiated but is not assignment compatible with {@link * MBeanServerBuilder}. */ public static MBeanServer createMBeanServer() { return createMBeanServer(null); } /** {@collect.stats} * <p>Return a new object implementing the {@link MBeanServer} * interface with the specified default domain name. The given * domain name is used as the domain part in the ObjectName of * MBeans when the domain is specified by the user is null.</p> * * <p>The MBeanServer reference is internally kept. This will * allow <CODE>findMBeanServer</CODE> to return a reference to * this MBeanServer object.</p> * * @param domain the default domain name for the created * MBeanServer. This is the value that will be returned by {@link * MBeanServer#getDefaultDomain}. * * @return the newly created MBeanServer. * * @exception SecurityException if there is a SecurityManager and * the caller's permissions do not include or imply <code>{@link * MBeanServerPermission}("createMBeanServer")</code>. * * @exception JMRuntimeException if the property * <code>javax.management.builder.initial</code> exists but the * class it names cannot be instantiated through a public * no-argument constructor; or if the instantiated builder returns * null from its {@link MBeanServerBuilder#newMBeanServerDelegate * newMBeanServerDelegate} or {@link * MBeanServerBuilder#newMBeanServer newMBeanServer} methods. * * @exception ClassCastException if the property * <code>javax.management.builder.initial</code> exists and can be * instantiated but is not assignment compatible with {@link * MBeanServerBuilder}. */ public static MBeanServer createMBeanServer(String domain) { checkPermission("createMBeanServer"); final MBeanServer mBeanServer = newMBeanServer(domain); addMBeanServer(mBeanServer); return mBeanServer; } /** {@collect.stats} * <p>Return a new object implementing the MBeanServer interface * with a standard default domain name, without keeping an * internal reference to this new object. The default domain name * is used as the domain part in the ObjectName of MBeans when the * domain is specified by the user is null.</p> * * <p>The standard default domain name is * <code>DefaultDomain</code>.</p> * * <p>No reference is kept. <CODE>findMBeanServer</CODE> will not * be able to return a reference to this MBeanServer object, but * the garbage collector will be able to remove the MBeanServer * object when it is no longer referenced.</p> * * <p>This method is equivalent to <code>newMBeanServer(null)</code>.</p> * * @return the newly created MBeanServer. * * @exception SecurityException if there is a SecurityManager and the * caller's permissions do not include or imply <code>{@link * MBeanServerPermission}("newMBeanServer")</code>. * * @exception JMRuntimeException if the property * <code>javax.management.builder.initial</code> exists but the * class it names cannot be instantiated through a public * no-argument constructor; or if the instantiated builder returns * null from its {@link MBeanServerBuilder#newMBeanServerDelegate * newMBeanServerDelegate} or {@link * MBeanServerBuilder#newMBeanServer newMBeanServer} methods. * * @exception ClassCastException if the property * <code>javax.management.builder.initial</code> exists and can be * instantiated but is not assignment compatible with {@link * MBeanServerBuilder}. */ public static MBeanServer newMBeanServer() { return newMBeanServer(null); } /** {@collect.stats} * <p>Return a new object implementing the MBeanServer interface * with the specified default domain name, without keeping an * internal reference to this new object. The given domain name * is used as the domain part in the ObjectName of MBeans when the * domain is specified by the user is null.</p> * * <p>No reference is kept. <CODE>findMBeanServer</CODE> will not * be able to return a reference to this MBeanServer object, but * the garbage collector will be able to remove the MBeanServer * object when it is no longer referenced.</p> * * @param domain the default domain name for the created * MBeanServer. This is the value that will be returned by {@link * MBeanServer#getDefaultDomain}. * * @return the newly created MBeanServer. * * @exception SecurityException if there is a SecurityManager and the * caller's permissions do not include or imply <code>{@link * MBeanServerPermission}("newMBeanServer")</code>. * * @exception JMRuntimeException if the property * <code>javax.management.builder.initial</code> exists but the * class it names cannot be instantiated through a public * no-argument constructor; or if the instantiated builder returns * null from its {@link MBeanServerBuilder#newMBeanServerDelegate * newMBeanServerDelegate} or {@link * MBeanServerBuilder#newMBeanServer newMBeanServer} methods. * * @exception ClassCastException if the property * <code>javax.management.builder.initial</code> exists and can be * instantiated but is not assignment compatible with {@link * MBeanServerBuilder}. */ public static MBeanServer newMBeanServer(String domain) { checkPermission("newMBeanServer"); // Get the builder. Creates a new one if necessary. // final MBeanServerBuilder mbsBuilder = getNewMBeanServerBuilder(); // Returned value cannot be null. NullPointerException if violated. synchronized(mbsBuilder) { final MBeanServerDelegate delegate = mbsBuilder.newMBeanServerDelegate(); if (delegate == null) { final String msg = "MBeanServerBuilder.newMBeanServerDelegate() " + "returned null"; throw new JMRuntimeException(msg); } final MBeanServer mbeanServer = mbsBuilder.newMBeanServer(domain,null,delegate); if (mbeanServer == null) { final String msg = "MBeanServerBuilder.newMBeanServer() returned null"; throw new JMRuntimeException(msg); } return mbeanServer; } } /** {@collect.stats} * <p>Return a list of registered MBeanServer objects. A * registered MBeanServer object is one that was created by one of * the <code>createMBeanServer</code> methods and not subsequently * released with <code>releaseMBeanServer</code>.</p> * * @param agentId The agent identifier of the MBeanServer to * retrieve. If this parameter is null, all registered * MBeanServers in this JVM are returned. Otherwise, only * MBeanServers whose id is equal to <code>agentId</code> are * returned. The id of an MBeanServer is the * <code>MBeanServerId</code> attribute of its delegate MBean. * * @return A list of MBeanServer objects. * * @exception SecurityException if there is a SecurityManager and the * caller's permissions do not include or imply <code>{@link * MBeanServerPermission}("findMBeanServer")</code>. */ public synchronized static ArrayList<MBeanServer> findMBeanServer(String agentId) { checkPermission("findMBeanServer"); if (agentId == null) return new ArrayList<MBeanServer>(mBeanServerList); ArrayList<MBeanServer> result = new ArrayList<MBeanServer>(); for (MBeanServer mbs : mBeanServerList) { String name = mBeanServerName(mbs); if (agentId.equals(name)) result.add(mbs); } return result; } /** {@collect.stats} * Return the ClassLoaderRepository used by the given MBeanServer. * This method is equivalent to {@link MBeanServer#getClassLoaderRepository() server.getClassLoaderRepository()}. * @param server The MBeanServer under examination. Since JMX 1.2, * if <code>server</code> is <code>null</code>, the result is a * {@link NullPointerException}. This behavior differs from what * was implemented in JMX 1.1 - where the possibility to use * <code>null</code> was deprecated. * @return The Class Loader Repository used by the given MBeanServer. * @exception SecurityException if there is a SecurityManager and * the caller's permissions do not include or imply <code>{@link * MBeanPermission}("getClassLoaderRepository")</code>. * * @exception NullPointerException if <code>server</code> is null. * **/ public static ClassLoaderRepository getClassLoaderRepository( MBeanServer server) { return server.getClassLoaderRepository(); } private static String mBeanServerName(MBeanServer mbs) { try { return (String) mbs.getAttribute(MBeanServerDelegate.DELEGATE_NAME, "MBeanServerId"); } catch (JMException e) { return null; } } private static void checkPermission(String action) throws SecurityException { SecurityManager sm = System.getSecurityManager(); if (sm != null) { Permission perm = new MBeanServerPermission(action); sm.checkPermission(perm); } } private static synchronized void addMBeanServer(MBeanServer mbs) { mBeanServerList.add(mbs); } private static synchronized void removeMBeanServer(MBeanServer mbs) { boolean removed = mBeanServerList.remove(mbs); if (!removed) { MBEANSERVER_LOGGER.logp(Level.FINER, MBeanServerFactory.class.getName(), "removeMBeanServer(MBeanServer)", "MBeanServer was not in list!"); throw new IllegalArgumentException("MBeanServer was not in list!"); } } private static final ArrayList<MBeanServer> mBeanServerList = new ArrayList<MBeanServer>(); /** {@collect.stats} * Load the builder class through the context class loader. * @param builderClassName The name of the builder class. **/ private static Class loadBuilderClass(String builderClassName) throws ClassNotFoundException { final ClassLoader loader = Thread.currentThread().getContextClassLoader(); if (loader != null) { // Try with context class loader return loader.loadClass(builderClassName); } // No context class loader? Try with Class.forName() return Class.forName(builderClassName); } /** {@collect.stats} * Creates the initial builder according to the * javax.management.builder.initial System property - if specified. * If any checked exception needs to be thrown, it is embedded in * a JMRuntimeException. **/ private static MBeanServerBuilder newBuilder(Class builderClass) { try { final Object builder = builderClass.newInstance(); return (MBeanServerBuilder)builder; } catch (RuntimeException x) { throw x; } catch (Exception x) { final String msg = "Failed to instantiate a MBeanServerBuilder from " + builderClass + ": " + x; throw new JMRuntimeException(msg, x); } } /** {@collect.stats} * Instantiate a new builder according to the * javax.management.builder.initial System property - if needed. **/ private static synchronized void checkMBeanServerBuilder() { try { GetPropertyAction act = new GetPropertyAction(JMX_INITIAL_BUILDER); String builderClassName = AccessController.doPrivileged(act); try { final Class newBuilderClass; if (builderClassName == null || builderClassName.length() == 0) newBuilderClass = MBeanServerBuilder.class; else newBuilderClass = loadBuilderClass(builderClassName); // Check whether a new builder needs to be created if (builder != null) { final Class builderClass = builder.getClass(); if (newBuilderClass == builderClass) return; // no need to create a new builder... } // Create a new builder builder = newBuilder(newBuilderClass); } catch (ClassNotFoundException x) { final String msg = "Failed to load MBeanServerBuilder class " + builderClassName + ": " + x; throw new JMRuntimeException(msg, x); } } catch (RuntimeException x) { if (MBEANSERVER_LOGGER.isLoggable(Level.FINEST)) { StringBuilder strb = new StringBuilder() .append("Failed to instantiate MBeanServerBuilder: ").append(x) .append("\n\t\tCheck the value of the ") .append(JMX_INITIAL_BUILDER).append(" property."); MBEANSERVER_LOGGER.logp(Level.FINEST, MBeanServerFactory.class.getName(), "checkMBeanServerBuilder", strb.toString()); } throw x; } } /** {@collect.stats} * Get the current {@link javax.management.MBeanServerBuilder}, * as specified by the current value of the * javax.management.builder.initial property. * * This method consults the property and instantiates a new builder * if needed. * * @return the new current {@link javax.management.MBeanServerBuilder}. * * @exception SecurityException if there is a SecurityManager and * the caller's permissions do not make it possible to instantiate * a new builder. * @exception JMRuntimeException if the builder instantiation * fails with a checked exception - * {@link java.lang.ClassNotFoundException} etc... * **/ private static synchronized MBeanServerBuilder getNewMBeanServerBuilder() { checkMBeanServerBuilder(); return builder; } }
Java
/* * Copyright (c) 2000, 2005, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ /* * @author IBM Corp. * * Copyright IBM Corp. 1999-2000. All rights reserved. */ package javax.management; import javax.management.MBeanException; import javax.management.RuntimeOperationsException; import javax.management.InstanceNotFoundException; /** {@collect.stats} * This class is the interface to be implemented by MBeans that are meant to be * persistent. MBeans supporting this interface should call the load method during * construction in order to prime the MBean from the persistent store. * In the case of a ModelMBean, the store method should be called by the MBeanServer based on the descriptors in * the ModelMBean or by the MBean itself during normal processing of the ModelMBean. * * @since 1.5 */ public interface PersistentMBean { /** {@collect.stats} * Instantiates thisMBean instance with the data found for * the MBean in the persistent store. The data loaded could include * attribute and operation values. * * This method should be called during construction or initialization of this instance, * and before the MBean is registered with the MBeanServer. * * @exception MBeanException Wraps another exception or persistence is not supported * @exception RuntimeOperationsException Wraps exceptions from the persistence mechanism * @exception InstanceNotFoundException Could not find or load this MBean from persistent * storage */ public void load() throws MBeanException, RuntimeOperationsException, InstanceNotFoundException; /** {@collect.stats} * Captures the current state of this MBean instance and * writes it out to the persistent store. The state stored could include * attribute and operation values. If one of these methods of persistence is * not supported a "serviceNotFound" exception will be thrown. * <P> * Persistence policy from the MBean and attribute descriptor is used to guide execution * of this method. The MBean should be stored if 'persistPolicy' field is: * <PRE> != "never" * = "always" * = "onTimer" and now > 'lastPersistTime' + 'persistPeriod' * = "NoMoreOftenThan" and now > 'lastPersistTime' + 'persistPeriod' * = "onUnregister" * <P> * Do not store the MBean if 'persistPolicy' field is: * = "never" * = "onUpdate" * = "onTimer" && now < 'lastPersistTime' + 'persistPeriod' * <P></PRE> * * @exception MBeanException Wraps another exception or persistence is not supported * @exception RuntimeOperationsException Wraps exceptions from the persistence mechanism * @exception InstanceNotFoundException Could not find/access the persistent store */ public void store() throws MBeanException, RuntimeOperationsException, InstanceNotFoundException; }
Java
/* * Copyright (c) 2002, 2007, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management; import java.io.IOException; import java.io.ObjectInputStream; import java.security.Permission; /** {@collect.stats} * <p>Permission controlling access to MBeanServer operations. If a * security manager has been set using {@link * System#setSecurityManager}, most operations on the MBean Server * require that the caller's permissions imply an MBeanPermission * appropriate for the operation. This is described in detail in the * documentation for the {@link MBeanServer} interface.</p> * * <p>As with other {@link Permission} objects, an MBeanPermission can * represent either a permission that you <em>have</em> or a * permission that you <em>need</em>. When a sensitive operation is * being checked for permission, an MBeanPermission is constructed * representing the permission you need. The operation is only * allowed if the permissions you have {@link #implies imply} the * permission you need.</p> * * <p>An MBeanPermission contains four items of information:</p> * * <ul> * * <li><p>The <em>action</em>. For a permission you need, * this is one of the actions in the list <a * href="#action-list">below</a>. For a permission you have, this is * a comma-separated list of those actions, or <code>*</code>, * representing all actions.</p> * * <p>The action is returned by {@link #getActions()}.</p> * * <li><p>The <em>class name</em>.</p> * * <p>For a permission you need, this is the class name of an MBean * you are accessing, as returned by {@link * MBeanServer#getMBeanInfo(ObjectName) * MBeanServer.getMBeanInfo(name)}.{@link MBeanInfo#getClassName() * getClassName()}. Certain operations do not reference a class name, * in which case the class name is null.</p> * * <p>For a permission you have, this is either empty or a <em>class * name pattern</em>. A class name pattern is a string following the * Java conventions for dot-separated class names. It may end with * "<code>.*</code>" meaning that the permission grants access to any * class that begins with the string preceding "<code>.*</code>". For * instance, "<code>javax.management.*</code>" grants access to * <code>javax.management.MBeanServerDelegate</code> and * <code>javax.management.timer.Timer</code>, among other classes.</p> * * <p>A class name pattern can also be empty or the single character * "<code>*</code>", both of which grant access to any class.</p> * * <li><p>The <em>member</em>.</p> * * <p>For a permission you need, this is the name of the attribute or * operation you are accessing. For operations that do not reference * an attribute or operation, the member is null.</p> * * <p>For a permission you have, this is either the name of an attribute * or operation you can access, or it is empty or the single character * "<code>*</code>", both of which grant access to any member.</p> * * <li><p>The <em>object name</em>.</p> * * <p>For a permission you need, this is the {@link ObjectName} of the * MBean you are accessing. For operations that do not reference a * single MBean, it is null. It is never an object name pattern.</p> * * <p>For a permission you have, this is the {@link ObjectName} of the * MBean or MBeans you can access. It may be an object name pattern * to grant access to all MBeans whose names match the pattern. It * may also be empty, which grants access to all MBeans whatever their * name.</p> * * </ul> * * <p>If you have an MBeanPermission, it allows operations only if all * four of the items match.</p> * * <p>The class name, member, and object name can be written together * as a single string, which is the <em>name</em> of this permission. * The name of the permission is the string returned by {@link * Permission#getName() getName()}. The format of the string is:</p> * * <blockquote> * <code>className#member[objectName]</code> * </blockquote> * * <p>The object name is written using the usual syntax for {@link * ObjectName}. It may contain any legal characters, including * <code>]</code>. It is terminated by a <code>]</code> character * that is the last character in the string.</p> * * <p>One or more of the <code>className</code>, <code>member</code>, * or <code>objectName</code> may be omitted. If the * <code>member</code> is omitted, the <code>#</code> may be too (but * does not have to be). If the <code>objectName</code> is omitted, * the <code>[]</code> may be too (but does not have to be). It is * not legal to omit all three items, that is to have a <em>name</em> * that is the empty string.</p> * * <p>One or more of the <code>className</code>, <code>member</code>, * or <code>objectName</code> may be the character "<code>-</code>", * which is equivalent to a null value. A null value is implied by * any value (including another null value) but does not imply any * other value.</p> * * <p><a name="action-list">The possible actions are these:</a></p> * * <ul> * <li>addNotificationListener</li> * <li>getAttribute</li> * <li>getClassLoader</li> * <li>getClassLoaderFor</li> * <li>getClassLoaderRepository</li> * <li>getDomains</li> * <li>getMBeanInfo</li> * <li>getObjectInstance</li> * <li>instantiate</li> * <li>invoke</li> * <li>isInstanceOf</li> * <li>queryMBeans</li> * <li>queryNames</li> * <li>registerMBean</li> * <li>removeNotificationListener</li> * <li>setAttribute</li> * <li>unregisterMBean</li> * </ul> * * <p>In a comma-separated list of actions, spaces are allowed before * and after each action.</p> * * @since 1.5 */ public class MBeanPermission extends Permission { private static final long serialVersionUID = -2416928705275160661L; /** {@collect.stats} * Actions list. */ private static final int AddNotificationListener = 0x00001; private static final int GetAttribute = 0x00002; private static final int GetClassLoader = 0x00004; private static final int GetClassLoaderFor = 0x00008; private static final int GetClassLoaderRepository = 0x00010; private static final int GetDomains = 0x00020; private static final int GetMBeanInfo = 0x00040; private static final int GetObjectInstance = 0x00080; private static final int Instantiate = 0x00100; private static final int Invoke = 0x00200; private static final int IsInstanceOf = 0x00400; private static final int QueryMBeans = 0x00800; private static final int QueryNames = 0x01000; private static final int RegisterMBean = 0x02000; private static final int RemoveNotificationListener = 0x04000; private static final int SetAttribute = 0x08000; private static final int UnregisterMBean = 0x10000; /** {@collect.stats} * No actions. */ private static final int NONE = 0x00000; /** {@collect.stats} * All actions. */ private static final int ALL = AddNotificationListener | GetAttribute | GetClassLoader | GetClassLoaderFor | GetClassLoaderRepository | GetDomains | GetMBeanInfo | GetObjectInstance | Instantiate | Invoke | IsInstanceOf | QueryMBeans | QueryNames | RegisterMBean | RemoveNotificationListener | SetAttribute | UnregisterMBean; /** {@collect.stats} * The actions string. */ private String actions; /** {@collect.stats} * The actions mask. */ private transient int mask; /** {@collect.stats} * The classname prefix that must match. If null, is implied by any * classNamePrefix but does not imply any non-null classNamePrefix. */ private transient String classNamePrefix; /** {@collect.stats} * True if classNamePrefix must match exactly. Otherwise, the * className being matched must start with classNamePrefix. */ private transient boolean classNameExactMatch; /** {@collect.stats} * The member that must match. If null, is implied by any member * but does not imply any non-null member. */ private transient String member; /** {@collect.stats} * The objectName that must match. If null, is implied by any * objectName but does not imply any non-null objectName. */ private transient ObjectName objectName; /** {@collect.stats} * Parse <code>actions</code> parameter. */ private void parseActions() { int mask; if (actions == null) throw new IllegalArgumentException("MBeanPermission: " + "actions can't be null"); if (actions.equals("")) throw new IllegalArgumentException("MBeanPermission: " + "actions can't be empty"); mask = getMask(actions); if ((mask & ALL) != mask) throw new IllegalArgumentException("Invalid actions mask"); if (mask == NONE) throw new IllegalArgumentException("Invalid actions mask"); this.mask = mask; } /** {@collect.stats} * Parse <code>name</code> parameter. */ private void parseName() { String name = getName(); if (name == null) throw new IllegalArgumentException("MBeanPermission name " + "cannot be null"); if (name.equals("")) throw new IllegalArgumentException("MBeanPermission name " + "cannot be empty"); /* The name looks like "class#member[objectname]". We subtract elements from the right as we parse, so after parsing the objectname we have "class#member" and after parsing the member we have "class". Each element is optional. */ // Parse ObjectName int openingBracket = name.indexOf("["); if (openingBracket == -1) { // If "[on]" missing then ObjectName("*:*") // objectName = ObjectName.WILDCARD; } else { if (!name.endsWith("]")) { throw new IllegalArgumentException("MBeanPermission: " + "The ObjectName in the " + "target name must be " + "included in square " + "brackets"); } else { // Create ObjectName // try { // If "[]" then ObjectName("*:*") // String on = name.substring(openingBracket + 1, name.length() - 1); if (on.equals("")) objectName = ObjectName.WILDCARD; else if (on.equals("-")) objectName = null; else objectName = new ObjectName(on); } catch (MalformedObjectNameException e) { throw new IllegalArgumentException("MBeanPermission: " + "The target name does " + "not specify a valid " + "ObjectName"); } } name = name.substring(0, openingBracket); } // Parse member int poundSign = name.indexOf("#"); if (poundSign == -1) setMember("*"); else { String memberName = name.substring(poundSign + 1); setMember(memberName); name = name.substring(0, poundSign); } // Parse className setClassName(name); } /** {@collect.stats} * Assign fields based on className, member, and objectName * parameters. */ private void initName(String className, String member, ObjectName objectName) { setClassName(className); setMember(member); this.objectName = objectName; } private void setClassName(String className) { if (className == null || className.equals("-")) { classNamePrefix = null; classNameExactMatch = false; } else if (className.equals("") || className.equals("*")) { classNamePrefix = ""; classNameExactMatch = false; } else if (className.endsWith(".*")) { // Note that we include the "." in the required prefix classNamePrefix = className.substring(0, className.length() - 1); classNameExactMatch = false; } else { classNamePrefix = className; classNameExactMatch = true; } } private void setMember(String member) { if (member == null || member.equals("-")) this.member = null; else if (member.equals("")) this.member = "*"; else this.member = member; } /** {@collect.stats} * <p>Create a new MBeanPermission object with the specified target name * and actions.</p> * * <p>The target name is of the form * "<code>className#member[objectName]</code>" where each part is * optional. It must not be empty or null.</p> * * <p>The actions parameter contains a comma-separated list of the * desired actions granted on the target name. It must not be * empty or null.</p> * * @param name the triplet "className#member[objectName]". * @param actions the action string. * * @exception IllegalArgumentException if the <code>name</code> or * <code>actions</code> is invalid. */ public MBeanPermission(String name, String actions) { super(name); parseName(); this.actions = actions; parseActions(); } /** {@collect.stats} * <p>Create a new MBeanPermission object with the specified target name * (class name, member, object name) and actions.</p> * * <p>The class name, member and object name parameters define a * target name of the form * "<code>className#member[objectName]</code>" where each part is * optional. This will be the result of {@link #getName()} on the * resultant MBeanPermission.</p> * * <p>The actions parameter contains a comma-separated list of the * desired actions granted on the target name. It must not be * empty or null.</p> * * @param className the class name to which this permission applies. * May be null or <code>"-"</code>, which represents a class name * that is implied by any class name but does not imply any other * class name. * @param member the member to which this permission applies. May * be null or <code>"-"</code>, which represents a member that is * implied by any member but does not imply any other member. * @param objectName the object name to which this permission * applies. May be null, which represents an object name that is * implied by any object name but does not imply any other object * name. * @param actions the action string. */ public MBeanPermission(String className, String member, ObjectName objectName, String actions) { super(makeName(className, member, objectName)); initName(className, member, objectName); this.actions = actions; parseActions(); } private static String makeName(String className, String member, ObjectName objectName) { final StringBuilder name = new StringBuilder(); if (className == null) className = "-"; name.append(className); if (member == null) member = "-"; name.append("#" + member); if (objectName == null) name.append("[-]"); else name.append("[").append(objectName.getCanonicalName()).append("]"); /* In the interests of legibility for Permission.toString(), we transform the empty string into "*". */ if (name.length() == 0) return "*"; else return name.toString(); } /** {@collect.stats} * Returns the "canonical string representation" of the actions. That is, * this method always returns present actions in alphabetical order. * * @return the canonical string representation of the actions. */ public String getActions() { if (actions == null) actions = getActions(this.mask); return actions; } /** {@collect.stats} * Returns the "canonical string representation" * of the actions from the mask. */ private static String getActions(int mask) { final StringBuilder sb = new StringBuilder(); boolean comma = false; if ((mask & AddNotificationListener) == AddNotificationListener) { comma = true; sb.append("addNotificationListener"); } if ((mask & GetAttribute) == GetAttribute) { if (comma) sb.append(','); else comma = true; sb.append("getAttribute"); } if ((mask & GetClassLoader) == GetClassLoader) { if (comma) sb.append(','); else comma = true; sb.append("getClassLoader"); } if ((mask & GetClassLoaderFor) == GetClassLoaderFor) { if (comma) sb.append(','); else comma = true; sb.append("getClassLoaderFor"); } if ((mask & GetClassLoaderRepository) == GetClassLoaderRepository) { if (comma) sb.append(','); else comma = true; sb.append("getClassLoaderRepository"); } if ((mask & GetDomains) == GetDomains) { if (comma) sb.append(','); else comma = true; sb.append("getDomains"); } if ((mask & GetMBeanInfo) == GetMBeanInfo) { if (comma) sb.append(','); else comma = true; sb.append("getMBeanInfo"); } if ((mask & GetObjectInstance) == GetObjectInstance) { if (comma) sb.append(','); else comma = true; sb.append("getObjectInstance"); } if ((mask & Instantiate) == Instantiate) { if (comma) sb.append(','); else comma = true; sb.append("instantiate"); } if ((mask & Invoke) == Invoke) { if (comma) sb.append(','); else comma = true; sb.append("invoke"); } if ((mask & IsInstanceOf) == IsInstanceOf) { if (comma) sb.append(','); else comma = true; sb.append("isInstanceOf"); } if ((mask & QueryMBeans) == QueryMBeans) { if (comma) sb.append(','); else comma = true; sb.append("queryMBeans"); } if ((mask & QueryNames) == QueryNames) { if (comma) sb.append(','); else comma = true; sb.append("queryNames"); } if ((mask & RegisterMBean) == RegisterMBean) { if (comma) sb.append(','); else comma = true; sb.append("registerMBean"); } if ((mask & RemoveNotificationListener) == RemoveNotificationListener) { if (comma) sb.append(','); else comma = true; sb.append("removeNotificationListener"); } if ((mask & SetAttribute) == SetAttribute) { if (comma) sb.append(','); else comma = true; sb.append("setAttribute"); } if ((mask & UnregisterMBean) == UnregisterMBean) { if (comma) sb.append(','); else comma = true; sb.append("unregisterMBean"); } return sb.toString(); } /** {@collect.stats} * Returns the hash code value for this object. * * @return a hash code value for this object. */ public int hashCode() { return this.getName().hashCode() + this.getActions().hashCode(); } /** {@collect.stats} * Converts an action String to an integer action mask. * * @param action the action string. * @return the action mask. */ private static int getMask(String action) { /* * BE CAREFUL HERE! PARSING ORDER IS IMPORTANT IN THIS ALGORITHM. * * The 'string length' test must be performed for the lengthiest * strings first. * * In this permission if the "unregisterMBean" string length test is * performed after the "registerMBean" string length test the algorithm * considers the 'unregisterMBean' action as being the 'registerMBean' * action and a parsing error is returned. */ int mask = NONE; if (action == null) { return mask; } if (action.equals("*")) { return ALL; } char[] a = action.toCharArray(); int i = a.length - 1; if (i < 0) return mask; while (i != -1) { char c; // skip whitespace while ((i!=-1) && ((c = a[i]) == ' ' || c == '\r' || c == '\n' || c == '\f' || c == '\t')) i--; // check for the known strings int matchlen; if (i >= 25 && /* removeNotificationListener */ (a[i-25] == 'r') && (a[i-24] == 'e') && (a[i-23] == 'm') && (a[i-22] == 'o') && (a[i-21] == 'v') && (a[i-20] == 'e') && (a[i-19] == 'N') && (a[i-18] == 'o') && (a[i-17] == 't') && (a[i-16] == 'i') && (a[i-15] == 'f') && (a[i-14] == 'i') && (a[i-13] == 'c') && (a[i-12] == 'a') && (a[i-11] == 't') && (a[i-10] == 'i') && (a[i-9] == 'o') && (a[i-8] == 'n') && (a[i-7] == 'L') && (a[i-6] == 'i') && (a[i-5] == 's') && (a[i-4] == 't') && (a[i-3] == 'e') && (a[i-2] == 'n') && (a[i-1] == 'e') && (a[i] == 'r')) { matchlen = 26; mask |= RemoveNotificationListener; } else if (i >= 23 && /* getClassLoaderRepository */ (a[i-23] == 'g') && (a[i-22] == 'e') && (a[i-21] == 't') && (a[i-20] == 'C') && (a[i-19] == 'l') && (a[i-18] == 'a') && (a[i-17] == 's') && (a[i-16] == 's') && (a[i-15] == 'L') && (a[i-14] == 'o') && (a[i-13] == 'a') && (a[i-12] == 'd') && (a[i-11] == 'e') && (a[i-10] == 'r') && (a[i-9] == 'R') && (a[i-8] == 'e') && (a[i-7] == 'p') && (a[i-6] == 'o') && (a[i-5] == 's') && (a[i-4] == 'i') && (a[i-3] == 't') && (a[i-2] == 'o') && (a[i-1] == 'r') && (a[i] == 'y')) { matchlen = 24; mask |= GetClassLoaderRepository; } else if (i >= 22 && /* addNotificationListener */ (a[i-22] == 'a') && (a[i-21] == 'd') && (a[i-20] == 'd') && (a[i-19] == 'N') && (a[i-18] == 'o') && (a[i-17] == 't') && (a[i-16] == 'i') && (a[i-15] == 'f') && (a[i-14] == 'i') && (a[i-13] == 'c') && (a[i-12] == 'a') && (a[i-11] == 't') && (a[i-10] == 'i') && (a[i-9] == 'o') && (a[i-8] == 'n') && (a[i-7] == 'L') && (a[i-6] == 'i') && (a[i-5] == 's') && (a[i-4] == 't') && (a[i-3] == 'e') && (a[i-2] == 'n') && (a[i-1] == 'e') && (a[i] == 'r')) { matchlen = 23; mask |= AddNotificationListener; } else if (i >= 16 && /* getClassLoaderFor */ (a[i-16] == 'g') && (a[i-15] == 'e') && (a[i-14] == 't') && (a[i-13] == 'C') && (a[i-12] == 'l') && (a[i-11] == 'a') && (a[i-10] == 's') && (a[i-9] == 's') && (a[i-8] == 'L') && (a[i-7] == 'o') && (a[i-6] == 'a') && (a[i-5] == 'd') && (a[i-4] == 'e') && (a[i-3] == 'r') && (a[i-2] == 'F') && (a[i-1] == 'o') && (a[i] == 'r')) { matchlen = 17; mask |= GetClassLoaderFor; } else if (i >= 16 && /* getObjectInstance */ (a[i-16] == 'g') && (a[i-15] == 'e') && (a[i-14] == 't') && (a[i-13] == 'O') && (a[i-12] == 'b') && (a[i-11] == 'j') && (a[i-10] == 'e') && (a[i-9] == 'c') && (a[i-8] == 't') && (a[i-7] == 'I') && (a[i-6] == 'n') && (a[i-5] == 's') && (a[i-4] == 't') && (a[i-3] == 'a') && (a[i-2] == 'n') && (a[i-1] == 'c') && (a[i] == 'e')) { matchlen = 17; mask |= GetObjectInstance; } else if (i >= 14 && /* unregisterMBean */ (a[i-14] == 'u') && (a[i-13] == 'n') && (a[i-12] == 'r') && (a[i-11] == 'e') && (a[i-10] == 'g') && (a[i-9] == 'i') && (a[i-8] == 's') && (a[i-7] == 't') && (a[i-6] == 'e') && (a[i-5] == 'r') && (a[i-4] == 'M') && (a[i-3] == 'B') && (a[i-2] == 'e') && (a[i-1] == 'a') && (a[i] == 'n')) { matchlen = 15; mask |= UnregisterMBean; } else if (i >= 13 && /* getClassLoader */ (a[i-13] == 'g') && (a[i-12] == 'e') && (a[i-11] == 't') && (a[i-10] == 'C') && (a[i-9] == 'l') && (a[i-8] == 'a') && (a[i-7] == 's') && (a[i-6] == 's') && (a[i-5] == 'L') && (a[i-4] == 'o') && (a[i-3] == 'a') && (a[i-2] == 'd') && (a[i-1] == 'e') && (a[i] == 'r')) { matchlen = 14; mask |= GetClassLoader; } else if (i >= 12 && /* registerMBean */ (a[i-12] == 'r') && (a[i-11] == 'e') && (a[i-10] == 'g') && (a[i-9] == 'i') && (a[i-8] == 's') && (a[i-7] == 't') && (a[i-6] == 'e') && (a[i-5] == 'r') && (a[i-4] == 'M') && (a[i-3] == 'B') && (a[i-2] == 'e') && (a[i-1] == 'a') && (a[i] == 'n')) { matchlen = 13; mask |= RegisterMBean; } else if (i >= 11 && /* getAttribute */ (a[i-11] == 'g') && (a[i-10] == 'e') && (a[i-9] == 't') && (a[i-8] == 'A') && (a[i-7] == 't') && (a[i-6] == 't') && (a[i-5] == 'r') && (a[i-4] == 'i') && (a[i-3] == 'b') && (a[i-2] == 'u') && (a[i-1] == 't') && (a[i] == 'e')) { matchlen = 12; mask |= GetAttribute; } else if (i >= 11 && /* getMBeanInfo */ (a[i-11] == 'g') && (a[i-10] == 'e') && (a[i-9] == 't') && (a[i-8] == 'M') && (a[i-7] == 'B') && (a[i-6] == 'e') && (a[i-5] == 'a') && (a[i-4] == 'n') && (a[i-3] == 'I') && (a[i-2] == 'n') && (a[i-1] == 'f') && (a[i] == 'o')) { matchlen = 12; mask |= GetMBeanInfo; } else if (i >= 11 && /* isInstanceOf */ (a[i-11] == 'i') && (a[i-10] == 's') && (a[i-9] == 'I') && (a[i-8] == 'n') && (a[i-7] == 's') && (a[i-6] == 't') && (a[i-5] == 'a') && (a[i-4] == 'n') && (a[i-3] == 'c') && (a[i-2] == 'e') && (a[i-1] == 'O') && (a[i] == 'f')) { matchlen = 12; mask |= IsInstanceOf; } else if (i >= 11 && /* setAttribute */ (a[i-11] == 's') && (a[i-10] == 'e') && (a[i-9] == 't') && (a[i-8] == 'A') && (a[i-7] == 't') && (a[i-6] == 't') && (a[i-5] == 'r') && (a[i-4] == 'i') && (a[i-3] == 'b') && (a[i-2] == 'u') && (a[i-1] == 't') && (a[i] == 'e')) { matchlen = 12; mask |= SetAttribute; } else if (i >= 10 && /* instantiate */ (a[i-10] == 'i') && (a[i-9] == 'n') && (a[i-8] == 's') && (a[i-7] == 't') && (a[i-6] == 'a') && (a[i-5] == 'n') && (a[i-4] == 't') && (a[i-3] == 'i') && (a[i-2] == 'a') && (a[i-1] == 't') && (a[i] == 'e')) { matchlen = 11; mask |= Instantiate; } else if (i >= 10 && /* queryMBeans */ (a[i-10] == 'q') && (a[i-9] == 'u') && (a[i-8] == 'e') && (a[i-7] == 'r') && (a[i-6] == 'y') && (a[i-5] == 'M') && (a[i-4] == 'B') && (a[i-3] == 'e') && (a[i-2] == 'a') && (a[i-1] == 'n') && (a[i] == 's')) { matchlen = 11; mask |= QueryMBeans; } else if (i >= 9 && /* getDomains */ (a[i-9] == 'g') && (a[i-8] == 'e') && (a[i-7] == 't') && (a[i-6] == 'D') && (a[i-5] == 'o') && (a[i-4] == 'm') && (a[i-3] == 'a') && (a[i-2] == 'i') && (a[i-1] == 'n') && (a[i] == 's')) { matchlen = 10; mask |= GetDomains; } else if (i >= 9 && /* queryNames */ (a[i-9] == 'q') && (a[i-8] == 'u') && (a[i-7] == 'e') && (a[i-6] == 'r') && (a[i-5] == 'y') && (a[i-4] == 'N') && (a[i-3] == 'a') && (a[i-2] == 'm') && (a[i-1] == 'e') && (a[i] == 's')) { matchlen = 10; mask |= QueryNames; } else if (i >= 5 && /* invoke */ (a[i-5] == 'i') && (a[i-4] == 'n') && (a[i-3] == 'v') && (a[i-2] == 'o') && (a[i-1] == 'k') && (a[i] == 'e')) { matchlen = 6; mask |= Invoke; } else { // parse error throw new IllegalArgumentException("Invalid permission: " + action); } // make sure we didn't just match the tail of a word // like "ackbarfaccept". Also, skip to the comma. boolean seencomma = false; while (i >= matchlen && !seencomma) { switch(a[i-matchlen]) { case ',': seencomma = true; break; case ' ': case '\r': case '\n': case '\f': case '\t': break; default: throw new IllegalArgumentException("Invalid permission: " + action); } i--; } // point i at the location of the comma minus one (or -1). i -= matchlen; } return mask; } /** {@collect.stats} * <p>Checks if this MBeanPermission object "implies" the * specified permission.</p> * * <p>More specifically, this method returns true if:</p> * * <ul> * * <li> <i>p</i> is an instance of MBeanPermission; and</li> * * <li> <i>p</i> has a null className or <i>p</i>'s className * matches this object's className; and</li> * * <li> <i>p</i> has a null member or <i>p</i>'s member matches this * object's member; and</li> * * <li> <i>p</i> has a null object name or <i>p</i>'s * object name matches this object's object name; and</li> * * <li> <i>p</i>'s actions are a subset of this object's actions</li> * * </ul> * * <p>If this object's className is "<code>*</code>", <i>p</i>'s * className always matches it. If it is "<code>a.*</code>", <i>p</i>'s * className matches it if it begins with "<code>a.</code>".</p> * * <p>If this object's member is "<code>*</code>", <i>p</i>'s * member always matches it.</p> * * <p>If this object's objectName <i>n1</i> is an object name pattern, * <i>p</i>'s objectName <i>n2</i> matches it if * {@link ObjectName#equals <i>n1</i>.equals(<i>n2</i>)} or if * {@link ObjectName#apply <i>n1</i>.apply(<i>n2</i>)}.</p> * * <p>A permission that includes the <code>queryMBeans</code> action * is considered to include <code>queryNames</code> as well.</p> * * @param p the permission to check against. * @return true if the specified permission is implied by this object, * false if not. */ public boolean implies(Permission p) { if (!(p instanceof MBeanPermission)) return false; MBeanPermission that = (MBeanPermission) p; // Actions // // The actions in 'this' permission must be a // superset of the actions in 'that' permission // /* "queryMBeans" implies "queryNames" */ if ((this.mask & QueryMBeans) == QueryMBeans) { if (((this.mask | QueryNames) & that.mask) != that.mask) { //System.out.println("action [with QueryNames] does not imply"); return false; } } else { if ((this.mask & that.mask) != that.mask) { //System.out.println("action does not imply"); return false; } } // Target name // // The 'className' check is true iff: // 1) the className in 'this' permission is omitted or "*", or // 2) the className in 'that' permission is omitted or "*", or // 3) the className in 'this' permission does pattern // matching with the className in 'that' permission. // // The 'member' check is true iff: // 1) the member in 'this' permission is omitted or "*", or // 2) the member in 'that' permission is omitted or "*", or // 3) the member in 'this' permission equals the member in // 'that' permission. // // The 'object name' check is true iff: // 1) the object name in 'this' permission is omitted or "*:*", or // 2) the object name in 'that' permission is omitted or "*:*", or // 3) the object name in 'this' permission does pattern // matching with the object name in 'that' permission. // /* Check if this.className implies that.className. If that.classNamePrefix is empty that means the className is irrelevant for this permission check. Otherwise, we do not expect that "that" contains a wildcard, since it is a needed permission. So we assume that.classNameExactMatch. */ if (that.classNamePrefix == null) { // bottom is implied } else if (this.classNamePrefix == null) { // bottom implies nothing but itself return false; } else if (this.classNameExactMatch) { if (!that.classNameExactMatch) return false; // exact never implies wildcard if (!that.classNamePrefix.equals(this.classNamePrefix)) return false; // exact match fails } else { // prefix match, works even if "that" is also a wildcard // e.g. a.* implies a.* and a.b.* if (!that.classNamePrefix.startsWith(this.classNamePrefix)) return false; } /* Check if this.member implies that.member */ if (that.member == null) { // bottom is implied } else if (this.member == null) { // bottom implies nothing but itself return false; } else if (this.member.equals("*")) { // wildcard implies everything (including itself) } else if (!this.member.equals(that.member)) { return false; } /* Check if this.objectName implies that.objectName */ if (that.objectName == null) { // bottom is implied } else if (this.objectName == null) { // bottom implies nothing but itself return false; } else if (!this.objectName.apply(that.objectName)) { /* ObjectName.apply returns false if that.objectName is a wildcard so we also allow equals for that case. This never happens during real permission checks, but means the implies relation is reflexive. */ if (!this.objectName.equals(that.objectName)) return false; } return true; } /** {@collect.stats} * Checks two MBeanPermission objects for equality. Checks * that <i>obj</i> is an MBeanPermission, and has the same * name and actions as this object. * <P> * @param obj the object we are testing for equality with this object. * @return true if obj is an MBeanPermission, and has the * same name and actions as this MBeanPermission object. */ public boolean equals(Object obj) { if (obj == this) return true; if (! (obj instanceof MBeanPermission)) return false; MBeanPermission that = (MBeanPermission) obj; return (this.mask == that.mask) && (this.getName().equals(that.getName())); } /** {@collect.stats} * Deserialize this object based on its name and actions. */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); parseName(); parseActions(); } }
Java
/* * Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management; /** {@collect.stats} * Provides definitions of the attribute change notifications sent by MBeans. * <P> * It's up to the MBean owning the attribute of interest to create and send * attribute change notifications when the attribute change occurs. * So the <CODE>NotificationBroadcaster</CODE> interface has to be implemented * by any MBean for which an attribute change is of interest. * <P> * Example: * If an MBean called <CODE>myMbean</CODE> needs to notify registered listeners * when its attribute: * <BLOCKQUOTE><CODE> * String myString * </CODE></BLOCKQUOTE> * is modified, <CODE>myMbean</CODE> creates and emits the following notification: * <BLOCKQUOTE><CODE> * new AttributeChangeNotification(myMbean, sequenceNumber, timeStamp, msg, * "myString", "String", oldValue, newValue); * </CODE></BLOCKQUOTE> * * @since 1.5 */ public class AttributeChangeNotification extends javax.management.Notification { /* Serial version */ private static final long serialVersionUID = 535176054565814134L; /** {@collect.stats} * Notification type which indicates that the observed MBean attribute value has changed. * <BR>The value of this type string is <CODE>jmx.attribute.change</CODE>. */ public static final String ATTRIBUTE_CHANGE = "jmx.attribute.change"; /** {@collect.stats} * @serial The MBean attribute name. */ private String attributeName = null; /** {@collect.stats} * @serial The MBean attribute type. */ private String attributeType = null; /** {@collect.stats} * @serial The MBean attribute old value. */ private Object oldValue = null; /** {@collect.stats} * @serial The MBean attribute new value. */ private Object newValue = null; /** {@collect.stats} * Constructs an attribute change notification object. * In addition to the information common to all notification, the caller must supply the name and type * of the attribute, as well as its old and new values. * * @param source The notification producer, that is, the MBean the attribute belongs to. * @param sequenceNumber The notification sequence number within the source object. * @param timeStamp The date at which the notification is being sent. * @param msg A String containing the message of the notification. * @param attributeName A String giving the name of the attribute. * @param attributeType A String containing the type of the attribute. * @param oldValue An object representing value of the attribute before the change. * @param newValue An object representing value of the attribute after the change. */ public AttributeChangeNotification(Object source, long sequenceNumber, long timeStamp, String msg, String attributeName, String attributeType, Object oldValue, Object newValue) { super(AttributeChangeNotification.ATTRIBUTE_CHANGE, source, sequenceNumber, timeStamp, msg); this.attributeName = attributeName; this.attributeType = attributeType; this.oldValue = oldValue; this.newValue = newValue; } /** {@collect.stats} * Gets the name of the attribute which has changed. * * @return A String containing the name of the attribute. */ public String getAttributeName() { return attributeName; } /** {@collect.stats} * Gets the type of the attribute which has changed. * * @return A String containing the type of the attribute. */ public String getAttributeType() { return attributeType; } /** {@collect.stats} * Gets the old value of the attribute which has changed. * * @return An Object containing the old value of the attribute. */ public Object getOldValue() { return oldValue; } /** {@collect.stats} * Gets the new value of the attribute which has changed. * * @return An Object containing the new value of the attribute. */ public Object getNewValue() { return newValue; } }
Java
/* * Copyright (c) 1999, 2006, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management; import java.util.List; import java.util.Vector; /** {@collect.stats} * Provides an implementation of the {@link javax.management.NotificationFilter} interface. * The filtering is performed on the notification type attribute. * <P> * Manages a list of enabled notification types. * A method allows users to enable/disable as many notification types as required. * <P> * Then, before sending a notification to a listener registered with a filter, * the notification broadcaster compares this notification type with all notification types * enabled by the filter. The notification will be sent to the listener * only if its filter enables this notification type. * <P> * Example: * <BLOCKQUOTE> * <PRE> * NotificationFilterSupport myFilter = new NotificationFilterSupport(); * myFilter.enableType("my_example.my_type"); * myBroadcaster.addListener(myListener, myFilter, null); * </PRE> * </BLOCKQUOTE> * The listener <CODE>myListener</CODE> will only receive notifications the type of which equals/starts with "my_example.my_type". * * @see javax.management.NotificationBroadcaster#addNotificationListener * * @since 1.5 */ public class NotificationFilterSupport implements NotificationFilter { /* Serial version */ private static final long serialVersionUID = 6579080007561786969L; /** {@collect.stats} * @serial {@link Vector} that contains the enabled notification types. * The default value is an empty vector. */ private List<String> enabledTypes = new Vector<String>(); /** {@collect.stats} * Invoked before sending the specified notification to the listener. * <BR>This filter compares the type of the specified notification with each enabled type. * If the notification type matches one of the enabled types, * the notification should be sent to the listener and this method returns <CODE>true</CODE>. * * @param notification The notification to be sent. * @return <CODE>true</CODE> if the notification should be sent to the listener, <CODE>false</CODE> otherwise. */ public synchronized boolean isNotificationEnabled(Notification notification) { String type = notification.getType(); if (type == null) { return false; } try { for (String prefix : enabledTypes) { if (type.startsWith(prefix)) { return true; } } } catch (java.lang.NullPointerException e) { // Should never occurs... return false; } return false; } /** {@collect.stats} * Enables all the notifications the type of which starts with the specified prefix * to be sent to the listener. * <BR>If the specified prefix is already in the list of enabled notification types, * this method has no effect. * <P> * Example: * <BLOCKQUOTE> * <PRE> * // Enables all notifications the type of which starts with "my_example" to be sent. * myFilter.enableType("my_example"); * // Enables all notifications the type of which is "my_example.my_type" to be sent. * myFilter.enableType("my_example.my_type"); * </PRE> * </BLOCKQUOTE> * * Note that: * <BLOCKQUOTE><CODE> * myFilter.enableType("my_example.*"); * </CODE></BLOCKQUOTE> * will no match any notification type. * * @param prefix The prefix. * @exception java.lang.IllegalArgumentException The prefix parameter is null. */ public synchronized void enableType(String prefix) throws IllegalArgumentException { if (prefix == null) { throw new IllegalArgumentException("The prefix cannot be null."); } if (!enabledTypes.contains(prefix)) { enabledTypes.add(prefix); } } /** {@collect.stats} * Removes the given prefix from the prefix list. * <BR>If the specified prefix is not in the list of enabled notification types, * this method has no effect. * * @param prefix The prefix. */ public synchronized void disableType(String prefix) { enabledTypes.remove(prefix); } /** {@collect.stats} * Disables all notification types. */ public synchronized void disableAllTypes() { enabledTypes.clear(); } /** {@collect.stats} * Gets all the enabled notification types for this filter. * * @return The list containing all the enabled notification types. */ public synchronized Vector<String> getEnabledTypes() { return (Vector<String>)enabledTypes; } }
Java
/* * Copyright (c) 1999, 2006, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.ObjectStreamField; import java.util.EventObject; import java.security.AccessController; import com.sun.jmx.mbeanserver.GetPropertyAction; /** {@collect.stats} * <p>The Notification class represents a notification emitted by an * MBean. It contains a reference to the source MBean: if the * notification has been forwarded through the MBean server, and the * original source of the notification was a reference to the emitting * MBean object, then the MBean server replaces it by the MBean's * ObjectName. If the listener has registered directly with the * MBean, this is either the object name or a direct reference to the * MBean.</p> * * <p>It is strongly recommended that notification senders use the * object name rather than a reference to the MBean object as the * source.</p> * * <p>The <b>serialVersionUID</b> of this class is <code>-7516092053498031989L</code>. * * @since 1.5 */ @SuppressWarnings("serial") // serialVersionUID is not constant public class Notification extends EventObject { // Serialization compatibility stuff: // Two serial forms are supported in this class. The selected form depends // on system property "jmx.serial.form": // - "1.0" for JMX 1.0 // - any other value for JMX 1.1 and higher // // Serial version for old serial form private static final long oldSerialVersionUID = 1716977971058914352L; // // Serial version for new serial form private static final long newSerialVersionUID = -7516092053498031989L; // // Serializable fields in old serial form private static final ObjectStreamField[] oldSerialPersistentFields = { new ObjectStreamField("message", String.class), new ObjectStreamField("sequenceNumber", Long.TYPE), new ObjectStreamField("source", Object.class), new ObjectStreamField("sourceObjectName", ObjectName.class), new ObjectStreamField("timeStamp", Long.TYPE), new ObjectStreamField("type", String.class), new ObjectStreamField("userData", Object.class) }; // // Serializable fields in new serial form private static final ObjectStreamField[] newSerialPersistentFields = { new ObjectStreamField("message", String.class), new ObjectStreamField("sequenceNumber", Long.TYPE), new ObjectStreamField("source", Object.class), new ObjectStreamField("timeStamp", Long.TYPE), new ObjectStreamField("type", String.class), new ObjectStreamField("userData", Object.class) }; // // Actual serial version and serial form private static final long serialVersionUID; /** {@collect.stats} * @serialField type String The notification type. * A string expressed in a dot notation similar to Java properties. * An example of a notification type is network.alarm.router * @serialField sequenceNumber long The notification sequence number. * A serial number which identify particular instance * of notification in the context of the notification source. * @serialField timeStamp long The notification timestamp. * Indicating when the notification was generated * @serialField userData Object The notification user data. * Used for whatever other data the notification * source wishes to communicate to its consumers * @serialField message String The notification message. * @serialField source Object The object on which the notification initially occurred. */ private static final ObjectStreamField[] serialPersistentFields; private static boolean compat = false; static { try { GetPropertyAction act = new GetPropertyAction("jmx.serial.form"); String form = AccessController.doPrivileged(act); compat = (form != null && form.equals("1.0")); } catch (Exception e) { // OK: exception means no compat with 1.0, too bad } if (compat) { serialPersistentFields = oldSerialPersistentFields; serialVersionUID = oldSerialVersionUID; } else { serialPersistentFields = newSerialPersistentFields; serialVersionUID = newSerialVersionUID; } } // // END Serialization compatibility stuff /** {@collect.stats} * @serial The notification type. * A string expressed in a dot notation similar to Java properties. * An example of a notification type is network.alarm.router */ private String type; /** {@collect.stats} * @serial The notification sequence number. * A serial number which identify particular instance * of notification in the context of the notification source. */ private long sequenceNumber; /** {@collect.stats} * @serial The notification timestamp. * Indicating when the notification was generated */ private long timeStamp; /** {@collect.stats} * @serial The notification user data. * Used for whatever other data the notification * source wishes to communicate to its consumers */ private Object userData = null; /** {@collect.stats} * @serial The notification message. */ private String message = ""; /** {@collect.stats} * <p>This field hides the {@link EventObject#source} field in the * parent class to make it non-transient and therefore part of the * serialized form.</p> * * @serial The object on which the notification initially occurred. */ protected Object source = null; /** {@collect.stats} * Creates a Notification object. * The notification timeStamp is set to the current date. * * @param type The notification type. * @param source The notification source. * @param sequenceNumber The notification sequence number within the source object. * */ public Notification(String type, Object source, long sequenceNumber) { super (source) ; this.source = source; this.type = type; this.sequenceNumber = sequenceNumber ; this.timeStamp = (new java.util.Date()).getTime() ; } /** {@collect.stats} * Creates a Notification object. * The notification timeStamp is set to the current date. * * @param type The notification type. * @param source The notification source. * @param sequenceNumber The notification sequence number within the source object. * @param message The detailed message. * */ public Notification(String type, Object source, long sequenceNumber, String message) { super (source) ; this.source = source; this.type = type; this.sequenceNumber = sequenceNumber ; this.timeStamp = (new java.util.Date()).getTime() ; this.message = message ; } /** {@collect.stats} * Creates a Notification object. * * @param type The notification type. * @param source The notification source. * @param sequenceNumber The notification sequence number within the source object. * @param timeStamp The notification emission date. * */ public Notification(String type, Object source, long sequenceNumber, long timeStamp) { super (source) ; this.source = source; this.type = type ; this.sequenceNumber = sequenceNumber ; this.timeStamp = timeStamp ; } /** {@collect.stats} * Creates a Notification object. * * @param type The notification type. * @param source The notification source. * @param sequenceNumber The notification sequence number within the source object. * @param timeStamp The notification emission date. * @param message The detailed message. * */ public Notification(String type, Object source, long sequenceNumber, long timeStamp, String message) { super (source) ; this.source = source; this.type = type ; this.sequenceNumber = sequenceNumber ; this.timeStamp = timeStamp ; this.message = message ; } /** {@collect.stats} * Sets the source. * * @param source the new source for this object. * * @see EventObject#getSource */ public void setSource(Object source) { super.source = source; this.source = source; } /** {@collect.stats} * Get the notification sequence number. * * @return The notification sequence number within the source object. It's a serial number * identifying a particular instance of notification in the context of the notification source. * The notification model does not assume that notifications will be received in the same order * that they are sent. The sequence number helps listeners to sort received notifications. * * @see #setSequenceNumber */ public long getSequenceNumber() { return sequenceNumber ; } /** {@collect.stats} * Set the notification sequence number. * * @param sequenceNumber The notification sequence number within the source object. It is * a serial number identifying a particular instance of notification in the * context of the notification source. * * @see #getSequenceNumber */ public void setSequenceNumber(long sequenceNumber) { this.sequenceNumber = sequenceNumber; } /** {@collect.stats} * Get the notification type. * * @return The notification type. It's a string expressed in a dot notation similar * to Java properties. An example of a notification type is network.alarm.router . */ public String getType() { return type ; } /** {@collect.stats} * Get the notification timestamp. * * @return The notification timestamp. * * @see #setTimeStamp */ public long getTimeStamp() { return timeStamp ; } /** {@collect.stats} * Set the notification timestamp. * * @param timeStamp The notification timestamp. It indicates when the notification was generated. * * @see #getTimeStamp */ public void setTimeStamp(long timeStamp) { this.timeStamp = timeStamp; } /** {@collect.stats} * Get the notification message. * * @return The message string of this notification object. It contains in a string, * which could be the explanation of the notification for displaying to a user * */ public String getMessage() { return message ; } /** {@collect.stats} * Get the user data. * * @return The user data object. It is used for whatever data * the notification source wishes to communicate to its consumers. * * @see #setUserData */ public Object getUserData() { return userData ; } /** {@collect.stats} * Set the user data. * * @param userData The user data object. It is used for whatever data * the notification source wishes to communicate to its consumers. * * @see #getUserData */ public void setUserData(Object userData) { this.userData = userData ; } /** {@collect.stats} * Returns a String representation of this notification. * * @return A String representation of this notification. */ public String toString() { return super.toString()+"[type="+type+"][message="+message+"]"; } /** {@collect.stats} * Deserializes a {@link Notification} from an {@link ObjectInputStream}. */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { // New serial form ignores extra field "sourceObjectName" in.defaultReadObject(); super.source = source; } /** {@collect.stats} * Serializes a {@link Notification} to an {@link ObjectOutputStream}. */ private void writeObject(ObjectOutputStream out) throws IOException { if (compat) { // Serializes this instance in the old serial form // ObjectOutputStream.PutField fields = out.putFields(); fields.put("type", type); fields.put("sequenceNumber", sequenceNumber); fields.put("timeStamp", timeStamp); fields.put("userData", userData); fields.put("message", message); fields.put("source", source); out.writeFields(); } else { // Serializes this instance in the new serial form // out.defaultWriteObject(); } } }
Java
/* * Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management; /** {@collect.stats} * This class is used by the query-building mechanism to represent negations * of relational expressions. * @serial include * * @since 1.5 */ class NotQueryExp extends QueryEval implements QueryExp { /* Serial version */ private static final long serialVersionUID = 5269643775896723397L; /** {@collect.stats} * @serial The negated {@link QueryExp} */ private QueryExp exp; /** {@collect.stats} * Basic Constructor. */ public NotQueryExp() { } /** {@collect.stats} * Creates a new NotQueryExp for negating the specified QueryExp. */ public NotQueryExp(QueryExp q) { exp = q; } /** {@collect.stats} * Returns the negated query expression of the query. */ public QueryExp getNegatedExp() { return exp; } /** {@collect.stats} * Applies the NotQueryExp on a MBean. * * @param name The name of the MBean on which the NotQueryExp will be applied. * * @return True if the query was successfully applied to the MBean, false otherwise. * * @exception BadStringOperationException * @exception BadBinaryOpValueExpException * @exception BadAttributeValueExpException * @exception InvalidApplicationException */ public boolean apply(ObjectName name) throws BadStringOperationException, BadBinaryOpValueExpException, BadAttributeValueExpException, InvalidApplicationException { return exp.apply(name) == false; } /** {@collect.stats} * Returns the string representing the object. */ public String toString() { return "not (" + exp + ")"; } }
Java
/* * Copyright (c) 2000, 2004, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ /* * @author IBM Corp. * * Copyright IBM Corp. 1999-2000. All rights reserved. */ package javax.management; /** {@collect.stats} * This interface is used to gain access to descriptors of the Descriptor class * which are associated with a JMX component, i.e. MBean, MBeanInfo, * MBeanAttributeInfo, MBeanNotificationInfo, * MBeanOperationInfo, MBeanParameterInfo. * <P> * ModelMBeans make extensive use of this interface in ModelMBeanInfo classes. * * @since 1.5 */ public interface DescriptorAccess extends DescriptorRead { /** {@collect.stats} * Sets Descriptor (full replace). * * @param inDescriptor replaces the Descriptor associated with the * component implementing this interface. If the inDescriptor is invalid for the * type of Info object it is being set for, an exception is thrown. If the * inDescriptor is null, then the Descriptor will revert to its default value * which should contain, at a minimum, the descriptor name and descriptorType. * * @see #getDescriptor */ public void setDescriptor(Descriptor inDescriptor); }
Java
/* * Copyright (c) 1999, 2005, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management; /** {@collect.stats} * Represents strings that are arguments to relational constraints. * A <CODE>StringValueExp</CODE> may be used anywhere a <CODE>ValueExp</CODE> is required. * * @since 1.5 */ public class StringValueExp implements ValueExp { /* Serial version */ private static final long serialVersionUID = -3256390509806284044L; /** {@collect.stats} * @serial The string literal */ private String val; /** {@collect.stats} * Basic constructor. */ public StringValueExp() { } /** {@collect.stats} * Creates a new <CODE>StringValueExp</CODE> representing the * given string. * * @param val the string that will be the value of this expression */ public StringValueExp(String val) { this.val = val; } /** {@collect.stats} * Returns the string represented by the * <CODE>StringValueExp</CODE> instance. * * @return the string. */ public String getValue() { return val; } /** {@collect.stats} * Returns the string representing the object. */ public String toString() { return "'" + val + "'"; } /** {@collect.stats} * Sets the MBean server on which the query is to be performed. * * @param s The MBean server on which the query is to be performed. */ /* There is no need for this method, because if a query is being evaluated a StringValueExp can only appear inside a QueryExp, and that QueryExp will itself have done setMBeanServer. */ public void setMBeanServer(MBeanServer s) { } /** {@collect.stats} * Applies the ValueExp on a MBean. * * @param name The name of the MBean on which the ValueExp will be applied. * * @return The <CODE>ValueExp</CODE>. * * @exception BadStringOperationException * @exception BadBinaryOpValueExpException * @exception BadAttributeValueExpException * @exception InvalidApplicationException */ public ValueExp apply(ObjectName name) throws BadStringOperationException, BadBinaryOpValueExpException, BadAttributeValueExpException, InvalidApplicationException { return this; } }
Java
/* * Copyright (c) 1999, 2006, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management; import java.lang.reflect.Method; import java.security.AccessController; import com.sun.jmx.mbeanserver.GetPropertyAction; import com.sun.jmx.mbeanserver.Introspector; /** {@collect.stats} * Describes an MBean attribute exposed for management. Instances of * this class are immutable. Subclasses may be mutable but this is * not recommended. * * @since 1.5 */ @SuppressWarnings("serial") // serialVersionUID not constant public class MBeanAttributeInfo extends MBeanFeatureInfo implements Cloneable { /* Serial version */ private static final long serialVersionUID; static { /* For complicated reasons, the serialVersionUID changed between JMX 1.0 and JMX 1.1, even though JMX 1.1 did not have compatibility code for this class. So the serialization produced by this class with JMX 1.2 and jmx.serial.form=1.0 is not the same as that produced by this class with JMX 1.1 and jmx.serial.form=1.0. However, the serialization without that property is the same, and that is the only form required by JMX 1.2. */ long uid = 8644704819898565848L; try { GetPropertyAction act = new GetPropertyAction("jmx.serial.form"); String form = AccessController.doPrivileged(act); if ("1.0".equals(form)) uid = 7043855487133450673L; } catch (Exception e) { // OK: exception means no compat with 1.0, too bad } serialVersionUID = uid; } static final MBeanAttributeInfo[] NO_ATTRIBUTES = new MBeanAttributeInfo[0]; /** {@collect.stats} * @serial The actual attribute type. */ private final String attributeType; /** {@collect.stats} * @serial The attribute write right. */ private final boolean isWrite; /** {@collect.stats} * @serial The attribute read right. */ private final boolean isRead; /** {@collect.stats} * @serial Indicates if this method is a "is" */ private final boolean is; /** {@collect.stats} * Constructs an <CODE>MBeanAttributeInfo</CODE> object. * * @param name The name of the attribute. * @param type The type or class name of the attribute. * @param description A human readable description of the attribute. * @param isReadable True if the attribute has a getter method, false otherwise. * @param isWritable True if the attribute has a setter method, false otherwise. * @param isIs True if this attribute has an "is" getter, false otherwise. * * @throws IllegalArgumentException if {@code isIs} is true but * {@code isReadable} is not, or if {@code isIs} is true and * {@code type} is not {@code boolean} or {@code java.lang.Boolean}. * (New code should always use {@code boolean} rather than * {@code java.lang.Boolean}.) */ public MBeanAttributeInfo(String name, String type, String description, boolean isReadable, boolean isWritable, boolean isIs) { this(name, type, description, isReadable, isWritable, isIs, (Descriptor) null); } /** {@collect.stats} * Constructs an <CODE>MBeanAttributeInfo</CODE> object. * * @param name The name of the attribute. * @param type The type or class name of the attribute. * @param description A human readable description of the attribute. * @param isReadable True if the attribute has a getter method, false otherwise. * @param isWritable True if the attribute has a setter method, false otherwise. * @param isIs True if this attribute has an "is" getter, false otherwise. * @param descriptor The descriptor for the attribute. This may be null * which is equivalent to an empty descriptor. * * @throws IllegalArgumentException if {@code isIs} is true but * {@code isReadable} is not, or if {@code isIs} is true and * {@code type} is not {@code boolean} or {@code java.lang.Boolean}. * (New code should always use {@code boolean} rather than * {@code java.lang.Boolean}.) * * @since 1.6 */ public MBeanAttributeInfo(String name, String type, String description, boolean isReadable, boolean isWritable, boolean isIs, Descriptor descriptor) { super(name, description, descriptor); this.attributeType = type; this.isRead = isReadable; this.isWrite = isWritable; if (isIs && !isReadable) { throw new IllegalArgumentException("Cannot have an \"is\" getter " + "for a non-readable attribute"); } if (isIs && !type.equals("java.lang.Boolean") && !type.equals("boolean")) { throw new IllegalArgumentException("Cannot have an \"is\" getter " + "for a non-boolean attribute"); } this.is = isIs; } /** {@collect.stats} * <p>This constructor takes the name of a simple attribute, and Method * objects for reading and writing the attribute. The {@link Descriptor} * of the constructed object will include fields contributed by any * annotations on the {@code Method} objects that contain the * {@link DescriptorKey} meta-annotation. * * @param name The programmatic name of the attribute. * @param description A human readable description of the attribute. * @param getter The method used for reading the attribute value. * May be null if the property is write-only. * @param setter The method used for writing the attribute value. * May be null if the attribute is read-only. * @exception IntrospectionException There is a consistency * problem in the definition of this attribute. */ public MBeanAttributeInfo(String name, String description, Method getter, Method setter) throws IntrospectionException { this(name, attributeType(getter, setter), description, (getter != null), (setter != null), isIs(getter), ImmutableDescriptor.union(Introspector.descriptorForElement(getter), Introspector.descriptorForElement(setter))); } /** {@collect.stats} * <p>Returns a shallow clone of this instance. * The clone is obtained by simply calling <tt>super.clone()</tt>, * thus calling the default native shallow cloning mechanism * implemented by <tt>Object.clone()</tt>. * No deeper cloning of any internal field is made.</p> * * <p>Since this class is immutable, cloning is chiefly of * interest to subclasses.</p> */ public Object clone () { try { return super.clone() ; } catch (CloneNotSupportedException e) { // should not happen as this class is cloneable return null; } } /** {@collect.stats} * Returns the class name of the attribute. * * @return the class name. */ public String getType() { return attributeType; } /** {@collect.stats} * Whether the value of the attribute can be read. * * @return True if the attribute can be read, false otherwise. */ public boolean isReadable() { return isRead; } /** {@collect.stats} * Whether new values can be written to the attribute. * * @return True if the attribute can be written to, false otherwise. */ public boolean isWritable() { return isWrite; } /** {@collect.stats} * Indicates if this attribute has an "is" getter. * * @return true if this attribute has an "is" getter. */ public boolean isIs() { return is; } public String toString() { String access; if (isReadable()) { if (isWritable()) access = "read/write"; else access = "read-only"; } else if (isWritable()) access = "write-only"; else access = "no-access"; return getClass().getName() + "[" + "description=" + getDescription() + ", " + "name=" + getName() + ", " + "type=" + getType() + ", " + access + ", " + (isIs() ? "isIs, " : "") + "descriptor=" + getDescriptor() + "]"; } /** {@collect.stats} * Compare this MBeanAttributeInfo to another. * * @param o the object to compare to. * * @return true if and only if <code>o</code> is an MBeanAttributeInfo such * that its {@link #getName()}, {@link #getType()}, {@link * #getDescription()}, {@link #isReadable()}, {@link * #isWritable()}, and {@link #isIs()} values are equal (not * necessarily identical) to those of this MBeanAttributeInfo. */ public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof MBeanAttributeInfo)) return false; MBeanAttributeInfo p = (MBeanAttributeInfo) o; return (p.getName().equals(getName()) && p.getType().equals(getType()) && p.getDescription().equals(getDescription()) && p.getDescriptor().equals(getDescriptor()) && p.isReadable() == isReadable() && p.isWritable() == isWritable() && p.isIs() == isIs()); } /* We do not include everything in the hashcode. We assume that if two operations are different they'll probably have different names or types. The penalty we pay when this assumption is wrong should be less than the penalty we would pay if it were right and we needlessly hashed in the description and parameter array. */ public int hashCode() { return getName().hashCode() ^ getType().hashCode(); } private static boolean isIs(Method getter) { return (getter != null && getter.getName().startsWith("is") && (getter.getReturnType().equals(Boolean.TYPE) || getter.getReturnType().equals(Boolean.class))); } /** {@collect.stats} * Finds the type of the attribute. */ private static String attributeType(Method getter, Method setter) throws IntrospectionException { Class type = null; if (getter != null) { if (getter.getParameterTypes().length != 0) { throw new IntrospectionException("bad getter arg count"); } type = getter.getReturnType(); if (type == Void.TYPE) { throw new IntrospectionException("getter " + getter.getName() + " returns void"); } } if (setter != null) { Class params[] = setter.getParameterTypes(); if (params.length != 1) { throw new IntrospectionException("bad setter arg count"); } if (type == null) type = params[0]; else if (type != params[0]) { throw new IntrospectionException("type mismatch between " + "getter and setter"); } } if (type == null) { throw new IntrospectionException("getter and setter cannot " + "both be null"); } return type.getName(); } }
Java
/* * Copyright (c) 1999, 2006, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management; import java.util.Arrays; /** {@collect.stats} * <p>The <CODE>MBeanNotificationInfo</CODE> class is used to describe the * characteristics of the different notification instances * emitted by an MBean, for a given Java class of notification. * If an MBean emits notifications that can be instances of different Java classes, * then the metadata for that MBean should provide an <CODE>MBeanNotificationInfo</CODE> * object for each of these notification Java classes.</p> * * <p>Instances of this class are immutable. Subclasses may be * mutable but this is not recommended.</p> * * <p>This class extends <CODE>javax.management.MBeanFeatureInfo</CODE> * and thus provides <CODE>name</CODE> and <CODE>description</CODE> fields. * The <CODE>name</CODE> field should be the fully qualified Java class name of * the notification objects described by this class.</p> * * <p>The <CODE>getNotifTypes</CODE> method returns an array of * strings containing the notification types that the MBean may * emit. The notification type is a dot-notation string which * describes what the emitted notification is about, not the Java * class of the notification. A single generic notification class can * be used to send notifications of several types. All of these types * are returned in the string array result of the * <CODE>getNotifTypes</CODE> method. * * @since 1.5 */ public class MBeanNotificationInfo extends MBeanFeatureInfo implements Cloneable { /* Serial version */ static final long serialVersionUID = -3888371564530107064L; private static final String[] NO_TYPES = new String[0]; static final MBeanNotificationInfo[] NO_NOTIFICATIONS = new MBeanNotificationInfo[0]; /** {@collect.stats} * @serial The different types of the notification. */ private final String[] types; /** {@collect.stats} @see MBeanInfo#arrayGettersSafe */ private final transient boolean arrayGettersSafe; /** {@collect.stats} * Constructs an <CODE>MBeanNotificationInfo</CODE> object. * * @param notifTypes The array of strings (in dot notation) * containing the notification types that the MBean may emit. * This may be null with the same effect as a zero-length array. * @param name The fully qualified Java class name of the * described notifications. * @param description A human readable description of the data. */ public MBeanNotificationInfo(String[] notifTypes, String name, String description) { this(notifTypes, name, description, null); } /** {@collect.stats} * Constructs an <CODE>MBeanNotificationInfo</CODE> object. * * @param notifTypes The array of strings (in dot notation) * containing the notification types that the MBean may emit. * This may be null with the same effect as a zero-length array. * @param name The fully qualified Java class name of the * described notifications. * @param description A human readable description of the data. * @param descriptor The descriptor for the notifications. This may be null * which is equivalent to an empty descriptor. * * @since 1.6 */ public MBeanNotificationInfo(String[] notifTypes, String name, String description, Descriptor descriptor) { super(name, description, descriptor); /* We do not validate the notifTypes, since the spec just says they are dot-separated, not that they must look like Java classes. E.g. the spec doesn't forbid "sun.prob.25" as a notifType, though it doesn't explicitly allow it either. */ if (notifTypes == null) notifTypes = NO_TYPES; this.types = notifTypes; this.arrayGettersSafe = MBeanInfo.arrayGettersSafe(this.getClass(), MBeanNotificationInfo.class); } /** {@collect.stats} * Returns a shallow clone of this instance. * The clone is obtained by simply calling <tt>super.clone()</tt>, * thus calling the default native shallow cloning mechanism * implemented by <tt>Object.clone()</tt>. * No deeper cloning of any internal field is made. */ public Object clone () { try { return super.clone() ; } catch (CloneNotSupportedException e) { // should not happen as this class is cloneable return null; } } /** {@collect.stats} * Returns the array of strings (in dot notation) containing the * notification types that the MBean may emit. * * @return the array of strings. Changing the returned array has no * effect on this MBeanNotificationInfo. */ public String[] getNotifTypes() { if (types.length == 0) return NO_TYPES; else return types.clone(); } private String[] fastGetNotifTypes() { if (arrayGettersSafe) return types; else return getNotifTypes(); } public String toString() { return getClass().getName() + "[" + "description=" + getDescription() + ", " + "name=" + getName() + ", " + "notifTypes=" + Arrays.asList(fastGetNotifTypes()) + ", " + "descriptor=" + getDescriptor() + "]"; } /** {@collect.stats} * Compare this MBeanNotificationInfo to another. * * @param o the object to compare to. * * @return true if and only if <code>o</code> is an MBeanNotificationInfo * such that its {@link #getName()}, {@link #getDescription()}, * {@link #getDescriptor()}, * and {@link #getNotifTypes()} values are equal (not necessarily * identical) to those of this MBeanNotificationInfo. Two * notification type arrays are equal if their corresponding * elements are equal. They are not equal if they have the same * elements but in a different order. */ public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof MBeanNotificationInfo)) return false; MBeanNotificationInfo p = (MBeanNotificationInfo) o; return (p.getName().equals(getName()) && p.getDescription().equals(getDescription()) && p.getDescriptor().equals(getDescriptor()) && Arrays.equals(p.fastGetNotifTypes(), fastGetNotifTypes())); } public int hashCode() { int hash = getName().hashCode(); for (int i = 0; i < types.length; i++) hash ^= types[i].hashCode(); return hash; } }
Java
/* * Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management; /** {@collect.stats} * Runtime exceptions emitted by JMX implementations. * * @since 1.5 */ public class JMRuntimeException extends RuntimeException { /* Serial version */ private static final long serialVersionUID = 6573344628407841861L; /** {@collect.stats} * Default constructor. */ public JMRuntimeException() { super(); } /** {@collect.stats} * Constructor that allows a specific error message to be specified. * * @param message the detail message. */ public JMRuntimeException(String message) { super(message); } /** {@collect.stats} * Constructor with a nested exception. This constructor is * package-private because it arrived too late for the JMX 1.2 * specification. A later version may make it public. */ JMRuntimeException(String message, Throwable cause) { super(message); /* Make a best effort to set the cause, but if we don't succeed, too bad, you don't get that useful debugging information. We jump through hoops here so that we can work on platforms prior to J2SE 1.4 where the Throwable.initCause method was introduced. If we change the public interface of JMRuntimeException in a future version we can add getCause() so we don't need to do this. */ try { java.lang.reflect.Method initCause = Throwable.class.getMethod("initCause", new Class[] {Throwable.class}); initCause.invoke(this, new Object[] {cause}); } catch (Exception e) { // OK: just means we won't have debugging info } } }
Java
/* * Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management; /** {@collect.stats} * Represents a notification emitted by the MBean server through the MBeanServerDelegate MBean. * The MBean Server emits the following types of notifications: MBean registration, MBean * de-registration. * <P> * To receive to MBeanServerNotifications, you need to be declared as listener to * the {@link javax.management.MBeanServerDelegate javax.management.MBeanServerDelegate} MBean * that represents the MBeanServer. The ObjectName of the MBeanServerDelegate is: * <CODE>JMImplementation:type=MBeanServerDelegate</CODE>. * * @since 1.5 */ public class MBeanServerNotification extends Notification { /* Serial version */ private static final long serialVersionUID = 2876477500475969677L; /** {@collect.stats} * Notification type denoting that an MBean has been registered. Value is "JMX.mbean.registered". */ public static final String REGISTRATION_NOTIFICATION = "JMX.mbean.registered" ; /** {@collect.stats} * Notification type denoting that an MBean has been unregistered. Value is "JMX.mbean.unregistered". */ public static final String UNREGISTRATION_NOTIFICATION = "JMX.mbean.unregistered" ; /** {@collect.stats} * @serial The object names of the MBeans concerned by this notification */ private final ObjectName objectName; /** {@collect.stats} * Creates an MBeanServerNotification object specifying object names of * the MBeans that caused the notification and the specified notification type. * * @param type A string denoting the type of the * notification. Set it to one these values: {@link * #REGISTRATION_NOTIFICATION}, {@link * #UNREGISTRATION_NOTIFICATION}. * @param source The MBeanServerNotification object responsible * for forwarding MBean server notification. * @param sequenceNumber A sequence number that can be used to order * received notifications. * @param objectName The object name of the MBean that caused the notification. * */ public MBeanServerNotification(String type, Object source, long sequenceNumber, ObjectName objectName ) { super (type,source,sequenceNumber) ; this.objectName = objectName ; } /** {@collect.stats} * Returns the object name of the MBean that caused the notification. * * @return the object name of the MBean that caused the notification. */ public ObjectName getMBeanName() { return objectName ; } }
Java
/* * Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management; /** {@collect.stats} * This class represents indexed attributes used as arguments to relational * constraints. An QualifiedAttributeValueExp may be used anywhere a * ValueExp is required. * @serial include * * @since 1.5 */ class QualifiedAttributeValueExp extends AttributeValueExp { /* Serial version */ private static final long serialVersionUID = 8832517277410933254L; /** {@collect.stats} * @serial The attribute class name */ private String className; /** {@collect.stats} * Basic Constructor. */ public QualifiedAttributeValueExp() { } /** {@collect.stats} * Creates a new QualifiedAttributeValueExp representing the specified object * attribute, named attr with class name className. */ public QualifiedAttributeValueExp(String className, String attr) { super(attr); this.className = className; } /** {@collect.stats} * Returns a string representation of the class name of the attribute. */ public String getAttrClassName() { return className; } /** {@collect.stats} * Applies the QualifiedAttributeValueExp to an MBean. * * @param name The name of the MBean on which the QualifiedAttributeValueExp will be applied. * * @return The ValueExp. * * @exception BadStringOperationException * @exception BadBinaryOpValueExpException * @exception BadAttributeValueExpException * @exception InvalidApplicationException */ public ValueExp apply(ObjectName name) throws BadStringOperationException, BadBinaryOpValueExpException, BadAttributeValueExpException, InvalidApplicationException { try { MBeanServer server = QueryEval.getMBeanServer(); String v = server.getObjectInstance(name).getClassName(); if (v.equals(className)) { return super.apply(name); } throw new InvalidApplicationException("Class name is " + v + ", should be " + className); } catch (Exception e) { throw new InvalidApplicationException("Qualified attribute: " + e); /* Can happen if MBean disappears between the time we construct the list of MBeans to query and the time we evaluate the query on this MBean, or if getObjectInstance throws SecurityException. */ } } /** {@collect.stats} * Returns the string representing its value */ public String toString() { if (className != null) { return className + "." + super.toString(); } else { return super.toString(); } } }
Java
/* * Copyright (c) 1999, 2006, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management; /** {@collect.stats} * Thrown when an attempt is made to apply either of the following: A * subquery expression to an MBean or a qualified attribute expression * to an MBean of the wrong class. This exception is used internally * by JMX during the evaluation of a query. User code does not * usually see it. * * @since 1.5 */ public class InvalidApplicationException extends Exception { /* Serial version */ private static final long serialVersionUID = -3048022274675537269L; /** {@collect.stats} * @serial The object representing the class of the MBean */ private Object val; /** {@collect.stats} * Constructs an <CODE>InvalidApplicationException</CODE> with the specified <CODE>Object</CODE>. * * @param val the detail message of this exception. */ public InvalidApplicationException(Object val) { this.val = val; } }
Java
/* * Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ /* * @author IBM Corp. * * Copyright IBM Corp. 1999-2000. All rights reserved. */ package javax.management; import java.io.Serializable; // Javadoc imports: import java.lang.management.MemoryUsage; import java.util.Arrays; import java.util.ResourceBundle; import javax.management.openmbean.CompositeData; import javax.management.openmbean.OpenMBeanAttributeInfoSupport; import javax.management.openmbean.OpenMBeanOperationInfoSupport; import javax.management.openmbean.OpenMBeanParameterInfoSupport; import javax.management.openmbean.OpenType; /** {@collect.stats} * <p>Additional metadata for a JMX element. A {@code Descriptor} * is associated with a {@link MBeanInfo}, {@link MBeanAttributeInfo}, etc. * It consists of a collection of fields. A field is a name and an * associated value.</p> * * <p>Field names are not case-sensitive. The names {@code descriptorType}, * {@code descriptortype}, and {@code DESCRIPTORTYPE} are all equivalent. * However, the case that was used when the field was first set is preserved * in the result of the {@link #getFields} and {@link #getFieldNames} * methods.</p> * * <p>Not all field names and values are predefined. * New fields can be defined and added by any program.</p> * * <p>A descriptor can be mutable or immutable. * An immutable descriptor, once created, never changes. * The <code>Descriptor</code> methods that could modify the contents * of the descriptor will throw an exception * for an immutable descriptor. Immutable descriptors are usually * instances of {@link ImmutableDescriptor} or a subclass. Mutable * descriptors are usually instances of * {@link javax.management.modelmbean.DescriptorSupport} or a subclass. * * <p>Certain fields are used by the JMX implementation. This means * either that the presence of the field may change the behavior of * the JMX API or that the field may be set in descriptors returned by * the JMX API. These fields appear in <i>italics</i> in the table * below, and each one has a corresponding constant in the {@link JMX} * class. For example, the field {@code defaultValue} is represented * by the constant {@link JMX#DEFAULT_VALUE_FIELD}.</p> * * <p>Certain other fields have conventional meanings described in the * table below but they are not required to be understood or set by * the JMX implementation.</p> * * <p>Field names defined by the JMX specification in this and all * future versions will never contain a period (.). Users can safely * create their own fields by including a period in the name and be * sure that these names will not collide with any future version of * the JMX API. It is recommended to follow the Java package naming * convention to avoid collisions between field names from different * origins. For example, a field created by {@code example.com} might * have the name {@code com.example.interestLevel}.</p> * * <p>Note that the values in the {@code defaultValue}, {@code * legalValues}, {@code maxValue}, and {@code minValue} fields should * be consistent with the type returned by the {@code getType()} * method for the associated {@code MBeanAttributeInfo} or {@code * MBeanParameterInfo}. For MXBeans, this means that they should be * of the mapped Java type, called <em>opendata</em>(J) in the <a * href="MXBean.html#mapping-rules">MXBean type mapping rules</a>.</p> * * <table border="1" cellpadding="5"> * * <tr><th>Name</th><th>Type</th><th>Used in</th><th>Meaning</th></tr> * * <tr><td><a name="defaultValue"><i>defaultValue</i></a><td>Object</td> * <td>MBeanAttributeInfo<br>MBeanParameterInfo</td> * * <td>Default value for an attribute or parameter. See * {@link javax.management.openmbean}.</td> * * <tr><td>deprecated</td><td>String</td><td>Any</td> * * <td>An indication that this element of the information model is no * longer recommended for use. A set of MBeans defined by an * application is collectively called an <em>information model</em>. * The convention is for the value of this field to contain a string * that is the version of the model in which the element was first * deprecated, followed by a space, followed by an explanation of the * deprecation, for example {@code "1.3 Replaced by the Capacity * attribute"}.</td> * * <tr><td>descriptionResource<br>BundleBaseName</td><td>String</td><td>Any</td> * * <td>The base name for the {@link ResourceBundle} in which the key given in * the {@code descriptionResourceKey} field can be found, for example * {@code "com.example.myapp.MBeanResources"}. The meaning of this * field is defined by this specification but the field is not set or * used by the JMX API itself.</td> * * <tr><td>descriptionResourceKey</td><td>String</td><td>Any</td> * * <td>A resource key for the description of this element. In * conjunction with the {@code descriptionResourceBundleBaseName}, * this can be used to find a localized version of the description. * The meaning of this field is defined by this specification but the * field is not set or used by the JMX API itself.</td> * * <tr><td>enabled</td><td>String</td> * <td>MBeanAttributeInfo<br>MBeanNotificationInfo<br>MBeanOperationInfo</td> * * <td>The string {@code "true"} or {@code "false"} according as this * item is enabled. When an attribute or operation is not enabled, it * exists but cannot currently be accessed. A user interface might * present it as a greyed-out item. For example, an attribute might * only be meaningful after the {@code start()} method of an MBean has * been called, and is otherwise disabled. Likewise, a notification * might be disabled if it cannot currently be emitted but could be in * other circumstances.</td> * * <tr><td><a name="immutableInfo"><i>immutableInfo</i></a><td>String</td> * <td>MBeanInfo</td> * * <td>The string {@code "true"} or {@code "false"} according as this * MBean's MBeanInfo is <em>immutable</em>. When this field is true, * the MBeanInfo for the given MBean is guaranteed not to change over * the lifetime of the MBean. Hence, a client can read it once and * cache the read value. When this field is false or absent, there is * no such guarantee, although that does not mean that the MBeanInfo * will necessarily change.</td> * * <tr><td>infoTimeout</td><td>String<br>Long</td><td>MBeanInfo</td> * * <td>The time in milli-seconds that the MBeanInfo can reasonably be * expected to be unchanged. The value can be a {@code Long} or a * decimal string. This provides a hint from a DynamicMBean or any * MBean that does not define {@code immutableInfo} as {@code true} * that the MBeanInfo is not likely to change within this period and * therefore can be cached. When this field is missing or has the * value zero, it is not recommended to cache the MBeanInfo unless it * has the {@code immutableInfo} set to {@code true}.</td></tr> * * <tr><td><a name="interfaceClassName"><i>interfaceClassName</i></a></td> * <td>String</td><td>MBeanInfo</td> * * <td>The Java interface name for a Standard MBean or MXBean, as * returned by {@link Class#getName()}. A Standard MBean or MXBean * registered directly in the MBean Server or created using the {@link * StandardMBean} class will have this field in its MBeanInfo * Descriptor.</td> * * <tr><td><a name="legalValues"><i>legalValues</i></a></td> * <td>{@literal Set<?>}</td><td>MBeanAttributeInfo<br>MBeanParameterInfo</td> * * <td>Legal values for an attribute or parameter. See * {@link javax.management.openmbean}.</td> * * <tr><td><a name="maxValue"><i>maxValue</i></a><td>Object</td> * <td>MBeanAttributeInfo<br>MBeanParameterInfo</td> * * <td>Maximum legal value for an attribute or parameter. See * {@link javax.management.openmbean}.</td> * * <tr><td><a name="metricType">metricType</a><td>String</td> * <td>MBeanAttributeInfo<br>MBeanOperationInfo</td> * * <td>The type of a metric, one of the strings "counter" or "gauge". * A metric is a measurement exported by an MBean, usually an * attribute but sometimes the result of an operation. A metric that * is a <em>counter</em> has a value that never decreases except by * being reset to a starting value. Counter metrics are almost always * non-negative integers. An example might be the number of requests * received. A metric that is a <em>gauge</em> has a numeric value * that can increase or decrease. Examples might be the number of * open connections or a cache hit rate or a temperature reading. * * <tr><td><a name="minValue"><i>minValue</i></a><td>Object</td> * <td>MBeanAttributeInfo<br>MBeanParameterInfo</td> * * <td>Minimum legal value for an attribute or parameter. See * {@link javax.management.openmbean}.</td> * * <tr><td><a name="mxbean"><i>mxbean</i></a><td>String</td> * <td>MBeanInfo</td> * * <td>The string {@code "true"} or {@code "false"} according as this * MBean is an {@link MXBean}. A Standard MBean or MXBean registered * directly with the MBean Server or created using the {@link * StandardMBean} class will have this field in its MBeanInfo * Descriptor.</td> * * <tr><td><a name="openType"><i>openType</i></a><td>{@link OpenType}</td> * <td>MBeanAttributeInfo<br>MBeanOperationInfo<br>MBeanParameterInfo</td> * * <td><p>The Open Type of this element. In the case of {@code * MBeanAttributeInfo} and {@code MBeanParameterInfo}, this is the * Open Type of the attribute or parameter. In the case of {@code * MBeanOperationInfo}, it is the Open Type of the return value. This * field is set in the Descriptor for all instances of {@link * OpenMBeanAttributeInfoSupport}, {@link * OpenMBeanOperationInfoSupport}, and {@link * OpenMBeanParameterInfoSupport}. It is also set for attributes, * operations, and parameters of MXBeans.</p> * * <p>This field can be set for an {@code MBeanNotificationInfo}, in * which case it indicates the Open Type that the {@link * Notification#getUserData() user data} will have.</td> * * <tr><td><a name="originalType"><i>originalType</i></a><td>String</td> * <td>MBeanAttributeInfo<br>MBeanOperationInfo<br>MBeanParameterInfo</td> * * <td><p>The original Java type of this element as it appeared in the * {@link MXBean} interface method that produced this {@code * MBeanAttributeInfo} (etc). For example, a method<br> <code>public * </code> {@link MemoryUsage}<code> getHeapMemoryUsage();</code><br> * in an MXBean interface defines an attribute called {@code * HeapMemoryUsage} of type {@link CompositeData}. The {@code * originalType} field in the Descriptor for this attribute will have * the value {@code "java.lang.management.MemoryUsage"}. * * <p>The format of this string is described in the section <a * href="MXBean.html#type-names">Type Names</a> of the MXBean * specification.</p> * * <tr><td>severity</td><td>String<br>Integer</td> * <td>MBeanNotificationInfo</td> * * <td>The severity of this notification. It can be 0 to mean * unknown severity or a value from 1 to 6 representing decreasing * levels of severity. It can be represented as a decimal string or * an {@code Integer}.</td> * * <tr><td>since</td><td>String</td><td>Any</td> * * <td>The version of the information model in which this element * was introduced. A set of MBeans defined by an application is * collectively called an <em>information model</em>. The * application may also define versions of this model, and use the * {@code "since"} field to record the version in which an element * first appeared.</td> * * <tr><td>units</td><td>String</td> * <td>MBeanAttributeInfo<br>MBeanParameterInfo<br>MBeanOperationInfo</td> * * <td>The units in which an attribute, parameter, or operation return * value is measured, for example {@code "bytes"} or {@code * "seconds"}.</td> * * </table> * * <p>Some additional fields are defined by Model MBeans. See * {@link javax.management.modelmbean.ModelMBeanInfo ModelMBeanInfo} * and related classes and the chapter "Model MBeans" of the * <a href="http://java.sun.com/products/JavaManagement/download.html"> * JMX Specification</a>.</p> * * @since 1.5 */ public interface Descriptor extends Serializable, Cloneable { /** {@collect.stats} * Returns the value for a specific field name, or null if no value * is present for that name. * * @param fieldName the field name. * * @return the corresponding value, or null if the field is not present. * * @exception RuntimeOperationsException if the field name is illegal. */ public Object getFieldValue(String fieldName) throws RuntimeOperationsException; /** {@collect.stats} * <p>Sets the value for a specific field name. This will * modify an existing field or add a new field.</p> * * <p>The field value will be validated before it is set. * If it is not valid, then an exception will be thrown. * The meaning of validity is dependent on the descriptor * implementation.</p> * * @param fieldName The field name to be set. Cannot be null or empty. * @param fieldValue The field value to be set for the field * name. Can be null if that is a valid value for the field. * * @exception RuntimeOperationsException if the field name or field value * is illegal (wrapped exception is {@link IllegalArgumentException}); or * if the descriptor is immutable (wrapped exception is * {@link UnsupportedOperationException}). */ public void setField(String fieldName, Object fieldValue) throws RuntimeOperationsException; /** {@collect.stats} * Returns all of the fields contained in this descriptor as a string array. * * @return String array of fields in the format <i>fieldName=fieldValue</i> * <br>If the value of a field is not a String, then the toString() method * will be called on it and the returned value, enclosed in parentheses, * used as the value for the field in the returned array. If the value * of a field is null, then the value of the field in the returned array * will be empty. If the descriptor is empty, you will get * an empty array. * * @see #setFields */ public String[] getFields(); /** {@collect.stats} * Returns all the field names in the descriptor. * * @return String array of field names. If the descriptor is empty, * you will get an empty array. */ public String[] getFieldNames(); /** {@collect.stats} * Returns all the field values in the descriptor as an array of Objects. The * returned values are in the same order as the {@code fieldNames} String array parameter. * * @param fieldNames String array of the names of the fields that * the values should be returned for. If the array is empty then * an empty array will be returned. If the array is null then all * values will be returned, as if the parameter were the array * returned by {@link #getFieldNames()}. If a field name in the * array does not exist, including the case where it is null or * the empty string, then null is returned for the matching array * element being returned. * * @return Object array of field values. If the list of {@code fieldNames} * is empty, you will get an empty array. */ public Object[] getFieldValues(String... fieldNames); /** {@collect.stats} * Removes a field from the descriptor. * * @param fieldName String name of the field to be removed. * If the field name is illegal or the field is not found, * no exception is thrown. * * @exception RuntimeOperationsException if a field of the given name * exists and the descriptor is immutable. The wrapped exception will * be an {@link UnsupportedOperationException}. */ public void removeField(String fieldName); /** {@collect.stats} * <p>Sets all fields in the field names array to the new value with * the same index in the field values array. Array sizes must match.</p> * * <p>The field value will be validated before it is set. * If it is not valid, then an exception will be thrown. * If the arrays are empty, then no change will take effect.</p> * * @param fieldNames String array of field names. The array and array * elements cannot be null. * @param fieldValues Object array of the corresponding field values. * The array cannot be null. Elements of the array can be null. * * @throws RuntimeOperationsException if the change fails for any reason. * Wrapped exception is {@link IllegalArgumentException} if * {@code fieldNames} or {@code fieldValues} is null, or if * the arrays are of different lengths, or if there is an * illegal value in one of them. * Wrapped exception is {@link UnsupportedOperationException} * if the descriptor is immutable, and the call would change * its contents. * * @see #getFields */ public void setFields(String[] fieldNames, Object[] fieldValues) throws RuntimeOperationsException; /** {@collect.stats} * <p>Returns a descriptor which is equal to this descriptor. * Changes to the returned descriptor will have no effect on this * descriptor, and vice versa. If this descriptor is immutable, * it may fulfill this condition by returning itself.</p> * @exception RuntimeOperationsException for illegal value for field names * or field values. * If the descriptor construction fails for any reason, this exception will * be thrown. * @return A descriptor which is equal to this descriptor. */ public Object clone() throws RuntimeOperationsException; /** {@collect.stats} * Returns true if all of the fields have legal values given their * names. * * @return true if the values are legal. * * @exception RuntimeOperationsException If the validity checking fails for * any reason, this exception will be thrown. * The method returns false if the descriptor is not valid, but throws * this exception if the attempt to determine validity fails. */ public boolean isValid() throws RuntimeOperationsException; /** {@collect.stats} * Compares this descriptor to the given object. The objects are equal if * the given object is also a Descriptor, and if the two Descriptors have * the same field names (possibly differing in case) and the same * associated values. The respective values for a field in the two * Descriptors are equal if the following conditions hold:</p> * * <ul> * <li>If one value is null then the other must be too.</li> * <li>If one value is a primitive array then the other must be a primitive * array of the same type with the same elements.</li> * <li>If one value is an object array then the other must be too and * {@link Arrays#deepEquals(Object[],Object[])} must return true.</li> * <li>Otherwise {@link Object#equals(Object)} must return true.</li> * </ul> * * @param obj the object to compare with. * * @return {@code true} if the objects are the same; {@code false} * otherwise. * * @since 1.6 */ public boolean equals(Object obj); /** {@collect.stats} * <p>Returns the hash code value for this descriptor. The hash * code is computed as the sum of the hash codes for each field in * the descriptor. The hash code of a field with name {@code n} * and value {@code v} is {@code n.toLowerCase().hashCode() ^ h}. * Here {@code h} is the hash code of {@code v}, computed as * follows:</p> * * <ul> * <li>If {@code v} is null then {@code h} is 0.</li> * <li>If {@code v} is a primitive array then {@code h} is computed using * the appropriate overloading of {@code java.util.Arrays.hashCode}.</li> * <li>If {@code v} is an object array then {@code h} is computed using * {@link Arrays#deepHashCode(Object[])}.</li> * <li>Otherwise {@code h} is {@code v.hashCode()}.</li> * </ul> * * @return A hash code value for this object. * * @since 1.6 */ public int hashCode(); }
Java
/* * Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management; /** {@collect.stats} * Exception which occurs when trying to register an object in the MBean server that is not a JMX compliant MBean. * * @since 1.5 */ public class NotCompliantMBeanException extends OperationsException { /* Serial version */ private static final long serialVersionUID = 5175579583207963577L; /** {@collect.stats} * Default constructor. */ public NotCompliantMBeanException() { super(); } /** {@collect.stats} * Constructor that allows a specific error message to be specified. * * @param message the detail message. */ public NotCompliantMBeanException(String message) { super(message); } }
Java
/* * Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ /* * @author IBM Corp. * * Copyright IBM Corp. 1999-2000. All rights reserved. */ package javax.management.modelmbean; import static com.sun.jmx.defaults.JmxProperties.MODELMBEAN_LOGGER; import com.sun.jmx.mbeanserver.GetPropertyAction; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.ObjectStreamField; import java.security.AccessController; import java.util.logging.Level; import javax.management.Descriptor; import javax.management.DescriptorAccess; import javax.management.MBeanNotificationInfo; import javax.management.RuntimeOperationsException; /** {@collect.stats} * The ModelMBeanNotificationInfo object describes a notification emitted * by a ModelMBean. * It is a subclass of MBeanNotificationInfo with the addition of an * associated Descriptor and an implementation of the Descriptor interface. * <P> * The fields in the descriptor are defined, but not limited to, * the following: * <PRE> * name : notification name * descriptorType : must be "notification" * severity : 0-6 where 0: unknown; 1: non-recoverable; * 2: critical, failure; 3: major, severe; * 4: minor, marginal, error; 5: warning; * 6: normal, cleared, informative * messageID : unique key for message text (to allow translation, * analysis) * messageText : text of notification * log : T - log message F - do not log message * logfile : string fully qualified file name appropriate for * operating system * visibility : 1-4 where 1: always visible 4: rarely visible * presentationString : xml formatted string to allow presentation of data * </PRE> * The default descriptor contains the name, descriptorType, displayName * and severity(=6) fields. * * <p>The <b>serialVersionUID</b> of this class is <code>-7445681389570207141L</code>. * * @since 1.5 */ // Sun Microsystems, Sept. 2002: Revisited for JMX 1.2 (DF) // @SuppressWarnings("serial") // serialVersionUID is not constant public class ModelMBeanNotificationInfo extends MBeanNotificationInfo implements DescriptorAccess { // Serialization compatibility stuff: // Two serial forms are supported in this class. The selected form // depends on system property "jmx.serial.form": // - "1.0" for JMX 1.0 // - any other value for JMX 1.1 and higher // // Serial version for old serial form private static final long oldSerialVersionUID = -5211564525059047097L; // // Serial version for new serial form private static final long newSerialVersionUID = -7445681389570207141L; // // Serializable fields in old serial form private static final ObjectStreamField[] oldSerialPersistentFields = { new ObjectStreamField("notificationDescriptor", Descriptor.class), new ObjectStreamField("currClass", String.class) }; // // Serializable fields in new serial form private static final ObjectStreamField[] newSerialPersistentFields = { new ObjectStreamField("notificationDescriptor", Descriptor.class) }; // // Actual serial version and serial form private static final long serialVersionUID; /** {@collect.stats} * @serialField notificationDescriptor Descriptor The descriptor * containing the appropriate metadata for this instance */ private static final ObjectStreamField[] serialPersistentFields; private static boolean compat = false; static { try { GetPropertyAction act = new GetPropertyAction("jmx.serial.form"); String form = AccessController.doPrivileged(act); compat = (form != null && form.equals("1.0")); } catch (Exception e) { // OK: No compat with 1.0 } if (compat) { serialPersistentFields = oldSerialPersistentFields; serialVersionUID = oldSerialVersionUID; } else { serialPersistentFields = newSerialPersistentFields; serialVersionUID = newSerialVersionUID; } } // // END Serialization compatibility stuff /** {@collect.stats} * @serial The descriptor containing the appropriate metadata for * this instance */ private Descriptor notificationDescriptor; private static final String currClass = "ModelMBeanNotificationInfo"; /** {@collect.stats} * Constructs a ModelMBeanNotificationInfo object with a default * descriptor. * * @param notifTypes The array of strings (in dot notation) containing * the notification types that may be emitted. * @param name The name of the Notification class. * @param description A human readable description of the * Notification. Optional. **/ public ModelMBeanNotificationInfo(String[] notifTypes, String name, String description) { this(notifTypes,name,description,null); } /** {@collect.stats} * Constructs a ModelMBeanNotificationInfo object. * * @param notifTypes The array of strings (in dot notation) * containing the notification types that may be emitted. * @param name The name of the Notification class. * @param description A human readable description of the Notification. * Optional. * @param descriptor An instance of Descriptor containing the * appropriate metadata for this instance of the * MBeanNotificationInfo. If it is null a default descriptor * will be created. If the descriptor does not contain the * fields "displayName" or "severity" these fields are added * in the descriptor with their default values. * * @exception RuntimeOperationsException Wraps an * {@link IllegalArgumentException}. The descriptor is invalid, or * descriptor field "name" is not equal to parameter name, or * descriptor field "DescriptorType" is not equal to "notification". * **/ public ModelMBeanNotificationInfo(String[] notifTypes, String name, String description, Descriptor descriptor) { super(notifTypes, name, description); final String mth = "ModelMBeanNotificationInfo"; if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanNotificationInfo.class.getName(), mth, "Entry"); } applyDescriptor(descriptor, mth); } /** {@collect.stats} * Constructs a new ModelMBeanNotificationInfo object from this * ModelMBeanNotfication Object. * * @param inInfo the ModelMBeanNotificationInfo to be duplicated * **/ public ModelMBeanNotificationInfo(ModelMBeanNotificationInfo inInfo) { this(inInfo.getNotifTypes(), inInfo.getName(), inInfo.getDescription(),inInfo.getDescriptor()); } /** {@collect.stats} * Creates and returns a new ModelMBeanNotificationInfo which is a * duplicate of this ModelMBeanNotificationInfo. **/ public Object clone () { if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanNotificationInfo.class.getName(), "clone()", "Entry"); } return(new ModelMBeanNotificationInfo(this)); } /** {@collect.stats} * Returns a copy of the associated Descriptor for the * ModelMBeanNotificationInfo. * * @return Descriptor associated with the * ModelMBeanNotificationInfo object. * * @see #setDescriptor **/ public Descriptor getDescriptor() { if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanNotificationInfo.class.getName(), "getDescriptor()", "Entry"); } if (notificationDescriptor == null) { // Dead code. Should never happen. if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanNotificationInfo.class.getName(), "getDescriptor()", "Descriptor value is null, " + "setting descriptor to default values"); } notificationDescriptor = createDefaultDescriptor(); } return((Descriptor)notificationDescriptor.clone()); } /** {@collect.stats} * Sets associated Descriptor (full replace) for the * ModelMBeanNotificationInfo If the new Descriptor is null, * then the associated Descriptor reverts to a default * descriptor. The Descriptor is validated before it is * assigned. If the new Descriptor is invalid, then a * RuntimeOperationsException wrapping an * IllegalArgumentException is thrown. * * @param inDescriptor replaces the Descriptor associated with the * ModelMBeanNotification interface * * @exception RuntimeOperationsException Wraps an * {@link IllegalArgumentException} for invalid Descriptor. * * @see #getDescriptor **/ public void setDescriptor(Descriptor inDescriptor) { if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanNotificationInfo.class.getName(), "setDescriptor(Descriptor)", "Entry"); } applyDescriptor(inDescriptor,"setDescriptor(Descriptor)"); } /** {@collect.stats} * Returns a human readable string containing * ModelMBeanNotificationInfo. * * @return a string describing this object. **/ public String toString() { if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanNotificationInfo.class.getName(), "toString()", "Entry"); } final StringBuilder retStr = new StringBuilder(); retStr.append("ModelMBeanNotificationInfo: ") .append(this.getName()); retStr.append(" ; Description: ") .append(this.getDescription()); retStr.append(" ; Descriptor: ") .append(this.getDescriptor()); retStr.append(" ; Types: "); String[] nTypes = this.getNotifTypes(); for (int i=0; i < nTypes.length; i++) { if (i > 0) retStr.append(", "); retStr.append(nTypes[i]); } return retStr.toString(); } /** {@collect.stats} * Creates default descriptor for notification as follows: * <pre>descriptorType=notification, * name=this.getName(),displayname=this.getName(),severity=6 * </pre> **/ private final Descriptor createDefaultDescriptor() { if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanNotificationInfo.class.getName(), "createDefaultDescriptor()", "Entry"); } return new DescriptorSupport(new String[] {"descriptorType=notification", ("name=" + this.getName()), ("displayName=" + this.getName()), "severity=6"}); } /** {@collect.stats} * Tests that the descriptor is valid and adds appropriate default * fields not already specified. Field values must be correct for * field names. * Descriptor must have the same name as the notification, * the descriptorType field must be "notification", **/ private boolean isValid(Descriptor inDesc) { boolean results = true; String badField = "none"; if (inDesc == null) { badField="nullDescriptor"; return false; } if (!inDesc.isValid()) { // checks for empty descriptors, null, // checks for empty name and descriptorType adn valid // values for fields. badField="invalidDescriptor"; results = false; } else if (!((String)inDesc.getFieldValue("name")). equalsIgnoreCase(this.getName())) { badField="name"; results = false; } else if (! ((String)inDesc.getFieldValue("descriptorType")). equalsIgnoreCase("notification")) { badField="descriptorType"; results = false; } if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanNotificationInfo.class.getName(), "isValid(Descriptor)", "Returning " + results + " : Invalid field is " + badField); } return results; } /** {@collect.stats} * The following fields will be defaulted if they are not already * set: * displayName=this.getName(),severity=6 * @return the given descriptor, possibly modified. **/ private final Descriptor setDefaults(Descriptor descriptor) { if ((descriptor.getFieldValue("displayName")) == null) { descriptor.setField("displayName",this.getName()); } if ((descriptor.getFieldValue("severity")) == null) { descriptor.setField("severity","6"); } return descriptor; } /** {@collect.stats} * Set the given descriptor as this.notificationDescriptor. * Creates a default descriptor if the given descriptor is null. * If the given descriptor is null, check its validity. * If it is valid, clones it and set the defaults fields * "displayName" and "severity", if not present. * If it is not valid, throws an exception. * This method is called both by the constructors and by * setDescriptor(). * @see #setDefaults * @see #setDescriptor **/ private final void applyDescriptor(Descriptor descriptor, String ftag) { if (descriptor == null) { if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanNotificationInfo.class.getName(), ftag, "Received null for new descriptor value, " + "setting descriptor to default values"); } notificationDescriptor = createDefaultDescriptor(); } else if (isValid(descriptor)) { notificationDescriptor = setDefaults((Descriptor)descriptor.clone()); } else { throw new RuntimeOperationsException(new IllegalArgumentException( "Invalid descriptor passed in parameter"), "Exception occurred in ModelMBeanNotificationInfo " + ftag); } } /** {@collect.stats} * Deserializes a {@link ModelMBeanNotificationInfo} from an * {@link ObjectInputStream}. **/ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { // New serial form ignores extra field "currClass" in.defaultReadObject(); } /** {@collect.stats} * Serializes a {@link ModelMBeanNotificationInfo} to an * {@link ObjectOutputStream}. **/ private void writeObject(ObjectOutputStream out) throws IOException { if (compat) { // Serializes this instance in the old serial form // ObjectOutputStream.PutField fields = out.putFields(); fields.put("notificationDescriptor", notificationDescriptor); fields.put("currClass", currClass); out.writeFields(); } else { // Serializes this instance in the new serial form // out.defaultWriteObject(); } } }
Java
/* * Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ /* * @author IBM Corp. * * Copyright IBM Corp. 1999-2000. All rights reserved. */ package javax.management.modelmbean; import com.sun.jmx.mbeanserver.GetPropertyAction; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.ObjectStreamField; import java.security.AccessController; /** {@collect.stats} * Exception thrown when an invalid target object type is specified. * * * <p>The <b>serialVersionUID</b> of this class is <code>1190536278266811217L</code>. * * @since 1.5 */ @SuppressWarnings("serial") // serialVersionUID not constant public class InvalidTargetObjectTypeException extends Exception { // Serialization compatibility stuff: // Two serial forms are supported in this class. The selected form depends // on system property "jmx.serial.form": // - "1.0" for JMX 1.0 // - any other value for JMX 1.1 and higher // // Serial version for old serial form private static final long oldSerialVersionUID = 3711724570458346634L; // // Serial version for new serial form private static final long newSerialVersionUID = 1190536278266811217L; // // Serializable fields in old serial form private static final ObjectStreamField[] oldSerialPersistentFields = { new ObjectStreamField("msgStr", String.class), new ObjectStreamField("relatedExcept", Exception.class) }; // // Serializable fields in new serial form private static final ObjectStreamField[] newSerialPersistentFields = { new ObjectStreamField("exception", Exception.class) }; // // Actual serial version and serial form private static final long serialVersionUID; /** {@collect.stats} * @serialField exception Exception Encapsulated {@link Exception} */ private static final ObjectStreamField[] serialPersistentFields; private static boolean compat = false; static { try { GetPropertyAction act = new GetPropertyAction("jmx.serial.form"); String form = AccessController.doPrivileged(act); compat = (form != null && form.equals("1.0")); } catch (Exception e) { // OK: No compat with 1.0 } if (compat) { serialPersistentFields = oldSerialPersistentFields; serialVersionUID = oldSerialVersionUID; } else { serialPersistentFields = newSerialPersistentFields; serialVersionUID = newSerialVersionUID; } } // // END Serialization compatibility stuff /** {@collect.stats} * @serial Encapsulated {@link Exception} */ Exception exception; /** {@collect.stats} * Default constructor. */ public InvalidTargetObjectTypeException () { super("InvalidTargetObjectTypeException: "); exception = null; } /** {@collect.stats} * Constructor from a string. * * @param s String value that will be incorporated in the message for * this exception. */ public InvalidTargetObjectTypeException (String s) { super("InvalidTargetObjectTypeException: " + s); exception = null; } /** {@collect.stats} * Constructor taking an exception and a string. * * @param e Exception that we may have caught to reissue as an * InvalidTargetObjectTypeException. The message will be used, and we may want to * consider overriding the printStackTrace() methods to get data * pointing back to original throw stack. * @param s String value that will be incorporated in message for * this exception. */ public InvalidTargetObjectTypeException (Exception e, String s) { super("InvalidTargetObjectTypeException: " + s + ((e != null)?("\n\t triggered by:" + e.toString()):"")); exception = e; } /** {@collect.stats} * Deserializes an {@link InvalidTargetObjectTypeException} from an {@link ObjectInputStream}. */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { if (compat) { // Read an object serialized in the old serial form // ObjectInputStream.GetField fields = in.readFields(); exception = (Exception) fields.get("relatedExcept", null); if (fields.defaulted("relatedExcept")) { throw new NullPointerException("relatedExcept"); } } else { // Read an object serialized in the new serial form // in.defaultReadObject(); } } /** {@collect.stats} * Serializes an {@link InvalidTargetObjectTypeException} to an {@link ObjectOutputStream}. */ private void writeObject(ObjectOutputStream out) throws IOException { if (compat) { // Serializes this instance in the old serial form // ObjectOutputStream.PutField fields = out.putFields(); fields.put("relatedExcept", exception); fields.put("msgStr", ((exception != null)?exception.getMessage():"")); out.writeFields(); } else { // Serializes this instance in the new serial form // out.defaultWriteObject(); } } }
Java
/* * Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ /* * @author IBM Corp. * * Copyright IBM Corp. 1999-2000. All rights reserved. */ package javax.management.modelmbean; import com.sun.jmx.mbeanserver.GetPropertyAction; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.ObjectStreamField; import java.security.AccessController; /** {@collect.stats} * This exception is thrown when an XML formatted string is being parsed into ModelMBean objects * or when XML formatted strings are being created from ModelMBean objects. * * It is also used to wrapper exceptions from XML parsers that may be used. * * <p>The <b>serialVersionUID</b> of this class is <code>3176664577895105181L</code>. * * @since 1.5 */ @SuppressWarnings("serial") // serialVersionUID not constant public class XMLParseException extends Exception { // Serialization compatibility stuff: // Two serial forms are supported in this class. The selected form depends // on system property "jmx.serial.form": // - "1.0" for JMX 1.0 // - any other value for JMX 1.1 and higher // // Serial version for old serial form private static final long oldSerialVersionUID = -7780049316655891976L; // // Serial version for new serial form private static final long newSerialVersionUID = 3176664577895105181L; // // Serializable fields in old serial form private static final ObjectStreamField[] oldSerialPersistentFields = { new ObjectStreamField("msgStr", String.class) }; // // Serializable fields in new serial form private static final ObjectStreamField[] newSerialPersistentFields = { }; // // Actual serial version and serial form private static final long serialVersionUID; private static final ObjectStreamField[] serialPersistentFields; private static boolean compat = false; static { try { GetPropertyAction act = new GetPropertyAction("jmx.serial.form"); String form = AccessController.doPrivileged(act); compat = (form != null && form.equals("1.0")); } catch (Exception e) { // OK: No compat with 1.0 } if (compat) { serialPersistentFields = oldSerialPersistentFields; serialVersionUID = oldSerialVersionUID; } else { serialPersistentFields = newSerialPersistentFields; serialVersionUID = newSerialVersionUID; } } // // END Serialization compatibility stuff /** {@collect.stats} * Default constructor . */ public XMLParseException () { super("XML Parse Exception."); } /** {@collect.stats} * Constructor taking a string. * * @param s the detail message. */ public XMLParseException (String s) { super("XML Parse Exception: " + s); } /** {@collect.stats} * Constructor taking a string and an exception. * * @param e the nested exception. * @param s the detail message. */ public XMLParseException (Exception e, String s) { super("XML Parse Exception: " + s + ":" + e.toString()); } /** {@collect.stats} * Deserializes an {@link XMLParseException} from an {@link ObjectInputStream}. */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { // New serial form ignores extra field "msgStr" in.defaultReadObject(); } /** {@collect.stats} * Serializes an {@link XMLParseException} to an {@link ObjectOutputStream}. */ private void writeObject(ObjectOutputStream out) throws IOException { if (compat) { // Serializes this instance in the old serial form // ObjectOutputStream.PutField fields = out.putFields(); fields.put("msgStr", getMessage()); out.writeFields(); } else { // Serializes this instance in the new serial form // out.defaultWriteObject(); } } }
Java
/* * Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ /* * @author IBM Corp. * * Copyright IBM Corp. 1999-2000. All rights reserved. */ package javax.management.modelmbean; import javax.management.Descriptor; import javax.management.MBeanAttributeInfo; import javax.management.MBeanConstructorInfo; import javax.management.RuntimeOperationsException; import javax.management.MBeanException; import javax.management.MBeanNotificationInfo; import javax.management.MBeanOperationInfo; /** {@collect.stats} * This interface is implemented by the ModelMBeanInfo for every ModelMBean. An implementation of this interface * must be shipped with every JMX Agent. * <P> * Java resources wishing to be manageable instantiate the ModelMBean using the MBeanServer's * createMBean method. The resource then sets the ModelMBeanInfo and Descriptors for the ModelMBean * instance. The attributes, operations, and notifications exposed via the ModelMBeanInfo for the * ModelMBean comprise the management interface and are accessible * from MBeans, connectors/adaptors like other MBeans. Through the Descriptors, values and methods in * the managed application can be defined and mapped to attributes and operations of the ModelMBean. * This mapping can be defined during development in a file or dynamically and * programmatically at runtime. * <P> * Every ModelMBean which is instantiated in the MBeanServer becomes manageable: * its attributes, operations, and notifications * become remotely accessible through the connectors/adaptors connected to that MBeanServer. * A Java object cannot be registered in the MBeanServer unless it is a JMX compliant MBean. * By instantiating a ModelMBean, resources are guaranteed that the MBean is valid. * * MBeanException and RuntimeOperationsException must be thrown on every public method. This allows * for wrapping exceptions from distributed communications (RMI, EJB, etc.) * * @since 1.5 */ public interface ModelMBeanInfo { /** {@collect.stats} * Returns a Descriptor array consisting of all * Descriptors for the ModelMBeanInfo of type inDescriptorType. * * @param inDescriptorType value of descriptorType field that must be set for the descriptor * to be returned. Must be "mbean", "attribute", "operation", "constructor" or "notification". * If it is null or empty then all types will be returned. * * @return Descriptor array containing all descriptors for the ModelMBean if type inDescriptorType. * * @exception MBeanException Wraps a distributed communication Exception. * @exception RuntimeOperationsException Wraps an IllegalArgumentException when the descriptorType in parameter is * not one of: "mbean", "attribute", "operation", "constructor", "notification", empty or null. * * @see #setDescriptors */ public Descriptor[] getDescriptors(String inDescriptorType) throws MBeanException, RuntimeOperationsException; /** {@collect.stats} * Adds or replaces descriptors in the ModelMBeanInfo. * * @param inDescriptors The descriptors to be set in the ModelMBeanInfo. Null * elements of the list will be ignored. All descriptors must have name and descriptorType fields. * * @exception RuntimeOperationsException Wraps an IllegalArgumentException for a null or invalid descriptor. * @exception MBeanException Wraps a distributed communication Exception. * * @see #getDescriptors */ public void setDescriptors(Descriptor[] inDescriptors) throws MBeanException, RuntimeOperationsException; /** {@collect.stats} * Returns a Descriptor requested by name and descriptorType. * * @param inDescriptorName The name of the descriptor. * @param inDescriptorType The type of the descriptor being * requested. If this is null or empty then all types are * searched. Valid types are 'mbean', 'attribute', 'constructor' * 'operation', and 'notification'. This value will be equal to * the 'descriptorType' field in the descriptor that is returned. * * @return Descriptor containing the descriptor for the ModelMBean * with the same name and descriptorType. If no descriptor is * found, null is returned. * * @exception MBeanException Wraps a distributed communication Exception. * @exception RuntimeOperationsException Wraps an IllegalArgumentException for a null descriptor name or null or invalid type. * The type must be "mbean","attribute", "constructor", "operation", or "notification". * * @see #setDescriptor */ public Descriptor getDescriptor(String inDescriptorName, String inDescriptorType) throws MBeanException, RuntimeOperationsException; /** {@collect.stats} * Sets descriptors in the info array of type inDescriptorType * for the ModelMBean. The setDescriptor method of the * corresponding ModelMBean*Info will be called to set the * specified descriptor. * * @param inDescriptor The descriptor to be set in the * ModelMBean. It must NOT be null. All descriptors must have * name and descriptorType fields. * @param inDescriptorType The type of the descriptor being * set. If this is null then the descriptorType field in the * descriptor is used. If specified this value must be set in * the descriptorType field in the descriptor. Must be * "mbean","attribute", "constructor", "operation", or * "notification". * * @exception RuntimeOperationsException Wraps an * IllegalArgumentException for illegal or null arguments or * if the name field of the descriptor is not found in the * corresponding MBeanAttributeInfo or MBeanConstructorInfo or * MBeanNotificationInfo or MBeanOperationInfo. * @exception MBeanException Wraps a distributed communication * Exception. * * @see #getDescriptor */ public void setDescriptor(Descriptor inDescriptor, String inDescriptorType) throws MBeanException, RuntimeOperationsException; /** {@collect.stats} * Returns the ModelMBean's descriptor which contains MBean wide policies. This descriptor contains * metadata about the MBean and default policies for persistence and caching. * <P> * The fields in the descriptor are defined, but not limited to, the following: * <PRE> * name : MBean name * descriptorType : must be "mbean" * displayName : name of attribute to be used in displays * persistPolicy : OnUpdate|OnTimer|NoMoreOftenThan|OnUnregister|Always|Never * persistLocation : The fully qualified directory name where the MBean should be persisted (if appropriate) * persistFile : File name into which the MBean should be persisted * persistPeriod : seconds - frequency of persist cycle for OnTime and NoMoreOftenThan PersistPolicy * currencyTimeLimit : how long value is valid, &lt;0 never, =0 always, &gt;0 seconds * log : where t: log all notifications f: log no notifications * logfile : fully qualified filename to log events to * visibility : 1-4 where 1: always visible 4: rarely visible * export : name to be used to export/expose this MBean so that it is findable by * other JMX Agents. * presentationString : xml formatted string to allow presentation of data to be associated with the MBean. * </PRE> * <P> * The default descriptor is: name=className,descriptorType="mbean", displayName=className, * persistPolicy="never",log="F",export="F",visibility="1" * If the descriptor does not contain all these fields, they will be added with these default values. * * <p><b>Note:</b> because of inconsistencies in previous versions of * this specification, it is recommended not to use negative or zero * values for <code>currencyTimeLimit</code>. To indicate that a * cached value is never valid, omit the * <code>currencyTimeLimit</code> field. To indicate that it is * always valid, use a very large number for this field.</p> * * @return the MBean descriptor. * * @exception MBeanException Wraps a distributed communication * Exception. * * @exception RuntimeOperationsException a {@link * RuntimeException} occurred while getting the descriptor. * * @see #setMBeanDescriptor */ public Descriptor getMBeanDescriptor() throws MBeanException, RuntimeOperationsException; /** {@collect.stats} * Sets the ModelMBean's descriptor. This descriptor contains default, MBean wide * metadata about the MBean and default policies for persistence and caching. This operation * does a complete replacement of the descriptor, no merging is done. If the descriptor to * set to is null then the default descriptor will be created. * The default descriptor is: name=className,descriptorType="mbean", displayName=className, * persistPolicy="never",log="F",export="F",visibility="1" * If the descriptor does not contain all these fields, they will be added with these default values. * * See {@link #getMBeanDescriptor getMBeanDescriptor} method javadoc for description of valid field names. * * @param inDescriptor the descriptor to set. * * @exception MBeanException Wraps a distributed communication Exception. * @exception RuntimeOperationsException Wraps an IllegalArgumentException for invalid descriptor. * * * @see #getMBeanDescriptor */ public void setMBeanDescriptor(Descriptor inDescriptor) throws MBeanException, RuntimeOperationsException; /** {@collect.stats} * Returns a ModelMBeanAttributeInfo requested by name. * * @param inName The name of the ModelMBeanAttributeInfo to get. * If no ModelMBeanAttributeInfo exists for this name null is returned. * * @return the attribute info for the named attribute, or null * if there is none. * * @exception MBeanException Wraps a distributed communication * Exception. * @exception RuntimeOperationsException Wraps an * IllegalArgumentException for a null attribute name. * */ public ModelMBeanAttributeInfo getAttribute(String inName) throws MBeanException, RuntimeOperationsException; /** {@collect.stats} * Returns a ModelMBeanOperationInfo requested by name. * * @param inName The name of the ModelMBeanOperationInfo to get. * If no ModelMBeanOperationInfo exists for this name null is returned. * * @return the operation info for the named operation, or null * if there is none. * * @exception MBeanException Wraps a distributed communication Exception. * @exception RuntimeOperationsException Wraps an IllegalArgumentException for a null operation name. * */ public ModelMBeanOperationInfo getOperation(String inName) throws MBeanException, RuntimeOperationsException; /** {@collect.stats} * Returns a ModelMBeanNotificationInfo requested by name. * * @param inName The name of the ModelMBeanNotificationInfo to get. * If no ModelMBeanNotificationInfo exists for this name null is returned. * * @return the info for the named notification, or null if there * is none. * * @exception MBeanException Wraps a distributed communication Exception. * @exception RuntimeOperationsException Wraps an IllegalArgumentException for a null notification name. * */ public ModelMBeanNotificationInfo getNotification(String inName) throws MBeanException, RuntimeOperationsException; /** {@collect.stats} * Creates and returns a copy of this object. */ public java.lang.Object clone(); /** {@collect.stats} * Returns the list of attributes exposed for management. * Each attribute is described by an <CODE>MBeanAttributeInfo</CODE> object. * * @return An array of <CODE>MBeanAttributeInfo</CODE> objects. */ public MBeanAttributeInfo[] getAttributes(); /** {@collect.stats} * Returns the name of the Java class of the MBean described by * this <CODE>MBeanInfo</CODE>. * * @return the Java class name. */ public java.lang.String getClassName(); /** {@collect.stats} * Returns the list of the public constructors of the MBean. * Each constructor is described by an <CODE>MBeanConstructorInfo</CODE> object. * * @return An array of <CODE>MBeanConstructorInfo</CODE> objects. */ public MBeanConstructorInfo[] getConstructors(); /** {@collect.stats} * Returns a human readable description of the MBean. * * @return the description. */ public java.lang.String getDescription(); /** {@collect.stats} * Returns the list of the notifications emitted by the MBean. * Each notification is described by an <CODE>MBeanNotificationInfo</CODE> object. * <P> * In addition to any notification specified by the application, * a ModelMBean may always send also two additional notifications: * <UL> * <LI> One with descriptor name "GENERIC" and displayName "jmx.modelmbean.generic" * <LI> Second is a standard attribute change notification * with descriptor name "ATTRIBUTE_CHANGE" and displayName "jmx.attribute.change" * </UL> * Thus any implementation of ModelMBeanInfo should always add those two notifications * in addition to those specified by the application. * * @return An array of <CODE>MBeanNotificationInfo</CODE> objects. */ public MBeanNotificationInfo[] getNotifications(); /** {@collect.stats} * Returns the list of operations of the MBean. * Each operation is described by an <CODE>MBeanOperationInfo</CODE> object. * * @return An array of <CODE>MBeanOperationInfo</CODE> objects. */ public MBeanOperationInfo[] getOperations(); }
Java
/* * Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ /* * @author IBM Corp. * * Copyright IBM Corp. 1999-2000. All rights reserved. */ package javax.management.modelmbean; import static com.sun.jmx.defaults.JmxProperties.MODELMBEAN_LOGGER; import com.sun.jmx.mbeanserver.GetPropertyAction; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.ObjectStreamField; import java.security.AccessController; import java.util.logging.Level; import javax.management.Descriptor; import javax.management.MBeanAttributeInfo; import javax.management.MBeanConstructorInfo; import javax.management.MBeanException; import javax.management.MBeanInfo; import javax.management.MBeanNotificationInfo; import javax.management.MBeanOperationInfo; import javax.management.RuntimeOperationsException; /** {@collect.stats} * This class represents the meta data for ModelMBeans. Descriptors have been * added on the meta data objects. * <P> * Java resources wishing to be manageable instantiate the ModelMBean using the * MBeanServer's createMBean method. The resource then sets the ModelMBeanInfo * and Descriptors for the ModelMBean instance. The attributes and operations * exposed via the ModelMBeanInfo for the ModelMBean are accessible * from MBeans, connectors/adaptors like other MBeans. Through the Descriptors, * values and methods in the managed application can be defined and mapped to * attributes and operations of the ModelMBean. * This mapping can be defined during development in a file or dynamically and * programmatically at runtime. * <P> * Every ModelMBean which is instantiated in the MBeanServer becomes manageable: * its attributes and operations * become remotely accessible through the connectors/adaptors connected to that * MBeanServer. * A Java object cannot be registered in the MBeanServer unless it is a JMX * compliant MBean. * By instantiating a ModelMBean, resources are guaranteed that the MBean is * valid. * * MBeanException and RuntimeOperationsException must be thrown on every public * method. This allows for wrapping exceptions from distributed * communications (RMI, EJB, etc.) * * <p>The <b>serialVersionUID</b> of this class is * <code>-1935722590756516193L</code>. * * @since 1.5 */ @SuppressWarnings("serial") public class ModelMBeanInfoSupport extends MBeanInfo implements ModelMBeanInfo { // Serialization compatibility stuff: // Two serial forms are supported in this class. The selected form depends // on system property "jmx.serial.form": // - "1.0" for JMX 1.0 // - any other value for JMX 1.1 and higher // // Serial version for old serial form private static final long oldSerialVersionUID = -3944083498453227709L; // // Serial version for new serial form private static final long newSerialVersionUID = -1935722590756516193L; // // Serializable fields in old serial form private static final ObjectStreamField[] oldSerialPersistentFields = { new ObjectStreamField("modelMBeanDescriptor", Descriptor.class), new ObjectStreamField("mmbAttributes", MBeanAttributeInfo[].class), new ObjectStreamField("mmbConstructors", MBeanConstructorInfo[].class), new ObjectStreamField("mmbNotifications", MBeanNotificationInfo[].class), new ObjectStreamField("mmbOperations", MBeanOperationInfo[].class), new ObjectStreamField("currClass", String.class) }; // // Serializable fields in new serial form private static final ObjectStreamField[] newSerialPersistentFields = { new ObjectStreamField("modelMBeanDescriptor", Descriptor.class), new ObjectStreamField("modelMBeanAttributes", MBeanAttributeInfo[].class), new ObjectStreamField("modelMBeanConstructors", MBeanConstructorInfo[].class), new ObjectStreamField("modelMBeanNotifications", MBeanNotificationInfo[].class), new ObjectStreamField("modelMBeanOperations", MBeanOperationInfo[].class) }; // // Actual serial version and serial form private static final long serialVersionUID; /** {@collect.stats} * @serialField modelMBeanDescriptor Descriptor The descriptor containing * MBean wide policy * @serialField modelMBeanAttributes ModelMBeanAttributeInfo[] The array of * {@link ModelMBeanAttributeInfo} objects which * have descriptors * @serialField modelMBeanConstructors MBeanConstructorInfo[] The array of * {@link ModelMBeanConstructorInfo} objects which * have descriptors * @serialField modelMBeanNotifications MBeanNotificationInfo[] The array of * {@link ModelMBeanNotificationInfo} objects which * have descriptors * @serialField modelMBeanOperations MBeanOperationInfo[] The array of * {@link ModelMBeanOperationInfo} objects which * have descriptors */ private static final ObjectStreamField[] serialPersistentFields; private static boolean compat = false; static { try { GetPropertyAction act = new GetPropertyAction("jmx.serial.form"); String form = AccessController.doPrivileged(act); compat = (form != null && form.equals("1.0")); } catch (Exception e) { // OK: No compat with 1.0 } if (compat) { serialPersistentFields = oldSerialPersistentFields; serialVersionUID = oldSerialVersionUID; } else { serialPersistentFields = newSerialPersistentFields; serialVersionUID = newSerialVersionUID; } } // // END Serialization compatibility stuff /** {@collect.stats} * @serial The descriptor containing MBean wide policy */ private Descriptor modelMBeanDescriptor = null; /* The following fields always have the same values as the fields inherited from MBeanInfo and are retained only for compatibility. By rewriting the serialization code we could get rid of them. These fields can't be final because they are assigned to by readObject(). */ /** {@collect.stats} * @serial The array of {@link ModelMBeanAttributeInfo} objects which * have descriptors */ private MBeanAttributeInfo[] modelMBeanAttributes; /** {@collect.stats} * @serial The array of {@link ModelMBeanConstructorInfo} objects which * have descriptors */ private MBeanConstructorInfo[] modelMBeanConstructors; /** {@collect.stats} * @serial The array of {@link ModelMBeanNotificationInfo} objects which * have descriptors */ private MBeanNotificationInfo[] modelMBeanNotifications; /** {@collect.stats} * @serial The array of {@link ModelMBeanOperationInfo} objects which * have descriptors */ private MBeanOperationInfo[] modelMBeanOperations; private static final String ATTR = "attribute"; private static final String OPER = "operation"; private static final String NOTF = "notification"; private static final String CONS = "constructor"; private static final String MMB = "mbean"; private static final String ALL = "all"; private static final String currClass = "ModelMBeanInfoSupport"; /** {@collect.stats} * Constructs a ModelMBeanInfoSupport which is a duplicate of the given * ModelMBeanInfo. The returned object is a shallow copy of the given * object. Neither the Descriptor nor the contained arrays * ({@code ModelMBeanAttributeInfo[]} etc) are cloned. This method is * chiefly of interest to modify the Descriptor of the returned instance * via {@link #setDescriptor setDescriptor} without affecting the * Descriptor of the original object. * * @param mbi the ModelMBeanInfo instance from which the ModelMBeanInfo * being created is initialized. */ public ModelMBeanInfoSupport(ModelMBeanInfo mbi) { super(mbi.getClassName(), mbi.getDescription(), mbi.getAttributes(), mbi.getConstructors(), mbi.getOperations(), mbi.getNotifications()); modelMBeanAttributes = mbi.getAttributes(); modelMBeanConstructors = mbi.getConstructors(); modelMBeanOperations = mbi.getOperations(); modelMBeanNotifications = mbi.getNotifications(); try { Descriptor mbeandescriptor = mbi.getMBeanDescriptor(); if ((mbeandescriptor != null) && isValidDescriptor(mbeandescriptor)) { if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanInfoSupport.class.getName(), "ModelMBeanInfo(ModelMBeanInfo)", "ModelMBeanDescriptor is valid, " + "cloning Descriptor *" + mbeandescriptor + "*"); } modelMBeanDescriptor = (Descriptor) mbeandescriptor.clone(); addDefaultFields(); } else { if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanInfoSupport.class.getName(), "ModelMBeanInfo(ModelMBeanInfo)", "ModelMBeanDescriptor in ModelMBeanInfo " + "is null or invalid, setting to default value"); } modelMBeanDescriptor = createDefaultDescriptor(); } } catch (MBeanException mbe) { modelMBeanDescriptor = createDefaultDescriptor(); if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanInfoSupport.class.getName(), "ModelMBeanInfo(ModelMBeanInfo)", "Could not get modelMBeanDescriptor, " + "setting to default value"); } } if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanInfoSupport.class.getName(), "ModelMBeanInfo(ModelMBeanInfo)", "Exit"); } } /** {@collect.stats} * Creates a ModelMBeanInfoSupport with the provided information, * but the descriptor is a default. * The default descriptor is: name=mbeanName, descriptorType=mbean, * displayName=ClassName, persistPolicy=never, log=F, visibility=1 * * @param className classname of the MBean * @param description human readable description of the * ModelMBean * @param attributes array of ModelMBeanAttributeInfo objects * which have descriptors * @param constructors array of ModelMBeanConstructorInfo * objects which have descriptors * @param operations array of ModelMBeanOperationInfo objects * which have descriptors * @param notifications array of ModelMBeanNotificationInfo * objects which have descriptors */ public ModelMBeanInfoSupport(String className, String description, ModelMBeanAttributeInfo[] attributes, ModelMBeanConstructorInfo[] constructors, ModelMBeanOperationInfo[] operations, ModelMBeanNotificationInfo[] notifications) { this(className, description, attributes, constructors, operations, notifications, null); } /** {@collect.stats} * Creates a ModelMBeanInfoSupport with the provided information * and the descriptor given in parameter. * * @param className classname of the MBean * @param description human readable description of the * ModelMBean * @param attributes array of ModelMBeanAttributeInfo objects * which have descriptors * @param constructors array of ModelMBeanConstructorInfo * objects which have descriptor * @param operations array of ModelMBeanOperationInfo objects * which have descriptor * @param notifications array of ModelMBeanNotificationInfo * objects which have descriptor * @param mbeandescriptor descriptor to be used as the * MBeanDescriptor containing MBean wide policy. If the * descriptor is null, a default descriptor will be constructed. * The default descriptor is: * name=className, descriptorType=mbean, displayName=className, * persistPolicy=never, log=F, visibility=1. If the * descriptor does not contain all these fields, they will be * added with these default values. * * @exception RuntimeOperationsException Wraps an * IllegalArgumentException for invalid descriptor passed in * parameter. (see {@link #getMBeanDescriptor * getMBeanDescriptor} for the definition of a valid MBean * descriptor.) */ public ModelMBeanInfoSupport(String className, String description, ModelMBeanAttributeInfo[] attributes, ModelMBeanConstructorInfo[] constructors, ModelMBeanOperationInfo[] operations, ModelMBeanNotificationInfo[] notifications, Descriptor mbeandescriptor) { super(className, description, (attributes != null) ? attributes : NO_ATTRIBUTES, (constructors != null) ? constructors : NO_CONSTRUCTORS, (operations != null) ? operations : NO_OPERATIONS, (notifications != null) ? notifications : NO_NOTIFICATIONS); /* The values saved here are possibly null, but we check this everywhere they are referenced. If at some stage we replace null with an empty array here, as we do in the superclass constructor parameters, then we must also do this in readObject(). */ modelMBeanAttributes = attributes; modelMBeanConstructors = constructors; modelMBeanOperations = operations; modelMBeanNotifications = notifications; if (mbeandescriptor ==null) { if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanInfoSupport.class.getName(), "ModelMBeanInfoSupport(String,String," + "ModelMBeanAttributeInfo[]," + "ModelMBeanConstructorInfo[]," + "ModelMBeanOperationInfo[]," + "ModelMBeanNotificationInfo[]," + "Descriptor)", "MBeanDescriptor is null, setting default descriptor"); } modelMBeanDescriptor = createDefaultDescriptor(); } else { if (isValidDescriptor(mbeandescriptor)) { modelMBeanDescriptor = (Descriptor) mbeandescriptor.clone(); addDefaultFields(); } else { throw new RuntimeOperationsException( new IllegalArgumentException( "Invalid descriptor passed in parameter")); } } if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanInfoSupport.class.getName(), "ModelMBeanInfoSupport(String,String,ModelMBeanAttributeInfo[]," + "ModelMBeanConstructorInfo[],ModelMBeanOperationInfo[]," + "ModelMBeanNotificationInfo[],Descriptor)", "Exit"); } } private static final ModelMBeanAttributeInfo[] NO_ATTRIBUTES = new ModelMBeanAttributeInfo[0]; private static final ModelMBeanConstructorInfo[] NO_CONSTRUCTORS = new ModelMBeanConstructorInfo[0]; private static final ModelMBeanNotificationInfo[] NO_NOTIFICATIONS = new ModelMBeanNotificationInfo[0]; private static final ModelMBeanOperationInfo[] NO_OPERATIONS = new ModelMBeanOperationInfo[0]; // Java doc inherited from MOdelMBeanInfo interface /** {@collect.stats} * Returns a shallow clone of this instance. Neither the Descriptor nor * the contained arrays ({@code ModelMBeanAttributeInfo[]} etc) are * cloned. This method is chiefly of interest to modify the Descriptor * of the clone via {@link #setDescriptor setDescriptor} without affecting * the Descriptor of the original object. * * @return a shallow clone of this instance. */ public Object clone() { return(new ModelMBeanInfoSupport(this)); } public Descriptor[] getDescriptors(String inDescriptorType) throws MBeanException, RuntimeOperationsException { if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanInfoSupport.class.getName(), "getDescriptors(String)", "Entry"); } if ((inDescriptorType == null) || (inDescriptorType.isEmpty())) { inDescriptorType = "all"; } // if no descriptors of that type, will return empty array // final Descriptor[] retList; if (inDescriptorType.equalsIgnoreCase(MMB)) { retList = new Descriptor[] {modelMBeanDescriptor}; } else if (inDescriptorType.equalsIgnoreCase(ATTR)) { final MBeanAttributeInfo[] attrList = modelMBeanAttributes; int numAttrs = 0; if (attrList != null) numAttrs = attrList.length; retList = new Descriptor[numAttrs]; for (int i=0; i < numAttrs; i++) { retList[i] = (((ModelMBeanAttributeInfo) attrList[i]).getDescriptor()); } } else if (inDescriptorType.equalsIgnoreCase(OPER)) { final MBeanOperationInfo[] operList = modelMBeanOperations; int numOpers = 0; if (operList != null) numOpers = operList.length; retList = new Descriptor[numOpers]; for (int i=0; i < numOpers; i++) { retList[i] = (((ModelMBeanOperationInfo) operList[i]).getDescriptor()); } } else if (inDescriptorType.equalsIgnoreCase(CONS)) { final MBeanConstructorInfo[] consList = modelMBeanConstructors; int numCons = 0; if (consList != null) numCons = consList.length; retList = new Descriptor[numCons]; for (int i=0; i < numCons; i++) { retList[i] = (((ModelMBeanConstructorInfo) consList[i]).getDescriptor()); } } else if (inDescriptorType.equalsIgnoreCase(NOTF)) { final MBeanNotificationInfo[] notifList = modelMBeanNotifications; int numNotifs = 0; if (notifList != null) numNotifs = notifList.length; retList = new Descriptor[numNotifs]; for (int i=0; i < numNotifs; i++) { retList[i] = (((ModelMBeanNotificationInfo) notifList[i]).getDescriptor()); } } else if (inDescriptorType.equalsIgnoreCase(ALL)) { final MBeanAttributeInfo[] attrList = modelMBeanAttributes; int numAttrs = 0; if (attrList != null) numAttrs = attrList.length; final MBeanOperationInfo[] operList = modelMBeanOperations; int numOpers = 0; if (operList != null) numOpers = operList.length; final MBeanConstructorInfo[] consList = modelMBeanConstructors; int numCons = 0; if (consList != null) numCons = consList.length; final MBeanNotificationInfo[] notifList = modelMBeanNotifications; int numNotifs = 0; if (notifList != null) numNotifs = notifList.length; int count = numAttrs + numCons + numOpers + numNotifs + 1; retList = new Descriptor[count]; retList[count-1] = modelMBeanDescriptor; int j=0; for (int i=0; i < numAttrs; i++) { retList[j] = (((ModelMBeanAttributeInfo) attrList[i]).getDescriptor()); j++; } for (int i=0; i < numCons; i++) { retList[j] = (((ModelMBeanConstructorInfo) consList[i]).getDescriptor()); j++; } for (int i=0; i < numOpers; i++) { retList[j] = (((ModelMBeanOperationInfo)operList[i]). getDescriptor()); j++; } for (int i=0; i < numNotifs; i++) { retList[j] = (((ModelMBeanNotificationInfo)notifList[i]). getDescriptor()); j++; } } else { final IllegalArgumentException iae = new IllegalArgumentException("Descriptor Type is invalid"); final String msg = "Exception occurred trying to find"+ " the descriptors of the MBean"; throw new RuntimeOperationsException(iae,msg); } if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanInfoSupport.class.getName(), "getDescriptors(String)", "Exit"); } return retList; } public void setDescriptors(Descriptor[] inDescriptors) throws MBeanException, RuntimeOperationsException { if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanInfoSupport.class.getName(), "setDescriptors(Descriptor[])", "Entry"); } if (inDescriptors==null) { // throw RuntimeOperationsException - invalid descriptor throw new RuntimeOperationsException( new IllegalArgumentException("Descriptor list is invalid"), "Exception occurred trying to set the descriptors " + "of the MBeanInfo"); } if (inDescriptors.length == 0) { // empty list, no-op return; } for (int j=0; j < inDescriptors.length; j++) { setDescriptor(inDescriptors[j],null); } if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanInfoSupport.class.getName(), "setDescriptors(Descriptor[])", "Exit"); } } /** {@collect.stats} * Returns a Descriptor requested by name. * * @param inDescriptorName The name of the descriptor. * * @return Descriptor containing a descriptor for the ModelMBean with the * same name. If no descriptor is found, null is returned. * * @exception MBeanException Wraps a distributed communication Exception. * @exception RuntimeOperationsException Wraps an IllegalArgumentException * for null name. * * @see #setDescriptor */ public Descriptor getDescriptor(String inDescriptorName) throws MBeanException, RuntimeOperationsException { if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanInfoSupport.class.getName(), "getDescriptor(String)", "Entry"); } return(getDescriptor(inDescriptorName, null)); } public Descriptor getDescriptor(String inDescriptorName, String inDescriptorType) throws MBeanException, RuntimeOperationsException { if (inDescriptorName==null) { // throw RuntimeOperationsException - invalid descriptor throw new RuntimeOperationsException( new IllegalArgumentException("Descriptor is invalid"), "Exception occurred trying to set the descriptors of " + "the MBeanInfo"); } if (MMB.equalsIgnoreCase(inDescriptorType)) { return (Descriptor) modelMBeanDescriptor.clone(); } /* The logic here is a bit convoluted, because we are dealing with two possible cases, depending on whether inDescriptorType is null. If it's not null, then only one of the following ifs will run, and it will either return a descriptor or null. If inDescriptorType is null, then all of the following ifs will run until one of them finds a descriptor. */ if (ATTR.equalsIgnoreCase(inDescriptorType) || inDescriptorType == null) { ModelMBeanAttributeInfo attr = getAttribute(inDescriptorName); if (attr != null) return attr.getDescriptor(); if (inDescriptorType != null) return null; } if (OPER.equalsIgnoreCase(inDescriptorType) || inDescriptorType == null) { ModelMBeanOperationInfo oper = getOperation(inDescriptorName); if (oper != null) return oper.getDescriptor(); if (inDescriptorType != null) return null; } if (CONS.equalsIgnoreCase(inDescriptorType) || inDescriptorType == null) { ModelMBeanConstructorInfo oper = getConstructor(inDescriptorName); if (oper != null) return oper.getDescriptor(); if (inDescriptorType != null) return null; } if (NOTF.equalsIgnoreCase(inDescriptorType) || inDescriptorType == null) { ModelMBeanNotificationInfo notif = getNotification(inDescriptorName); if (notif != null) return notif.getDescriptor(); if (inDescriptorType != null) return null; } if (inDescriptorType == null) return null; throw new RuntimeOperationsException( new IllegalArgumentException("Descriptor Type is invalid"), "Exception occurred trying to find the descriptors of the MBean"); } public void setDescriptor(Descriptor inDescriptor, String inDescriptorType) throws MBeanException, RuntimeOperationsException { final String excMsg = "Exception occurred trying to set the descriptors of the MBean"; if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanInfoSupport.class.getName(), "setDescriptor(Descriptor,String)", "Entry"); } if (inDescriptor==null) { RuntimeException iae = new IllegalArgumentException("Null Descriptor"); throw new RuntimeOperationsException(iae, excMsg); } if ((inDescriptorType == null) || (inDescriptorType.isEmpty())) { inDescriptorType = (String) inDescriptor.getFieldValue("descriptorType"); if (inDescriptorType == null) { RuntimeException iae = new IllegalArgumentException("Descriptor type is invalid"); throw new RuntimeOperationsException(iae, excMsg); } } String inDescriptorName = (String) inDescriptor.getFieldValue("name"); if (inDescriptorName == null) { RuntimeException iae = new IllegalArgumentException("Descriptor name is invalid"); throw new RuntimeOperationsException(iae, excMsg); } boolean found = false; if (inDescriptorType.equalsIgnoreCase(MMB)) { setMBeanDescriptor(inDescriptor); found = true; } else if (inDescriptorType.equalsIgnoreCase(ATTR)) { MBeanAttributeInfo[] attrList = modelMBeanAttributes; int numAttrs = 0; if (attrList != null) numAttrs = attrList.length; for (int i=0; i < numAttrs; i++) { if (inDescriptorName.equals(attrList[i].getName())) { found = true; ModelMBeanAttributeInfo mmbai = (ModelMBeanAttributeInfo) attrList[i]; mmbai.setDescriptor(inDescriptor); if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { StringBuilder strb = new StringBuilder() .append("Setting descriptor to ").append(inDescriptor) .append("\t\n local: AttributeInfo descriptor is ") .append(mmbai.getDescriptor()) .append("\t\n modelMBeanInfo: AttributeInfo descriptor is ") .append(this.getDescriptor(inDescriptorName,"attribute")); MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanInfoSupport.class.getName(), "setDescriptor(Descriptor,String)", strb.toString()); } } } } else if (inDescriptorType.equalsIgnoreCase(OPER)) { MBeanOperationInfo[] operList = modelMBeanOperations; int numOpers = 0; if (operList != null) numOpers = operList.length; for (int i=0; i < numOpers; i++) { if (inDescriptorName.equals(operList[i].getName())) { found = true; ModelMBeanOperationInfo mmboi = (ModelMBeanOperationInfo) operList[i]; mmboi.setDescriptor(inDescriptor); } } } else if (inDescriptorType.equalsIgnoreCase(CONS)) { MBeanConstructorInfo[] consList = modelMBeanConstructors; int numCons = 0; if (consList != null) numCons = consList.length; for (int i=0; i < numCons; i++) { if (inDescriptorName.equals(consList[i].getName())) { found = true; ModelMBeanConstructorInfo mmbci = (ModelMBeanConstructorInfo) consList[i]; mmbci.setDescriptor(inDescriptor); } } } else if (inDescriptorType.equalsIgnoreCase(NOTF)) { MBeanNotificationInfo[] notifList = modelMBeanNotifications; int numNotifs = 0; if (notifList != null) numNotifs = notifList.length; for (int i=0; i < numNotifs; i++) { if (inDescriptorName.equals(notifList[i].getName())) { found = true; ModelMBeanNotificationInfo mmbni = (ModelMBeanNotificationInfo) notifList[i]; mmbni.setDescriptor(inDescriptor); } } } else { RuntimeException iae = new IllegalArgumentException("Invalid descriptor type: " + inDescriptorType); throw new RuntimeOperationsException(iae, excMsg); } if (!found) { RuntimeException iae = new IllegalArgumentException("Descriptor name is invalid: " + "type=" + inDescriptorType + "; name=" + inDescriptorName); throw new RuntimeOperationsException(iae, excMsg); } if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanInfoSupport.class.getName(), "setDescriptor(Descriptor,String)", "Exit"); } } public ModelMBeanAttributeInfo getAttribute(String inName) throws MBeanException, RuntimeOperationsException { ModelMBeanAttributeInfo retInfo = null; if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanInfoSupport.class.getName(), "getAttribute(String)", "Entry"); } if (inName == null) { throw new RuntimeOperationsException( new IllegalArgumentException("Attribute Name is null"), "Exception occurred trying to get the " + "ModelMBeanAttributeInfo of the MBean"); } MBeanAttributeInfo[] attrList = modelMBeanAttributes; int numAttrs = 0; if (attrList != null) numAttrs = attrList.length; for (int i=0; (i < numAttrs) && (retInfo == null); i++) { if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { final StringBuilder strb = new StringBuilder() .append("\t\n this.getAttributes() MBeanAttributeInfo Array ") .append(i).append(":") .append(((ModelMBeanAttributeInfo)attrList[i]).getDescriptor()) .append("\t\n this.modelMBeanAttributes MBeanAttributeInfo Array ") .append(i).append(":") .append(((ModelMBeanAttributeInfo)modelMBeanAttributes[i]).getDescriptor()); MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanInfoSupport.class.getName(), "getAttribute(String)", strb.toString()); } if (inName.equals(attrList[i].getName())) { retInfo = ((ModelMBeanAttributeInfo)attrList[i].clone()); } } if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanInfoSupport.class.getName(), "getAttribute(String)", "Exit"); } return retInfo; } public ModelMBeanOperationInfo getOperation(String inName) throws MBeanException, RuntimeOperationsException { ModelMBeanOperationInfo retInfo = null; if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanInfoSupport.class.getName(), "getOperation(String)", "Entry"); } if (inName == null) { throw new RuntimeOperationsException( new IllegalArgumentException("inName is null"), "Exception occurred trying to get the " + "ModelMBeanOperationInfo of the MBean"); } MBeanOperationInfo[] operList = modelMBeanOperations; //this.getOperations(); int numOpers = 0; if (operList != null) numOpers = operList.length; for (int i=0; (i < numOpers) && (retInfo == null); i++) { if (inName.equals(operList[i].getName())) { retInfo = ((ModelMBeanOperationInfo) operList[i].clone()); } } if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanInfoSupport.class.getName(), "getOperation(String)", "Exit"); } return retInfo; } /** {@collect.stats} * Returns the ModelMBeanConstructorInfo requested by name. * If no ModelMBeanConstructorInfo exists for this name null is returned. * * @param inName the name of the constructor. * * @return the constructor info for the named constructor, or null * if there is none. * * @exception MBeanException Wraps a distributed communication Exception. * @exception RuntimeOperationsException Wraps an IllegalArgumentException * for a null constructor name. */ public ModelMBeanConstructorInfo getConstructor(String inName) throws MBeanException, RuntimeOperationsException { ModelMBeanConstructorInfo retInfo = null; if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanInfoSupport.class.getName(), "getConstructor(String)", "Entry"); } if (inName == null) { throw new RuntimeOperationsException( new IllegalArgumentException("Constructor name is null"), "Exception occurred trying to get the " + "ModelMBeanConstructorInfo of the MBean"); } MBeanConstructorInfo[] consList = modelMBeanConstructors; //this.getConstructors(); int numCons = 0; if (consList != null) numCons = consList.length; for (int i=0; (i < numCons) && (retInfo == null); i++) { if (inName.equals(consList[i].getName())) { retInfo = ((ModelMBeanConstructorInfo) consList[i].clone()); } } if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanInfoSupport.class.getName(), "getConstructor(String)", "Exit"); } return retInfo; } public ModelMBeanNotificationInfo getNotification(String inName) throws MBeanException, RuntimeOperationsException { ModelMBeanNotificationInfo retInfo = null; if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanInfoSupport.class.getName(), "getNotification(String)", "Entry"); } if (inName == null) { throw new RuntimeOperationsException( new IllegalArgumentException("Notification name is null"), "Exception occurred trying to get the " + "ModelMBeanNotificationInfo of the MBean"); } MBeanNotificationInfo[] notifList = modelMBeanNotifications; //this.getNotifications(); int numNotifs = 0; if (notifList != null) numNotifs = notifList.length; for (int i=0; (i < numNotifs) && (retInfo == null); i++) { if (inName.equals(notifList[i].getName())) { retInfo = ((ModelMBeanNotificationInfo) notifList[i].clone()); } } if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanInfoSupport.class.getName(), "getNotification(String)", "Exit"); } return retInfo; } /* We override MBeanInfo.getDescriptor() to return our descriptor. */ /** {@collect.stats} * @since 1.6 */ @Override public Descriptor getDescriptor() { return getMBeanDescriptorNoException(); } public Descriptor getMBeanDescriptor() throws MBeanException { return getMBeanDescriptorNoException(); } private Descriptor getMBeanDescriptorNoException() { if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanInfoSupport.class.getName(), "getMBeanDescriptorNoException()", "Entry"); } if (modelMBeanDescriptor == null) modelMBeanDescriptor = createDefaultDescriptor(); if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanInfoSupport.class.getName(), "getMBeanDescriptorNoException()", "Exit, returning: " + modelMBeanDescriptor); } return (Descriptor) modelMBeanDescriptor.clone(); } public void setMBeanDescriptor(Descriptor inMBeanDescriptor) throws MBeanException, RuntimeOperationsException { if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanInfoSupport.class.getName(), "setMBeanDescriptor(Descriptor)", "Entry"); } if (inMBeanDescriptor == null) { if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanInfoSupport.class.getName(), "setMBeanDescriptor(Descriptor)", "MBean Descriptor is not valid"); } modelMBeanDescriptor = createDefaultDescriptor(); } else { if (isValidDescriptor(inMBeanDescriptor)) { modelMBeanDescriptor = (Descriptor) inMBeanDescriptor.clone(); addDefaultFields(); } else { throw new RuntimeOperationsException( new IllegalArgumentException("Invalid descriptor " + "passed in parameter")); } } } /* The default descriptor is: * name=mbeanName,descriptorType=mbean, displayName=this.getClassName(), * persistPolicy=never,log=F,visibility=1 */ private Descriptor createDefaultDescriptor() { Descriptor dftDesc = null; dftDesc = new DescriptorSupport(new String[] { ("name=" + this.getClassName()), "descriptorType=mbean", ("displayName=" + this.getClassName()), "persistPolicy=never", "log=F", "visibility=1"}); return dftDesc; } /* * Validates the ModelMBeanDescriptor * If the descriptor does not contain all these fields, * they will be added with these default values. * name=mbeanName,descriptorType=mbean, displayName=this.getClassName(), * persistPolicy=never,log=F,visibility=1 * * Will return false if the MBeanDescriptor has a null name or descriptorType. */ private boolean isValidDescriptor(Descriptor inDesc) { String badField = null; // if name != mbi.getClassName // if (descriptorType != mbean) // look for displayName, persistPolicy, logging, visibility and add in if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanInfoSupport.class.getName(), "isValidDescriptor(Descriptor)", "Validating descriptor: " + inDesc); } if (inDesc == null) badField = "nullDescriptor"; else if (!inDesc.isValid()) // checks for empty descriptors, null, // checks for empty name and descriptorType and // valid values for fields. badField="InvalidDescriptor"; else if ((((String)inDesc.getFieldValue("name")) == null)) badField="name"; else if (! ((String)inDesc.getFieldValue("descriptorType")) .equalsIgnoreCase(MMB)) badField="descriptorType"; else { // no bad fields if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanInfoSupport.class.getName(), "isValidDescriptor(Descriptor)", "Exit, returning true"); } return true; } if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanInfoSupport.class.getName(), "isValidDescriptor(Descriptor)", "returning false: invalid field is " + badField); } return false; } private void addDefaultFields() { final Descriptor d = modelMBeanDescriptor; if ((d.getFieldValue("displayName")) == null) d.setField("displayName",this.getClassName()); if ((d.getFieldValue("persistPolicy")) == null) d.setField("persistPolicy","never"); if ((d.getFieldValue("log")) == null) d.setField("log","F"); if ((d.getFieldValue("visibility")) == null) d.setField("visibility","1"); } /** {@collect.stats} * Deserializes a {@link ModelMBeanInfoSupport} from an {@link ObjectInputStream}. */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { if (compat) { // Read an object serialized in the old serial form // ObjectInputStream.GetField fields = in.readFields(); modelMBeanDescriptor = (Descriptor) fields.get("modelMBeanDescriptor", null); if (fields.defaulted("modelMBeanDescriptor")) { throw new NullPointerException("modelMBeanDescriptor"); } modelMBeanAttributes = (MBeanAttributeInfo[]) fields.get("mmbAttributes", null); if (fields.defaulted("mmbAttributes")) { throw new NullPointerException("mmbAttributes"); } modelMBeanConstructors = (MBeanConstructorInfo[]) fields.get("mmbConstructors", null); if (fields.defaulted("mmbConstructors")) { throw new NullPointerException("mmbConstructors"); } modelMBeanNotifications = (MBeanNotificationInfo[]) fields.get("mmbNotifications", null); if (fields.defaulted("mmbNotifications")) { throw new NullPointerException("mmbNotifications"); } modelMBeanOperations = (MBeanOperationInfo[]) fields.get("mmbOperations", null); if (fields.defaulted("mmbOperations")) { throw new NullPointerException("mmbOperations"); } } else { // Read an object serialized in the new serial form // in.defaultReadObject(); } } /** {@collect.stats} * Serializes a {@link ModelMBeanInfoSupport} to an {@link ObjectOutputStream}. */ private void writeObject(ObjectOutputStream out) throws IOException { if (compat) { // Serializes this instance in the old serial form // ObjectOutputStream.PutField fields = out.putFields(); fields.put("modelMBeanDescriptor", modelMBeanDescriptor); fields.put("mmbAttributes", modelMBeanAttributes); fields.put("mmbConstructors", modelMBeanConstructors); fields.put("mmbNotifications", modelMBeanNotifications); fields.put("mmbOperations", modelMBeanOperations); fields.put("currClass", currClass); out.writeFields(); } else { // Serializes this instance in the new serial form // out.defaultWriteObject(); } } }
Java
/* * Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ /* * @author IBM Corp. * * Copyright IBM Corp. 1999-2000. All rights reserved. */ package javax.management.modelmbean; import javax.management.Attribute; import javax.management.AttributeChangeNotification; import javax.management.ListenerNotFoundException; import javax.management.MBeanException; import javax.management.Notification; import javax.management.NotificationBroadcaster; import javax.management.NotificationListener; import javax.management.RuntimeOperationsException; /** {@collect.stats} * This interface must be implemented by the ModelMBeans. An implementation of this interface * must be shipped with every JMX Agent. * <P> * Java resources wishing to be manageable instantiate the ModelMBean using the MBeanServer's * createMBean method. The resource then sets the ModelMBeanInfo (with Descriptors) for the ModelMBean * instance. The attributes and operations exposed via the ModelMBeanInfo for the ModelMBean are accessible * from MBeans, connectors/adaptors like other MBeans. Through the ModelMBeanInfo Descriptors, values and methods in * the managed application can be defined and mapped to attributes and operations of the ModelMBean. * This mapping can be defined during development in an XML formatted file or dynamically and * programmatically at runtime. * <P> * Every ModelMBean which is instantiated in the MBeanServer becomes manageable: * its attributes and operations * become remotely accessible through the connectors/adaptors connected to that MBeanServer. * A Java object cannot be registered in the MBeanServer unless it is a JMX compliant MBean. * By instantiating a ModelMBean, resources are guaranteed that the MBean is valid. * <P> * MBeanException and RuntimeOperationsException must be thrown on every public method. This allows * for wrapping exceptions from distributed communications (RMI, EJB, etc.). These exceptions do * not have to be thrown by the implementation except in the scenarios described in the specification * and javadoc. * * @since 1.5 */ public interface ModelMBeanNotificationBroadcaster extends NotificationBroadcaster { /** {@collect.stats} * Sends a Notification which is passed in to the registered * Notification listeners on the ModelMBean as a * jmx.modelmbean.generic notification. * * @param ntfyObj The notification which is to be passed to * the 'handleNotification' method of the listener object. * * @exception MBeanException Wraps a distributed communication Exception. * @exception RuntimeOperationsException Wraps an IllegalArgumentException: * The Notification object passed in parameter is null. * */ public void sendNotification(Notification ntfyObj) throws MBeanException, RuntimeOperationsException; /** {@collect.stats} * Sends a Notification which contains the text string that is passed in * to the registered Notification listeners on the ModelMBean. * * @param ntfyText The text which is to be passed in the Notification to the 'handleNotification' * method of the listener object. * the constructed Notification will be: * type "jmx.modelmbean.generic" * source this ModelMBean instance * sequence 1 * * * @exception MBeanException Wraps a distributed communication Exception. * @exception RuntimeOperationsException Wraps an IllegalArgumentException: * The Notification text string passed in parameter is null. * */ public void sendNotification(String ntfyText) throws MBeanException, RuntimeOperationsException; /** {@collect.stats} * Sends an attributeChangeNotification which is passed in to * the registered attributeChangeNotification listeners on the * ModelMBean. * * @param notification The notification which is to be passed * to the 'handleNotification' method of the listener object. * * @exception MBeanException Wraps a distributed communication Exception. * @exception RuntimeOperationsException Wraps an IllegalArgumentException: The AttributeChangeNotification object passed in parameter is null. * */ public void sendAttributeChangeNotification(AttributeChangeNotification notification) throws MBeanException, RuntimeOperationsException; /** {@collect.stats} * Sends an attributeChangeNotification which contains the old value and new value for the * attribute to the registered AttributeChangeNotification listeners on the ModelMBean. * <P> * @param oldValue The original value for the Attribute * @param newValue The current value for the Attribute *<P> * <PRE> * The constructed attributeChangeNotification will be: * type "jmx.attribute.change" * source this ModelMBean instance * sequence 1 * attributeName oldValue.getName() * attributeType oldValue's class * attributeOldValue oldValue.getValue() * attributeNewValue newValue.getValue() * </PRE> * * @exception MBeanException Wraps a distributed communication Exception. * @exception RuntimeOperationsException Wraps an IllegalArgumentException: An Attribute object passed in parameter is null * or the names of the two Attribute objects in parameter are not the same. */ public void sendAttributeChangeNotification(Attribute oldValue, Attribute newValue) throws MBeanException, RuntimeOperationsException; /** {@collect.stats} * Registers an object which implements the NotificationListener interface as a listener. This * object's 'handleNotification()' method will be invoked when any attributeChangeNotification is issued through * or by the ModelMBean. This does not include other Notifications. They must be registered * for independently. An AttributeChangeNotification will be generated for this attributeName. * * @param listener The listener object which will handles notifications emitted by the registered MBean. * @param attributeName The name of the ModelMBean attribute for which to receive change notifications. * If null, then all attribute changes will cause an attributeChangeNotification to be issued. * @param handback The context to be sent to the listener with the notification when a notification is emitted. * * @exception IllegalArgumentException The listener cannot be null. * @exception MBeanException Wraps a distributed communication Exception. * @exception RuntimeOperationsException Wraps an IllegalArgumentException The attribute name passed in parameter does not exist. * * @see #removeAttributeChangeNotificationListener */ public void addAttributeChangeNotificationListener(NotificationListener listener, String attributeName, Object handback) throws MBeanException, RuntimeOperationsException, IllegalArgumentException; /** {@collect.stats} * Removes a listener for attributeChangeNotifications from the RequiredModelMBean. * * @param listener The listener name which was handling notifications emitted by the registered MBean. * This method will remove all information related to this listener. * @param attributeName The attribute for which the listener no longer wants to receive attributeChangeNotifications. * If null the listener will be removed for all attributeChangeNotifications. * * @exception ListenerNotFoundException The listener is not registered in the MBean or is null. * @exception MBeanException Wraps a distributed communication Exception. * @exception RuntimeOperationsException Wraps an IllegalArgumentException If the inAttributeName parameter does not * correspond to an attribute name. * * @see #addAttributeChangeNotificationListener */ public void removeAttributeChangeNotificationListener(NotificationListener listener, String attributeName) throws MBeanException, RuntimeOperationsException, ListenerNotFoundException; }
Java
/* * Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ /* * @author IBM Corp. * * Copyright IBM Corp. 1999-2000. All rights reserved. */ package javax.management.modelmbean; import static com.sun.jmx.defaults.JmxProperties.MODELMBEAN_LOGGER; import com.sun.jmx.mbeanserver.GetPropertyAction; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.ObjectStreamField; import java.lang.reflect.Method; import java.security.AccessController; import java.util.logging.Level; import javax.management.Descriptor; import javax.management.DescriptorAccess; import javax.management.DescriptorKey; import javax.management.MBeanOperationInfo; import javax.management.MBeanParameterInfo; import javax.management.RuntimeOperationsException; /** {@collect.stats} * The ModelMBeanOperationInfo object describes a management operation of the ModelMBean. * It is a subclass of MBeanOperationInfo with the addition of an associated Descriptor * and an implementation of the DescriptorAccess interface. * <P> * <PRE> * The fields in the descriptor are defined, but not limited to, the following: * name : operation name * descriptorType : must be "operation" * class : class where method is defined (fully qualified) * role : must be "operation", "getter", or "setter * targetObject : object on which to execute this method * targetType : type of object reference for targetObject. Can be: ObjectReference | Handle | EJBHandle | IOR | RMIReference. * value : cached value for operation * currencyTimeLimit : how long cached value is valid * lastUpdatedTimeStamp : when cached value was set * visibility : 1-4 where 1: always visible 4: rarely visible * presentationString : xml formatted string to describe how to present operation * </PRE> * The default descriptor will have name, descriptorType, displayName and role fields set. * * <p><b>Note:</b> because of inconsistencies in previous versions of * this specification, it is recommended not to use negative or zero * values for <code>currencyTimeLimit</code>. To indicate that a * cached value is never valid, omit the * <code>currencyTimeLimit</code> field. To indicate that it is * always valid, use a very large number for this field.</p> * * <p>The <b>serialVersionUID</b> of this class is <code>6532732096650090465L</code>. * * @since 1.5 */ @SuppressWarnings("serial") // serialVersionUID is not constant public class ModelMBeanOperationInfo extends MBeanOperationInfo implements DescriptorAccess { // Serialization compatibility stuff: // Two serial forms are supported in this class. The selected form depends // on system property "jmx.serial.form": // - "1.0" for JMX 1.0 // - any other value for JMX 1.1 and higher // // Serial version for old serial form private static final long oldSerialVersionUID = 9087646304346171239L; // // Serial version for new serial form private static final long newSerialVersionUID = 6532732096650090465L; // // Serializable fields in old serial form private static final ObjectStreamField[] oldSerialPersistentFields = { new ObjectStreamField("operationDescriptor", Descriptor.class), new ObjectStreamField("currClass", String.class) }; // // Serializable fields in new serial form private static final ObjectStreamField[] newSerialPersistentFields = { new ObjectStreamField("operationDescriptor", Descriptor.class) }; // // Actual serial version and serial form private static final long serialVersionUID; /** {@collect.stats} * @serialField operationDescriptor Descriptor The descriptor containing the appropriate metadata for this instance */ private static final ObjectStreamField[] serialPersistentFields; private static boolean compat = false; static { try { GetPropertyAction act = new GetPropertyAction("jmx.serial.form"); String form = AccessController.doPrivileged(act); compat = (form != null && form.equals("1.0")); } catch (Exception e) { // OK: No compat with 1.0 } if (compat) { serialPersistentFields = oldSerialPersistentFields; serialVersionUID = oldSerialVersionUID; } else { serialPersistentFields = newSerialPersistentFields; serialVersionUID = newSerialVersionUID; } } // // END Serialization compatibility stuff /** {@collect.stats} * @serial The descriptor containing the appropriate metadata for this instance */ private Descriptor operationDescriptor = createDefaultDescriptor(); private static final String currClass = "ModelMBeanOperationInfo"; /** {@collect.stats} * Constructs a ModelMBeanOperationInfo object with a default * descriptor. The {@link Descriptor} of the constructed * object will include fields contributed by any annotations * on the {@code Method} object that contain the {@link * DescriptorKey} meta-annotation. * * @param operationMethod The java.lang.reflect.Method object * describing the MBean operation. * @param description A human readable description of the operation. */ public ModelMBeanOperationInfo(String description, Method operationMethod) { super(description, operationMethod); // create default descriptor if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanOperationInfo.class.getName(), "ModelMBeanOperationInfo(String,Method)", "Entry"); } operationDescriptor = createDefaultDescriptor(); } /** {@collect.stats} * Constructs a ModelMBeanOperationInfo object. The {@link * Descriptor} of the constructed object will include fields * contributed by any annotations on the {@code Method} object * that contain the {@link DescriptorKey} meta-annotation. * * @param operationMethod The java.lang.reflect.Method object * describing the MBean operation. * @param description A human readable description of the * operation. * @param descriptor An instance of Descriptor containing the * appropriate metadata for this instance of the * ModelMBeanOperationInfo. If it is null a default * descriptor will be created. If the descriptor does not * contain the fields "displayName" or "role" these fields are * added in the descriptor with their default values. * * @exception RuntimeOperationsException Wraps an * IllegalArgumentException. The descriptor is invalid; or * descriptor field "name" is not equal to operation name; or * descriptor field "DescriptorType" is not equal to * "operation"; or descriptor optional field "role" is not equal to * "operation", "getter", or "setter". * */ public ModelMBeanOperationInfo(String description, Method operationMethod, Descriptor descriptor) { super(description, operationMethod); if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanOperationInfo.class.getName(), "ModelMBeanOperationInfo(String,Method,Descriptor)", "Entry"); } if (descriptor == null) { if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanOperationInfo.class.getName(), "ModelMBeanOperationInfo(" + "String, Method, Descriptor)", "Received null for new descriptor value, " + "setting descriptor to default values"); } operationDescriptor = createDefaultDescriptor(); } else { if (isValid(descriptor)) { operationDescriptor = (Descriptor) descriptor.clone(); } else { operationDescriptor = createDefaultDescriptor(); throw new RuntimeOperationsException(new IllegalArgumentException("Invalid descriptor passed in parameter"), ("Exception occurred in ModelMBeanOperationInfo constructor")); } } } /** {@collect.stats} * Constructs a ModelMBeanOperationInfo object with a default descriptor. * * @param name The name of the method. * @param description A human readable description of the operation. * @param signature MBeanParameterInfo objects describing the parameters(arguments) of the method. * @param type The type of the method's return value. * @param impact The impact of the method, one of INFO, ACTION, ACTION_INFO, UNKNOWN. */ public ModelMBeanOperationInfo(String name, String description, MBeanParameterInfo[] signature, String type, int impact) { super(name, description, signature, type, impact); // create default descriptor if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanOperationInfo.class.getName(), "ModelMBeanOperationInfo(" + "String,String,MBeanParameterInfo[],String,int)", "Entry"); } operationDescriptor = createDefaultDescriptor(); } /** {@collect.stats} * Constructs a ModelMBeanOperationInfo object. * * @param name The name of the method. * @param description A human readable description of the operation. * @param signature MBeanParameterInfo objects describing the parameters(arguments) of the method. * @param type The type of the method's return value. * @param impact The impact of the method, one of INFO, ACTION, ACTION_INFO, UNKNOWN. * @param descriptor An instance of Descriptor containing the appropriate metadata. * for this instance of the MBeanOperationInfo.If it is null then a default descriptor will be created. * If the descriptor does not contain the fields * "displayName" or "role" these fields are added in the descriptor with their default values. * * @exception RuntimeOperationsException Wraps an * IllegalArgumentException. The descriptor is invalid; or * descriptor field "name" is not equal to operation name; or * descriptor field "DescriptorType" is not equal to * "operation"; or descriptor optional field "role" is not equal to * "operation", "getter", or "setter". */ public ModelMBeanOperationInfo(String name, String description, MBeanParameterInfo[] signature, String type, int impact, Descriptor descriptor) { super(name, description, signature, type, impact); if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanOperationInfo.class.getName(), "ModelMBeanOperationInfo(String,String," + "MBeanParameterInfo[],String,int,Descriptor)", "Entry"); } if (descriptor == null) { if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanOperationInfo.class.getName(), "ModelMBeanOperationInfo()", "Received null for new descriptor value, " + "setting descriptor to default values"); } operationDescriptor = createDefaultDescriptor(); } else { if (isValid(descriptor)) { operationDescriptor = (Descriptor) descriptor.clone(); } else { operationDescriptor = createDefaultDescriptor(); throw new RuntimeOperationsException(new IllegalArgumentException("Invalid descriptor passed in parameter"), ("Exception occurred in ModelMBeanOperationInfo constructor")); } } } /** {@collect.stats} * Constructs a new ModelMBeanOperationInfo object from this ModelMBeanOperation Object. * * @param inInfo the ModelMBeanOperationInfo to be duplicated * */ public ModelMBeanOperationInfo(ModelMBeanOperationInfo inInfo) { super(inInfo.getName(), inInfo.getDescription(), inInfo.getSignature(), inInfo.getReturnType(), inInfo.getImpact()); if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanOperationInfo.class.getName(), "ModelMBeanOperationInfo(ModelMBeanOperationInfo)", "Entry"); } Descriptor newDesc = inInfo.getDescriptor(); if (newDesc == null) { operationDescriptor = createDefaultDescriptor(); } else { if (isValid(newDesc)) { operationDescriptor = (Descriptor) newDesc.clone(); } else { operationDescriptor = createDefaultDescriptor(); throw new RuntimeOperationsException(new IllegalArgumentException("Invalid descriptor passed in parameter"), ("Exception occurred in ModelMBeanOperationInfo constructor")); } } } /** {@collect.stats} * Creates and returns a new ModelMBeanOperationInfo which is a duplicate of this ModelMBeanOperationInfo. * */ public Object clone () { if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanOperationInfo.class.getName(), "clone()", "Entry"); } return(new ModelMBeanOperationInfo(this)) ; } /** {@collect.stats} * Returns a copy of the associated Descriptor of the * ModelMBeanOperationInfo. * * @return Descriptor associated with the * ModelMBeanOperationInfo object. * * @see #setDescriptor */ public Descriptor getDescriptor() { if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanOperationInfo.class.getName(), "getDescriptor()", "Entry"); } if (operationDescriptor == null) { operationDescriptor = createDefaultDescriptor(); } return((Descriptor) operationDescriptor.clone()); } /** {@collect.stats} * Sets associated Descriptor (full replace) for the * ModelMBeanOperationInfo If the new Descriptor is null, then * the associated Descriptor reverts to a default descriptor. * The Descriptor is validated before it is assigned. If the * new Descriptor is invalid, then a * RuntimeOperationsException wrapping an * IllegalArgumentException is thrown. * * @param inDescriptor replaces the Descriptor associated with the * ModelMBeanOperation. * * @exception RuntimeOperationsException Wraps an * IllegalArgumentException for invalid Descriptor. * * @see #getDescriptor */ public void setDescriptor(Descriptor inDescriptor) { if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanOperationInfo.class.getName(), "setDescriptor(Descriptor)", "Entry"); } if (inDescriptor == null) { if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanOperationInfo.class.getName(), "setDescriptor()", "Received null for new descriptor value, " + "setting descriptor to default values"); } operationDescriptor = createDefaultDescriptor(); } else { if (isValid(inDescriptor)) { operationDescriptor = (Descriptor) inDescriptor.clone(); } else { throw new RuntimeOperationsException(new IllegalArgumentException("Invalid descriptor passed in parameter"), ("Exception occurred in ModelMBeanOperationInfo setDescriptor")); } } } /** {@collect.stats} * Returns a string containing the entire contents of the ModelMBeanOperationInfo in human readable form. */ public String toString() { if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanOperationInfo.class.getName(), "toString()", "Entry"); } String retStr = "ModelMBeanOperationInfo: " + this.getName() + " ; Description: " + this.getDescription() + " ; Descriptor: " + this.getDescriptor() + " ; ReturnType: " + this.getReturnType() + " ; Signature: "; MBeanParameterInfo[] pTypes = this.getSignature(); for (int i=0; i < pTypes.length; i++) { retStr = retStr.concat((pTypes[i]).getType() + ", "); } return retStr; } /** {@collect.stats} * Creates default descriptor for operation as follows: * descriptorType=operation,role=operation, name=this.getName(),displayname=this.getName(). */ private Descriptor createDefaultDescriptor() { if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanOperationInfo.class.getName(), "createDefaultDescriptor()", "Entry"); } return new DescriptorSupport(new String[] {"descriptorType=operation", ("name=" + this.getName()), "role=operation", ("displayname=" + this.getName())}); } /** {@collect.stats} * Tests that the descriptor is valid and adds appropriate * default fields not already specified. Field values must be * correct for field names. descriptorType field must be * "operation". We do not check the targetType because a * custom implementation of ModelMBean could recognize * additional types beyond the "standard" ones. The following * fields will be defaulted if they are not already set: * role=operation,displayName=this.getName() */ private boolean isValid(Descriptor inDesc) { boolean results = true; String badField = "none"; // if name != this.getName // if (descriptorType != operation) // look for displayName, persistPolicy, visibility and add in if (inDesc == null) { results = false; } else if (!inDesc.isValid()) { // checks for empty descriptors, null, // checks for empty name and descriptorType // and valid values for fields. results = false; } else { if (! ((String)inDesc.getFieldValue("name")).equalsIgnoreCase(this.getName())) { results = false; } if (! ((String)inDesc.getFieldValue("descriptorType")).equalsIgnoreCase("operation")) { results = false; } Object roleValue = inDesc.getFieldValue("role"); if (roleValue == null) { inDesc.setField("role","operation"); } else { final String role = (String)roleValue; if (!(role.equalsIgnoreCase("operation") || role.equalsIgnoreCase("setter") || role.equalsIgnoreCase("getter"))) { results = false; badField="role"; } } Object targetValue = inDesc.getFieldValue("targetType"); if (targetValue != null) { if (!(targetValue instanceof java.lang.String)) { results = false; badField="targetType"; } } if ((inDesc.getFieldValue("displayName")) == null) { inDesc.setField("displayName",this.getName()); } } if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanOperationInfo.class.getName(), "isValid()", "Returning " + results + " : Invalid field is " + badField); } return results; } /** {@collect.stats} * Deserializes a {@link ModelMBeanOperationInfo} from an {@link ObjectInputStream}. */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { // New serial form ignores extra field "currClass" in.defaultReadObject(); } /** {@collect.stats} * Serializes a {@link ModelMBeanOperationInfo} to an {@link ObjectOutputStream}. */ private void writeObject(ObjectOutputStream out) throws IOException { if (compat) { // Serializes this instance in the old serial form // ObjectOutputStream.PutField fields = out.putFields(); fields.put("operationDescriptor", operationDescriptor); fields.put("currClass", currClass); out.writeFields(); } else { // Serializes this instance in the new serial form // out.defaultWriteObject(); } } }
Java
/* * Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ /* * @author IBM Corp. * * Copyright IBM Corp. 1999-2000. All rights reserved. */ package javax.management.modelmbean; import static com.sun.jmx.defaults.JmxProperties.MODELMBEAN_LOGGER; import com.sun.jmx.mbeanserver.GetPropertyAction; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.ObjectStreamField; import java.lang.reflect.Constructor; import java.security.AccessController; import java.util.logging.Level; import javax.management.Descriptor; import javax.management.DescriptorAccess; import javax.management.DescriptorKey; import javax.management.MBeanConstructorInfo; import javax.management.MBeanParameterInfo; import javax.management.RuntimeOperationsException; /** {@collect.stats} * The ModelMBeanConstructorInfo object describes a constructor of the ModelMBean. * It is a subclass of MBeanConstructorInfo with the addition of an associated Descriptor * and an implementation of the DescriptorAccess interface. * <P> * <PRE> * The fields in the descriptor are defined, but not limited to, the following: <P> * name : constructor name * descriptorType : must be "operation" * role : must be "constructor" * displayName : human readable name of constructor * visibility : 1-4 where 1: always visible 4: rarely visible * presentationString : xml formatted string to describe how to present operation *</PRE> * * <p>The {@code persistPolicy} and {@code currencyTimeLimit} fields * are meaningless for constructors, but are not considered invalid. * * <p>The default descriptor will have the {@code name}, {@code * descriptorType}, {@code displayName} and {@code role} fields. * * <p>The <b>serialVersionUID</b> of this class is <code>3862947819818064362L</code>. * * @since 1.5 */ @SuppressWarnings("serial") // serialVersionUID is not constant public class ModelMBeanConstructorInfo extends MBeanConstructorInfo implements DescriptorAccess { // Serialization compatibility stuff: // Two serial forms are supported in this class. The selected form depends // on system property "jmx.serial.form": // - "1.0" for JMX 1.0 // - any other value for JMX 1.1 and higher // // Serial version for old serial form private static final long oldSerialVersionUID = -4440125391095574518L; // // Serial version for new serial form private static final long newSerialVersionUID = 3862947819818064362L; // // Serializable fields in old serial form private static final ObjectStreamField[] oldSerialPersistentFields = { new ObjectStreamField("consDescriptor", Descriptor.class), new ObjectStreamField("currClass", String.class) }; // // Serializable fields in new serial form private static final ObjectStreamField[] newSerialPersistentFields = { new ObjectStreamField("consDescriptor", Descriptor.class) }; // // Actual serial version and serial form private static final long serialVersionUID; /** {@collect.stats} * @serialField consDescriptor Descriptor The {@link Descriptor} containing the metadata for this instance */ private static final ObjectStreamField[] serialPersistentFields; private static boolean compat = false; static { try { GetPropertyAction act = new GetPropertyAction("jmx.serial.form"); String form = AccessController.doPrivileged(act); compat = (form != null && form.equals("1.0")); } catch (Exception e) { // OK: No compat with 1.0 } if (compat) { serialPersistentFields = oldSerialPersistentFields; serialVersionUID = oldSerialVersionUID; } else { serialPersistentFields = newSerialPersistentFields; serialVersionUID = newSerialVersionUID; } } // // END Serialization compatibility stuff /** {@collect.stats} * @serial The {@link Descriptor} containing the metadata for this instance */ private Descriptor consDescriptor = createDefaultDescriptor(); private final static String currClass = "ModelMBeanConstructorInfo"; /** {@collect.stats} * Constructs a ModelMBeanConstructorInfo object with a default * descriptor. The {@link Descriptor} of the constructed * object will include fields contributed by any annotations on * the {@code Constructor} object that contain the {@link * DescriptorKey} meta-annotation. * * @param description A human readable description of the constructor. * @param constructorMethod The java.lang.reflect.Constructor object * describing the MBean constructor. */ public ModelMBeanConstructorInfo(String description, Constructor constructorMethod) { super(description, constructorMethod); if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanConstructorInfo.class.getName(), "ModelMBeanConstructorInfo(String,Constructor)", "Entry"); } consDescriptor = createDefaultDescriptor(); // put getter and setter methods in constructors list // create default descriptor } /** {@collect.stats} * Constructs a ModelMBeanConstructorInfo object. The {@link * Descriptor} of the constructed object will include fields * contributed by any annotations on the {@code Constructor} * object that contain the {@link DescriptorKey} * meta-annotation. * * @param description A human readable description of the constructor. * @param constructorMethod The java.lang.reflect.Constructor object * describing the ModelMBean constructor. * @param descriptor An instance of Descriptor containing the * appropriate metadata for this instance of the * ModelMBeanConstructorInfo. If it is null, then a default * descriptor will be created.If the descriptor does not * contain the field "displayName" this fields is added in the * descriptor with its default value. * * @exception RuntimeOperationsException Wraps an * IllegalArgumentException. The descriptor is invalid, or * descriptor field "name" is not equal to name parameter, or * descriptor field "DescriptorType" is not equal to * "operation" or descriptor field "role" is not equal to * "constructor". */ public ModelMBeanConstructorInfo(String description, Constructor constructorMethod, Descriptor descriptor) { super(description, constructorMethod); // put getter and setter methods in constructors list if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanConstructorInfo.class.getName(), "ModelMBeanConstructorInfo(" + "String,Constructor,Descriptor)", "Entry"); } if (descriptor == null) { if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanConstructorInfo.class.getName(), "ModelMBeanConstructorInfo(" + "String,Constructor,Descriptor)", "Descriptor passed in is null, " + "setting descriptor to default values"); } consDescriptor = createDefaultDescriptor(); } else { if (isValid(descriptor)) { consDescriptor = (Descriptor) descriptor.clone(); } else { // exception consDescriptor = createDefaultDescriptor(); throw new RuntimeOperationsException(new IllegalArgumentException("Invalid descriptor passed in parameter"), ("Exception occurred in ModelMBeanConstructorInfo constructor")); } } } /** {@collect.stats} * Constructs a ModelMBeanConstructorInfo object with a default descriptor. * * @param name The name of the constructor. * @param description A human readable description of the constructor. * @param signature MBeanParameterInfo object array describing the parameters(arguments) of the constructor. */ public ModelMBeanConstructorInfo(String name, String description, MBeanParameterInfo[] signature) { super(name, description, signature); // create default descriptor if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanConstructorInfo.class.getName(), "ModelMBeanConstructorInfo(" + "String,String,MBeanParameterInfo[])", "Entry"); } consDescriptor = createDefaultDescriptor(); } /** {@collect.stats} * Constructs a ModelMBeanConstructorInfo object. * * @param name The name of the constructor. * @param description A human readable description of the constructor. * @param signature MBeanParameterInfo objects describing the parameters(arguments) of the constructor. * @param descriptor An instance of Descriptor containing the appropriate metadata * for this instance of the MBeanConstructorInfo. If it is null then a default descriptor will be created. * If the descriptor does not contain the field "displayName" this field is added in the descriptor with its default value. * * @exception RuntimeOperationsException Wraps an IllegalArgumentException. The descriptor is invalid, or descriptor field "name" * is not equal to name parameter, or descriptor field "DescriptorType" is not equal to "operation" or descriptor field "role" * is not equal to "constructor". */ public ModelMBeanConstructorInfo(String name, String description, MBeanParameterInfo[] signature, Descriptor descriptor) { super(name, description, signature); if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanConstructorInfo.class.getName(), "ModelMBeanConstructorInfo(" + "String,String,MBeanParameterInfo[],Descriptor)", "Entry"); } if (descriptor == null) { if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanConstructorInfo.class.getName(), "ModelMBeanConstructorInfo(" + "String,Method,Descriptor)", "Descriptor passed in is null, " + "setting descriptor to default values"); } consDescriptor = createDefaultDescriptor(); } else { if (isValid(descriptor)) { consDescriptor = (Descriptor) descriptor.clone(); } else { // exception consDescriptor = createDefaultDescriptor(); throw new RuntimeOperationsException(new IllegalArgumentException("Invalid descriptor passed in parameter"), ("Exception occurred in ModelMBeanConstructorInfo constructor")); } } } /** {@collect.stats} * Constructs a new ModelMBeanConstructorInfo object from this ModelMBeanConstructor Object. * * @param old the ModelMBeanConstructorInfo to be duplicated * */ ModelMBeanConstructorInfo(ModelMBeanConstructorInfo old) { super(old.getName(), old.getDescription(), old.getSignature()); if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanConstructorInfo.class.getName(), "ModelMBeanConstructorInfo(" + "ModelMBeanConstructorInfo)", "Entry"); } if (old.consDescriptor == null) { if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanConstructorInfo.class.getName(), "ModelMBeanConstructorInfo(" + "String,Method,Descriptor)", "Existing descriptor passed in is null, " + "setting new descriptor to default values"); } consDescriptor = createDefaultDescriptor(); } else { if (isValid(consDescriptor)) { consDescriptor = (Descriptor) old.consDescriptor.clone(); } else { // exception consDescriptor = createDefaultDescriptor(); throw new RuntimeOperationsException(new IllegalArgumentException("Invalid descriptor passed in parameter"), ("Exception occurred in ModelMBeanConstructorInfo constructor")); } } } /** {@collect.stats} * Creates and returns a new ModelMBeanConstructorInfo which is a duplicate of this ModelMBeanConstructorInfo. * */ public Object clone () { if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanConstructorInfo.class.getName(), "clone()", "Entry"); } return(new ModelMBeanConstructorInfo(this)) ; } /** {@collect.stats} * Returns a copy of the associated Descriptor. * * @return Descriptor associated with the * ModelMBeanConstructorInfo object. * * @see #setDescriptor */ public Descriptor getDescriptor() { if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanConstructorInfo.class.getName(), "getDescriptor()", "Entry"); } if (consDescriptor == null) { consDescriptor = createDefaultDescriptor(); } return((Descriptor)consDescriptor.clone()); } /** {@collect.stats} * Sets associated Descriptor (full replace) of * ModelMBeanConstructorInfo. If the new Descriptor is null, * then the associated Descriptor reverts to a default * descriptor. The Descriptor is validated before it is * assigned. If the new Descriptor is invalid, then a * RuntimeOperationsException wrapping an * IllegalArgumentException is thrown. * * @param inDescriptor replaces the Descriptor associated with * the ModelMBeanConstructor. If the descriptor does not * contain the field "displayName" this field is added in the * descriptor with its default value. * * @exception RuntimeOperationsException Wraps an * IllegalArgumentException. The descriptor is invalid, or * descriptor field "name" is not equal to name parameter, or * descriptor field "DescriptorType" is not equal to * "operation" or descriptor field "role" is not equal to * "constructor". * * @see #getDescriptor */ public void setDescriptor(Descriptor inDescriptor) { if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanConstructorInfo.class.getName(), "setDescriptor()", "Entry"); } if (inDescriptor == null) { if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanConstructorInfo.class.getName(), "ModelMBeanConstructorInfo(" + "String,Method,Descriptor)", "Descriptor passed in is null, " + "setting descriptor to default values"); } consDescriptor = createDefaultDescriptor(); } else { if (isValid(inDescriptor)) { consDescriptor = (Descriptor) inDescriptor.clone(); } else { throw new RuntimeOperationsException(new IllegalArgumentException("Invalid descriptor passed in parameter"), ("Exception occurred in ModelMBeanConstructorInfo setDescriptor")); } } } /** {@collect.stats} * Returns a string containing the entire contents of the ModelMBeanConstructorInfo in human readable form. */ public String toString() { if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanConstructorInfo.class.getName(), "toString()", "Entry"); } String retStr = "ModelMBeanConstructorInfo: " + this.getName() + " ; Description: " + this.getDescription() + " ; Descriptor: " + this.getDescriptor() + " ; Signature: "; MBeanParameterInfo[] pTypes = this.getSignature(); for (int i=0; i < pTypes.length; i++) { retStr = retStr.concat((pTypes[i]).getType() + ", "); } return retStr; } /** {@collect.stats} * Creates default descriptor for constructor as follows: * descriptorType=operation,role=constructor, * name=this.getName(),displayname=this.getName(),visibility=1 */ private Descriptor createDefaultDescriptor() { if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanConstructorInfo.class.getName(), "createDefaultDescriptor()", "Entry"); } return new DescriptorSupport(new String[] {"descriptorType=operation", "role=constructor", ("name=" + this.getName()), ("displayname=" + this.getName())}); } /** {@collect.stats} * Tests that the descriptor is valid and adds appropriate default fields not already * specified. Field values must be correct for field names. * Descriptor must have the same name as the operation,the descriptorType field must * be "operation", the role field must be set to "constructor". * The following fields will be defaulted if they are not already set: * displayName=this.getName() */ private boolean isValid(Descriptor inDesc) { boolean results = true; String badField="none"; // if name != this.getName // if (descriptorType != operation) // look for displayName, persistPolicy, visibility and add in if (inDesc == null) { badField="nullDescriptor"; results = false; } else if (!inDesc.isValid()) { // checks for empty descriptors, null, // checks for empty name and descriptorType adn valid values for fields. badField="invalidDescriptor"; results = false; } else { if (! ((String)inDesc.getFieldValue("name")).equalsIgnoreCase(this.getName())) { badField="name"; results = false; } if (! ((String)inDesc.getFieldValue("descriptorType")).equalsIgnoreCase("operation")) { badField="descriptorType"; results = false; } if (inDesc.getFieldValue("role") == null) { inDesc.setField("role","constructor"); } if (! ((String)inDesc.getFieldValue("role")).equalsIgnoreCase("constructor")) { badField = "role"; results = false; } else if ((inDesc.getFieldValue("displayName")) == null) { inDesc.setField("displayName",this.getName()); } } if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanConstructorInfo.class.getName(), "isValid(Descriptor)", "Returning " + results + " : Invalid field is " + badField); } return results; } /** {@collect.stats} * Deserializes a {@link ModelMBeanConstructorInfo} from an {@link ObjectInputStream}. */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { // New serial form ignores extra field "currClass" in.defaultReadObject(); } /** {@collect.stats} * Serializes a {@link ModelMBeanConstructorInfo} to an {@link ObjectOutputStream}. */ private void writeObject(ObjectOutputStream out) throws IOException { if (compat) { // Serializes this instance in the old serial form // ObjectOutputStream.PutField fields = out.putFields(); fields.put("consDescriptor", consDescriptor); fields.put("currClass", currClass); out.writeFields(); } else { // Serializes this instance in the new serial form // out.defaultWriteObject(); } } }
Java
/* * Copyright (c) 2000, 2007, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ /* * @author IBM Corp. * * Copyright IBM Corp. 1999-2000. All rights reserved. */ package javax.management.modelmbean; /* java imports */ import static com.sun.jmx.defaults.JmxProperties.MODELMBEAN_LOGGER; import java.io.FileOutputStream; import java.io.PrintStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.logging.Level; import java.util.Map; import java.util.Set; import javax.management.Attribute; import javax.management.AttributeChangeNotification; import javax.management.AttributeChangeNotificationFilter; import javax.management.AttributeList; import javax.management.AttributeNotFoundException; import javax.management.Descriptor; import javax.management.InstanceNotFoundException; import javax.management.InvalidAttributeValueException; import javax.management.ListenerNotFoundException; import javax.management.MBeanAttributeInfo; import javax.management.MBeanConstructorInfo; import javax.management.MBeanException; import javax.management.MBeanInfo; import javax.management.MBeanNotificationInfo; import javax.management.MBeanOperationInfo; import javax.management.MBeanRegistration; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import javax.management.Notification; import javax.management.NotificationBroadcasterSupport; import javax.management.NotificationEmitter; import javax.management.NotificationFilter; import javax.management.NotificationListener; import javax.management.ObjectName; import javax.management.ReflectionException; import javax.management.RuntimeErrorException; import javax.management.RuntimeOperationsException; import javax.management.ServiceNotFoundException; import javax.management.loading.ClassLoaderRepository; import sun.reflect.misc.MethodUtil; import sun.reflect.misc.ReflectUtil; /** {@collect.stats} * This class is the implementation of a ModelMBean. An appropriate * implementation of a ModelMBean must be shipped with every JMX Agent * and the class must be named RequiredModelMBean. * <P> * Java resources wishing to be manageable instantiate the * RequiredModelMBean using the MBeanServer's createMBean method. * The resource then sets the MBeanInfo and Descriptors for the * RequiredModelMBean instance. The attributes and operations exposed * via the ModelMBeanInfo for the ModelMBean are accessible * from MBeans, connectors/adaptors like other MBeans. Through the * Descriptors, values and methods in the managed application can be * defined and mapped to attributes and operations of the ModelMBean. * This mapping can be defined in an XML formatted file or dynamically and * programmatically at runtime. * <P> * Every RequiredModelMBean which is instantiated in the MBeanServer * becomes manageable:<br> * its attributes and operations become remotely accessible through the * connectors/adaptors connected to that MBeanServer. * <P> * A Java object cannot be registered in the MBeanServer unless it is a * JMX compliant MBean. By instantiating a RequiredModelMBean, resources * are guaranteed that the MBean is valid. * * MBeanException and RuntimeOperationsException must be thrown on every * public method. This allows for wrapping exceptions from distributed * communications (RMI, EJB, etc.) * * @since 1.5 */ public class RequiredModelMBean implements ModelMBean, MBeanRegistration, NotificationEmitter { /** {@collect.stats}***********************************/ /* attributes */ /** {@collect.stats}***********************************/ ModelMBeanInfo modelMBeanInfo; /* Notification broadcaster for any notification to be sent * from the application through the RequiredModelMBean. */ private NotificationBroadcasterSupport generalBroadcaster = null; /* Notification broadcaster for attribute change notifications */ private NotificationBroadcasterSupport attributeBroadcaster = null; /* handle, name, or reference for instance on which the actual invoke * and operations will be executed */ private Object managedResource = null; private static final String currClass = "RequiredModelMBean"; /* records the registering in MBeanServer */ private boolean registered = false; private transient MBeanServer server = null; /** {@collect.stats}***********************************/ /* constructors */ /** {@collect.stats}***********************************/ /** {@collect.stats} * Constructs an <CODE>RequiredModelMBean</CODE> with an empty * ModelMBeanInfo. * <P> * The RequiredModelMBean's MBeanInfo and Descriptors * can be customized using the {@link #setModelMBeanInfo} method. * After the RequiredModelMBean's MBeanInfo and Descriptors are * customized, the RequiredModelMBean can be registered with * the MBeanServer. * * @exception MBeanException Wraps a distributed communication Exception. * * @exception RuntimeOperationsException Wraps a {@link * RuntimeException} during the construction of the object. **/ public RequiredModelMBean() throws MBeanException, RuntimeOperationsException { if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), "RequiredModelMBean()", "Entry"); } modelMBeanInfo = createDefaultModelMBeanInfo(); if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), "RequiredModelMBean()", "Exit"); } } /** {@collect.stats} * Constructs a RequiredModelMBean object using ModelMBeanInfo passed in. * As long as the RequiredModelMBean is not registered * with the MBeanServer yet, the RequiredModelMBean's MBeanInfo and * Descriptors can be customized using the {@link #setModelMBeanInfo} * method. * After the RequiredModelMBean's MBeanInfo and Descriptors are * customized, the RequiredModelMBean can be registered with the * MBeanServer. * * @param mbi The ModelMBeanInfo object to be used by the * RequiredModelMBean. The given ModelMBeanInfo is cloned * and modified as specified by {@link #setModelMBeanInfo} * * @exception MBeanException Wraps a distributed communication Exception. * @exception RuntimeOperationsException Wraps an * {link java.lang.IllegalArgumentException}: * The MBeanInfo passed in parameter is null. * **/ public RequiredModelMBean(ModelMBeanInfo mbi) throws MBeanException, RuntimeOperationsException { if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), "RequiredModelMBean(MBeanInfo)", "Entry"); } setModelMBeanInfo(mbi); if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), "RequiredModelMBean(MBeanInfo)", "Exit"); } } /** {@collect.stats}***********************************/ /* initializers */ /** {@collect.stats}***********************************/ /** {@collect.stats} * Initializes a ModelMBean object using ModelMBeanInfo passed in. * This method makes it possible to set a customized ModelMBeanInfo on * the ModelMBean as long as it is not registered with the MBeanServer. * <br> * Once the ModelMBean's ModelMBeanInfo (with Descriptors) are * customized and set on the ModelMBean, the ModelMBean be * registered with the MBeanServer. * <P> * If the ModelMBean is currently registered, this method throws * a {@link javax.management.RuntimeOperationsException} wrapping an * {@link IllegalStateException} * <P> * If the given <var>inModelMBeanInfo</var> does not contain any * {@link ModelMBeanNotificationInfo} for the <code>GENERIC</code> * or <code>ATTRIBUTE_CHANGE</code> notifications, then the * RequiredModelMBean will supply its own default * {@link ModelMBeanNotificationInfo ModelMBeanNotificationInfo}s for * those missing notifications. * * @param mbi The ModelMBeanInfo object to be used * by the ModelMBean. * * @exception MBeanException Wraps a distributed communication * Exception. * @exception RuntimeOperationsException * <ul><li>Wraps an {@link IllegalArgumentException} if * the MBeanInfo passed in parameter is null.</li> * <li>Wraps an {@link IllegalStateException} if the ModelMBean * is currently registered in the MBeanServer.</li> * </ul> * **/ public void setModelMBeanInfo(ModelMBeanInfo mbi) throws MBeanException, RuntimeOperationsException { if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), "setModelMBeanInfo(ModelMBeanInfo)","Entry"); } if (mbi == null) { if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), "setModelMBeanInfo(ModelMBeanInfo)", "ModelMBeanInfo is null: Raising exception."); } final RuntimeException x = new IllegalArgumentException("ModelMBeanInfo must not be null"); final String exceptionText = "Exception occurred trying to initialize the " + "ModelMBeanInfo of the RequiredModelMBean"; throw new RuntimeOperationsException(x,exceptionText); } if (registered) { if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), "setModelMBeanInfo(ModelMBeanInfo)", "RequiredMBean is registered: Raising exception."); } final String exceptionText = "Exception occurred trying to set the " + "ModelMBeanInfo of the RequiredModelMBean"; final RuntimeException x = new IllegalStateException( "cannot call setModelMBeanInfo while ModelMBean is registered"); throw new RuntimeOperationsException(x,exceptionText); } if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), "setModelMBeanInfo(ModelMBeanInfo)", "Setting ModelMBeanInfo to " + printModelMBeanInfo(mbi)); MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), "setModelMBeanInfo(ModelMBeanInfo)", "ModelMBeanInfo notifications has " + (mbi.getNotifications()).length + " elements"); } modelMBeanInfo = (ModelMBeanInfo)mbi.clone(); if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), "setModelMBeanInfo(ModelMBeanInfo)","set mbeanInfo to: "+ printModelMBeanInfo(modelMBeanInfo)); MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), "setModelMBeanInfo(ModelMBeanInfo)","Exit"); } } /** {@collect.stats} * Sets the instance handle of the object against which to * execute all methods in this ModelMBean management interface * (MBeanInfo and Descriptors). * * @param mr Object that is the managed resource * @param mr_type The type of reference for the managed resource. * <br>Can be: "ObjectReference", "Handle", "IOR", "EJBHandle", * or "RMIReference". * <br>In this implementation only "ObjectReference" is supported. * * @exception MBeanException The initializer of the object has * thrown an exception. * @exception InstanceNotFoundException The managed resource * object could not be found * @exception InvalidTargetObjectTypeException The managed * resource type should be "ObjectReference". * @exception RuntimeOperationsException Wraps a {@link * RuntimeException} when setting the resource. **/ public void setManagedResource(Object mr, String mr_type) throws MBeanException, RuntimeOperationsException, InstanceNotFoundException, InvalidTargetObjectTypeException { if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), "setManagedResource(Object,String)","Entry"); } // check that the mr_type is supported by this JMXAgent // only "objectReference" is supported if ((mr_type == null) || (! mr_type.equalsIgnoreCase("objectReference"))) { if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), "setManagedResource(Object,String)", "Managed Resouce Type is not supported: " + mr_type); } throw new InvalidTargetObjectTypeException(mr_type); } if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), "setManagedResource(Object,String)", "Managed Resouce is valid"); } managedResource = mr; if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), "setManagedResource(Object, String)", "Exit"); } } /** {@collect.stats} * <p>Instantiates this MBean instance with the data found for * the MBean in the persistent store. The data loaded could include * attribute and operation values.</p> * * <p>This method should be called during construction or * initialization of this instance, and before the MBean is * registered with the MBeanServer.</p> * * <p>If the implementation of this class does not support * persistence, an {@link MBeanException} wrapping a {@link * ServiceNotFoundException} is thrown.</p> * * @exception MBeanException Wraps another exception, or * persistence is not supported * @exception RuntimeOperationsException Wraps exceptions from the * persistence mechanism * @exception InstanceNotFoundException Could not find or load * this MBean from persistent storage */ public void load() throws MBeanException, RuntimeOperationsException, InstanceNotFoundException { final ServiceNotFoundException x = new ServiceNotFoundException( "Persistence not supported for this MBean"); throw new MBeanException(x, x.getMessage()); } /** {@collect.stats} * <p>Captures the current state of this MBean instance and writes * it out to the persistent store. The state stored could include * attribute and operation values.</p> * * <p>If the implementation of this class does not support * persistence, an {@link MBeanException} wrapping a {@link * ServiceNotFoundException} is thrown.</p> * * <p>Persistence policy from the MBean and attribute descriptor * is used to guide execution of this method. The MBean should be * stored if 'persistPolicy' field is:</p> * * <PRE> != "never" * = "always" * = "onTimer" and now > 'lastPersistTime' + 'persistPeriod' * = "NoMoreOftenThan" and now > 'lastPersistTime' + 'persistPeriod' * = "onUnregister" * </PRE> * * <p>Do not store the MBean if 'persistPolicy' field is:</p> * <PRE> * = "never" * = "onUpdate" * = "onTimer" && now < 'lastPersistTime' + 'persistPeriod' * </PRE> * * @exception MBeanException Wraps another exception, or * persistence is not supported * @exception RuntimeOperationsException Wraps exceptions from the * persistence mechanism * @exception InstanceNotFoundException Could not find/access the * persistent store */ public void store() throws MBeanException, RuntimeOperationsException, InstanceNotFoundException { final ServiceNotFoundException x = new ServiceNotFoundException( "Persistence not supported for this MBean"); throw new MBeanException(x, x.getMessage()); } /** {@collect.stats}***********************************/ /* DynamicMBean Interface */ /** {@collect.stats}***********************************/ /** {@collect.stats} * The resolveForCacheValue method checks the descriptor passed in to * see if there is a valid cached value in the descriptor. * The valid value will be in the 'value' field if there is one. * If the 'currencyTimeLimit' field in the descriptor is: * <ul> * <li><b>&lt;0</b> Then the value is not cached and is never valid. * Null is returned. The 'value' and 'lastUpdatedTimeStamp' * fields are cleared.</li> * <li><b>=0</b> Then the value is always cached and always valid. * The 'value' field is returned. * The 'lastUpdatedTimeStamp' field is not checked.</li> * <li><b>&gt;0</b> Represents the number of seconds that the * 'value' field is valid. * The 'value' field is no longer valid when * 'lastUpdatedTimeStamp' + 'currencyTimeLimit' &gt; Now.</li> * </ul> * <li>When 'value' is valid, 'valid' is returned.</li> * <li>When 'value' is no longer valid then null is returned and * 'value' and 'lastUpdatedTimeStamp' fields are cleared.</li> * **/ private Object resolveForCacheValue(Descriptor descr) throws MBeanException, RuntimeOperationsException { final boolean tracing = MODELMBEAN_LOGGER.isLoggable(Level.FINER); final String mth = "resolveForCacheValue(Descriptor)"; if (tracing) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(),mth,"Entry"); } Object response = null; boolean resetValue = false, returnCachedValue = true; long currencyPeriod = 0; if (descr == null) { if (tracing) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(),mth, "Input Descriptor is null"); } return response; } if (tracing) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "descriptor is " + descr); } final Descriptor mmbDescr = modelMBeanInfo.getMBeanDescriptor(); if (mmbDescr == null) { if (tracing) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth,"MBean Descriptor is null"); } //return response; } Object objExpTime = descr.getFieldValue("currencyTimeLimit"); String expTime; if (objExpTime != null) { expTime = objExpTime.toString(); } else { expTime = null; } if ((expTime == null) && (mmbDescr != null)) { objExpTime = mmbDescr.getFieldValue("currencyTimeLimit"); if (objExpTime != null) { expTime = objExpTime.toString(); } else { expTime = null; } } if (expTime != null) { if (tracing) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth,"currencyTimeLimit: " + expTime); } // convert seconds to milliseconds for time comparison currencyPeriod = ((new Long(expTime)).longValue()) * 1000; if (currencyPeriod < 0) { /* if currencyTimeLimit is -1 then value is never cached */ returnCachedValue = false; resetValue = true; if (tracing) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(),mth, currencyPeriod + ": never Cached"); } } else if (currencyPeriod == 0) { /* if currencyTimeLimit is 0 then value is always cached */ returnCachedValue = true; resetValue = false; if (tracing) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(),mth, "always valid Cache"); } } else { Object objtStamp = descr.getFieldValue("lastUpdatedTimeStamp"); String tStamp; if (objtStamp != null) tStamp = objtStamp.toString(); else tStamp = null; if (tracing) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(),mth, "lastUpdatedTimeStamp: " + tStamp); } if (tStamp == null) tStamp = "0"; long lastTime = (new Long(tStamp)).longValue(); if (tracing) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(),mth, "currencyPeriod:" + currencyPeriod + " lastUpdatedTimeStamp:" + lastTime); } long now = (new Date()).getTime(); if (now < (lastTime + currencyPeriod)) { returnCachedValue = true; resetValue = false; if (tracing) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(),mth, " timed valid Cache for " + now + " < " + (lastTime + currencyPeriod)); } } else { /* value is expired */ returnCachedValue = false; resetValue = true; if (tracing) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(),mth, "timed expired cache for " + now + " > " + (lastTime + currencyPeriod)); } } } if (tracing) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(),mth, "returnCachedValue:" + returnCachedValue + " resetValue: " + resetValue); } if (returnCachedValue == true) { Object currValue = descr.getFieldValue("value"); if (currValue != null) { /* error/validity check return value here */ response = currValue; /* need to cast string cached value to type */ if (tracing) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(),mth, "valid Cache value: " + currValue); } } else { response = null; if (tracing) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth,"no Cached value"); } } } if (resetValue == true) { /* value is not current, so remove it */ descr.removeField("lastUpdatedTimeStamp"); descr.removeField("value"); response = null; modelMBeanInfo.setDescriptor(descr,null); if (tracing) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth,"reset cached value to null"); } } } if (tracing) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(),mth,"Exit"); } return response; } /** {@collect.stats} * Returns the attributes, operations, constructors and notifications * that this RequiredModelMBean exposes for management. * * @return An instance of ModelMBeanInfo allowing retrieval all * attributes, operations, and Notifications of this MBean. * **/ public MBeanInfo getMBeanInfo() { if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), "getMBeanInfo()","Entry"); } if (modelMBeanInfo == null) { if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), "getMBeanInfo()","modelMBeanInfo is null"); } modelMBeanInfo = createDefaultModelMBeanInfo(); //return new ModelMBeanInfo(" ", "", null, null, null, null); } if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), "getMBeanInfo()","ModelMBeanInfo is " + modelMBeanInfo.getClassName() + " for " + modelMBeanInfo.getDescription()); MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), "getMBeanInfo()",printModelMBeanInfo(modelMBeanInfo)); } return((MBeanInfo) modelMBeanInfo.clone()); } private String printModelMBeanInfo(ModelMBeanInfo info) { final StringBuilder retStr = new StringBuilder(); if (info == null) { if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), "printModelMBeanInfo(ModelMBeanInfo)", "ModelMBeanInfo to print is null, " + "printing local ModelMBeanInfo"); } info = modelMBeanInfo; } retStr.append("\nMBeanInfo for ModelMBean is:"); retStr.append("\nCLASSNAME: \t"+ info.getClassName()); retStr.append("\nDESCRIPTION: \t"+ info.getDescription()); try { retStr.append("\nMBEAN DESCRIPTOR: \t"+ info.getMBeanDescriptor()); } catch (Exception e) { retStr.append("\nMBEAN DESCRIPTOR: \t" + " is invalid"); } retStr.append("\nATTRIBUTES"); final MBeanAttributeInfo[] attrInfo = info.getAttributes(); if ((attrInfo != null) && (attrInfo.length>0)) { for (int i=0; i<attrInfo.length; i++) { final ModelMBeanAttributeInfo attInfo = (ModelMBeanAttributeInfo)attrInfo[i]; retStr.append(" ** NAME: \t"+ attInfo.getName()); retStr.append(" DESCR: \t"+ attInfo.getDescription()); retStr.append(" TYPE: \t"+ attInfo.getType() + " READ: \t"+ attInfo.isReadable() + " WRITE: \t"+ attInfo.isWritable()); retStr.append(" DESCRIPTOR: " + attInfo.getDescriptor().toString()); } } else { retStr.append(" ** No attributes **"); } retStr.append("\nCONSTRUCTORS"); final MBeanConstructorInfo[] constrInfo = info.getConstructors(); if ((constrInfo != null) && (constrInfo.length > 0 )) { for (int i=0; i<constrInfo.length; i++) { final ModelMBeanConstructorInfo ctorInfo = (ModelMBeanConstructorInfo)constrInfo[i]; retStr.append(" ** NAME: \t"+ ctorInfo.getName()); retStr.append(" DESCR: \t"+ ctorInfo.getDescription()); retStr.append(" PARAM: \t"+ ctorInfo.getSignature().length + " parameter(s)"); retStr.append(" DESCRIPTOR: " + ctorInfo.getDescriptor().toString()); } } else { retStr.append(" ** No Constructors **"); } retStr.append("\nOPERATIONS"); final MBeanOperationInfo[] opsInfo = info.getOperations(); if ((opsInfo != null) && (opsInfo.length>0)) { for (int i=0; i<opsInfo.length; i++) { final ModelMBeanOperationInfo operInfo = (ModelMBeanOperationInfo)opsInfo[i]; retStr.append(" ** NAME: \t"+ operInfo.getName()); retStr.append(" DESCR: \t"+ operInfo.getDescription()); retStr.append(" PARAM: \t"+ operInfo.getSignature().length + " parameter(s)"); retStr.append(" DESCRIPTOR: " + operInfo.getDescriptor().toString()); } } else { retStr.append(" ** No operations ** "); } retStr.append("\nNOTIFICATIONS"); MBeanNotificationInfo[] notifInfo = info.getNotifications(); if ((notifInfo != null) && (notifInfo.length>0)) { for (int i=0; i<notifInfo.length; i++) { final ModelMBeanNotificationInfo nInfo = (ModelMBeanNotificationInfo)notifInfo[i]; retStr.append(" ** NAME: \t"+ nInfo.getName()); retStr.append(" DESCR: \t"+ nInfo.getDescription()); retStr.append(" DESCRIPTOR: " + nInfo.getDescriptor().toString()); } } else { retStr.append(" ** No notifications **"); } retStr.append(" ** ModelMBean: End of MBeanInfo ** "); return retStr.toString(); } /** {@collect.stats} * Invokes a method on or through a RequiredModelMBean and returns * the result of the method execution. * <P> * If the given method to be invoked, together with the provided * signature, matches one of RequiredModelMbean * accessible methods, this one will be call. Otherwise the call to * the given method will be tried on the managed resource. * <P> * The last value returned by an operation may be cached in * the operation's descriptor which * is in the ModelMBeanOperationInfo's descriptor. * The valid value will be in the 'value' field if there is one. * If the 'currencyTimeLimit' field in the descriptor is: * <UL> * <LI><b>&lt;0</b> Then the value is not cached and is never valid. * The operation method is invoked. * The 'value' and 'lastUpdatedTimeStamp' fields are cleared.</LI> * <LI><b>=0</b> Then the value is always cached and always valid. * The 'value' field is returned. If there is no 'value' field * then the operation method is invoked for the attribute. * The 'lastUpdatedTimeStamp' field and `value' fields are set to * the operation's return value and the current time stamp.</LI> * <LI><b>&gt;0</b> Represents the number of seconds that the 'value' * field is valid. * The 'value' field is no longer valid when * 'lastUpdatedTimeStamp' + 'currencyTimeLimit' &gt; Now. * <UL> * <LI>When 'value' is valid, 'value' is returned.</LI> * <LI>When 'value' is no longer valid then the operation * method is invoked. The 'lastUpdatedTimeStamp' field * and `value' fields are updated.</lI> * </UL> * </LI> * </UL> * * <p><b>Note:</b> because of inconsistencies in previous versions of * this specification, it is recommended not to use negative or zero * values for <code>currencyTimeLimit</code>. To indicate that a * cached value is never valid, omit the * <code>currencyTimeLimit</code> field. To indicate that it is * always valid, use a very large number for this field.</p> * * @param opName The name of the method to be invoked. The * name can be the fully qualified method name including the * classname, or just the method name if the classname is * defined in the 'class' field of the operation descriptor. * @param opArgs An array containing the parameters to be set * when the operation is invoked * @param sig An array containing the signature of the * operation. The class objects will be loaded using the same * class loader as the one used for loading the MBean on which * the operation was invoked. * * @return The object returned by the method, which represents the * result of invoking the method on the specified managed resource. * * @exception MBeanException Wraps one of the following Exceptions: * <UL> * <LI> An Exception thrown by the managed object's invoked method.</LI> * <LI> {@link ServiceNotFoundException}: No ModelMBeanOperationInfo or * no descriptor defined for the specified operation or the managed * resource is null.</LI> * <LI> {@link InvalidTargetObjectTypeException}: The 'targetType' * field value is not 'objectReference'.</LI> * </UL> * @exception ReflectionException Wraps an {@link java.lang.Exception} * thrown while trying to invoke the method. * @exception RuntimeOperationsException Wraps an * {@link IllegalArgumentException} Method name is null. * **/ /* The requirement to be able to invoke methods on the RequiredModelMBean class itself makes this method considerably more complicated than it might otherwise be. Note that, unlike earlier versions, we do not allow you to invoke such methods if they are not explicitly mentioned in the ModelMBeanInfo. Doing so was potentially a security problem, and certainly very surprising. We do not look for the method in the RequiredModelMBean class itself if: (a) there is a "targetObject" field in the Descriptor for the operation; or (b) there is a "class" field in the Descriptor for the operation and the named class is not RequiredModelMBean or one of its superinterfaces; or (c) the name of the operation is not the name of a method in RequiredModelMBean (this is just an optimization). In cases (a) and (b), if you have gone to the trouble of adding those fields specifically for this operation then presumably you do not want RequiredModelMBean's methods to be called. We have to pay attention to class loading issues. If the "class" field is present, the named class has to be resolved relative to RequiredModelMBean's class loader to test the condition (b) above, and relative to the managed resource's class loader to ensure that the managed resource is in fact of the named class (or a subclass). The class names in the sig array likewise have to be resolved, first against RequiredModelMBean's class loader, then against the managed resource's class loader. There is no point in using any other loader because when we call Method.invoke we must call it on a Method that is implemented by the target object. */ public Object invoke(String opName, Object[] opArgs, String[] sig) throws MBeanException, ReflectionException { final boolean tracing = MODELMBEAN_LOGGER.isLoggable(Level.FINER); final String mth = "invoke(String, Object[], String[])"; if (tracing) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "Entry"); } if (opName == null) { final RuntimeException x = new IllegalArgumentException("Method name must not be null"); throw new RuntimeOperationsException(x, "An exception occurred while trying to " + "invoke a method on a RequiredModelMBean"); } String opClassName = null; String opMethodName; // Parse for class name and method int opSplitter = opName.lastIndexOf("."); if (opSplitter > 0) { opClassName = opName.substring(0,opSplitter); opMethodName = opName.substring(opSplitter+1); } else opMethodName = opName; /* Ignore anything after a left paren. We keep this for compatibility but it isn't specified. */ opSplitter = opMethodName.indexOf("("); if (opSplitter > 0) opMethodName = opMethodName.substring(0,opSplitter); if (tracing) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "Finding operation " + opName + " as " + opMethodName); } ModelMBeanOperationInfo opInfo = modelMBeanInfo.getOperation(opMethodName); if (opInfo == null) { final String msg = "Operation " + opName + " not in ModelMBeanInfo"; throw new MBeanException(new ServiceNotFoundException(msg), msg); } final Descriptor opDescr = opInfo.getDescriptor(); if (opDescr == null) { final String msg = "Operation descriptor null"; throw new MBeanException(new ServiceNotFoundException(msg), msg); } final Object cached = resolveForCacheValue(opDescr); if (cached != null) { if (tracing) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "Returning cached value"); } return cached; } if (opClassName == null) opClassName = (String) opDescr.getFieldValue("class"); // may still be null now opMethodName = (String) opDescr.getFieldValue("name"); if (opMethodName == null) { final String msg = "Method descriptor must include `name' field"; throw new MBeanException(new ServiceNotFoundException(msg), msg); } final String targetTypeField = (String) opDescr.getFieldValue("targetType"); if (targetTypeField != null && !targetTypeField.equalsIgnoreCase("objectReference")) { final String msg = "Target type must be objectReference: " + targetTypeField; throw new MBeanException(new InvalidTargetObjectTypeException(msg), msg); } final Object targetObjectField = opDescr.getFieldValue("targetObject"); if (tracing && targetObjectField != null) MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "Found target object in descriptor"); /* Now look for the method, either in RequiredModelMBean itself or in the target object. Set "method" and "targetObject" appropriately. */ Method method; Object targetObject; method = findRMMBMethod(opMethodName, targetObjectField, opClassName, sig); if (method != null) targetObject = this; else { if (tracing) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "looking for method in managedResource class"); } if (targetObjectField != null) targetObject = targetObjectField; else { targetObject = managedResource; if (targetObject == null) { final String msg = "managedResource for invoke " + opName + " is null"; Exception snfe = new ServiceNotFoundException(msg); throw new MBeanException(snfe); } } final Class targetClass; if (opClassName != null) { try { final ClassLoader targetClassLoader = targetObject.getClass().getClassLoader(); targetClass = Class.forName(opClassName, false, targetClassLoader); } catch (ClassNotFoundException e) { final String msg = "class for invoke " + opName + " not found"; throw new ReflectionException(e, msg); } } else targetClass = targetObject.getClass(); method = resolveMethod(targetClass, opMethodName, sig); } if (tracing) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "found " + opMethodName + ", now invoking"); } final Object result = invokeMethod(opName, method, targetObject, opArgs); if (tracing) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "successfully invoked method"); } if (result != null) cacheResult(opInfo, opDescr, result); return result; } private static Method resolveMethod(Class<?> targetClass, String opMethodName, String[] sig) throws ReflectionException { final boolean tracing = MODELMBEAN_LOGGER.isLoggable(Level.FINER); if (tracing) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(),"resolveMethod", "resolving " + targetClass + "." + opMethodName); } final Class[] argClasses; if (sig == null) argClasses = null; else { final ClassLoader targetClassLoader = targetClass.getClassLoader(); argClasses = new Class[sig.length]; for (int i = 0; i < sig.length; i++) { if (tracing) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(),"resolveMethod", "resolve type " + sig[i]); } argClasses[i] = (Class) primitiveClassMap.get(sig[i]); if (argClasses[i] == null) { try { argClasses[i] = Class.forName(sig[i], false, targetClassLoader); } catch (ClassNotFoundException e) { if (tracing) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), "resolveMethod", "class not found"); } final String msg = "Parameter class not found"; throw new ReflectionException(e, msg); } } } } try { return targetClass.getMethod(opMethodName, argClasses); } catch (NoSuchMethodException e) { final String msg = "Target method not found: " + targetClass.getName() + "." + opMethodName; throw new ReflectionException(e, msg); } } /* Map e.g. "int" to int.class. Goodness knows how many time this particular wheel has been reinvented. */ private static final Class[] primitiveClasses = { int.class, long.class, boolean.class, double.class, float.class, short.class, byte.class, char.class, }; private static final Map<String,Class<?>> primitiveClassMap = new HashMap<String,Class<?>>(); static { for (int i = 0; i < primitiveClasses.length; i++) { final Class c = primitiveClasses[i]; primitiveClassMap.put(c.getName(), c); } } /* Find a method in RequiredModelMBean as determined by the given parameters. Return null if there is none, or if the parameters exclude using it. Called from invoke. */ private static Method findRMMBMethod(String opMethodName, Object targetObjectField, String opClassName, String[] sig) { final boolean tracing = MODELMBEAN_LOGGER.isLoggable(Level.FINER); if (tracing) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), "invoke(String, Object[], String[])", "looking for method in RequiredModelMBean class"); } if (!isRMMBMethodName(opMethodName)) return null; if (targetObjectField != null) return null; final Class<RequiredModelMBean> rmmbClass = RequiredModelMBean.class; final Class<?> targetClass; if (opClassName == null) targetClass = rmmbClass; else { try { final ClassLoader targetClassLoader = rmmbClass.getClassLoader(); targetClass = Class.forName(opClassName, false, targetClassLoader); if (!rmmbClass.isAssignableFrom(targetClass)) return null; } catch (ClassNotFoundException e) { return null; } } try { return resolveMethod(targetClass, opMethodName, sig); } catch (ReflectionException e) { return null; } } /* * Invoke the given method, and throw the somewhat unpredictable * appropriate exception if the method itself gets an exception. */ private Object invokeMethod(String opName, Method method, Object targetObject, Object[] opArgs) throws MBeanException, ReflectionException { try { ReflectUtil.checkPackageAccess(method.getDeclaringClass()); return MethodUtil.invoke(method, targetObject, opArgs); } catch (RuntimeErrorException ree) { throw new RuntimeOperationsException(ree, "RuntimeException occurred in RequiredModelMBean "+ "while trying to invoke operation " + opName); } catch (RuntimeException re) { throw new RuntimeOperationsException(re, "RuntimeException occurred in RequiredModelMBean "+ "while trying to invoke operation " + opName); } catch (IllegalAccessException iae) { throw new ReflectionException(iae, "IllegalAccessException occurred in " + "RequiredModelMBean while trying to " + "invoke operation " + opName); } catch (InvocationTargetException ite) { Throwable mmbTargEx = ite.getTargetException(); if (mmbTargEx instanceof RuntimeException) { throw new MBeanException ((RuntimeException)mmbTargEx, "RuntimeException thrown in RequiredModelMBean "+ "while trying to invoke operation " + opName); } else if (mmbTargEx instanceof Error) { throw new RuntimeErrorException((Error)mmbTargEx, "Error occurred in RequiredModelMBean while trying "+ "to invoke operation " + opName); } else if (mmbTargEx instanceof ReflectionException) { throw (ReflectionException) mmbTargEx; } else { throw new MBeanException ((Exception)mmbTargEx, "Exception thrown in RequiredModelMBean "+ "while trying to invoke operation " + opName); } } catch (Error err) { throw new RuntimeErrorException(err, "Error occurred in RequiredModelMBean while trying "+ "to invoke operation " + opName); } catch (Exception e) { throw new ReflectionException(e, "Exception occurred in RequiredModelMBean while " + "trying to invoke operation " + opName); } } /* * Cache the result of an operation in the descriptor, if that is * called for by the descriptor's configuration. Note that we * don't remember operation parameters when caching the result, so * this is unlikely to be useful if there are any. */ private void cacheResult(ModelMBeanOperationInfo opInfo, Descriptor opDescr, Object result) throws MBeanException { Descriptor mmbDesc = modelMBeanInfo.getMBeanDescriptor(); Object objctl = opDescr.getFieldValue("currencyTimeLimit"); String ctl; if (objctl != null) { ctl = objctl.toString(); } else { ctl = null; } if ((ctl == null) && (mmbDesc != null)) { objctl = mmbDesc.getFieldValue("currencyTimeLimit"); if (objctl != null) { ctl = objctl.toString(); } else { ctl = null; } } if ((ctl != null) && !(ctl.equals("-1"))) { opDescr.setField("value", result); opDescr.setField("lastUpdatedTimeStamp", String.valueOf((new Date()).getTime())); modelMBeanInfo.setDescriptor(opDescr, "operation"); if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), "invoke(String,Object[],Object[])", "new descriptor is " + opDescr); } } } /* * Determine whether the given name is the name of a public method * in this class. This is only an optimization: it prevents us * from trying to do argument type lookups and reflection on a * method that will obviously fail because it has the wrong name. * * The first time this method is called we do the reflection, and * every other time we reuse the remembered values. * * It's conceivable that the (possibly malicious) first caller * doesn't have the required permissions to do reflection, in * which case we don't touch anything so as not to interfere * with a later permissionful caller. */ private static Set<String> rmmbMethodNames; private static synchronized boolean isRMMBMethodName(String name) { if (rmmbMethodNames == null) { try { Set<String> names = new HashSet<String>(); Method[] methods = RequiredModelMBean.class.getMethods(); for (int i = 0; i < methods.length; i++) names.add(methods[i].getName()); rmmbMethodNames = names; } catch (Exception e) { return true; // This is only an optimization so we'll go on to discover // whether the name really is an RMMB method. } } return rmmbMethodNames.contains(name); } /** {@collect.stats} * Returns the value of a specific attribute defined for this * ModelMBean. * The last value returned by an attribute may be cached in the * attribute's descriptor. * The valid value will be in the 'value' field if there is one. * If the 'currencyTimeLimit' field in the descriptor is: * <UL> * <LI> <b>&lt;0</b> Then the value is not cached and is never valid. * The getter method is invoked for the attribute. * The 'value' and 'lastUpdatedTimeStamp' fields are cleared.</LI> * <LI> <b>=0</b> Then the value is always cached and always valid. * The 'value' field is returned. If there is no'value' field * then the getter method is invoked for the attribute. * The 'lastUpdatedTimeStamp' field and `value' fields are set * to the attribute's value and the current time stamp.</LI> * <LI> <b>&gt;0</b> Represents the number of seconds that the 'value' * field is valid. * The 'value' field is no longer valid when * 'lastUpdatedTimeStamp' + 'currencyTimeLimit' &gt; Now. * <UL> * <LI>When 'value' is valid, 'value' is returned.</LI> * <LI>When 'value' is no longer valid then the getter * method is invoked for the attribute. * The 'lastUpdatedTimeStamp' field and `value' fields * are updated.</LI> * </UL></LI> * </UL> * * <p><b>Note:</b> because of inconsistencies in previous versions of * this specification, it is recommended not to use negative or zero * values for <code>currencyTimeLimit</code>. To indicate that a * cached value is never valid, omit the * <code>currencyTimeLimit</code> field. To indicate that it is * always valid, use a very large number for this field.</p> * * <p>If the 'getMethod' field contains the name of a valid * operation descriptor, then the method described by the * operation descriptor is executed. The response from the * method is returned as the value of the attribute. If the * operation fails or the returned value is not compatible with * the declared type of the attribute, an exception will be thrown.</p> * * <p>If no 'getMethod' field is defined then the default value of the * attribute is returned. If the returned value is not compatible with * the declared type of the attribute, an exception will be thrown.</p> * * <p>The declared type of the attribute is the String returned by * {@link ModelMBeanAttributeInfo#getType()}. A value is compatible * with this type if one of the following is true: * <ul> * <li>the value is null;</li> * <li>the declared name is a primitive type name (such as "int") * and the value is an instance of the corresponding wrapper * type (such as java.lang.Integer);</li> * <li>the name of the value's class is identical to the declared name;</li> * <li>the declared name can be loaded by the value's class loader and * produces a class to which the value can be assigned.</li> * </ul> * * <p>In this implementation, in every case where the getMethod needs to * be called, because the method is invoked through the standard "invoke" * method and thus needs operationInfo, an operation must be specified * for that getMethod so that the invocation works correctly.</p> * * @param attrName A String specifying the name of the * attribute to be retrieved. It must match the name of a * ModelMBeanAttributeInfo. * * @return The value of the retrieved attribute from the * descriptor 'value' field or from the invocation of the * operation in the 'getMethod' field of the descriptor. * * @exception AttributeNotFoundException The specified attribute is * not accessible in the MBean. * The following cases may result in an AttributeNotFoundException: * <UL> * <LI> No ModelMBeanInfo was found for the Model MBean.</LI> * <LI> No ModelMBeanAttributeInfo was found for the specified * attribute name.</LI> * <LI> The ModelMBeanAttributeInfo isReadable method returns * 'false'.</LI> * </UL> * @exception MBeanException Wraps one of the following Exceptions: * <UL> * <LI> {@link InvalidAttributeValueException}: A wrong value type * was received from the attribute's getter method or * no 'getMethod' field defined in the descriptor for * the attribute and no default value exists.</LI> * <LI> {@link ServiceNotFoundException}: No * ModelMBeanOperationInfo defined for the attribute's * getter method or no descriptor associated with the * ModelMBeanOperationInfo or the managed resource is * null.</LI> * <LI> {@link InvalidTargetObjectTypeException} The 'targetType' * field value is not 'objectReference'.</LI> * <LI> An Exception thrown by the managed object's getter.</LI> * </UL> * @exception ReflectionException Wraps an {@link java.lang.Exception} * thrown while trying to invoke the getter. * @exception RuntimeOperationsException Wraps an * {@link IllegalArgumentException}: The attribute name in * parameter is null. * * @see #setAttribute(javax.management.Attribute) **/ public Object getAttribute(String attrName) throws AttributeNotFoundException, MBeanException, ReflectionException { if (attrName == null) throw new RuntimeOperationsException(new IllegalArgumentException("attributeName must not be null"), "Exception occurred trying to get attribute of a " + "RequiredModelMBean"); final String mth = "getAttribute(String)"; final boolean tracing = MODELMBEAN_LOGGER.isLoggable(Level.FINER); if (tracing) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "Entry with " + attrName); } /* Check attributeDescriptor for getMethod */ ModelMBeanAttributeInfo attrInfo=null; Descriptor attrDescr=null; Object response = null; try { if (modelMBeanInfo == null) throw new AttributeNotFoundException( "getAttribute failed: ModelMBeanInfo not found for "+ attrName); attrInfo = modelMBeanInfo.getAttribute(attrName); Descriptor mmbDesc = modelMBeanInfo.getMBeanDescriptor(); if (attrInfo == null) throw new AttributeNotFoundException("getAttribute failed:"+ " ModelMBeanAttributeInfo not found for " + attrName); attrDescr = attrInfo.getDescriptor(); if (attrDescr != null) { if (!attrInfo.isReadable()) throw new AttributeNotFoundException( "getAttribute failed: " + attrName + " is not readable "); response = resolveForCacheValue(attrDescr); /* return current cached value */ if (tracing) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "*** cached value is " + response); } if (response == null) { /* no cached value, run getMethod */ if (tracing) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "**** cached value is null - getting getMethod"); } String attrGetMethod = (String)(attrDescr.getFieldValue("getMethod")); if (attrGetMethod != null) { /* run method from operations descriptor */ if (tracing) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "invoking a getMethod for " + attrName); } Object getResponse = invoke(attrGetMethod, new Object[] {}, new String[] {}); if (getResponse != null) { // error/validity check return value here if (tracing) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "got a non-null response " + "from getMethod\n"); } response = getResponse; // change cached value in attribute descriptor Object objctl = attrDescr.getFieldValue("currencyTimeLimit"); String ctl; if (objctl != null) ctl = objctl.toString(); else ctl = null; if ((ctl == null) && (mmbDesc != null)) { objctl = mmbDesc. getFieldValue("currencyTimeLimit"); if (objctl != null) ctl = objctl.toString(); else ctl = null; } if ((ctl != null) && !(ctl.equals("-1"))) { if (tracing) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "setting cached value and " + "lastUpdatedTime in descriptor"); } attrDescr.setField("value", response); final String stamp = String.valueOf( (new Date()).getTime()); attrDescr.setField("lastUpdatedTimeStamp", stamp); attrInfo.setDescriptor(attrDescr); modelMBeanInfo.setDescriptor(attrDescr, "attribute"); if (tracing) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth,"new descriptor is " +attrDescr); MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth,"AttributeInfo descriptor is " + attrInfo.getDescriptor()); final String attStr = modelMBeanInfo. getDescriptor(attrName,"attribute"). toString(); MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "modelMBeanInfo: AttributeInfo " + "descriptor is " + attStr); } } } else { // response was invalid or really returned null if (tracing) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "got a null response from getMethod\n"); } response = null; } } else { // not getMethod so return descriptor (default) value String qualifier=""; response = attrDescr.getFieldValue("value"); if (response == null) { qualifier="default "; response = attrDescr.getFieldValue("default"); } if (tracing) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "could not find getMethod for " +attrName + ", returning descriptor " +qualifier + "value"); } // !! cast response to right class } } // make sure response class matches type field String respType = attrInfo.getType(); if (response != null) { String responseClass = response.getClass().getName(); if (!respType.equals(responseClass)) { boolean wrongType = false; boolean primitiveType = false; boolean correspondingTypes = false; for (int i = 0; i < primitiveTypes.length; i++) { if (respType.equals(primitiveTypes[i])) { primitiveType = true; if (responseClass.equals(primitiveWrappers[i])) correspondingTypes = true; break; } } if (primitiveType) { // inequality may come from primitive/wrapper class if (!correspondingTypes) wrongType = true; } else { // inequality may come from type subclassing boolean subtype; try { ClassLoader cl = response.getClass().getClassLoader(); Class c = Class.forName(respType, true, cl); subtype = c.isInstance(response); } catch (Exception e) { subtype = false; if (tracing) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "Exception: ",e); } } if (!subtype) wrongType = true; } if (wrongType) { if (tracing) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "Wrong response type '" + respType + "'"); } // throw exception, didn't get // back right attribute type throw new MBeanException( new InvalidAttributeValueException( "Wrong value type received for get attribute"), "An exception occurred while trying to get an " + "attribute value through a RequiredModelMBean"); } } } } else { if (tracing) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "getMethod failed " + attrName + " not in attributeDescriptor\n"); } throw new MBeanException(new InvalidAttributeValueException( "Unable to resolve attribute value, " + "no getMethod defined in descriptor for attribute"), "An exception occurred while trying to get an "+ "attribute value through a RequiredModelMBean"); } } catch (MBeanException mbe) { throw mbe; } catch (AttributeNotFoundException t) { throw t; } catch (Exception e) { if (tracing) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "getMethod failed with " + e.getMessage() + " exception type " + (e.getClass()).toString()); } throw new MBeanException(e,"An exception occurred while trying "+ "to get an attribute value: " + e.getMessage()); } if (tracing) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "Exit"); } return response; } /** {@collect.stats} * Returns the values of several attributes in the ModelMBean. * Executes a getAttribute for each attribute name in the * attrNames array passed in. * * @param attrNames A String array of names of the attributes * to be retrieved. * * @return The array of the retrieved attributes. * * @exception RuntimeOperationsException Wraps an * {@link IllegalArgumentException}: The object name in parameter is * null or attributes in parameter is null. * * @see #setAttributes(javax.management.AttributeList) */ public AttributeList getAttributes(String[] attrNames) { if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), "getAttributes(String[])","Entry"); } AttributeList responseList = null; if (attrNames == null) throw new RuntimeOperationsException(new IllegalArgumentException("attributeNames must not be null"), "Exception occurred trying to get attributes of a "+ "RequiredModelMBean"); responseList = new AttributeList(); for (int i = 0; i < attrNames.length; i++) { try { responseList.add(new Attribute(attrNames[i], getAttribute(attrNames[i]))); } catch (Exception e) { // eat exceptions because interface doesn't have an // exception on it if (MODELMBEAN_LOGGER.isLoggable(Level.WARNING)) { MODELMBEAN_LOGGER.logp(Level.WARNING, RequiredModelMBean.class.getName(), "getAttributes(String[])", "Failed to get \"" + attrNames[i] + "\": ", e); } } } if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), "getAttributes(String[])","Exit"); } return responseList; } /** {@collect.stats} * Sets the value of a specific attribute of a named ModelMBean. * * If the 'setMethod' field of the attribute's descriptor * contains the name of a valid operation descriptor, then the * method described by the operation descriptor is executed. * In this implementation, the operation descriptor must be specified * correctly and assigned to the modelMBeanInfo so that the 'setMethod' * works correctly. * The response from the method is set as the value of the attribute * in the descriptor. * * <p>If currencyTimeLimit is &gt; 0, then the new value for the * attribute is cached in the attribute descriptor's * 'value' field and the 'lastUpdatedTimeStamp' field is set to * the current time stamp. * * <p>If the persist field of the attribute's descriptor is not null * then Persistence policy from the attribute descriptor is used to * guide storing the attribute in a persistent store. * <br>Store the MBean if 'persistPolicy' field is: * <UL> * <Li> != "never"</Li> * <Li> = "always"</Li> * <Li> = "onUpdate"</Li> * <Li> = "onTimer" and now &gt; 'lastPersistTime' + 'persistPeriod'</Li> * <Li> = "NoMoreOftenThan" and now &gt; 'lastPersistTime' + * 'persistPeriod'</Li> * </UL> * Do not store the MBean if 'persistPolicy' field is: * <UL> * <Li> = "never"</Li> * <Li> = "onTimer" && now &lt; 'lastPersistTime' + 'persistPeriod'</Li> * <Li> = "onUnregister"</Li> * <Li> = "NoMoreOftenThan" and now &lt; 'lastPersistTime' + * 'persistPeriod'</Li> * </UL> * * <p>The ModelMBeanInfo of the Model MBean is stored in a file. * * @param attribute The Attribute instance containing the name of * the attribute to be set and the value it is to be set to. * * * @exception AttributeNotFoundException The specified attribute is * not accessible in the MBean. * <br>The following cases may result in an AttributeNotFoundException: * <UL> * <LI> No ModelMBeanAttributeInfo is found for the specified * attribute.</LI> * <LI> The ModelMBeanAttributeInfo's isWritable method returns * 'false'.</LI> * </UL> * @exception InvalidAttributeValueException No descriptor is defined * for the specified attribute. * @exception MBeanException Wraps one of the following Exceptions: * <UL> * <LI> An Exception thrown by the managed object's setter.</LI> * <LI> A {@link ServiceNotFoundException} if a setMethod field is * defined in the descriptor for the attribute and the managed * resource is null; or if no setMethod field is defined and * caching is not enabled for the attribute. * Note that if there is no getMethod field either, then caching * is automatically enabled.</LI> * <LI> {@link InvalidTargetObjectTypeException} The 'targetType' * field value is not 'objectReference'.</LI> * <LI> An Exception thrown by the managed object's getter.</LI> * </UL> * @exception ReflectionException Wraps an {@link java.lang.Exception} * thrown while trying to invoke the setter. * @exception RuntimeOperationsException Wraps an * {@link IllegalArgumentException}: The attribute in parameter is * null. * * @see #getAttribute(java.lang.String) **/ public void setAttribute(Attribute attribute) throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException { final boolean tracing = MODELMBEAN_LOGGER.isLoggable(Level.FINER); if (tracing) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), "setAttribute()","Entry"); } if (attribute == null) throw new RuntimeOperationsException(new IllegalArgumentException("attribute must not be null"), "Exception occurred trying to set an attribute of a "+ "RequiredModelMBean"); /* run setMethod if there is one */ /* return cached value if its current */ /* set cached value in descriptor and set date/time */ /* send attribute change Notification */ /* check persistence policy and persist if need be */ String attrName = attribute.getName(); Object attrValue = attribute.getValue(); boolean updateDescriptor = false; ModelMBeanAttributeInfo attrInfo = modelMBeanInfo.getAttribute(attrName); if (attrInfo == null) throw new AttributeNotFoundException("setAttribute failed: " + attrName + " is not found "); Descriptor mmbDesc = modelMBeanInfo.getMBeanDescriptor(); Descriptor attrDescr = attrInfo.getDescriptor(); if (attrDescr != null) { if (!attrInfo.isWritable()) throw new AttributeNotFoundException("setAttribute failed: " + attrName + " is not writable "); Object setResponse = null; String attrSetMethod = (String) (attrDescr.getFieldValue("setMethod")); String attrGetMethod = (String) (attrDescr.getFieldValue("getMethod")); String attrType = attrInfo.getType(); Object currValue = "Unknown"; try { currValue = this.getAttribute(attrName); } catch (Throwable t) { // OK: Default "Unknown" value used for unknown attribute } Attribute oldAttr = new Attribute(attrName, currValue); /* run method from operations descriptor */ if (attrSetMethod == null) { if (attrValue != null) { try { final Class clazz = loadClass(attrType); if (! clazz.isInstance(attrValue)) throw new InvalidAttributeValueException(clazz.getName() + " expected, " + attrValue.getClass().getName() + " received."); } catch (ClassNotFoundException x) { if (MODELMBEAN_LOGGER.isLoggable(Level.WARNING)) { MODELMBEAN_LOGGER.logp(Level.WARNING, RequiredModelMBean.class.getName(), "setAttribute(Attribute)","Class " + attrType + " for attribute " + attrName + " not found: ", x); } } } updateDescriptor = true; } else { setResponse = invoke(attrSetMethod, (new Object[] {attrValue}), (new String[] {attrType}) ); } /* change cached value */ Object objctl = attrDescr.getFieldValue("currencyTimeLimit"); String ctl; if (objctl != null) ctl = objctl.toString(); else ctl = null; if ((ctl == null) && (mmbDesc != null)) { objctl = mmbDesc.getFieldValue("currencyTimeLimit"); if (objctl != null) ctl = objctl.toString(); else ctl = null; } final boolean updateCache = ((ctl != null) && !(ctl.equals("-1"))); if(attrSetMethod == null && !updateCache && attrGetMethod != null) throw new MBeanException(new ServiceNotFoundException("No " + "setMethod field is defined in the descriptor for " + attrName + " attribute and caching is not enabled " + "for it")); if (updateCache || updateDescriptor) { if (tracing) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), "setAttribute(Attribute)", "setting cached value of " + attrName + " to " + attrValue); } attrDescr.setField("value", attrValue); if (updateCache) { final String currtime = String.valueOf( (new Date()).getTime()); attrDescr.setField("lastUpdatedTimeStamp", currtime); } attrInfo.setDescriptor(attrDescr); modelMBeanInfo.setDescriptor(attrDescr,"attribute"); if (tracing) { final StringBuilder strb = new StringBuilder() .append("new descriptor is ").append(attrDescr) .append(". AttributeInfo descriptor is ") .append(attrInfo.getDescriptor()) .append(". AttributeInfo descriptor is ") .append(modelMBeanInfo.getDescriptor(attrName,"attribute")); MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), "setAttribute(Attribute)",strb.toString()); } } if (tracing) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), "setAttribute(Attribute)","sending sendAttributeNotification"); } sendAttributeChangeNotification(oldAttr,attribute); } else { // if descriptor ... else no descriptor if (tracing) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), "setAttribute(Attribute)","setMethod failed "+attrName+ " not in attributeDescriptor\n"); } throw new InvalidAttributeValueException( "Unable to resolve attribute value, "+ "no defined in descriptor for attribute"); } // else no descriptor if (tracing) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), "setAttribute(Attribute)", "Exit"); } } /** {@collect.stats} * Sets the values of an array of attributes of this ModelMBean. * Executes the setAttribute() method for each attribute in the list. * * @param attributes A list of attributes: The identification of the * attributes to be set and the values they are to be set to. * * @return The array of attributes that were set, with their new * values in Attribute instances. * * @exception RuntimeOperationsException Wraps an * {@link IllegalArgumentException}: The object name in parameter * is null or attributes in parameter is null. * * @see #getAttributes **/ public AttributeList setAttributes(AttributeList attributes) { if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), "setAttribute(Attribute)", "Entry"); } if (attributes == null) throw new RuntimeOperationsException(new IllegalArgumentException("attributes must not be null"), "Exception occurred trying to set attributes of a "+ "RequiredModelMBean"); final AttributeList responseList = new AttributeList(); // Go through the list of attributes for (Iterator i = attributes.iterator(); i.hasNext();) { final Attribute attr = (Attribute) i.next(); try { setAttribute(attr); responseList.add(attr); } catch (Exception excep) { responseList.remove(attr); } } return responseList; } private ModelMBeanInfo createDefaultModelMBeanInfo() { return(new ModelMBeanInfoSupport((this.getClass().getName()), "Default ModelMBean", null, null, null, null)); } /** {@collect.stats}***********************************/ /* NotificationBroadcaster Interface */ /** {@collect.stats}***********************************/ private synchronized void writeToLog(String logFileName, String logEntry) throws Exception { PrintStream logOut = null; FileOutputStream fos = null; if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), "writeToLog(String, String)", "Notification Logging to " + logFileName + ": " + logEntry); } if ((logFileName == null) || (logEntry == null)) { if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), "writeToLog(String, String)", "Bad input parameters, will not log this entry."); } return; } try { fos = new FileOutputStream(logFileName, true); logOut = new PrintStream(fos); logOut.println(logEntry); logOut.close(); if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), "writeToLog(String, String)","Successfully opened log " + logFileName); } } catch (Exception e) { if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), "writeToLog(String, String)", "Exception " + e.toString() + " trying to write to the Notification log file " + logFileName); } throw e; } } /** {@collect.stats} * Registers an object which implements the NotificationListener * interface as a listener. This * object's 'handleNotification()' method will be invoked when any * notification is issued through or by the ModelMBean. This does * not include attributeChangeNotifications. They must be registered * for independently. * * @param listener The listener object which will handles * notifications emitted by the registered MBean. * @param filter The filter object. If null, no filtering will be * performed before handling notifications. * @param handback The context to be sent to the listener with * the notification when a notification is emitted. * * @exception IllegalArgumentException The listener cannot be null. * * @see #removeNotificationListener */ public void addNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback) throws java.lang.IllegalArgumentException { final String mth = "addNotificationListener(" + "NotificationListener, NotificationFilter, Object)"; if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "Entry"); } if (listener == null) throw new IllegalArgumentException( "notification listener must not be null"); if (generalBroadcaster == null) generalBroadcaster = new NotificationBroadcasterSupport(); generalBroadcaster.addNotificationListener(listener, filter, handback); if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "NotificationListener added"); MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "Exit"); } } /** {@collect.stats} * Removes a listener for Notifications from the RequiredModelMBean. * * @param listener The listener name which was handling notifications * emitted by the registered MBean. * This method will remove all information related to this listener. * * @exception ListenerNotFoundException The listener is not registered * in the MBean or is null. * * @see #addNotificationListener **/ public void removeNotificationListener(NotificationListener listener) throws ListenerNotFoundException { if (listener == null) throw new ListenerNotFoundException( "Notification listener is null"); final String mth="removeNotificationListener(NotificationListener)"; if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "Entry"); } if (generalBroadcaster == null) throw new ListenerNotFoundException( "No notification listeners registered"); generalBroadcaster.removeNotificationListener(listener); if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "Exit"); } } public void removeNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback) throws ListenerNotFoundException { if (listener == null) throw new ListenerNotFoundException( "Notification listener is null"); final String mth = "removeNotificationListener(" + "NotificationListener, NotificationFilter, Object)"; if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "Entry"); } if (generalBroadcaster == null) throw new ListenerNotFoundException( "No notification listeners registered"); generalBroadcaster.removeNotificationListener(listener,filter, handback); if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "Exit"); } } public void sendNotification(Notification ntfyObj) throws MBeanException, RuntimeOperationsException { if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), "sendNotification(Notification)", "Entry"); } if (ntfyObj == null) throw new RuntimeOperationsException(new IllegalArgumentException("notification object must not be "+ "null"), "Exception occurred trying to send a notification from a "+ "RequiredModelMBean"); // log notification if specified in descriptor Descriptor ntfyDesc = modelMBeanInfo.getDescriptor(ntfyObj.getType(),"notification"); Descriptor mmbDesc = modelMBeanInfo.getMBeanDescriptor(); if (ntfyDesc != null) { String logging = (String) ntfyDesc.getFieldValue("log"); if (logging == null) { if (mmbDesc != null) logging = (String) mmbDesc.getFieldValue("log"); } if ((logging != null) && (logging.equalsIgnoreCase("t") || logging.equalsIgnoreCase("true"))) { String logfile = (String) ntfyDesc.getFieldValue("logfile"); if (logfile == null) { if (mmbDesc != null) logfile = (String)mmbDesc.getFieldValue("logfile"); } if (logfile != null) { try { writeToLog(logfile,"LogMsg: " + ((new Date(ntfyObj.getTimeStamp())).toString())+ " " + ntfyObj.getType() + " " + ntfyObj.getMessage() + " Severity = " + (String)ntfyDesc.getFieldValue("severity")); } catch (Exception e) { if (MODELMBEAN_LOGGER.isLoggable(Level.WARNING)) { MODELMBEAN_LOGGER.logp(Level.WARNING, RequiredModelMBean.class.getName(), "sendNotification(Notification)", "Failed to log " + ntfyObj.getType() + " notification: ", e); } } } } } if (generalBroadcaster != null) { generalBroadcaster.sendNotification(ntfyObj); } if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), "sendNotification(Notification)", "sendNotification sent provided notification object"); MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), "sendNotification(Notification)"," Exit"); } } public void sendNotification(String ntfyText) throws MBeanException, RuntimeOperationsException { if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), "sendNotification(String)","Entry"); } if (ntfyText == null) throw new RuntimeOperationsException(new IllegalArgumentException("notification message must not "+ "be null"), "Exception occurred trying to send a text notification "+ "from a ModelMBean"); Notification myNtfyObj = new Notification("jmx.modelmbean.generic", this, 1, ntfyText); sendNotification(myNtfyObj); if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), "sendNotification(String)","Notification sent"); MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), "sendNotification(String)","Exit"); } } /** {@collect.stats} * Returns `true' if the notification `notifName' is found * in `info'. (bug 4744667) **/ private static final boolean hasNotification(final ModelMBeanInfo info, final String notifName) { try { if (info == null) return false; else return (info.getNotification(notifName)!=null); } catch (MBeanException x) { return false; } catch (RuntimeOperationsException r) { return false; } } /** {@collect.stats} * Creates a default ModelMBeanNotificationInfo for GENERIC * notification. (bug 4744667) **/ private static final ModelMBeanNotificationInfo makeGenericInfo() { final Descriptor genericDescriptor = new DescriptorSupport( new String[] { "name=GENERIC", "descriptorType=notification", "log=T", "severity=6", "displayName=jmx.modelmbean.generic"} ); return new ModelMBeanNotificationInfo(new String[] {"jmx.modelmbean.generic"}, "GENERIC", "A text notification has been issued by the managed resource", genericDescriptor); } /** {@collect.stats} * Creates a default ModelMBeanNotificationInfo for ATTRIBUTE_CHANGE * notification. (bug 4744667) **/ private static final ModelMBeanNotificationInfo makeAttributeChangeInfo() { final Descriptor attributeDescriptor = new DescriptorSupport(new String[] { "name=ATTRIBUTE_CHANGE", "descriptorType=notification", "log=T", "severity=6", "displayName=jmx.attribute.change"}); return new ModelMBeanNotificationInfo(new String[] {"jmx.attribute.change"}, "ATTRIBUTE_CHANGE", "Signifies that an observed MBean attribute value has changed", attributeDescriptor ); } /** {@collect.stats} * Returns the array of Notifications always generated by the * RequiredModelMBean. * <P> * * RequiredModelMBean may always send also two additional notifications: * <UL> * <LI> One with descriptor <code>"name=GENERIC,descriptorType=notification,log=T,severity=6,displayName=jmx.modelmbean.generic"</code></LI> * <LI> Second is a standard attribute change notification * with descriptor <code>"name=ATTRIBUTE_CHANGE,descriptorType=notification,log=T,severity=6,displayName=jmx.attribute.change"</code></LI> * </UL> * Thus these two notifications are always added to those specified * by the application. * * @return MBeanNotificationInfo[] * **/ public MBeanNotificationInfo[] getNotificationInfo() { if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), "getNotificationInfo()","Entry"); } // Using hasNotification() is not optimal, but shouldn't really // matter in this context... // hasGeneric==true if GENERIC notification is present. // (bug 4744667) final boolean hasGeneric = hasNotification(modelMBeanInfo,"GENERIC"); // hasAttributeChange==true if ATTRIBUTE_CHANGE notification is // present. // (bug 4744667) final boolean hasAttributeChange = hasNotification(modelMBeanInfo,"ATTRIBUTE_CHANGE"); // User supplied list of notification infos. // final ModelMBeanNotificationInfo[] currInfo = (ModelMBeanNotificationInfo[])modelMBeanInfo.getNotifications(); // Length of the returned list of notification infos: // length of user suplied list + possibly 1 for GENERIC, + // possibly 1 for ATTRIBUTE_CHANGE // (bug 4744667) final int len = ((currInfo==null?0:currInfo.length) + (hasGeneric?0:1) + (hasAttributeChange?0:1)); // Returned list of notification infos: // final ModelMBeanNotificationInfo[] respInfo = new ModelMBeanNotificationInfo[len]; // Preserve previous ordering (JMX 1.1) // // Counter of "standard" notification inserted before user // supplied notifications. // int inserted=0; if (!hasGeneric) // We need to add description for GENERIC notification // (bug 4744667) respInfo[inserted++] = makeGenericInfo(); if (!hasAttributeChange) // We need to add description for ATTRIBUTE_CHANGE notification // (bug 4744667) respInfo[inserted++] = makeAttributeChangeInfo(); // Now copy user supplied list in returned list. // final int count = currInfo.length; final int offset = inserted; for (int j=0; j < count; j++) { respInfo[offset+j] = currInfo[j]; } if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), "getNotificationInfo()","Exit"); } return respInfo; } public void addAttributeChangeNotificationListener(NotificationListener inlistener, String inAttributeName, Object inhandback) throws MBeanException, RuntimeOperationsException, IllegalArgumentException { final String mth="addAttributeChangeNotificationListener(" + "NotificationListener, String, Object)"; if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(),mth,"Entry"); } if (inlistener == null) throw new IllegalArgumentException( "Listener to be registered must not be null"); if (attributeBroadcaster == null) attributeBroadcaster = new NotificationBroadcasterSupport(); AttributeChangeNotificationFilter currFilter = new AttributeChangeNotificationFilter(); MBeanAttributeInfo[] attrInfo = modelMBeanInfo.getAttributes(); boolean found = false; if (inAttributeName == null) { if ((attrInfo != null) && (attrInfo.length>0)) { for (int i=0; i<attrInfo.length; i++) { currFilter.enableAttribute(attrInfo[i].getName()); } } } else { if ((attrInfo != null) && (attrInfo.length>0)) { for (int i=0; i<attrInfo.length; i++) { if (inAttributeName.equals(attrInfo[i].getName())) { found = true; currFilter.enableAttribute(inAttributeName); break; } } } if (!found) { throw new RuntimeOperationsException(new IllegalArgumentException( "The attribute name does not exist"), "Exception occurred trying to add an "+ "AttributeChangeNotification listener"); } } if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "Set attribute change filter to " + currFilter.getEnabledAttributes().firstElement()); } attributeBroadcaster.addNotificationListener(inlistener,currFilter, inhandback); if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(),mth, "Notification listener added for " + inAttributeName); MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(),mth,"Exit"); } } public void removeAttributeChangeNotificationListener( NotificationListener inlistener, String inAttributeName) throws MBeanException, RuntimeOperationsException, ListenerNotFoundException { if (inlistener == null) throw new ListenerNotFoundException("Notification listener is null"); final String mth = "removeAttributeChangeNotificationListener(" + "NotificationListener, String)"; if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(),mth,"Entry"); } if (attributeBroadcaster == null) throw new ListenerNotFoundException( "No attribute change notification listeners registered"); MBeanAttributeInfo[] attrInfo = modelMBeanInfo.getAttributes(); boolean found = false; if ((attrInfo != null) && (attrInfo.length>0)) { for (int i=0; i<attrInfo.length; i++) { if (attrInfo[i].getName().equals(inAttributeName)) { found = true; break; } } } if ((!found) && (inAttributeName != null)) { throw new RuntimeOperationsException(new IllegalArgumentException("Invalid attribute name"), "Exception occurred trying to remove "+ "attribute change notification listener"); } /* note: */ /* this may be a problem if the same listener is registered for multiple attributes with multiple filters and/or handback objects. It may remove all of them */ attributeBroadcaster.removeNotificationListener(inlistener); if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(),mth,"Exit"); } } public void sendAttributeChangeNotification(AttributeChangeNotification ntfyObj) throws MBeanException, RuntimeOperationsException { final String mth = "sendAttributeChangeNotification(" + "AttributeChangeNotification)"; if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(),mth,"Entry"); } if (ntfyObj == null) throw new RuntimeOperationsException(new IllegalArgumentException( "attribute change notification object must not be null"), "Exception occurred trying to send "+ "attribute change notification of a ModelMBean"); Object oldv = ntfyObj.getOldValue(); Object newv = ntfyObj.getNewValue(); if (oldv == null) oldv = "null"; if (newv == null) newv = "null"; if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(),mth, "Sending AttributeChangeNotification with " + ntfyObj.getAttributeName() + ntfyObj.getAttributeType() + ntfyObj.getNewValue() + ntfyObj.getOldValue()); } // log notification if specified in descriptor Descriptor ntfyDesc = modelMBeanInfo.getDescriptor(ntfyObj.getType(),"notification"); Descriptor mmbDesc = modelMBeanInfo.getMBeanDescriptor(); String logging, logfile; if (ntfyDesc != null) { logging =(String) ntfyDesc.getFieldValue("log"); if (logging == null) { if (mmbDesc != null) logging = (String) mmbDesc.getFieldValue("log"); } if ((logging != null) && ( logging.equalsIgnoreCase("t") || logging.equalsIgnoreCase("true"))) { logfile = (String) ntfyDesc.getFieldValue("logfile"); if (logfile == null) { if (mmbDesc != null) logfile = (String)mmbDesc.getFieldValue("logfile"); } if (logfile != null) { try { writeToLog(logfile,"LogMsg: " + ((new Date(ntfyObj.getTimeStamp())).toString())+ " " + ntfyObj.getType() + " " + ntfyObj.getMessage() + " Name = " + ntfyObj.getAttributeName() + " Old value = " + oldv + " New value = " + newv); } catch (Exception e) { if (MODELMBEAN_LOGGER.isLoggable(Level.WARNING)) { MODELMBEAN_LOGGER.logp(Level.WARNING, RequiredModelMBean.class.getName(),mth, "Failed to log " + ntfyObj.getType() + " notification: ", e); } } } } } else if (mmbDesc != null) { logging = (String) mmbDesc.getFieldValue("log"); if ((logging != null) && ( logging.equalsIgnoreCase("t") || logging.equalsIgnoreCase("true") )) { logfile = (String) mmbDesc.getFieldValue("logfile"); if (logfile != null) { try { writeToLog(logfile,"LogMsg: " + ((new Date(ntfyObj.getTimeStamp())).toString())+ " " + ntfyObj.getType() + " " + ntfyObj.getMessage() + " Name = " + ntfyObj.getAttributeName() + " Old value = " + oldv + " New value = " + newv); } catch (Exception e) { if (MODELMBEAN_LOGGER.isLoggable(Level.WARNING)) { MODELMBEAN_LOGGER.logp(Level.WARNING, RequiredModelMBean.class.getName(),mth, "Failed to log " + ntfyObj.getType() + " notification: ", e); } } } } } if (attributeBroadcaster != null) { attributeBroadcaster.sendNotification(ntfyObj); } // XXX Revisit: This is a quickfix: it would be better to have a // single broadcaster. However, it is not so simple because // removeAttributeChangeNotificationListener() should // remove only listeners whose filter is an instanceof // AttributeChangeNotificationFilter. // if (generalBroadcaster != null) { generalBroadcaster.sendNotification(ntfyObj); } if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(),mth, "sent notification"); MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(),mth, "Exit"); } } public void sendAttributeChangeNotification(Attribute inOldVal, Attribute inNewVal) throws MBeanException, RuntimeOperationsException { final String mth = "sendAttributeChangeNotification(Attribute, Attribute)"; if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(),mth, "Entry"); } // do we really want to do this? if ((inOldVal == null) || (inNewVal == null)) throw new RuntimeOperationsException(new IllegalArgumentException("Attribute object must not be null"), "Exception occurred trying to send " + "attribute change notification of a ModelMBean"); if (!(inOldVal.getName().equals(inNewVal.getName()))) throw new RuntimeOperationsException(new IllegalArgumentException("Attribute names are not the same"), "Exception occurred trying to send " + "attribute change notification of a ModelMBean"); Object newVal = inNewVal.getValue(); Object oldVal = inOldVal.getValue(); String className = "unknown"; if (newVal != null) className = newVal.getClass().getName(); if (oldVal != null) className = oldVal.getClass().getName(); AttributeChangeNotification myNtfyObj = new AttributeChangeNotification(this, 1, ((new Date()).getTime()), "AttributeChangeDetected", inOldVal.getName(), className, inOldVal.getValue(), inNewVal.getValue()); sendAttributeChangeNotification(myNtfyObj); if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(),mth, "Exit"); } } /** {@collect.stats} * Return the Class Loader Repository used to perform class loading. * Subclasses may wish to redefine this method in order to return * the appropriate {@link javax.management.loading.ClassLoaderRepository} * that should be used in this object. * * @return the Class Loader Repository. * */ protected ClassLoaderRepository getClassLoaderRepository() { return MBeanServerFactory.getClassLoaderRepository(server); } private Class loadClass(String className) throws ClassNotFoundException { try { return Class.forName(className); } catch (ClassNotFoundException e) { final ClassLoaderRepository clr = getClassLoaderRepository(); if (clr == null) throw new ClassNotFoundException(className); return clr.loadClass(className); } } /** {@collect.stats}***********************************/ /* MBeanRegistration Interface */ /** {@collect.stats}***********************************/ /** {@collect.stats} * Allows the MBean to perform any operations it needs before * being registered in the MBean server. If the name of the MBean * is not specified, the MBean can provide a name for its * registration. If any exception is raised, the MBean will not be * registered in the MBean server. * <P> * In order to ensure proper run-time semantics of RequireModelMBean, * Any subclass of RequiredModelMBean overloading or overriding this * method should call <code>super.preRegister(server, name)</code> * in its own <code>preRegister</code> implementation. * * @param server The MBean server in which the MBean will be registered. * * @param name The object name of the MBean. This name is null if * the name parameter to one of the <code>createMBean</code> or * <code>registerMBean</code> methods in the {@link MBeanServer} * interface is null. In that case, this method must return a * non-null ObjectName for the new MBean. * * @return The name under which the MBean is to be registered. * This value must not be null. If the <code>name</code> * parameter is not null, it will usually but not necessarily be * the returned value. * * @exception java.lang.Exception This exception will be caught by * the MBean server and re-thrown as an * {@link javax.management.MBeanRegistrationException * MBeanRegistrationException}. */ public ObjectName preRegister(MBeanServer server, ObjectName name) throws java.lang.Exception { // Since ModelMbeanInfo cannot be null (otherwise exception // thrown at creation) // no exception thrown on ModelMBeanInfo not set. if (name == null) throw new NullPointerException( "name of RequiredModelMBean to registered is null"); this.server = server; return name; } /** {@collect.stats} * Allows the MBean to perform any operations needed after having been * registered in the MBean server or after the registration has failed. * <P> * In order to ensure proper run-time semantics of RequireModelMBean, * Any subclass of RequiredModelMBean overloading or overriding this * method should call <code>super.postRegister(registrationDone)</code> * in its own <code>postRegister</code> implementation. * * @param registrationDone Indicates whether or not the MBean has * been successfully registered in the MBean server. The value * false means that the registration phase has failed. */ public void postRegister(Boolean registrationDone) { registered = registrationDone.booleanValue(); } /** {@collect.stats} * Allows the MBean to perform any operations it needs before * being unregistered by the MBean server. * <P> * In order to ensure proper run-time semantics of RequireModelMBean, * Any subclass of RequiredModelMBean overloading or overriding this * method should call <code>super.preDeregister()</code> in its own * <code>preDeregister</code> implementation. * * @exception java.lang.Exception This exception will be caught by * the MBean server and re-thrown as an * {@link javax.management.MBeanRegistrationException * MBeanRegistrationException}. */ public void preDeregister() throws java.lang.Exception { } /** {@collect.stats} * Allows the MBean to perform any operations needed after having been * unregistered in the MBean server. * <P> * In order to ensure proper run-time semantics of RequireModelMBean, * Any subclass of RequiredModelMBean overloading or overriding this * method should call <code>super.postDeregister()</code> in its own * <code>postDeregister</code> implementation. */ public void postDeregister() { registered = false; this.server=null; } private static final String[] primitiveTypes; private static final String[] primitiveWrappers; static { primitiveTypes = new String[] { Boolean.TYPE.getName(), Byte.TYPE.getName(), Character.TYPE.getName(), Short.TYPE.getName(), Integer.TYPE.getName(), Long.TYPE.getName(), Float.TYPE.getName(), Double.TYPE.getName(), Void.TYPE.getName() }; primitiveWrappers = new String[] { Boolean.class.getName(), Byte.class.getName(), Character.class.getName(), Short.class.getName(), Integer.class.getName(), Long.class.getName(), Float.class.getName(), Double.class.getName(), Void.class.getName() }; } }
Java
/* * Copyright (c) 2000, 2007, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ /* * @author IBM Corp. * * Copyright IBM Corp. 1999-2000. All rights reserved. */ package javax.management.modelmbean; import static com.sun.jmx.defaults.JmxProperties.MODELMBEAN_LOGGER; import static com.sun.jmx.mbeanserver.Util.cast; import com.sun.jmx.mbeanserver.GetPropertyAction; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.ObjectStreamField; import java.lang.reflect.Constructor; import java.security.AccessController; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.logging.Level; import javax.management.Descriptor; import javax.management.ImmutableDescriptor; import javax.management.MBeanException; import javax.management.RuntimeOperationsException; import sun.reflect.misc.ReflectUtil; /** {@collect.stats} * This class represents the metadata set for a ModelMBean element. A * descriptor is part of the ModelMBeanInfo, * ModelMBeanNotificationInfo, ModelMBeanAttributeInfo, * ModelMBeanConstructorInfo, and ModelMBeanParameterInfo. * <P> * A descriptor consists of a collection of fields. Each field is in * fieldname=fieldvalue format. Field names are not case sensitive, * case will be preserved on field values. * <P> * All field names and values are not predefined. New fields can be * defined and added by any program. Some fields have been predefined * for consistency of implementation and support by the * ModelMBeanInfo, ModelMBeanAttributeInfo, ModelMBeanConstructorInfo, * ModelMBeanNotificationInfo, ModelMBeanOperationInfo and ModelMBean * classes. * * <p>The <b>serialVersionUID</b> of this class is <code>-6292969195866300415L</code>. * * @since 1.5 */ @SuppressWarnings("serial") // serialVersionUID not constant public class DescriptorSupport implements javax.management.Descriptor { // Serialization compatibility stuff: // Two serial forms are supported in this class. The selected form depends // on system property "jmx.serial.form": // - "1.0" for JMX 1.0 // - any other value for JMX 1.1 and higher // // Serial version for old serial form private static final long oldSerialVersionUID = 8071560848919417985L; // // Serial version for new serial form private static final long newSerialVersionUID = -6292969195866300415L; // // Serializable fields in old serial form private static final ObjectStreamField[] oldSerialPersistentFields = { new ObjectStreamField("descriptor", HashMap.class), new ObjectStreamField("currClass", String.class) }; // // Serializable fields in new serial form private static final ObjectStreamField[] newSerialPersistentFields = { new ObjectStreamField("descriptor", HashMap.class) }; // // Actual serial version and serial form private static final long serialVersionUID; /** {@collect.stats} * @serialField descriptor HashMap The collection of fields representing this descriptor */ private static final ObjectStreamField[] serialPersistentFields; private static final String serialForm; static { String form = null; boolean compat = false; try { GetPropertyAction act = new GetPropertyAction("jmx.serial.form"); form = AccessController.doPrivileged(act); compat = "1.0".equals(form); // form may be null } catch (Exception e) { // OK: No compat with 1.0 } serialForm = form; if (compat) { serialPersistentFields = oldSerialPersistentFields; serialVersionUID = oldSerialVersionUID; } else { serialPersistentFields = newSerialPersistentFields; serialVersionUID = newSerialVersionUID; } } // // END Serialization compatibility stuff /* Spec says that field names are case-insensitive, but that case is preserved. This means that we need to be able to map from a name that may differ in case to the actual name that is used in the HashMap. Thus, descriptorMap is a TreeMap with a Comparator that ignores case. Previous versions of this class had a field called "descriptor" of type HashMap where the keys were directly Strings. This is hard to reconcile with the required semantics, so we fabricate that field virtually during serialization and deserialization but keep the real information in descriptorMap. */ private transient SortedMap<String, Object> descriptorMap; private static final String currClass = "DescriptorSupport"; /** {@collect.stats} * Descriptor default constructor. * Default initial descriptor size is 20. It will grow as needed.<br> * Note that the created empty descriptor is not a valid descriptor * (the method {@link #isValid isValid} returns <CODE>false</CODE>) */ public DescriptorSupport() { if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "DescriptorSupport()" , "Constructor"); } init(null); } /** {@collect.stats} * Descriptor constructor. Takes as parameter the initial * capacity of the Map that stores the descriptor fields. * Capacity will grow as needed.<br> Note that the created empty * descriptor is not a valid descriptor (the method {@link * #isValid isValid} returns <CODE>false</CODE>). * * @param initNumFields The initial capacity of the Map that * stores the descriptor fields. * * @exception RuntimeOperationsException for illegal value for * initNumFields (&lt;= 0) * @exception MBeanException Wraps a distributed communication Exception. */ public DescriptorSupport(int initNumFields) throws MBeanException, RuntimeOperationsException { if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "Descriptor(initNumFields = " + initNumFields + ")", "Constructor"); } if (initNumFields <= 0) { if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "Descriptor(initNumFields)", "Illegal arguments: initNumFields <= 0"); } final String msg = "Descriptor field limit invalid: " + initNumFields; final RuntimeException iae = new IllegalArgumentException(msg); throw new RuntimeOperationsException(iae, msg); } init(null); } /** {@collect.stats} * Descriptor constructor taking a Descriptor as parameter. * Creates a new descriptor initialized to the values of the * descriptor passed in parameter. * * @param inDescr the descriptor to be used to initialize the * constructed descriptor. If it is null or contains no descriptor * fields, an empty Descriptor will be created. */ public DescriptorSupport(DescriptorSupport inDescr) { if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "Descriptor(Descriptor)", "Constructor"); } if (inDescr == null) init(null); else init(inDescr.descriptorMap); } /** {@collect.stats} * <p>Descriptor constructor taking an XML String.</p> * * <p>The format of the XML string is not defined, but an * implementation must ensure that the string returned by * {@link #toXMLString() toXMLString()} on an existing * descriptor can be used to instantiate an equivalent * descriptor using this constructor.</p> * * <p>In this implementation, all field values will be created * as Strings. If the field values are not Strings, the * programmer will have to reset or convert these fields * correctly.</p> * * @param inStr An XML-formatted string used to populate this * Descriptor. The format is not defined, but any * implementation must ensure that the string returned by * method {@link #toXMLString toXMLString} on an existing * descriptor can be used to instantiate an equivalent * descriptor when instantiated using this constructor. * * @exception RuntimeOperationsException If the String inStr * passed in parameter is null * @exception XMLParseException XML parsing problem while parsing * the input String * @exception MBeanException Wraps a distributed communication Exception. */ /* At some stage we should rewrite this code to be cleverer. Using a StringTokenizer as we do means, first, that we accept a lot of bogus strings without noticing they are bogus, and second, that we split the string being parsed at characters like > even if they occur in the middle of a field value. */ public DescriptorSupport(String inStr) throws MBeanException, RuntimeOperationsException, XMLParseException { /* parse an XML-formatted string and populate internal * structure with it */ if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "Descriptor(String = '" + inStr + "')", "Constructor"); } if (inStr == null) { if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "Descriptor(String = null)", "Illegal arguments"); } final String msg = "String in parameter is null"; final RuntimeException iae = new IllegalArgumentException(msg); throw new RuntimeOperationsException(iae, msg); } final String lowerInStr = inStr.toLowerCase(); if (!lowerInStr.startsWith("<descriptor>") || !lowerInStr.endsWith("</descriptor>")) { throw new XMLParseException("No <descriptor>, </descriptor> pair"); } // parse xmlstring into structures init(null); // create dummy descriptor: should have same size // as number of fields in xmlstring // loop through structures and put them in descriptor StringTokenizer st = new StringTokenizer(inStr, "<> \t\n\r\f"); boolean inFld = false; boolean inDesc = false; String fieldName = null; String fieldValue = null; while (st.hasMoreTokens()) { // loop through tokens String tok = st.nextToken(); if (tok.equalsIgnoreCase("FIELD")) { inFld = true; } else if (tok.equalsIgnoreCase("/FIELD")) { if ((fieldName != null) && (fieldValue != null)) { fieldName = fieldName.substring(fieldName.indexOf('"') + 1, fieldName.lastIndexOf('"')); final Object fieldValueObject = parseQuotedFieldValue(fieldValue); setField(fieldName, fieldValueObject); } fieldName = null; fieldValue = null; inFld = false; } else if (tok.equalsIgnoreCase("DESCRIPTOR")) { inDesc = true; } else if (tok.equalsIgnoreCase("/DESCRIPTOR")) { inDesc = false; fieldName = null; fieldValue = null; inFld = false; } else if (inFld && inDesc) { // want kw=value, eg, name="myname" value="myvalue" int eq_separator = tok.indexOf("="); if (eq_separator > 0) { String kwPart = tok.substring(0,eq_separator); String valPart = tok.substring(eq_separator+1); if (kwPart.equalsIgnoreCase("NAME")) fieldName = valPart; else if (kwPart.equalsIgnoreCase("VALUE")) fieldValue = valPart; else { // xml parse exception final String msg = "Expected `name' or `value', got `" + tok + "'"; throw new XMLParseException(msg); } } else { // xml parse exception final String msg = "Expected `keyword=value', got `" + tok + "'"; throw new XMLParseException(msg); } } } // while tokens if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "Descriptor(XMLString)", "Exit"); } } /** {@collect.stats} * Constructor taking field names and field values. Neither array * can be null. * * @param fieldNames String array of field names. No elements of * this array can be null. * @param fieldValues Object array of the corresponding field * values. Elements of the array can be null. The * <code>fieldValue</code> must be valid for the * <code>fieldName</code> (as defined in method {@link #isValid * isValid}) * * <p>Note: array sizes of parameters should match. If both arrays * are empty, then an empty descriptor is created.</p> * * @exception RuntimeOperationsException for illegal value for * field Names or field Values. The array lengths must be equal. * If the descriptor construction fails for any reason, this * exception will be thrown. * */ public DescriptorSupport(String[] fieldNames, Object[] fieldValues) throws RuntimeOperationsException { if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "Descriptor(fieldNames,fieldObjects)", "Constructor"); } if ((fieldNames == null) || (fieldValues == null) || (fieldNames.length != fieldValues.length)) { if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "Descriptor(fieldNames,fieldObjects)", "Illegal arguments"); } final String msg = "Null or invalid fieldNames or fieldValues"; final RuntimeException iae = new IllegalArgumentException(msg); throw new RuntimeOperationsException(iae, msg); } /* populate internal structure with fields */ init(null); for (int i=0; i < fieldNames.length; i++) { // setField will throw an exception if a fieldName is be null. // the fieldName and fieldValue will be validated in setField. setField(fieldNames[i], fieldValues[i]); } if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "Descriptor(fieldNames,fieldObjects)", "Exit"); } } /** {@collect.stats} * Constructor taking fields in the <i>fieldName=fieldValue</i> * format. * * @param fields String array with each element containing a * field name and value. If this array is null or empty, then the * default constructor will be executed. Null strings or empty * strings will be ignored. * * <p>All field values should be Strings. If the field values are * not Strings, the programmer will have to reset or convert these * fields correctly. * * <p>Note: Each string should be of the form * <i>fieldName=fieldValue</i>. The field name * ends at the first {@code =} character; for example if the String * is {@code a=b=c} then the field name is {@code a} and its value * is {@code b=c}. * * @exception RuntimeOperationsException for illegal value for * field Names or field Values. The field must contain an * "=". "=fieldValue", "fieldName", and "fieldValue" are illegal. * FieldName cannot be null. "fieldName=" will cause the value to * be null. If the descriptor construction fails for any reason, * this exception will be thrown. * */ public DescriptorSupport(String... fields) { if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "Descriptor(String... fields)", "Constructor"); } init(null); if (( fields == null ) || ( fields.length == 0)) return; init(null); for (int i=0; i < fields.length; i++) { if ((fields[i] == null) || (fields[i].equals(""))) { continue; } int eq_separator = fields[i].indexOf("="); if (eq_separator < 0) { // illegal if no = or is first character if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "Descriptor(String... fields)", "Illegal arguments: field does not have " + "'=' as a name and value separator"); } final String msg = "Field in invalid format: no equals sign"; final RuntimeException iae = new IllegalArgumentException(msg); throw new RuntimeOperationsException(iae, msg); } String fieldName = fields[i].substring(0,eq_separator); String fieldValue = null; if (eq_separator < fields[i].length()) { // = is not in last character fieldValue = fields[i].substring(eq_separator+1); } if (fieldName.equals("")) { if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "Descriptor(String... fields)", "Illegal arguments: fieldName is empty"); } final String msg = "Field in invalid format: no fieldName"; final RuntimeException iae = new IllegalArgumentException(msg); throw new RuntimeOperationsException(iae, msg); } setField(fieldName,fieldValue); } if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "Descriptor(String... fields)", "Exit"); } } private void init(Map<String, ?> initMap) { descriptorMap = new TreeMap<String, Object>(String.CASE_INSENSITIVE_ORDER); if (initMap != null) descriptorMap.putAll(initMap); } // Implementation of the Descriptor interface public synchronized Object getFieldValue(String fieldName) throws RuntimeOperationsException { if ((fieldName == null) || (fieldName.equals(""))) { if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "getFieldValue(String fieldName)", "Illegal arguments: null field name"); } final String msg = "Fieldname requested is null"; final RuntimeException iae = new IllegalArgumentException(msg); throw new RuntimeOperationsException(iae, msg); } Object retValue = descriptorMap.get(fieldName); if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "getFieldValue(String fieldName = " + fieldName + ")", "Returns '" + retValue + "'"); } return(retValue); } public synchronized void setField(String fieldName, Object fieldValue) throws RuntimeOperationsException { // field name cannot be null or empty if ((fieldName == null) || (fieldName.equals(""))) { if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "setField(fieldName,fieldValue)", "Illegal arguments: null or empty field name"); } final String msg = "Field name to be set is null or empty"; final RuntimeException iae = new IllegalArgumentException(msg); throw new RuntimeOperationsException(iae, msg); } if (!validateField(fieldName, fieldValue)) { if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "setField(fieldName,fieldValue)", "Illegal arguments"); } final String msg = "Field value invalid: " + fieldName + "=" + fieldValue; final RuntimeException iae = new IllegalArgumentException(msg); throw new RuntimeOperationsException(iae, msg); } if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "setField(fieldName,fieldValue)", "Entry: setting '" + fieldName + "' to '" + fieldValue + "'"); } // Since we do not remove any existing entry with this name, // the field will preserve whatever case it had, ignoring // any difference there might be in fieldName. descriptorMap.put(fieldName, fieldValue); } public synchronized String[] getFields() { if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "getFields()", "Entry"); } int numberOfEntries = descriptorMap.size(); String[] responseFields = new String[numberOfEntries]; Set returnedSet = descriptorMap.entrySet(); int i = 0; Object currValue = null; Map.Entry currElement = null; if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "getFields()", "Returning " + numberOfEntries + " fields"); } for (Iterator iter = returnedSet.iterator(); iter.hasNext(); i++) { currElement = (Map.Entry) iter.next(); if (currElement == null) { if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "getFields()", "Element is null"); } } else { currValue = currElement.getValue(); if (currValue == null) { responseFields[i] = currElement.getKey() + "="; } else { if (currValue instanceof java.lang.String) { responseFields[i] = currElement.getKey() + "=" + currValue.toString(); } else { responseFields[i] = currElement.getKey() + "=(" + currValue.toString() + ")"; } } } } if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "getFields()", "Exit"); } return responseFields; } public synchronized String[] getFieldNames() { if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "getFieldNames()", "Entry"); } int numberOfEntries = descriptorMap.size(); String[] responseFields = new String[numberOfEntries]; Set returnedSet = descriptorMap.entrySet(); int i = 0; if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "getFieldNames()", "Returning " + numberOfEntries + " fields"); } for (Iterator iter = returnedSet.iterator(); iter.hasNext(); i++) { Map.Entry currElement = (Map.Entry) iter.next(); if (( currElement == null ) || (currElement.getKey() == null)) { if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "getFieldNames()", "Field is null"); } } else { responseFields[i] = currElement.getKey().toString(); } } if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "getFieldNames()", "Exit"); } return responseFields; } public synchronized Object[] getFieldValues(String... fieldNames) { if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "getFieldValues(String... fieldNames)", "Entry"); } // if fieldNames == null return all values // if fieldNames is String[0] return no values final int numberOfEntries = (fieldNames == null) ? descriptorMap.size() : fieldNames.length; final Object[] responseFields = new Object[numberOfEntries]; int i = 0; if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "getFieldValues(String... fieldNames)", "Returning " + numberOfEntries + " fields"); } if (fieldNames == null) { for (Iterator iter = descriptorMap.values().iterator(); iter.hasNext(); i++) responseFields[i] = iter.next(); } else { for (i=0; i < fieldNames.length; i++) { if ((fieldNames[i] == null) || (fieldNames[i].equals(""))) { responseFields[i] = null; } else { responseFields[i] = getFieldValue(fieldNames[i]); } } } if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "getFieldValues(String... fieldNames)", "Exit"); } return responseFields; } public synchronized void setFields(String[] fieldNames, Object[] fieldValues) throws RuntimeOperationsException { if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "setFields(fieldNames,fieldValues)", "Entry"); } if ((fieldNames == null) || (fieldValues == null) || (fieldNames.length != fieldValues.length)) { if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "setFields(fieldNames,fieldValues)", "Illegal arguments"); } final String msg = "fieldNames and fieldValues are null or invalid"; final RuntimeException iae = new IllegalArgumentException(msg); throw new RuntimeOperationsException(iae, msg); } for (int i=0; i < fieldNames.length; i++) { if (( fieldNames[i] == null) || (fieldNames[i].equals(""))) { if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "setFields(fieldNames,fieldValues)", "Null field name encountered at element " + i); } final String msg = "fieldNames is null or invalid"; final RuntimeException iae = new IllegalArgumentException(msg); throw new RuntimeOperationsException(iae, msg); } setField(fieldNames[i], fieldValues[i]); } if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "setFields(fieldNames,fieldValues)", "Exit"); } } /** {@collect.stats} * Returns a new Descriptor which is a duplicate of the Descriptor. * * @exception RuntimeOperationsException for illegal value for * field Names or field Values. If the descriptor construction * fails for any reason, this exception will be thrown. */ public synchronized Object clone() throws RuntimeOperationsException { if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "clone()", "Entry"); } return(new DescriptorSupport(this)); } public synchronized void removeField(String fieldName) { if ((fieldName == null) || (fieldName.equals(""))) { return; } descriptorMap.remove(fieldName); } /** {@collect.stats} * Compares this descriptor to the given object. The objects are equal if * the given object is also a Descriptor, and if the two Descriptors have * the same field names (possibly differing in case) and the same * associated values. The respective values for a field in the two * Descriptors are equal if the following conditions hold:</p> * * <ul> * <li>If one value is null then the other must be too.</li> * <li>If one value is a primitive array then the other must be a primitive * array of the same type with the same elements.</li> * <li>If one value is an object array then the other must be too and * {@link java.util.Arrays#deepEquals(Object[],Object[]) Arrays.deepEquals} * must return true.</li> * <li>Otherwise {@link Object#equals(Object)} must return true.</li> * </ul> * * @param o the object to compare with. * * @return {@code true} if the objects are the same; {@code false} * otherwise. * */ // XXXX TODO: This is not very efficient! // Note: this Javadoc is copied from javax.management.Descriptor // due to 6369229. public synchronized boolean equals(Object o) { if (o == this) return true; return new ImmutableDescriptor(descriptorMap).equals(o); } /** {@collect.stats} * <p>Returns the hash code value for this descriptor. The hash * code is computed as the sum of the hash codes for each field in * the descriptor. The hash code of a field with name {@code n} * and value {@code v} is {@code n.toLowerCase().hashCode() ^ h}. * Here {@code h} is the hash code of {@code v}, computed as * follows:</p> * * <ul> * <li>If {@code v} is null then {@code h} is 0.</li> * <li>If {@code v} is a primitive array then {@code h} is computed using * the appropriate overloading of {@code java.util.Arrays.hashCode}.</li> * <li>If {@code v} is an object array then {@code h} is computed using * {@link java.util.Arrays#deepHashCode(Object[]) Arrays.deepHashCode}.</li> * <li>Otherwise {@code h} is {@code v.hashCode()}.</li> * </ul> * * @return A hash code value for this object. * */ // XXXX TODO: This is not very efficient! // Note: this Javadoc is copied from javax.management.Descriptor // due to 6369229. public synchronized int hashCode() { return new ImmutableDescriptor(descriptorMap).hashCode(); } /** {@collect.stats} * Returns true if all of the fields have legal values given their * names. * <P> * This implementation does not support interoperating with a directory * or lookup service. Thus, conforming to the specification, no checking is * done on the <i>"export"</i> field. * <P> * Otherwise this implementation returns false if: * <P> * <UL> * <LI> name and descriptorType fieldNames are not defined, or * null, or empty, or not String * <LI> class, role, getMethod, setMethod fieldNames, if defined, * are null or not String * <LI> persistPeriod, currencyTimeLimit, lastUpdatedTimeStamp, * lastReturnedTimeStamp if defined, are null, or not a Numeric * String or not a Numeric Value >= -1 * <LI> log fieldName, if defined, is null, or not a Boolean or * not a String with value "t", "f", "true", "false". These String * values must not be case sensitive. * <LI> visibility fieldName, if defined, is null, or not a * Numeric String or a not Numeric Value >= 1 and <= 4 * <LI> severity fieldName, if defined, is null, or not a Numeric * String or not a Numeric Value >= 0 and <= 6<br> * <LI> persistPolicy fieldName, if defined, is null, or not one of * the following strings:<br> * "OnUpdate", "OnTimer", "NoMoreOftenThan", "OnUnregister", "Always", * "Never". These String values must not be case sensitive.<br> * </UL> * * @exception RuntimeOperationsException If the validity checking * fails for any reason, this exception will be thrown. */ public synchronized boolean isValid() throws RuntimeOperationsException { if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "isValid()", "Entry"); } // verify that the descriptor is valid, by iterating over each field... Set returnedSet = descriptorMap.entrySet(); if (returnedSet == null) { // null descriptor, not valid if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "isValid()", "Returns false (null set)"); } return false; } // must have a name and descriptor type field String thisName = (String)(this.getFieldValue("name")); String thisDescType = (String)(getFieldValue("descriptorType")); if ((thisName == null) || (thisDescType == null) || (thisName.equals("")) || (thisDescType.equals(""))) { return false; } // According to the descriptor type we validate the fields contained for (Iterator iter = returnedSet.iterator(); iter.hasNext();) { Map.Entry currElement = (Map.Entry) iter.next(); if (currElement != null) { if (currElement.getValue() != null) { // validate the field valued... if (validateField((currElement.getKey()).toString(), (currElement.getValue()).toString())) { continue; } else { if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "isValid()", "Field " + currElement.getKey() + "=" + currElement.getValue() + " is not valid"); } return false; } } } } // fell through, all fields OK if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "isValid()", "Returns true"); } return true; } // worker routine for isValid() // name is not null // descriptorType is not null // getMethod and setMethod are not null // persistPeriod is numeric // currencyTimeLimit is numeric // lastUpdatedTimeStamp is numeric // visibility is 1-4 // severity is 0-6 // log is T or F // role is not null // class is not null // lastReturnedTimeStamp is numeric private boolean validateField(String fldName, Object fldValue) { if ((fldName == null) || (fldName.equals(""))) return false; String SfldValue = ""; boolean isAString = false; if ((fldValue != null) && (fldValue instanceof java.lang.String)) { SfldValue = (String) fldValue; isAString = true; } boolean nameOrDescriptorType = (fldName.equalsIgnoreCase("Name") || fldName.equalsIgnoreCase("DescriptorType")); if (nameOrDescriptorType || fldName.equalsIgnoreCase("SetMethod") || fldName.equalsIgnoreCase("GetMethod") || fldName.equalsIgnoreCase("Role") || fldName.equalsIgnoreCase("Class")) { if (fldValue == null || !isAString) return false; if (nameOrDescriptorType && SfldValue.equals("")) return false; return true; } else if (fldName.equalsIgnoreCase("visibility")) { long v; if ((fldValue != null) && (isAString)) { v = toNumeric(SfldValue); } else if (fldValue instanceof java.lang.Integer) { v = ((Integer)fldValue).intValue(); } else return false; if (v >= 1 && v <= 4) return true; else return false; } else if (fldName.equalsIgnoreCase("severity")) { long v; if ((fldValue != null) && (isAString)) { v = toNumeric(SfldValue); } else if (fldValue instanceof java.lang.Integer) { v = ((Integer)fldValue).intValue(); } else return false; return (v >= 0 && v <= 6); } else if (fldName.equalsIgnoreCase("PersistPolicy")) { return (((fldValue != null) && (isAString)) && ( SfldValue.equalsIgnoreCase("OnUpdate") || SfldValue.equalsIgnoreCase("OnTimer") || SfldValue.equalsIgnoreCase("NoMoreOftenThan") || SfldValue.equalsIgnoreCase("Always") || SfldValue.equalsIgnoreCase("Never") || SfldValue.equalsIgnoreCase("OnUnregister"))); } else if (fldName.equalsIgnoreCase("PersistPeriod") || fldName.equalsIgnoreCase("CurrencyTimeLimit") || fldName.equalsIgnoreCase("LastUpdatedTimeStamp") || fldName.equalsIgnoreCase("LastReturnedTimeStamp")) { long v; if ((fldValue != null) && (isAString)) { v = toNumeric(SfldValue); } else if (fldValue instanceof java.lang.Number) { v = ((Number)fldValue).longValue(); } else return false; return (v >= -1); } else if (fldName.equalsIgnoreCase("log")) { return ((fldValue instanceof java.lang.Boolean) || (isAString && (SfldValue.equalsIgnoreCase("T") || SfldValue.equalsIgnoreCase("true") || SfldValue.equalsIgnoreCase("F") || SfldValue.equalsIgnoreCase("false") ))); } // default to true, it is a field we aren't validating (user etc.) return true; } /** {@collect.stats} * <p>Returns an XML String representing the descriptor.</p> * * <p>The format is not defined, but an implementation must * ensure that the string returned by this method can be * used to build an equivalent descriptor when instantiated * using the constructor {@link #DescriptorSupport(String) * DescriptorSupport(String inStr)}.</p> * * <p>Fields which are not String objects will have toString() * called on them to create the value. The value will be * enclosed in parentheses. It is not guaranteed that you can * reconstruct these objects unless they have been * specifically set up to support toString() in a meaningful * format and have a matching constructor that accepts a * String in the same format.</p> * * <p>If the descriptor is empty the following String is * returned: &lt;Descriptor&gt;&lt;/Descriptor&gt;</p> * * @return the XML string. * * @exception RuntimeOperationsException for illegal value for * field Names or field Values. If the XML formatted string * construction fails for any reason, this exception will be * thrown. */ public synchronized String toXMLString() { final StringBuilder buf = new StringBuilder("<Descriptor>"); Set returnedSet = descriptorMap.entrySet(); for (Iterator iter = returnedSet.iterator(); iter.hasNext(); ) { final Map.Entry currElement = (Map.Entry) iter.next(); final String name = currElement.getKey().toString(); Object value = currElement.getValue(); String valueString = null; /* Set valueString to non-null if and only if this is a string that cannot be confused with the encoding of an object. If it could be so confused (surrounded by parentheses) then we call makeFieldValue as for any non-String object and end up with an encoding like "(java.lang.String/(thing))". */ if (value instanceof String) { final String svalue = (String) value; if (!svalue.startsWith("(") || !svalue.endsWith(")")) valueString = quote(svalue); } if (valueString == null) valueString = makeFieldValue(value); buf.append("<field name=\"").append(name).append("\" value=\"") .append(valueString).append("\"></field>"); } buf.append("</Descriptor>"); return buf.toString(); } private static final String[] entities = { " &#32;", "\"&quot;", "<&lt;", ">&gt;", "&&amp;", "\r&#13;", "\t&#9;", "\n&#10;", "\f&#12;", }; private static final Map<String,Character> entityToCharMap = new HashMap<String,Character>(); private static final String[] charToEntityMap; static { char maxChar = 0; for (int i = 0; i < entities.length; i++) { final char c = entities[i].charAt(0); if (c > maxChar) maxChar = c; } charToEntityMap = new String[maxChar + 1]; for (int i = 0; i < entities.length; i++) { final char c = entities[i].charAt(0); final String entity = entities[i].substring(1); charToEntityMap[c] = entity; entityToCharMap.put(entity, new Character(c)); } } private static boolean isMagic(char c) { return (c < charToEntityMap.length && charToEntityMap[c] != null); } /* * Quote the string so that it will be acceptable to the (String) * constructor. Since the parsing code in that constructor is fairly * stupid, we're obliged to quote apparently innocuous characters like * space, <, and >. In a future version, we should rewrite the parser * and only quote " plus either \ or & (depending on the quote syntax). */ private static String quote(String s) { boolean found = false; for (int i = 0; i < s.length(); i++) { if (isMagic(s.charAt(i))) { found = true; break; } } if (!found) return s; final StringBuilder buf = new StringBuilder(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (isMagic(c)) buf.append(charToEntityMap[c]); else buf.append(c); } return buf.toString(); } private static String unquote(String s) throws XMLParseException { if (!s.startsWith("\"") || !s.endsWith("\"")) throw new XMLParseException("Value must be quoted: <" + s + ">"); final StringBuilder buf = new StringBuilder(); final int len = s.length() - 1; for (int i = 1; i < len; i++) { final char c = s.charAt(i); final int semi; final Character quoted; if (c == '&' && (semi = s.indexOf(';', i + 1)) >= 0 && ((quoted = entityToCharMap.get(s.substring(i, semi+1))) != null)) { buf.append(quoted); i = semi; } else buf.append(c); } return buf.toString(); } /** {@collect.stats} * Make the string that will go inside "..." for a value that is not * a plain String. * @throws RuntimeOperationsException if the value cannot be encoded. */ private static String makeFieldValue(Object value) { if (value == null) return "(null)"; Class<?> valueClass = value.getClass(); try { valueClass.getConstructor(String.class); } catch (NoSuchMethodException e) { final String msg = "Class " + valueClass + " does not have a public " + "constructor with a single string arg"; final RuntimeException iae = new IllegalArgumentException(msg); throw new RuntimeOperationsException(iae, "Cannot make XML descriptor"); } catch (SecurityException e) { // OK: we'll pretend the constructor is there // too bad if it's not: we'll find out when we try to // reconstruct the DescriptorSupport } final String quotedValueString = quote(value.toString()); return "(" + valueClass.getName() + "/" + quotedValueString + ")"; } /* * Parse a field value from the XML produced by toXMLString(). * Given a descriptor XML containing <field name="nnn" value="vvv">, * the argument to this method will be "vvv" (a string including the * containing quote characters). If vvv begins and ends with parentheses, * then it may contain: * - the characters "null", in which case the result is null; * - a value of the form "some.class.name/xxx", in which case the * result is equivalent to `new some.class.name("xxx")'; * - some other string, in which case the result is that string, * without the parentheses. */ private static Object parseQuotedFieldValue(String s) throws XMLParseException { s = unquote(s); if (s.equalsIgnoreCase("(null)")) return null; if (!s.startsWith("(") || !s.endsWith(")")) return s; final int slash = s.indexOf('/'); if (slash < 0) { // compatibility: old code didn't include class name return s.substring(1, s.length() - 1); } final String className = s.substring(1, slash); final Constructor<?> constr; try { final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); if (contextClassLoader == null) { ReflectUtil.checkPackageAccess(className); } final Class<?> c = Class.forName(className, false, contextClassLoader); constr = c.getConstructor(new Class[] {String.class}); } catch (Exception e) { throw new XMLParseException(e, "Cannot parse value: <" + s + ">"); } final String arg = s.substring(slash + 1, s.length() - 1); try { return constr.newInstance(new Object[] {arg}); } catch (Exception e) { final String msg = "Cannot construct instance of " + className + " with arg: <" + s + ">"; throw new XMLParseException(e, msg); } } /** {@collect.stats} * Returns <pv>a human readable string representing the * descriptor</pv>. The string will be in the format of * "fieldName=fieldValue,fieldName2=fieldValue2,..."<br> * * If there are no fields in the descriptor, then an empty String * is returned.<br> * * If a fieldValue is an object then the toString() method is * called on it and its returned value is used as the value for * the field enclosed in parenthesis. * * @exception RuntimeOperationsException for illegal value for * field Names or field Values. If the descriptor string fails * for any reason, this exception will be thrown. */ public synchronized String toString() { if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "toString()", "Entry"); } String respStr = ""; String[] fields = getFields(); if ((fields == null) || (fields.length == 0)) { if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "toString()", "Empty Descriptor"); } return respStr; } if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "toString()", "Printing " + fields.length + " fields"); } for (int i=0; i < fields.length; i++) { if (i == (fields.length - 1)) { respStr = respStr.concat(fields[i]); } else { respStr = respStr.concat(fields[i] + ", "); } } if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "toString()", "Exit returning " + respStr); } return respStr; } // utility to convert to int, returns -2 if bogus. private long toNumeric(String inStr) { long result = -2; try { result = java.lang.Long.parseLong(inStr); } catch (Exception e) { return -2; } return result; } /** {@collect.stats} * Deserializes a {@link DescriptorSupport} from an {@link * ObjectInputStream}. */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { ObjectInputStream.GetField fields = in.readFields(); Map<String, Object> descriptor = cast(fields.get("descriptor", null)); init(null); if (descriptor != null) { descriptorMap.putAll(descriptor); } } /** {@collect.stats} * Serializes a {@link DescriptorSupport} to an {@link ObjectOutputStream}. */ /* If you set jmx.serial.form to "1.2.0" or "1.2.1", then we are bug-compatible with those versions. Specifically, field names are forced to lower-case before being written. This contradicts the spec, which, though it does not mention serialization explicitly, does say that the case of field names is preserved. But in 1.2.0 and 1.2.1, this requirement was not met. Instead, field names in the descriptor map were forced to lower case. Those versions expect this to have happened to a descriptor they deserialize and e.g. getFieldValue will not find a field whose name is spelt with a different case. */ private void writeObject(ObjectOutputStream out) throws IOException { ObjectOutputStream.PutField fields = out.putFields(); boolean compat = "1.0".equals(serialForm); if (compat) fields.put("currClass", currClass); /* Purge the field "targetObject" from the DescriptorSupport before * serializing since the referenced object is typically not * serializable. We do this here rather than purging the "descriptor" * variable below because that HashMap doesn't do case-insensitivity. * See CR 6332962. */ SortedMap<String, Object> startMap = descriptorMap; if (startMap.containsKey("targetObject")) { startMap = new TreeMap<String, Object>(descriptorMap); startMap.remove("targetObject"); } final HashMap<String, Object> descriptor; if (compat || "1.2.0".equals(serialForm) || "1.2.1".equals(serialForm)) { descriptor = new HashMap<String, Object>(); for (Map.Entry<String, Object> entry : startMap.entrySet()) descriptor.put(entry.getKey().toLowerCase(), entry.getValue()); } else descriptor = new HashMap<String, Object>(startMap); fields.put("descriptor", descriptor); out.writeFields(); } }
Java
/* * Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ /* * @author IBM Corp. * * Copyright IBM Corp. 1999-2000. All rights reserved. */ package javax.management.modelmbean; import javax.management.DynamicMBean; import javax.management.InstanceNotFoundException; import javax.management.MBeanException; import javax.management.PersistentMBean; import javax.management.RuntimeOperationsException; /** {@collect.stats} * This interface must be implemented by the ModelMBeans. An implementation of this interface * must be shipped with every JMX Agent. * <P> * Java resources wishing to be manageable instantiate the ModelMBean using the MBeanServer's * createMBean method. The resource then sets the ModelMBeanInfo (with Descriptors) for the ModelMBean * instance. The attributes and operations exposed via the ModelMBeanInfo for the ModelMBean are accessible * from MBeans, connectors/adaptors like other MBeans. Through the ModelMBeanInfo Descriptors, values and methods in * the managed application can be defined and mapped to attributes and operations of the ModelMBean. * This mapping can be defined during development in an XML formatted file or dynamically and * programmatically at runtime. * <P> * Every ModelMBean which is instantiated in the MBeanServer becomes manageable: * its attributes and operations * become remotely accessible through the connectors/adaptors connected to that MBeanServer. * A Java object cannot be registered in the MBeanServer unless it is a JMX compliant MBean. * By instantiating a ModelMBean, resources are guaranteed that the MBean is valid. * <P> * MBeanException and RuntimeOperationsException must be thrown on every public method. This allows * for wrapping exceptions from distributed communications (RMI, EJB, etc.). These exceptions do * not have to be thrown by the implementation except in the scenarios described in the specification * and javadoc. * * @since 1.5 */ public interface ModelMBean extends DynamicMBean, PersistentMBean, ModelMBeanNotificationBroadcaster { /** {@collect.stats} * Initializes a ModelMBean object using ModelMBeanInfo passed in. * This method makes it possible to set a customized ModelMBeanInfo on * the ModelMBean as long as it is not registered with the MBeanServer. * <br> * Once the ModelMBean's ModelMBeanInfo (with Descriptors) are * customized and set on the ModelMBean, the ModelMBean can be * registered with the MBeanServer. * <P> * If the ModelMBean is currently registered, this method throws * a {@link javax.management.RuntimeOperationsException} wrapping an * {@link IllegalStateException} * * @param inModelMBeanInfo The ModelMBeanInfo object to be used * by the ModelMBean. * * @exception MBeanException Wraps a distributed communication * Exception. * @exception RuntimeOperationsException * <ul><li>Wraps an {@link IllegalArgumentException} if * the MBeanInfo passed in parameter is null.</li> * <li>Wraps an {@link IllegalStateException} if the ModelMBean * is currently registered in the MBeanServer.</li> * </ul> * **/ public void setModelMBeanInfo(ModelMBeanInfo inModelMBeanInfo) throws MBeanException, RuntimeOperationsException; /** {@collect.stats} * Sets the instance handle of the object against which to * execute all methods in this ModelMBean management interface * (MBeanInfo and Descriptors). * * @param mr Object that is the managed resource * @param mr_type The type of reference for the managed resource. Can be: ObjectReference, * Handle, IOR, EJBHandle, RMIReference. * If the MBeanServer cannot process the mr_type passed in, an InvalidTargetTypeException * will be thrown. * * * @exception MBeanException The initializer of the object has thrown an exception. * @exception RuntimeOperationsException Wraps an IllegalArgumentException: * The managed resource type passed in parameter is null. * @exception InstanceNotFoundException The managed resource object could not be found * @exception InvalidTargetObjectTypeException The managed resource type cannot be processed by the * ModelMBean or JMX Agent. */ public void setManagedResource(Object mr, String mr_type) throws MBeanException, RuntimeOperationsException, InstanceNotFoundException, InvalidTargetObjectTypeException ; }
Java
/* * Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ /* * @author IBM Corp. * * Copyright IBM Corp. 1999-2000. All rights reserved. */ package javax.management.modelmbean; import static com.sun.jmx.defaults.JmxProperties.MODELMBEAN_LOGGER; import com.sun.jmx.mbeanserver.GetPropertyAction; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.ObjectStreamField; import java.lang.reflect.Method; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.logging.Level; import javax.management.Descriptor; import javax.management.DescriptorKey; import javax.management.DescriptorAccess; import javax.management.MBeanAttributeInfo; import javax.management.RuntimeOperationsException; /** {@collect.stats} * The ModelMBeanAttributeInfo object describes an attribute of the ModelMBean. * It is a subclass of MBeanAttributeInfo with the addition of an associated Descriptor * and an implementation of the DescriptorAccess interface. * <P> * The fields in the descriptor are defined, but not limited to, the following: <P> * <PRE> * name : attribute name * descriptorType : must be "attribute" * value : current value for attribute * default : default value for attribute * displayName : name of attribute to be used in displays * getMethod : name of operation descriptor for get method * setMethod : name of operation descriptor for set method * protocolMap : object which implements the Descriptor interface: mappings must be appropriate for the attribute * and entries can be updated or augmented at runtime. * persistPolicy : OnUpdate|OnTimer|NoMoreOftenThan|OnUnregister|Always|Never * persistPeriod : seconds - frequency of persist cycle. Used when persistPolicy is"OnTimer" or "NoMoreOftenThan". * currencyTimeLimit : how long value is valid, &lt;0 never, =0 always, &gt;0 seconds * lastUpdatedTimeStamp : when value was set * visibility : 1-4 where 1: always visible 4: rarely visible * presentationString : xml formatted string to allow presentation of data * </PRE> * The default descriptor contains the name, descriptorType and displayName fields. * * <p><b>Note:</b> because of inconsistencies in previous versions of * this specification, it is recommended not to use negative or zero * values for <code>currencyTimeLimit</code>. To indicate that a * cached value is never valid, omit the * <code>currencyTimeLimit</code> field. To indicate that it is * always valid, use a very large number for this field.</p> * * <p>The <b>serialVersionUID</b> of this class is <code>6181543027787327345L</code>. * * @since 1.5 */ @SuppressWarnings("serial") // serialVersionUID is not constant public class ModelMBeanAttributeInfo extends MBeanAttributeInfo implements DescriptorAccess { // Serialization compatibility stuff: // Two serial forms are supported in this class. The selected form depends // on system property "jmx.serial.form": // - "1.0" for JMX 1.0 // - any other value for JMX 1.1 and higher // // Serial version for old serial form private static final long oldSerialVersionUID = 7098036920755973145L; // // Serial version for new serial form private static final long newSerialVersionUID = 6181543027787327345L; // // Serializable fields in old serial form private static final ObjectStreamField[] oldSerialPersistentFields = { new ObjectStreamField("attrDescriptor", Descriptor.class), new ObjectStreamField("currClass", String.class) }; // // Serializable fields in new serial form private static final ObjectStreamField[] newSerialPersistentFields = { new ObjectStreamField("attrDescriptor", Descriptor.class) }; // // Actual serial version and serial form private static final long serialVersionUID; /** {@collect.stats} * @serialField attrDescriptor Descriptor The {@link Descriptor} containing the metadata corresponding to * this attribute */ private static final ObjectStreamField[] serialPersistentFields; private static boolean compat = false; static { try { GetPropertyAction act = new GetPropertyAction("jmx.serial.form"); String form = AccessController.doPrivileged(act); compat = (form != null && form.equals("1.0")); } catch (Exception e) { // OK: No compat with 1.0 } if (compat) { serialPersistentFields = oldSerialPersistentFields; serialVersionUID = oldSerialVersionUID; } else { serialPersistentFields = newSerialPersistentFields; serialVersionUID = newSerialVersionUID; } } // // END Serialization compatibility stuff /** {@collect.stats} * @serial The {@link Descriptor} containing the metadata corresponding to * this attribute */ private Descriptor attrDescriptor = createDefaultDescriptor(); private final static String currClass = "ModelMBeanAttributeInfo"; /** {@collect.stats} * Constructs a ModelMBeanAttributeInfo object with a default * descriptor. The {@link Descriptor} of the constructed * object will include fields contributed by any annotations * on the {@code Method} objects that contain the {@link * DescriptorKey} meta-annotation. * * @param name The name of the attribute. * @param description A human readable description of the attribute. Optional. * @param getter The method used for reading the attribute value. * May be null if the property is write-only. * @param setter The method used for writing the attribute value. * May be null if the attribute is read-only. * @exception IntrospectionException There is a consistency problem in the definition of this attribute. * */ public ModelMBeanAttributeInfo(String name, String description, Method getter, Method setter) throws javax.management.IntrospectionException { super(name, description, getter, setter); if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanAttributeInfo.class.getName(), "ModelMBeanAttributeInfo(" + "String,String,Method,Method)", "Entry", name); } attrDescriptor = createDefaultDescriptor(); // put getter and setter methods in operations list // create default descriptor } /** {@collect.stats} * Constructs a ModelMBeanAttributeInfo object. The {@link * Descriptor} of the constructed object will include fields * contributed by any annotations on the {@code Method} * objects that contain the {@link DescriptorKey} * meta-annotation. * * @param name The name of the attribute. * @param description A human readable description of the attribute. Optional. * @param getter The method used for reading the attribute value. * May be null if the property is write-only. * @param setter The method used for writing the attribute value. * May be null if the attribute is read-only. * @param descriptor An instance of Descriptor containing the appropriate metadata * for this instance of the Attribute. If it is null, then a default descriptor will be created. * If the descriptor does not contain the field "displayName" this field is added in the descriptor with its default value. * * @exception IntrospectionException There is a consistency problem in the definition of this attribute. * @exception RuntimeOperationsException Wraps an IllegalArgumentException. The descriptor is invalid, or descriptor field "name" is not * equal to name parameter, or descriptor field "DescriptorType" is not equal to "attribute". * */ public ModelMBeanAttributeInfo(String name, String description, Method getter, Method setter, Descriptor descriptor) throws javax.management.IntrospectionException { super(name, description, getter, setter); // put getter and setter methods in operations list if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanAttributeInfo.class.getName(), "ModelMBeanAttributeInfo(" + "String,String,Method,Method,Descriptor)", "Entry", name); } if (descriptor == null) { attrDescriptor = createDefaultDescriptor(); } else { if (isValid(descriptor)) { attrDescriptor = (Descriptor) descriptor.clone(); } else { throw new RuntimeOperationsException(new IllegalArgumentException("Invalid descriptor passed in parameter"), ("Exception occurred in ModelMBeanAttributeInfo constructor")); } } } /** {@collect.stats} * Constructs a ModelMBeanAttributeInfo object with a default descriptor. * * @param name The name of the attribute * @param type The type or class name of the attribute * @param description A human readable description of the attribute. * @param isReadable True if the attribute has a getter method, false otherwise. * @param isWritable True if the attribute has a setter method, false otherwise. * @param isIs True if the attribute has an "is" getter, false otherwise. * */ public ModelMBeanAttributeInfo(String name, String type, String description, boolean isReadable, boolean isWritable, boolean isIs) { super(name, type, description, isReadable, isWritable, isIs); // create default descriptor if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanAttributeInfo.class.getName(), "ModelMBeanAttributeInfo(" + "String,String,String,boolean,boolean,boolean)", "Entry", name); } attrDescriptor = createDefaultDescriptor(); } /** {@collect.stats} * Constructs a ModelMBeanAttributeInfo object with a default descriptor. * * @param name The name of the attribute * @param type The type or class name of the attribute * @param description A human readable description of the attribute. * @param isReadable True if the attribute has a getter method, false otherwise. * @param isWritable True if the attribute has a setter method, false otherwise. * @param isIs True if the attribute has an "is" getter, false otherwise. * @param descriptor An instance of Descriptor containing the appropriate metadata * for this instance of the Attribute. If it is null then a default descriptor will be created. * If the descriptor does not contain the field "displayName" this field is added in the descriptor with its default value. * * @exception RuntimeOperationsException Wraps an IllegalArgumentException. The descriptor is invalid, or descriptor field "name" is not * equal to name parameter, or descriptor field "DescriptorType" is not equal to "attribute". * */ public ModelMBeanAttributeInfo(String name, String type, String description, boolean isReadable, boolean isWritable, boolean isIs, Descriptor descriptor) { super(name, type, description, isReadable, isWritable, isIs); if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanAttributeInfo.class.getName(), "ModelMBeanAttributeInfo(String,String,String," + "boolean,boolean,boolean,Descriptor)", "Entry", name); } if (descriptor == null) { attrDescriptor = createDefaultDescriptor(); } else { if (isValid(descriptor)) { attrDescriptor = (Descriptor) descriptor.clone(); } else { throw new RuntimeOperationsException(new IllegalArgumentException("Invalid descriptor passed in parameter"), ("Exception occurred in ModelMBeanAttributeInfo constructor")); } } } /** {@collect.stats} * Constructs a new ModelMBeanAttributeInfo object from this ModelMBeanAttributeInfo Object. * A default descriptor will be created. * * @param inInfo the ModelMBeanAttributeInfo to be duplicated */ public ModelMBeanAttributeInfo(ModelMBeanAttributeInfo inInfo) { super(inInfo.getName(), inInfo.getType(), inInfo.getDescription(), inInfo.isReadable(), inInfo.isWritable(), inInfo.isIs()); if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanAttributeInfo.class.getName(), "ModelMBeanAttributeInfo(ModelMBeanAttributeInfo)", "Entry"); } Descriptor newDesc = inInfo.getDescriptor(); //Descriptor newDesc = inInfo.attrDescriptor; if ((newDesc != null) && (isValid(newDesc))) { attrDescriptor = newDesc; } else { attrDescriptor = createDefaultDescriptor(); } } /** {@collect.stats} * Gets a copy of the associated Descriptor for the * ModelMBeanAttributeInfo. * * @return Descriptor associated with the * ModelMBeanAttributeInfo object. * * @see #setDescriptor */ public Descriptor getDescriptor() { if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanAttributeInfo.class.getName(), "getDescriptor()", "Entry"); } if (attrDescriptor == null) { attrDescriptor = createDefaultDescriptor(); } return((Descriptor)attrDescriptor.clone()); } /** {@collect.stats} * Sets associated Descriptor (full replace) for the * ModelMBeanAttributeDescriptor. If the new Descriptor is * null, then the associated Descriptor reverts to a default * descriptor. The Descriptor is validated before it is * assigned. If the new Descriptor is invalid, then a * RuntimeOperationsException wrapping an * IllegalArgumentException is thrown. * * @param inDescriptor replaces the Descriptor associated with the * ModelMBeanAttributeInfo * * @exception RuntimeOperationsException Wraps an * IllegalArgumentException for an invalid Descriptor * * @see #getDescriptor */ public void setDescriptor(Descriptor inDescriptor) { if (inDescriptor == null) { if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanAttributeInfo.class.getName(), "setDescriptor(Descriptor)", "Received null for new descriptor value, " + "setting descriptor to default values"); } attrDescriptor = createDefaultDescriptor(); } else { if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanAttributeInfo.class.getName(), "setDescriptor(Descriptor)", "Executed for " + inDescriptor.toString()); } if (isValid(inDescriptor)) { attrDescriptor = (Descriptor) inDescriptor.clone(); } else { throw new RuntimeOperationsException(new IllegalArgumentException("Invalid descriptor passed in parameter"), ("Exception occurred in ModelMBeanAttributeInfo setDescriptor")); } } } /** {@collect.stats} * Creates and returns a new ModelMBeanAttributeInfo which is a duplicate of this ModelMBeanAttributeInfo. * * @exception RuntimeOperationsException for illegal value for field Names or field Values. * If the descriptor construction fails for any reason, this exception will be thrown. */ public Object clone() { if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanAttributeInfo.class.getName(), "clone()", "Entry"); } return(new ModelMBeanAttributeInfo(this)); } /** {@collect.stats} * Returns a human-readable version of the * ModelMBeanAttributeInfo instance. */ public String toString() { return "ModelMBeanAttributeInfo: " + this.getName() + " ; Description: " + this.getDescription() + " ; Types: " + this.getType() + " ; isReadable: " + this.isReadable() + " ; isWritable: " + this.isWritable() + " ; Descriptor: " + this.getDescriptor(); } /** {@collect.stats} * Creates and returns a Descriptor with default values set: * descriptorType=attribute,name=this.getName(),displayName=this.getName(), * persistPolicy=never,visibility=1 */ private Descriptor createDefaultDescriptor() { if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanAttributeInfo.class.getName(), "createDefaultDescriptor()", "Entry"); } return new DescriptorSupport( new String[] {"descriptorType=attribute", ("name=" + this.getName()), ("displayName=" + this.getName()) }); } /** {@collect.stats} * Tests that the descriptor is valid and adds appropriate default fields not already * specified. Field values must be correct for field names. * Descriptor must have the same name as the attribute,the descriptorType field must be "attribute", * The following fields will be defaulted if they are not already set: * displayName=this.getName(),persistPolicy=never,visibility=1 */ private boolean isValid(Descriptor inDesc) { // name and descriptor type must be correct // add in displayName, persistPolicy, visibility if they apply boolean results=true; String badField="none"; if (inDesc == null) { badField="nullDescriptor"; results = false; } else if (!inDesc.isValid()) { // checks for empty descriptors, null, // checks for empty name and descriptorType adn valid values for fields. badField="inValidDescriptor"; results = false; } else if (! ((String)inDesc.getFieldValue("name")).equalsIgnoreCase(this.getName())) { badField="name"; results = false; } else { if (! ((String)inDesc.getFieldValue("descriptorType")).equalsIgnoreCase("attribute")) { badField="desriptorType"; results = false; } else if ((inDesc.getFieldValue("displayName")) == null) { inDesc.setField("displayName",this.getName()); } } if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) { MODELMBEAN_LOGGER.logp(Level.FINER, ModelMBeanAttributeInfo.class.getName(), "isValid()", "Returning " + results + " : Invalid field is " + badField); } return results; } /** {@collect.stats} * Deserializes a {@link ModelMBeanAttributeInfo} from an {@link ObjectInputStream}. */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { // New serial form ignores extra field "currClass" in.defaultReadObject(); } /** {@collect.stats} * Serializes a {@link ModelMBeanAttributeInfo} to an {@link ObjectOutputStream}. */ private void writeObject(ObjectOutputStream out) throws IOException { if (compat) { // Serializes this instance in the old serial form // ObjectOutputStream.PutField fields = out.putFields(); fields.put("attrDescriptor", attrDescriptor); fields.put("currClass", currClass); out.writeFields(); } else { // Serializes this instance in the new serial form // out.defaultWriteObject(); } } }
Java
/* * Copyright (c) 1999, 2004, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management; /** {@collect.stats} * Represents values that can be passed as arguments to * relational expressions. Strings, numbers, attributes are valid values * and should be represented by implementations of <CODE>ValueExp</CODE>. * * @since 1.5 */ /* We considered generifying this interface as ValueExp<T>, where T is the Java type that this expression generates. This allows some additional checking in the various methods of the Query class, but in practice not much. Typically you have something like Query.lt(Query.attr("A"), Query.value(5)). We can arrange for Query.value to have type ValueExp<Integer> (or maybe ValueExp<Long> or ValueExp<Number>) but for Query.attr we can't do better than ValueExp<?> or plain ValueExp. So even though we could define Query.lt as: QueryExp <T> lt(ValueExp<T> v1, ValueExp<T> v2) and thus prevent comparing a number against a string, in practice the first ValueExp will almost always be a Query.attr so this check serves no purpose. You would have to write Query.<Number>attr("A"), for example, which would be awful. And, if you wrote Query.<Integer>attr("A") you would then discover that you couldn't compare it against Query.value(5) if the latter is defined as ValueExp<Number>, or against Query.value(5L) if it is defined as ValueExp<Integer>. Worse, for Query.in we would like to define: QueryExp <T> in(ValueExp<T> val, ValueExp<T>[] valueList) but this is unusable because you cannot write "new ValueExp<Integer>[] {...}" (the compiler forbids it). The few mistakes you might catch with this generification certainly wouldn't justify the hassle of modifying user code to get the checks to be made and the "unchecked" warnings that would arise if it wasn't so modified. We could reconsider this if the Query methods were augmented, for example with: AttributeValueExp<Number> numberAttr(String name); AttributeValueExp<String> stringAttr(String name); AttributeValueExp<Boolean> booleanAttr(String name); QueryExp <T> in(ValueExp<T> val, Set<ValueExp<T>> valueSet). But it's not really clear what numberAttr should do if it finds that the attribute is not in fact a Number. */ public interface ValueExp extends java.io.Serializable { /** {@collect.stats} * Applies the ValueExp on a MBean. * * @param name The name of the MBean on which the ValueExp will be applied. * * @return The <CODE>ValueExp</CODE>. * * @exception BadStringOperationException * @exception BadBinaryOpValueExpException * @exception BadAttributeValueExpException * @exception InvalidApplicationException */ public ValueExp apply(ObjectName name) throws BadStringOperationException, BadBinaryOpValueExpException, BadAttributeValueExpException, InvalidApplicationException; /** {@collect.stats} * Sets the MBean server on which the query is to be performed. * * @param s The MBean server on which the query is to be performed. * * @deprecated This method is not needed because a * <code>ValueExp</code> can access the MBean server in which it * is being evaluated by using {@link QueryEval#getMBeanServer()}. */ @Deprecated public void setMBeanServer(MBeanServer s) ; }
Java
/* * Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management; /** {@collect.stats} * The specified MBean does not exist in the repository. * * @since 1.5 */ public class InstanceNotFoundException extends OperationsException { /* Serial version */ private static final long serialVersionUID = -882579438394773049L; /** {@collect.stats} * Default constructor. */ public InstanceNotFoundException() { super(); } /** {@collect.stats} * Constructor that allows a specific error message to be specified. * * @param message the detail message. */ public InstanceNotFoundException(String message) { super(message); } }
Java
/* * Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management; /** {@collect.stats} * Represents "user defined" exceptions thrown by MBean methods * in the agent. It "wraps" the actual "user defined" exception thrown. * This exception will be built by the MBeanServer when a call to an * MBean method results in an unknown exception. * * @since 1.5 */ public class MBeanException extends JMException { /* Serial version */ private static final long serialVersionUID = 4066342430588744142L; /** {@collect.stats} * @serial Encapsulated {@link Exception} */ private java.lang.Exception exception ; /** {@collect.stats} * Creates an <CODE>MBeanException</CODE> that wraps the actual <CODE>java.lang.Exception</CODE>. * * @param e the wrapped exception. */ public MBeanException(java.lang.Exception e) { super() ; exception = e ; } /** {@collect.stats} * Creates an <CODE>MBeanException</CODE> that wraps the actual <CODE>java.lang.Exception</CODE> with * a detail message. * * @param e the wrapped exception. * @param message the detail message. */ public MBeanException(java.lang.Exception e, String message) { super(message) ; exception = e ; } /** {@collect.stats} * Return the actual {@link Exception} thrown. * * @return the wrapped exception. */ public Exception getTargetException() { return exception; } /** {@collect.stats} * Return the actual {@link Exception} thrown. * * @return the wrapped exception. */ public Throwable getCause() { return exception; } }
Java
/* * Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management; /** {@collect.stats} * Represents exceptions thrown in the MBean server when performing operations * on MBeans. * * @since 1.5 */ public class OperationsException extends JMException { /* Serial version */ private static final long serialVersionUID = -4967597595580536216L; /** {@collect.stats} * Default constructor. */ public OperationsException() { super(); } /** {@collect.stats} * Constructor that allows a specific error message to be specified. * * @param message the detail message. */ public OperationsException(String message) { super(message); } }
Java
/* * Copyright (c) 1999, 2006, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management; import java.util.Vector; /** {@collect.stats} * This class implements of the {@link javax.management.NotificationFilter NotificationFilter} * interface for the {@link javax.management.AttributeChangeNotification attribute change notification}. * The filtering is performed on the name of the observed attribute. * <P> * It manages a list of enabled attribute names. * A method allows users to enable/disable as many attribute names as required. * * @since 1.5 */ public class AttributeChangeNotificationFilter implements NotificationFilter { /* Serial version */ private static final long serialVersionUID = -6347317584796410029L; /** {@collect.stats} * @serial {@link Vector} that contains the enabled attribute names. * The default value is an empty vector. */ private Vector<String> enabledAttributes = new Vector<String>(); /** {@collect.stats} * Invoked before sending the specified notification to the listener. * <BR>This filter compares the attribute name of the specified attribute change notification * with each enabled attribute name. * If the attribute name equals one of the enabled attribute names, * the notification must be sent to the listener and this method returns <CODE>true</CODE>. * * @param notification The attribute change notification to be sent. * @return <CODE>true</CODE> if the notification has to be sent to the listener, <CODE>false</CODE> otherwise. */ public synchronized boolean isNotificationEnabled(Notification notification) { String type = notification.getType(); if ((type == null) || (type.equals(AttributeChangeNotification.ATTRIBUTE_CHANGE) == false) || (!(notification instanceof AttributeChangeNotification))) { return false; } String attributeName = ((AttributeChangeNotification)notification).getAttributeName(); return enabledAttributes.contains(attributeName); } /** {@collect.stats} * Enables all the attribute change notifications the attribute name of which equals * the specified name to be sent to the listener. * <BR>If the specified name is already in the list of enabled attribute names, * this method has no effect. * * @param name The attribute name. * @exception java.lang.IllegalArgumentException The attribute name parameter is null. */ public synchronized void enableAttribute(String name) throws java.lang.IllegalArgumentException { if (name == null) { throw new java.lang.IllegalArgumentException("The name cannot be null."); } if (!enabledAttributes.contains(name)) { enabledAttributes.addElement(name); } } /** {@collect.stats} * Disables all the attribute change notifications the attribute name of which equals * the specified attribute name to be sent to the listener. * <BR>If the specified name is not in the list of enabled attribute names, * this method has no effect. * * @param name The attribute name. */ public synchronized void disableAttribute(String name) { enabledAttributes.removeElement(name); } /** {@collect.stats} * Disables all the attribute names. */ public synchronized void disableAllAttributes() { enabledAttributes.removeAllElements(); } /** {@collect.stats} * Gets all the enabled attribute names for this filter. * * @return The list containing all the enabled attribute names. */ public synchronized Vector<String> getEnabledAttributes() { return enabledAttributes; } }
Java
/* * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management; import java.lang.annotation.*; /** {@collect.stats} * <p>Meta-annotation that describes how an annotation element relates * to a field in a {@link Descriptor}. This can be the Descriptor for * an MBean, or for an attribute, operation, or constructor in an * MBean, or for a parameter of an operation or constructor.</p> * * <p>Consider this annotation for example:</p> * * <pre> * &#64;Documented * &#64;Target(ElementType.METHOD) * &#64;Retention(RetentionPolicy.RUNTIME) * public &#64;interface Units { * <b>&#64;DescriptorKey("units")</b> * String value(); * } * </pre> * * <p>and this use of the annotation:</p> * * <pre> * public interface CacheControlMBean { * <b>&#64;Units("bytes")</b> * public long getCacheSize(); * } * </pre> * * <p>When a Standard MBean is made from the {@code CacheControlMBean}, * the usual rules mean that it will have an attribute called * {@code CacheSize} of type {@code long}. The {@code @Units} * attribute, given the above definition, will ensure that the * {@link MBeanAttributeInfo} for this attribute will have a * {@code Descriptor} that has a field called {@code units} with * corresponding value {@code bytes}.</p> * * <p>Similarly, if the annotation looks like this:</p> * * <pre> * &#64;Documented * &#64;Target(ElementType.METHOD) * &#64;Retention(RetentionPolicy.RUNTIME) * public &#64;interface Units { * <b>&#64;DescriptorKey("units")</b> * String value(); * * <b>&#64;DescriptorKey("descriptionResourceKey")</b> * String resourceKey() default ""; * * <b>&#64;DescriptorKey("descriptionResourceBundleBaseName")</b> * String resourceBundleBaseName() default ""; * } * </pre> * * <p>and it is used like this:</p> * * <pre> * public interface CacheControlMBean { * <b>&#64;Units("bytes", * resourceKey="bytes.key", * resourceBundleBaseName="com.example.foo.MBeanResources")</b> * public long getCacheSize(); * } * </pre> * * <p>then the resulting {@code Descriptor} will contain the following * fields:</p> * * <table border="2"> * <tr><th>Name</th><th>Value</th></tr> * <tr><td>units</td><td>"bytes"</td></tr> * <tr><td>descriptionResourceKey</td><td>"bytes.key"</td></tr> * <tr><td>descriptionResourceBundleBaseName</td> * <td>"com.example.foo.MBeanResources"</td></tr> * </table> * * <p>An annotation such as {@code @Units} can be applied to:</p> * * <ul> * <li>a Standard MBean or MXBean interface; * <li>a method in such an interface; * <li>a parameter of a method in a Standard MBean or MXBean interface * when that method is an operation (not a getter or setter for an attribute); * <li>a public constructor in the class that implements a Standard MBean * or MXBean; * <li>a parameter in such a constructor. * </ul> * * <p>Other uses of the annotation are ignored.</p> * * <p>Interface annotations are checked only on the exact interface * that defines the management interface of a Standard MBean or an * MXBean, not on its parent interfaces. Method annotations are * checked only in the most specific interface in which the method * appears; in other words, if a child interface overrides a method * from a parent interface, only {@code @DescriptorKey} annotations in * the method in the child interface are considered. * * <p>The Descriptor fields contributed in this way by different * annotations on the same program element must be consistent. That * is, two different annotations, or two members of the same * annotation, must not define a different value for the same * Descriptor field. Fields from annotations on a getter method must * also be consistent with fields from annotations on the * corresponding setter method.</p> * * <p>The Descriptor resulting from these annotations will be merged * with any Descriptor fields provided by the implementation, such as * the <a href="Descriptor.html#immutableInfo">{@code * immutableInfo}</a> field for an MBean. The fields from the annotations * must be consistent with these fields provided by the implementation.</p> * * <p>An annotation element to be converted into a descriptor field * can be of any type allowed by the Java language, except an annotation * or an array of annotations. The value of the field is derived from * the value of the annotation element as follows:</p> * * <table border="2"> * <tr><th>Annotation element</th><th>Descriptor field</th></tr> * <tr><td>Primitive value ({@code 5}, {@code false}, etc)</td> * <td>Wrapped value ({@code Integer.valueOf(5)}, * {@code Boolean.FALSE}, etc)</td></tr> * <tr><td>Class constant (e.g. {@code Thread.class})</td> * <td>Class name from {@link Class#getName()} * (e.g. {@code "java.lang.Thread"})</td></tr> * <tr><td>Enum constant (e.g. {@link ElementType#FIELD})</td> * <td>Constant name from {@link Enum#name()} * (e.g. {@code "FIELD"})</td></tr> * <tr><td>Array of class constants or enum constants</td> * <td>String array derived by applying these rules to each * element</td></tr> * <tr><td>Value of any other type<br> * ({@code String}, {@code String[]}, {@code int[]}, etc)</td> * <td>The same value</td></tr> * </table> * * @since 1.6 */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface DescriptorKey { String value(); }
Java
/* * Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management; //RI import import javax.management.OperationsException; /** {@collect.stats} * Represents exceptions raised when a requested service is not supported. * * @since 1.5 */ public class ServiceNotFoundException extends OperationsException { /* Serial version */ private static final long serialVersionUID = -3990675661956646827L; /** {@collect.stats} * Default constructor. */ public ServiceNotFoundException() { super(); } /** {@collect.stats} * Constructor that allows a specific error message to be specified. * * @param message the detail message. */ public ServiceNotFoundException(String message) { super(message); } }
Java
/* * Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management; /** {@collect.stats} * This class is used by the query-building mechanism to represent binary * operations. * @serial include * * @since 1.5 */ class BinaryOpValueExp extends QueryEval implements ValueExp { /* Serial version */ private static final long serialVersionUID = 1216286847881456786L; /** {@collect.stats} * @serial The operator */ private int op; /** {@collect.stats} * @serial The first value */ private ValueExp exp1; /** {@collect.stats} * @serial The second value */ private ValueExp exp2; /** {@collect.stats} * Basic Constructor. */ public BinaryOpValueExp() { } /** {@collect.stats} * Creates a new BinaryOpValueExp using operator o applied on v1 and * v2 values. */ public BinaryOpValueExp(int o, ValueExp v1, ValueExp v2) { op = o; exp1 = v1; exp2 = v2; } /** {@collect.stats} * Returns the operator of the value expression. */ public int getOperator() { return op; } /** {@collect.stats} * Returns the left value of the value expression. */ public ValueExp getLeftValue() { return exp1; } /** {@collect.stats} * Returns the right value of the value expression. */ public ValueExp getRightValue() { return exp2; } /** {@collect.stats} * Applies the BinaryOpValueExp on a MBean. * * @param name The name of the MBean on which the BinaryOpValueExp will be applied. * * @return The ValueExp. * * @exception BadStringOperationException * @exception BadBinaryOpValueExpException * @exception BadAttributeValueExpException * @exception InvalidApplicationException */ public ValueExp apply(ObjectName name) throws BadStringOperationException, BadBinaryOpValueExpException, BadAttributeValueExpException, InvalidApplicationException { ValueExp val1 = exp1.apply(name); ValueExp val2 = exp2.apply(name); String sval1; String sval2; double dval1; double dval2; long lval1; long lval2; boolean numeric = val1 instanceof NumericValueExp; if (numeric) { if (((NumericValueExp)val1).isLong()) { lval1 = ((NumericValueExp)val1).longValue(); lval2 = ((NumericValueExp)val2).longValue(); switch (op) { case Query.PLUS: return Query.value(lval1 + lval2); case Query.TIMES: return Query.value(lval1 * lval2); case Query.MINUS: return Query.value(lval1 - lval2); case Query.DIV: return Query.value(lval1 / lval2); } } else { dval1 = ((NumericValueExp)val1).doubleValue(); dval2 = ((NumericValueExp)val2).doubleValue(); switch (op) { case Query.PLUS: return Query.value(dval1 + dval2); case Query.TIMES: return Query.value(dval1 * dval2); case Query.MINUS: return Query.value(dval1 - dval2); case Query.DIV: return Query.value(dval1 / dval2); } } } else { sval1 = ((StringValueExp)val1).getValue(); sval2 = ((StringValueExp)val2).getValue(); switch (op) { case Query.PLUS: return new StringValueExp(sval1 + sval2); default: throw new BadStringOperationException(opString()); } } throw new BadBinaryOpValueExpException(this); } /** {@collect.stats} * Returns the string representing the object */ public String toString() { try { return exp1 + " " + opString() + " " + exp2; } catch (BadBinaryOpValueExpException ex) { return "invalid expression"; } } private String opString() throws BadBinaryOpValueExpException { switch (op) { case Query.PLUS: return "+"; case Query.TIMES: return "*"; case Query.MINUS: return "-"; case Query.DIV: return "/"; } throw new BadBinaryOpValueExpException(this); } }
Java
/* * Copyright (c) 1999, 2004, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management; /** {@collect.stats} * This class is used by the query building mechanism to represent conjunctions * of relational expressions. * @serial include * * @since 1.5 */ class AndQueryExp extends QueryEval implements QueryExp { /* Serial version */ private static final long serialVersionUID = -1081892073854801359L; /** {@collect.stats} * @serial The first QueryExp of the conjunction */ private QueryExp exp1; /** {@collect.stats} * @serial The second QueryExp of the conjunction */ private QueryExp exp2; /** {@collect.stats} * Default constructor. */ public AndQueryExp() { } /** {@collect.stats} * Creates a new AndQueryExp with q1 and q2 QueryExp. */ public AndQueryExp(QueryExp q1, QueryExp q2) { exp1 = q1; exp2 = q2; } /** {@collect.stats} * Returns the left query expression. */ public QueryExp getLeftExp() { return exp1; } /** {@collect.stats} * Returns the right query expression. */ public QueryExp getRightExp() { return exp2; } /** {@collect.stats} * Applies the AndQueryExp on a MBean. * * @param name The name of the MBean on which the AndQueryExp will be applied. * * @return True if the query was successfully applied to the MBean, false otherwise. * * * @exception BadStringOperationException The string passed to the method is invalid. * @exception BadBinaryOpValueExpException The expression passed to the method is invalid. * @exception BadAttributeValueExpException The attribute value passed to the method is invalid. * @exception InvalidApplicationException An attempt has been made to apply a subquery expression to a * managed object or a qualified attribute expression to a managed object of the wrong class. */ public boolean apply(ObjectName name) throws BadStringOperationException, BadBinaryOpValueExpException, BadAttributeValueExpException, InvalidApplicationException { return exp1.apply(name) && exp2.apply(name); } /** {@collect.stats} * Returns a string representation of this AndQueryExp */ public String toString() { return "(" + exp1 + ") and (" + exp2 + ")"; } }
Java
/* * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; // remaining imports are for Javadoc import java.beans.ConstructorProperties; import java.io.InvalidObjectException; import java.lang.management.MemoryUsage; import java.lang.reflect.UndeclaredThrowableException; import java.util.Arrays; import java.util.List; import javax.management.openmbean.ArrayType; import javax.management.openmbean.CompositeData; import javax.management.openmbean.CompositeDataInvocationHandler; import javax.management.openmbean.CompositeDataSupport; import javax.management.openmbean.CompositeDataView; import javax.management.openmbean.CompositeType; import javax.management.openmbean.OpenDataException; import javax.management.openmbean.OpenMBeanInfo; import javax.management.openmbean.OpenType; import javax.management.openmbean.SimpleType; import javax.management.openmbean.TabularData; import javax.management.openmbean.TabularDataSupport; import javax.management.openmbean.TabularType; /** {@collect.stats} <p>Annotation to mark an interface explicitly as being an MXBean interface, or as not being an MXBean interface. By default, an interface is an MXBean interface if its name ends with {@code MXBean}, as in {@code SomethingMXBean}. The following interfaces are MXBean interfaces:</p> <pre> public interface WhatsitMXBean {} &#64;MXBean public interface Whatsit1Interface {} &#64;MXBean(true) public interface Whatsit2Interface {} </pre> <p>The following interfaces are not MXBean interfaces:</p> <pre> public interface Whatsit3Interface{} &#64;MXBean(false) public interface MisleadingMXBean {} </pre> <h3><a name="MXBean-spec">MXBean specification</a></h3> <p>The MXBean concept provides a simple way to code an MBean that only references a predefined set of types, the ones defined by {@link javax.management.openmbean}. In this way, you can be sure that your MBean will be usable by any client, including remote clients, without any requirement that the client have access to <em>model-specific classes</em> representing the types of your MBeans.</p> <p>The concepts are easier to understand by comparison with the Standard MBean concept. Here is how a managed object might be represented as a Standard MBean, and as an MXBean:</p> <table border="1" cellpadding="5"> <tr> <th>Standard MBean</th><th>MXBean</th> </tr> <tr> <td><pre> public interface MemoryPool<b>MBean</b> { String getName(); MemoryUsage getUsage(); // ... } </pre></td> <td><pre> public interface MemoryPool<b>MXBean</b> { String getName(); MemoryUsage getUsage(); // ... } </pre></td> </tr> </table> <p>As you can see, the definitions are very similar. The only difference is that the convention for naming the interface is to use <code><em>Something</em>MXBean</code> for MXBeans, rather than <code><em>Something</em>MBean</code> for Standard MBeans.</p> <p>In this managed object, there is an attribute called <code>Usage</code> of type {@link MemoryUsage}. The point of an attribute like this is that it gives a coherent snapshot of a set of data items. For example, it might include the current amount of used memory in the memory pool, and the current maximum of the memory pool. If these were separate items, obtained with separate {@link MBeanServer#getAttribute getAttribute} calls, then we could get values seen at different times that were not consistent. We might get a <code>used</code> value that was greater than the <code>max</code> value.</p> <p>So, we might define <code>MemoryUsage</code> like this:</p> <table border="1" cellpadding="5"> <tr> <th>Standard MBean</th><th>MXBean</th> </tr> <tr> <td><pre> public class MemoryUsage <b>implements Serializable</b> { // standard JavaBean conventions with getters public MemoryUsage(long init, long used, long committed, long max) {...} long getInit() {...} long getUsed() {...} long getCommitted() {...} long getMax() {...} } </pre></td> <td><pre> public class MemoryUsage { // standard JavaBean conventions with getters <b>&#64;ConstructorProperties({"init", "used", "committed", "max"})</b> public MemoryUsage(long init, long used, long committed, long max) {...} long getInit() {...} long getUsed() {...} long getCommitted() {...} long getMax() {...} } </pre></td> </tr> </table> <p>The definitions are the same in the two cases, except that with the MXBean, <code>MemoryUsage</code> no longer needs to be marked <code>Serializable</code> (though it can be). On the other hand, we have added a {@code @ConstructorProperties} annotation to link the constructor parameters to the corresponding getters. We will see more about this below.</p> <p><code>MemoryUsage</code> is a <em>model-specific class</em>. With Standard MBeans, a client of the MBean Server cannot access the <code>Usage</code> attribute if it does not know the class <code>MemoryUsage</code>. Suppose the client is a generic console based on JMX technology. Then the console would have to be configured with the model-specific classes of every application it might connect to. The problem is even worse for clients that are not written in the Java language. Then there may not be any way to tell the client what a <code>MemoryUsage</code> looks like.</p> <p>This is where MXBeans differ from Standard MBeans. Although we define the management interface in almost exactly the same way, the MXBean framework <em>converts</em> model-specific classes into standard classes from the Java platform. Using arrays and the {@link javax.management.openmbean.CompositeData CompositeData} and {@link javax.management.openmbean.TabularData TabularData} classes from the standard {@link javax.management.openmbean} package, it is possible to build data structures of arbitrary complexity using only standard classes.</p> <p>This becomes clearer if we compare what the clients of the two models might look like:</p> <table border="1" cellpadding="5"> <tr> <th>Standard MBean</th><th>MXBean</th> </tr> <tr> <td><pre> String name = (String) mbeanServer.{@link MBeanServer#getAttribute getAttribute}(objectName, "Name"); <b>MemoryUsage</b> usage = (<b>MemoryUsage</b>) mbeanServer.getAttribute(objectName, "Usage"); <b>long used = usage.getUsed();</b> </pre></td> <td><pre> String name = (String) mbeanServer.{@link MBeanServer#getAttribute getAttribute}(objectName, "Name"); <b>{@link CompositeData}</b> usage = (<b>CompositeData</b>) mbeanServer.getAttribute(objectName, "Usage"); <b>long used = (Long) usage.{@link CompositeData#get get}("used");</b> </pre></td> </table> <p>For attributes with simple types like <code>String</code>, the code is the same. But for attributes with complex types, the Standard MBean code requires the client to know the model-specific class <code>MemoryUsage</code>, while the MXBean code requires no non-standard classes.</p> <p>The client code shown here is slightly more complicated for the MXBean client. But, if the client does in fact know the model, here the interface <code>MemoryPoolMXBean</code> and the class <code>MemoryUsage</code>, then it can construct a <em>proxy</em>. This is the recommended way to interact with managed objects when you know the model beforehand, regardless of whether you are using Standard MBeans or MXBeans:</p> <table border="1" cellpadding="5"> <tr> <th>Standard MBean</th><th>MXBean</th> </tr> <tr> <td><pre> MemoryPool<b>MBean</b> proxy = JMX.<b>{@link JMX#newMBeanProxy(MBeanServerConnection, ObjectName, Class) newMBeanProxy}</b>( mbeanServer, objectName, MemoryPool<b>MBean</b>.class); String name = proxy.getName(); MemoryUsage usage = proxy.getUsage(); long used = usage.getUsed(); </pre></td> <td><pre> MemoryPool<b>MXBean</b> proxy = JMX.<b>{@link JMX#newMXBeanProxy(MBeanServerConnection, ObjectName, Class) newMXBeanProxy}</b>( mbeanServer, objectName, MemoryPool<b>MXBean</b>.class); String name = proxy.getName(); MemoryUsage usage = proxy.getUsage(); long used = usage.getUsed(); </pre></td> </tr> </table> <p>Implementing the MemoryPool object works similarly for both Standard MBeans and MXBeans.</p> <table border="1" cellpadding="5"> <tr> <th>Standard MBean</th><th>MXBean</th> </tr> <tr> <td><pre> public class MemoryPool implements MemoryPool<b>MBean</b> { public String getName() {...} public MemoryUsage getUsage() {...} // ... } </pre></td> <td><pre> public class MemoryPool implements MemoryPool<b>MXBean</b> { public String getName() {...} public MemoryUsage getUsage() {...} // ... } </pre></td> </tr> </table> <p>Registering the MBean in the MBean Server works in the same way in both cases:</p> <table border="1" cellpadding="5"> <tr> <th>Standard MBean</th><th>MXBean</th> </tr> <tr> <td><pre> { MemoryPool<b>MBean</b> pool = new MemoryPool(); mbeanServer.{@link MBeanServer#registerMBean registerMBean}(pool, objectName); } </pre></td> <td><pre> { MemoryPool<b>MXBean</b> pool = new MemoryPool(); mbeanServer.{@link MBeanServer#registerMBean registerMBean}(pool, objectName); } </pre></td> </tr> </table> <h2><a name="mxbean-def">Definition of an MXBean</a></h2> <p>An MXBean is a kind of MBean. An MXBean object can be registered directly in the MBean Server, or it can be used as an argument to {@link StandardMBean} and the resultant MBean registered in the MBean Server.</p> <p>When an object is registered in the MBean Server using the {@code registerMBean} or {@code createMBean} methods of the {@link MBeanServer} interface, the object's class is examined to determine what type of MBean it is:</p> <ul> <li>If the class implements the interface {@link DynamicMBean} then the MBean is a Dynamic MBean. Note that the class {@code StandardMBean} implements this interface, so this case applies to a Standard MBean or MXBean created using the class {@code StandardMBean}.</li> <li>Otherwise, if the class matches the Standard MBean naming conventions, then the MBean is a Standard MBean.</li> <li>Otherwise, it may be an MXBean. The set of interfaces implemented by the object is examined for interfaces that: <ul> <li>have a class name <code><em>S</em>MXBean</code> where <code><em>S</em></code> is any non-empty string, and do not have an annotation {@code @MXBean(false)}; and/or</li> <li>have an annotation {@code @MXBean(true)} or just {@code @MXBean}.</li> </ul> If there is exactly one such interface, or if there is one such interface that is a subinterface of all the others, then the object is an MXBean. The interface in question is the <em>MXBean interface</em>. In the example above, the MXBean interface is {@code MemoryPoolMXBean}. <li>If none of these conditions is met, the MBean is invalid and the attempt to register it will generate {@link NotCompliantMBeanException}. </ul> <p>Every Java type that appears as the parameter or return type of a method in an MXBean interface must be <em>convertible</em> using the rules below. Additionally, parameters must be <em>reconstructible</em> as defined below.</p> <p>An attempt to construct an MXBean that does not conform to the above rules will produce an exception.</p> <h2><a name="naming-conv">Naming conventions</a></h2> <p>The same naming conventions are applied to the methods in an MXBean as in a Standard MBean:</p> <ol> <li>A method <code><em>T</em> get<em>N</em>()</code>, where <code><em>T</em></code> is a Java type (not <code>void</code>) and <code><em>N</em></code> is a non-empty string, specifies that there is a readable attribute called <code><em>N</em></code>. The Java type and Open type of the attribute are determined by the mapping rules below. The method {@code final Class getClass()} inherited from {@code Object} is ignored when looking for getters.</li> <li>A method <code>boolean is<em>N</em>()</code> specifies that there is a readable attribute called <code><em>N</em></code> with Java type <code>boolean</code> and Open type <code>SimpleType.Boolean</code>.</li> <li>A method <code>void set<em>N</em>(<em>T</em> x)</code> specifies that there is a writeable attribute called <code><em>N</em></code>. The Java type and Open type of the attribute are determined by the mapping rules below. (Of course, the name <code>x</code> of the parameter is irrelevant.)</li> <li>Every other method specifies that there is an operation with the same name as the method. The Java type and Open type of the return value and of each parameter are determined by the mapping rules below.</li> </ol> <p>The rules for <code>get<em>N</em></code> and <code>is<em>N</em></code> collectively define the notion of a <em>getter</em>. The rule for <code>set<em>N</em></code> defines the notion of a <em>setter</em>.</p> <p>It is an error for there to be two getters with the same name, or two setters with the same name. If there is a getter and a setter for the same name, then the type <code><em>T</em></code> in both must be the same. In this case the attribute is read/write. If there is only a getter or only a setter, the attribute is read-only or write-only respectively.</p> <h2><a name="mapping-rules">Type mapping rules</a></h2> <p>An MXBean is a kind of Open MBean, as defined by the {@link javax.management.openmbean} package. This means that the types of attributes, operation parameters, and operation return values must all be describable using <em>Open Types</em>, that is the four standard subclasses of {@link javax.management.openmbean.OpenType}. MXBeans achieve this by mapping Java types into Open Types.</p> <p>For every Java type <em>J</em>, the MXBean mapping is described by the following information:</p> <ul> <li>The corresponding Open Type, <em>opentype(J)</em>. This is an instance of a subclass of {@link javax.management.openmbean.OpenType}.</li> <li>The <em>mapped</em> Java type, <em>opendata(J)</em>, which is always the same for any given <em>opentype(J)</em>. This is a Java class.</li> <li>How a value is converted from type <em>J</em> to type <em>opendata(J)</em>.</li> <li>How a value is converted from type <em>opendata(J)</em> to type <em>J</em>, if it can be.</li> </ul> <p>For example, for the Java type {@code List<String>}:</p> <ul> <li>The Open Type, <em>opentype(</em>{@code List<String>}<em>)</em>, is {@link ArrayType}<code>(1, </code>{@link SimpleType#STRING}<code>)</code>, representing a 1-dimensional array of <code>String</code>s.</li> <li>The mapped Java type, <em>opendata(</em>{@code List<String>}<em>)</em>, is {@code String[]}.</li> <li>A {@code List<String>} can be converted to a {@code String[]} using {@link List#toArray(Object[]) List.toArray(new String[0])}.</li> <li>A {@code String[]} can be converted to a {@code List<String>} using {@link Arrays#asList Arrays.asList}.</li> </ul> <p>If no mapping rules exist to derive <em>opentype(J)</em> from <em>J</em>, then <em>J</em> cannot be the type of a method parameter or return value in an MXBean interface.</p> <p>If there is a way to convert <em>opendata(J)</em> back to <em>J</em> then we say that <em>J</em> is <em>reconstructible</em>. All method parameters in an MXBean interface must be reconstructible, because when the MXBean framework is invoking a method it will need to convert those parameters from <em>opendata(J)</em> to <em>J</em>. In a proxy generated by {@link JMX#newMXBeanProxy(MBeanServerConnection, ObjectName, Class) JMX.newMXBeanProxy}, it is the return values of the methods in the MXBean interface that must be reconstructible.</p> <p>Null values are allowed for all Java types and Open Types, except primitive Java types where they are not possible. When converting from type <em>J</em> to type <em>opendata(J)</em> or from type <em>opendata(J)</em> to type <em>J</em>, a null value is mapped to a null value.</p> <p>The following table summarizes the type mapping rules.</p> <table border="1" cellpadding="5"> <tr> <th>Java type <em>J</em></th> <th><em>opentype(J)</em></th> <th><em>opendata(J)</em></th> </tr> <tbody cellvalign="top"> <tr> <td>{@code int}, {@code boolean}, etc<br> (the 8 primitive Java types)</td> <td>{@code SimpleType.INTEGER},<br> {@code SimpleType.BOOLEAN}, etc</td> <td>{@code Integer}, {@code Boolean}, etc<br> (the corresponding boxed types)</td> </tr> <tr> <td>{@code Integer}, {@code ObjectName}, etc<br> (the types covered by {@link SimpleType})</td> <td>the corresponding {@code SimpleType}</td> <td><em>J</em>, the same type</td> </tr> <tr> <td>{@code int[]} etc<br> (a one-dimensional array with<br> primitive element type)</td> <td>{@code ArrayType.getPrimitiveArrayType(int[].class)} etc</td> <td><em>J</em>, the same type</td> <tr> <td><em>E</em>{@code []}<br> (an array with non-primitive element type <em>E</em>; this includes {@code int[][]}, where <em>E</em> is {@code int[]})</td> <td>{@code ArrayType.getArrayType(}<em>opentype(E)</em>{@code )}</td> <td><em>opendata(E)</em>{@code []}</td> </tr> <tr> <td>{@code List<}<em>E</em>{@code >}<br> {@code Set<}<em>E</em>{@code >}<br> {@code SortedSet<}<em>E</em>{@code >} (see below)</td> <td>same as for <em>E</em>{@code []}</td> <td>same as for <em>E</em>{@code []}</td> </tr> <tr> <td>An enumeration <em>E</em><br> (declared in Java as {@code enum }<em>E</em> {@code {...}})</td> <td>{@code SimpleType.STRING}</td> <td>{@code String}</td> </tr> <tr> <td>{@code Map<}<em>K</em>,<em>V</em>{@code >}<br> {@code SortedMap<}<em>K</em>,<em>V</em>{@code >}</td> <td>{@link TabularType}<br> (see below)</td> <td>{@link TabularData}<br> (see below)</td> </tr> <tr> <td>An MXBean interface</td> <td>{@code SimpleType.OBJECTNAME}<br> (see below)</td> <td>{@link ObjectName}<br> (see below)</td> </tr> <tr> <td>Any other type</td> <td>{@link CompositeType}, if possible<br> (see below)</td> <td>{@link CompositeData}</td> </tbody> </table> <p>The following sections give further details of these rules.</p> <h3>Mappings for primitive types</h3> <p>The 8 primitive Java types ({@code boolean}, {@code byte}, {@code short}, {@code int}, {@code long}, {@code float}, {@code double}, {@code char}) are mapped to the corresponding boxed types from {@code java.lang}, namely {@code Boolean}, {@code Byte}, etc. The Open Type is the corresponding {@code SimpleType}. Thus, <em>opentype(</em>{@code long}<em>)</em> is {@code SimpleType.LONG}, and <em>opendata(</em>{@code long}<em>)</em> is {@code java.lang.Long}.</p> <p>An array of primitive type such as {@code long[]} can be represented directly as an Open Type. Thus, <em>openType(</em>{@code long[]}<em>)</em> is {@code ArrayType.getPrimitiveArrayType(long[].class)}, and <em>opendata(</em>{@code long[]}<em>)</em> is {@code long[]}.</p> <p>In practice, the difference between a plain {@code int} and {@code Integer}, etc, does not show up because operations in the JMX API are always on Java objects, not primitives. However, the difference <em>does</em> show up with arrays.</p> <h3>Mappings for collections ({@code List<}<em>E</em>{@code >} etc)</h3> <p>A {@code List<}<em>E</em>{@code >} or {@code Set<}<em>E</em>{@code >}, such as {@code List<String>} or {@code Set<ObjectName>}, is mapped in the same way as an array of the same element type, such as {@code String[]} or {@code ObjectName[]}.</p> <p>A {@code SortedSet<}<em>E</em>{@code >} is also mapped in the same way as an <em>E</em>{@code []}, but it is only convertible if <em>E</em> is a class or interface that implements {@link java.lang.Comparable}. Thus, a {@code SortedSet<String>} or {@code SortedSet<Integer>} is convertible, but a {@code SortedSet<int[]>} or {@code SortedSet<List<String>>} is not. The conversion of a {@code SortedSet} instance will fail with an {@code IllegalArgumentException} if it has a non-null {@link java.util.SortedSet#comparator() comparator()}.</p> <p>A {@code List<}<em>E</em>{@code >} is reconstructed as a {@code java.util.ArrayList<}<em>E</em>{@code >}; a {@code Set<}<em>E</em>{@code >} as a {@code java.util.HashSet<}<em>E</em>{@code >}; a {@code SortedSet<}<em>E</em>{@code >} as a {@code java.util.TreeSet<}<em>E</em>{@code >}.</p> <h3>Mappings for maps ({@code Map<}<em>K</em>,<em>V</em>{@code >} etc)</h3> <p>A {@code Map<}<em>K</em>,<em>V</em>{@code >} or {@code SortedMap<}<em>K</em>,<em>V</em>{@code >}, for example {@code Map<String,ObjectName>}, has Open Type {@link TabularType} and is mapped to a {@link TabularData}. The {@code TabularType} has two items called {@code key} and {@code value}. The Open Type of {@code key} is <em>opentype(K)</em>, and the Open Type of {@code value} is <em>opentype(V)</em>. The index of the {@code TabularType} is the single item {@code key}.</p> <p>For example, the {@code TabularType} for a {@code Map<String,ObjectName>} might be constructed with code like this:</p> <pre> String typeName = "java.util.Map&lt;java.lang.String, javax.management.ObjectName&gt;"; String[] keyValue = new String[] {"key", "value"}; OpenType[] openTypes = new OpenType[] {SimpleType.STRING, SimpleType.OBJECTNAME}; CompositeType rowType = new CompositeType(typeName, typeName, keyValue, keyValue, openTypes); TabularType tabularType = new TabularType(typeName, typeName, rowType, new String[] {"key"}); </pre> <p>The {@code typeName} here is determined by the <a href="#type-names"> type name rules</a> detailed below. <p>A {@code SortedMap<}<em>K</em>,<em>V</em>{@code >} is mapped in the same way, but it is only convertible if <em>K</em> is a class or interface that implements {@link java.lang.Comparable}. Thus, a {@code SortedMap<String,int[]>} is convertible, but a {@code SortedMap<int[],String>} is not. The conversion of a {@code SortedMap} instance will fail with an {@code IllegalArgumentException} if it has a non-null {@link java.util.SortedMap#comparator() comparator()}.</p> <p>A {@code Map<}<em>K</em>,<em>V</em>{@code >} is reconstructed as a {@code java.util.HashMap<}<em>K</em>,<em>V</em>{@code >}; a {@code SortedMap<}<em>K</em>,<em>V</em>{@code >} as a {@code java.util.TreeMap<}<em>K</em>,<em>V</em>{@code >}.</p> <p>{@code TabularData} is an interface. The concrete class that is used to represent a {@code Map<}<em>K</em>,<em>V</em>{@code >} as Open Data is {@link TabularDataSupport}, or another class implementing {@code TabularData} that serializes as {@code TabularDataSupport}.</p> <h3><a name="mxbean-map">Mappings for MXBean interfaces</a></h3> <p>An MXBean interface, or a type referenced within an MXBean interface, can reference another MXBean interface, <em>J</em>. Then <em>opentype(J)</em> is {@code SimpleType.OBJECTNAME} and <em>opendata(J)</em> is {@code ObjectName}.</p> <p>For example, suppose you have two MXBean interfaces like this:</p> <pre> public interface ProductMXBean { public ModuleMXBean[] getModules(); } public interface ModuleMXBean { public ProductMXBean getProduct(); } </pre> <p>The object implementing the {@code ModuleMXBean} interface returns from its {@code getProduct} method an object implementing the {@code ProductMXBean} interface. The {@code ModuleMXBean} object and the returned {@code ProductMXBean} objects must both be registered as MXBeans in the same MBean Server.</p> <p>The method {@code ModuleMXBean.getProduct()} defines an attribute called {@code Product}. The Open Type for this attribute is {@code SimpleType.OBJECTNAME}, and the corresponding {@code ObjectName} value will be the name under which the referenced {@code ProductMXBean} is registered in the MBean Server.</p> <p>If you make an MXBean proxy for a {@code ModuleMXBean} and call its {@code getProduct()} method, the proxy will map the {@code ObjectName} back into a {@code ProductMXBean} by making another MXBean proxy. More formally, when a proxy made with {@link JMX#newMXBeanProxy(MBeanServerConnection, ObjectName, Class) JMX.newMXBeanProxy(mbeanServerConnection, objectNameX, interfaceX)} needs to map {@code objectNameY} back into {@code interfaceY}, another MXBean interface, it does so with {@code JMX.newMXBeanProxy(mbeanServerConnection, objectNameY, interfaceY)}. The implementation may return a proxy that was previously created by a call to {@code JMX.newMXBeanProxy} with the same parameters, or it may create a new proxy.</p> <p>The reverse mapping is illustrated by the following change to the {@code ModuleMXBean} interface:</p> <pre> public interface ModuleMXBean { public ProductMXBean getProduct(); public void setProduct(ProductMXBean c); } </pre> <p>The presence of the {@code setProduct} method now means that the {@code Product} attribute is read/write. As before, the value of this attribute is an {@code ObjectName}. When the attribute is set, the {@code ObjectName} must be converted into the {@code ProductMXBean} object that the {@code setProduct} method expects. This object will be an MXBean proxy for the given {@code ObjectName} in the same MBean Server.</p> <p>If you make an MXBean proxy for a {@code ModuleMXBean} and call its {@code setProduct} method, the proxy will map its {@code ProductMXBean} argument back into an {@code ObjectName}. This will only work if the argument is in fact another proxy, for a {@code ProductMXBean} in the same {@code MBeanServerConnection}. The proxy can have been returned from another proxy (like {@code ModuleMXBean.getProduct()} which returns a proxy for a {@code ProductMXBean}); or it can have been created by {@link JMX#newMXBeanProxy(MBeanServerConnection, ObjectName, Class) JMX.newMXBeanProxy}; or it can have been created using {@link java.lang.reflect.Proxy Proxy} with an invocation handler that is {@link MBeanServerInvocationHandler} or a subclass.</p> <p>If the same MXBean were registered under two different {@code ObjectName}s, a reference to that MXBean from another MXBean would be ambiguous. Therefore, if an MXBean object is already registered in an MBean Server and an attempt is made to register it in the same MBean Server under another name, the result is an {@link InstanceAlreadyExistsException}. Registering the same MBean object under more than one name is discouraged in general, notably because it does not work well for MBeans that are {@link NotificationBroadcaster}s.</p> <h3><a name="composite-map">Mappings for other types</a></h3> <p>Given a Java class or interface <em>J</em> that does not match the other rules in the table above, the MXBean framework will attempt to map it to a {@link CompositeType} as follows. The type name of this {@code CompositeType} is determined by the <a href="#type-names"> type name rules</a> below.</p> <p>The class is examined for getters using the conventions <a href="#naming-conv">above</a>. (Getters must be public instance methods.) If there are no getters, or if any getter has a type that is not convertible, then <em>J</em> is not convertible.</p> <p>If there is at least one getter and every getter has a convertible type, then <em>opentype(J)</em> is a {@code CompositeType} with one item for every getter. If the getter is <blockquote> <code><em>T</em> get<em>Name</em>()</code> </blockquote> then the item in the {@code CompositeType} is called {@code name} and has type <em>opentype(T)</em>. For example, if the item is <blockquote> <code>String getOwner()</code> </blockquote> then the item is called {@code owner} and has Open Type {@code SimpleType.STRING}. If the getter is <blockquote> <code>boolean is<em>Name</em>()</code> </blockquote> then the item in the {@code CompositeType} is called {@code name} and has type {@code SimpleType.BOOLEAN}.</p> <p>Notice that the first character (or code point) is converted to lower case. This follows the Java Beans convention, which for historical reasons is different from the Standard MBean convention. In a Standard MBean or MXBean interface, a method {@code getOwner} defines an attribute called {@code Owner}, while in a Java Bean or mapped {@code CompositeType}, a method {@code getOwner} defines a property or item called {@code owner}.</p> <p>If two methods produce the same item name (for example, {@code getOwner} and {@code isOwner}, or {@code getOwner} and {@code getowner}) then the type is not convertible.</p> <p>When the Open Type is {@code CompositeType}, the corresponding mapped Java type (<em>opendata(J)</em>) is {@link CompositeData}. The mapping from an instance of <em>J</em> to a {@code CompositeData} corresponding to the {@code CompositeType} just described is done as follows. First, if <em>J</em> implements the interface {@link CompositeDataView}, then that interface's {@link CompositeDataView#toCompositeData toCompositeData} method is called to do the conversion. Otherwise, the {@code CompositeData} is constructed by calling the getter for each item and converting it to the corresponding Open Data type. Thus, a getter such as</p> <blockquote> {@code List<String> getNames()} </blockquote> <p>will have been mapped to an item with name "{@code names}" and Open Type {@code ArrayType(1, SimpleType.STRING)}. The conversion to {@code CompositeData} will call {@code getNames()} and convert the resultant {@code List<String>} into a {@code String[]} for the item "{@code names}".</p> <p>{@code CompositeData} is an interface. The concrete class that is used to represent a type as Open Data is {@link CompositeDataSupport}, or another class implementing {@code CompositeData} that serializes as {@code CompositeDataSupport}.</p> <h4>Reconstructing an instance of Java type <em>J</em> from a {@code CompositeData}</h4> <p>If <em>opendata(J)</em> is {@code CompositeData} for a Java type <em>J</em>, then either an instance of <em>J</em> can be reconstructed from a {@code CompositeData}, or <em>J</em> is not reconstructible. If any item in the {@code CompositeData} is not reconstructible, then <em>J</em> is not reconstructible either.</p> <p>For any given <em>J</em>, the following rules are consulted to determine how to reconstruct instances of <em>J</em> from {@code CompositeData}. The first applicable rule in the list is the one that will be used.</p> <ol> <li><p>If <em>J</em> has a method<br> {@code public static }<em>J </em>{@code from(CompositeData cd)}<br> then that method is called to reconstruct an instance of <em>J</em>.</p></li> <li><p>Otherwise, if <em>J</em> has at least one public constructor with a {@link ConstructorProperties} annotation, then one of those constructors (not necessarily always the same one) will be called to reconstruct an instance of <em>J</em>. Every such annotation must list as many strings as the constructor has parameters; each string must name a property corresponding to a getter of <em>J</em>; and the type of this getter must be the same as the corresponding constructor parameter. It is not an error for there to be getters that are not mentioned in the {@code ConstructorProperties} annotation (these may correspond to information that is not needed to reconstruct the object).</p> <p>An instance of <em>J</em> is reconstructed by calling a constructor with the appropriate reconstructed items from the {@code CompositeData}. The constructor to be called will be determined at runtime based on the items actually present in the {@code CompositeData}, given that this {@code CompositeData} might come from an earlier version of <em>J</em> where not all the items were present. A constructor is <em>applicable</em> if all the properties named in its {@code ConstructorProperties} annotation are present as items in the {@code CompositeData}. If no constructor is applicable, then the attempt to reconstruct <em>J</em> fails.</p> <p>For any possible combination of properties, it must be the case that either (a) there are no applicable constructors, or (b) there is exactly one applicable constructor, or (c) one of the applicable constructors names a proper superset of the properties named by each other applicable constructor. (In other words, there should never be ambiguity over which constructor to choose.) If this condition is not true, then <em>J</em> is not reconstructible.</p></li> <li><p>Otherwise, if <em>J</em> has a public no-arg constructor, and for every getter in <em>J</em> with type <em>T</em> and name <em>N</em> there is a corresponding setter with the same name and type, then an instance of <em>J</em> is constructed with the no-arg constructor and the setters are called with the reconstructed items from the {@code CompositeData} to restore the values. For example, if there is a method<br> {@code public List<String> getNames()}<br> then there must also be a method<br> {@code public void setNames(List<String> names)}<br> for this rule to apply.</p> <p>If the {@code CompositeData} came from an earlier version of <em>J</em>, some items might not be present. In this case, the corresponding setters will not be called.</p></li> <li><p>Otherwise, if <em>J</em> is an interface that has no methods other than getters, an instance of <em>J</em> is constructed using a {@link java.lang.reflect.Proxy} with a {@link CompositeDataInvocationHandler} backed by the {@code CompositeData} being converted.</p></li> <li><p>Otherwise, <em>J</em> is not reconstructible.</p></li> </ol> <p>Here are examples showing different ways to code a type {@code NamedNumber} that consists of an {@code int} and a {@code String}. In each case, the {@code CompositeType} looks like this:</p> <blockquote> <pre> {@link CompositeType}( "NamedNumber", // typeName "NamedNumber", // description new String[] {"number", "name"}, // itemNames new String[] {"number", "name"}, // itemDescriptions new OpenType[] {SimpleType.INTEGER, SimpleType.STRING} // itemTypes ); </pre> </blockquote> <ol> <li>Static {@code from} method: <blockquote> <pre> public class NamedNumber { public int getNumber() {return number;} public String getName() {return name;} private NamedNumber(int number, String name) { this.number = number; this.name = name; } <b>public static NamedNumber from(CompositeData cd)</b> { return new NamedNumber((Integer) cd.get("number"), (String) cd.get("name")); } private final int number; private final String name; } </pre> </blockquote> </li> <li>Public constructor with <code>&#64;ConstructorProperties</code> annotation: <blockquote> <pre> public class NamedNumber { public int getNumber() {return number;} public String getName() {return name;} <b>&#64;ConstructorProperties({"number", "name"}) public NamedNumber(int number, String name)</b> { this.number = number; this.name = name; } private final int number; private final String name; } </pre> </blockquote> </li> <li>Setter for every getter: <blockquote> <pre> public class NamedNumber { public int getNumber() {return number;} public void <b>setNumber</b>(int number) {this.number = number;} public String getName() {return name;} public void <b>setName</b>(String name) {this.name = name;} <b>public NamedNumber()</b> {} private int number; private String name; } </pre> </blockquote> </li> <li>Interface with only getters: <blockquote> <pre> public interface NamedNumber { public int getNumber(); public String getName(); } </pre> </blockquote> </li> </ol> <p>It is usually better for classes that simply represent a collection of data to be <em>immutable</em>. An instance of an immutable class cannot be changed after it has been constructed. Notice that {@code CompositeData} itself is immutable. Immutability has many advantages, notably with regard to thread-safety and security. So the approach using setters should generally be avoided if possible.</p> <h3>Recursive types</h3> <p>Recursive (self-referential) types cannot be used in MXBean interfaces. This is a consequence of the immutability of {@link CompositeType}. For example, the following type could not be the type of an attribute, because it refers to itself:</p> <pre> public interface <b>Node</b> { public String getName(); public int getPriority(); public <b>Node</b> getNext(); } </pre> <p>It is always possible to rewrite recursive types like this so they are no longer recursive. Doing so may require introducing new types. For example:</p> <pre> public interface <b>NodeList</b> { public List&lt;Node&gt; getNodes(); } public interface Node { public String getName(); public int getPriority(); } </pre> <h3>MBeanInfo contents for an MXBean</h3> <p>An MXBean is a type of Open MBean. However, for compatibility reasons, its {@link MBeanInfo} is not an {@link OpenMBeanInfo}. In particular, when the type of an attribute, parameter, or operation return value is a primitive type such as {@code int}, or is {@code void} (for a return type), then the attribute, parameter, or operation will be represented respectively by an {@link MBeanAttributeInfo}, {@link MBeanParameterInfo}, or {@link MBeanOperationInfo} whose {@code getType()} or {@code getReturnType()} returns the primitive name ("{@code int}" etc). This is so even though the mapping rules above specify that the <em>opendata</em> mapping is the wrapped type ({@code Integer} etc).</p> <p>The array of public constructors returned by {@link MBeanInfo#getConstructors()} for an MXBean that is directly registered in the MBean Server will contain all of the public constructors of that MXBean. If the class of the MXBean is not public then its constructors are not considered public either. The list returned for an MXBean that is constructed using the {@link StandardMBean} class is derived in the same way as for Standard MBeans. Regardless of how the MXBean was constructed, its constructor parameters are not subject to MXBean mapping rules and do not have a corresponding {@code OpenType}.</p> <p>The array of notification types returned by {@link MBeanInfo#getNotifications()} for an MXBean that is directly registered in the MBean Server will be empty if the MXBean does not implement the {@link NotificationBroadcaster} interface. Otherwise, it will be the result of calling {@link NotificationBroadcaster#getNotificationInfo()} at the time the MXBean was registered. Even if the result of this method changes subsequently, the result of {@code MBeanInfo.getNotifications()} will not. The list returned for an MXBean that is constructed using the {@link StandardMBean} or {@link StandardEmitterMBean} class is derived in the same way as for Standard MBeans.</p> <p>The {@link Descriptor} for all of the {@code MBeanAttributeInfo}, {@code MBeanParameterInfo}, and {@code MBeanOperationInfo} objects contained in the {@code MBeanInfo} will have a field {@code openType} whose value is the {@link OpenType} specified by the mapping rules above. So even when {@code getType()} is "{@code int}", {@code getDescriptor().getField("openType")} will be {@link SimpleType#INTEGER}.</p> <p>The {@code Descriptor} for each of these objects will also have a field {@code originalType} that is a string representing the Java type that appeared in the MXBean interface. The format of this string is described in the section <a href="#type-names">Type Names</a> below.</p> <p>The {@code Descriptor} for the {@code MBeanInfo} will have a field {@code mxbean} whose value is the string "{@code true}".</p> <h3><a name="type-names">Type Names</a></h3> <p>Sometimes the unmapped type <em>T</em> of a method parameter or return value in an MXBean must be represented as a string. If <em>T</em> is a non-generic type, this string is the value returned by {@link Class#getName()}. Otherwise it is the value of <em>genericstring(T)</em>, defined as follows: <ul> <li>If <em>T</em> is a non-generic non-array type, <em>genericstring(T)</em> is the value returned by {@link Class#getName()}, for example {@code "int"} or {@code "java.lang.String"}. <li>If <em>T</em> is an array <em>E[]</em>, <em>genericstring(T)</em> is <em>genericstring(E)</em> followed by {@code "[]"}. For example, <em>genericstring({@code int[]})</em> is {@code "int[]"}, and <em>genericstring({@code List<String>[][]})</em> is {@code "java.util.List<java.lang.String>[][]"}. <li>Otherwise, <em>T</em> is a parameterized type such as {@code List<String>} and <em>genericstring(T)</em> consists of the following: the fully-qualified name of the parameterized type as returned by {@code Class.getName()}; a left angle bracket ({@code "<"}); <em>genericstring(A)</em> where <em>A</em> is the first type parameter; if there is a second type parameter <em>B</em> then {@code ", "} (a comma and a single space) followed by <em>genericstring(B)</em>; a right angle bracket ({@code ">"}). </ul> <p>Note that if a method returns {@code int[]}, this will be represented by the string {@code "[I"} returned by {@code Class.getName()}, but if a method returns {@code List<int[]>}, this will be represented by the string {@code "java.util.List<int[]>"}. <h3>Exceptions</h3> <p>A problem with mapping <em>from</em> Java types <em>to</em> Open types is signaled with an {@link OpenDataException}. This can happen when an MXBean interface is being analyzed, for example if it references a type like {@link java.util.Random java.util.Random} that has no getters. Or it can happen when an instance is being converted (a return value from a method in an MXBean or a parameter to a method in an MXBean proxy), for example when converting from {@code SortedSet<String>} to {@code String[]} if the {@code SortedSet} has a non-null {@code Comparator}.</p> <p>A problem with mapping <em>to</em> Java types <em>from</em> Open types is signaled with an {@link InvalidObjectException}. This can happen when an MXBean interface is being analyzed, for example if it references a type that is not <em>reconstructible</em> according to the rules above, in a context where a reconstructible type is required. Or it can happen when an instance is being converted (a parameter to a method in an MXBean or a return value from a method in an MXBean proxy), for example from a String to an Enum if there is no Enum constant with that name.</p> <p>Depending on the context, the {@code OpenDataException} or {@code InvalidObjectException} may be wrapped in another exception such as {@link RuntimeMBeanException} or {@link UndeclaredThrowableException}. For every thrown exception, the condition <em>C</em> will be true: "<em>e</em> is {@code OpenDataException} or {@code InvalidObjectException} (as appropriate), or <em>C</em> is true of <em>e</em>.{@link Throwable#getCause() getCause()}".</p> @since 1.6 */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface MXBean { /** {@collect.stats} True if the annotated interface is an MXBean interface. @return true if the annotated interface is an MXBean interface. */ boolean value() default true; }
Java
/* * Copyright (c) 1999, 2006, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management; import com.sun.jmx.defaults.ServiceName; /** {@collect.stats} * Represents the MBean server from the management point of view. * The MBeanServerDelegate MBean emits the MBeanServerNotifications when * an MBean is registered/unregistered in the MBean server. * * @since 1.5 */ public class MBeanServerDelegate implements MBeanServerDelegateMBean, NotificationEmitter { /** {@collect.stats} The MBean server agent identification.*/ private String mbeanServerId ; /** {@collect.stats} The NotificationBroadcasterSupport object that sends the notifications */ private final NotificationBroadcasterSupport broadcaster; private static long oldStamp = 0; private final long stamp; private long sequenceNumber = 1; private static final MBeanNotificationInfo[] notifsInfo; static { final String[] types = { MBeanServerNotification.UNREGISTRATION_NOTIFICATION, MBeanServerNotification.REGISTRATION_NOTIFICATION }; notifsInfo = new MBeanNotificationInfo[1]; notifsInfo[0] = new MBeanNotificationInfo(types, "javax.management.MBeanServerNotification", "Notifications sent by the MBeanServerDelegate MBean"); } /** {@collect.stats} * Create a MBeanServerDelegate object. */ public MBeanServerDelegate () { stamp = getStamp(); broadcaster = new NotificationBroadcasterSupport() ; } /** {@collect.stats} * Returns the MBean server agent identity. * * @return the identity. */ public synchronized String getMBeanServerId() { if (mbeanServerId == null) { String localHost; try { localHost = java.net.InetAddress.getLocalHost().getHostName(); } catch (java.net.UnknownHostException e) { localHost = "localhost"; } mbeanServerId = localHost + "_" + stamp; } return mbeanServerId; } /** {@collect.stats} * Returns the full name of the JMX specification implemented * by this product. * * @return the specification name. */ public String getSpecificationName() { return ServiceName.JMX_SPEC_NAME; } /** {@collect.stats} * Returns the version of the JMX specification implemented * by this product. * * @return the specification version. */ public String getSpecificationVersion() { return ServiceName.JMX_SPEC_VERSION; } /** {@collect.stats} * Returns the vendor of the JMX specification implemented * by this product. * * @return the specification vendor. */ public String getSpecificationVendor() { return ServiceName.JMX_SPEC_VENDOR; } /** {@collect.stats} * Returns the JMX implementation name (the name of this product). * * @return the implementation name. */ public String getImplementationName() { return ServiceName.JMX_IMPL_NAME; } /** {@collect.stats} * Returns the JMX implementation version (the version of this product). * * @return the implementation version. */ public String getImplementationVersion() { try { return System.getProperty("java.runtime.version"); } catch (SecurityException e) { return ""; } } /** {@collect.stats} * Returns the JMX implementation vendor (the vendor of this product). * * @return the implementation vendor. */ public String getImplementationVendor() { return ServiceName.JMX_IMPL_VENDOR; } // From NotificationEmitter extends NotificationBroacaster // public MBeanNotificationInfo[] getNotificationInfo() { final int len = MBeanServerDelegate.notifsInfo.length; final MBeanNotificationInfo[] infos = new MBeanNotificationInfo[len]; System.arraycopy(MBeanServerDelegate.notifsInfo,0,infos,0,len); return infos; } // From NotificationEmitter extends NotificationBroacaster // public synchronized void addNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback) throws IllegalArgumentException { broadcaster.addNotificationListener(listener,filter,handback) ; } // From NotificationEmitter extends NotificationBroacaster // public synchronized void removeNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback) throws ListenerNotFoundException { broadcaster.removeNotificationListener(listener,filter,handback) ; } // From NotificationEmitter extends NotificationBroacaster // public synchronized void removeNotificationListener(NotificationListener listener) throws ListenerNotFoundException { broadcaster.removeNotificationListener(listener) ; } /** {@collect.stats} * Enables the MBean server to send a notification. * If the passed <var>notification</var> has a sequence number lesser * or equal to 0, then replace it with the delegate's own sequence * number. * @param notification The notification to send. * */ public void sendNotification(Notification notification) { if (notification.getSequenceNumber() < 1) { synchronized (this) { notification.setSequenceNumber(this.sequenceNumber++); } } broadcaster.sendNotification(notification); } /** {@collect.stats} * Defines the default ObjectName of the MBeanServerDelegate. * * @since 1.6 */ public static final ObjectName DELEGATE_NAME; static { try { DELEGATE_NAME = new ObjectName("JMImplementation:type=MBeanServerDelegate"); } catch (MalformedObjectNameException e) { throw new Error("Can't initialize delegate name", e); } } /* Return a timestamp that is monotonically increasing even if System.currentTimeMillis() isn't (for example, if you call this constructor more than once in the same millisecond, or if the clock always returns the same value). This means that the ids for a given JVM will always be distinact, though there is no such guarantee for two different JVMs. */ private static synchronized long getStamp() { long s = System.currentTimeMillis(); if (oldStamp >= s) { s = oldStamp + 1; } oldStamp = s; return s; } }
Java
/* * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management; // java import import java.util.Set; import java.io.ObjectInputStream; // RI import import javax.management.loading.ClassLoaderRepository; /** {@collect.stats} * <p>This is the interface for MBean manipulation on the agent * side. It contains the methods necessary for the creation, * registration, and deletion of MBeans as well as the access methods * for registered MBeans. This is the core component of the JMX * infrastructure.</p> * * <p>User code does not usually implement this interface. Instead, * an object that implements this interface is obtained with one of * the methods in the {@link MBeanServerFactory} class.</p> * * <p>Every MBean which is added to the MBean server becomes * manageable: its attributes and operations become remotely * accessible through the connectors/adaptors connected to that MBean * server. A Java object cannot be registered in the MBean server * unless it is a JMX compliant MBean.</p> * * <p>When an MBean is registered or unregistered in the MBean server * a {@link javax.management.MBeanServerNotification * MBeanServerNotification} Notification is emitted. To register an * object as listener to MBeanServerNotifications you should call the * MBean server method {@link #addNotificationListener * addNotificationListener} with <CODE>ObjectName</CODE> the * <CODE>ObjectName</CODE> of the {@link * javax.management.MBeanServerDelegate MBeanServerDelegate}. This * <CODE>ObjectName</CODE> is: <BR> * <CODE>JMImplementation:type=MBeanServerDelegate</CODE>.</p> * * <p>An object obtained from the {@link * MBeanServerFactory#createMBeanServer(String) createMBeanServer} or * {@link MBeanServerFactory#newMBeanServer(String) newMBeanServer} * methods of the {@link MBeanServerFactory} class applies security * checks to its methods, as follows.</p> * * <p>First, if there is no security manager ({@link * System#getSecurityManager()} is null), then an implementation of * this interface is free not to make any checks.</p> * * <p>Assuming that there is a security manager, or that the * implementation chooses to make checks anyway, the checks are made * as detailed below. In what follows, <code>className</code> is the * string returned by {@link MBeanInfo#getClassName()} for the target * MBean.</p> * * <p>If a security check fails, the method throws {@link * SecurityException}.</p> * * <p>For methods that can throw {@link InstanceNotFoundException}, * this exception is thrown for a non-existent MBean, regardless of * permissions. This is because a non-existent MBean has no * <code>className</code>.</p> * * <ul> * * <li><p>For the {@link #invoke invoke} method, the caller's * permissions must imply {@link * MBeanPermission#MBeanPermission(String,String,ObjectName,String) * MBeanPermission(className, operationName, name, "invoke")}.</p> * * <li><p>For the {@link #getAttribute getAttribute} method, the * caller's permissions must imply {@link * MBeanPermission#MBeanPermission(String,String,ObjectName,String) * MBeanPermission(className, attribute, name, "getAttribute")}.</p> * * <li><p>For the {@link #getAttributes getAttributes} method, the * caller's permissions must imply {@link * MBeanPermission#MBeanPermission(String,String,ObjectName,String) * MBeanPermission(className, null, name, "getAttribute")}. * Additionally, for each attribute <em>a</em> in the {@link * AttributeList}, if the caller's permissions do not imply {@link * MBeanPermission#MBeanPermission(String,String,ObjectName,String) * MBeanPermission(className, <em>a</em>, name, "getAttribute")}, the * MBean server will behave as if that attribute had not been in the * supplied list.</p> * * <li><p>For the {@link #setAttribute setAttribute} method, the * caller's permissions must imply {@link * MBeanPermission#MBeanPermission(String,String,ObjectName,String) * MBeanPermission(className, attrName, name, "setAttribute")}, where * <code>attrName</code> is {@link Attribute#getName() * attribute.getName()}.</p> * * <li><p>For the {@link #setAttributes setAttributes} method, the * caller's permissions must imply {@link * MBeanPermission#MBeanPermission(String,String,ObjectName,String) * MBeanPermission(className, null, name, "setAttribute")}. * Additionally, for each attribute <em>a</em> in the {@link * AttributeList}, if the caller's permissions do not imply {@link * MBeanPermission#MBeanPermission(String,String,ObjectName,String) * MBeanPermission(className, <em>a</em>, name, "setAttribute")}, the * MBean server will behave as if that attribute had not been in the * supplied list.</p> * * <li><p>For the <code>addNotificationListener</code> methods, * the caller's permissions must imply {@link * MBeanPermission#MBeanPermission(String,String,ObjectName,String) * MBeanPermission(className, null, name, * "addNotificationListener")}.</p> * * <li><p>For the <code>removeNotificationListener</code> methods, * the caller's permissions must imply {@link * MBeanPermission#MBeanPermission(String,String,ObjectName,String) * MBeanPermission(className, null, name, * "removeNotificationListener")}.</p> * * <li><p>For the {@link #getMBeanInfo getMBeanInfo} method, the * caller's permissions must imply {@link * MBeanPermission#MBeanPermission(String,String,ObjectName,String) * MBeanPermission(className, null, name, "getMBeanInfo")}.</p> * * <li><p>For the {@link #getObjectInstance getObjectInstance} method, * the caller's permissions must imply {@link * MBeanPermission#MBeanPermission(String,String,ObjectName,String) * MBeanPermission(className, null, name, "getObjectInstance")}.</p> * * <li><p>For the {@link #isInstanceOf isInstanceOf} method, the * caller's permissions must imply {@link * MBeanPermission#MBeanPermission(String,String,ObjectName,String) * MBeanPermission(className, null, name, "isInstanceOf")}.</p> * * <li><p>For the {@link #queryMBeans queryMBeans} method, the * caller's permissions must imply {@link * MBeanPermission#MBeanPermission(String,String,ObjectName,String) * MBeanPermission(null, null, name, "queryMBeans")}. * Additionally, for each MBean that matches <code>name</code>, * if the caller's permissions do not imply {@link * MBeanPermission#MBeanPermission(String,String,ObjectName,String) * MBeanPermission(className, null, name, "queryMBeans")}, the * MBean server will behave as if that MBean did not exist.</p> * * <p>Certain query elements perform operations on the MBean server. * If the caller does not have the required permissions for a given * MBean, that MBean will not be included in the result of the query. * The standard query elements that are affected are {@link * Query#attr(String)}, {@link Query#attr(String,String)}, and {@link * Query#classattr()}.</p> * * <li><p>For the {@link #queryNames queryNames} method, the checks * are the same as for <code>queryMBeans</code> except that * <code>"queryNames"</code> is used instead of * <code>"queryMBeans"</code> in the <code>MBeanPermission</code> * objects. Note that a <code>"queryMBeans"</code> permission implies * the corresponding <code>"queryNames"</code> permission.</p> * * <li><p>For the {@link #getDomains getDomains} method, the caller's * permissions must imply {@link * MBeanPermission#MBeanPermission(String,String,ObjectName,String) * MBeanPermission(null, null, name, "getDomains")}. Additionally, * for each domain <var>d</var> in the returned array, if the caller's * permissions do not imply {@link * MBeanPermission#MBeanPermission(String,String,ObjectName,String) * MBeanPermission(null, null, new ObjectName("<var>d</var>:x=x"), * "getDomains")}, the domain is eliminated from the array. Here, * <code>x=x</code> is any <var>key=value</var> pair, needed to * satisfy ObjectName's constructor but not otherwise relevant.</p> * * <li><p>For the {@link #getClassLoader getClassLoader} method, the * caller's permissions must imply {@link * MBeanPermission#MBeanPermission(String,String,ObjectName,String) * MBeanPermission(className, null, loaderName, * "getClassLoader")}.</p> * * <li><p>For the {@link #getClassLoaderFor getClassLoaderFor} method, * the caller's permissions must imply {@link * MBeanPermission#MBeanPermission(String,String,ObjectName,String) * MBeanPermission(className, null, mbeanName, * "getClassLoaderFor")}.</p> * * <li><p>For the {@link #getClassLoaderRepository * getClassLoaderRepository} method, the caller's permissions must * imply {@link * MBeanPermission#MBeanPermission(String,String,ObjectName,String) * MBeanPermission(null, null, null, "getClassLoaderRepository")}.</p> * * <li><p>For the deprecated <code>deserialize</code> methods, the * required permissions are the same as for the methods that replace * them.</p> * * <li><p>For the <code>instantiate</code> methods, the caller's * permissions must imply {@link * MBeanPermission#MBeanPermission(String,String,ObjectName,String) * MBeanPermission(className, null, null, "instantiate")}.</p> * * <li><p>For the {@link #registerMBean registerMBean} method, the * caller's permissions must imply {@link * MBeanPermission#MBeanPermission(String,String,ObjectName,String) * MBeanPermission(className, null, name, "registerMBean")}. Here * <code>className</code> is the string returned by {@link * MBeanInfo#getClassName()} for an object of this class. * * <p>If the <code>MBeanPermission</code> check succeeds, the MBean's * class is validated by checking that its {@link * java.security.ProtectionDomain ProtectionDomain} implies {@link * MBeanTrustPermission#MBeanTrustPermission(String) * MBeanTrustPermission("register")}.</p> * * <p>Finally, if the <code>name</code> argument is null, another * <code>MBeanPermission</code> check is made using the * <code>ObjectName</code> returned by {@link * MBeanRegistration#preRegister MBeanRegistration.preRegister}.</p> * * <li><p>For the <code>createMBean</code> methods, the caller's * permissions must imply the permissions needed by the equivalent * <code>instantiate</code> followed by * <code>registerMBean</code>.</p> * * <li><p>For the {@link #unregisterMBean unregisterMBean} method, * the caller's permissions must imply {@link * MBeanPermission#MBeanPermission(String,String,ObjectName,String) * MBeanPermission(className, null, name, "unregisterMBean")}.</p> * * </ul> * * @since 1.5 */ /* DELETED: * * <li><p>For the {@link #isRegistered isRegistered} method, the * caller's permissions must imply {@link * MBeanPermission#MBeanPermission(String,String,ObjectName,String) * MBeanPermission(null, null, name, "isRegistered")}.</p> */ public interface MBeanServer extends MBeanServerConnection { // doc comment inherited from MBeanServerConnection public ObjectInstance createMBean(String className, ObjectName name) throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException; // doc comment inherited from MBeanServerConnection public ObjectInstance createMBean(String className, ObjectName name, ObjectName loaderName) throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException, InstanceNotFoundException; // doc comment inherited from MBeanServerConnection public ObjectInstance createMBean(String className, ObjectName name, Object params[], String signature[]) throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException; // doc comment inherited from MBeanServerConnection public ObjectInstance createMBean(String className, ObjectName name, ObjectName loaderName, Object params[], String signature[]) throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException, InstanceNotFoundException; /** {@collect.stats} * Registers a pre-existing object as an MBean with the MBean * server. If the object name given is null, the MBean must * provide its own name by implementing the {@link * javax.management.MBeanRegistration MBeanRegistration} interface * and returning the name from the {@link * MBeanRegistration#preRegister preRegister} method. * * @param object The MBean to be registered as an MBean. * @param name The object name of the MBean. May be null. * * @return An <CODE>ObjectInstance</CODE>, containing the * <CODE>ObjectName</CODE> and the Java class name of the newly * registered MBean. If the contained <code>ObjectName</code> * is <code>n</code>, the contained Java class name is * <code>{@link #getMBeanInfo getMBeanInfo(n)}.getClassName()</code>. * * @exception InstanceAlreadyExistsException The MBean is already * under the control of the MBean server. * @exception MBeanRegistrationException The * <CODE>preRegister</CODE> (<CODE>MBeanRegistration</CODE> * interface) method of the MBean has thrown an exception. The * MBean will not be registered. * @exception NotCompliantMBeanException This object is not a JMX * compliant MBean * @exception RuntimeOperationsException Wraps a * <CODE>java.lang.IllegalArgumentException</CODE>: The object * passed in parameter is null or no object name is specified. */ public ObjectInstance registerMBean(Object object, ObjectName name) throws InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException; // doc comment inherited from MBeanServerConnection public void unregisterMBean(ObjectName name) throws InstanceNotFoundException, MBeanRegistrationException; // doc comment inherited from MBeanServerConnection public ObjectInstance getObjectInstance(ObjectName name) throws InstanceNotFoundException; // doc comment inherited from MBeanServerConnection public Set<ObjectInstance> queryMBeans(ObjectName name, QueryExp query); // doc comment inherited from MBeanServerConnection public Set<ObjectName> queryNames(ObjectName name, QueryExp query); // doc comment inherited from MBeanServerConnection public boolean isRegistered(ObjectName name); /** {@collect.stats} * Returns the number of MBeans registered in the MBean server. * * @return the number of registered MBeans, wrapped in an Integer. * If the caller's permissions are restricted, this number may * be greater than the number of MBeans the caller can access. */ public Integer getMBeanCount(); // doc comment inherited from MBeanServerConnection public Object getAttribute(ObjectName name, String attribute) throws MBeanException, AttributeNotFoundException, InstanceNotFoundException, ReflectionException; // doc comment inherited from MBeanServerConnection public AttributeList getAttributes(ObjectName name, String[] attributes) throws InstanceNotFoundException, ReflectionException; // doc comment inherited from MBeanServerConnection public void setAttribute(ObjectName name, Attribute attribute) throws InstanceNotFoundException, AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException; // doc comment inherited from MBeanServerConnection public AttributeList setAttributes(ObjectName name, AttributeList attributes) throws InstanceNotFoundException, ReflectionException; // doc comment inherited from MBeanServerConnection public Object invoke(ObjectName name, String operationName, Object params[], String signature[]) throws InstanceNotFoundException, MBeanException, ReflectionException; // doc comment inherited from MBeanServerConnection public String getDefaultDomain(); // doc comment inherited from MBeanServerConnection public String[] getDomains(); // doc comment inherited from MBeanServerConnection public void addNotificationListener(ObjectName name, NotificationListener listener, NotificationFilter filter, Object handback) throws InstanceNotFoundException; // doc comment inherited from MBeanServerConnection public void addNotificationListener(ObjectName name, ObjectName listener, NotificationFilter filter, Object handback) throws InstanceNotFoundException; // doc comment inherited from MBeanServerConnection public void removeNotificationListener(ObjectName name, ObjectName listener) throws InstanceNotFoundException, ListenerNotFoundException; // doc comment inherited from MBeanServerConnection public void removeNotificationListener(ObjectName name, ObjectName listener, NotificationFilter filter, Object handback) throws InstanceNotFoundException, ListenerNotFoundException; // doc comment inherited from MBeanServerConnection public void removeNotificationListener(ObjectName name, NotificationListener listener) throws InstanceNotFoundException, ListenerNotFoundException; // doc comment inherited from MBeanServerConnection public void removeNotificationListener(ObjectName name, NotificationListener listener, NotificationFilter filter, Object handback) throws InstanceNotFoundException, ListenerNotFoundException; // doc comment inherited from MBeanServerConnection public MBeanInfo getMBeanInfo(ObjectName name) throws InstanceNotFoundException, IntrospectionException, ReflectionException; // doc comment inherited from MBeanServerConnection public boolean isInstanceOf(ObjectName name, String className) throws InstanceNotFoundException; /** {@collect.stats} * <p>Instantiates an object using the list of all class loaders * registered in the MBean server's {@link * javax.management.loading.ClassLoaderRepository Class Loader * Repository}. The object's class should have a public * constructor. This method returns a reference to the newly * created object. The newly created object is not registered in * the MBean server.</p> * * <p>This method is equivalent to {@link * #instantiate(String,Object[],String[]) * instantiate(className, (Object[]) null, (String[]) null)}.</p> * * @param className The class name of the object to be instantiated. * * @return The newly instantiated object. * * @exception ReflectionException Wraps a * <CODE>java.lang.ClassNotFoundException</CODE> or the * <CODE>java.lang.Exception</CODE> that occurred when trying to * invoke the object's constructor. * @exception MBeanException The constructor of the object has * thrown an exception * @exception RuntimeOperationsException Wraps a * <CODE>java.lang.IllegalArgumentException</CODE>: The className * passed in parameter is null. */ public Object instantiate(String className) throws ReflectionException, MBeanException; /** {@collect.stats} * <p>Instantiates an object using the class Loader specified by its * <CODE>ObjectName</CODE>. If the loader name is null, the * ClassLoader that loaded the MBean Server will be used. The * object's class should have a public constructor. This method * returns a reference to the newly created object. The newly * created object is not registered in the MBean server.</p> * * <p>This method is equivalent to {@link * #instantiate(String,ObjectName,Object[],String[]) * instantiate(className, loaderName, (Object[]) null, (String[]) * null)}.</p> * * @param className The class name of the MBean to be instantiated. * @param loaderName The object name of the class loader to be used. * * @return The newly instantiated object. * * @exception ReflectionException Wraps a * <CODE>java.lang.ClassNotFoundException</CODE> or the * <CODE>java.lang.Exception</CODE> that occurred when trying to * invoke the object's constructor. * @exception MBeanException The constructor of the object has * thrown an exception. * @exception InstanceNotFoundException The specified class loader * is not registered in the MBeanServer. * @exception RuntimeOperationsException Wraps a * <CODE>java.lang.IllegalArgumentException</CODE>: The className * passed in parameter is null. */ public Object instantiate(String className, ObjectName loaderName) throws ReflectionException, MBeanException, InstanceNotFoundException; /** {@collect.stats} * <p>Instantiates an object using the list of all class loaders * registered in the MBean server {@link * javax.management.loading.ClassLoaderRepository Class Loader * Repository}. The object's class should have a public * constructor. The call returns a reference to the newly created * object. The newly created object is not registered in the * MBean server.</p> * * @param className The class name of the object to be instantiated. * @param params An array containing the parameters of the * constructor to be invoked. * @param signature An array containing the signature of the * constructor to be invoked. * * @return The newly instantiated object. * * @exception ReflectionException Wraps a * <CODE>java.lang.ClassNotFoundException</CODE> or the * <CODE>java.lang.Exception</CODE> that occurred when trying to * invoke the object's constructor. * @exception MBeanException The constructor of the object has * thrown an exception * @exception RuntimeOperationsException Wraps a * <CODE>java.lang.IllegalArgumentException</CODE>: The className * passed in parameter is null. */ public Object instantiate(String className, Object params[], String signature[]) throws ReflectionException, MBeanException; /** {@collect.stats} * <p>Instantiates an object. The class loader to be used is * identified by its object name. If the object name of the loader * is null, the ClassLoader that loaded the MBean server will be * used. The object's class should have a public constructor. * The call returns a reference to the newly created object. The * newly created object is not registered in the MBean server.</p> * * @param className The class name of the object to be instantiated. * @param params An array containing the parameters of the * constructor to be invoked. * @param signature An array containing the signature of the * constructor to be invoked. * @param loaderName The object name of the class loader to be used. * * @return The newly instantiated object. * * @exception ReflectionException Wraps a <CODE>java.lang.ClassNotFoundException</CODE> or the <CODE>java.lang.Exception</CODE> that * occurred when trying to invoke the object's constructor. * @exception MBeanException The constructor of the object has * thrown an exception * @exception InstanceNotFoundException The specified class loader * is not registered in the MBean server. * @exception RuntimeOperationsException Wraps a * <CODE>java.lang.IllegalArgumentException</CODE>: The className * passed in parameter is null. */ public Object instantiate(String className, ObjectName loaderName, Object params[], String signature[]) throws ReflectionException, MBeanException, InstanceNotFoundException; /** {@collect.stats} * <p>De-serializes a byte array in the context of the class loader * of an MBean.</p> * * @param name The name of the MBean whose class loader should be * used for the de-serialization. * @param data The byte array to be de-sererialized. * * @return The de-serialized object stream. * * @exception InstanceNotFoundException The MBean specified is not * found. * @exception OperationsException Any of the usual Input/Output * related exceptions. * * @deprecated Use {@link #getClassLoaderFor getClassLoaderFor} to * obtain the appropriate class loader for deserialization. */ @Deprecated public ObjectInputStream deserialize(ObjectName name, byte[] data) throws InstanceNotFoundException, OperationsException; /** {@collect.stats} * <p>De-serializes a byte array in the context of a given MBean * class loader. The class loader is found by loading the class * <code>className</code> through the {@link * javax.management.loading.ClassLoaderRepository Class Loader * Repository}. The resultant class's class loader is the one to * use. * * @param className The name of the class whose class loader should be * used for the de-serialization. * @param data The byte array to be de-sererialized. * * @return The de-serialized object stream. * * @exception OperationsException Any of the usual Input/Output * related exceptions. * @exception ReflectionException The specified class could not be * loaded by the class loader repository * * @deprecated Use {@link #getClassLoaderRepository} to obtain the * class loader repository and use it to deserialize. */ @Deprecated public ObjectInputStream deserialize(String className, byte[] data) throws OperationsException, ReflectionException; /** {@collect.stats} * <p>De-serializes a byte array in the context of a given MBean * class loader. The class loader is the one that loaded the * class with name "className". The name of the class loader to * be used for loading the specified class is specified. If null, * the MBean Server's class loader will be used.</p> * * @param className The name of the class whose class loader should be * used for the de-serialization. * @param data The byte array to be de-sererialized. * @param loaderName The name of the class loader to be used for * loading the specified class. If null, the MBean Server's class * loader will be used. * * @return The de-serialized object stream. * * @exception InstanceNotFoundException The specified class loader * MBean is not found. * @exception OperationsException Any of the usual Input/Output * related exceptions. * @exception ReflectionException The specified class could not be * loaded by the specified class loader. * * @deprecated Use {@link #getClassLoader getClassLoader} to obtain * the class loader for deserialization. */ @Deprecated public ObjectInputStream deserialize(String className, ObjectName loaderName, byte[] data) throws InstanceNotFoundException, OperationsException, ReflectionException; /** {@collect.stats} * <p>Return the {@link java.lang.ClassLoader} that was used for * loading the class of the named MBean.</p> * * @param mbeanName The ObjectName of the MBean. * * @return The ClassLoader used for that MBean. If <var>l</var> * is the MBean's actual ClassLoader, and <var>r</var> is the * returned value, then either: * * <ul> * <li><var>r</var> is identical to <var>l</var>; or * <li>the result of <var>r</var>{@link * ClassLoader#loadClass(String) .loadClass(<var>s</var>)} is the * same as <var>l</var>{@link ClassLoader#loadClass(String) * .loadClass(<var>s</var>)} for any string <var>s</var>. * </ul> * * What this means is that the ClassLoader may be wrapped in * another ClassLoader for security or other reasons. * * @exception InstanceNotFoundException if the named MBean is not found. * */ public ClassLoader getClassLoaderFor(ObjectName mbeanName) throws InstanceNotFoundException; /** {@collect.stats} * <p>Return the named {@link java.lang.ClassLoader}.</p> * * @param loaderName The ObjectName of the ClassLoader. May be * null, in which case the MBean server's own ClassLoader is * returned. * * @return The named ClassLoader. If <var>l</var> is the actual * ClassLoader with that name, and <var>r</var> is the returned * value, then either: * * <ul> * <li><var>r</var> is identical to <var>l</var>; or * <li>the result of <var>r</var>{@link * ClassLoader#loadClass(String) .loadClass(<var>s</var>)} is the * same as <var>l</var>{@link ClassLoader#loadClass(String) * .loadClass(<var>s</var>)} for any string <var>s</var>. * </ul> * * What this means is that the ClassLoader may be wrapped in * another ClassLoader for security or other reasons. * * @exception InstanceNotFoundException if the named ClassLoader is * not found. * */ public ClassLoader getClassLoader(ObjectName loaderName) throws InstanceNotFoundException; /** {@collect.stats} * <p>Return the ClassLoaderRepository for this MBeanServer. * @return The ClassLoaderRepository for this MBeanServer. * */ public ClassLoaderRepository getClassLoaderRepository(); }
Java
/* * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management; import com.sun.jmx.mbeanserver.GetPropertyAction; import java.io.IOException; import java.io.InvalidObjectException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.ObjectStreamField; import java.security.AccessController; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Hashtable; import java.util.Map; /** {@collect.stats} * <p>Represents the object name of an MBean, or a pattern that can * match the names of several MBeans. Instances of this class are * immutable.</p> * * <p>An instance of this class can be used to represent:</p> * <ul> * <li>An object name</li> * <li>An object name pattern, within the context of a query</li> * </ul> * * <p>An object name consists of two parts, the domain and the key * properties.</p> * * <p>The <em>domain</em> is a string of characters not including * the character colon (<code>:</code>). It is recommended that the domain * should not contain the string "{@code //}", which is reserved for future use. * * <p>If the domain includes at least one occurrence of the wildcard * characters asterisk (<code>*</code>) or question mark * (<code>?</code>), then the object name is a pattern. The asterisk * matches any sequence of zero or more characters, while the question * mark matches any single character.</p> * * <p>If the domain is empty, it will be replaced in certain contexts * by the <em>default domain</em> of the MBean server in which the * ObjectName is used.</p> * * <p>The <em>key properties</em> are an unordered set of keys and * associated values.</p> * * <p>Each <em>key</em> is a nonempty string of characters which may * not contain any of the characters comma (<code>,</code>), equals * (<code>=</code>), colon, asterisk, or question mark. The same key * may not occur twice in a given ObjectName.</p> * * <p>Each <em>value</em> associated with a key is a string of * characters that is either unquoted or quoted.</p> * * <p>An <em>unquoted value</em> is a possibly empty string of * characters which may not contain any of the characters comma, * equals, colon, or quote.</p> * * <p>If the <em>unquoted value</em> contains at least one occurrence * of the wildcard characters asterisk or question mark, then the object * name is a <em>property value pattern</em>. The asterisk matches any * sequence of zero or more characters, while the question mark matches * any single character.</p> * * <p>A <em>quoted value</em> consists of a quote (<code>"</code>), * followed by a possibly empty string of characters, followed by * another quote. Within the string of characters, the backslash * (<code>\</code>) has a special meaning. It must be followed by * one of the following characters:</p> * * <ul> * <li>Another backslash. The second backslash has no special * meaning and the two characters represent a single backslash.</li> * * <li>The character 'n'. The two characters represent a newline * ('\n' in Java).</li> * * <li>A quote. The two characters represent a quote, and that quote * is not considered to terminate the quoted value. An ending closing * quote must be present for the quoted value to be valid.</li> * * <li>A question mark (?) or asterisk (*). The two characters represent * a question mark or asterisk respectively.</li> * </ul> * * <p>A quote may not appear inside a quoted value except immediately * after an odd number of consecutive backslashes.</p> * * <p>The quotes surrounding a quoted value, and any backslashes * within that value, are considered to be part of the value.</p> * * <p>If the <em>quoted value</em> contains at least one occurrence of * the characters asterisk or question mark and they are not preceded * by a backslash, then they are considered as wildcard characters and * the object name is a <em>property value pattern</em>. The asterisk * matches any sequence of zero or more characters, while the question * mark matches any single character.</p> * * <p>An ObjectName may be a <em>property list pattern</em>. In this * case it may have zero or more keys and associated values. It matches * a nonpattern ObjectName whose domain matches and that contains the * same keys and associated values, as well as possibly other keys and * values.</p> * * <p>An ObjectName is a <em>property value pattern</em> when at least * one of its <em>quoted</em> or <em>unquoted</em> key property values * contains the wildcard characters asterisk or question mark as described * above. In this case it has one or more keys and associated values, with * at least one of the values containing wildcard characters. It matches a * nonpattern ObjectName whose domain matches and that contains the same * keys whose values match; if the property value pattern is also a * property list pattern then the nonpattern ObjectName can contain * other keys and values.</p> * * <p>An ObjectName is a <em>property pattern</em> if it is either a * <em>property list pattern</em> or a <em>property value pattern</em> * or both.</p> * * <p>An ObjectName is a pattern if its domain contains a wildcard or * if the ObjectName is a property pattern.</p> * * <p>If an ObjectName is not a pattern, it must contain at least one * key with its associated value.</p> * * <p>Examples of ObjectName patterns are:</p> * * <ul> * <li>{@code *:type=Foo,name=Bar} to match names in any domain whose * exact set of keys is {@code type=Foo,name=Bar}.</li> * <li>{@code d:type=Foo,name=Bar,*} to match names in the domain * {@code d} that have the keys {@code type=Foo,name=Bar} plus * zero or more other keys.</li> * <li>{@code *:type=Foo,name=Bar,*} to match names in any domain * that has the keys {@code type=Foo,name=Bar} plus zero or * more other keys.</li> * <li>{@code d:type=F?o,name=Bar} will match e.g. * {@code d:type=Foo,name=Bar} and {@code d:type=Fro,name=Bar}.</li> * <li>{@code d:type=F*o,name=Bar} will match e.g. * {@code d:type=Fo,name=Bar} and {@code d:type=Frodo,name=Bar}.</li> * <li>{@code d:type=Foo,name="B*"} will match e.g. * {@code d:type=Foo,name="Bling"}. Wildcards are recognized even * inside quotes, and like other special characters can be escaped * with {@code \}.</li> * </ul> * * <p>An ObjectName can be written as a String with the following * elements in order:</p> * * <ul> * <li>The domain. * <li>A colon (<code>:</code>). * <li>A key property list as defined below. * </ul> * * <p>A key property list written as a String is a comma-separated * list of elements. Each element is either an asterisk or a key * property. A key property consists of a key, an equals * (<code>=</code>), and the associated value.</p> * * <p>At most one element of a key property list may be an asterisk. * If the key property list contains an asterisk element, the * ObjectName is a property list pattern.</p> * * <p>Spaces have no special significance in a String representing an * ObjectName. For example, the String: * <pre> * domain: key1 = value1 , key2 = value2 * </pre> * represents an ObjectName with two keys. The name of each key * contains six characters, of which the first and last are spaces. * The value associated with the key <code>"&nbsp;key1&nbsp;"</code> * also begins and ends with a space.</p> * * <p>In addition to the restrictions on characters spelt out above, * no part of an ObjectName may contain a newline character * (<code>'\n'</code>), whether the domain, a key, or a value, whether * quoted or unquoted. The newline character can be represented in a * quoted value with the sequence <code>\n</code>. * * <p>The rules on special characters and quoting apply regardless of * which constructor is used to make an ObjectName.</p> * * <p>To avoid collisions between MBeans supplied by different * vendors, a useful convention is to begin the domain name with the * reverse DNS name of the organization that specifies the MBeans, * followed by a period and a string whose interpretation is * determined by that organization. For example, MBeans specified by * Sun Microsystems Inc., DNS name <code>sun.com</code>, would have * domains such as <code>com.sun.MyDomain</code>. This is essentially * the same convention as for Java-language package names.</p> * * <p>The <b>serialVersionUID</b> of this class is <code>1081892073854801359L</code>. * * @since 1.5 */ @SuppressWarnings("serial") // don't complain serialVersionUID not constant public class ObjectName implements Comparable<ObjectName>, QueryExp { /** {@collect.stats} * A structure recording property structure and * proposing minimal services */ private static class Property { int _key_index; int _key_length; int _value_length; /** {@collect.stats} * Constructor. */ Property(int key_index, int key_length, int value_length) { _key_index = key_index; _key_length = key_length; _value_length = value_length; } /** {@collect.stats} * Assigns the key index of property */ void setKeyIndex(int key_index) { _key_index = key_index; } /** {@collect.stats} * Returns a key string for receiver key */ String getKeyString(String name) { return name.substring(_key_index, _key_index + _key_length); } /** {@collect.stats} * Returns a value string for receiver key */ String getValueString(String name) { int in_begin = _key_index + _key_length + 1; int out_end = in_begin + _value_length; return name.substring(in_begin, out_end); } } /** {@collect.stats} * Marker class for value pattern property. */ private static class PatternProperty extends Property { /** {@collect.stats} * Constructor. */ PatternProperty(int key_index, int key_length, int value_length) { super(key_index, key_length, value_length); } } // Inner classes <======================================== // Private fields ----------------------------------------> // Serialization compatibility stuff --------------------> // Two serial forms are supported in this class. The selected form depends // on system property "jmx.serial.form": // - "1.0" for JMX 1.0 // - any other value for JMX 1.1 and higher // // Serial version for old serial form private static final long oldSerialVersionUID = -5467795090068647408L; // // Serial version for new serial form private static final long newSerialVersionUID = 1081892073854801359L; // // Serializable fields in old serial form private static final ObjectStreamField[] oldSerialPersistentFields = { new ObjectStreamField("domain", String.class), new ObjectStreamField("propertyList", Hashtable.class), new ObjectStreamField("propertyListString", String.class), new ObjectStreamField("canonicalName", String.class), new ObjectStreamField("pattern", Boolean.TYPE), new ObjectStreamField("propertyPattern", Boolean.TYPE) }; // // Serializable fields in new serial form private static final ObjectStreamField[] newSerialPersistentFields = { }; // // Actual serial version and serial form private static final long serialVersionUID; private static final ObjectStreamField[] serialPersistentFields; private static boolean compat = false; static { try { GetPropertyAction act = new GetPropertyAction("jmx.serial.form"); String form = AccessController.doPrivileged(act); compat = (form != null && form.equals("1.0")); } catch (Exception e) { // OK: exception means no compat with 1.0, too bad } if (compat) { serialPersistentFields = oldSerialPersistentFields; serialVersionUID = oldSerialVersionUID; } else { serialPersistentFields = newSerialPersistentFields; serialVersionUID = newSerialVersionUID; } } // // Serialization compatibility stuff <============================== // Class private fields -----------------------------------> /** {@collect.stats} * a shared empty array for empty property lists */ static final private Property[] _Empty_property_array = new Property[0]; // Class private fields <============================== // Instance private fields -----------------------------------> /** {@collect.stats} * a String containing the canonical name */ private transient String _canonicalName; /** {@collect.stats} * An array of properties in the same seq order as time creation */ private transient Property[] _kp_array; /** {@collect.stats} * An array of properties in the same seq order as canonical order */ private transient Property[] _ca_array; /** {@collect.stats} * The length of the domain part of built objectname */ private transient int _domain_length = 0; /** {@collect.stats} * The propertyList of built object name. Initialized lazily. * Table that contains all the pairs (key,value) for this ObjectName. */ private transient Map<String,String> _propertyList; /** {@collect.stats} * boolean that declares if this ObjectName domain part is a pattern */ private transient boolean _domain_pattern = false; /** {@collect.stats} * boolean that declares if this ObjectName contains a pattern on the * key property list */ private transient boolean _property_list_pattern = false; /** {@collect.stats} * boolean that declares if this ObjectName contains a pattern on the * value of at least one key property */ private transient boolean _property_value_pattern = false; // Instance private fields <======================================= // Private fields <======================================== // Private methods ----------------------------------------> // Category : Instance construction -------------------------> /** {@collect.stats} * Initializes this {@link ObjectName} from the given string * representation. * * @param name A string representation of the {@link ObjectName} * * @exception MalformedObjectNameException The string passed as a * parameter does not have the right format. * @exception NullPointerException The <code>name</code> parameter * is null. */ private void construct(String name) throws MalformedObjectNameException, NullPointerException { // The name cannot be null if (name == null) throw new NullPointerException("name cannot be null"); // Test if the name is empty if (name.length() == 0) { // this is equivalent to the whole word query object name. _canonicalName = "*:*"; _kp_array = _Empty_property_array; _ca_array = _Empty_property_array; _domain_length = 1; _propertyList = null; _domain_pattern = true; _property_list_pattern = true; _property_value_pattern = false; return; } // initialize parsing of the string char[] name_chars = name.toCharArray(); int len = name_chars.length; char[] canonical_chars = new char[len]; // canonical form will be same // length at most int cname_index = 0; int index = 0; char c, c1; // parses domain part domain_parsing: while (index < len) { switch (c = name_chars[index]) { case ':' : _domain_length = index++; break domain_parsing; case '=' : // ":" omission check. // // Although "=" is a valid character in the domain part // it is true that it is rarely used in the real world. // So check straight away if the ":" has been omitted // from the ObjectName. This allows us to provide a more // accurate exception message. int i = ++index; while ((i < len) && (name_chars[i++] != ':')) if (i == len) throw new MalformedObjectNameException( "Domain part must be specified"); break; case '\n' : throw new MalformedObjectNameException( "Invalid character '\\n' in domain name"); case '*' : case '?' : _domain_pattern = true; index++; break; default : index++; break; } } // check for non-empty properties if (index == len) throw new MalformedObjectNameException( "Key properties cannot be empty"); // we have got the domain part, begins building of _canonicalName System.arraycopy(name_chars, 0, canonical_chars, 0, _domain_length); canonical_chars[_domain_length] = ':'; cname_index = _domain_length + 1; // parses property list Property prop; Map<String,Property> keys_map = new HashMap<String,Property>(); String[] keys; String key_name; boolean quoted_value; int property_index = 0; int in_index; int key_index, key_length, value_index, value_length; keys = new String[10]; _kp_array = new Property[10]; _property_list_pattern = false; _property_value_pattern = false; while (index < len) { c = name_chars[index]; // case of pattern properties if (c == '*') { if (_property_list_pattern) throw new MalformedObjectNameException( "Cannot have several '*' characters in pattern " + "property list"); else { _property_list_pattern = true; if ((++index < len ) && (name_chars[index] != ',')) throw new MalformedObjectNameException( "Invalid character found after '*': end of " + "name or ',' expected"); else if (index == len) { if (property_index == 0) { // empty properties case _kp_array = _Empty_property_array; _ca_array = _Empty_property_array; _propertyList = Collections.emptyMap(); } break; } else { // correct pattern spec in props, continue index++; continue; } } } // standard property case, key part in_index = index; key_index = in_index; if (name_chars[in_index] == '=') throw new MalformedObjectNameException("Invalid key (empty)"); while ((in_index < len) && ((c1 = name_chars[in_index++]) != '=')) switch (c1) { // '=' considered to introduce value part case '*' : case '?' : case ',' : case ':' : case '\n' : final String ichar = ((c1=='\n')?"\\n":""+c1); throw new MalformedObjectNameException( "Invalid character '" + ichar + "' in key part of property"); } if (name_chars[in_index - 1] != '=') throw new MalformedObjectNameException( "Unterminated key property part"); value_index = in_index; // in_index pointing after '=' char key_length = value_index - key_index - 1; // found end of key // standard property case, value part boolean value_pattern = false; if (in_index < len && name_chars[in_index] == '\"') { quoted_value = true; // the case of quoted value part quoted_value_parsing: while ((++in_index < len) && ((c1 = name_chars[in_index]) != '\"')) { // the case of an escaped character if (c1 == '\\') { if (++in_index == len) throw new MalformedObjectNameException( "Unterminated quoted value"); switch (c1 = name_chars[in_index]) { case '\\' : case '\"' : case '?' : case '*' : case 'n' : break; // valid character default : throw new MalformedObjectNameException( "Invalid escape sequence '\\" + c1 + "' in quoted value"); } } else if (c1 == '\n') { throw new MalformedObjectNameException( "Newline in quoted value"); } else { switch (c1) { case '?' : case '*' : value_pattern = true; break; } } } if (in_index == len) throw new MalformedObjectNameException( "Unterminated quoted value"); else value_length = ++in_index - value_index; } else { // the case of standard value part quoted_value = false; while ((in_index < len) && ((c1 = name_chars[in_index]) != ',')) switch (c1) { // ',' considered to be the value separator case '*' : case '?' : value_pattern = true; in_index++; break; case '=' : case ':' : case '"' : case '\n' : final String ichar = ((c1=='\n')?"\\n":""+c1); throw new MalformedObjectNameException( "Invalid character '" + c1 + "' in value part of property"); default : in_index++; break; } value_length = in_index - value_index; } // Parsed property, checks the end of name if (in_index == len - 1) { if (quoted_value) throw new MalformedObjectNameException( "Invalid ending character `" + name_chars[in_index] + "'"); else throw new MalformedObjectNameException( "Invalid ending comma"); } else in_index++; // we got the key and value part, prepare a property for this if (!value_pattern) { prop = new Property(key_index, key_length, value_length); } else { _property_value_pattern = true; prop = new PatternProperty(key_index, key_length, value_length); } key_name = name.substring(key_index, key_index + key_length); if (property_index == keys.length) { String[] tmp_string_array = new String[property_index + 10]; System.arraycopy(keys, 0, tmp_string_array, 0, property_index); keys = tmp_string_array; } keys[property_index] = key_name; addProperty(prop, property_index, keys_map, key_name); property_index++; index = in_index; } // computes and set canonical name setCanonicalName(name_chars, canonical_chars, keys, keys_map, cname_index, property_index); } /** {@collect.stats} * Construct an ObjectName from a domain and a Hashtable. * * @param domain Domain of the ObjectName. * @param props Map containing couples <i>key</i> -> <i>value</i>. * * @exception MalformedObjectNameException The <code>domain</code> * contains an illegal character, or one of the keys or values in * <code>table</code> contains an illegal character, or one of the * values in <code>table</code> does not follow the rules for quoting. * @exception NullPointerException One of the parameters is null. */ private void construct(String domain, Map<String,String> props) throws MalformedObjectNameException, NullPointerException { // The domain cannot be null if (domain == null) throw new NullPointerException("domain cannot be null"); // The key property list cannot be null if (props == null) throw new NullPointerException("key property list cannot be null"); // The key property list cannot be empty if (props.isEmpty()) throw new MalformedObjectNameException( "key property list cannot be empty"); // checks domain validity if (!isDomain(domain)) throw new MalformedObjectNameException("Invalid domain: " + domain); // init canonicalname final StringBuilder sb = new StringBuilder(); sb.append(domain).append(':'); _domain_length = domain.length(); // allocates the property array int nb_props = props.size(); _kp_array = new Property[nb_props]; String[] keys = new String[nb_props]; final Map<String,Property> keys_map = new HashMap<String,Property>(); Property prop; int key_index; int i = 0; for (Map.Entry<String,String> entry : props.entrySet()) { if (sb.length() > 0) sb.append(","); String key = entry.getKey(); String value; try { value = entry.getValue(); } catch (ClassCastException e) { throw new MalformedObjectNameException(e.getMessage()); } key_index = sb.length(); checkKey(key); sb.append(key); keys[i] = key; sb.append("="); boolean value_pattern = checkValue(value); sb.append(value); if (!value_pattern) { prop = new Property(key_index, key.length(), value.length()); } else { _property_value_pattern = true; prop = new PatternProperty(key_index, key.length(), value.length()); } addProperty(prop, i, keys_map, key); i++; } // initialize canonical name and data structure int len = sb.length(); char[] initial_chars = new char[len]; sb.getChars(0, len, initial_chars, 0); char[] canonical_chars = new char[len]; System.arraycopy(initial_chars, 0, canonical_chars, 0, _domain_length + 1); setCanonicalName(initial_chars, canonical_chars, keys, keys_map, _domain_length + 1, _kp_array.length); } // Category : Instance construction <============================== // Category : Internal utilities ------------------------------> /** {@collect.stats} * Add passed property to the list at the given index * for the passed key name */ private void addProperty(Property prop, int index, Map<String,Property> keys_map, String key_name) throws MalformedObjectNameException { if (keys_map.containsKey(key_name)) throw new MalformedObjectNameException("key `" + key_name +"' already defined"); // if no more space for property arrays, have to increase it if (index == _kp_array.length) { Property[] tmp_prop_array = new Property[index + 10]; System.arraycopy(_kp_array, 0, tmp_prop_array, 0, index); _kp_array = tmp_prop_array; } _kp_array[index] = prop; keys_map.put(key_name, prop); } /** {@collect.stats} * Sets the canonical name of receiver from input 'specified_chars' * array, by filling 'canonical_chars' array with found 'nb-props' * properties starting at position 'prop_index'. */ private void setCanonicalName(char[] specified_chars, char[] canonical_chars, String[] keys, Map<String,Property> keys_map, int prop_index, int nb_props) { // Sort the list of found properties if (_kp_array != _Empty_property_array) { String[] tmp_keys = new String[nb_props]; Property[] tmp_props = new Property[nb_props]; System.arraycopy(keys, 0, tmp_keys, 0, nb_props); Arrays.sort(tmp_keys); keys = tmp_keys; System.arraycopy(_kp_array, 0, tmp_props, 0 , nb_props); _kp_array = tmp_props; _ca_array = new Property[nb_props]; // now assigns _ca_array to the sorted list of keys // (there cannot be two identical keys in an objectname. for (int i = 0; i < nb_props; i++) _ca_array[i] = keys_map.get(keys[i]); // now we build the canonical name and set begin indexes of // properties to reflect canonical form int last_index = nb_props - 1; int prop_len; Property prop; for (int i = 0; i <= last_index; i++) { prop = _ca_array[i]; // length of prop including '=' char prop_len = prop._key_length + prop._value_length + 1; System.arraycopy(specified_chars, prop._key_index, canonical_chars, prop_index, prop_len); prop.setKeyIndex(prop_index); prop_index += prop_len; if (i != last_index) { canonical_chars[prop_index] = ','; prop_index++; } } } // terminate canonicalname with '*' in case of pattern if (_property_list_pattern) { if (_kp_array != _Empty_property_array) canonical_chars[prop_index++] = ','; canonical_chars[prop_index++] = '*'; } // we now build the canonicalname string _canonicalName = (new String(canonical_chars, 0, prop_index)).intern(); } /** {@collect.stats} * Parse a key. * <pre>final int endKey=parseKey(s,startKey);</pre> * <p>key starts at startKey (included), and ends at endKey (excluded). * If (startKey == endKey), then the key is empty. * * @param s The char array of the original string. * @param startKey index at which to begin parsing. * @return The index following the last character of the key. **/ private static int parseKey(final char[] s, final int startKey) throws MalformedObjectNameException { int next = startKey; int endKey = startKey; final int len = s.length; while (next < len) { final char k = s[next++]; switch (k) { case '*': case '?': case ',': case ':': case '\n': final String ichar = ((k=='\n')?"\\n":""+k); throw new MalformedObjectNameException("Invalid character in key: `" + ichar + "'"); case '=': // we got the key. endKey = next-1; break; default: if (next < len) continue; else endKey=next; } break; } return endKey; } /** {@collect.stats} * Parse a value. * <pre>final int endVal=parseValue(s,startVal);</pre> * <p>value starts at startVal (included), and ends at endVal (excluded). * If (startVal == endVal), then the key is empty. * * @param s The char array of the original string. * @param startValue index at which to begin parsing. * @return The first element of the int array indicates the index * following the last character of the value. The second * element of the int array indicates that the value is * a pattern when its value equals 1. **/ private static int[] parseValue(final char[] s, final int startValue) throws MalformedObjectNameException { boolean value_pattern = false; int next = startValue; int endValue = startValue; final int len = s.length; final char q=s[startValue]; if (q == '"') { // quoted value if (++next == len) throw new MalformedObjectNameException("Invalid quote"); while (next < len) { char last = s[next]; if (last == '\\') { if (++next == len) throw new MalformedObjectNameException( "Invalid unterminated quoted character sequence"); last = s[next]; switch (last) { case '\\' : case '?' : case '*' : case 'n' : break; case '\"' : // We have an escaped quote. If this escaped // quote is the last character, it does not // qualify as a valid termination quote. // if (next+1 == len) throw new MalformedObjectNameException( "Missing termination quote"); break; default: throw new MalformedObjectNameException( "Invalid quoted character sequence '\\" + last + "'"); } } else if (last == '\n') { throw new MalformedObjectNameException( "Newline in quoted value"); } else if (last == '\"') { next++; break; } else { switch (last) { case '?' : case '*' : value_pattern = true; break; } } next++; // Check that last character is a termination quote. // We have already handled the case were the last // character is an escaped quote earlier. // if ((next >= len) && (last != '\"')) throw new MalformedObjectNameException("Missing termination quote"); } endValue = next; if (next < len) { if (s[next++] != ',') throw new MalformedObjectNameException("Invalid quote"); } } else { // Non quoted value. while (next < len) { final char v=s[next++]; switch(v) { case '*': case '?': value_pattern = true; if (next < len) continue; else endValue=next; break; case '=': case ':': case '\n' : final String ichar = ((v=='\n')?"\\n":""+v); throw new MalformedObjectNameException("Invalid character `" + ichar + "' in value"); case ',': endValue = next-1; break; default: if (next < len) continue; else endValue=next; } break; } } return new int[] { endValue, value_pattern ? 1 : 0 }; } /** {@collect.stats} * Check if the supplied value is a valid value. * * @return true if the value is a pattern, otherwise false. */ private static boolean checkValue(String val) throws MalformedObjectNameException { if (val == null) throw new NullPointerException("Invalid value (null)"); final int len = val.length(); if (len == 0) return false; final char[] s = val.toCharArray(); final int[] result = parseValue(s,0); final int endValue = result[0]; final boolean value_pattern = result[1] == 1; if (endValue < len) throw new MalformedObjectNameException("Invalid character in value: `" + s[endValue] + "'"); return value_pattern; } /** {@collect.stats} * Check if the supplied key is a valid key. */ private static void checkKey(String key) throws MalformedObjectNameException, NullPointerException { if (key == null) throw new NullPointerException("Invalid key (null)"); final int len = key.length(); if (len == 0) throw new MalformedObjectNameException("Invalid key (empty)"); final char[] k=key.toCharArray(); final int endKey = parseKey(k,0); if (endKey < len) throw new MalformedObjectNameException("Invalid character in value: `" + k[endKey] + "'"); } /* * Tests whether string s is matched by pattern p. * Supports "?", "*" each of which may be escaped with "\"; * Not yet supported: internationalization; "\" inside brackets.<P> * Wildcard matching routine by Karl Heuer. Public Domain.<P> */ private static boolean wildmatch(char[] s, char[] p, int si, int pi) { char c; final int slen = s.length; final int plen = p.length; while (pi < plen) { // While still string c = p[pi++]; if (c == '?') { if (++si > slen) return false; } else if (c == '*') { // Wildcard if (pi >= plen) return true; do { if (wildmatch(s,p,si,pi)) return true; } while (++si < slen); return false; } else { if (si >= slen || c != s[si++]) return false; } } return (si == slen); } // Category : Internal utilities <============================== // Category : Internal accessors ------------------------------> /** {@collect.stats} * Check if domain is a valid domain. Set _domain_pattern if appropriate. */ private boolean isDomain(String domain) { if (domain == null) return true; final char[] d=domain.toCharArray(); final int len = d.length; int next = 0; while (next < len) { final char c = d[next++]; switch (c) { case ':' : case '\n' : return false; case '*' : case '?' : _domain_pattern = true; break; } } return true; } // Category : Internal accessors <============================== // Category : Serialization -----------------------------------> /** {@collect.stats} * Deserializes an {@link ObjectName} from an {@link ObjectInputStream}. * @serialData <ul> * <li>In the current serial form (value of property * <code>jmx.serial.form</code> differs from * <code>1.0</code>): the string * &quot;&lt;domain&gt;:&lt;properties&gt;&lt;wild&gt;&quot;, * where: <ul> * <li>&lt;domain&gt; represents the domain part * of the {@link ObjectName}</li> * <li>&lt;properties&gt; represents the list of * properties, as returned by * {@link #getKeyPropertyListString} * <li>&lt;wild&gt; is empty if not * <code>isPropertyPattern</code>, or * is the character "<code>*</code>" if * <code>isPropertyPattern</code> * and &lt;properties&gt; is empty, or * is "<code>,*</code>" if * <code>isPropertyPattern</code> and * &lt;properties&gt; is not empty. * </li> * </ul> * The intent is that this string could be supplied * to the {@link #ObjectName(String)} constructor to * produce an equivalent {@link ObjectName}. * </li> * <li>In the old serial form (value of property * <code>jmx.serial.form</code> is * <code>1.0</code>): &lt;domain&gt; &lt;propertyList&gt; * &lt;propertyListString&gt; &lt;canonicalName&gt; * &lt;pattern&gt; &lt;propertyPattern&gt;, * where: <ul> * <li>&lt;domain&gt; represents the domain part * of the {@link ObjectName}</li> * <li>&lt;propertyList&gt; is the * {@link Hashtable} that contains all the * pairs (key,value) for this * {@link ObjectName}</li> * <li>&lt;propertyListString&gt; is the * {@link String} representation of the * list of properties in any order (not * mandatorily a canonical representation) * </li> * <li>&lt;canonicalName&gt; is the * {@link String} containing this * {@link ObjectName}'s canonical name</li> * <li>&lt;pattern&gt; is a boolean which is * <code>true</code> if this * {@link ObjectName} contains a pattern</li> * <li>&lt;propertyPattern&gt; is a boolean which * is <code>true</code> if this * {@link ObjectName} contains a pattern in * the list of properties</li> * </ul> * </li> * </ul> */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { String cn; if (compat) { // Read an object serialized in the old serial form // //in.defaultReadObject(); final ObjectInputStream.GetField fields = in.readFields(); String propListString = (String)fields.get("propertyListString", ""); // 6616825: take care of property patterns final boolean propPattern = fields.get("propertyPattern" , false); if (propPattern) { propListString = (propListString.length()==0?"*":(propListString+",*")); } cn = (String)fields.get("domain", "default")+ ":"+ propListString; } else { // Read an object serialized in the new serial form // in.defaultReadObject(); cn = (String)in.readObject(); } try { construct(cn); } catch (NullPointerException e) { throw new InvalidObjectException(e.toString()); } catch (MalformedObjectNameException e) { throw new InvalidObjectException(e.toString()); } } /** {@collect.stats} * Serializes an {@link ObjectName} to an {@link ObjectOutputStream}. * @serialData <ul> * <li>In the current serial form (value of property * <code>jmx.serial.form</code> differs from * <code>1.0</code>): the string * &quot;&lt;domain&gt;:&lt;properties&gt;&lt;wild&gt;&quot;, * where: <ul> * <li>&lt;domain&gt; represents the domain part * of the {@link ObjectName}</li> * <li>&lt;properties&gt; represents the list of * properties, as returned by * {@link #getKeyPropertyListString} * <li>&lt;wild&gt; is empty if not * <code>isPropertyPattern</code>, or * is the character "<code>*</code>" if * this <code>isPropertyPattern</code> * and &lt;properties&gt; is empty, or * is "<code>,*</code>" if * <code>isPropertyPattern</code> and * &lt;properties&gt; is not empty. * </li> * </ul> * The intent is that this string could be supplied * to the {@link #ObjectName(String)} constructor to * produce an equivalent {@link ObjectName}. * </li> * <li>In the old serial form (value of property * <code>jmx.serial.form</code> is * <code>1.0</code>): &lt;domain&gt; &lt;propertyList&gt; * &lt;propertyListString&gt; &lt;canonicalName&gt; * &lt;pattern&gt; &lt;propertyPattern&gt;, * where: <ul> * <li>&lt;domain&gt; represents the domain part * of the {@link ObjectName}</li> * <li>&lt;propertyList&gt; is the * {@link Hashtable} that contains all the * pairs (key,value) for this * {@link ObjectName}</li> * <li>&lt;propertyListString&gt; is the * {@link String} representation of the * list of properties in any order (not * mandatorily a canonical representation) * </li> * <li>&lt;canonicalName&gt; is the * {@link String} containing this * {@link ObjectName}'s canonical name</li> * <li>&lt;pattern&gt; is a boolean which is * <code>true</code> if this * {@link ObjectName} contains a pattern</li> * <li>&lt;propertyPattern&gt; is a boolean which * is <code>true</code> if this * {@link ObjectName} contains a pattern in * the list of properties</li> * </ul> * </li> * </ul> */ private void writeObject(ObjectOutputStream out) throws IOException { if (compat) { // Serializes this instance in the old serial form // Read CR 6441274 before making any changes to this code ObjectOutputStream.PutField fields = out.putFields(); fields.put("domain", _canonicalName.substring(0, _domain_length)); fields.put("propertyList", getKeyPropertyList()); fields.put("propertyListString", getKeyPropertyListString()); fields.put("canonicalName", _canonicalName); fields.put("pattern", (_domain_pattern || _property_list_pattern)); fields.put("propertyPattern", _property_list_pattern); out.writeFields(); } else { // Serializes this instance in the new serial form // out.defaultWriteObject(); out.writeObject(getSerializedNameString()); } } // Category : Serialization <=================================== // Private methods <======================================== // Public methods ----------------------------------------> // Category : ObjectName Construction ------------------------------> /** {@collect.stats} * <p>Return an instance of ObjectName that can be used anywhere * an object obtained with {@link #ObjectName(String) new * ObjectName(name)} can be used. The returned object may be of * a subclass of ObjectName. Calling this method twice with the * same parameters may return the same object or two equal but * not identical objects.</p> * * @param name A string representation of the object name. * * @return an ObjectName corresponding to the given String. * * @exception MalformedObjectNameException The string passed as a * parameter does not have the right format. * @exception NullPointerException The <code>name</code> parameter * is null. * */ public static ObjectName getInstance(String name) throws MalformedObjectNameException, NullPointerException { return new ObjectName(name); } /** {@collect.stats} * <p>Return an instance of ObjectName that can be used anywhere * an object obtained with {@link #ObjectName(String, String, * String) new ObjectName(domain, key, value)} can be used. The * returned object may be of a subclass of ObjectName. Calling * this method twice with the same parameters may return the same * object or two equal but not identical objects.</p> * * @param domain The domain part of the object name. * @param key The attribute in the key property of the object name. * @param value The value in the key property of the object name. * * @return an ObjectName corresponding to the given domain, * key, and value. * * @exception MalformedObjectNameException The * <code>domain</code>, <code>key</code>, or <code>value</code> * contains an illegal character, or <code>value</code> does not * follow the rules for quoting. * @exception NullPointerException One of the parameters is null. * */ public static ObjectName getInstance(String domain, String key, String value) throws MalformedObjectNameException, NullPointerException { return new ObjectName(domain, key, value); } /** {@collect.stats} * <p>Return an instance of ObjectName that can be used anywhere * an object obtained with {@link #ObjectName(String, Hashtable) * new ObjectName(domain, table)} can be used. The returned * object may be of a subclass of ObjectName. Calling this method * twice with the same parameters may return the same object or * two equal but not identical objects.</p> * * @param domain The domain part of the object name. * @param table A hash table containing one or more key * properties. The key of each entry in the table is the key of a * key property in the object name. The associated value in the * table is the associated value in the object name. * * @return an ObjectName corresponding to the given domain and * key mappings. * * @exception MalformedObjectNameException The <code>domain</code> * contains an illegal character, or one of the keys or values in * <code>table</code> contains an illegal character, or one of the * values in <code>table</code> does not follow the rules for * quoting. * @exception NullPointerException One of the parameters is null. * */ public static ObjectName getInstance(String domain, Hashtable<String,String> table) throws MalformedObjectNameException, NullPointerException { return new ObjectName(domain, table); } /** {@collect.stats} * <p>Return an instance of ObjectName that can be used anywhere * the given object can be used. The returned object may be of a * subclass of ObjectName. If <code>name</code> is of a subclass * of ObjectName, it is not guaranteed that the returned object * will be of the same class.</p> * * <p>The returned value may or may not be identical to * <code>name</code>. Calling this method twice with the same * parameters may return the same object or two equal but not * identical objects.</p> * * <p>Since ObjectName is immutable, it is not usually useful to * make a copy of an ObjectName. The principal use of this method * is to guard against a malicious caller who might pass an * instance of a subclass with surprising behavior to sensitive * code. Such code can call this method to obtain an ObjectName * that is known not to have surprising behavior.</p> * * @param name an instance of the ObjectName class or of a subclass * * @return an instance of ObjectName or a subclass that is known to * have the same semantics. If <code>name</code> respects the * semantics of ObjectName, then the returned object is equal * (though not necessarily identical) to <code>name</code>. * * @exception NullPointerException The <code>name</code> is null. * */ public static ObjectName getInstance(ObjectName name) throws NullPointerException { if (name.getClass().equals(ObjectName.class)) return name; try { return new ObjectName(name.getSerializedNameString()); } catch (MalformedObjectNameException e) { throw new IllegalArgumentException("Unexpected: " + e); // can't happen } } /** {@collect.stats} * Construct an object name from the given string. * * @param name A string representation of the object name. * * @exception MalformedObjectNameException The string passed as a * parameter does not have the right format. * @exception NullPointerException The <code>name</code> parameter * is null. */ public ObjectName(String name) throws MalformedObjectNameException, NullPointerException { construct(name); } /** {@collect.stats} * Construct an object name with exactly one key property. * * @param domain The domain part of the object name. * @param key The attribute in the key property of the object name. * @param value The value in the key property of the object name. * * @exception MalformedObjectNameException The * <code>domain</code>, <code>key</code>, or <code>value</code> * contains an illegal character, or <code>value</code> does not * follow the rules for quoting. * @exception NullPointerException One of the parameters is null. */ public ObjectName(String domain, String key, String value) throws MalformedObjectNameException, NullPointerException { // If key or value are null a NullPointerException // will be thrown by the put method in Hashtable. // Map<String,String> table = Collections.singletonMap(key, value); construct(domain, table); } /** {@collect.stats} * Construct an object name with several key properties from a Hashtable. * * @param domain The domain part of the object name. * @param table A hash table containing one or more key * properties. The key of each entry in the table is the key of a * key property in the object name. The associated value in the * table is the associated value in the object name. * * @exception MalformedObjectNameException The <code>domain</code> * contains an illegal character, or one of the keys or values in * <code>table</code> contains an illegal character, or one of the * values in <code>table</code> does not follow the rules for * quoting. * @exception NullPointerException One of the parameters is null. */ public ObjectName(String domain, Hashtable<String,String> table) throws MalformedObjectNameException, NullPointerException { construct(domain, table); /* The exception for when a key or value in the table is not a String is now ClassCastException rather than MalformedObjectNameException. This was not previously specified. */ } // Category : ObjectName Construction <============================== // Category : Getter methods ------------------------------> /** {@collect.stats} * Checks whether the object name is a pattern. * <p> * An object name is a pattern if its domain contains a * wildcard or if the object name is a property pattern. * * @return True if the name is a pattern, otherwise false. */ public boolean isPattern() { return (_domain_pattern || _property_list_pattern || _property_value_pattern); } /** {@collect.stats} * Checks whether the object name is a pattern on the domain part. * * @return True if the name is a domain pattern, otherwise false. * */ public boolean isDomainPattern() { return _domain_pattern; } /** {@collect.stats} * Checks whether the object name is a pattern on the key properties. * <p> * An object name is a pattern on the key properties if it is a * pattern on the key property list (e.g. "d:k=v,*") or on the * property values (e.g. "d:k=*") or on both (e.g. "d:k=*,*"). * * @return True if the name is a property pattern, otherwise false. */ public boolean isPropertyPattern() { return _property_list_pattern || _property_value_pattern; } /** {@collect.stats} * Checks whether the object name is a pattern on the key property list. * <p> * For example, "d:k=v,*" and "d:k=*,*" are key property list patterns * whereas "d:k=*" is not. * * @return True if the name is a property list pattern, otherwise false. * * @since 1.6 */ public boolean isPropertyListPattern() { return _property_list_pattern; } /** {@collect.stats} * Checks whether the object name is a pattern on the value part * of at least one of the key properties. * <p> * For example, "d:k=*" and "d:k=*,*" are property value patterns * whereas "d:k=v,*" is not. * * @return True if the name is a property value pattern, otherwise false. * * @since 1.6 */ public boolean isPropertyValuePattern() { return _property_value_pattern; } /** {@collect.stats} * Checks whether the value associated with a key in a key * property is a pattern. * * @param property The property whose value is to be checked. * * @return True if the value associated with the given key property * is a pattern, otherwise false. * * @exception NullPointerException If <code>property</code> is null. * @exception IllegalArgumentException If <code>property</code> is not * a valid key property for this ObjectName. * * @since 1.6 */ public boolean isPropertyValuePattern(String property) throws NullPointerException, IllegalArgumentException { if (property == null) throw new NullPointerException("key property can't be null"); for (int i = 0; i < _ca_array.length; i++) { Property prop = _ca_array[i]; String key = prop.getKeyString(_canonicalName); if (key.equals(property)) return (prop instanceof PatternProperty); } throw new IllegalArgumentException("key property not found"); } /** {@collect.stats} * <p>Returns the canonical form of the name; that is, a string * representation where the properties are sorted in lexical * order.</p> * * <p>More precisely, the canonical form of the name is a String * consisting of the <em>domain part</em>, a colon * (<code>:</code>), the <em>canonical key property list</em>, and * a <em>pattern indication</em>.</p> * * <p>The <em>canonical key property list</em> is the same string * as described for {@link #getCanonicalKeyPropertyListString()}.</p> * * <p>The <em>pattern indication</em> is: * <ul> * <li>empty for an ObjectName * that is not a property list pattern; * <li>an asterisk for an ObjectName * that is a property list pattern with no keys; or * <li>a comma and an * asterisk (<code>,*</code>) for an ObjectName that is a property * list pattern with at least one key. * </ul></p> * * @return The canonical form of the name. */ public String getCanonicalName() { return _canonicalName; } /** {@collect.stats} * Returns the domain part. * * @return The domain. */ public String getDomain() { return _canonicalName.substring(0, _domain_length); } /** {@collect.stats} * Obtains the value associated with a key in a key property. * * @param property The property whose value is to be obtained. * * @return The value of the property, or null if there is no such * property in this ObjectName. * * @exception NullPointerException If <code>property</code> is null. */ public String getKeyProperty(String property) throws NullPointerException { return _getKeyPropertyList().get(property); } /** {@collect.stats} * <p>Returns the key properties as a Map. The returned * value is a Map in which each key is a key in the * ObjectName's key property list and each value is the associated * value.</p> * * <p>The returned value must not be modified.</p> * * @return The table of key properties. */ private Map<String,String> _getKeyPropertyList() { synchronized (this) { if (_propertyList == null) { // build (lazy eval) the property list from the canonical // properties array _propertyList = new HashMap<String,String>(); int len = _ca_array.length; Property prop; for (int i = len - 1; i >= 0; i--) { prop = _ca_array[i]; _propertyList.put(prop.getKeyString(_canonicalName), prop.getValueString(_canonicalName)); } } } return _propertyList; } /** {@collect.stats} * <p>Returns the key properties as a Hashtable. The returned * value is a Hashtable in which each key is a key in the * ObjectName's key property list and each value is the associated * value.</p> * * <p>The returned value may be unmodifiable. If it is * modifiable, changing it has no effect on this ObjectName.</p> * * @return The table of key properties. */ // CR 6441274 depends on the modification property defined above public Hashtable<String,String> getKeyPropertyList() { return new Hashtable<String,String>(_getKeyPropertyList()); } /** {@collect.stats} * <p>Returns a string representation of the list of key * properties specified at creation time. If this ObjectName was * constructed with the constructor {@link #ObjectName(String)}, * the key properties in the returned String will be in the same * order as in the argument to the constructor.</p> * * @return The key property list string. This string is * independent of whether the ObjectName is a pattern. */ public String getKeyPropertyListString() { // BEWARE : we rebuild the propertyliststring at each call !! if (_kp_array.length == 0) return ""; // the size of the string is the canonical one minus domain // part and pattern part final int total_size = _canonicalName.length() - _domain_length - 1 - (_property_list_pattern?2:0); final char[] dest_chars = new char[total_size]; final char[] value = _canonicalName.toCharArray(); writeKeyPropertyListString(value,dest_chars,0); return new String(dest_chars); } /** {@collect.stats} * <p>Returns the serialized string of the ObjectName. * properties specified at creation time. If this ObjectName was * constructed with the constructor {@link #ObjectName(String)}, * the key properties in the returned String will be in the same * order as in the argument to the constructor.</p> * * @return The key property list string. This string is * independent of whether the ObjectName is a pattern. */ private String getSerializedNameString() { // the size of the string is the canonical one final int total_size = _canonicalName.length(); final char[] dest_chars = new char[total_size]; final char[] value = _canonicalName.toCharArray(); final int offset = _domain_length+1; // copy "domain:" into dest_chars // System.arraycopy(value, 0, dest_chars, 0, offset); // Add property list string final int end = writeKeyPropertyListString(value,dest_chars,offset); // Add ",*" if necessary if (_property_list_pattern) { if (end == offset) { // Property list string is empty. dest_chars[end] = '*'; } else { // Property list string is not empty. dest_chars[end] = ','; dest_chars[end+1] = '*'; } } return new String(dest_chars); } /** {@collect.stats} * <p>Write a string representation of the list of key * properties specified at creation time in the given array, starting * at the specified offset. If this ObjectName was * constructed with the constructor {@link #ObjectName(String)}, * the key properties in the returned String will be in the same * order as in the argument to the constructor.</p> * * @return offset + #of chars written */ private int writeKeyPropertyListString(char[] canonicalChars, char[] data, int offset) { if (_kp_array.length == 0) return offset; final char[] dest_chars = data; final char[] value = _canonicalName.toCharArray(); int index = offset; final int len = _kp_array.length; final int last = len - 1; for (int i = 0; i < len; i++) { final Property prop = _kp_array[i]; final int prop_len = prop._key_length + prop._value_length + 1; System.arraycopy(value, prop._key_index, dest_chars, index, prop_len); index += prop_len; if (i < last ) dest_chars[index++] = ','; } return index; } /** {@collect.stats} * Returns a string representation of the list of key properties, * in which the key properties are sorted in lexical order. This * is used in lexicographic comparisons performed in order to * select MBeans based on their key property list. Lexical order * is the order implied by {@link String#compareTo(String) * String.compareTo(String)}. * * @return The canonical key property list string. This string is * independent of whether the ObjectName is a pattern. */ public String getCanonicalKeyPropertyListString() { if (_ca_array.length == 0) return ""; int len = _canonicalName.length(); if (_property_list_pattern) len -= 2; return _canonicalName.substring(_domain_length +1, len); } // Category : Getter methods <=================================== // Category : Utilities ----------------------------------------> /** {@collect.stats} * <p>Returns a string representation of the object name. The * format of this string is not specified, but users can expect * that two ObjectNames return the same string if and only if they * are equal.</p> * * @return a string representation of this object name. */ public String toString() { return getSerializedNameString(); } /** {@collect.stats} * Compares the current object name with another object name. Two * ObjectName instances are equal if and only if their canonical * forms are equal. The canonical form is the string described * for {@link #getCanonicalName()}. * * @param object The object name that the current object name is to be * compared with. * * @return True if <code>object</code> is an ObjectName whose * canonical form is equal to that of this ObjectName. */ @Override public boolean equals(Object object) { // same object case if (this == object) return true; // object is not an object name case if (!(object instanceof ObjectName)) return false; // equality when canonical names are the same // (because usage of intern()) ObjectName on = (ObjectName) object; String on_string = on._canonicalName; if (_canonicalName == on_string) return true; // Because we are sharing canonical form between object names, // we have finished the comparison at this stage ==> unequal return false; } /** {@collect.stats} * Returns a hash code for this object name. * */ @Override public int hashCode() { return _canonicalName.hashCode(); } /** {@collect.stats} * <p>Returns a quoted form of the given String, suitable for * inclusion in an ObjectName. The returned value can be used as * the value associated with a key in an ObjectName. The String * <code>s</code> may contain any character. Appropriate quoting * ensures that the returned value is legal in an ObjectName.</p> * * <p>The returned value consists of a quote ('"'), a sequence of * characters corresponding to the characters of <code>s</code>, * and another quote. Characters in <code>s</code> appear * unchanged within the returned value except:</p> * * <ul> * <li>A quote ('"') is replaced by a backslash (\) followed by a quote.</li> * <li>An asterisk ('*') is replaced by a backslash (\) followed by an * asterisk.</li> * <li>A question mark ('?') is replaced by a backslash (\) followed by * a question mark.</li> * <li>A backslash ('\') is replaced by two backslashes.</li> * <li>A newline character (the character '\n' in Java) is replaced * by a backslash followed by the character '\n'.</li> * </ul> * * @param s the String to be quoted. * * @return the quoted String. * * @exception NullPointerException if <code>s</code> is null. * */ public static String quote(String s) throws NullPointerException { final StringBuilder buf = new StringBuilder("\""); final int len = s.length(); for (int i = 0; i < len; i++) { char c = s.charAt(i); switch (c) { case '\n': c = 'n'; buf.append('\\'); break; case '\\': case '\"': case '*': case '?': buf.append('\\'); break; } buf.append(c); } buf.append('"'); return buf.toString(); } /** {@collect.stats} * <p>Returns an unquoted form of the given String. If * <code>q</code> is a String returned by {@link #quote quote(s)}, * then <code>unquote(q).equals(s)</code>. If there is no String * <code>s</code> for which <code>quote(s).equals(q)</code>, then * unquote(q) throws an IllegalArgumentException.</p> * * <p>These rules imply that there is a one-to-one mapping between * quoted and unquoted forms.</p> * * @param q the String to be unquoted. * * @return the unquoted String. * * @exception IllegalArgumentException if <code>q</code> could not * have been returned by the {@link #quote} method, for instance * if it does not begin and end with a quote ("). * * @exception NullPointerException if <code>q</code> is null. * */ public static String unquote(String q) throws IllegalArgumentException, NullPointerException { final StringBuilder buf = new StringBuilder(); final int len = q.length(); if (len < 2 || q.charAt(0) != '"' || q.charAt(len - 1) != '"') throw new IllegalArgumentException("Argument not quoted"); for (int i = 1; i < len - 1; i++) { char c = q.charAt(i); if (c == '\\') { if (i == len - 2) throw new IllegalArgumentException("Trailing backslash"); c = q.charAt(++i); switch (c) { case 'n': c = '\n'; break; case '\\': case '\"': case '*': case '?': break; default: throw new IllegalArgumentException( "Bad character '" + c + "' after backslash"); } } else { switch (c) { case '*' : case '?' : case '\"': case '\n': throw new IllegalArgumentException( "Invalid unescaped character '" + c + "' in the string to unquote"); } } buf.append(c); } return buf.toString(); } /** {@collect.stats} * Defines the wildcard "*:*" ObjectName. * * @since 1.6 */ public static final ObjectName WILDCARD; static { try { WILDCARD = new ObjectName("*:*"); } catch (MalformedObjectNameException e) { throw new Error("Can't initialize wildcard name", e); } } // Category : Utilities <=================================== // Category : QueryExp Interface ----------------------------------------> /** {@collect.stats} * <p>Test whether this ObjectName, which may be a pattern, * matches another ObjectName. If <code>name</code> is a pattern, * the result is false. If this ObjectName is a pattern, the * result is true if and only if <code>name</code> matches the * pattern. If neither this ObjectName nor <code>name</code> is * a pattern, the result is true if and only if the two * ObjectNames are equal as described for the {@link * #equals(Object)} method.</p> * * @param name The name of the MBean to compare to. * * @return True if <code>name</code> matches this ObjectName. * * @exception NullPointerException if <code>name</code> is null. * */ public boolean apply(ObjectName name) throws NullPointerException { if (name == null) throw new NullPointerException(); if (name._domain_pattern || name._property_list_pattern || name._property_value_pattern) return false; // No pattern if (!_domain_pattern && !_property_list_pattern && !_property_value_pattern) return _canonicalName.equals(name._canonicalName); return matchDomains(name) && matchKeys(name); } private final boolean matchDomains(ObjectName name) { if (_domain_pattern) { // wildmatch domains final char[] dom_pattern = getDomain().toCharArray(); final char[] dom_string = name.getDomain().toCharArray(); return wildmatch(dom_string,dom_pattern,0,0); } return getDomain().equals(name.getDomain()); } private final boolean matchKeys(ObjectName name) { // If key property value pattern but not key property list // pattern, then the number of key properties must be equal // if (_property_value_pattern && !_property_list_pattern && (name._ca_array.length != _ca_array.length)) return false; // If key property value pattern or key property list pattern, // then every property inside pattern should exist in name // if (_property_value_pattern || _property_list_pattern) { final Map<String,String> nameProps = name._getKeyPropertyList(); final Property[] props = _ca_array; final String cn = _canonicalName; for (int i = props.length - 1; i >= 0 ; i--) { // Find value in given object name for key at current // index in receiver // final Property p = props[i]; final String k = p.getKeyString(cn); final String v = nameProps.get(k); // Did we find a value for this key ? // if (v == null) return false; // If this property is ok (same key, same value), go to next // if (_property_value_pattern && (p instanceof PatternProperty)) { // wildmatch key property values final char[] val_pattern = p.getValueString(cn).toCharArray(); final char[] val_string = v.toCharArray(); if (wildmatch(val_string,val_pattern,0,0)) continue; else return false; } if (v.equals(p.getValueString(cn))) continue; return false; } return true; } // If no pattern, then canonical names must be equal // final String p1 = name.getCanonicalKeyPropertyListString(); final String p2 = getCanonicalKeyPropertyListString(); return (p1.equals(p2)); } /* Method inherited from QueryExp, no implementation needed here because ObjectName is not relative to an MBeanServer and does not contain a subquery. */ public void setMBeanServer(MBeanServer mbs) { } // Category : QueryExp Interface <========================= // Category : Comparable Interface ----------------------------------------> /** {@collect.stats} * <p>Compares two ObjectName instances. The ordering relation between * ObjectNames is not completely specified but is intended to be such * that a sorted list of ObjectNames will appear in an order that is * convenient for a person to read.</p> * * <p>In particular, if the two ObjectName instances have different * domains then their order is the lexicographical order of the domains. * The ordering of the key property list remains unspecified.</p> * * <p>For example, the ObjectName instances below:</p> * <ul> * <li>Shapes:type=Square,name=3</li> * <li>Colors:type=Red,name=2</li> * <li>Shapes:type=Triangle,side=isosceles,name=2</li> * <li>Colors:type=Red,name=1</li> * <li>Shapes:type=Square,name=1</li> * <li>Colors:type=Blue,name=1</li> * <li>Shapes:type=Square,name=2</li> * <li>JMImplementation:type=MBeanServerDelegate</li> * <li>Shapes:type=Triangle,side=scalene,name=1</li> * </ul> * <p>could be ordered as follows:</p> * <ul> * <li>Colors:type=Blue,name=1</li> * <li>Colors:type=Red,name=1</li> * <li>Colors:type=Red,name=2</li> * <li>JMImplementation:type=MBeanServerDelegate</li> * <li>Shapes:type=Square,name=1</li> * <li>Shapes:type=Square,name=2</li> * <li>Shapes:type=Square,name=3</li> * <li>Shapes:type=Triangle,side=scalene,name=1</li> * <li>Shapes:type=Triangle,side=isosceles,name=2</li> * </ul> * * @param name the ObjectName to be compared. * * @return a negative integer, zero, or a positive integer as this * ObjectName is less than, equal to, or greater than the * specified ObjectName. * * @since 1.6 */ public int compareTo(ObjectName name) { // (1) Compare domains // int domainValue = this.getDomain().compareTo(name.getDomain()); if (domainValue != 0) return domainValue; // (2) Compare "type=" keys // // Within a given domain, all names with missing or empty "type=" // come before all names with non-empty type. // // When both types are missing or empty, canonical-name ordering // applies which is a total order. // String thisTypeKey = this.getKeyProperty("type"); String anotherTypeKey = name.getKeyProperty("type"); if (thisTypeKey == null) thisTypeKey = ""; if (anotherTypeKey == null) anotherTypeKey = ""; int typeKeyValue = thisTypeKey.compareTo(anotherTypeKey); if (typeKeyValue != 0) return typeKeyValue; // (3) Compare canonical names // return this.getCanonicalName().compareTo(name.getCanonicalName()); } // Category : Comparable Interface <========================= // Public methods <======================================== }
Java
/* * Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management; /** {@collect.stats} * Exceptions thrown by JMX implementations. * It does not include the runtime exceptions. * * @since 1.5 */ public class JMException extends java.lang.Exception { /* Serial version */ private static final long serialVersionUID = 350520924977331825L; /** {@collect.stats} * Default constructor. */ public JMException() { super(); } /** {@collect.stats} * Constructor that allows a specific error message to be specified. * * @param msg the detail message. */ public JMException(String msg) { super(msg); } }
Java
/* * Copyright (c) 1999, 2004, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management; // RI import import javax.management.MBeanServer; /** {@collect.stats} * Represents attributes used as arguments to relational constraints. * An <CODE>AttributeValueExp</CODE> may be used anywhere a <CODE>ValueExp</CODE> is required. * * @since 1.5 */ public class AttributeValueExp implements ValueExp { /* Serial version */ private static final long serialVersionUID = -7768025046539163385L; /** {@collect.stats} * @serial The name of the attribute */ private String attr; /** {@collect.stats} * An <code>AttributeValueExp</code> with a null attribute. * @deprecated An instance created with this constructor cannot be * used in a query. */ @Deprecated public AttributeValueExp() { } /** {@collect.stats} * Creates a new <CODE>AttributeValueExp</CODE> representing the * specified object attribute, named attr. * * @param attr the name of the attribute whose value is the value * of this {@link ValueExp}. */ public AttributeValueExp(String attr) { this.attr = attr; } /** {@collect.stats} * Returns a string representation of the name of the attribute. * * @return the attribute name. */ public String getAttributeName() { return attr; } /** {@collect.stats} * Applies the <CODE>AttributeValueExp</CODE> on an MBean. * * @param name The name of the MBean on which the <CODE>AttributeValueExp</CODE> will be applied. * * @return The <CODE>ValueExp</CODE>. * * @exception BadAttributeValueExpException * @exception InvalidApplicationException * @exception BadStringOperationException * @exception BadBinaryOpValueExpException * */ public ValueExp apply(ObjectName name) throws BadStringOperationException, BadBinaryOpValueExpException, BadAttributeValueExpException, InvalidApplicationException { Object result = getAttribute(name); if (result instanceof Number) { return new NumericValueExp((Number)result); } else if (result instanceof String) { return new StringValueExp((String)result); } else if (result instanceof Boolean) { return new BooleanValueExp((Boolean)result); } else { throw new BadAttributeValueExpException(result); } } /** {@collect.stats} * Returns the string representing its value. */ public String toString() { return attr; } /** {@collect.stats} * Sets the MBean server on which the query is to be performed. * * @param s The MBean server on which the query is to be performed. */ /* There is no need for this method, because if a query is being evaluted an AttributeValueExp can only appear inside a QueryExp, and that QueryExp will itself have done setMBeanServer. */ public void setMBeanServer(MBeanServer s) { } /** {@collect.stats} * Return the value of the given attribute in the named MBean. * If the attempt to access the attribute generates an exception, * return null. * * @param name the name of the MBean whose attribute is to be returned. * * @return the value of the attribute, or null if it could not be * obtained. */ protected Object getAttribute(ObjectName name) { try { // Get the value from the MBeanServer MBeanServer server = QueryEval.getMBeanServer(); return server.getAttribute(name, attr); } catch (Exception re) { return null; } } }
Java
/* * Copyright (c) 1999, 2006, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management; import javax.management.loading.ClassLoaderRepository; /** {@collect.stats} * <p>Keeps the list of Class Loaders registered in the MBean Server. * It provides the necessary methods to load classes using the registered * Class Loaders.</p> * * <p>This deprecated class is maintained for compatibility. In * previous versions of the JMX API, there was one * <code>DefaultLoaderRepository</code> shared by all MBean servers. * As of version 1.2 of the JMX API, that functionality is * approximated by using {@link MBeanServerFactory#findMBeanServer} to * find all known MBean servers, and consulting the {@link * ClassLoaderRepository} of each one. It is strongly recommended * that code referencing <code>DefaultLoaderRepository</code> be * rewritten.</p> * * @deprecated Use * {@link javax.management.MBeanServer#getClassLoaderRepository()} * instead. * * @since 1.5 */ @Deprecated public class DefaultLoaderRepository { /** {@collect.stats} * Go through the list of class loaders and try to load the requested class. * The method will stop as soon as the class is found. If the class * is not found the method will throw a <CODE>ClassNotFoundException</CODE> * exception. * * @param className The name of the class to be loaded. * * @return the loaded class. * * @exception ClassNotFoundException The specified class could not be found. */ public static Class loadClass(String className) throws ClassNotFoundException { return javax.management.loading.DefaultLoaderRepository.loadClass(className); } /** {@collect.stats} * Go through the list of class loaders but exclude the given class loader, then try to load * the requested class. * The method will stop as soon as the class is found. If the class * is not found the method will throw a <CODE>ClassNotFoundException</CODE> * exception. * * @param className The name of the class to be loaded. * @param loader The class loader to be excluded. * * @return the loaded class. * * @exception ClassNotFoundException The specified class could not be found. */ public static Class loadClassWithout(ClassLoader loader,String className) throws ClassNotFoundException { return javax.management.loading.DefaultLoaderRepository.loadClassWithout(loader, className); } }
Java
/* * Copyright (c) 2000, 2007, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management.openmbean; // java import // import java.util.Set; import java.lang.Comparable; // to be substituted for jdk1.1.x // jmx import // /** {@collect.stats} * <p>Describes a parameter used in one or more operations or * constructors of an open MBean.</p> * * <p>This interface declares the same methods as the class {@link * javax.management.MBeanParameterInfo}. A class implementing this * interface (typically {@link OpenMBeanParameterInfoSupport}) should * extend {@link javax.management.MBeanParameterInfo}.</p> * * * @since 1.5 */ public interface OpenMBeanParameterInfo { // Re-declares methods that are in class MBeanParameterInfo of JMX 1.0 // (these will be removed when MBeanParameterInfo is made a parent interface of this interface) /** {@collect.stats} * Returns a human readable description of the parameter * described by this <tt>OpenMBeanParameterInfo</tt> instance. * * @return the description. */ public String getDescription() ; /** {@collect.stats} * Returns the name of the parameter * described by this <tt>OpenMBeanParameterInfo</tt> instance. * * @return the name. */ public String getName() ; // Now declares methods that are specific to open MBeans // /** {@collect.stats} * Returns the <i>open type</i> of the values of the parameter * described by this <tt>OpenMBeanParameterInfo</tt> instance. * * @return the open type. */ public OpenType<?> getOpenType() ; /** {@collect.stats} * Returns the default value for this parameter, if it has one, or * <tt>null</tt> otherwise. * * @return the default value. */ public Object getDefaultValue() ; /** {@collect.stats} * Returns the set of legal values for this parameter, if it has * one, or <tt>null</tt> otherwise. * * @return the set of legal values. */ public Set<?> getLegalValues() ; /** {@collect.stats} * Returns the minimal value for this parameter, if it has one, or * <tt>null</tt> otherwise. * * @return the minimum value. */ public Comparable<?> getMinValue() ; /** {@collect.stats} * Returns the maximal value for this parameter, if it has one, or * <tt>null</tt> otherwise. * * @return the maximum value. */ public Comparable<?> getMaxValue() ; /** {@collect.stats} * Returns <tt>true</tt> if this parameter has a specified default * value, or <tt>false</tt> otherwise. * * @return true if there is a default value. */ public boolean hasDefaultValue() ; /** {@collect.stats} * Returns <tt>true</tt> if this parameter has a specified set of * legal values, or <tt>false</tt> otherwise. * * @return true if there is a set of legal values. */ public boolean hasLegalValues() ; /** {@collect.stats} * Returns <tt>true</tt> if this parameter has a specified minimal * value, or <tt>false</tt> otherwise. * * @return true if there is a minimum value. */ public boolean hasMinValue() ; /** {@collect.stats} * Returns <tt>true</tt> if this parameter has a specified maximal * value, or <tt>false</tt> otherwise. * * @return true if there is a maximum value. */ public boolean hasMaxValue() ; /** {@collect.stats} * Tests whether <var>obj</var> is a valid value for the parameter * described by this <code>OpenMBeanParameterInfo</code> instance. * * @param obj the object to be tested. * * @return <code>true</code> if <var>obj</var> is a valid value * for the parameter described by this * <code>OpenMBeanParameterInfo</code> instance, * <code>false</code> otherwise. */ public boolean isValue(Object obj) ; /** {@collect.stats} * Compares the specified <var>obj</var> parameter with this <code>OpenMBeanParameterInfo</code> instance for equality. * <p> * Returns <tt>true</tt> if and only if all of the following statements are true: * <ul> * <li><var>obj</var> is non null,</li> * <li><var>obj</var> also implements the <code>OpenMBeanParameterInfo</code> interface,</li> * <li>their names are equal</li> * <li>their open types are equal</li> * <li>their default, min, max and legal values are equal.</li> * </ul> * This ensures that this <tt>equals</tt> method works properly for <var>obj</var> parameters which are * different implementations of the <code>OpenMBeanParameterInfo</code> interface. * <br>&nbsp; * @param obj the object to be compared for equality with this <code>OpenMBeanParameterInfo</code> instance; * * @return <code>true</code> if the specified object is equal to this <code>OpenMBeanParameterInfo</code> instance. */ public boolean equals(Object obj); /** {@collect.stats} * Returns the hash code value for this <code>OpenMBeanParameterInfo</code> instance. * <p> * The hash code of an <code>OpenMBeanParameterInfo</code> instance is the sum of the hash codes * of all elements of information used in <code>equals</code> comparisons * (ie: its name, its <i>open type</i>, and its default, min, max and legal values). * <p> * This ensures that <code> t1.equals(t2) </code> implies that <code> t1.hashCode()==t2.hashCode() </code> * for any two <code>OpenMBeanParameterInfo</code> instances <code>t1</code> and <code>t2</code>, * as required by the general contract of the method * {@link Object#hashCode() Object.hashCode()}. * <p> * * @return the hash code value for this <code>OpenMBeanParameterInfo</code> instance */ public int hashCode(); /** {@collect.stats} * Returns a string representation of this <code>OpenMBeanParameterInfo</code> instance. * <p> * The string representation consists of the name of this class (ie <code>javax.management.openmbean.OpenMBeanParameterInfo</code>), * the string representation of the name and open type of the described parameter, * and the string representation of its default, min, max and legal values. * * @return a string representation of this <code>OpenMBeanParameterInfo</code> instance */ public String toString(); }
Java
/* * Copyright (c) 2000, 2007, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management.openmbean; /** {@collect.stats} * This runtime exception is thrown to indicate that the <i>open type</i> of an <i>open data</i> value * is not the one expected. * * * @since 1.5 */ public class InvalidOpenTypeException extends IllegalArgumentException { private static final long serialVersionUID = -2837312755412327534L; /** {@collect.stats} An InvalidOpenTypeException with no detail message. */ public InvalidOpenTypeException() { super(); } /** {@collect.stats} * An InvalidOpenTypeException with a detail message. * * @param msg the detail message. */ public InvalidOpenTypeException(String msg) { super(msg); } }
Java
/* * Copyright (c) 2000, 2007, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management.openmbean; // jmx import // import javax.management.JMException; /** {@collect.stats} * This checked exception is thrown when an <i>open type</i>, an <i>open data</i> or an <i>open MBean metadata info</i> instance * could not be constructed because one or more validity constraints were not met. * * * @since 1.5 */ public class OpenDataException extends JMException { private static final long serialVersionUID = 8346311255433349870L; /** {@collect.stats} * An OpenDataException with no detail message. */ public OpenDataException() { super(); } /** {@collect.stats} * An OpenDataException with a detail message. * * @param msg the detail message. */ public OpenDataException(String msg) { super(msg); } }
Java
/* * Copyright (c) 2000, 2007, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management.openmbean; import com.sun.jmx.mbeanserver.GetPropertyAction; import java.io.IOException; import java.io.InvalidObjectException; import java.io.ObjectInputStream; import java.io.Serializable; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.Arrays; import java.util.Collections; import java.util.List; import javax.management.Descriptor; import javax.management.ImmutableDescriptor; /** {@collect.stats} * The <code>OpenType</code> class is the parent abstract class of all classes which describe the actual <i>open type</i> * of open data values. * <p> * An <i>open type</i> is defined by: * <ul> * <li>the fully qualified Java class name of the open data values this type describes; * note that only a limited set of Java classes is allowed for open data values * (see {@link #ALLOWED_CLASSNAMES_LIST ALLOWED_CLASSNAMES_LIST}),</li> * <li>its name,</li> * <li>its description.</li> * </ul> * * @param <T> the Java type that instances described by this type must * have. For example, {@link SimpleType#INTEGER} is a {@code * SimpleType<Integer>} which is a subclass of {@code OpenType<Integer>}, * meaning that an attribute, parameter, or return value that is described * as a {@code SimpleType.INTEGER} must have Java type * {@link Integer}. * * @since 1.5 */ public abstract class OpenType<T> implements Serializable { /* Serial version */ static final long serialVersionUID = -9195195325186646468L; /** {@collect.stats} * List of the fully qualified names of the Java classes allowed for open * data values. A multidimensional array of any one of these classes or * their corresponding primitive types is also an allowed class for open * data values. * <pre>ALLOWED_CLASSNAMES_LIST = { "java.lang.Void", "java.lang.Boolean", "java.lang.Character", "java.lang.Byte", "java.lang.Short", "java.lang.Integer", "java.lang.Long", "java.lang.Float", "java.lang.Double", "java.lang.String", "java.math.BigDecimal", "java.math.BigInteger", "java.util.Date", "javax.management.ObjectName", CompositeData.class.getName(), TabularData.class.getName() } ; </pre> * */ public static final List<String> ALLOWED_CLASSNAMES_LIST = Collections.unmodifiableList( Arrays.asList( "java.lang.Void", "java.lang.Boolean", "java.lang.Character", "java.lang.Byte", "java.lang.Short", "java.lang.Integer", "java.lang.Long", "java.lang.Float", "java.lang.Double", "java.lang.String", "java.math.BigDecimal", "java.math.BigInteger", "java.util.Date", "javax.management.ObjectName", CompositeData.class.getName(), // better refer to these two class names like this, rather than hardcoding a string, TabularData.class.getName()) ); // in case the package of these classes should change (who knows...) /** {@collect.stats} * @deprecated Use {@link #ALLOWED_CLASSNAMES_LIST ALLOWED_CLASSNAMES_LIST} instead. */ @Deprecated public static final String[] ALLOWED_CLASSNAMES = ALLOWED_CLASSNAMES_LIST.toArray(new String[0]); /** {@collect.stats} * @serial The fully qualified Java class name of open data values this * type describes. */ private String className; /** {@collect.stats} * @serial The type description (should not be null or empty). */ private String description; /** {@collect.stats} * @serial The name given to this type (should not be null or empty). */ private String typeName; /** {@collect.stats} * Tells if this type describes an array (checked in constructor). */ private transient boolean isArray = false; /** {@collect.stats} * Cached Descriptor for this OpenType, constructed on demand. */ private transient Descriptor descriptor; /* *** Constructor *** */ /** {@collect.stats} * Constructs an <code>OpenType</code> instance (actually a subclass instance as <code>OpenType</code> is abstract), * checking for the validity of the given parameters. * The validity constraints are described below for each parameter. * <br>&nbsp; * @param className The fully qualified Java class name of the open data values this open type describes. * The valid Java class names allowed for open data values are listed in * {@link #ALLOWED_CLASSNAMES_LIST ALLOWED_CLASSNAMES_LIST}. * A multidimensional array of any one of these classes * or their corresponding primitive types is also an allowed class, * in which case the class name follows the rules defined by the method * {@link Class#getName() getName()} of <code>java.lang.Class</code>. * For example, a 3-dimensional array of Strings has for class name * &quot;<code>[[[Ljava.lang.String;</code>&quot; (without the quotes). * <br>&nbsp; * @param typeName The name given to the open type this instance represents; cannot be a null or empty string. * <br>&nbsp; * @param description The human readable description of the open type this instance represents; * cannot be a null or empty string. * <br>&nbsp; * @throws IllegalArgumentException if <var>className</var>, <var>typeName</var> or <var>description</var> * is a null or empty string * <br>&nbsp; * @throws OpenDataException if <var>className</var> is not one of the allowed Java class names for open data */ protected OpenType(String className, String typeName, String description) throws OpenDataException { checkClassNameOverride(); this.typeName = valid("typeName", typeName); this.description = valid("description", description); this.className = validClassName(className); this.isArray = (this.className != null && this.className.startsWith("[")); } /* Package-private constructor for callers we trust to get it right. */ OpenType(String className, String typeName, String description, boolean isArray) { this.className = valid("className",className); this.typeName = valid("typeName", typeName); this.description = valid("description", description); this.isArray = isArray; } private void checkClassNameOverride() throws SecurityException { if (this.getClass().getClassLoader() == null) return; // We trust bootstrap classes. if (overridesGetClassName(this.getClass())) { final GetPropertyAction getExtendOpenTypes = new GetPropertyAction("jmx.extend.open.types"); if (AccessController.doPrivileged(getExtendOpenTypes) == null) { throw new SecurityException("Cannot override getClassName() " + "unless -Djmx.extend.open.types"); } } } private static boolean overridesGetClassName(final Class<? extends OpenType> c) { return AccessController.doPrivileged(new PrivilegedAction<Boolean>() { public Boolean run() { try { return (c.getMethod("getClassName").getDeclaringClass() != OpenType.class); } catch (Exception e) { return true; // fail safe } } }); } private static String validClassName(String className) throws OpenDataException { className = valid("className", className); // Check if className describes an array class, and determines its elements' class name. // (eg: a 3-dimensional array of Strings has for class name: "[[[Ljava.lang.String;") // int n = 0; while (className.startsWith("[", n)) { n++; } String eltClassName; // class name of array elements boolean isPrimitiveArray = false; if (n > 0) { if (className.startsWith("L", n) && className.endsWith(";")) { // removes the n leading '[' + the 'L' characters // and the last ';' character eltClassName = className.substring(n+1, className.length()-1); } else if (n == className.length() - 1) { // removes the n leading '[' characters eltClassName = className.substring(n, className.length()); isPrimitiveArray = true; } else { throw new OpenDataException("Argument className=\"" + className + "\" is not a valid class name"); } } else { // not an array eltClassName = className; } // Check that eltClassName's value is one of the allowed basic data types for open data // boolean ok = false; if (isPrimitiveArray) { ok = ArrayType.isPrimitiveContentType(eltClassName); } else { ok = ALLOWED_CLASSNAMES_LIST.contains(eltClassName); } if ( ! ok ) { throw new OpenDataException("Argument className=\""+ className + "\" is not one of the allowed Java class names for open data."); } return className; } /* Return argValue.trim() provided argValue is neither null nor empty; otherwise throw IllegalArgumentException. */ private static String valid(String argName, String argValue) { if (argValue == null || (argValue = argValue.trim()).equals("")) throw new IllegalArgumentException("Argument " + argName + " cannot be null or empty"); return argValue; } /* Package-private access to a Descriptor containing this OpenType. */ synchronized Descriptor getDescriptor() { if (descriptor == null) { descriptor = new ImmutableDescriptor(new String[] {"openType"}, new Object[] {this}); } return descriptor; } /* *** Open type information methods *** */ /** {@collect.stats} * Returns the fully qualified Java class name of the open data values * this open type describes. * The only possible Java class names for open data values are listed in * {@link #ALLOWED_CLASSNAMES_LIST ALLOWED_CLASSNAMES_LIST}. * A multidimensional array of any one of these classes or their * corresponding primitive types is also an allowed class, * in which case the class name follows the rules defined by the method * {@link Class#getName() getName()} of <code>java.lang.Class</code>. * For example, a 3-dimensional array of Strings has for class name * &quot;<code>[[[Ljava.lang.String;</code>&quot; (without the quotes), * a 3-dimensional array of Integers has for class name * &quot;<code>[[[Ljava.lang.Integer;</code>&quot; (without the quotes), * and a 3-dimensional array of int has for class name * &quot;<code>[[[I</code>&quot; (without the quotes) * * @return the class name. */ public String getClassName() { return className; } // A version of getClassName() that can only be called from within this // package and that cannot be overridden. String safeGetClassName() { return className; } /** {@collect.stats} * Returns the name of this <code>OpenType</code> instance. * * @return the type name. */ public String getTypeName() { return typeName; } /** {@collect.stats} * Returns the text description of this <code>OpenType</code> instance. * * @return the description. */ public String getDescription() { return description; } /** {@collect.stats} * Returns <code>true</code> if the open data values this open * type describes are arrays, <code>false</code> otherwise. * * @return true if this is an array type. */ public boolean isArray() { return isArray; } /** {@collect.stats} * Tests whether <var>obj</var> is a value for this open type. * * @param obj the object to be tested for validity. * * @return <code>true</code> if <var>obj</var> is a value for this * open type, <code>false</code> otherwise. */ public abstract boolean isValue(Object obj) ; /** {@collect.stats} * Tests whether values of the given type can be assigned to this open type. * The default implementation of this method returns true only if the * types are equal. * * @param ot the type to be tested. * * @return true if {@code ot} is assignable to this open type. */ boolean isAssignableFrom(OpenType<?> ot) { return this.equals(ot); } /* *** Methods overriden from class Object *** */ /** {@collect.stats} * Compares the specified <code>obj</code> parameter with this * open type instance for equality. * * @param obj the object to compare to. * * @return true if this object and <code>obj</code> are equal. */ public abstract boolean equals(Object obj) ; public abstract int hashCode() ; /** {@collect.stats} * Returns a string representation of this open type instance. * * @return the string representation. */ public abstract String toString() ; /** {@collect.stats} * Deserializes an {@link OpenType} from an {@link java.io.ObjectInputStream}. */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { checkClassNameOverride(); ObjectInputStream.GetField fields = in.readFields(); final String classNameField; final String descriptionField; final String typeNameField; try { classNameField = validClassName((String) fields.get("className", null)); descriptionField = valid("description", (String) fields.get("description", null)); typeNameField = valid("typeName", (String) fields.get("typeName", null)); } catch (Exception e) { IOException e2 = new InvalidObjectException(e.getMessage()); e2.initCause(e); throw e2; } className = classNameField; description = descriptionField; typeName = typeNameField; isArray = (className.startsWith("[")); } }
Java
/* * Copyright (c) 2000, 2007, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management.openmbean; // java import // import java.io.Serializable; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; // jmx import // /** {@collect.stats} * The <tt>CompositeDataSupport</tt> class is the <i>open data</i> class which * implements the <tt>CompositeData</tt> interface. * * * @since 1.5 */ public class CompositeDataSupport implements CompositeData, Serializable { /* Serial version */ static final long serialVersionUID = 8003518976613702244L; /** {@collect.stats} * @serial Internal representation of the mapping of item names to their * respective values. * A {@link SortedMap} is used for faster retrieval of elements. */ private SortedMap<String, Object> contents = new TreeMap<String, Object>(); /** {@collect.stats} * @serial The <i>composite type </i> of this <i>composite data</i> instance. */ private CompositeType compositeType; /** {@collect.stats} * <p> * Constructs a <tt>CompositeDataSupport</tt> instance with the specified * <tt>compositeType</tt>, whose item values * are specified by <tt>itemValues[]</tt>, in the same order as in * <tt>itemNames[]</tt>. * As a <tt>CompositeType</tt> does not specify any order on its items, * the <tt>itemNames[]</tt> parameter is used * to specify the order in which the values are given in <tt>itemValues[]</tt>. * The items contained in this <tt>CompositeDataSupport</tt> instance are * internally stored in a <tt>TreeMap</tt>, * thus sorted in ascending lexicographic order of their names, for faster * retrieval of individual item values. * <p> * The constructor checks that all the constraints listed below for each * parameter are satisfied, * and throws the appropriate exception if they are not. * <p> * @param compositeType the <i>composite type </i> of this <i>composite * data</i> instance; * must not be null. * <p> * @param itemNames <tt>itemNames</tt> must list, in any order, all the * item names defined in <tt>compositeType</tt>; * the order in which the names are listed, is used to * match values in <tt>itemValues[]</tt>; * must not be null or empty. * <p> * @param itemValues the values of the items, listed in the same order as * their respective names in <tt>itemNames</tt>; * each item value can be null, but if it is non-null it must be * a valid value for the open type defined in <tt>compositeType</tt> for the corresponding item; * must be of the same size as <tt>itemNames</tt>; must not be null or empty. * <p> * @throws IllegalArgumentException <tt>compositeType</tt> is null, or <tt>itemNames[]</tt> or <tt>itemValues[]</tt> is null or empty, * or one of the elements in <tt>itemNames[]</tt> is a null or empty string, * or <tt>itemNames[]</tt> and <tt>itemValues[]</tt> are not of the same size. * <p> * @throws OpenDataException <tt>itemNames[]</tt> or <tt>itemValues[]</tt>'s size differs from * the number of items defined in <tt>compositeType</tt>, * or one of the elements in <tt>itemNames[]</tt> does not exist as an item name defined in <tt>compositeType</tt>, * or one of the elements in <tt>itemValues[]</tt> is not a valid value for the corresponding item * as defined in <tt>compositeType</tt>. * <p> */ public CompositeDataSupport(CompositeType compositeType, String[] itemNames, Object[] itemValues) throws OpenDataException { // Check compositeType is not null // if (compositeType == null) { throw new IllegalArgumentException("Argument compositeType cannot be null."); } // item names defined in compositeType: Set<String> namesSet = compositeType.keySet(); // Check the array itemNames is not null or empty (length!=0) and // that there is no null element or empty string in it // checkForNullElement(itemNames, "itemNames"); checkForEmptyString(itemNames, "itemNames"); // Check the array itemValues is not null or empty (length!=0) // (NOTE: we allow null values as array elements) // if ( (itemValues == null) || (itemValues.length == 0) ) { throw new IllegalArgumentException("Argument itemValues[] cannot be null or empty."); } // Check that the sizes of the 2 arrays itemNames and itemValues are the same // if (itemNames.length != itemValues.length) { throw new IllegalArgumentException("Array arguments itemNames[] and itemValues[] "+ "should be of same length (got "+ itemNames.length + " and "+ itemValues.length +")."); } // Check the size of the 2 arrays is equal to the number of items defined in compositeType // if (itemNames.length != namesSet.size()) { throw new OpenDataException("The size of array arguments itemNames[] and itemValues[] should be equal to the number of items defined"+ " in argument compositeType (found "+ itemNames.length +" elements in itemNames[] and itemValues[],"+ " expecting "+ namesSet.size() +" elements according to compositeType."); } // Check parameter itemNames[] contains all names defined in the compositeType of this instance // if ( ! Arrays.asList(itemNames).containsAll(namesSet) ) { throw new OpenDataException("Argument itemNames[] does not contain all names defined in the compositeType of this instance."); } // Check each element of itemValues[], if not null, is of the open type defined for the corresponding item // OpenType<?> itemType; for (int i=0; i<itemValues.length; i++) { itemType = compositeType.getType(itemNames[i]); if ( (itemValues[i] != null) && (! itemType.isValue(itemValues[i])) ) { throw new OpenDataException("Argument's element itemValues["+ i +"]=\""+ itemValues[i] +"\" is not a valid value for"+ " this item (itemName="+ itemNames[i] +",itemType="+ itemType +")."); } } // Initialize internal fields: compositeType and contents // this.compositeType = compositeType; for (int i=0; i<itemNames.length; i++) { this.contents.put(itemNames[i], itemValues[i]); } } /** {@collect.stats} * <p> * Constructs a <tt>CompositeDataSupport</tt> instance with the specified <tt>compositeType</tt>, whose item names and corresponding values * are given by the mappings in the map <tt>items</tt>. * This constructor converts the keys to a string array and the values to an object array and calls * <tt>CompositeDataSupport(javax.management.openmbean.CompositeType, java.lang.String[], java.lang.Object[])</tt>. * <p> * @param compositeType the <i>composite type </i> of this <i>composite data</i> instance; * must not be null. * <p> * @param items the mappings of all the item names to their values; * <tt>items</tt> must contain all the item names defined in <tt>compositeType</tt>; * must not be null or empty. * <p> * @throws IllegalArgumentException <tt>compositeType</tt> is null, or <tt>items</tt> is null or empty, * or one of the keys in <tt>items</tt> is a null or empty string, * or one of the values in <tt>items</tt> is null. * <p> * @throws OpenDataException <tt>items</tt>' size differs from the number of items defined in <tt>compositeType</tt>, * or one of the keys in <tt>items</tt> does not exist as an item name defined in <tt>compositeType</tt>, * or one of the values in <tt>items</tt> is not a valid value for the corresponding item * as defined in <tt>compositeType</tt>. * <p> * @throws ArrayStoreException one or more keys in <tt>items</tt> is not of the class <tt>java.lang.String</tt>. * <p> */ public CompositeDataSupport(CompositeType compositeType, Map<String,?> items) throws OpenDataException { // Let the other constructor do the job, as the call to another constructor must be the first call // this( compositeType, (items==null ? null : items.keySet().toArray(new String[items.size()])), // may raise an ArrayStoreException (items==null ? null : items.values().toArray()) ); } /** {@collect.stats} * */ private static void checkForNullElement(Object[] arg, String argName) { if ( (arg == null) || (arg.length == 0) ) { throw new IllegalArgumentException( "Argument "+ argName +"[] cannot be null or empty."); } for (int i=0; i<arg.length; i++) { if (arg[i] == null) { throw new IllegalArgumentException( "Argument's element "+ argName +"["+ i +"] cannot be null."); } } } /** {@collect.stats} * */ private static void checkForEmptyString(String[] arg, String argName) { for (int i=0; i<arg.length; i++) { if (arg[i].trim().equals("")) { throw new IllegalArgumentException( "Argument's element "+ argName +"["+ i +"] cannot be an empty string."); } } } /** {@collect.stats} * Returns the <i>composite type </i> of this <i>composite data</i> instance. */ public CompositeType getCompositeType() { return compositeType; } /** {@collect.stats} * Returns the value of the item whose name is <tt>key</tt>. * * @throws IllegalArgumentException if <tt>key</tt> is a null or empty String. * * @throws InvalidKeyException if <tt>key</tt> is not an existing item name for * this <tt>CompositeData</tt> instance. */ public Object get(String key) { if ( (key == null) || (key.trim().equals("")) ) { throw new IllegalArgumentException("Argument key cannot be a null or empty String."); } if ( ! contents.containsKey(key.trim())) { throw new InvalidKeyException("Argument key=\""+ key.trim() +"\" is not an existing item name for this CompositeData instance."); } return contents.get(key.trim()); } /** {@collect.stats} * Returns an array of the values of the items whose names are specified by * <tt>keys</tt>, in the same order as <tt>keys</tt>. * * @throws IllegalArgumentException if an element in <tt>keys</tt> is a null * or empty String. * * @throws InvalidKeyException if an element in <tt>keys</tt> is not an existing * item name for this <tt>CompositeData</tt> instance. */ public Object[] getAll(String[] keys) { if ( (keys == null) || (keys.length == 0) ) { return new Object[0]; } Object[] results = new Object[keys.length]; for (int i=0; i<keys.length; i++) { results[i] = this.get(keys[i]); } return results; } /** {@collect.stats} * Returns <tt>true</tt> if and only if this <tt>CompositeData</tt> instance contains * an item whose name is <tt>key</tt>. * If <tt>key</tt> is a null or empty String, this method simply returns false. */ public boolean containsKey(String key) { if ( (key == null) || (key.trim().equals("")) ) { return false; } return contents.containsKey(key); } /** {@collect.stats} * Returns <tt>true</tt> if and only if this <tt>CompositeData</tt> instance * contains an item * whose value is <tt>value</tt>. */ public boolean containsValue(Object value) { return contents.containsValue(value); } /** {@collect.stats} * Returns an unmodifiable Collection view of the item values contained in this * <tt>CompositeData</tt> instance. * The returned collection's iterator will return the values in the ascending * lexicographic order of the corresponding * item names. */ public Collection<?> values() { return Collections.unmodifiableCollection(contents.values()); } /** {@collect.stats} * Compares the specified <var>obj</var> parameter with this * <code>CompositeDataSupport</code> instance for equality. * <p> * Returns <tt>true</tt> if and only if all of the following statements are true: * <ul> * <li><var>obj</var> is non null,</li> * <li><var>obj</var> also implements the <code>CompositeData</code> interface,</li> * <li>their composite types are equal</li> * <li>their contents, i.e. (name, value) pairs are equal. If a value contained in * the content is an array, the value comparison is done as if by calling * the {@link java.util.Arrays#deepEquals(Object[], Object[]) deepEquals} method * for arrays of object reference types or the appropriate overloading of * {@code Arrays.equals(e1,e2)} for arrays of primitive types</li> * </ul> * <p> * This ensures that this <tt>equals</tt> method works properly for * <var>obj</var> parameters which are different implementations of the * <code>CompositeData</code> interface, with the restrictions mentioned in the * {@link java.util.Collection#equals(Object) equals} * method of the <tt>java.util.Collection</tt> interface. * * @param obj the object to be compared for equality with this * <code>CompositeDataSupport</code> instance. * @return <code>true</code> if the specified object is equal to this * <code>CompositeDataSupport</code> instance. */ public boolean equals(Object obj) { if (this == obj) { return true; } // if obj is not a CompositeData, return false if (!(obj instanceof CompositeData)) { return false; } CompositeData other = (CompositeData) obj; // their compositeType should be equal if (!this.getCompositeType().equals(other.getCompositeType()) ) { return false; } if (contents.size() != other.values().size()) { return false; } for (Map.Entry<String,Object> entry : contents.entrySet()) { Object e1 = entry.getValue(); Object e2 = other.get(entry.getKey()); if (e1 == e2) continue; if (e1 == null) return false; boolean eq = e1.getClass().isArray() ? Arrays.deepEquals(new Object[] {e1}, new Object[] {e2}) : e1.equals(e2); if (!eq) return false; } // All tests for equality were successful // return true; } /** {@collect.stats} * Returns the hash code value for this <code>CompositeDataSupport</code> instance. * <p> * The hash code of a <code>CompositeDataSupport</code> instance is the sum of the hash codes * of all elements of information used in <code>equals</code> comparisons * (ie: its <i>composite type</i> and all the item values). * <p> * This ensures that <code> t1.equals(t2) </code> implies that <code> t1.hashCode()==t2.hashCode() </code> * for any two <code>CompositeDataSupport</code> instances <code>t1</code> and <code>t2</code>, * as required by the general contract of the method * {@link Object#hashCode() Object.hashCode()}. * <p> * Each item value's hash code is added to the returned hash code. * If an item value is an array, * its hash code is obtained as if by calling the * {@link java.util.Arrays#deepHashCode(Object[]) deepHashCode} method * for arrays of object reference types or the appropriate overloading * of {@code Arrays.hashCode(e)} for arrays of primitive types. * * @return the hash code value for this <code>CompositeDataSupport</code> instance */ public int hashCode() { int hashcode = compositeType.hashCode(); for (Object o : contents.values()) { if (o instanceof Object[]) hashcode += Arrays.deepHashCode((Object[]) o); else if (o instanceof byte[]) hashcode += Arrays.hashCode((byte[]) o); else if (o instanceof short[]) hashcode += Arrays.hashCode((short[]) o); else if (o instanceof int[]) hashcode += Arrays.hashCode((int[]) o); else if (o instanceof long[]) hashcode += Arrays.hashCode((long[]) o); else if (o instanceof char[]) hashcode += Arrays.hashCode((char[]) o); else if (o instanceof float[]) hashcode += Arrays.hashCode((float[]) o); else if (o instanceof double[]) hashcode += Arrays.hashCode((double[]) o); else if (o instanceof boolean[]) hashcode += Arrays.hashCode((boolean[]) o); else if (o != null) hashcode += o.hashCode(); } return hashcode; } /** {@collect.stats} * Returns a string representation of this <code>CompositeDataSupport</code> instance. * <p> * The string representation consists of the name of this class (ie <code>javax.management.openmbean.CompositeDataSupport</code>), * the string representation of the composite type of this instance, and the string representation of the contents * (ie list the itemName=itemValue mappings). * * @return a string representation of this <code>CompositeDataSupport</code> instance */ public String toString() { return new StringBuilder() .append(this.getClass().getName()) .append("(compositeType=") .append(compositeType.toString()) .append(",contents=") .append(contents.toString()) .append(")") .toString(); } }
Java
/* * Copyright (c) 2000, 2007, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management.openmbean; // java import // import java.util.Set; import java.util.TreeMap; import java.util.Collections; import java.util.Iterator; // jmx import // /** {@collect.stats} * The <code>CompositeType</code> class is the <i>open type</i> class * whose instances describe the types of {@link CompositeData <code>CompositeData</code>} values. * * * @since 1.5 */ public class CompositeType extends OpenType<CompositeData> { /* Serial version */ static final long serialVersionUID = -5366242454346948798L; /** {@collect.stats} * @serial Sorted mapping of the item names to their descriptions */ private TreeMap<String,String> nameToDescription; /** {@collect.stats} * @serial Sorted mapping of the item names to their open types */ private TreeMap<String,OpenType<?>> nameToType; /* As this instance is immutable, following three values need only * be calculated once. */ private transient Integer myHashCode = null; private transient String myToString = null; private transient Set<String> myNamesSet = null; /* *** Constructor *** */ /** {@collect.stats} * Constructs a <code>CompositeType</code> instance, checking for the validity of the given parameters. * The validity constraints are described below for each parameter. * <p> * Note that the contents of the three array parameters * <var>itemNames</var>, <var>itemDescriptions</var> and <var>itemTypes</var> * are internally copied so that any subsequent modification of these arrays by the caller of this constructor * has no impact on the constructed <code>CompositeType</code> instance. * <p> * The Java class name of composite data values this composite type represents * (ie the class name returned by the {@link OpenType#getClassName() getClassName} method) * is set to the string value returned by <code>CompositeData.class.getName()</code>. * <p> * @param typeName The name given to the composite type this instance represents; cannot be a null or empty string. * <br>&nbsp; * @param description The human readable description of the composite type this instance represents; * cannot be a null or empty string. * <br>&nbsp; * @param itemNames The names of the items contained in the * composite data values described by this <code>CompositeType</code> instance; * cannot be null and should contain at least one element; no element can be a null or empty string. * Note that the order in which the item names are given is not important to differentiate a * <code>CompositeType</code> instance from another; * the item names are internally stored sorted in ascending alphanumeric order. * <br>&nbsp; * @param itemDescriptions The descriptions, in the same order as <var>itemNames</var>, of the items contained in the * composite data values described by this <code>CompositeType</code> instance; * should be of the same size as <var>itemNames</var>; * no element can be a null or empty string. * <br>&nbsp; * @param itemTypes The open type instances, in the same order as <var>itemNames</var>, describing the items contained * in the composite data values described by this <code>CompositeType</code> instance; * should be of the same size as <var>itemNames</var>; * no element can be null. * <br>&nbsp; * @throws IllegalArgumentException If <var>typeName</var> or <var>description</var> is a null or empty string, * or <var>itemNames</var> or <var>itemDescriptions</var> or <var>itemTypes</var> is null, * or any element of <var>itemNames</var> or <var>itemDescriptions</var> * is a null or empty string, * or any element of <var>itemTypes</var> is null, * or <var>itemNames</var> or <var>itemDescriptions</var> or <var>itemTypes</var> * are not of the same size. * <br>&nbsp; * @throws OpenDataException If <var>itemNames</var> contains duplicate item names * (case sensitive, but leading and trailing whitespaces removed). */ public CompositeType(String typeName, String description, String[] itemNames, String[] itemDescriptions, OpenType<?>[] itemTypes) throws OpenDataException { // Check and construct state defined by parent // super(CompositeData.class.getName(), typeName, description, false); // Check the 3 arrays are not null or empty (ie length==0) and that there is no null element or empty string in them // checkForNullElement(itemNames, "itemNames"); checkForNullElement(itemDescriptions, "itemDescriptions"); checkForNullElement(itemTypes, "itemTypes"); checkForEmptyString(itemNames, "itemNames"); checkForEmptyString(itemDescriptions, "itemDescriptions"); // Check the sizes of the 3 arrays are the same // if ( (itemNames.length != itemDescriptions.length) || (itemNames.length != itemTypes.length) ) { throw new IllegalArgumentException("Array arguments itemNames[], itemDescriptions[] and itemTypes[] "+ "should be of same length (got "+ itemNames.length +", "+ itemDescriptions.length +" and "+ itemTypes.length +")."); } // Initialize internal "names to descriptions" and "names to types" sorted maps, // and, by doing so, check there are no duplicate item names // nameToDescription = new TreeMap<String,String>(); nameToType = new TreeMap<String,OpenType<?>>(); String key; for (int i=0; i<itemNames.length; i++) { key = itemNames[i].trim(); if (nameToDescription.containsKey(key)) { throw new OpenDataException("Argument's element itemNames["+ i +"]=\""+ itemNames[i] + "\" duplicates a previous item names."); } nameToDescription.put(key, itemDescriptions[i].trim()); nameToType.put(key, itemTypes[i]); } } private static void checkForNullElement(Object[] arg, String argName) { if ( (arg == null) || (arg.length == 0) ) { throw new IllegalArgumentException("Argument "+ argName +"[] cannot be null or empty."); } for (int i=0; i<arg.length; i++) { if (arg[i] == null) { throw new IllegalArgumentException("Argument's element "+ argName +"["+ i +"] cannot be null."); } } } private static void checkForEmptyString(String[] arg, String argName) { for (int i=0; i<arg.length; i++) { if (arg[i].trim().equals("")) { throw new IllegalArgumentException("Argument's element "+ argName +"["+ i +"] cannot be an empty string."); } } } /* *** Composite type specific information methods *** */ /** {@collect.stats} * Returns <code>true</code> if this <code>CompositeType</code> instance defines an item * whose name is <var>itemName</var>. * * @param itemName the name of the item. * * @return true if an item of this name is present. */ public boolean containsKey(String itemName) { if (itemName == null) { return false; } return nameToDescription.containsKey(itemName); } /** {@collect.stats} * Returns the description of the item whose name is <var>itemName</var>, * or <code>null</code> if this <code>CompositeType</code> instance does not define any item * whose name is <var>itemName</var>. * * @param itemName the name of the item. * * @return the description. */ public String getDescription(String itemName) { if (itemName == null) { return null; } return nameToDescription.get(itemName); } /** {@collect.stats} * Returns the <i>open type</i> of the item whose name is <var>itemName</var>, * or <code>null</code> if this <code>CompositeType</code> instance does not define any item * whose name is <var>itemName</var>. * * @param itemName the name of the time. * * @return the type. */ public OpenType<?> getType(String itemName) { if (itemName == null) { return null; } return (OpenType<?>) nameToType.get(itemName); } /** {@collect.stats} * Returns an unmodifiable Set view of all the item names defined by this <code>CompositeType</code> instance. * The set's iterator will return the item names in ascending order. * * @return a {@link Set} of {@link String}. */ public Set<String> keySet() { // Initializes myNamesSet on first call if (myNamesSet == null) { myNamesSet = Collections.unmodifiableSet(nameToDescription.keySet()); } return myNamesSet; // always return the same value } /** {@collect.stats} * Tests whether <var>obj</var> is a value which could be * described by this <code>CompositeType</code> instance. * * <p>If <var>obj</var> is null or is not an instance of * <code>javax.management.openmbean.CompositeData</code>, * <code>isValue</code> returns <code>false</code>.</p> * * <p>If <var>obj</var> is an instance of * <code>javax.management.openmbean.CompositeData</code>, then let * {@code ct} be its {@code CompositeType} as returned by {@link * CompositeData#getCompositeType()}. The result is true if * {@code this} is <em>assignable from</em> {@code ct}. This * means that:</p> * * <ul> * <li>{@link #getTypeName() this.getTypeName()} equals * {@code ct.getTypeName()}, and * <li>there are no item names present in {@code this} that are * not also present in {@code ct}, and * <li>for every item in {@code this}, its type is assignable from * the type of the corresponding item in {@code ct}. * </ul> * * <p>A {@code TabularType} is assignable from another {@code * TabularType} if they have the same {@linkplain * TabularType#getTypeName() typeName} and {@linkplain * TabularType#getIndexNames() index name list}, and the * {@linkplain TabularType#getRowType() row type} of the first is * assignable from the row type of the second. * * <p>An {@code ArrayType} is assignable from another {@code * ArrayType} if they have the same {@linkplain * ArrayType#getDimension() dimension}; and both are {@linkplain * ArrayType#isPrimitiveArray() primitive arrays} or neither is; * and the {@linkplain ArrayType#getElementOpenType() element * type} of the first is assignable from the element type of the * second. * * <p>In every other case, an {@code OpenType} is assignable from * another {@code OpenType} only if they are equal.</p> * * <p>These rules mean that extra items can be added to a {@code * CompositeData} without making it invalid for a {@code CompositeType} * that does not have those items.</p> * * @param obj the value whose open type is to be tested for compatibility * with this <code>CompositeType</code> instance. * * @return <code>true</code> if <var>obj</var> is a value for this * composite type, <code>false</code> otherwise. */ public boolean isValue(Object obj) { // if obj is null or not CompositeData, return false // if (!(obj instanceof CompositeData)) { return false; } // if obj is not a CompositeData, return false // CompositeData value = (CompositeData) obj; // test value's CompositeType is assignable to this CompositeType instance // CompositeType valueType = value.getCompositeType(); return this.isAssignableFrom(valueType); } /** {@collect.stats} * Tests whether values of the given type can be assigned to this * open type. The result is true if the given type is also a * CompositeType with the same name ({@link #getTypeName()}), and * every item in this type is also present in the given type with * the same name and assignable type. There can be additional * items in the given type, which are ignored. * * @param ot the type to be tested. * * @return true if {@code ot} is assignable to this open type. */ @Override boolean isAssignableFrom(OpenType ot) { if (!(ot instanceof CompositeType)) return false; CompositeType ct = (CompositeType) ot; if (!ct.getTypeName().equals(getTypeName())) return false; for (String key : keySet()) { OpenType<?> otItemType = ct.getType(key); OpenType<?> thisItemType = getType(key); if (otItemType == null || !thisItemType.isAssignableFrom(otItemType)) return false; } return true; } /* *** Methods overriden from class Object *** */ /** {@collect.stats} * Compares the specified <code>obj</code> parameter with this <code>CompositeType</code> instance for equality. * <p> * Two <code>CompositeType</code> instances are equal if and only if all of the following statements are true: * <ul> * <li>their type names are equal</li> * <li>their items' names and types are equal</li> * </ul> * <br>&nbsp; * @param obj the object to be compared for equality with this <code>CompositeType</code> instance; * if <var>obj</var> is <code>null</code>, <code>equals</code> returns <code>false</code>. * * @return <code>true</code> if the specified object is equal to this <code>CompositeType</code> instance. */ public boolean equals(Object obj) { // if obj is null, return false // if (obj == null) { return false; } // if obj is not a CompositeType, return false // CompositeType other; try { other = (CompositeType) obj; } catch (ClassCastException e) { return false; } // Now, really test for equality between this CompositeType instance and the other // // their names should be equal if ( ! this.getTypeName().equals(other.getTypeName()) ) { return false; } // their items names and types should be equal if ( ! this.nameToType.equals(other.nameToType) ) { return false; } // All tests for equality were successfull // return true; } /** {@collect.stats} * Returns the hash code value for this <code>CompositeType</code> instance. * <p> * The hash code of a <code>CompositeType</code> instance is the sum of the hash codes * of all elements of information used in <code>equals</code> comparisons * (ie: name, items names, items types). * This ensures that <code> t1.equals(t2) </code> implies that <code> t1.hashCode()==t2.hashCode() </code> * for any two <code>CompositeType</code> instances <code>t1</code> and <code>t2</code>, * as required by the general contract of the method * {@link Object#hashCode() Object.hashCode()}. * <p> * As <code>CompositeType</code> instances are immutable, the hash code for this instance is calculated once, * on the first call to <code>hashCode</code>, and then the same value is returned for subsequent calls. * * @return the hash code value for this <code>CompositeType</code> instance */ public int hashCode() { // Calculate the hash code value if it has not yet been done (ie 1st call to hashCode()) // if (myHashCode == null) { int value = 0; value += this.getTypeName().hashCode(); String key; for (Iterator k = nameToDescription.keySet().iterator(); k.hasNext(); ) { key = (String) k.next(); value += key.hashCode(); value += this.nameToType.get(key).hashCode(); } myHashCode = new Integer(value); } // return always the same hash code for this instance (immutable) // return myHashCode.intValue(); } /** {@collect.stats} * Returns a string representation of this <code>CompositeType</code> instance. * <p> * The string representation consists of * the name of this class (ie <code>javax.management.openmbean.CompositeType</code>), the type name for this instance, * and the list of the items names and types string representation of this instance. * <p> * As <code>CompositeType</code> instances are immutable, the string representation for this instance is calculated once, * on the first call to <code>toString</code>, and then the same value is returned for subsequent calls. * * @return a string representation of this <code>CompositeType</code> instance */ public String toString() { // Calculate the string representation if it has not yet been done (ie 1st call to toString()) // if (myToString == null) { final StringBuilder result = new StringBuilder(); result.append(this.getClass().getName()); result.append("(name="); result.append(getTypeName()); result.append(",items=("); int i=0; Iterator k=nameToType.keySet().iterator(); String key; while (k.hasNext()) { key = (String) k.next(); if (i > 0) result.append(","); result.append("(itemName="); result.append(key); result.append(",itemType="); result.append(nameToType.get(key).toString() +")"); i++; } result.append("))"); myToString = result.toString(); } // return always the same string representation for this instance (immutable) // return myToString; } }
Java
/* * Copyright (c) 2000, 2007, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management.openmbean; import java.io.ObjectStreamException; import java.lang.reflect.Array; /** {@collect.stats} * The <code>ArrayType</code> class is the <i>open type</i> class whose instances describe * all <i>open data</i> values which are n-dimensional arrays of <i>open data</i> values. * <p> * Examples of valid {@code ArrayType} instances are: * <pre> * // 2-dimension array of java.lang.String * ArrayType<String[][]> a1 = new ArrayType<String[][]>(2, SimpleType.STRING); * * // 1-dimension array of int * ArrayType<int[]> a2 = new ArrayType<int[]>(SimpleType.INTEGER, true); * * // 1-dimension array of java.lang.Integer * ArrayType<Integer[]> a3 = new ArrayType<Integer[]>(SimpleType.INTEGER, false); * * // 4-dimension array of int * ArrayType<int[][][][]> a4 = new ArrayType<int[][][][]>(3, a2); * * // 4-dimension array of java.lang.Integer * ArrayType<Integer[][][][]> a5 = new ArrayType<Integer[][][][]>(3, a3); * * // 1-dimension array of java.lang.String * ArrayType<String[]> a6 = new ArrayType<String[]>(SimpleType.STRING, false); * * // 1-dimension array of long * ArrayType<long[]> a7 = new ArrayType<long[]>(SimpleType.LONG, true); * * // 1-dimension array of java.lang.Integer * ArrayType<Integer[]> a8 = ArrayType.getArrayType(SimpleType.INTEGER); * * // 2-dimension array of java.lang.Integer * ArrayType<Integer[][]> a9 = ArrayType.getArrayType(a8); * * // 2-dimension array of int * ArrayType<int[][]> a10 = ArrayType.getPrimitiveArrayType(int[][].class); * * // 3-dimension array of int * ArrayType<int[][][]> a11 = ArrayType.getArrayType(a10); * * // 1-dimension array of float * ArrayType<float[]> a12 = ArrayType.getPrimitiveArrayType(float[].class); * * // 2-dimension array of float * ArrayType<float[][]> a13 = ArrayType.getArrayType(a12); * * // 1-dimension array of javax.management.ObjectName * ArrayType<ObjectName[]> a14 = ArrayType.getArrayType(SimpleType.OBJECTNAME); * * // 2-dimension array of javax.management.ObjectName * ArrayType<ObjectName[][]> a15 = ArrayType.getArrayType(a14); * * // 3-dimension array of java.lang.String * ArrayType<String[][][]> a16 = new ArrayType<String[][][]>(3, SimpleType.STRING); * * // 1-dimension array of java.lang.String * ArrayType<String[]> a17 = new ArrayType<String[]>(1, SimpleType.STRING); * * // 2-dimension array of java.lang.String * ArrayType<String[][]> a18 = new ArrayType<String[][]>(1, a17); * * // 3-dimension array of java.lang.String * ArrayType<String[][][]> a19 = new ArrayType<String[][][]>(1, a18); * </pre> * * * @since 1.5 */ /* Generification note: we could have defined a type parameter that is the element type, with class ArrayType<E> extends OpenType<E[]>. However, that doesn't buy us all that much. We can't say public OpenType<E> getElementOpenType() because this ArrayType could be a multi-dimensional array. For example, if we had ArrayType(2, SimpleType.INTEGER) then E would have to be Integer[], while getElementOpenType() would return SimpleType.INTEGER, which is an OpenType<Integer>. Furthermore, we would like to support int[] (as well as Integer[]) as an Open Type (RFE 5045358). We would want this to be an OpenType<int[]> which can't be expressed as <E[]> because E can't be a primitive type like int. */ public class ArrayType<T> extends OpenType<T> { /* Serial version */ static final long serialVersionUID = 720504429830309770L; /** {@collect.stats} * @serial The dimension of arrays described by this {@link ArrayType} * instance. */ private int dimension; /** {@collect.stats} * @serial The <i>open type</i> of element values contained in the arrays * described by this {@link ArrayType} instance. */ private OpenType<?> elementType; /** {@collect.stats} * @serial This flag indicates whether this {@link ArrayType} * describes a primitive array. * * @since 1.6 */ private boolean primitiveArray; private transient Integer myHashCode = null; // As this instance is immutable, these two values private transient String myToString = null; // need only be calculated once. // indexes refering to columns in the PRIMITIVE_ARRAY_TYPES table. private static final int PRIMITIVE_WRAPPER_NAME_INDEX = 0; private static final int PRIMITIVE_TYPE_NAME_INDEX = 1; private static final int PRIMITIVE_TYPE_KEY_INDEX = 2; private static final int PRIMITIVE_OPEN_TYPE_INDEX = 3; private static final Object[][] PRIMITIVE_ARRAY_TYPES = { { Boolean.class.getName(), boolean.class.getName(), "Z", SimpleType.BOOLEAN }, { Character.class.getName(), char.class.getName(), "C", SimpleType.CHARACTER }, { Byte.class.getName(), byte.class.getName(), "B", SimpleType.BYTE }, { Short.class.getName(), short.class.getName(), "S", SimpleType.SHORT }, { Integer.class.getName(), int.class.getName(), "I", SimpleType.INTEGER }, { Long.class.getName(), long.class.getName(), "J", SimpleType.LONG }, { Float.class.getName(), float.class.getName(), "F", SimpleType.FLOAT }, { Double.class.getName(), double.class.getName(), "D", SimpleType.DOUBLE } }; static boolean isPrimitiveContentType(final String primitiveKey) { for (Object[] typeDescr : PRIMITIVE_ARRAY_TYPES) { if (typeDescr[PRIMITIVE_TYPE_KEY_INDEX].equals(primitiveKey)) { return true; } } return false; } /** {@collect.stats} * Return the key used to identify the element type in * arrays - e.g. "Z" for boolean, "C" for char etc... * @param elementClassName the wrapper class name of the array * element ("Boolean", "Character", etc...) * @return the key corresponding to the given type ("Z", "C", etc...) * return null if the given elementClassName is not a primitive * wrapper class name. **/ static String getPrimitiveTypeKey(String elementClassName) { for (Object[] typeDescr : PRIMITIVE_ARRAY_TYPES) { if (elementClassName.equals(typeDescr[PRIMITIVE_WRAPPER_NAME_INDEX])) return (String)typeDescr[PRIMITIVE_TYPE_KEY_INDEX]; } return null; } /** {@collect.stats} * Return the primitive type name corresponding to the given wrapper class. * e.g. "boolean" for "Boolean", "char" for "Character" etc... * @param elementClassName the type of the array element ("Boolean", * "Character", etc...) * @return the primitive type name corresponding to the given wrapper class * ("boolean", "char", etc...) * return null if the given elementClassName is not a primitive * wrapper type name. **/ static String getPrimitiveTypeName(String elementClassName) { for (Object[] typeDescr : PRIMITIVE_ARRAY_TYPES) { if (elementClassName.equals(typeDescr[PRIMITIVE_WRAPPER_NAME_INDEX])) return (String)typeDescr[PRIMITIVE_TYPE_NAME_INDEX]; } return null; } /** {@collect.stats} * Return the primitive open type corresponding to the given primitive type. * e.g. SimpleType.BOOLEAN for "boolean", SimpleType.CHARACTER for * "char", etc... * @param primitiveTypeName the primitive type of the array element ("boolean", * "char", etc...) * @return the OpenType corresponding to the given primitive type name * (SimpleType.BOOLEAN, SimpleType.CHARACTER, etc...) * return null if the given elementClassName is not a primitive * type name. **/ static SimpleType<?> getPrimitiveOpenType(String primitiveTypeName) { for (Object[] typeDescr : PRIMITIVE_ARRAY_TYPES) { if (primitiveTypeName.equals(typeDescr[PRIMITIVE_TYPE_NAME_INDEX])) return (SimpleType<?>)typeDescr[PRIMITIVE_OPEN_TYPE_INDEX]; } return null; } /* *** Constructor *** */ /** {@collect.stats} * Constructs an <tt>ArrayType</tt> instance describing <i>open data</i> values which are * arrays with dimension <var>dimension</var> of elements whose <i>open type</i> is <var>elementType</var>. * <p> * When invoked on an <tt>ArrayType</tt> instance, the {@link OpenType#getClassName() getClassName} method * returns the class name of the array instances it describes (following the rules defined by the * {@link Class#getName() getName} method of <code>java.lang.Class</code>), not the class name of the array elements * (which is returned by a call to <tt>getElementOpenType().getClassName()</tt>). * <p> * The internal field corresponding to the type name of this <code>ArrayType</code> instance is also set to * the class name of the array instances it describes. * In other words, the methods <code>getClassName</code> and <code>getTypeName</code> return the same string value. * The internal field corresponding to the description of this <code>ArrayType</code> instance is set to a string value * which follows the following template: * <ul> * <li>if non-primitive array: <tt><i>&lt;dimension&gt;</i>-dimension array of <i>&lt;element_class_name&gt;</i></tt></li> * <li>if primitive array: <tt><i>&lt;dimension&gt;</i>-dimension array of <i>&lt;primitive_type_of_the_element_class_name&gt;</i></tt></li> * </ul> * <p> * As an example, the following piece of code: * <pre> * ArrayType<String[][][]> t = new ArrayType<String[][][]>(3, SimpleType.STRING); * System.out.println("array class name = " + t.getClassName()); * System.out.println("element class name = " + t.getElementOpenType().getClassName()); * System.out.println("array type name = " + t.getTypeName()); * System.out.println("array type description = " + t.getDescription()); * </pre> * would produce the following output: * <pre> * array class name = [[[Ljava.lang.String; * element class name = java.lang.String * array type name = [[[Ljava.lang.String; * array type description = 3-dimension array of java.lang.String * </pre> * And the following piece of code which is equivalent to the one listed * above would also produce the same output: * <pre> * ArrayType<String[]> t1 = new ArrayType<String[]>(1, SimpleType.STRING); * ArrayType<String[][]> t2 = new ArrayType<String[][]>(1, t1); * ArrayType<String[][][]> t3 = new ArrayType<String[][][]>(1, t2); * System.out.println("array class name = " + t3.getClassName()); * System.out.println("element class name = " + t3.getElementOpenType().getClassName()); * System.out.println("array type name = " + t3.getTypeName()); * System.out.println("array type description = " + t3.getDescription()); * </pre> * * @param dimension the dimension of arrays described by this <tt>ArrayType</tt> instance; * must be greater than or equal to 1. * * @param elementType the <i>open type</i> of element values contained * in the arrays described by this <tt>ArrayType</tt> * instance; must be an instance of either * <tt>SimpleType</tt>, <tt>CompositeType</tt>, * <tt>TabularType</tt> or another <tt>ArrayType</tt> * with a <tt>SimpleType</tt>, <tt>CompositeType</tt> * or <tt>TabularType</tt> as its <tt>elementType</tt>. * * @throws IllegalArgumentException if {@code dimension} is not a positive * integer. * @throws OpenDataException if <var>elementType's className</var> is not * one of the allowed Java class names for open * data. */ public ArrayType(int dimension, OpenType<?> elementType) throws OpenDataException { // Check and construct state defined by parent. // We can't use the package-private OpenType constructor because // we don't know if the elementType parameter is sane. super(buildArrayClassName(dimension, elementType), buildArrayClassName(dimension, elementType), buildArrayDescription(dimension, elementType)); // Check and construct state specific to ArrayType // if (elementType.isArray()) { ArrayType at = (ArrayType) elementType; this.dimension = at.getDimension() + dimension; this.elementType = at.getElementOpenType(); this.primitiveArray = at.isPrimitiveArray(); } else { this.dimension = dimension; this.elementType = elementType; this.primitiveArray = false; } } /** {@collect.stats} * Constructs a unidimensional {@code ArrayType} instance for the * supplied {@code SimpleType}. * <p> * This constructor supports the creation of arrays of primitive * types when {@code primitiveArray} is {@code true}. * <p> * For primitive arrays the {@link #getElementOpenType()} method * returns the {@link SimpleType} corresponding to the wrapper * type of the primitive type of the array. * <p> * When invoked on an <tt>ArrayType</tt> instance, the {@link OpenType#getClassName() getClassName} method * returns the class name of the array instances it describes (following the rules defined by the * {@link Class#getName() getName} method of <code>java.lang.Class</code>), not the class name of the array elements * (which is returned by a call to <tt>getElementOpenType().getClassName()</tt>). * <p> * The internal field corresponding to the type name of this <code>ArrayType</code> instance is also set to * the class name of the array instances it describes. * In other words, the methods <code>getClassName</code> and <code>getTypeName</code> return the same string value. * The internal field corresponding to the description of this <code>ArrayType</code> instance is set to a string value * which follows the following template: * <ul> * <li>if non-primitive array: <tt>1-dimension array of <i>&lt;element_class_name&gt;</i></tt></li> * <li>if primitive array: <tt>1-dimension array of <i>&lt;primitive_type_of_the_element_class_name&gt;</i></tt></li> * </ul> * <p> * As an example, the following piece of code: * <pre> * ArrayType<int[]> t = new ArrayType<int[]>(SimpleType.INTEGER, true); * System.out.println("array class name = " + t.getClassName()); * System.out.println("element class name = " + t.getElementOpenType().getClassName()); * System.out.println("array type name = " + t.getTypeName()); * System.out.println("array type description = " + t.getDescription()); * </pre> * would produce the following output: * <pre> * array class name = [I * element class name = java.lang.Integer * array type name = [I * array type description = 1-dimension array of int * </pre> * * @param elementType the {@code SimpleType} of the element values * contained in the arrays described by this * {@code ArrayType} instance. * * @param primitiveArray {@code true} when this array describes * primitive arrays. * * @throws IllegalArgumentException if {@code dimension} is not a positive * integer. * @throws OpenDataException if {@code primitiveArray} is {@code true} and * {@code elementType} is not a valid {@code SimpleType} for a primitive * type. * * @since 1.6 */ public ArrayType(SimpleType<?> elementType, boolean primitiveArray) throws OpenDataException { // Check and construct state defined by parent. // We can call the package-private OpenType constructor because the // set of SimpleTypes is fixed and SimpleType can't be subclassed. super(buildArrayClassName(1, elementType, primitiveArray), buildArrayClassName(1, elementType, primitiveArray), buildArrayDescription(1, elementType, primitiveArray), true); // Check and construct state specific to ArrayType // this.dimension = 1; this.elementType = elementType; this.primitiveArray = primitiveArray; } /* Package-private constructor for callers we trust to get it right. */ ArrayType(String className, String typeName, String description, int dimension, OpenType elementType, boolean primitiveArray) { super(className, typeName, description, true); this.dimension = dimension; this.elementType = elementType; this.primitiveArray = primitiveArray; } private static String buildArrayClassName(int dimension, OpenType<?> elementType) throws OpenDataException { boolean isPrimitiveArray = false; if (elementType.isArray()) { isPrimitiveArray = ((ArrayType) elementType).isPrimitiveArray(); } return buildArrayClassName(dimension, elementType, isPrimitiveArray); } private static String buildArrayClassName(int dimension, OpenType<?> elementType, boolean isPrimitiveArray) throws OpenDataException { if (dimension < 1) { throw new IllegalArgumentException( "Value of argument dimension must be greater than 0"); } StringBuilder result = new StringBuilder(); String elementClassName = elementType.getClassName(); // Add N (= dimension) additional '[' characters to the existing array for (int i = 1; i <= dimension; i++) { result.append('['); } if (elementType.isArray()) { result.append(elementClassName); } else { if (isPrimitiveArray) { final String key = getPrimitiveTypeKey(elementClassName); // Ideally we should throw an IllegalArgumentException here, // but for compatibility reasons we throw an OpenDataException. // (used to be thrown by OpenType() constructor). // if (key == null) throw new OpenDataException("Element type is not primitive: " + elementClassName); result.append(key); } else { result.append("L"); result.append(elementClassName); result.append(';'); } } return result.toString(); } private static String buildArrayDescription(int dimension, OpenType<?> elementType) throws OpenDataException { boolean isPrimitiveArray = false; if (elementType.isArray()) { isPrimitiveArray = ((ArrayType) elementType).isPrimitiveArray(); } return buildArrayDescription(dimension, elementType, isPrimitiveArray); } private static String buildArrayDescription(int dimension, OpenType<?> elementType, boolean isPrimitiveArray) throws OpenDataException { if (elementType.isArray()) { ArrayType at = (ArrayType) elementType; dimension += at.getDimension(); elementType = at.getElementOpenType(); isPrimitiveArray = at.isPrimitiveArray(); } StringBuilder result = new StringBuilder(dimension + "-dimension array of "); final String elementClassName = elementType.getClassName(); if (isPrimitiveArray) { // Convert from wrapper type to primitive type final String primitiveType = getPrimitiveTypeName(elementClassName); // Ideally we should throw an IllegalArgumentException here, // but for compatibility reasons we throw an OpenDataException. // (used to be thrown by OpenType() constructor). // if (primitiveType == null) throw new OpenDataException("Element is not a primitive type: "+ elementClassName); result.append(primitiveType); } else { result.append(elementClassName); } return result.toString(); } /* *** ArrayType specific information methods *** */ /** {@collect.stats} * Returns the dimension of arrays described by this <tt>ArrayType</tt> instance. * * @return the dimension. */ public int getDimension() { return dimension; } /** {@collect.stats} * Returns the <i>open type</i> of element values contained in the arrays described by this <tt>ArrayType</tt> instance. * * @return the element type. */ public OpenType<?> getElementOpenType() { return elementType; } /** {@collect.stats} * Returns <code>true</code> if the open data values this open * type describes are primitive arrays, <code>false</code> otherwise. * * @return true if this is a primitive array type. * * @since 1.6 */ public boolean isPrimitiveArray() { return primitiveArray; } /** {@collect.stats} * Tests whether <var>obj</var> is a value for this <code>ArrayType</code> * instance. * <p> * This method returns <code>true</code> if and only if <var>obj</var> * is not null, <var>obj</var> is an array and any one of the following * is <tt>true</tt>: * * <ul> * <li>if this <code>ArrayType</code> instance describes an array of * <tt>SimpleType</tt> elements or their corresponding primitive types, * <var>obj</var>'s class name is the same as the className field defined * for this <code>ArrayType</code> instance (i.e. the class name returned * by the {@link OpenType#getClassName() getClassName} method, which * includes the dimension information),<br>&nbsp;</li> * <li>if this <code>ArrayType</code> instance describes an array of * classes implementing the {@code TabularData} interface or the * {@code CompositeData} interface, <var>obj</var> is assignable to * such a declared array, and each element contained in <var>obj</var> * is either null or a valid value for the element's open type specified * by this <code>ArrayType</code> instance.</li> * </ul> * * @param obj the object to be tested. * * @return <code>true</code> if <var>obj</var> is a value for this * <code>ArrayType</code> instance. */ public boolean isValue(Object obj) { // if obj is null, return false // if (obj == null) { return false; } Class objClass = obj.getClass(); String objClassName = objClass.getName(); // if obj is not an array, return false // if ( ! objClass.isArray() ) { return false; } // Test if obj's class name is the same as for the array values that this instance describes // (this is fine if elements are of simple types, which are final classes) // if ( this.getClassName().equals(objClassName) ) { return true; } // In case this ArrayType instance describes an array of classes implementing the TabularData or CompositeData interface, // we first check for the assignability of obj to such an array of TabularData or CompositeData, // which ensures that: // . obj is of the the same dimension as this ArrayType instance, // . it is declared as an array of elements which are either all TabularData or all CompositeData. // // If the assignment check is positive, // then we have to check that each element in obj is of the same TabularType or CompositeType // as the one described by this ArrayType instance. // // [About assignment check, note that the call below returns true: ] // [Class.forName("[Lpackage.CompositeData;").isAssignableFrom(Class.forName("[Lpackage.CompositeDataImpl;)")); ] // if ( (this.elementType.getClassName().equals(TabularData.class.getName())) || (this.elementType.getClassName().equals(CompositeData.class.getName())) ) { boolean isTabular = (elementType.getClassName().equals(TabularData.class.getName())); int[] dims = new int[getDimension()]; Class<?> elementClass = isTabular ? TabularData.class : CompositeData.class; Class<?> targetClass = Array.newInstance(elementClass, dims).getClass(); // assignment check: return false if negative if ( ! targetClass.isAssignableFrom(objClass) ) { return false; } // check that all elements in obj are valid values for this ArrayType if ( ! checkElementsType( (Object[]) obj, this.dimension) ) { // we know obj's dimension is this.dimension return false; } return true; } // if previous tests did not return, then obj is not a value for this ArrayType instance return false; } /** {@collect.stats} * Returns true if and only if all elements contained in the array argument x_dim_Array of dimension dim * are valid values (ie either null or of the right openType) * for the element open type specified by this ArrayType instance. * * This method's implementation uses recursion to go down the dimensions of the array argument. */ private boolean checkElementsType(Object[] x_dim_Array, int dim) { // if the elements of x_dim_Array are themselves array: go down recursively.... if ( dim > 1 ) { for (int i=0; i<x_dim_Array.length; i++) { if ( ! checkElementsType((Object[])x_dim_Array[i], dim-1) ) { return false; } } return true; } // ...else, for a non-empty array, each element must be a valid value: either null or of the right openType else { for (int i=0; i<x_dim_Array.length; i++) { if ( (x_dim_Array[i] != null) && (! this.getElementOpenType().isValue(x_dim_Array[i])) ) { return false; } } return true; } } @Override boolean isAssignableFrom(OpenType ot) { if (!(ot instanceof ArrayType)) return false; ArrayType<?> at = (ArrayType<?>) ot; return (at.getDimension() == getDimension() && at.isPrimitiveArray() == isPrimitiveArray() && at.getElementOpenType().isAssignableFrom(getElementOpenType())); } /* *** Methods overriden from class Object *** */ /** {@collect.stats} * Compares the specified <code>obj</code> parameter with this * <code>ArrayType</code> instance for equality. * <p> * Two <code>ArrayType</code> instances are equal if and only if they * describe array instances which have the same dimension, elements' * open type and primitive array flag. * * @param obj the object to be compared for equality with this * <code>ArrayType</code> instance; if <var>obj</var> * is <code>null</code> or is not an instance of the * class <code>ArrayType</code> this method returns * <code>false</code>. * * @return <code>true</code> if the specified object is equal to * this <code>ArrayType</code> instance. */ public boolean equals(Object obj) { // if obj is null, return false // if (obj == null) { return false; } // if obj is not an ArrayType, return false // if (!(obj instanceof ArrayType)) return false; ArrayType other = (ArrayType) obj; // if other's dimension is different than this instance's, return false // if (this.dimension != other.dimension) { return false; } // Test if other's elementType field is the same as for this instance // if (!this.elementType.equals(other.elementType)) { return false; } // Test if other's primitiveArray flag is the same as for this instance // return this.primitiveArray == other.primitiveArray; } /** {@collect.stats} * Returns the hash code value for this <code>ArrayType</code> instance. * <p> * The hash code of an <code>ArrayType</code> instance is the sum of the * hash codes of all the elements of information used in <code>equals</code> * comparisons (i.e. dimension, elements' open type and primitive array flag). * The hashcode for a primitive value is the hashcode of the corresponding boxed * object (e.g. the hashcode for <tt>true</tt> is <tt>Boolean.TRUE.hashCode()</tt>). * This ensures that <code> t1.equals(t2) </code> implies that * <code> t1.hashCode()==t2.hashCode() </code> for any two * <code>ArrayType</code> instances <code>t1</code> and <code>t2</code>, * as required by the general contract of the method * {@link Object#hashCode() Object.hashCode()}. * <p> * As <code>ArrayType</code> instances are immutable, the hash * code for this instance is calculated once, on the first call * to <code>hashCode</code>, and then the same value is returned * for subsequent calls. * * @return the hash code value for this <code>ArrayType</code> instance */ public int hashCode() { // Calculate the hash code value if it has not yet been done (ie 1st call to hashCode()) // if (myHashCode == null) { int value = 0; value += dimension; value += elementType.hashCode(); value += Boolean.valueOf(primitiveArray).hashCode(); myHashCode = new Integer(value); } // return always the same hash code for this instance (immutable) // return myHashCode.intValue(); } /** {@collect.stats} * Returns a string representation of this <code>ArrayType</code> instance. * <p> * The string representation consists of the name of this class (i.e. * <code>javax.management.openmbean.ArrayType</code>), the type name, * the dimension, the elements' open type and the primitive array flag * defined for this instance. * <p> * As <code>ArrayType</code> instances are immutable, the * string representation for this instance is calculated * once, on the first call to <code>toString</code>, and * then the same value is returned for subsequent calls. * * @return a string representation of this <code>ArrayType</code> instance */ public String toString() { // Calculate the string representation if it has not yet been done (ie 1st call to toString()) // if (myToString == null) { myToString = getClass().getName() + "(name=" + getTypeName() + ",dimension=" + dimension + ",elementType=" + elementType + ",primitiveArray=" + primitiveArray + ")"; } // return always the same string representation for this instance (immutable) // return myToString; } /** {@collect.stats} * Create an {@code ArrayType} instance in a type-safe manner. * <p> * Multidimensional arrays can be built up by calling this method as many * times as necessary. * <p> * Calling this method twice with the same parameters may return the same * object or two equal but not identical objects. * <p> * As an example, the following piece of code: * <pre> * ArrayType<String[]> t1 = ArrayType.getArrayType(SimpleType.STRING); * ArrayType<String[][]> t2 = ArrayType.getArrayType(t1); * ArrayType<String[][][]> t3 = ArrayType.getArrayType(t2); * System.out.println("array class name = " + t3.getClassName()); * System.out.println("element class name = " + t3.getElementOpenType().getClassName()); * System.out.println("array type name = " + t3.getTypeName()); * System.out.println("array type description = " + t3.getDescription()); * </pre> * would produce the following output: * <pre> * array class name = [[[Ljava.lang.String; * element class name = java.lang.String * array type name = [[[Ljava.lang.String; * array type description = 3-dimension array of java.lang.String * </pre> * * @param elementType the <i>open type</i> of element values contained * in the arrays described by this <tt>ArrayType</tt> * instance; must be an instance of either * <tt>SimpleType</tt>, <tt>CompositeType</tt>, * <tt>TabularType</tt> or another <tt>ArrayType</tt> * with a <tt>SimpleType</tt>, <tt>CompositeType</tt> * or <tt>TabularType</tt> as its <tt>elementType</tt>. * * @throws OpenDataException if <var>elementType's className</var> is not * one of the allowed Java class names for open * data. * * @since 1.6 */ public static <E> ArrayType<E[]> getArrayType(OpenType<E> elementType) throws OpenDataException { return new ArrayType<E[]>(1, elementType); } /** {@collect.stats} * Create an {@code ArrayType} instance in a type-safe manner. * <p> * Calling this method twice with the same parameters may return the * same object or two equal but not identical objects. * <p> * As an example, the following piece of code: * <pre> * ArrayType<int[][][]> t = ArrayType.getPrimitiveArrayType(int[][][].class); * System.out.println("array class name = " + t.getClassName()); * System.out.println("element class name = " + t.getElementOpenType().getClassName()); * System.out.println("array type name = " + t.getTypeName()); * System.out.println("array type description = " + t.getDescription()); * </pre> * would produce the following output: * <pre> * array class name = [[[I * element class name = java.lang.Integer * array type name = [[[I * array type description = 3-dimension array of int * </pre> * * @param arrayClass a primitive array class such as {@code int[].class}, * {@code boolean[][].class}, etc. The {@link * #getElementOpenType()} method of the returned * {@code ArrayType} returns the {@link SimpleType} * corresponding to the wrapper type of the primitive * type of the array. * * @throws IllegalArgumentException if <var>arrayClass</var> is not * a primitive array. * * @since 1.6 */ @SuppressWarnings("unchecked") // can't get appropriate T for primitive array public static <T> ArrayType<T> getPrimitiveArrayType(Class<T> arrayClass) { // Check if the supplied parameter is an array // if (!arrayClass.isArray()) { throw new IllegalArgumentException("arrayClass must be an array"); } // Calculate array dimension and component type name // int n = 1; Class<?> componentType = arrayClass.getComponentType(); while (componentType.isArray()) { n++; componentType = componentType.getComponentType(); } String componentTypeName = componentType.getName(); // Check if the array's component type is a primitive type // if (!componentType.isPrimitive()) { throw new IllegalArgumentException( "component type of the array must be a primitive type"); } // Map component type name to corresponding SimpleType // final SimpleType<?> simpleType = getPrimitiveOpenType(componentTypeName); // Build primitive array // try { ArrayType at = new ArrayType(simpleType, true); if (n > 1) at = new ArrayType<T>(n - 1, at); return at; } catch (OpenDataException e) { throw new IllegalArgumentException(e); // should not happen } } /** {@collect.stats} * Replace/resolve the object read from the stream before it is returned * to the caller. * * @serialData The new serial form of this class defines a new serializable * {@code boolean} field {@code primitiveArray}. In order to guarantee the * interoperability with previous versions of this class the new serial * form must continue to refer to primitive wrapper types even when the * {@code ArrayType} instance describes a primitive type array. So when * {@code primitiveArray} is {@code true} the {@code className}, * {@code typeName} and {@code description} serializable fields * are converted into primitive types before the deserialized * {@code ArrayType} instance is return to the caller. The * {@code elementType} field always returns the {@code SimpleType} * corresponding to the primitive wrapper type of the array's * primitive type. * <p> * Therefore the following serializable fields are deserialized as follows: * <ul> * <li>if {@code primitiveArray} is {@code true} the {@code className} * field is deserialized by replacing the array's component primitive * wrapper type by the corresponding array's component primitive type, * e.g. {@code "[[Ljava.lang.Integer;"} will be deserialized as * {@code "[[I"}.</li> * <li>if {@code primitiveArray} is {@code true} the {@code typeName} * field is deserialized by replacing the array's component primitive * wrapper type by the corresponding array's component primitive type, * e.g. {@code "[[Ljava.lang.Integer;"} will be deserialized as * {@code "[[I"}.</li> * <li>if {@code primitiveArray} is {@code true} the {@code description} * field is deserialized by replacing the array's component primitive * wrapper type by the corresponding array's component primitive type, * e.g. {@code "2-dimension array of java.lang.Integer"} will be * deserialized as {@code "2-dimension array of int"}.</li> * </ul> * * @since 1.6 */ private Object readResolve() throws ObjectStreamException { if (primitiveArray) { return convertFromWrapperToPrimitiveTypes(); } else { return this; } } private ArrayType convertFromWrapperToPrimitiveTypes() { String cn = getClassName(); String tn = getTypeName(); String d = getDescription(); for (Object[] typeDescr : PRIMITIVE_ARRAY_TYPES) { if (cn.indexOf((String)typeDescr[PRIMITIVE_WRAPPER_NAME_INDEX]) != -1) { cn = cn.replaceFirst( "L" + typeDescr[PRIMITIVE_WRAPPER_NAME_INDEX] + ";", (String) typeDescr[PRIMITIVE_TYPE_KEY_INDEX]); tn = tn.replaceFirst( "L" + typeDescr[PRIMITIVE_WRAPPER_NAME_INDEX] + ";", (String) typeDescr[PRIMITIVE_TYPE_KEY_INDEX]); d = d.replaceFirst( (String) typeDescr[PRIMITIVE_WRAPPER_NAME_INDEX], (String) typeDescr[PRIMITIVE_TYPE_NAME_INDEX]); break; } } return new ArrayType(cn, tn, d, dimension, elementType, primitiveArray); } /** {@collect.stats} * Nominate a replacement for this object in the stream before the object * is written. * * @serialData The new serial form of this class defines a new serializable * {@code boolean} field {@code primitiveArray}. In order to guarantee the * interoperability with previous versions of this class the new serial * form must continue to refer to primitive wrapper types even when the * {@code ArrayType} instance describes a primitive type array. So when * {@code primitiveArray} is {@code true} the {@code className}, * {@code typeName} and {@code description} serializable fields * are converted into wrapper types before the serialized * {@code ArrayType} instance is written to the stream. The * {@code elementType} field always returns the {@code SimpleType} * corresponding to the primitive wrapper type of the array's * primitive type. * <p> * Therefore the following serializable fields are serialized as follows: * <ul> * <li>if {@code primitiveArray} is {@code true} the {@code className} * field is serialized by replacing the array's component primitive * type by the corresponding array's component primitive wrapper type, * e.g. {@code "[[I"} will be serialized as * {@code "[[Ljava.lang.Integer;"}.</li> * <li>if {@code primitiveArray} is {@code true} the {@code typeName} * field is serialized by replacing the array's component primitive * type by the corresponding array's component primitive wrapper type, * e.g. {@code "[[I"} will be serialized as * {@code "[[Ljava.lang.Integer;"}.</li> * <li>if {@code primitiveArray} is {@code true} the {@code description} * field is serialized by replacing the array's component primitive * type by the corresponding array's component primitive wrapper type, * e.g. {@code "2-dimension array of int"} will be serialized as * {@code "2-dimension array of java.lang.Integer"}.</li> * </ul> * * @since 1.6 */ private Object writeReplace() throws ObjectStreamException { if (primitiveArray) { return convertFromPrimitiveToWrapperTypes(); } else { return this; } } private ArrayType convertFromPrimitiveToWrapperTypes() { String cn = getClassName(); String tn = getTypeName(); String d = getDescription(); for (Object[] typeDescr : PRIMITIVE_ARRAY_TYPES) { if (cn.indexOf((String) typeDescr[PRIMITIVE_TYPE_KEY_INDEX]) != -1) { cn = cn.replaceFirst( (String) typeDescr[PRIMITIVE_TYPE_KEY_INDEX], "L" + typeDescr[PRIMITIVE_WRAPPER_NAME_INDEX] + ";"); tn = tn.replaceFirst( (String) typeDescr[PRIMITIVE_TYPE_KEY_INDEX], "L" + typeDescr[PRIMITIVE_WRAPPER_NAME_INDEX] + ";"); d = d.replaceFirst( (String) typeDescr[PRIMITIVE_TYPE_NAME_INDEX], (String) typeDescr[PRIMITIVE_WRAPPER_NAME_INDEX]); break; } } return new ArrayType(cn, tn, d, dimension, elementType, primitiveArray); } }
Java
/* * Copyright (c) 2000, 2007, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management.openmbean; // java import // import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; // jmx import // /** {@collect.stats} * The <tt>TabularDataSupport</tt> class is the <i>open data</i> class which implements the <tt>TabularData</tt> * and the <tt>Map</tt> interfaces, and which is internally based on a hash map data structure. * * @since 1.5 */ /* It would make much more sense to implement Map<List<?>,CompositeData> here, but unfortunately we cannot for compatibility reasons. If we did that, then we would have to define e.g. CompositeData remove(Object) instead of Object remove(Object). That would mean that if any existing code subclassed TabularDataSupport and overrode Object remove(Object), it would (a) no longer compile and (b) not actually override CompositeData remove(Object) in binaries compiled before the change. */ public class TabularDataSupport implements TabularData, Map<Object,Object>, Cloneable, Serializable { /* Serial version */ static final long serialVersionUID = 5720150593236309827L; /** {@collect.stats} * @serial This tabular data instance's contents: a {@link HashMap} */ private Map<Object,CompositeData> dataMap; /** {@collect.stats} * @serial This tabular data instance's tabular type */ private TabularType tabularType; /** {@collect.stats} * The array of item names that define the index used for rows (convenience field) */ private transient String[] indexNamesArray; /* *** Constructors *** */ /** {@collect.stats} * Creates an empty <tt>TabularDataSupport</tt> instance whose open-type is <var>tabularType</var>, * and whose underlying <tt>HashMap</tt> has a default initial capacity (101) and default load factor (0.75). * <p> * This constructor simply calls <tt>this(tabularType, 101, 0.75f);</tt> * * @param tabularType the <i>tabular type</i> describing this <tt>TabularData</tt> instance; * cannot be null. * * @throws IllegalArgumentException if the tabular type is null. */ public TabularDataSupport(TabularType tabularType) { this(tabularType, 101, 0.75f); } /** {@collect.stats} * Creates an empty <tt>TabularDataSupport</tt> instance whose open-type is <var>tabularType</var>, * and whose underlying <tt>HashMap</tt> has the specified initial capacity and load factor. * * @param tabularType the <i>tabular type</i> describing this <tt>TabularData</tt> instance; * cannot be null. * * @param initialCapacity the initial capacity of the HashMap. * * @param loadFactor the load factor of the HashMap * * @throws IllegalArgumentException if the initial capacity is less than zero, * or the load factor is nonpositive, * or the tabular type is null. */ public TabularDataSupport(TabularType tabularType, int initialCapacity, float loadFactor) { // Check tabularType is not null // if (tabularType == null) { throw new IllegalArgumentException("Argument tabularType cannot be null."); } // Initialize this.tabularType (and indexNamesArray for convenience) // this.tabularType = tabularType; List<String> tmpNames = tabularType.getIndexNames(); this.indexNamesArray = tmpNames.toArray(new String[tmpNames.size()]); // Construct the empty contents HashMap // this.dataMap = new HashMap<Object,CompositeData>(initialCapacity, loadFactor); } /* *** TabularData specific information methods *** */ /** {@collect.stats} * Returns the <i>tabular type</i> describing this <tt>TabularData</tt> instance. */ public TabularType getTabularType() { return tabularType; } /** {@collect.stats} * Calculates the index that would be used in this <tt>TabularData</tt> instance to refer to the specified * composite data <var>value</var> parameter if it were added to this instance. * This method checks for the type validity of the specified <var>value</var>, * but does not check if the calculated index is already used to refer to a value in this <tt>TabularData</tt> instance. * * @param value the composite data value whose index in this * <tt>TabularData</tt> instance is to be calculated; * must be of the same composite type as this instance's row type; * must not be null. * * @return the index that the specified <var>value</var> would have in this <tt>TabularData</tt> instance. * * @throws NullPointerException if <var>value</var> is <tt>null</tt>. * * @throws InvalidOpenTypeException if <var>value</var> does not conform to this <tt>TabularData</tt> instance's * row type definition. */ public Object[] calculateIndex(CompositeData value) { // Check value is valid // checkValueType(value); // Return its calculated index // return internalCalculateIndex(value).toArray(); } /* *** Content information query methods *** */ /** {@collect.stats} * Returns <tt>true</tt> if and only if this <tt>TabularData</tt> instance contains a <tt>CompositeData</tt> value * (ie a row) whose index is the specified <var>key</var>. If <var>key</var> cannot be cast to a one dimension array * of Object instances, this method simply returns <tt>false</tt>; otherwise it returns the the result of the call to * <tt>this.containsKey((Object[]) key)</tt>. * * @param key the index value whose presence in this <tt>TabularData</tt> instance is to be tested. * * @return <tt>true</tt> if this <tt>TabularData</tt> indexes a row value with the specified key. */ public boolean containsKey(Object key) { // if key is not an array of Object instances, return false // Object[] k; try { k = (Object[]) key; } catch (ClassCastException e) { return false; } return this.containsKey(k); } /** {@collect.stats} * Returns <tt>true</tt> if and only if this <tt>TabularData</tt> instance contains a <tt>CompositeData</tt> value * (ie a row) whose index is the specified <var>key</var>. If <var>key</var> is <tt>null</tt> or does not conform to * this <tt>TabularData</tt> instance's <tt>TabularType</tt> definition, this method simply returns <tt>false</tt>. * * @param key the index value whose presence in this <tt>TabularData</tt> instance is to be tested. * * @return <tt>true</tt> if this <tt>TabularData</tt> indexes a row value with the specified key. */ public boolean containsKey(Object[] key) { return ( key == null ? false : dataMap.containsKey(Arrays.asList(key))); } /** {@collect.stats} * Returns <tt>true</tt> if and only if this <tt>TabularData</tt> instance contains the specified * <tt>CompositeData</tt> value. If <var>value</var> is <tt>null</tt> or does not conform to * this <tt>TabularData</tt> instance's row type definition, this method simply returns <tt>false</tt>. * * @param value the row value whose presence in this <tt>TabularData</tt> instance is to be tested. * * @return <tt>true</tt> if this <tt>TabularData</tt> instance contains the specified row value. */ public boolean containsValue(CompositeData value) { return dataMap.containsValue(value); } /** {@collect.stats} * Returns <tt>true</tt> if and only if this <tt>TabularData</tt> instance contains the specified * value. * * @param value the row value whose presence in this <tt>TabularData</tt> instance is to be tested. * * @return <tt>true</tt> if this <tt>TabularData</tt> instance contains the specified row value. */ public boolean containsValue(Object value) { return dataMap.containsValue(value); } /** {@collect.stats} * This method simply calls <tt>get((Object[]) key)</tt>. * * @throws NullPointerException if the <var>key</var> is <tt>null</tt> * @throws ClassCastException if the <var>key</var> is not of the type <tt>Object[]</tt> * @throws InvalidKeyException if the <var>key</var> does not conform to this <tt>TabularData</tt> instance's * <tt>TabularType</tt> definition */ public Object get(Object key) { return get((Object[]) key); } /** {@collect.stats} * Returns the <tt>CompositeData</tt> value whose index is * <var>key</var>, or <tt>null</tt> if there is no value mapping * to <var>key</var>, in this <tt>TabularData</tt> instance. * * @param key the index of the value to get in this * <tt>TabularData</tt> instance; * must be valid with this * <tt>TabularData</tt> instance's row type definition; * must not * be null. * * @return the value corresponding to <var>key</var>. * * @throws NullPointerException if the <var>key</var> is <tt>null</tt> * @throws InvalidKeyException if the <var>key</var> does not conform to this <tt>TabularData</tt> instance's * <tt>TabularType</tt> type definition. */ public CompositeData get(Object[] key) { // Check key is not null and valid with tabularType // (throws NullPointerException, InvalidKeyException) // checkKeyType(key); // Return the mapping stored in the parent HashMap // return dataMap.get(Arrays.asList(key)); } /* *** Content modification operations (one element at a time) *** */ /** {@collect.stats} * This method simply calls <tt>put((CompositeData) value)</tt> and * therefore ignores its <var>key</var> parameter which can be <tt>null</tt>. * * @param key an ignored parameter. * @param value the {@link CompositeData} to put. * * @return the value which is put * * @throws NullPointerException if the <var>value</var> is <tt>null</tt> * @throws ClassCastException if the <var>value</var> is not of * the type <tt>CompositeData</tt> * @throws InvalidOpenTypeException if the <var>value</var> does * not conform to this <tt>TabularData</tt> instance's * <tt>TabularType</tt> definition * @throws KeyAlreadyExistsException if the key for the * <var>value</var> parameter, calculated according to this * <tt>TabularData</tt> instance's <tt>TabularType</tt> definition * already maps to an existing value */ public Object put(Object key, Object value) { internalPut((CompositeData) value); return value; // should be return internalPut(...); (5090566) } public void put(CompositeData value) { internalPut(value); } private CompositeData internalPut(CompositeData value) { // Check value is not null, value's type is the same as this instance's row type, // and calculate the value's index according to this instance's tabularType and // check it is not already used for a mapping in the parent HashMap // List<?> index = checkValueAndIndex(value); // store the (key, value) mapping in the dataMap HashMap // return dataMap.put(index, value); } /** {@collect.stats} * This method simply calls <tt>remove((Object[]) key)</tt>. * * @param key an <tt>Object[]</tt> representing the key to remove. * * @return previous value associated with specified key, or <tt>null</tt> * if there was no mapping for key. * * @throws NullPointerException if the <var>key</var> is <tt>null</tt> * @throws ClassCastException if the <var>key</var> is not of the type <tt>Object[]</tt> * @throws InvalidKeyException if the <var>key</var> does not conform to this <tt>TabularData</tt> instance's * <tt>TabularType</tt> definition */ public Object remove(Object key) { return remove((Object[]) key); } /** {@collect.stats} * Removes the <tt>CompositeData</tt> value whose index is <var>key</var> from this <tt>TabularData</tt> instance, * and returns the removed value, or returns <tt>null</tt> if there is no value whose index is <var>key</var>. * * @param key the index of the value to get in this <tt>TabularData</tt> instance; * must be valid with this <tt>TabularData</tt> instance's row type definition; * must not be null. * * @return previous value associated with specified key, or <tt>null</tt> * if there was no mapping for key. * * @throws NullPointerException if the <var>key</var> is <tt>null</tt> * @throws InvalidKeyException if the <var>key</var> does not conform to this <tt>TabularData</tt> instance's * <tt>TabularType</tt> definition */ public CompositeData remove(Object[] key) { // Check key is not null and valid with tabularType // (throws NullPointerException, InvalidKeyException) // checkKeyType(key); // Removes the (key, value) mapping in the parent HashMap // return dataMap.remove(Arrays.asList(key)); } /* *** Content modification bulk operations *** */ /** {@collect.stats} * Add all the values contained in the specified map <var>t</var> * to this <tt>TabularData</tt> instance. This method converts * the collection of values contained in this map into an array of * <tt>CompositeData</tt> values, if possible, and then call the * method <tt>putAll(CompositeData[])</tt>. Note that the keys * used in the specified map <var>t</var> are ignored. This method * allows, for example to add the content of another * <tt>TabularData</tt> instance with the same row type (but * possibly different index names) into this instance. * * @param t the map whose values are to be added as new rows to * this <tt>TabularData</tt> instance; if <var>t</var> is * <tt>null</tt> or empty, this method returns without doing * anything. * * @throws NullPointerException if a value in <var>t</var> is * <tt>null</tt>. * @throws ClassCastException if a value in <var>t</var> is not an * instance of <tt>CompositeData</tt>. * @throws InvalidOpenTypeException if a value in <var>t</var> * does not conform to this <tt>TabularData</tt> instance's row * type definition. * @throws KeyAlreadyExistsException if the index for a value in * <var>t</var>, calculated according to this * <tt>TabularData</tt> instance's <tt>TabularType</tt> definition * already maps to an existing value in this instance, or two * values in <var>t</var> have the same index. */ public void putAll(Map<?,?> t) { // if t is null or empty, just return // if ( (t == null) || (t.size() == 0) ) { return; } // Convert the values in t into an array of <tt>CompositeData</tt> // CompositeData[] values; try { values = t.values().toArray(new CompositeData[t.size()]); } catch (java.lang.ArrayStoreException e) { throw new ClassCastException("Map argument t contains values which are not instances of <tt>CompositeData</tt>"); } // Add the array of values // putAll(values); } /** {@collect.stats} * Add all the elements in <var>values</var> to this * <tt>TabularData</tt> instance. If any element in * <var>values</var> does not satisfy the constraints defined in * {@link #put(CompositeData) <tt>put</tt>}, or if any two * elements in <var>values</var> have the same index calculated * according to this <tt>TabularData</tt> instance's * <tt>TabularType</tt> definition, then an exception describing * the failure is thrown and no element of <var>values</var> is * added, thus leaving this <tt>TabularData</tt> instance * unchanged. * * @param values the array of composite data values to be added as * new rows to this <tt>TabularData</tt> instance; if * <var>values</var> is <tt>null</tt> or empty, this method * returns without doing anything. * * @throws NullPointerException if an element of <var>values</var> * is <tt>null</tt> * @throws InvalidOpenTypeException if an element of * <var>values</var> does not conform to this * <tt>TabularData</tt> instance's row type definition (ie its * <tt>TabularType</tt> definition) * @throws KeyAlreadyExistsException if the index for an element * of <var>values</var>, calculated according to this * <tt>TabularData</tt> instance's <tt>TabularType</tt> definition * already maps to an existing value in this instance, or two * elements of <var>values</var> have the same index */ public void putAll(CompositeData[] values) { // if values is null or empty, just return // if ( (values == null) || (values.length == 0) ) { return; } // create the list of indexes corresponding to each value List<List<?>> indexes = new ArrayList<List<?>>(values.length + 1); // Check all elements in values and build index list // List<?> index; for (int i=0; i<values.length; i++) { // check value and calculate index index = checkValueAndIndex(values[i]); // check index is different of those previously calculated if (indexes.contains(index)) { throw new KeyAlreadyExistsException("Argument elements values["+ i +"] and values["+ indexes.indexOf(index) + "] have the same indexes, "+ "calculated according to this TabularData instance's tabularType."); } // add to index list indexes.add(index); } // store all (index, value) mappings in the dataMap HashMap // for (int i=0; i<values.length; i++) { dataMap.put(indexes.get(i), values[i]); } } /** {@collect.stats} * Removes all rows from this <code>TabularDataSupport</code> instance. */ public void clear() { dataMap.clear(); } /* *** Informational methods from java.util.Map *** */ /** {@collect.stats} * Returns the number of rows in this <code>TabularDataSupport</code> instance. * * @return the number of rows in this <code>TabularDataSupport</code> instance. */ public int size() { return dataMap.size(); } /** {@collect.stats} * Returns <tt>true</tt> if this <code>TabularDataSupport</code> instance contains no rows. * * @return <tt>true</tt> if this <code>TabularDataSupport</code> instance contains no rows. */ public boolean isEmpty() { return (this.size() == 0); } /* *** Collection views from java.util.Map *** */ /** {@collect.stats} * Returns a set view of the keys contained in the underlying map of this * {@code TabularDataSupport} instance used to index the rows. * Each key contained in this {@code Set} is an unmodifiable {@code List<?>} * so the returned set view is a {@code Set<List<?>>} but is declared as a * {@code Set<Object>} for compatibility reasons. * The set is backed by the underlying map of this * {@code TabularDataSupport} instance, so changes to the * {@code TabularDataSupport} instance are reflected in the * set, and vice-versa. * * The set supports element removal, which removes the corresponding * row from this {@code TabularDataSupport} instance, via the * {@link Iterator#remove}, {@link Set#remove}, {@link Set#removeAll}, * {@link Set#retainAll}, and {@link Set#clear} operations. It does * not support the {@link Set#add} or {@link Set#addAll} operations. * * @return a set view ({@code Set<List<?>>}) of the keys used to index * the rows of this {@code TabularDataSupport} instance. */ public Set<Object> keySet() { return dataMap.keySet() ; } /** {@collect.stats} * Returns a collection view of the rows contained in this * {@code TabularDataSupport} instance. The returned {@code Collection} * is a {@code Collection<CompositeData>} but is declared as a * {@code Collection<Object>} for compatibility reasons. * The returned collection can be used to iterate over the values. * The collection is backed by the underlying map, so changes to the * {@code TabularDataSupport} instance are reflected in the collection, * and vice-versa. * * The collection supports element removal, which removes the corresponding * index to row mapping from this {@code TabularDataSupport} instance, via * the {@link Iterator#remove}, {@link Collection#remove}, * {@link Collection#removeAll}, {@link Collection#retainAll}, * and {@link Collection#clear} operations. It does not support * the {@link Collection#add} or {@link Collection#addAll} operations. * * @return a collection view ({@code Collection<CompositeData>}) of * the values contained in this {@code TabularDataSupport} instance. */ @SuppressWarnings("unchecked") // historical confusion about the return type public Collection<Object> values() { return (Collection) dataMap.values() ; } /** {@collect.stats} * Returns a collection view of the index to row mappings * contained in this {@code TabularDataSupport} instance. * Each element in the returned collection is * a {@code Map.Entry<List<?>,CompositeData>} but * is declared as a {@code Map.Entry<Object,Object>} * for compatibility reasons. Each of the map entry * keys is an unmodifiable {@code List<?>}. * The collection is backed by the underlying map of this * {@code TabularDataSupport} instance, so changes to the * {@code TabularDataSupport} instance are reflected in * the collection, and vice-versa. * The collection supports element removal, which removes * the corresponding mapping from the map, via the * {@link Iterator#remove}, {@link Collection#remove}, * {@link Collection#removeAll}, {@link Collection#retainAll}, * and {@link Collection#clear} operations. It does not support * the {@link Collection#add} or {@link Collection#addAll} * operations. * <p> * <b>IMPORTANT NOTICE</b>: Do not use the {@code setValue} method of the * {@code Map.Entry} elements contained in the returned collection view. * Doing so would corrupt the index to row mappings contained in this * {@code TabularDataSupport} instance. * * @return a collection view ({@code Set<Map.Entry<List<?>,CompositeData>>}) * of the mappings contained in this map. * @see java.util.Map.Entry */ @SuppressWarnings("unchecked") // historical confusion about the return type public Set<Map.Entry<Object,Object>> entrySet() { return (Set) dataMap.entrySet(); } /* *** Commodity methods from java.lang.Object *** */ /** {@collect.stats} * Returns a clone of this <code>TabularDataSupport</code> instance: * the clone is obtained by calling <tt>super.clone()</tt>, and then cloning the underlying map. * Only a shallow clone of the underlying map is made, i.e. no cloning of the indexes and row values is made as they are immutable. */ /* We cannot use covariance here and return TabularDataSupport because this would fail with existing code that subclassed TabularDataSupport and overrode Object clone(). It would not override the new clone(). */ public Object clone() { try { TabularDataSupport c = (TabularDataSupport) super.clone(); c.dataMap = new HashMap<Object,CompositeData>(c.dataMap); return c; } catch (CloneNotSupportedException e) { throw new InternalError(e.toString()); } } /** {@collect.stats} * Compares the specified <var>obj</var> parameter with this <code>TabularDataSupport</code> instance for equality. * <p> * Returns <tt>true</tt> if and only if all of the following statements are true: * <ul> * <li><var>obj</var> is non null,</li> * <li><var>obj</var> also implements the <code>TabularData</code> interface,</li> * <li>their tabular types are equal</li> * <li>their contents (ie all CompositeData values) are equal.</li> * </ul> * This ensures that this <tt>equals</tt> method works properly for <var>obj</var> parameters which are * different implementations of the <code>TabularData</code> interface. * <br>&nbsp; * @param obj the object to be compared for equality with this <code>TabularDataSupport</code> instance; * * @return <code>true</code> if the specified object is equal to this <code>TabularDataSupport</code> instance. */ public boolean equals(Object obj) { // if obj is null, return false // if (obj == null) { return false; } // if obj is not a TabularData, return false // TabularData other; try { other = (TabularData) obj; } catch (ClassCastException e) { return false; } // Now, really test for equality between this TabularData implementation and the other: // // their tabularType should be equal if ( ! this.getTabularType().equals(other.getTabularType()) ) { return false; } // their contents should be equal: // . same size // . values in this instance are in the other (we know there are no duplicate elements possible) // (row values comparison is enough, because keys are calculated according to tabularType) if (this.size() != other.size()) { return false; } for (Iterator iter = this.values().iterator(); iter.hasNext(); ) { CompositeData value = (CompositeData) iter.next(); if ( ! other.containsValue(value) ) { return false; } } // All tests for equality were successfull // return true; } /** {@collect.stats} * Returns the hash code value for this <code>TabularDataSupport</code> instance. * <p> * The hash code of a <code>TabularDataSupport</code> instance is the sum of the hash codes * of all elements of information used in <code>equals</code> comparisons * (ie: its <i>tabular type</i> and its content, where the content is defined as all the CompositeData values). * <p> * This ensures that <code> t1.equals(t2) </code> implies that <code> t1.hashCode()==t2.hashCode() </code> * for any two <code>TabularDataSupport</code> instances <code>t1</code> and <code>t2</code>, * as required by the general contract of the method * {@link Object#hashCode() Object.hashCode()}. * <p> * However, note that another instance of a class implementing the <code>TabularData</code> interface * may be equal to this <code>TabularDataSupport</code> instance as defined by {@link #equals}, * but may have a different hash code if it is calculated differently. * * @return the hash code value for this <code>TabularDataSupport</code> instance */ public int hashCode() { int result = 0; result += this.tabularType.hashCode(); for (Iterator iter = this.values().iterator(); iter.hasNext(); ) { result += ((CompositeData)iter.next()).hashCode(); } return result; } /** {@collect.stats} * Returns a string representation of this <code>TabularDataSupport</code> instance. * <p> * The string representation consists of the name of this class (ie <code>javax.management.openmbean.TabularDataSupport</code>), * the string representation of the tabular type of this instance, and the string representation of the contents * (ie list the key=value mappings as returned by a call to * <tt>dataMap.</tt>{@link java.util.HashMap#toString() toString()}). * * @return a string representation of this <code>TabularDataSupport</code> instance */ public String toString() { return new StringBuilder() .append(this.getClass().getName()) .append("(tabularType=") .append(tabularType.toString()) .append(",contents=") .append(dataMap.toString()) .append(")") .toString(); } /* *** TabularDataSupport internal utility methods *** */ /** {@collect.stats} * Returns the index for value, assuming value is valid for this <tt>TabularData</tt> instance * (ie value is not null, and its composite type is equal to row type). * * The index is a List, and not an array, so that an index.equals(otherIndex) call will actually compare contents, * not just the objects references as is done for an array object. * * The returned List is unmodifiable so that once a row has been put into the dataMap, its index cannot be modified, * for example by a user that would attempt to modify an index contained in the Set returned by keySet(). */ private List<?> internalCalculateIndex(CompositeData value) { return Collections.unmodifiableList(Arrays.asList(value.getAll(this.indexNamesArray))); } /** {@collect.stats} * Checks if the specified key is valid for this <tt>TabularData</tt> instance. * * @throws NullPointerException * @throws InvalidOpenTypeException */ private void checkKeyType(Object[] key) { // Check key is neither null nor empty // if ( (key == null) || (key.length == 0) ) { throw new NullPointerException("Argument key cannot be null or empty."); } /* Now check key is valid with tabularType index and row type definitions: */ // key[] should have the size expected for an index // if (key.length != this.indexNamesArray.length) { throw new InvalidKeyException("Argument key's length="+ key.length + " is different from the number of item values, which is "+ indexNamesArray.length + ", specified for the indexing rows in this TabularData instance."); } // each element in key[] should be a value for its corresponding open type specified in rowType // OpenType<?> keyElementType; for (int i=0; i<key.length; i++) { keyElementType = tabularType.getRowType().getType(this.indexNamesArray[i]); if ( (key[i] != null) && (! keyElementType.isValue(key[i])) ) { throw new InvalidKeyException("Argument element key["+ i +"] is not a value for the open type expected for "+ "this element of the index, whose name is \""+ indexNamesArray[i] + "\" and whose open type is "+ keyElementType); } } } /** {@collect.stats} * Checks the specified value's type is valid for this <tt>TabularData</tt> instance * (ie value is not null, and its composite type is equal to row type). * * @throws NullPointerException * @throws InvalidOpenTypeException */ private void checkValueType(CompositeData value) { // Check value is not null // if (value == null) { throw new NullPointerException("Argument value cannot be null."); } // if value's type is not the same as this instance's row type, throw InvalidOpenTypeException // if (!tabularType.getRowType().isValue(value)) { throw new InvalidOpenTypeException("Argument value's composite type ["+ value.getCompositeType() + "] is not assignable to "+ "this TabularData instance's row type ["+ tabularType.getRowType() +"]."); } } /** {@collect.stats} * Checks if the specified value can be put (ie added) in this <tt>TabularData</tt> instance * (ie value is not null, its composite type is equal to row type, and its index is not already used), * and returns the index calculated for this value. * * The index is a List, and not an array, so that an index.equals(otherIndex) call will actually compare contents, * not just the objects references as is done for an array object. * * @throws NullPointerException * @throws InvalidOpenTypeException * @throws KeyAlreadyExistsException */ private List<?> checkValueAndIndex(CompositeData value) { // Check value is valid // checkValueType(value); // Calculate value's index according to this instance's tabularType // and check it is not already used for a mapping in the parent HashMap // List<?> index = internalCalculateIndex(value); if (dataMap.containsKey(index)) { throw new KeyAlreadyExistsException("Argument value's index, calculated according to this TabularData "+ "instance's tabularType, already refers to a value in this table."); } // The check is OK, so return the index // return index; } /** {@collect.stats} * Deserializes a {@link TabularDataSupport} from an {@link ObjectInputStream}. */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); List<String> tmpNames = tabularType.getIndexNames(); indexNamesArray = tmpNames.toArray(new String[tmpNames.size()]); } }
Java
/* * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management.openmbean; import com.sun.jmx.mbeanserver.MXBeanLookup; import com.sun.jmx.mbeanserver.OpenConverter; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; /** {@collect.stats} <p>An {@link InvocationHandler} that forwards getter methods to a {@link CompositeData}. If you have an interface that contains only getter methods (such as {@code String getName()} or {@code boolean isActive()}) then you can use this class in conjunction with the {@link Proxy} class to produce an implementation of the interface where each getter returns the value of the corresponding item in a {@code CompositeData}.</p> <p>For example, suppose you have an interface like this: <blockquote> <pre> public interface NamedNumber { public int getNumber(); public String getName(); } </pre> </blockquote> and a {@code CompositeData} constructed like this: <blockquote> <pre> CompositeData cd = new {@link CompositeDataSupport}( someCompositeType, new String[] {"number", "name"}, new Object[] {<b>5</b>, "five"} ); </pre> </blockquote> then you can construct an object implementing {@code NamedNumber} and backed by the object {@code cd} like this: <blockquote> <pre> InvocationHandler handler = new CompositeDataInvocationHandler(cd); NamedNumber nn = (NamedNumber) Proxy.newProxyInstance(NamedNumber.class.getClassLoader(), new Class[] {NamedNumber.class}, handler); </pre> </blockquote> A call to {@code nn.getNumber()} will then return <b>5</b>.</p> <p>If the first letter of the property defined by a getter is a capital, then this handler will look first for an item in the {@code CompositeData} beginning with a capital, then, if that is not found, for an item beginning with the corresponding lowercase letter or code point. For a getter called {@code getNumber()}, the handler will first look for an item called {@code Number}, then for {@code number}. If the getter is called {@code getnumber()}, then the item must be called {@code number}.</p> <p>If the method given to {@link #invoke invoke} is the method {@code boolean equals(Object)} inherited from {@code Object}, then it will return true if and only if the argument is a {@code Proxy} whose {@code InvocationHandler} is also a {@code CompositeDataInvocationHandler} and whose backing {@code CompositeData} is equal (not necessarily identical) to this object's. If the method given to {@code invoke} is the method {@code int hashCode()} inherited from {@code Object}, then it will return a value that is consistent with this definition of {@code equals}: if two objects are equal according to {@code equals}, then they will have the same {@code hashCode}.</p> @since 1.6 */ public class CompositeDataInvocationHandler implements InvocationHandler { /** {@collect.stats} <p>Construct a handler backed by the given {@code CompositeData}.</p> @param compositeData the {@code CompositeData} that will supply information to getters. @throws IllegalArgumentException if {@code compositeData} is null. */ public CompositeDataInvocationHandler(CompositeData compositeData) { this(compositeData, null); } /** {@collect.stats} <p>Construct a handler backed by the given {@code CompositeData}.</p> @param mbsc the {@code MBeanServerConnection} related to this {@code CompositeData}. This is only relevant if a method in the interface for which this is an invocation handler returns a type that is an MXBean interface. Otherwise, it can be null. @param compositeData the {@code CompositeData} that will supply information to getters. @throws IllegalArgumentException if {@code compositeData} is null. */ CompositeDataInvocationHandler(CompositeData compositeData, MXBeanLookup lookup) { if (compositeData == null) throw new IllegalArgumentException("compositeData"); this.compositeData = compositeData; this.lookup = lookup; } /** {@collect.stats} Return the {@code CompositeData} that was supplied to the constructor. @return the {@code CompositeData} that this handler is backed by. This is never null. */ public CompositeData getCompositeData() { assert compositeData != null; return compositeData; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { final String methodName = method.getName(); // Handle the methods from java.lang.Object if (method.getDeclaringClass() == Object.class) { if (methodName.equals("toString") && args == null) return "Proxy[" + compositeData + "]"; else if (methodName.equals("hashCode") && args == null) return compositeData.hashCode() + 0x43444948; else if (methodName.equals("equals") && args.length == 1 && method.getParameterTypes()[0] == Object.class) return equals(proxy, args[0]); else { /* Either someone is calling invoke by hand, or it is a non-final method from Object overriden by the generated Proxy. At the time of writing, the only non-final methods in Object that are not handled above are finalize and clone, and these are not overridden in generated proxies. */ return method.invoke(this, args); } } String propertyName = OpenConverter.propertyName(method); if (propertyName == null) { throw new IllegalArgumentException("Method is not getter: " + method.getName()); } Object openValue; if (compositeData.containsKey(propertyName)) openValue = compositeData.get(propertyName); else { String decap = OpenConverter.decapitalize(propertyName); if (compositeData.containsKey(decap)) openValue = compositeData.get(decap); else { final String msg = "No CompositeData item " + propertyName + (decap.equals(propertyName) ? "" : " or " + decap) + " to match " + methodName; throw new IllegalArgumentException(msg); } } OpenConverter converter = OpenConverter.toConverter(method.getGenericReturnType()); return converter.fromOpenValue(lookup, openValue); } /* This method is called when equals(Object) is * called on our proxy and hence forwarded to us. For example, if we * are a proxy for an interface like this: * public interface GetString { * public String string(); * } * then we must compare equal to another CompositeDataInvocationHandler * proxy for the same interface and where string() returns the same value. * * You might think that we should also compare equal to another * object that implements GetString directly rather than using * Proxy, provided that its string() returns the same result as * ours, and in fact an earlier version of this class did that (by * converting the other object into a CompositeData and comparing * that with ours). But in fact that doesn't make a great deal of * sense because there's absolutely no guarantee that the * resulting equals would be reflexive (otherObject.equals(this) * might be false even if this.equals(otherObject) is true), and, * especially, there's no way we could generate a hashCode() that * would be equal to otherObject.hashCode() when * this.equals(otherObject), because we don't know how * otherObject.hashCode() is computed. */ private boolean equals(Object proxy, Object other) { if (other == null) return false; final Class proxyClass = proxy.getClass(); final Class otherClass = other.getClass(); if (proxyClass != otherClass) return false; InvocationHandler otherih = Proxy.getInvocationHandler(other); if (!(otherih instanceof CompositeDataInvocationHandler)) return false; CompositeDataInvocationHandler othercdih = (CompositeDataInvocationHandler) otherih; return compositeData.equals(othercdih.compositeData); } private final CompositeData compositeData; private final MXBeanLookup lookup; }
Java
/* * Copyright (c) 2000, 2007, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management.openmbean; // java import // import java.util.Set; import java.util.Collection; // jmx import // /** {@collect.stats} * The <tt>TabularData</tt> interface specifies the behavior of a specific type of complex <i>open data</i> objects * which represent <i>tabular data</i> structures. * * @since 1.5 */ public interface TabularData /*extends Map*/ { /* *** TabularData specific information methods *** */ /** {@collect.stats} * Returns the <i>tabular type</i> describing this * <tt>TabularData</tt> instance. * * @return the tabular type. */ public TabularType getTabularType(); /** {@collect.stats} * Calculates the index that would be used in this <tt>TabularData</tt> instance to refer to the specified * composite data <var>value</var> parameter if it were added to this instance. * This method checks for the type validity of the specified <var>value</var>, * but does not check if the calculated index is already used to refer to a value in this <tt>TabularData</tt> instance. * * @param value the composite data value whose index in this * <tt>TabularData</tt> instance is to be calculated; * must be of the same composite type as this instance's row type; * must not be null. * * @return the index that the specified <var>value</var> would have in this <tt>TabularData</tt> instance. * * @throws NullPointerException if <var>value</var> is <tt>null</tt> * * @throws InvalidOpenTypeException if <var>value</var> does not conform to this <tt>TabularData</tt> instance's * row type definition. */ public Object[] calculateIndex(CompositeData value) ; /* *** Content information query methods *** */ /** {@collect.stats} * Returns the number of <tt>CompositeData</tt> values (ie the * number of rows) contained in this <tt>TabularData</tt> * instance. * * @return the number of values contained. */ public int size() ; /** {@collect.stats} * Returns <tt>true</tt> if the number of <tt>CompositeData</tt> * values (ie the number of rows) contained in this * <tt>TabularData</tt> instance is zero. * * @return true if this <tt>TabularData</tt> is empty. */ public boolean isEmpty() ; /** {@collect.stats} * Returns <tt>true</tt> if and only if this <tt>TabularData</tt> instance contains a <tt>CompositeData</tt> value * (ie a row) whose index is the specified <var>key</var>. If <var>key</var> is <tt>null</tt> or does not conform to * this <tt>TabularData</tt> instance's <tt>TabularType</tt> definition, this method simply returns <tt>false</tt>. * * @param key the index value whose presence in this <tt>TabularData</tt> instance is to be tested. * * @return <tt>true</tt> if this <tt>TabularData</tt> indexes a row value with the specified key. */ public boolean containsKey(Object[] key) ; /** {@collect.stats} * Returns <tt>true</tt> if and only if this <tt>TabularData</tt> instance contains the specified * <tt>CompositeData</tt> value. If <var>value</var> is <tt>null</tt> or does not conform to * this <tt>TabularData</tt> instance's row type definition, this method simply returns <tt>false</tt>. * * @param value the row value whose presence in this <tt>TabularData</tt> instance is to be tested. * * @return <tt>true</tt> if this <tt>TabularData</tt> instance contains the specified row value. */ public boolean containsValue(CompositeData value) ; /** {@collect.stats} * Returns the <tt>CompositeData</tt> value whose index is * <var>key</var>, or <tt>null</tt> if there is no value mapping * to <var>key</var>, in this <tt>TabularData</tt> instance. * * @param key the key of the row to return. * * @return the value corresponding to <var>key</var>. * * @throws NullPointerException if the <var>key</var> is * <tt>null</tt> * @throws InvalidKeyException if the <var>key</var> does not * conform to this <tt>TabularData</tt> instance's * * <tt>TabularType</tt> definition */ public CompositeData get(Object[] key) ; /* *** Content modification operations (one element at a time) *** */ /** {@collect.stats} * Adds <var>value</var> to this <tt>TabularData</tt> instance. * The composite type of <var>value</var> must be the same as this * instance's row type (ie the composite type returned by * <tt>this.getTabularType().{@link TabularType#getRowType * getRowType()}</tt>), and there must not already be an existing * value in this <tt>TabularData</tt> instance whose index is the * same as the one calculated for the <var>value</var> to be * added. The index for <var>value</var> is calculated according * to this <tt>TabularData</tt> instance's <tt>TabularType</tt> * definition (see <tt>TabularType.{@link * TabularType#getIndexNames getIndexNames()}</tt>). * * @param value the composite data value to be added as a new row to this <tt>TabularData</tt> instance; * must be of the same composite type as this instance's row type; * must not be null. * * @throws NullPointerException if <var>value</var> is <tt>null</tt> * @throws InvalidOpenTypeException if <var>value</var> does not conform to this <tt>TabularData</tt> instance's * row type definition. * @throws KeyAlreadyExistsException if the index for <var>value</var>, calculated according to * this <tt>TabularData</tt> instance's <tt>TabularType</tt> definition * already maps to an existing value in the underlying HashMap. */ public void put(CompositeData value) ; /** {@collect.stats} * Removes the <tt>CompositeData</tt> value whose index is <var>key</var> from this <tt>TabularData</tt> instance, * and returns the removed value, or returns <tt>null</tt> if there is no value whose index is <var>key</var>. * * @param key the index of the value to get in this <tt>TabularData</tt> instance; * must be valid with this <tt>TabularData</tt> instance's row type definition; * must not be null. * * @return previous value associated with specified key, or <tt>null</tt> * if there was no mapping for key. * * @throws NullPointerException if the <var>key</var> is <tt>null</tt> * @throws InvalidKeyException if the <var>key</var> does not conform to this <tt>TabularData</tt> instance's * <tt>TabularType</tt> definition */ public CompositeData remove(Object[] key) ; /* *** Content modification bulk operations *** */ /** {@collect.stats} * Add all the elements in <var>values</var> to this <tt>TabularData</tt> instance. * If any element in <var>values</var> does not satisfy the constraints defined in {@link #put(CompositeData) <tt>put</tt>}, * or if any two elements in <var>values</var> have the same index calculated according to this <tt>TabularData</tt> * instance's <tt>TabularType</tt> definition, then an exception describing the failure is thrown * and no element of <var>values</var> is added, thus leaving this <tt>TabularData</tt> instance unchanged. * * @param values the array of composite data values to be added as new rows to this <tt>TabularData</tt> instance; * if <var>values</var> is <tt>null</tt> or empty, this method returns without doing anything. * * @throws NullPointerException if an element of <var>values</var> is <tt>null</tt> * @throws InvalidOpenTypeException if an element of <var>values</var> does not conform to * this <tt>TabularData</tt> instance's row type definition * @throws KeyAlreadyExistsException if the index for an element of <var>values</var>, calculated according to * this <tt>TabularData</tt> instance's <tt>TabularType</tt> definition * already maps to an existing value in this instance, * or two elements of <var>values</var> have the same index. */ public void putAll(CompositeData[] values) ; /** {@collect.stats} * Removes all <tt>CompositeData</tt> values (ie rows) from this <tt>TabularData</tt> instance. */ public void clear(); /* *** Collection views of the keys and values *** */ /** {@collect.stats} * Returns a set view of the keys (ie the index values) of the * {@code CompositeData} values (ie the rows) contained in this * {@code TabularData} instance. The returned {@code Set} is a * {@code Set<List<?>>} but is declared as a {@code Set<?>} for * compatibility reasons. The returned set can be used to iterate * over the keys. * * @return a set view ({@code Set<List<?>>}) of the index values * used in this {@code TabularData} instance. */ public Set<?> keySet(); /** {@collect.stats} * Returns a collection view of the {@code CompositeData} values * (ie the rows) contained in this {@code TabularData} instance. * The returned {@code Collection} is a {@code Collection<CompositeData>} * but is declared as a {@code Collection<?>} for compatibility reasons. * The returned collection can be used to iterate over the values. * * @return a collection view ({@code Collection<CompositeData>}) * of the rows contained in this {@code TabularData} instance. */ public Collection<?> values(); /* *** Commodity methods from java.lang.Object *** */ /** {@collect.stats} * Compares the specified <var>obj</var> parameter with this <code>TabularData</code> instance for equality. * <p> * Returns <tt>true</tt> if and only if all of the following statements are true: * <ul> * <li><var>obj</var> is non null,</li> * <li><var>obj</var> also implements the <code>TabularData</code> interface,</li> * <li>their row types are equal</li> * <li>their contents (ie index to value mappings) are equal</li> * </ul> * This ensures that this <tt>equals</tt> method works properly for <var>obj</var> parameters which are * different implementations of the <code>TabularData</code> interface. * <br>&nbsp; * @param obj the object to be compared for equality with this <code>TabularData</code> instance; * * @return <code>true</code> if the specified object is equal to this <code>TabularData</code> instance. */ public boolean equals(Object obj); /** {@collect.stats} * Returns the hash code value for this <code>TabularData</code> instance. * <p> * The hash code of a <code>TabularData</code> instance is the sum of the hash codes * of all elements of information used in <code>equals</code> comparisons * (ie: its <i>tabular type</i> and its content, where the content is defined as all the index to value mappings). * <p> * This ensures that <code> t1.equals(t2) </code> implies that <code> t1.hashCode()==t2.hashCode() </code> * for any two <code>TabularDataSupport</code> instances <code>t1</code> and <code>t2</code>, * as required by the general contract of the method * {@link Object#hashCode() Object.hashCode()}. * * @return the hash code value for this <code>TabularDataSupport</code> instance */ public int hashCode(); /** {@collect.stats} * Returns a string representation of this <code>TabularData</code> instance. * <p> * The string representation consists of the name of the implementing class, * and the tabular type of this instance. * * @return a string representation of this <code>TabularData</code> instance */ public String toString(); }
Java
/* * Copyright (c) 2000, 2007, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management.openmbean; // java import // // jmx import // import javax.management.MBeanParameterInfo; /** {@collect.stats} * <p>Describes a constructor of an Open MBean.</p> * * <p>This interface declares the same methods as the class {@link * javax.management.MBeanConstructorInfo}. A class implementing this * interface (typically {@link OpenMBeanConstructorInfoSupport}) * should extend {@link javax.management.MBeanConstructorInfo}.</p> * * <p>The {@link #getSignature()} method should return at runtime an * array of instances of a subclass of {@link MBeanParameterInfo} * which implements the {@link OpenMBeanParameterInfo} interface * (typically {@link OpenMBeanParameterInfoSupport}).</p> * * * * @since 1.5 */ public interface OpenMBeanConstructorInfo { // Re-declares the methods that are in class MBeanConstructorInfo of JMX 1.0 // (methods will be removed when MBeanConstructorInfo is made a parent interface of this interface) /** {@collect.stats} * Returns a human readable description of the constructor * described by this <tt>OpenMBeanConstructorInfo</tt> instance. * * @return the description. */ public String getDescription() ; /** {@collect.stats} * Returns the name of the constructor * described by this <tt>OpenMBeanConstructorInfo</tt> instance. * * @return the name. */ public String getName() ; /** {@collect.stats} * Returns an array of <tt>OpenMBeanParameterInfo</tt> instances * describing each parameter in the signature of the constructor * described by this <tt>OpenMBeanConstructorInfo</tt> instance. * * @return the signature. */ public MBeanParameterInfo[] getSignature() ; // commodity methods // /** {@collect.stats} * Compares the specified <var>obj</var> parameter with this <code>OpenMBeanConstructorInfo</code> instance for equality. * <p> * Returns <tt>true</tt> if and only if all of the following statements are true: * <ul> * <li><var>obj</var> is non null,</li> * <li><var>obj</var> also implements the <code>OpenMBeanConstructorInfo</code> interface,</li> * <li>their names are equal</li> * <li>their signatures are equal.</li> * </ul> * This ensures that this <tt>equals</tt> method works properly for <var>obj</var> parameters which are * different implementations of the <code>OpenMBeanConstructorInfo</code> interface. * <br>&nbsp; * @param obj the object to be compared for equality with this <code>OpenMBeanConstructorInfo</code> instance; * * @return <code>true</code> if the specified object is equal to this <code>OpenMBeanConstructorInfo</code> instance. */ public boolean equals(Object obj); /** {@collect.stats} * Returns the hash code value for this <code>OpenMBeanConstructorInfo</code> instance. * <p> * The hash code of an <code>OpenMBeanConstructorInfo</code> instance is the sum of the hash codes * of all elements of information used in <code>equals</code> comparisons * (ie: its name and signature, where the signature hashCode is calculated by a call to * <tt>java.util.Arrays.asList(this.getSignature).hashCode()</tt>). * <p> * This ensures that <code> t1.equals(t2) </code> implies that <code> t1.hashCode()==t2.hashCode() </code> * for any two <code>OpenMBeanConstructorInfo</code> instances <code>t1</code> and <code>t2</code>, * as required by the general contract of the method * {@link Object#hashCode() Object.hashCode()}. * <p> * * @return the hash code value for this <code>OpenMBeanConstructorInfo</code> instance */ public int hashCode(); /** {@collect.stats} * Returns a string representation of this <code>OpenMBeanConstructorInfo</code> instance. * <p> * The string representation consists of the name of this class (ie <code>javax.management.openmbean.OpenMBeanConstructorInfo</code>), * and the name and signature of the described constructor. * * @return a string representation of this <code>OpenMBeanConstructorInfo</code> instance */ public String toString(); }
Java
/* * Copyright (c) 2000, 2007, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management.openmbean; // java import // import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import javax.management.Descriptor; import javax.management.DescriptorRead; import javax.management.ImmutableDescriptor; import javax.management.MBeanAttributeInfo; import com.sun.jmx.remote.util.EnvHelp; /** {@collect.stats} * Describes an attribute of an open MBean. * * * @since 1.5 */ public class OpenMBeanAttributeInfoSupport extends MBeanAttributeInfo implements OpenMBeanAttributeInfo { /* Serial version */ static final long serialVersionUID = -4867215622149721849L; /** {@collect.stats} * @serial The open mbean attribute's <i>open type</i> */ private OpenType<?> openType; /** {@collect.stats} * @serial The open mbean attribute's default value */ private final Object defaultValue; /** {@collect.stats} * @serial The open mbean attribute's legal values. This {@link * Set} is unmodifiable */ private final Set<?> legalValues; // to be constructed unmodifiable /** {@collect.stats} * @serial The open mbean attribute's min value */ private final Comparable minValue; /** {@collect.stats} * @serial The open mbean attribute's max value */ private final Comparable maxValue; // As this instance is immutable, these two values need only // be calculated once. private transient Integer myHashCode = null; private transient String myToString = null; /** {@collect.stats} * Constructs an {@code OpenMBeanAttributeInfoSupport} instance, * which describes the attribute of an open MBean with the * specified {@code name}, {@code openType} and {@code * description}, and the specified read/write access properties. * * @param name cannot be a null or empty string. * * @param description cannot be a null or empty string. * * @param openType cannot be null. * * @param isReadable {@code true} if the attribute has a getter * exposed for management. * * @param isWritable {@code true} if the attribute has a setter * exposed for management. * * @param isIs {@code true} if the attribute's getter is of the * form <tt>is<i>XXX</i></tt>. * * @throws IllegalArgumentException if {@code name} or {@code * description} are null or empty string, or {@code openType} is * null. */ public OpenMBeanAttributeInfoSupport(String name, String description, OpenType<?> openType, boolean isReadable, boolean isWritable, boolean isIs) { this(name, description, openType, isReadable, isWritable, isIs, (Descriptor) null); } /** {@collect.stats} * <p>Constructs an {@code OpenMBeanAttributeInfoSupport} instance, * which describes the attribute of an open MBean with the * specified {@code name}, {@code openType}, {@code * description}, read/write access properties, and {@code Descriptor}.</p> * * <p>The {@code descriptor} can contain entries that will define * the values returned by certain methods of this class, as * explained in the {@link <a href="package-summary.html#constraints"> * package description</a>}. * * @param name cannot be a null or empty string. * * @param description cannot be a null or empty string. * * @param openType cannot be null. * * @param isReadable {@code true} if the attribute has a getter * exposed for management. * * @param isWritable {@code true} if the attribute has a setter * exposed for management. * * @param isIs {@code true} if the attribute's getter is of the * form <tt>is<i>XXX</i></tt>. * * @param descriptor The descriptor for the attribute. This may be null * which is equivalent to an empty descriptor. * * @throws IllegalArgumentException if {@code name} or {@code * description} are null or empty string, or {@code openType} is * null, or the descriptor entries are invalid as described in the * {@link <a href="package-summary.html#constraints">package * description</a>}. * * @since 1.6 */ public OpenMBeanAttributeInfoSupport(String name, String description, OpenType<?> openType, boolean isReadable, boolean isWritable, boolean isIs, Descriptor descriptor) { // Construct parent's state // super(name, (openType==null) ? null : openType.getClassName(), description, isReadable, isWritable, isIs, ImmutableDescriptor.union(descriptor, (openType==null)?null: openType.getDescriptor())); // Initialize this instance's specific state // this.openType = openType; descriptor = getDescriptor(); // replace null by empty this.defaultValue = valueFrom(descriptor, "defaultValue", openType); this.legalValues = valuesFrom(descriptor, "legalValues", openType); this.minValue = comparableValueFrom(descriptor, "minValue", openType); this.maxValue = comparableValueFrom(descriptor, "maxValue", openType); try { check(this); } catch (OpenDataException e) { throw new IllegalArgumentException(e.getMessage(), e); } } /** {@collect.stats} * Constructs an {@code OpenMBeanAttributeInfoSupport} instance, * which describes the attribute of an open MBean with the * specified {@code name}, {@code openType}, {@code description} * and {@code defaultValue}, and the specified read/write access * properties. * * @param name cannot be a null or empty string. * * @param description cannot be a null or empty string. * * @param openType cannot be null. * * @param isReadable {@code true} if the attribute has a getter * exposed for management. * * @param isWritable {@code true} if the attribute has a setter * exposed for management. * * @param isIs {@code true} if the attribute's getter is of the * form <tt>is<i>XXX</i></tt>. * * @param defaultValue must be a valid value for the {@code * openType} specified for this attribute; default value not * supported for {@code ArrayType} and {@code TabularType}; can * be null, in which case it means that no default value is set. * * @param <T> allows the compiler to check that the {@code defaultValue}, * if non-null, has the correct Java type for the given {@code openType}. * * @throws IllegalArgumentException if {@code name} or {@code * description} are null or empty string, or {@code openType} is * null. * * @throws OpenDataException if {@code defaultValue} is not a * valid value for the specified {@code openType}, or {@code * defaultValue} is non null and {@code openType} is an {@code * ArrayType} or a {@code TabularType}. */ public <T> OpenMBeanAttributeInfoSupport(String name, String description, OpenType<T> openType, boolean isReadable, boolean isWritable, boolean isIs, T defaultValue) throws OpenDataException { this(name, description, openType, isReadable, isWritable, isIs, defaultValue, (T[]) null); } /** {@collect.stats} * <p>Constructs an {@code OpenMBeanAttributeInfoSupport} instance, * which describes the attribute of an open MBean with the * specified {@code name}, {@code openType}, {@code description}, * {@code defaultValue} and {@code legalValues}, and the specified * read/write access properties.</p> * * <p>The contents of {@code legalValues} are copied, so subsequent * modifications of the array referenced by {@code legalValues} * have no impact on this {@code OpenMBeanAttributeInfoSupport} * instance.</p> * * @param name cannot be a null or empty string. * * @param description cannot be a null or empty string. * * @param openType cannot be null. * * @param isReadable {@code true} if the attribute has a getter * exposed for management. * * @param isWritable {@code true} if the attribute has a setter * exposed for management. * * @param isIs {@code true} if the attribute's getter is of the * form <tt>is<i>XXX</i></tt>. * * @param defaultValue must be a valid value * for the {@code * openType} specified for this attribute; default value not * supported for {@code ArrayType} and {@code TabularType}; can * be null, in which case it means that no default value is set. * * @param legalValues each contained value must be valid for the * {@code openType} specified for this attribute; legal values * not supported for {@code ArrayType} and {@code TabularType}; * can be null or empty. * * @param <T> allows the compiler to check that the {@code * defaultValue} and {@code legalValues}, if non-null, have the * correct Java type for the given {@code openType}. * * @throws IllegalArgumentException if {@code name} or {@code * description} are null or empty string, or {@code openType} is * null. * * @throws OpenDataException if {@code defaultValue} is not a * valid value for the specified {@code openType}, or one value in * {@code legalValues} is not valid for the specified {@code * openType}, or {@code defaultValue} is non null and {@code * openType} is an {@code ArrayType} or a {@code TabularType}, or * {@code legalValues} is non null and non empty and {@code * openType} is an {@code ArrayType} or a {@code TabularType}, or * {@code legalValues} is non null and non empty and {@code * defaultValue} is not contained in {@code legalValues}. */ public <T> OpenMBeanAttributeInfoSupport(String name, String description, OpenType<T> openType, boolean isReadable, boolean isWritable, boolean isIs, T defaultValue, T[] legalValues) throws OpenDataException { this(name, description, openType, isReadable, isWritable, isIs, defaultValue, legalValues, null, null); } /** {@collect.stats} * Constructs an {@code OpenMBeanAttributeInfoSupport} instance, * which describes the attribute of an open MBean, with the * specified {@code name}, {@code openType}, {@code description}, * {@code defaultValue}, {@code minValue} and {@code maxValue}. * * It is possible to specify minimal and maximal values only for * an open type whose values are {@code Comparable}. * * @param name cannot be a null or empty string. * * @param description cannot be a null or empty string. * * @param openType cannot be null. * * @param isReadable {@code true} if the attribute has a getter * exposed for management. * * @param isWritable {@code true} if the attribute has a setter * exposed for management. * * @param isIs {@code true} if the attribute's getter is of the * form <tt>is<i>XXX</i></tt>. * * @param defaultValue must be a valid value for the {@code * openType} specified for this attribute; default value not * supported for {@code ArrayType} and {@code TabularType}; can be * null, in which case it means that no default value is set. * * @param minValue must be valid for the {@code openType} * specified for this attribute; can be null, in which case it * means that no minimal value is set. * * @param maxValue must be valid for the {@code openType} * specified for this attribute; can be null, in which case it * means that no maximal value is set. * * @param <T> allows the compiler to check that the {@code * defaultValue}, {@code minValue}, and {@code maxValue}, if * non-null, have the correct Java type for the given {@code * openType}. * * @throws IllegalArgumentException if {@code name} or {@code * description} are null or empty string, or {@code openType} is * null. * * @throws OpenDataException if {@code defaultValue}, {@code * minValue} or {@code maxValue} is not a valid value for the * specified {@code openType}, or {@code defaultValue} is non null * and {@code openType} is an {@code ArrayType} or a {@code * TabularType}, or both {@code minValue} and {@code maxValue} are * non-null and {@code minValue.compareTo(maxValue) > 0} is {@code * true}, or both {@code defaultValue} and {@code minValue} are * non-null and {@code minValue.compareTo(defaultValue) > 0} is * {@code true}, or both {@code defaultValue} and {@code maxValue} * are non-null and {@code defaultValue.compareTo(maxValue) > 0} * is {@code true}. */ public <T> OpenMBeanAttributeInfoSupport(String name, String description, OpenType<T> openType, boolean isReadable, boolean isWritable, boolean isIs, T defaultValue, Comparable<T> minValue, Comparable<T> maxValue) throws OpenDataException { this(name, description, openType, isReadable, isWritable, isIs, defaultValue, null, minValue, maxValue); } private <T> OpenMBeanAttributeInfoSupport(String name, String description, OpenType<T> openType, boolean isReadable, boolean isWritable, boolean isIs, T defaultValue, T[] legalValues, Comparable<T> minValue, Comparable<T> maxValue) throws OpenDataException { super(name, (openType==null) ? null : openType.getClassName(), description, isReadable, isWritable, isIs, makeDescriptor(openType, defaultValue, legalValues, minValue, maxValue)); this.openType = openType; Descriptor d = getDescriptor(); this.defaultValue = defaultValue; this.minValue = minValue; this.maxValue = maxValue; // We already converted the array into an unmodifiable Set // in the descriptor. this.legalValues = (Set<?>) d.getFieldValue("legalValues"); check(this); } /** {@collect.stats} * An object serialized in a version of the API before Descriptors were * added to this class will have an empty or null Descriptor. * For consistency with our * behavior in this version, we must replace the object with one * where the Descriptors reflect the same values of openType, defaultValue, * etc. **/ private Object readResolve() { if (getDescriptor().getFieldNames().length == 0) { OpenType<Object> xopenType = cast(openType); Set<Object> xlegalValues = cast(legalValues); Comparable<Object> xminValue = cast(minValue); Comparable<Object> xmaxValue = cast(maxValue); return new OpenMBeanAttributeInfoSupport( name, description, openType, isReadable(), isWritable(), isIs(), makeDescriptor(xopenType, defaultValue, xlegalValues, xminValue, xmaxValue)); } else return this; } static void check(OpenMBeanParameterInfo info) throws OpenDataException { OpenType openType = info.getOpenType(); if (openType == null) throw new IllegalArgumentException("OpenType cannot be null"); if (info.getName() == null || info.getName().trim().equals("")) throw new IllegalArgumentException("Name cannot be null or empty"); if (info.getDescription() == null || info.getDescription().trim().equals("")) throw new IllegalArgumentException("Description cannot be null or empty"); // Check and initialize defaultValue // if (info.hasDefaultValue()) { // Default value not supported for ArrayType and TabularType // Cast to Object because "OpenType<T> instanceof" is illegal if (openType.isArray() || (Object)openType instanceof TabularType) { throw new OpenDataException("Default value not supported " + "for ArrayType and TabularType"); } // Check defaultValue's class if (!openType.isValue(info.getDefaultValue())) { final String msg = "Argument defaultValue's class [\"" + info.getDefaultValue().getClass().getName() + "\"] does not match the one defined in openType[\"" + openType.getClassName() +"\"]"; throw new OpenDataException(msg); } } // Check that we don't have both legalValues and min or max // if (info.hasLegalValues() && (info.hasMinValue() || info.hasMaxValue())) { throw new OpenDataException("cannot have both legalValue and " + "minValue or maxValue"); } // Check minValue and maxValue if (info.hasMinValue() && !openType.isValue(info.getMinValue())) { final String msg = "Type of minValue [" + info.getMinValue().getClass().getName() + "] does not match OpenType [" + openType.getClassName() + "]"; throw new OpenDataException(msg); } if (info.hasMaxValue() && !openType.isValue(info.getMaxValue())) { final String msg = "Type of maxValue [" + info.getMaxValue().getClass().getName() + "] does not match OpenType [" + openType.getClassName() + "]"; throw new OpenDataException(msg); } // Check that defaultValue is a legal value // if (info.hasDefaultValue()) { Object defaultValue = info.getDefaultValue(); if (info.hasLegalValues() && !info.getLegalValues().contains(defaultValue)) { throw new OpenDataException("defaultValue is not contained " + "in legalValues"); } // Check that minValue <= defaultValue <= maxValue // if (info.hasMinValue()) { if (compare(info.getMinValue(), defaultValue) > 0) { throw new OpenDataException("minValue cannot be greater " + "than defaultValue"); } } if (info.hasMaxValue()) { if (compare(info.getMaxValue(), defaultValue) < 0) { throw new OpenDataException("maxValue cannot be less " + "than defaultValue"); } } } // Check legalValues // if (info.hasLegalValues()) { // legalValues not supported for TabularType and arrays if ((Object)openType instanceof TabularType || openType.isArray()) { throw new OpenDataException("Legal values not supported " + "for TabularType and arrays"); } // Check legalValues are valid with openType for (Object v : info.getLegalValues()) { if (!openType.isValue(v)) { final String msg = "Element of legalValues [" + v + "] is not a valid value for the specified openType [" + openType.toString() +"]"; throw new OpenDataException(msg); } } } // Check that, if both specified, minValue <= maxValue // if (info.hasMinValue() && info.hasMaxValue()) { if (compare(info.getMinValue(), info.getMaxValue()) > 0) { throw new OpenDataException("minValue cannot be greater " + "than maxValue"); } } } @SuppressWarnings("unchecked") static int compare(Object x, Object y) { return ((Comparable) x).compareTo(y); } static <T> Descriptor makeDescriptor(OpenType<T> openType, T defaultValue, T[] legalValues, Comparable<T> minValue, Comparable<T> maxValue) { Map<String, Object> map = new HashMap<String, Object>(); if (defaultValue != null) map.put("defaultValue", defaultValue); if (legalValues != null) { Set<T> set = new HashSet<T>(); for (T v : legalValues) set.add(v); set = Collections.unmodifiableSet(set); map.put("legalValues", set); } if (minValue != null) map.put("minValue", minValue); if (maxValue != null) map.put("maxValue", maxValue); if (map.isEmpty()) { return openType.getDescriptor(); } else { map.put("openType", openType); return new ImmutableDescriptor(map); } } static <T> Descriptor makeDescriptor(OpenType<T> openType, T defaultValue, Set<T> legalValues, Comparable<T> minValue, Comparable<T> maxValue) { T[] legals; if (legalValues == null) legals = null; else { legals = cast(new Object[legalValues.size()]); legalValues.toArray(legals); } return makeDescriptor(openType, defaultValue, legals, minValue, maxValue); } static <T> T valueFrom(Descriptor d, String name, OpenType<T> openType) { Object x = d.getFieldValue(name); if (x == null) return null; try { return convertFrom(x, openType); } catch (Exception e) { final String msg = "Cannot convert descriptor field " + name + " to " + openType.getTypeName(); throw EnvHelp.initCause(new IllegalArgumentException(msg), e); } } static <T> Set<T> valuesFrom(Descriptor d, String name, OpenType<T> openType) { Object x = d.getFieldValue(name); if (x == null) return null; Collection<?> coll; if (x instanceof Set<?>) { Set<?> set = (Set<?>) x; boolean asis = true; for (Object element : set) { if (!openType.isValue(element)) { asis = false; break; } } if (asis) return cast(set); coll = set; } else if (x instanceof Object[]) { coll = Arrays.asList((Object[]) x); } else { final String msg = "Descriptor value for " + name + " must be a Set or " + "an array: " + x.getClass().getName(); throw new IllegalArgumentException(msg); } Set<T> result = new HashSet<T>(); for (Object element : coll) result.add(convertFrom(element, openType)); return result; } static <T> Comparable comparableValueFrom(Descriptor d, String name, OpenType<T> openType) { T t = valueFrom(d, name, openType); if (t == null || t instanceof Comparable<?>) return (Comparable) t; final String msg = "Descriptor field " + name + " with value " + t + " is not Comparable"; throw new IllegalArgumentException(msg); } private static <T> T convertFrom(Object x, OpenType<T> openType) { if (openType.isValue(x)) { T t = OpenMBeanAttributeInfoSupport.<T>cast(x); return t; } return convertFromStrings(x, openType); } private static <T> T convertFromStrings(Object x, OpenType<T> openType) { if (openType instanceof ArrayType<?>) return convertFromStringArray(x, openType); else if (x instanceof String) return convertFromString((String) x, openType); final String msg = "Cannot convert value " + x + " of type " + x.getClass().getName() + " to type " + openType.getTypeName(); throw new IllegalArgumentException(msg); } private static <T> T convertFromString(String s, OpenType<T> openType) { Class<T> c; try { c = cast(Class.forName(openType.safeGetClassName())); } catch (ClassNotFoundException e) { throw new NoClassDefFoundError(e.toString()); // can't happen } // Look for: public static T valueOf(String) Method valueOf; try { valueOf = c.getMethod("valueOf", String.class); if (!Modifier.isStatic(valueOf.getModifiers()) || valueOf.getReturnType() != c) valueOf = null; } catch (NoSuchMethodException e) { valueOf = null; } if (valueOf != null) { try { return c.cast(valueOf.invoke(null, s)); } catch (Exception e) { final String msg = "Could not convert \"" + s + "\" using method: " + valueOf; throw new IllegalArgumentException(msg, e); } } // Look for: public T(String) Constructor<T> con; try { con = c.getConstructor(String.class); } catch (NoSuchMethodException e) { con = null; } if (con != null) { try { return con.newInstance(s); } catch (Exception e) { final String msg = "Could not convert \"" + s + "\" using constructor: " + con; throw new IllegalArgumentException(msg, e); } } throw new IllegalArgumentException("Don't know how to convert " + "string to " + openType.getTypeName()); } /* A Descriptor contained an array value encoded as Strings. The Strings must be organized in an array corresponding to the desired array. If the desired array has n dimensions, so must the String array. We will convert element by element from String to desired component type. */ private static <T> T convertFromStringArray(Object x, OpenType<T> openType) { ArrayType<?> arrayType = (ArrayType<?>) openType; OpenType<?> baseType = arrayType.getElementOpenType(); int dim = arrayType.getDimension(); String squareBrackets = "["; for (int i = 1; i < dim; i++) squareBrackets += "["; Class<?> stringArrayClass; Class<?> targetArrayClass; try { stringArrayClass = Class.forName(squareBrackets + "Ljava.lang.String;"); targetArrayClass = Class.forName(squareBrackets + "L" + baseType.safeGetClassName() + ";"); } catch (ClassNotFoundException e) { throw new NoClassDefFoundError(e.toString()); // can't happen } if (!stringArrayClass.isInstance(x)) { final String msg = "Value for " + dim + "-dimensional array of " + baseType.getTypeName() + " must be same type or a String " + "array with same dimensions"; throw new IllegalArgumentException(msg); } OpenType<?> componentOpenType; if (dim == 1) componentOpenType = baseType; else { try { componentOpenType = new ArrayType<T>(dim - 1, baseType); } catch (OpenDataException e) { throw new IllegalArgumentException(e.getMessage(), e); // can't happen } } int n = Array.getLength(x); Object[] targetArray = (Object[]) Array.newInstance(targetArrayClass.getComponentType(), n); for (int i = 0; i < n; i++) { Object stringish = Array.get(x, i); // String or String[] etc Object converted = convertFromStrings(stringish, componentOpenType); Array.set(targetArray, i, converted); } return OpenMBeanAttributeInfoSupport.<T>cast(targetArray); } @SuppressWarnings("unchecked") static <T> T cast(Object x) { return (T) x; } /** {@collect.stats} * Returns the open type for the values of the attribute described * by this {@code OpenMBeanAttributeInfoSupport} instance. */ public OpenType<?> getOpenType() { return openType; } /** {@collect.stats} * Returns the default value for the attribute described by this * {@code OpenMBeanAttributeInfoSupport} instance, if specified, * or {@code null} otherwise. */ public Object getDefaultValue() { // Special case for ArrayType and TabularType // [JF] TODO: clone it so that it cannot be altered, // [JF] TODO: if we decide to support defaultValue as an array itself. // [JF] As of today (oct 2000) it is not supported so // defaultValue is null for arrays. Nothing to do. return defaultValue; } /** {@collect.stats} * Returns an unmodifiable Set of legal values for the attribute * described by this {@code OpenMBeanAttributeInfoSupport} * instance, if specified, or {@code null} otherwise. */ public Set<?> getLegalValues() { // Special case for ArrayType and TabularType // [JF] TODO: clone values so that they cannot be altered, // [JF] TODO: if we decide to support LegalValues as an array itself. // [JF] As of today (oct 2000) it is not supported so // legalValues is null for arrays. Nothing to do. // Returns our legalValues Set (set was constructed unmodifiable) return (legalValues); } /** {@collect.stats} * Returns the minimal value for the attribute described by this * {@code OpenMBeanAttributeInfoSupport} instance, if specified, * or {@code null} otherwise. */ public Comparable<?> getMinValue() { // Note: only comparable values have a minValue, // so that's not the case of arrays and tabulars (always null). return minValue; } /** {@collect.stats} * Returns the maximal value for the attribute described by this * {@code OpenMBeanAttributeInfoSupport} instance, if specified, * or {@code null} otherwise. */ public Comparable<?> getMaxValue() { // Note: only comparable values have a maxValue, // so that's not the case of arrays and tabulars (always null). return maxValue; } /** {@collect.stats} * Returns {@code true} if this {@code * OpenMBeanAttributeInfoSupport} instance specifies a non-null * default value for the described attribute, {@code false} * otherwise. */ public boolean hasDefaultValue() { return (defaultValue != null); } /** {@collect.stats} * Returns {@code true} if this {@code * OpenMBeanAttributeInfoSupport} instance specifies a non-null * set of legal values for the described attribute, {@code false} * otherwise. */ public boolean hasLegalValues() { return (legalValues != null); } /** {@collect.stats} * Returns {@code true} if this {@code * OpenMBeanAttributeInfoSupport} instance specifies a non-null * minimal value for the described attribute, {@code false} * otherwise. */ public boolean hasMinValue() { return (minValue != null); } /** {@collect.stats} * Returns {@code true} if this {@code * OpenMBeanAttributeInfoSupport} instance specifies a non-null * maximal value for the described attribute, {@code false} * otherwise. */ public boolean hasMaxValue() { return (maxValue != null); } /** {@collect.stats} * Tests whether {@code obj} is a valid value for the attribute * described by this {@code OpenMBeanAttributeInfoSupport} * instance. * * @param obj the object to be tested. * * @return {@code true} if {@code obj} is a valid value for * the parameter described by this {@code * OpenMBeanAttributeInfoSupport} instance, {@code false} * otherwise. */ public boolean isValue(Object obj) { return isValue(this, obj); } @SuppressWarnings("unchecked") // cast to Comparable static boolean isValue(OpenMBeanParameterInfo info, Object obj) { if (info.hasDefaultValue() && obj == null) return true; return info.getOpenType().isValue(obj) && (!info.hasLegalValues() || info.getLegalValues().contains(obj)) && (!info.hasMinValue() || ((Comparable) info.getMinValue()).compareTo(obj) <= 0) && (!info.hasMaxValue() || ((Comparable) info.getMaxValue()).compareTo(obj) >= 0); } /* *** Commodity methods from java.lang.Object *** */ /** {@collect.stats} * Compares the specified {@code obj} parameter with this {@code * OpenMBeanAttributeInfoSupport} instance for equality. * <p> * Returns {@code true} if and only if all of the following statements are true: * <ul> * <li>{@code obj} is non null,</li> * <li>{@code obj} also implements the {@code OpenMBeanAttributeInfo} interface,</li> * <li>their names are equal</li> * <li>their open types are equal</li> * <li>their access properties (isReadable, isWritable and isIs) are equal</li> * <li>their default, min, max and legal values are equal.</li> * </ul> * This ensures that this {@code equals} method works properly for * {@code obj} parameters which are different implementations of * the {@code OpenMBeanAttributeInfo} interface. * * <p>If {@code obj} also implements {@link DescriptorRead}, then its * {@link DescriptorRead#getDescriptor() getDescriptor()} method must * also return the same value as for this object.</p> * * @param obj the object to be compared for equality with this * {@code OpenMBeanAttributeInfoSupport} instance. * * @return {@code true} if the specified object is equal to this * {@code OpenMBeanAttributeInfoSupport} instance. */ public boolean equals(Object obj) { if (!(obj instanceof OpenMBeanAttributeInfo)) return false; OpenMBeanAttributeInfo other = (OpenMBeanAttributeInfo) obj; return this.isReadable() == other.isReadable() && this.isWritable() == other.isWritable() && this.isIs() == other.isIs() && equal(this, other); } static boolean equal(OpenMBeanParameterInfo x1, OpenMBeanParameterInfo x2) { if (x1 instanceof DescriptorRead) { if (!(x2 instanceof DescriptorRead)) return false; Descriptor d1 = ((DescriptorRead) x1).getDescriptor(); Descriptor d2 = ((DescriptorRead) x2).getDescriptor(); if (!d1.equals(d2)) return false; } else if (x2 instanceof DescriptorRead) return false; return x1.getName().equals(x2.getName()) && x1.getOpenType().equals(x2.getOpenType()) && (x1.hasDefaultValue() ? x1.getDefaultValue().equals(x2.getDefaultValue()) : !x2.hasDefaultValue()) && (x1.hasMinValue() ? x1.getMinValue().equals(x2.getMinValue()) : !x2.hasMinValue()) && (x1.hasMaxValue() ? x1.getMaxValue().equals(x2.getMaxValue()) : !x2.hasMaxValue()) && (x1.hasLegalValues() ? x1.getLegalValues().equals(x2.getLegalValues()) : !x2.hasLegalValues()); } /** {@collect.stats} * <p>Returns the hash code value for this {@code * OpenMBeanAttributeInfoSupport} instance.</p> * * <p>The hash code of an {@code OpenMBeanAttributeInfoSupport} * instance is the sum of the hash codes of all elements of * information used in {@code equals} comparisons (ie: its name, * its <i>open type</i>, its default, min, max and legal * values, and its Descriptor). * * <p>This ensures that {@code t1.equals(t2)} implies that {@code * t1.hashCode()==t2.hashCode()} for any two {@code * OpenMBeanAttributeInfoSupport} instances {@code t1} and {@code * t2}, as required by the general contract of the method {@link * Object#hashCode() Object.hashCode()}. * * <p>However, note that another instance of a class implementing * the {@code OpenMBeanAttributeInfo} interface may be equal to * this {@code OpenMBeanAttributeInfoSupport} instance as defined * by {@link #equals(java.lang.Object)}, but may have a different * hash code if it is calculated differently. * * <p>As {@code OpenMBeanAttributeInfoSupport} instances are * immutable, the hash code for this instance is calculated once, * on the first call to {@code hashCode}, and then the same value * is returned for subsequent calls. * * @return the hash code value for this {@code * OpenMBeanAttributeInfoSupport} instance */ public int hashCode() { // Calculate the hash code value if it has not yet been done // (ie 1st call to hashCode()) // if (myHashCode == null) myHashCode = hashCode(this); // return always the same hash code for this instance (immutable) // return myHashCode.intValue(); } static int hashCode(OpenMBeanParameterInfo info) { int value = 0; value += info.getName().hashCode(); value += info.getOpenType().hashCode(); if (info.hasDefaultValue()) value += info.getDefaultValue().hashCode(); if (info.hasMinValue()) value += info.getMinValue().hashCode(); if (info.hasMaxValue()) value += info.getMaxValue().hashCode(); if (info.hasLegalValues()) value += info.getLegalValues().hashCode(); if (info instanceof DescriptorRead) value += ((DescriptorRead) info).getDescriptor().hashCode(); return value; } /** {@collect.stats} * Returns a string representation of this * {@code OpenMBeanAttributeInfoSupport} instance. * <p> * The string representation consists of the name of this class (i.e. * {@code javax.management.openmbean.OpenMBeanAttributeInfoSupport}), * the string representation of the name and open type of the * described parameter, the string representation of its * default, min, max and legal values and the string * representation of its descriptor. * * <p>As {@code OpenMBeanAttributeInfoSupport} instances are * immutable, the string representation for this instance is * calculated once, on the first call to {@code toString}, and * then the same value is returned for subsequent calls. * * @return a string representation of this * {@code OpenMBeanAttributeInfoSupport} instance. */ public String toString() { // Calculate the string value if it has not yet been done // (ie 1st call to toString()) // if (myToString == null) myToString = toString(this); // return always the same string representation for this // instance (immutable) // return myToString; } static String toString(OpenMBeanParameterInfo info) { Descriptor d = (info instanceof DescriptorRead) ? ((DescriptorRead) info).getDescriptor() : null; return info.getClass().getName() + "(name=" + info.getName() + ",openType=" + info.getOpenType() + ",default=" + info.getDefaultValue() + ",minValue=" + info.getMinValue() + ",maxValue=" + info.getMaxValue() + ",legalValues=" + info.getLegalValues() + ((d == null) ? "" : ",descriptor=" + d) + ")"; } }
Java
/* * Copyright (c) 2000, 2007, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management.openmbean; // java import // import java.io.InvalidObjectException; import java.io.ObjectStreamException; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Date; import java.util.Map; import java.util.HashMap; // jmx import // import javax.management.ObjectName; /** {@collect.stats} * The <code>SimpleType</code> class is the <i>open type</i> class whose instances describe * all <i>open data</i> values which are neither arrays, * nor {@link CompositeData <code>CompositeData</code>} values, * nor {@link TabularData <code>TabularData</code>} values. * It predefines all its possible instances as static fields, and has no public constructor. * <p> * Given a <code>SimpleType</code> instance describing values whose Java class name is <i>className</i>, * the internal fields corresponding to the name and description of this <code>SimpleType</code> instance * are also set to <i>className</i>. * In other words, its methods <code>getClassName</code>, <code>getTypeName</code> and <code>getDescription</code> * all return the same string value <i>className</i>. * * @since 1.5 */ public final class SimpleType<T> extends OpenType<T> { /* Serial version */ static final long serialVersionUID = 2215577471957694503L; // SimpleType instances. // IF YOU ADD A SimpleType, YOU MUST UPDATE OpenType and typeArray /** {@collect.stats} * The <code>SimpleType</code> instance describing values whose * Java class name is <code>java.lang.Void</code>. */ public static final SimpleType<Void> VOID = new SimpleType<Void>(Void.class); /** {@collect.stats} * The <code>SimpleType</code> instance describing values whose * Java class name is <code>java.lang.Boolean</code>. */ public static final SimpleType<Boolean> BOOLEAN = new SimpleType<Boolean>(Boolean.class); /** {@collect.stats} * The <code>SimpleType</code> instance describing values whose * Java class name is <code>java.lang.Character</code>. */ public static final SimpleType<Character> CHARACTER = new SimpleType<Character>(Character.class); /** {@collect.stats} * The <code>SimpleType</code> instance describing values whose * Java class name is <code>java.lang.Byte</code>. */ public static final SimpleType<Byte> BYTE = new SimpleType<Byte>(Byte.class); /** {@collect.stats} * The <code>SimpleType</code> instance describing values whose * Java class name is <code>java.lang.Short</code>. */ public static final SimpleType<Short> SHORT = new SimpleType<Short>(Short.class); /** {@collect.stats} * The <code>SimpleType</code> instance describing values whose * Java class name is <code>java.lang.Integer</code>. */ public static final SimpleType<Integer> INTEGER = new SimpleType<Integer>(Integer.class); /** {@collect.stats} * The <code>SimpleType</code> instance describing values whose * Java class name is <code>java.lang.Long</code>. */ public static final SimpleType<Long> LONG = new SimpleType<Long>(Long.class); /** {@collect.stats} * The <code>SimpleType</code> instance describing values whose * Java class name is <code>java.lang.Float</code>. */ public static final SimpleType<Float> FLOAT = new SimpleType<Float>(Float.class); /** {@collect.stats} * The <code>SimpleType</code> instance describing values whose * Java class name is <code>java.lang.Double</code>. */ public static final SimpleType<Double> DOUBLE = new SimpleType<Double>(Double.class); /** {@collect.stats} * The <code>SimpleType</code> instance describing values whose * Java class name is <code>java.lang.String</code>. */ public static final SimpleType<String> STRING = new SimpleType<String>(String.class); /** {@collect.stats} * The <code>SimpleType</code> instance describing values whose * Java class name is <code>java.math.BigDecimal</code>. */ public static final SimpleType<BigDecimal> BIGDECIMAL = new SimpleType<BigDecimal>(BigDecimal.class); /** {@collect.stats} * The <code>SimpleType</code> instance describing values whose * Java class name is <code>java.math.BigInteger</code>. */ public static final SimpleType<BigInteger> BIGINTEGER = new SimpleType<BigInteger>(BigInteger.class); /** {@collect.stats} * The <code>SimpleType</code> instance describing values whose * Java class name is <code>java.util.Date</code>. */ public static final SimpleType<Date> DATE = new SimpleType<Date>(Date.class); /** {@collect.stats} * The <code>SimpleType</code> instance describing values whose * Java class name is <code>javax.management.ObjectName</code>. */ public static final SimpleType<ObjectName> OBJECTNAME = new SimpleType<ObjectName>(ObjectName.class); private static final SimpleType[] typeArray = { VOID, BOOLEAN, CHARACTER, BYTE, SHORT, INTEGER, LONG, FLOAT, DOUBLE, STRING, BIGDECIMAL, BIGINTEGER, DATE, OBJECTNAME, }; private transient Integer myHashCode = null; // As this instance is immutable, these two values private transient String myToString = null; // need only be calculated once. /* *** Constructor *** */ private SimpleType(Class<T> valueClass) { super(valueClass.getName(), valueClass.getName(), valueClass.getName(), false); } /* *** SimpleType specific information methods *** */ /** {@collect.stats} * Tests whether <var>obj</var> is a value for this * <code>SimpleType</code> instance. <p> This method returns * <code>true</code> if and only if <var>obj</var> is not null and * <var>obj</var>'s class name is the same as the className field * defined for this <code>SimpleType</code> instance (ie the class * name returned by the {@link OpenType#getClassName() * getClassName} method). * * @param obj the object to be tested. * * @return <code>true</code> if <var>obj</var> is a value for this * <code>SimpleType</code> instance. */ public boolean isValue(Object obj) { // if obj is null, return false // if (obj == null) { return false; } // Test if obj's class name is the same as for this instance // return this.getClassName().equals(obj.getClass().getName()); } /* *** Methods overriden from class Object *** */ /** {@collect.stats} * Compares the specified <code>obj</code> parameter with this <code>SimpleType</code> instance for equality. * <p> * Two <code>SimpleType</code> instances are equal if and only if their * {@link OpenType#getClassName() getClassName} methods return the same value. * * @param obj the object to be compared for equality with this <code>SimpleType</code> instance; * if <var>obj</var> is <code>null</code> or is not an instance of the class <code>SimpleType</code>, * <code>equals</code> returns <code>false</code>. * * @return <code>true</code> if the specified object is equal to this <code>SimpleType</code> instance. */ public boolean equals(Object obj) { /* If it weren't for readReplace(), we could replace this method with just: return (this == obj); */ if (!(obj instanceof SimpleType)) return false; SimpleType other = (SimpleType) obj; // Test if other's className field is the same as for this instance // return this.getClassName().equals(other.getClassName()); } /** {@collect.stats} * Returns the hash code value for this <code>SimpleType</code> instance. * The hash code of a <code>SimpleType</code> instance is the the hash code of * the string value returned by the {@link OpenType#getClassName() getClassName} method. * <p> * As <code>SimpleType</code> instances are immutable, the hash code for this instance is calculated once, * on the first call to <code>hashCode</code>, and then the same value is returned for subsequent calls. * * @return the hash code value for this <code>SimpleType</code> instance */ public int hashCode() { // Calculate the hash code value if it has not yet been done (ie 1st call to hashCode()) // if (myHashCode == null) { myHashCode = new Integer(this.getClassName().hashCode()); } // return always the same hash code for this instance (immutable) // return myHashCode.intValue(); } /** {@collect.stats} * Returns a string representation of this <code>SimpleType</code> instance. * <p> * The string representation consists of * the name of this class (ie <code>javax.management.openmbean.SimpleType</code>) and the type name * for this instance (which is the java class name of the values this <code>SimpleType</code> instance represents). * <p> * As <code>SimpleType</code> instances are immutable, the string representation for this instance is calculated once, * on the first call to <code>toString</code>, and then the same value is returned for subsequent calls. * * @return a string representation of this <code>SimpleType</code> instance */ public String toString() { // Calculate the string representation if it has not yet been done (ie 1st call to toString()) // if (myToString == null) { myToString = this.getClass().getName()+ "(name="+ getTypeName() +")"; } // return always the same string representation for this instance (immutable) // return myToString; } private static final Map<SimpleType,SimpleType> canonicalTypes = new HashMap<SimpleType,SimpleType>(); static { for (int i = 0; i < typeArray.length; i++) { final SimpleType type = typeArray[i]; canonicalTypes.put(type, type); } } /** {@collect.stats} * Replace an object read from an {@link * java.io.ObjectInputStream} with the unique instance for that * value. * * @return the replacement object. * * @exception ObjectStreamException if the read object cannot be * resolved. */ public Object readResolve() throws ObjectStreamException { final SimpleType canonical = canonicalTypes.get(this); if (canonical == null) { // Should not happen throw new InvalidObjectException("Invalid SimpleType: " + this); } return canonical; } }
Java
/* * Copyright (c) 2000, 2007, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management.openmbean; // java import // // jmx import // import javax.management.MBeanAttributeInfo; import javax.management.MBeanOperationInfo; import javax.management.MBeanConstructorInfo; import javax.management.MBeanNotificationInfo; /** {@collect.stats} * <p>Describes an Open MBean: an Open MBean is recognized as such if * its {@link javax.management.DynamicMBean#getMBeanInfo() * getMBeanInfo()} method returns an instance of a class which * implements the {@link OpenMBeanInfo} interface, typically {@link * OpenMBeanInfoSupport}.</p> * * <p>This interface declares the same methods as the class {@link * javax.management.MBeanInfo}. A class implementing this interface * (typically {@link OpenMBeanInfoSupport}) should extend {@link * javax.management.MBeanInfo}.</p> * * <p>The {@link #getAttributes()}, {@link #getOperations()} and * {@link #getConstructors()} methods of the implementing class should * return at runtime an array of instances of a subclass of {@link * MBeanAttributeInfo}, {@link MBeanOperationInfo} or {@link * MBeanConstructorInfo} respectively which implement the {@link * OpenMBeanAttributeInfo}, {@link OpenMBeanOperationInfo} or {@link * OpenMBeanConstructorInfo} interface respectively. * * * @since 1.5 */ public interface OpenMBeanInfo { // Re-declares the methods that are in class MBeanInfo of JMX 1.0 // (methods will be removed when MBeanInfo is made a parent interface of this interface) /** {@collect.stats} * Returns the fully qualified Java class name of the open MBean * instances this <tt>OpenMBeanInfo</tt> describes. * * @return the class name. */ public String getClassName() ; /** {@collect.stats} * Returns a human readable description of the type of open MBean * instances this <tt>OpenMBeanInfo</tt> describes. * * @return the description. */ public String getDescription() ; /** {@collect.stats} * Returns an array of <tt>OpenMBeanAttributeInfo</tt> instances * describing each attribute in the open MBean described by this * <tt>OpenMBeanInfo</tt> instance. Each instance in the returned * array should actually be a subclass of * <tt>MBeanAttributeInfo</tt> which implements the * <tt>OpenMBeanAttributeInfo</tt> interface (typically {@link * OpenMBeanAttributeInfoSupport}). * * @return the attribute array. */ public MBeanAttributeInfo[] getAttributes() ; /** {@collect.stats} * Returns an array of <tt>OpenMBeanOperationInfo</tt> instances * describing each operation in the open MBean described by this * <tt>OpenMBeanInfo</tt> instance. Each instance in the returned * array should actually be a subclass of * <tt>MBeanOperationInfo</tt> which implements the * <tt>OpenMBeanOperationInfo</tt> interface (typically {@link * OpenMBeanOperationInfoSupport}). * * @return the operation array. */ public MBeanOperationInfo[] getOperations() ; /** {@collect.stats} * Returns an array of <tt>OpenMBeanConstructorInfo</tt> instances * describing each constructor in the open MBean described by this * <tt>OpenMBeanInfo</tt> instance. Each instance in the returned * array should actually be a subclass of * <tt>MBeanConstructorInfo</tt> which implements the * <tt>OpenMBeanConstructorInfo</tt> interface (typically {@link * OpenMBeanConstructorInfoSupport}). * * @return the constructor array. */ public MBeanConstructorInfo[] getConstructors() ; /** {@collect.stats} * Returns an array of <tt>MBeanNotificationInfo</tt> instances * describing each notification emitted by the open MBean * described by this <tt>OpenMBeanInfo</tt> instance. * * @return the notification array. */ public MBeanNotificationInfo[] getNotifications() ; // commodity methods // /** {@collect.stats} * Compares the specified <var>obj</var> parameter with this <code>OpenMBeanInfo</code> instance for equality. * <p> * Returns <tt>true</tt> if and only if all of the following statements are true: * <ul> * <li><var>obj</var> is non null,</li> * <li><var>obj</var> also implements the <code>OpenMBeanInfo</code> interface,</li> * <li>their class names are equal</li> * <li>their infos on attributes, constructors, operations and notifications are equal</li> * </ul> * This ensures that this <tt>equals</tt> method works properly for <var>obj</var> parameters which are * different implementations of the <code>OpenMBeanInfo</code> interface. * <br>&nbsp; * @param obj the object to be compared for equality with this <code>OpenMBeanInfo</code> instance; * * @return <code>true</code> if the specified object is equal to this <code>OpenMBeanInfo</code> instance. */ public boolean equals(Object obj); /** {@collect.stats} * Returns the hash code value for this <code>OpenMBeanInfo</code> instance. * <p> * The hash code of an <code>OpenMBeanInfo</code> instance is the sum of the hash codes * of all elements of information used in <code>equals</code> comparisons * (ie: its class name, and its infos on attributes, constructors, operations and notifications, * where the hashCode of each of these arrays is calculated by a call to * <tt>new java.util.HashSet(java.util.Arrays.asList(this.getSignature)).hashCode()</tt>). * <p> * This ensures that <code> t1.equals(t2) </code> implies that <code> t1.hashCode()==t2.hashCode() </code> * for any two <code>OpenMBeanInfo</code> instances <code>t1</code> and <code>t2</code>, * as required by the general contract of the method * {@link Object#hashCode() Object.hashCode()}. * <p> * * @return the hash code value for this <code>OpenMBeanInfo</code> instance */ public int hashCode(); /** {@collect.stats} * Returns a string representation of this <code>OpenMBeanInfo</code> instance. * <p> * The string representation consists of the name of this class (ie <code>javax.management.openmbean.OpenMBeanInfo</code>), * the MBean class name, * and the string representation of infos on attributes, constructors, operations and notifications of the described MBean. * * @return a string representation of this <code>OpenMBeanInfo</code> instance */ public String toString(); }
Java
/* * Copyright (c) 2000, 2007, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management.openmbean; // java import // import java.util.Collection; // jmx import // /** {@collect.stats} * The <tt>CompositeData</tt> interface specifies the behavior of a specific type of complex <i>open data</i> objects * which represent <i>composite data</i> structures. * * * @since 1.5 */ public interface CompositeData { /** {@collect.stats} * Returns the <i>composite type </i> of this <i>composite data</i> instance. * * @return the type of this CompositeData. */ public CompositeType getCompositeType(); /** {@collect.stats} * Returns the value of the item whose name is <tt>key</tt>. * * @param key the name of the item. * * @return the value associated with this key. * * @throws IllegalArgumentException if <tt>key</tt> is a null or empty String. * * @throws InvalidKeyException if <tt>key</tt> is not an existing item name for this <tt>CompositeData</tt> instance. */ public Object get(String key) ; /** {@collect.stats} * Returns an array of the values of the items whose names are specified by <tt>keys</tt>, in the same order as <tt>keys</tt>. * * @param keys the names of the items. * * @return the values corresponding to the keys. * * @throws IllegalArgumentException if an element in <tt>keys</tt> is a null or empty String. * * @throws InvalidKeyException if an element in <tt>keys</tt> is not an existing item name for this <tt>CompositeData</tt> instance. */ public Object[] getAll(String[] keys) ; /** {@collect.stats} * Returns <tt>true</tt> if and only if this <tt>CompositeData</tt> instance contains * an item whose name is <tt>key</tt>. * If <tt>key</tt> is a null or empty String, this method simply returns false. * * @param key the key to be tested. * * @return true if this <tt>CompositeData</tt> contains the key. */ public boolean containsKey(String key) ; /** {@collect.stats} * Returns <tt>true</tt> if and only if this <tt>CompositeData</tt> instance contains an item * whose value is <tt>value</tt>. * * @param value the value to be tested. * * @return true if this <tt>CompositeData</tt> contains the value. */ public boolean containsValue(Object value) ; /** {@collect.stats} * Returns an unmodifiable Collection view of the item values contained in this <tt>CompositeData</tt> instance. * The returned collection's iterator will return the values in the ascending lexicographic order of the corresponding * item names. * * @return the values. */ public Collection<?> values() ; /** {@collect.stats} * Compares the specified <var>obj</var> parameter with this * <code>CompositeData</code> instance for equality. * <p> * Returns <tt>true</tt> if and only if all of the following statements are true: * <ul> * <li><var>obj</var> is non null,</li> * <li><var>obj</var> also implements the <code>CompositeData</code> interface,</li> * <li>their composite types are equal</li> * <li>their contents, i.e. (name, value) pairs are equal. If a value contained in * the content is an array, the value comparison is done as if by calling * the {@link java.util.Arrays#deepEquals(Object[], Object[]) deepEquals} method * for arrays of object reference types or the appropriate overloading of * {@code Arrays.equals(e1,e2)} for arrays of primitive types</li> * </ul> * <p> * This ensures that this <tt>equals</tt> method works properly for * <var>obj</var> parameters which are different implementations of the * <code>CompositeData</code> interface, with the restrictions mentioned in the * {@link java.util.Collection#equals(Object) equals} * method of the <tt>java.util.Collection</tt> interface. * * @param obj the object to be compared for equality with this * <code>CompositeData</code> instance. * @return <code>true</code> if the specified object is equal to this * <code>CompositeData</code> instance. */ public boolean equals(Object obj) ; /** {@collect.stats} * Returns the hash code value for this <code>CompositeData</code> instance. * <p> * The hash code of a <code>CompositeData</code> instance is the sum of the hash codes * of all elements of information used in <code>equals</code> comparisons * (ie: its <i>composite type</i> and all the item values). * <p> * This ensures that <code> t1.equals(t2) </code> implies that <code> t1.hashCode()==t2.hashCode() </code> * for any two <code>CompositeData</code> instances <code>t1</code> and <code>t2</code>, * as required by the general contract of the method * {@link Object#hashCode() Object.hashCode()}. * <p> * Each item value's hash code is added to the returned hash code. * If an item value is an array, * its hash code is obtained as if by calling the * {@link java.util.Arrays#deepHashCode(Object[]) deepHashCode} method * for arrays of object reference types or the appropriate overloading * of {@code Arrays.hashCode(e)} for arrays of primitive types. * * @return the hash code value for this <code>CompositeData</code> instance */ public int hashCode() ; /** {@collect.stats} * Returns a string representation of this <code>CompositeData</code> instance. * <p> * The string representation consists of the name of the implementing class, * the string representation of the composite type of this instance, and the string representation of the contents * (ie list the itemName=itemValue mappings). * * @return a string representation of this <code>CompositeData</code> instance */ public String toString() ; }
Java
/* * Copyright (c) 2000, 2007, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management.openmbean; // java import // import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; // jmx import // /** {@collect.stats} * The <code>TabularType</code> class is the <i> open type</i> class * whose instances describe the types of {@link TabularData <code>TabularData</code>} values. * * @since 1.5 */ public class TabularType extends OpenType<TabularData> { /* Serial version */ static final long serialVersionUID = 6554071860220659261L; /** {@collect.stats} * @serial The composite type of rows */ private CompositeType rowType; /** {@collect.stats} * @serial The items used to index each row element, kept in the order the user gave * This is an unmodifiable {@link ArrayList} */ private List<String> indexNames; private transient Integer myHashCode = null; // As this instance is immutable, these two values private transient String myToString = null; // need only be calculated once. /* *** Constructor *** */ /** {@collect.stats} * Constructs a <code>TabularType</code> instance, checking for the validity of the given parameters. * The validity constraints are described below for each parameter. * <p> * The Java class name of tabular data values this tabular type represents * (ie the class name returned by the {@link OpenType#getClassName() getClassName} method) * is set to the string value returned by <code>TabularData.class.getName()</code>. * <p> * @param typeName The name given to the tabular type this instance represents; cannot be a null or empty string. * <br>&nbsp; * @param description The human readable description of the tabular type this instance represents; * cannot be a null or empty string. * <br>&nbsp; * @param rowType The type of the row elements of tabular data values described by this tabular type instance; * cannot be null. * <br>&nbsp; * @param indexNames The names of the items the values of which are used to uniquely index each row element in the * tabular data values described by this tabular type instance; * cannot be null or empty. Each element should be an item name defined in <var>rowType</var> * (no null or empty string allowed). * It is important to note that the <b>order</b> of the item names in <var>indexNames</var> * is used by the methods {@link TabularData#get(java.lang.Object[]) <code>get</code>} and * {@link TabularData#remove(java.lang.Object[]) <code>remove</code>} of class * <code>TabularData</code> to match their array of values parameter to items. * <br>&nbsp; * @throws IllegalArgumentException if <var>rowType</var> is null, * or <var>indexNames</var> is a null or empty array, * or an element in <var>indexNames</var> is a null or empty string, * or <var>typeName</var> or <var>description</var> is a null or empty string. * <br>&nbsp; * @throws OpenDataException if an element's value of <var>indexNames</var> * is not an item name defined in <var>rowType</var>. */ public TabularType(String typeName, String description, CompositeType rowType, String[] indexNames) throws OpenDataException { // Check and initialize state defined by parent. // super(TabularData.class.getName(), typeName, description, false); // Check rowType is not null // if (rowType == null) { throw new IllegalArgumentException("Argument rowType cannot be null."); } // Check indexNames is neither null nor empty and does not contain any null element or empty string // checkForNullElement(indexNames, "indexNames"); checkForEmptyString(indexNames, "indexNames"); // Check all indexNames values are valid item names for rowType // for (int i=0; i<indexNames.length; i++) { if ( ! rowType.containsKey(indexNames[i]) ) { throw new OpenDataException("Argument's element value indexNames["+ i +"]=\""+ indexNames[i] + "\" is not a valid item name for rowType."); } } // initialize rowType // this.rowType = rowType; // initialize indexNames (copy content so that subsequent // modifs to the array referenced by the indexNames parameter // have no impact) // List<String> tmpList = new ArrayList<String>(indexNames.length + 1); for (int i=0; i<indexNames.length; i++) { tmpList.add(indexNames[i]); } this.indexNames = Collections.unmodifiableList(tmpList); } /** {@collect.stats} * Checks that Object[] arg is neither null nor empty (ie length==0) * and that it does not contain any null element. */ private static void checkForNullElement(Object[] arg, String argName) { if ( (arg == null) || (arg.length == 0) ) { throw new IllegalArgumentException("Argument "+ argName +"[] cannot be null or empty."); } for (int i=0; i<arg.length; i++) { if (arg[i] == null) { throw new IllegalArgumentException("Argument's element "+ argName +"["+ i +"] cannot be null."); } } } /** {@collect.stats} * Checks that String[] does not contain any empty (or blank characters only) string. */ private static void checkForEmptyString(String[] arg, String argName) { for (int i=0; i<arg.length; i++) { if (arg[i].trim().equals("")) { throw new IllegalArgumentException("Argument's element "+ argName +"["+ i +"] cannot be an empty string."); } } } /* *** Tabular type specific information methods *** */ /** {@collect.stats} * Returns the type of the row elements of tabular data values * described by this <code>TabularType</code> instance. * * @return the type of each row. */ public CompositeType getRowType() { return rowType; } /** {@collect.stats} * <p>Returns, in the same order as was given to this instance's * constructor, an unmodifiable List of the names of the items the * values of which are used to uniquely index each row element of * tabular data values described by this <code>TabularType</code> * instance.</p> * * @return a List of String representing the names of the index * items. * */ public List<String> getIndexNames() { return indexNames; } /** {@collect.stats} * Tests whether <var>obj</var> is a value which could be * described by this <code>TabularType</code> instance. * * <p>If <var>obj</var> is null or is not an instance of * <code>javax.management.openmbean.TabularData</code>, * <code>isValue</code> returns <code>false</code>.</p> * * <p>If <var>obj</var> is an instance of * <code>javax.management.openmbean.TabularData</code>, say {@code * td}, the result is true if this {@code TabularType} is * <em>assignable from</em> {@link TabularData#getTabularType() * td.getTabularType()}, as defined in {@link * CompositeType#isValue CompositeType.isValue}.</p> * * @param obj the value whose open type is to be tested for * compatibility with this <code>TabularType</code> instance. * * @return <code>true</code> if <var>obj</var> is a value for this * tabular type, <code>false</code> otherwise. */ public boolean isValue(Object obj) { // if obj is null or not a TabularData, return false // if (!(obj instanceof TabularData)) return false; // if obj is not a TabularData, return false // TabularData value = (TabularData) obj; TabularType valueType = value.getTabularType(); return isAssignableFrom(valueType); } @Override boolean isAssignableFrom(OpenType ot) { if (!(ot instanceof TabularType)) return false; TabularType tt = (TabularType) ot; if (!getTypeName().equals(tt.getTypeName()) || !getIndexNames().equals(tt.getIndexNames())) return false; return getRowType().isAssignableFrom(tt.getRowType()); } /* *** Methods overriden from class Object *** */ /** {@collect.stats} * Compares the specified <code>obj</code> parameter with this <code>TabularType</code> instance for equality. * <p> * Two <code>TabularType</code> instances are equal if and only if all of the following statements are true: * <ul> * <li>their type names are equal</li> * <li>their row types are equal</li> * <li>they use the same index names, in the same order</li> * </ul> * <br>&nbsp; * @param obj the object to be compared for equality with this <code>TabularType</code> instance; * if <var>obj</var> is <code>null</code>, <code>equals</code> returns <code>false</code>. * * @return <code>true</code> if the specified object is equal to this <code>TabularType</code> instance. */ public boolean equals(Object obj) { // if obj is null, return false // if (obj == null) { return false; } // if obj is not a TabularType, return false // TabularType other; try { other = (TabularType) obj; } catch (ClassCastException e) { return false; } // Now, really test for equality between this TabularType instance and the other: // // their names should be equal if ( ! this.getTypeName().equals(other.getTypeName()) ) { return false; } // their row types should be equal if ( ! this.rowType.equals(other.rowType) ) { return false; } // their index names should be equal and in the same order (ensured by List.equals()) if ( ! this.indexNames.equals(other.indexNames) ) { return false; } // All tests for equality were successfull // return true; } /** {@collect.stats} * Returns the hash code value for this <code>TabularType</code> instance. * <p> * The hash code of a <code>TabularType</code> instance is the sum of the hash codes * of all elements of information used in <code>equals</code> comparisons * (ie: name, row type, index names). * This ensures that <code> t1.equals(t2) </code> implies that <code> t1.hashCode()==t2.hashCode() </code> * for any two <code>TabularType</code> instances <code>t1</code> and <code>t2</code>, * as required by the general contract of the method * {@link Object#hashCode() Object.hashCode()}. * <p> * As <code>TabularType</code> instances are immutable, the hash code for this instance is calculated once, * on the first call to <code>hashCode</code>, and then the same value is returned for subsequent calls. * * @return the hash code value for this <code>TabularType</code> instance */ public int hashCode() { // Calculate the hash code value if it has not yet been done (ie 1st call to hashCode()) // if (myHashCode == null) { int value = 0; value += this.getTypeName().hashCode(); value += this.rowType.hashCode(); for (Iterator k = indexNames.iterator(); k.hasNext(); ) { value += k.next().hashCode(); } myHashCode = new Integer(value); } // return always the same hash code for this instance (immutable) // return myHashCode.intValue(); } /** {@collect.stats} * Returns a string representation of this <code>TabularType</code> instance. * <p> * The string representation consists of the name of this class (ie <code>javax.management.openmbean.TabularType</code>), * the type name for this instance, the row type string representation of this instance, * and the index names of this instance. * <p> * As <code>TabularType</code> instances are immutable, the string representation for this instance is calculated once, * on the first call to <code>toString</code>, and then the same value is returned for subsequent calls. * * @return a string representation of this <code>TabularType</code> instance */ public String toString() { // Calculate the string representation if it has not yet been done (ie 1st call to toString()) // if (myToString == null) { final StringBuilder result = new StringBuilder() .append(this.getClass().getName()) .append("(name=") .append(getTypeName()) .append(",rowType=") .append(rowType.toString()) .append(",indexNames=("); int i=0; Iterator k = indexNames.iterator(); while( k.hasNext() ) { if (i > 0) result.append(","); result.append(k.next().toString()); i++; } result.append("))"); myToString = result.toString(); } // return always the same string representation for this instance (immutable) // return myToString; } }
Java
/* * Copyright (c) 2000, 2007, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management.openmbean; // java import // // jmx import // import javax.management.MBeanParameterInfo; /** {@collect.stats} * <p>Describes an operation of an Open MBean.</p> * * <p>This interface declares the same methods as the class {@link * javax.management.MBeanOperationInfo}. A class implementing this * interface (typically {@link OpenMBeanOperationInfoSupport}) should * extend {@link javax.management.MBeanOperationInfo}.</p> * * <p>The {@link #getSignature()} method should return at runtime an * array of instances of a subclass of {@link MBeanParameterInfo} * which implements the {@link OpenMBeanParameterInfo} interface * (typically {@link OpenMBeanParameterInfoSupport}).</p> * * * @since 1.5 */ public interface OpenMBeanOperationInfo { // Re-declares fields and methods that are in class MBeanOperationInfo of JMX 1.0 // (fields and methods will be removed when MBeanOperationInfo is made a parent interface of this interface) /** {@collect.stats} * Returns a human readable description of the operation * described by this <tt>OpenMBeanOperationInfo</tt> instance. * * @return the description. */ public String getDescription() ; /** {@collect.stats} * Returns the name of the operation * described by this <tt>OpenMBeanOperationInfo</tt> instance. * * @return the name. */ public String getName() ; /** {@collect.stats} * Returns an array of <tt>OpenMBeanParameterInfo</tt> instances * describing each parameter in the signature of the operation * described by this <tt>OpenMBeanOperationInfo</tt> instance. * Each instance in the returned array should actually be a * subclass of <tt>MBeanParameterInfo</tt> which implements the * <tt>OpenMBeanParameterInfo</tt> interface (typically {@link * OpenMBeanParameterInfoSupport}). * * @return the signature. */ public MBeanParameterInfo[] getSignature() ; /** {@collect.stats} * Returns an <tt>int</tt> constant qualifying the impact of the * operation described by this <tt>OpenMBeanOperationInfo</tt> * instance. * * The returned constant is one of {@link * javax.management.MBeanOperationInfo#INFO}, {@link * javax.management.MBeanOperationInfo#ACTION}, {@link * javax.management.MBeanOperationInfo#ACTION_INFO}, or {@link * javax.management.MBeanOperationInfo#UNKNOWN}. * * @return the impact code. */ public int getImpact() ; /** {@collect.stats} * Returns the fully qualified Java class name of the values * returned by the operation described by this * <tt>OpenMBeanOperationInfo</tt> instance. This method should * return the same value as a call to * <tt>getReturnOpenType().getClassName()</tt>. * * @return the return type. */ public String getReturnType() ; // Now declares methods that are specific to open MBeans // /** {@collect.stats} * Returns the <i>open type</i> of the values returned by the * operation described by this <tt>OpenMBeanOperationInfo</tt> * instance. * * @return the return type. */ public OpenType<?> getReturnOpenType() ; // open MBean specific method // commodity methods // /** {@collect.stats} * Compares the specified <var>obj</var> parameter with this <code>OpenMBeanOperationInfo</code> instance for equality. * <p> * Returns <tt>true</tt> if and only if all of the following statements are true: * <ul> * <li><var>obj</var> is non null,</li> * <li><var>obj</var> also implements the <code>OpenMBeanOperationInfo</code> interface,</li> * <li>their names are equal</li> * <li>their signatures are equal</li> * <li>their return open types are equal</li> * <li>their impacts are equal</li> * </ul> * This ensures that this <tt>equals</tt> method works properly for <var>obj</var> parameters which are * different implementations of the <code>OpenMBeanOperationInfo</code> interface. * <br>&nbsp; * @param obj the object to be compared for equality with this <code>OpenMBeanOperationInfo</code> instance; * * @return <code>true</code> if the specified object is equal to this <code>OpenMBeanOperationInfo</code> instance. */ public boolean equals(Object obj); /** {@collect.stats} * Returns the hash code value for this <code>OpenMBeanOperationInfo</code> instance. * <p> * The hash code of an <code>OpenMBeanOperationInfo</code> instance is the sum of the hash codes * of all elements of information used in <code>equals</code> comparisons * (ie: its name, return open type, impact and signature, where the signature hashCode is calculated by a call to * <tt>java.util.Arrays.asList(this.getSignature).hashCode()</tt>). * <p> * This ensures that <code> t1.equals(t2) </code> implies that <code> t1.hashCode()==t2.hashCode() </code> * for any two <code>OpenMBeanOperationInfo</code> instances <code>t1</code> and <code>t2</code>, * as required by the general contract of the method * {@link Object#hashCode() Object.hashCode()}. * <p> * * @return the hash code value for this <code>OpenMBeanOperationInfo</code> instance */ public int hashCode(); /** {@collect.stats} * Returns a string representation of this <code>OpenMBeanOperationInfo</code> instance. * <p> * The string representation consists of the name of this class (ie <code>javax.management.openmbean.OpenMBeanOperationInfo</code>), * and the name, signature, return open type and impact of the described operation. * * @return a string representation of this <code>OpenMBeanOperationInfo</code> instance */ public String toString(); }
Java
/* * Copyright (c) 2000, 2007, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management.openmbean; // java import // import java.util.Arrays; import javax.management.Descriptor; import javax.management.ImmutableDescriptor; import javax.management.MBeanOperationInfo; import javax.management.MBeanParameterInfo; /** {@collect.stats} * Describes an operation of an Open MBean. * * * @since 1.5 */ public class OpenMBeanOperationInfoSupport extends MBeanOperationInfo implements OpenMBeanOperationInfo { /* Serial version */ static final long serialVersionUID = 4996859732565369366L; /** {@collect.stats} * @serial The <i>open type</i> of the values returned by the operation * described by this {@link OpenMBeanOperationInfo} instance * */ private OpenType<?> returnOpenType; // As this instance is immutable, // these two values need only be calculated once. private transient Integer myHashCode = null; private transient String myToString = null; /** {@collect.stats} * <p>Constructs an {@code OpenMBeanOperationInfoSupport} * instance, which describes the operation of a class of open * MBeans, with the specified {@code name}, {@code description}, * {@code signature}, {@code returnOpenType} and {@code * impact}.</p> * * <p>The {@code signature} array parameter is internally copied, * so that subsequent changes to the array referenced by {@code * signature} have no effect on this instance.</p> * * @param name cannot be a null or empty string. * * @param description cannot be a null or empty string. * * @param signature can be null or empty if there are no * parameters to describe. * * @param returnOpenType cannot be null: use {@code * SimpleType.VOID} for operations that return nothing. * * @param impact must be one of {@code ACTION}, {@code * ACTION_INFO}, {@code INFO}, or {@code UNKNOWN}. * * @throws IllegalArgumentException if {@code name} or {@code * description} are null or empty string, or {@code * returnOpenType} is null, or {@code impact} is not one of {@code * ACTION}, {@code ACTION_INFO}, {@code INFO}, or {@code UNKNOWN}. * * @throws ArrayStoreException If {@code signature} is not an * array of instances of a subclass of {@code MBeanParameterInfo}. */ public OpenMBeanOperationInfoSupport(String name, String description, OpenMBeanParameterInfo[] signature, OpenType<?> returnOpenType, int impact) { this(name, description, signature, returnOpenType, impact, (Descriptor) null); } /** {@collect.stats} * <p>Constructs an {@code OpenMBeanOperationInfoSupport} * instance, which describes the operation of a class of open * MBeans, with the specified {@code name}, {@code description}, * {@code signature}, {@code returnOpenType}, {@code * impact}, and {@code descriptor}.</p> * * <p>The {@code signature} array parameter is internally copied, * so that subsequent changes to the array referenced by {@code * signature} have no effect on this instance.</p> * * @param name cannot be a null or empty string. * * @param description cannot be a null or empty string. * * @param signature can be null or empty if there are no * parameters to describe. * * @param returnOpenType cannot be null: use {@code * SimpleType.VOID} for operations that return nothing. * * @param impact must be one of {@code ACTION}, {@code * ACTION_INFO}, {@code INFO}, or {@code UNKNOWN}. * * @param descriptor The descriptor for the operation. This may * be null, which is equivalent to an empty descriptor. * * @throws IllegalArgumentException if {@code name} or {@code * description} are null or empty string, or {@code * returnOpenType} is null, or {@code impact} is not one of {@code * ACTION}, {@code ACTION_INFO}, {@code INFO}, or {@code UNKNOWN}. * * @throws ArrayStoreException If {@code signature} is not an * array of instances of a subclass of {@code MBeanParameterInfo}. * * @since 1.6 */ public OpenMBeanOperationInfoSupport(String name, String description, OpenMBeanParameterInfo[] signature, OpenType<?> returnOpenType, int impact, Descriptor descriptor) { super(name, description, arrayCopyCast(signature), // must prevent NPE here - we will throw IAE later on if // returnOpenType is null (returnOpenType == null) ? null : returnOpenType.getClassName(), impact, ImmutableDescriptor.union(descriptor, // must prevent NPE here - we will throw IAE later on if // returnOpenType is null (returnOpenType==null) ? null :returnOpenType.getDescriptor())); // check parameters that should not be null or empty // (unfortunately it is not done in superclass :-( ! ) // if (name == null || name.trim().equals("")) { throw new IllegalArgumentException("Argument name cannot " + "be null or empty"); } if (description == null || description.trim().equals("")) { throw new IllegalArgumentException("Argument description cannot " + "be null or empty"); } if (returnOpenType == null) { throw new IllegalArgumentException("Argument returnOpenType " + "cannot be null"); } if (impact != ACTION && impact != ACTION_INFO && impact != INFO && impact != UNKNOWN) { throw new IllegalArgumentException("Argument impact can only be " + "one of ACTION, ACTION_INFO, " + "INFO, or UNKNOWN: " + impact); } this.returnOpenType = returnOpenType; } // Converts an array of OpenMBeanParameterInfo objects extending // MBeanParameterInfo into an array of MBeanParameterInfo. // private static MBeanParameterInfo[] arrayCopyCast(OpenMBeanParameterInfo[] src) { if (src == null) return null; MBeanParameterInfo[] dst = new MBeanParameterInfo[src.length]; System.arraycopy(src, 0, dst, 0, src.length); // may throw an ArrayStoreException return dst; } // Converts an array of MBeanParameterInfo objects implementing // OpenMBeanParameterInfo into an array of OpenMBeanParameterInfo. // private static OpenMBeanParameterInfo[] arrayCopyCast(MBeanParameterInfo[] src) { if (src == null) return null; OpenMBeanParameterInfo[] dst = new OpenMBeanParameterInfo[src.length]; System.arraycopy(src, 0, dst, 0, src.length); // may throw an ArrayStoreException return dst; } // [JF]: should we add constructor with java.lang.reflect.Method // method parameter ? would need to add consistency check between // OpenType<?> returnOpenType and method.getReturnType(). /** {@collect.stats} * Returns the <i>open type</i> of the values returned by the * operation described by this {@code OpenMBeanOperationInfo} * instance. */ public OpenType<?> getReturnOpenType() { return returnOpenType; } /* *** Commodity methods from java.lang.Object *** */ /** {@collect.stats} * <p>Compares the specified {@code obj} parameter with this * {@code OpenMBeanOperationInfoSupport} instance for * equality.</p> * * <p>Returns {@code true} if and only if all of the following * statements are true: * * <ul> * <li>{@code obj} is non null,</li> * <li>{@code obj} also implements the {@code * OpenMBeanOperationInfo} interface,</li> * <li>their names are equal</li> * <li>their signatures are equal</li> * <li>their return open types are equal</li> * <li>their impacts are equal</li> * </ul> * * This ensures that this {@code equals} method works properly for * {@code obj} parameters which are different implementations of * the {@code OpenMBeanOperationInfo} interface. * * @param obj the object to be compared for equality with this * {@code OpenMBeanOperationInfoSupport} instance; * * @return {@code true} if the specified object is equal to this * {@code OpenMBeanOperationInfoSupport} instance. */ public boolean equals(Object obj) { // if obj is null, return false // if (obj == null) { return false; } // if obj is not a OpenMBeanOperationInfo, return false // OpenMBeanOperationInfo other; try { other = (OpenMBeanOperationInfo) obj; } catch (ClassCastException e) { return false; } // Now, really test for equality between this // OpenMBeanOperationInfo implementation and the other: // // their Name should be equal if ( ! this.getName().equals(other.getName()) ) { return false; } // their Signatures should be equal if ( ! Arrays.equals(this.getSignature(), other.getSignature()) ) { return false; } // their return open types should be equal if ( ! this.getReturnOpenType().equals(other.getReturnOpenType()) ) { return false; } // their impacts should be equal if ( this.getImpact() != other.getImpact() ) { return false; } // All tests for equality were successfull // return true; } /** {@collect.stats} * <p>Returns the hash code value for this {@code * OpenMBeanOperationInfoSupport} instance.</p> * * <p>The hash code of an {@code OpenMBeanOperationInfoSupport} * instance is the sum of the hash codes of all elements of * information used in {@code equals} comparisons (ie: its name, * return open type, impact and signature, where the signature * hashCode is calculated by a call to {@code * java.util.Arrays.asList(this.getSignature).hashCode()}).</p> * * <p>This ensures that {@code t1.equals(t2) } implies that {@code * t1.hashCode()==t2.hashCode() } for any two {@code * OpenMBeanOperationInfoSupport} instances {@code t1} and {@code * t2}, as required by the general contract of the method {@link * Object#hashCode() Object.hashCode()}.</p> * * <p>However, note that another instance of a class implementing * the {@code OpenMBeanOperationInfo} interface may be equal to * this {@code OpenMBeanOperationInfoSupport} instance as defined * by {@link #equals(java.lang.Object)}, but may have a different * hash code if it is calculated differently.</p> * * <p>As {@code OpenMBeanOperationInfoSupport} instances are * immutable, the hash code for this instance is calculated once, * on the first call to {@code hashCode}, and then the same value * is returned for subsequent calls.</p> * * @return the hash code value for this {@code * OpenMBeanOperationInfoSupport} instance */ public int hashCode() { // Calculate the hash code value if it has not yet been done // (ie 1st call to hashCode()) // if (myHashCode == null) { int value = 0; value += this.getName().hashCode(); value += Arrays.asList(this.getSignature()).hashCode(); value += this.getReturnOpenType().hashCode(); value += this.getImpact(); myHashCode = new Integer(value); } // return always the same hash code for this instance (immutable) // return myHashCode.intValue(); } /** {@collect.stats} * <p>Returns a string representation of this {@code * OpenMBeanOperationInfoSupport} instance.</p> * * <p>The string representation consists of the name of this class * (ie {@code * javax.management.openmbean.OpenMBeanOperationInfoSupport}), and * the name, signature, return open type and impact of the * described operation and the string representation of its descriptor.</p> * * <p>As {@code OpenMBeanOperationInfoSupport} instances are * immutable, the string representation for this instance is * calculated once, on the first call to {@code toString}, and * then the same value is returned for subsequent calls.</p> * * @return a string representation of this {@code * OpenMBeanOperationInfoSupport} instance */ public String toString() { // Calculate the hash code value if it has not yet been done // (ie 1st call to toString()) // if (myToString == null) { myToString = new StringBuilder() .append(this.getClass().getName()) .append("(name=") .append(this.getName()) .append(",signature=") .append(Arrays.asList(this.getSignature()).toString()) .append(",return=") .append(this.getReturnOpenType().toString()) .append(",impact=") .append(this.getImpact()) .append(",descriptor=") .append(this.getDescriptor()) .append(")") .toString(); } // return always the same string representation for this // instance (immutable) // return myToString; } /** {@collect.stats} * An object serialized in a version of the API before Descriptors were * added to this class will have an empty or null Descriptor. * For consistency with our * behavior in this version, we must replace the object with one * where the Descriptors reflect the same value of returned openType. **/ private Object readResolve() { if (getDescriptor().getFieldNames().length == 0) { // This constructor will construct the expected default Descriptor. // return new OpenMBeanOperationInfoSupport( name, description, arrayCopyCast(getSignature()), returnOpenType, getImpact()); } else return this; } }
Java
/* * Copyright (c) 2000, 2007, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management.openmbean; // java import // import java.util.Set; import javax.management.Descriptor; import javax.management.DescriptorRead; // for Javadoc import javax.management.ImmutableDescriptor; import javax.management.MBeanParameterInfo; // OpenMBeanAttributeInfoSupport and this class are very similar // but can't easily be refactored because there's no multiple inheritance. // The best we can do for refactoring is to put a bunch of static methods // in OpenMBeanAttributeInfoSupport and import them here. import static javax.management.openmbean.OpenMBeanAttributeInfoSupport.*; /** {@collect.stats} * Describes a parameter used in one or more operations or * constructors of an open MBean. * * * @since 1.5 */ public class OpenMBeanParameterInfoSupport extends MBeanParameterInfo implements OpenMBeanParameterInfo { /* Serial version */ static final long serialVersionUID = -7235016873758443122L; /** {@collect.stats} * @serial The open mbean parameter's <i>open type</i> */ private OpenType<?> openType; /** {@collect.stats} * @serial The open mbean parameter's default value */ private Object defaultValue = null; /** {@collect.stats} * @serial The open mbean parameter's legal values. This {@link * Set} is unmodifiable */ private Set<?> legalValues = null; // to be constructed unmodifiable /** {@collect.stats} * @serial The open mbean parameter's min value */ private Comparable minValue = null; /** {@collect.stats} * @serial The open mbean parameter's max value */ private Comparable maxValue = null; // As this instance is immutable, these two values need only // be calculated once. private transient Integer myHashCode = null; // As this instance is immutable, these two values private transient String myToString = null; // need only be calculated once. /** {@collect.stats} * Constructs an {@code OpenMBeanParameterInfoSupport} instance, * which describes the parameter used in one or more operations or * constructors of a class of open MBeans, with the specified * {@code name}, {@code openType} and {@code description}. * * @param name cannot be a null or empty string. * * @param description cannot be a null or empty string. * * @param openType cannot be null. * * @throws IllegalArgumentException if {@code name} or {@code * description} are null or empty string, or {@code openType} is * null. */ public OpenMBeanParameterInfoSupport(String name, String description, OpenType<?> openType) { this(name, description, openType, (Descriptor) null); } /** {@collect.stats} * <p>Constructs an {@code OpenMBeanParameterInfoSupport} instance, * which describes the parameter used in one or more operations or * constructors of a class of open MBeans, with the specified * {@code name}, {@code openType}, {@code description}, * and {@code descriptor}.</p> * * <p>The {@code descriptor} can contain entries that will define * the values returned by certain methods of this class, as * explained in the {@link <a href="package-summary.html#constraints"> * package description</a>}. * * @param name cannot be a null or empty string. * * @param description cannot be a null or empty string. * * @param openType cannot be null. * * @param descriptor The descriptor for the parameter. This may be null * which is equivalent to an empty descriptor. * * @throws IllegalArgumentException if {@code name} or {@code * description} are null or empty string, or {@code openType} is * null, or the descriptor entries are invalid as described in the * {@link <a href="package-summary.html#constraints">package * description</a>}. * * @since 1.6 */ public OpenMBeanParameterInfoSupport(String name, String description, OpenType<?> openType, Descriptor descriptor) { // Construct parent's state // super(name, (openType==null) ? null : openType.getClassName(), description, ImmutableDescriptor.union(descriptor,(openType==null)?null: openType.getDescriptor())); // Initialize this instance's specific state // this.openType = openType; descriptor = getDescriptor(); // replace null by empty this.defaultValue = valueFrom(descriptor, "defaultValue", openType); this.legalValues = valuesFrom(descriptor, "legalValues", openType); this.minValue = comparableValueFrom(descriptor, "minValue", openType); this.maxValue = comparableValueFrom(descriptor, "maxValue", openType); try { check(this); } catch (OpenDataException e) { throw new IllegalArgumentException(e.getMessage(), e); } } /** {@collect.stats} * Constructs an {@code OpenMBeanParameterInfoSupport} instance, * which describes the parameter used in one or more operations or * constructors of a class of open MBeans, with the specified * {@code name}, {@code openType}, {@code description} and {@code * defaultValue}. * * @param name cannot be a null or empty string. * * @param description cannot be a null or empty string. * * @param openType cannot be null. * * @param defaultValue must be a valid value for the {@code * openType} specified for this parameter; default value not * supported for {@code ArrayType} and {@code TabularType}; can be * null, in which case it means that no default value is set. * * @param <T> allows the compiler to check that the {@code defaultValue}, * if non-null, has the correct Java type for the given {@code openType}. * * @throws IllegalArgumentException if {@code name} or {@code * description} are null or empty string, or {@code openType} is * null. * * @throws OpenDataException if {@code defaultValue} is not a * valid value for the specified {@code openType}, or {@code * defaultValue} is non null and {@code openType} is an {@code * ArrayType} or a {@code TabularType}. */ public <T> OpenMBeanParameterInfoSupport(String name, String description, OpenType<T> openType, T defaultValue) throws OpenDataException { this(name, description, openType, defaultValue, (T[]) null); } /** {@collect.stats} * <p>Constructs an {@code OpenMBeanParameterInfoSupport} instance, * which describes the parameter used in one or more operations or * constructors of a class of open MBeans, with the specified * {@code name}, {@code openType}, {@code description}, {@code * defaultValue} and {@code legalValues}.</p> * * <p>The contents of {@code legalValues} are copied, so subsequent * modifications of the array referenced by {@code legalValues} * have no impact on this {@code OpenMBeanParameterInfoSupport} * instance.</p> * * @param name cannot be a null or empty string. * * @param description cannot be a null or empty string. * * @param openType cannot be null. * * @param defaultValue must be a valid value for the {@code * openType} specified for this parameter; default value not * supported for {@code ArrayType} and {@code TabularType}; can be * null, in which case it means that no default value is set. * * @param legalValues each contained value must be valid for the * {@code openType} specified for this parameter; legal values not * supported for {@code ArrayType} and {@code TabularType}; can be * null or empty. * * @param <T> allows the compiler to check that the {@code * defaultValue} and {@code legalValues}, if non-null, have the * correct Java type for the given {@code openType}. * * @throws IllegalArgumentException if {@code name} or {@code * description} are null or empty string, or {@code openType} is * null. * * @throws OpenDataException if {@code defaultValue} is not a * valid value for the specified {@code openType}, or one value in * {@code legalValues} is not valid for the specified {@code * openType}, or {@code defaultValue} is non null and {@code * openType} is an {@code ArrayType} or a {@code TabularType}, or * {@code legalValues} is non null and non empty and {@code * openType} is an {@code ArrayType} or a {@code TabularType}, or * {@code legalValues} is non null and non empty and {@code * defaultValue} is not contained in {@code legalValues}. */ public <T> OpenMBeanParameterInfoSupport(String name, String description, OpenType<T> openType, T defaultValue, T[] legalValues) throws OpenDataException { this(name, description, openType, defaultValue, legalValues, null, null); } /** {@collect.stats} * Constructs an {@code OpenMBeanParameterInfoSupport} instance, * which describes the parameter used in one or more operations or * constructors of a class of open MBeans, with the specified * {@code name}, {@code openType}, {@code description}, {@code * defaultValue}, {@code minValue} and {@code maxValue}. * * It is possible to specify minimal and maximal values only for * an open type whose values are {@code Comparable}. * * @param name cannot be a null or empty string. * * @param description cannot be a null or empty string. * * @param openType cannot be null. * * @param defaultValue must be a valid value for the {@code * openType} specified for this parameter; default value not * supported for {@code ArrayType} and {@code TabularType}; can be * null, in which case it means that no default value is set. * * @param minValue must be valid for the {@code openType} * specified for this parameter; can be null, in which case it * means that no minimal value is set. * * @param maxValue must be valid for the {@code openType} * specified for this parameter; can be null, in which case it * means that no maximal value is set. * * @param <T> allows the compiler to check that the {@code * defaultValue}, {@code minValue}, and {@code maxValue}, if * non-null, have the correct Java type for the given {@code * openType}. * * @throws IllegalArgumentException if {@code name} or {@code * description} are null or empty string, or {@code openType} is * null. * * @throws OpenDataException if {@code defaultValue}, {@code * minValue} or {@code maxValue} is not a valid value for the * specified {@code openType}, or {@code defaultValue} is non null * and {@code openType} is an {@code ArrayType} or a {@code * TabularType}, or both {@code minValue} and {@code maxValue} are * non-null and {@code minValue.compareTo(maxValue) > 0} is {@code * true}, or both {@code defaultValue} and {@code minValue} are * non-null and {@code minValue.compareTo(defaultValue) > 0} is * {@code true}, or both {@code defaultValue} and {@code maxValue} * are non-null and {@code defaultValue.compareTo(maxValue) > 0} * is {@code true}. */ public <T> OpenMBeanParameterInfoSupport(String name, String description, OpenType<T> openType, T defaultValue, Comparable<T> minValue, Comparable<T> maxValue) throws OpenDataException { this(name, description, openType, defaultValue, null, minValue, maxValue); } private <T> OpenMBeanParameterInfoSupport(String name, String description, OpenType<T> openType, T defaultValue, T[] legalValues, Comparable<T> minValue, Comparable<T> maxValue) throws OpenDataException { super(name, (openType == null) ? null : openType.getClassName(), description, makeDescriptor(openType, defaultValue, legalValues, minValue, maxValue)); this.openType = openType; Descriptor d = getDescriptor(); this.defaultValue = defaultValue; this.minValue = minValue; this.maxValue = maxValue; // We already converted the array into an unmodifiable Set // in the descriptor. this.legalValues = (Set<?>) d.getFieldValue("legalValues"); check(this); } /** {@collect.stats} * An object serialized in a version of the API before Descriptors were * added to this class will have an empty or null Descriptor. * For consistency with our * behavior in this version, we must replace the object with one * where the Descriptors reflect the same values of openType, defaultValue, * etc. **/ private Object readResolve() { if (getDescriptor().getFieldNames().length == 0) { // This noise allows us to avoid "unchecked" warnings without // having to suppress them explicitly. OpenType<Object> xopenType = cast(openType); Set<Object> xlegalValues = cast(legalValues); Comparable<Object> xminValue = cast(minValue); Comparable<Object> xmaxValue = cast(maxValue); return new OpenMBeanParameterInfoSupport( name, description, openType, makeDescriptor(xopenType, defaultValue, xlegalValues, xminValue, xmaxValue)); } else return this; } /** {@collect.stats} * Returns the open type for the values of the parameter described * by this {@code OpenMBeanParameterInfoSupport} instance. */ public OpenType<?> getOpenType() { return openType; } /** {@collect.stats} * Returns the default value for the parameter described by this * {@code OpenMBeanParameterInfoSupport} instance, if specified, * or {@code null} otherwise. */ public Object getDefaultValue() { // Special case for ArrayType and TabularType // [JF] TODO: clone it so that it cannot be altered, // [JF] TODO: if we decide to support defaultValue as an array itself. // [JF] As of today (oct 2000) it is not supported so // defaultValue is null for arrays. Nothing to do. return defaultValue; } /** {@collect.stats} * Returns an unmodifiable Set of legal values for the parameter * described by this {@code OpenMBeanParameterInfoSupport} * instance, if specified, or {@code null} otherwise. */ public Set<?> getLegalValues() { // Special case for ArrayType and TabularType // [JF] TODO: clone values so that they cannot be altered, // [JF] TODO: if we decide to support LegalValues as an array itself. // [JF] As of today (oct 2000) it is not supported so // legalValues is null for arrays. Nothing to do. // Returns our legalValues Set (set was constructed unmodifiable) return (legalValues); } /** {@collect.stats} * Returns the minimal value for the parameter described by this * {@code OpenMBeanParameterInfoSupport} instance, if specified, * or {@code null} otherwise. */ public Comparable<?> getMinValue() { // Note: only comparable values have a minValue, so that's not // the case of arrays and tabulars (always null). return minValue; } /** {@collect.stats} * Returns the maximal value for the parameter described by this * {@code OpenMBeanParameterInfoSupport} instance, if specified, * or {@code null} otherwise. */ public Comparable<?> getMaxValue() { // Note: only comparable values have a maxValue, so that's not // the case of arrays and tabulars (always null). return maxValue; } /** {@collect.stats} * Returns {@code true} if this {@code * OpenMBeanParameterInfoSupport} instance specifies a non-null * default value for the described parameter, {@code false} * otherwise. */ public boolean hasDefaultValue() { return (defaultValue != null); } /** {@collect.stats} * Returns {@code true} if this {@code * OpenMBeanParameterInfoSupport} instance specifies a non-null * set of legal values for the described parameter, {@code false} * otherwise. */ public boolean hasLegalValues() { return (legalValues != null); } /** {@collect.stats} * Returns {@code true} if this {@code * OpenMBeanParameterInfoSupport} instance specifies a non-null * minimal value for the described parameter, {@code false} * otherwise. */ public boolean hasMinValue() { return (minValue != null); } /** {@collect.stats} * Returns {@code true} if this {@code * OpenMBeanParameterInfoSupport} instance specifies a non-null * maximal value for the described parameter, {@code false} * otherwise. */ public boolean hasMaxValue() { return (maxValue != null); } /** {@collect.stats} * Tests whether {@code obj} is a valid value for the parameter * described by this {@code OpenMBeanParameterInfo} instance. * * @param obj the object to be tested. * * @return {@code true} if {@code obj} is a valid value * for the parameter described by this * {@code OpenMBeanParameterInfo} instance, * {@code false} otherwise. */ public boolean isValue(Object obj) { return OpenMBeanAttributeInfoSupport.isValue(this, obj); // compiler bug? should be able to omit class name here // also below in toString and hashCode } /* *** Commodity methods from java.lang.Object *** */ /** {@collect.stats} * <p>Compares the specified {@code obj} parameter with this {@code * OpenMBeanParameterInfoSupport} instance for equality.</p> * * <p>Returns {@code true} if and only if all of the following * statements are true: * * <ul> * <li>{@code obj} is non null,</li> * <li>{@code obj} also implements the {@code OpenMBeanParameterInfo} * interface,</li> * <li>their names are equal</li> * <li>their open types are equal</li> * <li>their default, min, max and legal values are equal.</li> * </ul> * This ensures that this {@code equals} method works properly for * {@code obj} parameters which are different implementations of * the {@code OpenMBeanParameterInfo} interface. * * <p>If {@code obj} also implements {@link DescriptorRead}, then its * {@link DescriptorRead#getDescriptor() getDescriptor()} method must * also return the same value as for this object.</p> * * @param obj the object to be compared for equality with this * {@code OpenMBeanParameterInfoSupport} instance. * * @return {@code true} if the specified object is equal to this * {@code OpenMBeanParameterInfoSupport} instance. */ public boolean equals(Object obj) { if (!(obj instanceof OpenMBeanParameterInfo)) return false; OpenMBeanParameterInfo other = (OpenMBeanParameterInfo) obj; return equal(this, other); } /** {@collect.stats} * <p>Returns the hash code value for this {@code * OpenMBeanParameterInfoSupport} instance.</p> * * <p>The hash code of an {@code OpenMBeanParameterInfoSupport} * instance is the sum of the hash codes of all elements of * information used in {@code equals} comparisons (ie: its name, * its <i>open type</i>, its default, min, max and legal * values, and its Descriptor). * * <p>This ensures that {@code t1.equals(t2)} implies that {@code * t1.hashCode()==t2.hashCode()} for any two {@code * OpenMBeanParameterInfoSupport} instances {@code t1} and {@code * t2}, as required by the general contract of the method {@link * Object#hashCode() Object.hashCode()}. * * <p>However, note that another instance of a class implementing * the {@code OpenMBeanParameterInfo} interface may be equal to * this {@code OpenMBeanParameterInfoSupport} instance as defined * by {@link #equals(java.lang.Object)}, but may have a different * hash code if it is calculated differently. * * <p>As {@code OpenMBeanParameterInfoSupport} instances are * immutable, the hash code for this instance is calculated once, * on the first call to {@code hashCode}, and then the same value * is returned for subsequent calls. * * @return the hash code value for this {@code * OpenMBeanParameterInfoSupport} instance */ public int hashCode() { // Calculate the hash code value if it has not yet been done // (ie 1st call to hashCode()) // if (myHashCode == null) myHashCode = OpenMBeanAttributeInfoSupport.hashCode(this); // return always the same hash code for this instance (immutable) // return myHashCode.intValue(); } /** {@collect.stats} * Returns a string representation of this * {@code OpenMBeanParameterInfoSupport} instance. * <p> * The string representation consists of the name of this class (i.e. * {@code javax.management.openmbean.OpenMBeanParameterInfoSupport}), * the string representation of the name and open type of the described * parameter, the string representation of its default, min, max and legal * values and the string representation of its descriptor. * <p> * As {@code OpenMBeanParameterInfoSupport} instances are immutable, * the string representation for this instance is calculated once, * on the first call to {@code toString}, and then the same value * is returned for subsequent calls. * * @return a string representation of this * {@code OpenMBeanParameterInfoSupport} instance. */ public String toString() { // Calculate the string value if it has not yet been done (ie // 1st call to toString()) // if (myToString == null) myToString = OpenMBeanAttributeInfoSupport.toString(this); // return always the same string representation for this // instance (immutable) // return myToString; } }
Java
/* * Copyright (c) 2000, 2007, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management.openmbean; // java import // // jmx import // /** {@collect.stats} * <p>Describes an attribute of an open MBean.</p> * * <p>This interface declares the same methods as the class {@link * javax.management.MBeanAttributeInfo}. A class implementing this * interface (typically {@link OpenMBeanAttributeInfoSupport}) should * extend {@link javax.management.MBeanAttributeInfo}.</p> * * * @since 1.5 */ public interface OpenMBeanAttributeInfo extends OpenMBeanParameterInfo { // Re-declares the methods that are in class MBeanAttributeInfo of JMX 1.0 // (these will be removed when MBeanAttributeInfo is made a parent interface of this interface) /** {@collect.stats} * Returns <tt>true</tt> if the attribute described by this <tt>OpenMBeanAttributeInfo</tt> instance is readable, * <tt>false</tt> otherwise. * * @return true if the attribute is readable. */ public boolean isReadable() ; /** {@collect.stats} * Returns <tt>true</tt> if the attribute described by this <tt>OpenMBeanAttributeInfo</tt> instance is writable, * <tt>false</tt> otherwise. * * @return true if the attribute is writable. */ public boolean isWritable() ; /** {@collect.stats} * Returns <tt>true</tt> if the attribute described by this <tt>OpenMBeanAttributeInfo</tt> instance * is accessed through a <tt>is<i>XXX</i></tt> getter (applies only to <tt>boolean</tt> and <tt>Boolean</tt> values), * <tt>false</tt> otherwise. * * @return true if the attribute is accessed through <tt>is<i>XXX</i></tt>. */ public boolean isIs() ; // commodity methods // /** {@collect.stats} * Compares the specified <var>obj</var> parameter with this <code>OpenMBeanAttributeInfo</code> instance for equality. * <p> * Returns <tt>true</tt> if and only if all of the following statements are true: * <ul> * <li><var>obj</var> is non null,</li> * <li><var>obj</var> also implements the <code>OpenMBeanAttributeInfo</code> interface,</li> * <li>their names are equal</li> * <li>their open types are equal</li> * <li>their access properties (isReadable, isWritable and isIs) are equal</li> * <li>their default, min, max and legal values are equal.</li> * </ul> * This ensures that this <tt>equals</tt> method works properly for <var>obj</var> parameters which are * different implementations of the <code>OpenMBeanAttributeInfo</code> interface. * <br>&nbsp; * @param obj the object to be compared for equality with this <code>OpenMBeanAttributeInfo</code> instance; * * @return <code>true</code> if the specified object is equal to this <code>OpenMBeanAttributeInfo</code> instance. */ public boolean equals(Object obj); /** {@collect.stats} * Returns the hash code value for this <code>OpenMBeanAttributeInfo</code> instance. * <p> * The hash code of an <code>OpenMBeanAttributeInfo</code> instance is the sum of the hash codes * of all elements of information used in <code>equals</code> comparisons * (ie: its name, its <i>open type</i>, and its default, min, max and legal values). * <p> * This ensures that <code> t1.equals(t2) </code> implies that <code> t1.hashCode()==t2.hashCode() </code> * for any two <code>OpenMBeanAttributeInfo</code> instances <code>t1</code> and <code>t2</code>, * as required by the general contract of the method * {@link Object#hashCode() Object.hashCode()}. * <p> * * @return the hash code value for this <code>OpenMBeanAttributeInfo</code> instance */ public int hashCode(); /** {@collect.stats} * Returns a string representation of this <code>OpenMBeanAttributeInfo</code> instance. * <p> * The string representation consists of the name of this class (ie <code>javax.management.openmbean.OpenMBeanAttributeInfo</code>), * the string representation of the name and open type of the described attribute, * and the string representation of its default, min, max and legal values. * * @return a string representation of this <code>OpenMBeanAttributeInfo</code> instance */ public String toString(); // methods specific to open MBeans are inherited from // OpenMBeanParameterInfo // }
Java
/* * Copyright (c) 2000, 2007, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management.openmbean; /** {@collect.stats} * This runtime exception is thrown to indicate that the index of a row to be added to a <i>tabular data</i> instance * is already used to refer to another row in this <i>tabular data</i> instance. * * * @since 1.5 */ public class KeyAlreadyExistsException extends IllegalArgumentException { private static final long serialVersionUID = 1845183636745282866L; /** {@collect.stats} * A KeyAlreadyExistsException with no detail message. */ public KeyAlreadyExistsException() { super(); } /** {@collect.stats} * A KeyAlreadyExistsException with a detail message. * * @param msg the detail message. */ public KeyAlreadyExistsException(String msg) { super(msg); } }
Java
/* * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management.openmbean; /** {@collect.stats} * <p>A Java class can implement this interface to indicate how it is * to be converted into a {@code CompositeData} by the MXBean framework.</p> * * <p>A typical way to use this class is to add extra items to the * {@code CompositeData} in addition to the ones that are declared in the * {@code CompositeType} supplied by the MXBean framework. To do this, * you must create another {@code CompositeType} that has all the same items, * plus your extra items.</p> * * <p>For example, suppose you have a class {@code Measure} that consists of * a String called {@code units} and a {@code value} that is either a * {@code long} or a {@code double}. It might look like this:</p> * * <pre> * public class Measure implements CompositeDataView { * private String units; * private Number value; // a Long or a Double * * public Measure(String units, Number value) { * this.units = units; * this.value = value; * } * * public static Measure from(CompositeData cd) { * return new Measure((String) cd.get("units"), * (Number) cd.get("value")); * } * * public String getUnits() { * return units; * } * * // Can't be called getValue(), because Number is not a valid type * // in an MXBean, so the implied "value" property would be rejected. * public Number _getValue() { * return value; * } * * public CompositeData toCompositeData(CompositeType ct) { * try { * {@code List<String> itemNames = new ArrayList<String>(ct.keySet());} * {@code List<String> itemDescriptions = new ArrayList<String>();} * {@code List<OpenType<?>> itemTypes = new ArrayList<OpenType<?>>();} * for (String item : itemNames) { * itemDescriptions.add(ct.getDescription(item)); * itemTypes.add(ct.getType(item)); * } * itemNames.add("value"); * itemDescriptions.add("long or double value of the measure"); * itemTypes.add((value instanceof Long) ? SimpleType.LONG : * SimpleType.DOUBLE); * CompositeType xct = * new CompositeType(ct.getTypeName(), * ct.getDescription(), * itemNames.toArray(new String[0]), * itemDescriptions.toArray(new String[0]), * itemTypes.toArray(new OpenType&lt;?&gt;[0])); * CompositeData cd = * new CompositeDataSupport(xct, * new String[] {"units", "value"}, * new Object[] {units, value}); * assert ct.isValue(cd); // check we've done it right * return cd; * } catch (Exception e) { * throw new RuntimeException(e); * } * } * } * </pre> * * <p>The {@code CompositeType} that will appear in the {@code openType} field * of the {@link javax.management.Descriptor Descriptor} for an attribute or * operation of this type will show only the {@code units} item, but the actual * {@code CompositeData} that is generated will have both {@code units} and * {@code value}.</p> * * @see javax.management.MXBean * * @since 1.6 */ public interface CompositeDataView { /** {@collect.stats} * <p>Return a {@code CompositeData} corresponding to the values in * this object. The returned value should usually be an instance of * {@link CompositeDataSupport}, or a class that serializes as a * {@code CompositeDataSupport} via a {@code writeReplace} method. * Otherwise, a remote client that receives the object might not be * able to reconstruct it. * * @param ct The expected {@code CompositeType} of the returned * value. If the returned value is {@code cd}, then * {@code cd.getCompositeType().equals(ct)} should be true. * Typically this will be because {@code cd} is a * {@link CompositeDataSupport} constructed with {@code ct} as its * {@code CompositeType}. * * @return the {@code CompositeData}. */ public CompositeData toCompositeData(CompositeType ct); }
Java
/* * Copyright (c) 2000, 2007, Oracle and/or its affiliates. All rights reserved. * 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 * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. * * 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. */ package javax.management.openmbean; // java import // import java.util.Arrays; import javax.management.Descriptor; import javax.management.MBeanConstructorInfo; import javax.management.MBeanParameterInfo; /** {@collect.stats} * Describes a constructor of an Open MBean. * * * @since 1.5 */ public class OpenMBeanConstructorInfoSupport extends MBeanConstructorInfo implements OpenMBeanConstructorInfo { /* Serial version */ static final long serialVersionUID = -4400441579007477003L; // As this instance is immutable, // these two values need only be calculated once. private transient Integer myHashCode = null; private transient String myToString = null; /** {@collect.stats} * <p>Constructs an {@code OpenMBeanConstructorInfoSupport} * instance, which describes the constructor of a class of open * MBeans with the specified {@code name}, {@code description} and * {@code signature}.</p> * * <p>The {@code signature} array parameter is internally copied, * so that subsequent changes to the array referenced by {@code * signature} have no effect on this instance.</p> * * @param name cannot be a null or empty string. * * @param description cannot be a null or empty string. * * @param signature can be null or empty if there are no * parameters to describe. * * @throws IllegalArgumentException if {@code name} or {@code * description} are null or empty string. * * @throws ArrayStoreException If {@code signature} is not an * array of instances of a subclass of {@code MBeanParameterInfo}. */ public OpenMBeanConstructorInfoSupport(String name, String description, OpenMBeanParameterInfo[] signature) { this(name, description, signature, (Descriptor) null); } /** {@collect.stats} * <p>Constructs an {@code OpenMBeanConstructorInfoSupport} * instance, which describes the constructor of a class of open * MBeans with the specified {@code name}, {@code description}, * {@code signature}, and {@code descriptor}.</p> * * <p>The {@code signature} array parameter is internally copied, * so that subsequent changes to the array referenced by {@code * signature} have no effect on this instance.</p> * * @param name cannot be a null or empty string. * * @param description cannot be a null or empty string. * * @param signature can be null or empty if there are no * parameters to describe. * * @param descriptor The descriptor for the constructor. This may * be null which is equivalent to an empty descriptor. * * @throws IllegalArgumentException if {@code name} or {@code * description} are null or empty string. * * @throws ArrayStoreException If {@code signature} is not an * array of instances of a subclass of {@code MBeanParameterInfo}. * * @since 1.6 */ public OpenMBeanConstructorInfoSupport(String name, String description, OpenMBeanParameterInfo[] signature, Descriptor descriptor) { super(name, description, arrayCopyCast(signature), // may throw an ArrayStoreException descriptor); // check parameters that should not be null or empty // (unfortunately it is not done in superclass :-( ! ) // if (name == null || name.trim().equals("")) { throw new IllegalArgumentException("Argument name cannot be " + "null or empty"); } if (description == null || description.trim().equals("")) { throw new IllegalArgumentException("Argument description cannot " + "be null or empty"); } } private static MBeanParameterInfo[] arrayCopyCast(OpenMBeanParameterInfo[] src) { if (src == null) return null; MBeanParameterInfo[] dst = new MBeanParameterInfo[src.length]; System.arraycopy(src, 0, dst, 0, src.length); // may throw an ArrayStoreException return dst; } /* *** Commodity methods from java.lang.Object *** */ /** {@collect.stats} * <p>Compares the specified {@code obj} parameter with this * {@code OpenMBeanConstructorInfoSupport} instance for * equality.</p> * * <p>Returns {@code true} if and only if all of the following * statements are true: * * <ul> * <li>{@code obj} is non null,</li> * <li>{@code obj} also implements the {@code * OpenMBeanConstructorInfo} interface,</li> * <li>their names are equal</li> * <li>their signatures are equal.</li> * </ul> * * This ensures that this {@code equals} method works properly for * {@code obj} parameters which are different implementations of * the {@code OpenMBeanConstructorInfo} interface. * * @param obj the object to be compared for equality with this * {@code OpenMBeanConstructorInfoSupport} instance; * * @return {@code true} if the specified object is equal to this * {@code OpenMBeanConstructorInfoSupport} instance. */ public boolean equals(Object obj) { // if obj is null, return false // if (obj == null) { return false; } // if obj is not a OpenMBeanConstructorInfo, return false // OpenMBeanConstructorInfo other; try { other = (OpenMBeanConstructorInfo) obj; } catch (ClassCastException e) { return false; } // Now, really test for equality between this // OpenMBeanConstructorInfo implementation and the other: // // their Name should be equal if ( ! this.getName().equals(other.getName()) ) { return false; } // their Signatures should be equal if ( ! Arrays.equals(this.getSignature(), other.getSignature()) ) { return false; } // All tests for equality were successfull // return true; } /** {@collect.stats} * <p>Returns the hash code value for this {@code * OpenMBeanConstructorInfoSupport} instance.</p> * * <p>The hash code of an {@code OpenMBeanConstructorInfoSupport} * instance is the sum of the hash codes of all elements of * information used in {@code equals} comparisons (ie: its name * and signature, where the signature hashCode is calculated by a * call to {@code * java.util.Arrays.asList(this.getSignature).hashCode()}).</p> * * <p>This ensures that {@code t1.equals(t2)} implies that {@code * t1.hashCode()==t2.hashCode()} for any two {@code * OpenMBeanConstructorInfoSupport} instances {@code t1} and * {@code t2}, as required by the general contract of the method * {@link Object#hashCode() Object.hashCode()}.</p> * * <p>However, note that another instance of a class implementing * the {@code OpenMBeanConstructorInfo} interface may be equal to * this {@code OpenMBeanConstructorInfoSupport} instance as * defined by {@link #equals(java.lang.Object)}, but may have a * different hash code if it is calculated differently.</p> * * <p>As {@code OpenMBeanConstructorInfoSupport} instances are * immutable, the hash code for this instance is calculated once, * on the first call to {@code hashCode}, and then the same value * is returned for subsequent calls.</p> * * @return the hash code value for this {@code * OpenMBeanConstructorInfoSupport} instance */ public int hashCode() { // Calculate the hash code value if it has not yet been done // (ie 1st call to hashCode()) // if (myHashCode == null) { int value = 0; value += this.getName().hashCode(); value += Arrays.asList(this.getSignature()).hashCode(); myHashCode = new Integer(value); } // return always the same hash code for this instance (immutable) // return myHashCode.intValue(); } /** {@collect.stats} * <p>Returns a string representation of this {@code * OpenMBeanConstructorInfoSupport} instance.</p> * * <p>The string representation consists of the name of this class * (ie {@code * javax.management.openmbean.OpenMBeanConstructorInfoSupport}), * the name and signature of the described constructor and the * string representation of its descriptor.</p> * * <p>As {@code OpenMBeanConstructorInfoSupport} instances are * immutable, the string representation for this instance is * calculated once, on the first call to {@code toString}, and * then the same value is returned for subsequent calls.</p> * * @return a string representation of this {@code * OpenMBeanConstructorInfoSupport} instance */ public String toString() { // Calculate the string value if it has not yet been done (ie // 1st call to toString()) // if (myToString == null) { myToString = new StringBuilder() .append(this.getClass().getName()) .append("(name=") .append(this.getName()) .append(",signature=") .append(Arrays.asList(this.getSignature()).toString()) .append(",descriptor=") .append(this.getDescriptor()) .append(")") .toString(); } // return always the same string representation for this // instance (immutable) // return myToString; } }
Java