feat(jdk8): move files to new folder to avoid resources compiled.

This commit is contained in:
2025-09-07 15:25:52 +08:00
parent 3f0047bf6f
commit 8c35cfb1c0
17415 changed files with 217 additions and 213 deletions

View File

@@ -0,0 +1,107 @@
/*
* Copyright (c) 1999, 2008, 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;
/**
* 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;
/**
* @serial The first QueryExp of the conjunction
*/
private QueryExp exp1;
/**
* @serial The second QueryExp of the conjunction
*/
private QueryExp exp2;
/**
* Default constructor.
*/
public AndQueryExp() {
}
/**
* Creates a new AndQueryExp with q1 and q2 QueryExp.
*/
public AndQueryExp(QueryExp q1, QueryExp q2) {
exp1 = q1;
exp2 = q2;
}
/**
* Returns the left query expression.
*/
public QueryExp getLeftExp() {
return exp1;
}
/**
* Returns the right query expression.
*/
public QueryExp getRightExp() {
return exp2;
}
/**
* 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);
}
/**
* Returns a string representation of this AndQueryExp
*/
@Override
public String toString() {
return "(" + exp1 + ") and (" + exp2 + ")";
}
}

View File

@@ -0,0 +1,135 @@
/*
* 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;
// java import
import java.io.Serializable;
/**
* Represents an MBean attribute by associating its name with its value.
* The MBean server and other objects use this class to get and set attributes values.
*
* @since 1.5
*/
public class Attribute implements Serializable {
/* Serial version */
private static final long serialVersionUID = 2484220110589082382L;
/**
* @serial Attribute name.
*/
private String name;
/**
* @serial Attribute value
*/
private Object value= null;
/**
* Constructs an Attribute object which associates the given attribute name with the given value.
*
* @param name A String containing the name of the attribute to be created. Cannot be null.
* @param value The Object which is assigned to the attribute. This object must be of the same type as the attribute.
*
*/
public Attribute(String name, Object value) {
if (name == null) {
throw new RuntimeOperationsException(new IllegalArgumentException("Attribute name cannot be null "));
}
this.name = name;
this.value = value;
}
/**
* Returns a String containing the name of the attribute.
*
* @return the name of the attribute.
*/
public String getName() {
return name;
}
/**
* Returns an Object that is the value of this attribute.
*
* @return the value of the attribute.
*/
public Object getValue() {
return value;
}
/**
* Compares the current Attribute Object with another Attribute Object.
*
* @param object The Attribute that the current Attribute is to be compared with.
*
* @return True if the two Attribute objects are equal, otherwise false.
*/
public boolean equals(Object object) {
if (!(object instanceof Attribute)) {
return false;
}
Attribute val = (Attribute) object;
if (value == null) {
if (val.getValue() == null) {
return name.equals(val.getName());
} else {
return false;
}
}
return ((name.equals(val.getName())) &&
(value.equals(val.getValue())));
}
/**
* Returns a hash code value for this attribute.
*
* @return a hash code value for this attribute.
*/
public int hashCode() {
return name.hashCode() ^ (value == null ? 0 : value.hashCode());
}
/**
* Returns a String object representing this Attribute's value. The format of this
* string is not specified, but users can expect that two Attributes return the
* same string if and only if they are equal.
*/
public String toString() {
return getName() + " = " + getValue();
}
}

View File

@@ -0,0 +1,146 @@
/*
* 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;
/**
* 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;
/**
* 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";
/**
* @serial The MBean attribute name.
*/
private String attributeName = null;
/**
* @serial The MBean attribute type.
*/
private String attributeType = null;
/**
* @serial The MBean attribute old value.
*/
private Object oldValue = null;
/**
* @serial The MBean attribute new value.
*/
private Object newValue = null;
/**
* 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;
}
/**
* Gets the name of the attribute which has changed.
*
* @return A String containing the name of the attribute.
*/
public String getAttributeName() {
return attributeName;
}
/**
* Gets the type of the attribute which has changed.
*
* @return A String containing the type of the attribute.
*/
public String getAttributeType() {
return attributeType;
}
/**
* 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;
}
/**
* 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;
}
}

View File

@@ -0,0 +1,126 @@
/*
* 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;
/**
* 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;
/**
* @serial {@link Vector} that contains the enabled attribute names.
* The default value is an empty vector.
*/
private Vector<String> enabledAttributes = new Vector<String>();
/**
* 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);
}
/**
* 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);
}
}
/**
* 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);
}
/**
* Disables all the attribute names.
*/
public synchronized void disableAllAttributes() {
enabledAttributes.removeAllElements();
}
/**
* 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;
}
}

View File

@@ -0,0 +1,337 @@
/*
* Copyright (c) 1999, 2013, 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.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* <p>Represents a list of values for attributes of an MBean. See the
* {@link MBeanServerConnection#getAttributes getAttributes} and
* {@link MBeanServerConnection#setAttributes setAttributes} methods of
* {@link MBeanServer} and {@link MBeanServerConnection}.</p>
*
* <p id="type-safe">For compatibility reasons, it is possible, though
* highly discouraged, to add objects to an {@code AttributeList} that are
* not instances of {@code Attribute}. However, an {@code AttributeList}
* can be made <em>type-safe</em>, which means that an attempt to add
* an object that is not an {@code Attribute} will produce an {@code
* IllegalArgumentException}. An {@code AttributeList} becomes type-safe
* when the method {@link #asList()} is called on it.</p>
*
* @since 1.5
*/
/* We cannot extend ArrayList<Attribute> because our legacy
add(Attribute) method would then override add(E) in ArrayList<E>,
and our return value is void whereas ArrayList.add(E)'s is boolean.
Likewise for set(int,Attribute). Grrr. We cannot use covariance
to override the most important methods and have them return
Attribute, either, because that would break subclasses that
override those methods in turn (using the original return type
of Object). Finally, we cannot implement Iterable<Attribute>
so you could write
for (Attribute a : attributeList)
because ArrayList<> implements Iterable<> and the same class cannot
implement two versions of a generic interface. Instead we provide
the asList() method so you can write
for (Attribute a : attributeList.asList())
*/
public class AttributeList extends ArrayList<Object> {
private transient volatile boolean typeSafe;
private transient volatile boolean tainted;
/* Serial version */
private static final long serialVersionUID = -4077085769279709076L;
/**
* Constructs an empty <CODE>AttributeList</CODE>.
*/
public AttributeList() {
super();
}
/**
* Constructs an empty <CODE>AttributeList</CODE> with
* the initial capacity specified.
*
* @param initialCapacity the initial capacity of the
* <code>AttributeList</code>, as specified by {@link
* ArrayList#ArrayList(int)}.
*/
public AttributeList(int initialCapacity) {
super(initialCapacity);
}
/**
* Constructs an <CODE>AttributeList</CODE> containing the
* elements of the <CODE>AttributeList</CODE> specified, in the
* order in which they are returned by the
* <CODE>AttributeList</CODE>'s iterator. The
* <CODE>AttributeList</CODE> instance has an initial capacity of
* 110% of the size of the <CODE>AttributeList</CODE> specified.
*
* @param list the <code>AttributeList</code> that defines the initial
* contents of the new <code>AttributeList</code>.
*
* @see ArrayList#ArrayList(java.util.Collection)
*/
public AttributeList(AttributeList list) {
super(list);
}
/**
* Constructs an {@code AttributeList} containing the elements of the
* {@code List} specified, in the order in which they are returned by
* the {@code List}'s iterator.
*
* @param list the {@code List} that defines the initial contents of
* the new {@code AttributeList}.
*
* @exception IllegalArgumentException if the {@code list} parameter
* is {@code null} or if the {@code list} parameter contains any
* non-Attribute objects.
*
* @see ArrayList#ArrayList(java.util.Collection)
*
* @since 1.6
*/
public AttributeList(List<Attribute> list) {
// Check for null parameter
//
if (list == null)
throw new IllegalArgumentException("Null parameter");
// Check for non-Attribute objects
//
adding(list);
// Build the List<Attribute>
//
super.addAll(list);
}
/**
* Return a view of this list as a {@code List<Attribute>}.
* Changes to the returned value are reflected by changes
* to the original {@code AttributeList} and vice versa.
*
* @return a {@code List<Attribute>} whose contents
* reflect the contents of this {@code AttributeList}.
*
* <p>If this method has ever been called on a given
* {@code AttributeList} instance, a subsequent attempt to add
* an object to that instance which is not an {@code Attribute}
* will fail with a {@code IllegalArgumentException}. For compatibility
* reasons, an {@code AttributeList} on which this method has never
* been called does allow objects other than {@code Attribute}s to
* be added.</p>
*
* @throws IllegalArgumentException if this {@code AttributeList} contains
* an element that is not an {@code Attribute}.
*
* @since 1.6
*/
@SuppressWarnings("unchecked")
public List<Attribute> asList() {
typeSafe = true;
if (tainted)
adding((Collection<?>) this); // will throw IllegalArgumentException
return (List<Attribute>) (List<?>) this;
}
/**
* Adds the {@code Attribute} specified as the last element of the list.
*
* @param object The attribute to be added.
*/
public void add(Attribute object) {
super.add(object);
}
/**
* Inserts the attribute specified as an element at the position specified.
* Elements with an index greater than or equal to the current position are
* shifted up. If the index is out of range {@literal (index < 0 || index >
* size())} a RuntimeOperationsException should be raised, wrapping the
* java.lang.IndexOutOfBoundsException thrown.
*
* @param object The <CODE>Attribute</CODE> object to be inserted.
* @param index The position in the list where the new {@code Attribute}
* object is to be inserted.
*/
public void add(int index, Attribute object) {
try {
super.add(index, object);
}
catch (IndexOutOfBoundsException e) {
throw new RuntimeOperationsException(e,
"The specified index is out of range");
}
}
/**
* Sets the element at the position specified to be the attribute specified.
* The previous element at that position is discarded. If the index is
* out of range {@literal (index < 0 || index > size())} a RuntimeOperationsException
* should be raised, wrapping the java.lang.IndexOutOfBoundsException thrown.
*
* @param object The value to which the attribute element should be set.
* @param index The position specified.
*/
public void set(int index, Attribute object) {
try {
super.set(index, object);
}
catch (IndexOutOfBoundsException e) {
throw new RuntimeOperationsException(e,
"The specified index is out of range");
}
}
/**
* Appends all the elements in the <CODE>AttributeList</CODE> specified to
* the end of the list, in the order in which they are returned by the
* Iterator of the <CODE>AttributeList</CODE> specified.
*
* @param list Elements to be inserted into the list.
*
* @return true if this list changed as a result of the call.
*
* @see ArrayList#addAll(java.util.Collection)
*/
public boolean addAll(AttributeList list) {
return (super.addAll(list));
}
/**
* Inserts all of the elements in the <CODE>AttributeList</CODE> specified
* into this list, starting at the specified position, in the order in which
* they are returned by the Iterator of the {@code AttributeList} specified.
* If the index is out of range {@literal (index < 0 || index > size())} a
* RuntimeOperationsException should be raised, wrapping the
* java.lang.IndexOutOfBoundsException thrown.
*
* @param list Elements to be inserted into the list.
* @param index Position at which to insert the first element from the
* <CODE>AttributeList</CODE> specified.
*
* @return true if this list changed as a result of the call.
*
* @see ArrayList#addAll(int, java.util.Collection)
*/
public boolean addAll(int index, AttributeList list) {
try {
return super.addAll(index, list);
} catch (IndexOutOfBoundsException e) {
throw new RuntimeOperationsException(e,
"The specified index is out of range");
}
}
/*
* Override all of the methods from ArrayList<Object> that might add
* a non-Attribute to the List, and disallow that if asList has ever
* been called on this instance.
*/
/**
* {@inheritDoc}
* @throws IllegalArgumentException if this {@code AttributeList} is
* <a href="#type-safe">type-safe</a> and {@code element} is not an
* {@code Attribute}.
*/
@Override
public boolean add(Object element) {
adding(element);
return super.add(element);
}
/**
* {@inheritDoc}
* @throws IllegalArgumentException if this {@code AttributeList} is
* <a href="#type-safe">type-safe</a> and {@code element} is not an
* {@code Attribute}.
*/
@Override
public void add(int index, Object element) {
adding(element);
super.add(index, element);
}
/**
* {@inheritDoc}
* @throws IllegalArgumentException if this {@code AttributeList} is
* <a href="#type-safe">type-safe</a> and {@code c} contains an
* element that is not an {@code Attribute}.
*/
@Override
public boolean addAll(Collection<?> c) {
adding(c);
return super.addAll(c);
}
/**
* {@inheritDoc}
* @throws IllegalArgumentException if this {@code AttributeList} is
* <a href="#type-safe">type-safe</a> and {@code c} contains an
* element that is not an {@code Attribute}.
*/
@Override
public boolean addAll(int index, Collection<?> c) {
adding(c);
return super.addAll(index, c);
}
/**
* {@inheritDoc}
* @throws IllegalArgumentException if this {@code AttributeList} is
* <a href="#type-safe">type-safe</a> and {@code element} is not an
* {@code Attribute}.
*/
@Override
public Object set(int index, Object element) {
adding(element);
return super.set(index, element);
}
private void adding(Object x) {
if (x == null || x instanceof Attribute)
return;
if (typeSafe)
throw new IllegalArgumentException("Not an Attribute: " + x);
else
tainted = true;
}
private void adding(Collection<?> c) {
for (Object x : c)
adding(x);
}
}

View File

@@ -0,0 +1,55 @@
/*
* 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;
/**
* The specified attribute does not exist or cannot be retrieved.
*
* @since 1.5
*/
public class AttributeNotFoundException extends OperationsException {
/* Serial version */
private static final long serialVersionUID = 6511584241791106926L;
/**
* Default constructor.
*/
public AttributeNotFoundException() {
super();
}
/**
* Constructor that allows a specific error message to be specified.
*
* @param message detail message.
*/
public AttributeNotFoundException(String message) {
super(message);
}
}

View File

@@ -0,0 +1,168 @@
/*
* Copyright (c) 1999, 2008, 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.Introspector;
import java.io.IOException;
import java.io.ObjectInputStream;
/**
* <p>Represents attributes used as arguments to relational constraints.
* Instances of this class are usually obtained using {@link Query#attr(String)
* Query.attr}.</p>
*
* <p>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;
/**
* @serial The name of the attribute
*/
private String attr;
/**
* An <code>AttributeValueExp</code> with a null attribute.
* @deprecated An instance created with this constructor cannot be
* used in a query.
*/
@Deprecated
public AttributeValueExp() {
}
/**
* 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;
}
/**
* Returns a string representation of the name of the attribute.
*
* @return the attribute name.
*/
public String getAttributeName() {
return attr;
}
/**
* <p>Applies the <CODE>AttributeValueExp</CODE> on an MBean.
* This method calls {@link #getAttribute getAttribute(name)} and wraps
* the result as a {@code ValueExp}. The value returned by
* {@code getAttribute} must be a {@code Number}, {@code String},
* or {@code Boolean}; otherwise this method throws a
* {@code BadAttributeValueExpException}, which will cause
* the containing query to be false for this {@code name}.</p>
*
* @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
*
*/
@Override
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);
}
}
/**
* Returns the string representing its value.
*/
@Override
public String toString() {
return attr;
}
/**
* 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 has no effect. The MBean Server used to
* obtain an attribute value is {@link QueryEval#getMBeanServer()}.
*/
/* 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. */
@Deprecated
@Override
public void setMBeanServer(MBeanServer s) {
}
/**
* <p>Return the value of the given attribute in the named MBean.
* If the attempt to access the attribute generates an exception,
* return null.</p>
*
* <p>The MBean Server used is the one returned by {@link
* QueryEval#getMBeanServer()}.</p>
*
* @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;
}
}
}

View File

@@ -0,0 +1,91 @@
/*
* Copyright (c) 1999, 2013, 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;
/**
* Thrown when an invalid MBean attribute is passed to a query
* constructing method. 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 BadAttributeValueExpException extends Exception {
/* Serial version */
private static final long serialVersionUID = -3105272988410493376L;
/**
* @serial A string representation of the attribute that originated this exception.
* for example, the string value can be the return of {@code attribute.toString()}
*/
private Object val;
/**
* Constructs a BadAttributeValueExpException using the specified Object to
* create the toString() value.
*
* @param val the inappropriate value.
*/
public BadAttributeValueExpException (Object val) {
this.val = val == null ? null : val.toString();
}
/**
* Returns the string representing the object.
*/
public String toString() {
return "BadAttributeValueException: " + val;
}
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
ObjectInputStream.GetField gf = ois.readFields();
Object valObj = gf.get("val", null);
if (valObj == null) {
val = null;
} else if (valObj instanceof String) {
val= valObj;
} else if (System.getSecurityManager() == null
|| valObj instanceof Long
|| valObj instanceof Integer
|| valObj instanceof Float
|| valObj instanceof Double
|| valObj instanceof Byte
|| valObj instanceof Short
|| valObj instanceof Boolean) {
val = valObj.toString();
} else { // the serialized object is from a version without JDK-8019292 fix
val = System.identityHashCode(valObj) + "@" + valObj.getClass().getName();
}
}
}

View File

@@ -0,0 +1,75 @@
/*
* 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;
/**
* Thrown when an invalid expression is passed to a method for
* constructing a query. 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 BadBinaryOpValueExpException extends Exception {
/* Serial version */
private static final long serialVersionUID = 5068475589449021227L;
/**
* @serial the {@link ValueExp} that originated this exception
*/
private ValueExp exp;
/**
* Constructs a <CODE>BadBinaryOpValueExpException</CODE> with the specified <CODE>ValueExp</CODE>.
*
* @param exp the expression whose value was inappropriate.
*/
public BadBinaryOpValueExpException(ValueExp exp) {
this.exp = exp;
}
/**
* Returns the <CODE>ValueExp</CODE> that originated the exception.
*
* @return the problematic {@link ValueExp}.
*/
public ValueExp getExp() {
return exp;
}
/**
* Returns the string representing the object.
*/
public String toString() {
return "BadBinaryOpValueExpException: " + exp;
}
}

View File

@@ -0,0 +1,63 @@
/*
* 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;
/**
* Thrown when an invalid string operation is passed
* to a method for constructing a query.
*
* @since 1.5
*/
public class BadStringOperationException extends Exception {
/* Serial version */
private static final long serialVersionUID = 7802201238441662100L;
/**
* @serial The description of the operation that originated this exception
*/
private String op;
/**
* Constructs a <CODE>BadStringOperationException</CODE> with the specified detail
* message.
*
* @param message the detail message.
*/
public BadStringOperationException(String message) {
this.op = message;
}
/**
* Returns the string representing the object.
*/
public String toString() {
return "BadStringOperationException: " + op;
}
}

View File

@@ -0,0 +1,142 @@
/*
* Copyright (c) 1999, 2008, 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;
/**
* This class is used by the query-building mechanism to represent binary
* relations.
* @serial include
*
* @since 1.5
*/
class BetweenQueryExp extends QueryEval implements QueryExp {
/* Serial version */
private static final long serialVersionUID = -2933597532866307444L;
/**
* @serial The checked value
*/
private ValueExp exp1;
/**
* @serial The lower bound value
*/
private ValueExp exp2;
/**
* @serial The upper bound value
*/
private ValueExp exp3;
/**
* Basic Constructor.
*/
public BetweenQueryExp() {
}
/**
* Creates a new BetweenQueryExp with v1 checked value, v2 lower bound
* and v3 upper bound values.
*/
public BetweenQueryExp(ValueExp v1, ValueExp v2, ValueExp v3) {
exp1 = v1;
exp2 = v2;
exp3 = v3;
}
/**
* Returns the checked value of the query.
*/
public ValueExp getCheckedValue() {
return exp1;
}
/**
* Returns the lower bound value of the query.
*/
public ValueExp getLowerBound() {
return exp2;
}
/**
* Returns the upper bound value of the query.
*/
public ValueExp getUpperBound() {
return exp3;
}
/**
* Applies the BetweenQueryExp on an MBean.
*
* @param name The name of the MBean on which the BetweenQueryExp 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 {
ValueExp val1 = exp1.apply(name);
ValueExp val2 = exp2.apply(name);
ValueExp val3 = exp3.apply(name);
boolean numeric = val1 instanceof NumericValueExp;
if (numeric) {
if (((NumericValueExp)val1).isLong()) {
long lval1 = ((NumericValueExp)val1).longValue();
long lval2 = ((NumericValueExp)val2).longValue();
long lval3 = ((NumericValueExp)val3).longValue();
return lval2 <= lval1 && lval1 <= lval3;
} else {
double dval1 = ((NumericValueExp)val1).doubleValue();
double dval2 = ((NumericValueExp)val2).doubleValue();
double dval3 = ((NumericValueExp)val3).doubleValue();
return dval2 <= dval1 && dval1 <= dval3;
}
} else {
String sval1 = ((StringValueExp)val1).getValue();
String sval2 = ((StringValueExp)val2).getValue();
String sval3 = ((StringValueExp)val3).getValue();
return sval2.compareTo(sval1) <= 0 && sval1.compareTo(sval3) <= 0;
}
}
/**
* Returns the string representing the object.
*/
@Override
public String toString() {
return "(" + exp1 + ") between (" + exp2 + ") and (" + exp3 + ")";
}
}

View File

@@ -0,0 +1,257 @@
/*
* Copyright (c) 1999, 2008, 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;
/**
* 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;
/**
* @serial The operator
*/
private int op;
/**
* @serial The first value
*/
private ValueExp exp1;
/**
* @serial The second value
*/
private ValueExp exp2;
/**
* Basic Constructor.
*/
public BinaryOpValueExp() {
}
/**
* 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;
}
/**
* Returns the operator of the value expression.
*/
public int getOperator() {
return op;
}
/**
* Returns the left value of the value expression.
*/
public ValueExp getLeftValue() {
return exp1;
}
/**
* Returns the right value of the value expression.
*/
public ValueExp getRightValue() {
return exp2;
}
/**
* 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);
}
/**
* Returns the string representing the object
*/
public String toString() {
try {
return parens(exp1, true) + " " + opString() + " " + parens(exp2, false);
} catch (BadBinaryOpValueExpException ex) {
return "invalid expression";
}
}
/*
* Add parentheses to the given subexpression if necessary to
* preserve meaning. Suppose this BinaryOpValueExp is
* Query.times(Query.plus(Query.attr("A"), Query.attr("B")), Query.attr("C")).
* Then the original toString() logic would return A + B * C.
* We check precedences in order to return (A + B) * C, which is the
* meaning of the ValueExp.
*
* We need to add parentheses if the unparenthesized expression would
* be parsed as a different ValueExp from the original.
* We cannot omit parentheses even when mathematically
* the result would be equivalent, because we do not know whether the
* numeric values will be integer or floating-point. Addition and
* multiplication are associative for integers but not always for
* floating-point.
*
* So the rule is that we omit parentheses if the ValueExp
* is (A op1 B) op2 C and the precedence of op1 is greater than or
* equal to that of op2; or if the ValueExp is A op1 (B op2 C) and
* the precedence of op2 is greater than that of op1. (There are two
* precedences: that of * and / is greater than that of + and -.)
* The case of (A op1 B) op2 (C op3 D) applies each rule in turn.
*
* The following examples show the rules in action. On the left,
* the original ValueExp. On the right, the string representation.
*
* (A + B) + C A + B + C
* (A * B) + C A * B + C
* (A + B) * C (A + B) * C
* (A * B) * C A * B * C
* A + (B + C) A + (B + C)
* A + (B * C) A + B * C
* A * (B + C) A * (B + C)
* A * (B * C) A * (B * C)
*/
private String parens(ValueExp subexp, boolean left)
throws BadBinaryOpValueExpException {
boolean omit;
if (subexp instanceof BinaryOpValueExp) {
int subop = ((BinaryOpValueExp) subexp).op;
if (left)
omit = (precedence(subop) >= precedence(op));
else
omit = (precedence(subop) > precedence(op));
} else
omit = true;
if (omit)
return subexp.toString();
else
return "(" + subexp + ")";
}
private int precedence(int xop) throws BadBinaryOpValueExpException {
switch (xop) {
case Query.PLUS: case Query.MINUS: return 0;
case Query.TIMES: case Query.DIV: return 1;
default:
throw new BadBinaryOpValueExpException(this);
}
}
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);
}
@Deprecated
public void setMBeanServer(MBeanServer s) {
super.setMBeanServer(s);
}
}

View File

@@ -0,0 +1,212 @@
/*
* Copyright (c) 1999, 2008, 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;
/**
* This class is used by the query-building mechanism to represent binary
* operations.
* @serial include
*
* @since 1.5
*/
class BinaryRelQueryExp extends QueryEval implements QueryExp {
/* Serial version */
private static final long serialVersionUID = -5690656271650491000L;
/**
* @serial The operator
*/
private int relOp;
/**
* @serial The first value
*/
private ValueExp exp1;
/**
* @serial The second value
*/
private ValueExp exp2;
/**
* Basic Constructor.
*/
public BinaryRelQueryExp() {
}
/**
* Creates a new BinaryRelQueryExp with operator op applied on v1 and
* v2 values.
*/
public BinaryRelQueryExp(int op, ValueExp v1, ValueExp v2) {
relOp = op;
exp1 = v1;
exp2 = v2;
}
/**
* Returns the operator of the query.
*/
public int getOperator() {
return relOp;
}
/**
* Returns the left value of the query.
*/
public ValueExp getLeftValue() {
return exp1;
}
/**
* Returns the right value of the query.
*/
public ValueExp getRightValue() {
return exp2;
}
/**
* Applies the BinaryRelQueryExp on an MBean.
*
* @param name The name of the MBean on which the BinaryRelQueryExp 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 {
Object val1 = exp1.apply(name);
Object val2 = exp2.apply(name);
boolean numeric = val1 instanceof NumericValueExp;
boolean bool = val1 instanceof BooleanValueExp;
if (numeric) {
if (((NumericValueExp)val1).isLong()) {
long lval1 = ((NumericValueExp)val1).longValue();
long lval2 = ((NumericValueExp)val2).longValue();
switch (relOp) {
case Query.GT:
return lval1 > lval2;
case Query.LT:
return lval1 < lval2;
case Query.GE:
return lval1 >= lval2;
case Query.LE:
return lval1 <= lval2;
case Query.EQ:
return lval1 == lval2;
}
} else {
double dval1 = ((NumericValueExp)val1).doubleValue();
double dval2 = ((NumericValueExp)val2).doubleValue();
switch (relOp) {
case Query.GT:
return dval1 > dval2;
case Query.LT:
return dval1 < dval2;
case Query.GE:
return dval1 >= dval2;
case Query.LE:
return dval1 <= dval2;
case Query.EQ:
return dval1 == dval2;
}
}
} else if (bool) {
boolean bval1 = ((BooleanValueExp)val1).getValue().booleanValue();
boolean bval2 = ((BooleanValueExp)val2).getValue().booleanValue();
switch (relOp) {
case Query.GT:
return bval1 && !bval2;
case Query.LT:
return !bval1 && bval2;
case Query.GE:
return bval1 || !bval2;
case Query.LE:
return !bval1 || bval2;
case Query.EQ:
return bval1 == bval2;
}
} else {
String sval1 = ((StringValueExp)val1).getValue();
String sval2 = ((StringValueExp)val2).getValue();
switch (relOp) {
case Query.GT:
return sval1.compareTo(sval2) > 0;
case Query.LT:
return sval1.compareTo(sval2) < 0;
case Query.GE:
return sval1.compareTo(sval2) >= 0;
case Query.LE:
return sval1.compareTo(sval2) <= 0;
case Query.EQ:
return sval1.compareTo(sval2) == 0;
}
}
return false;
}
/**
* Returns the string representing the object.
*/
@Override
public String toString() {
return "(" + exp1 + ") " + relOpString() + " (" + exp2 + ")";
}
private String relOpString() {
switch (relOp) {
case Query.GT:
return ">";
case Query.LT:
return "<";
case Query.GE:
return ">=";
case Query.LE:
return "<=";
case Query.EQ:
return "=";
}
return "=";
}
}

View File

@@ -0,0 +1,93 @@
/*
* Copyright (c) 1999, 2013, 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;
/**
* This class represents a boolean value. A BooleanValueExp may be
* used anywhere a ValueExp is required.
* @serial include
*
* @since 1.5
*/
class BooleanValueExp extends QueryEval implements ValueExp {
/* Serial version */
private static final long serialVersionUID = 7754922052666594581L;
/**
* @serial The boolean value
*/
private boolean val = false;
/** Creates a new BooleanValueExp representing the boolean literal {@code val}.*/
BooleanValueExp(boolean val) {
this.val = val;
}
/**Creates a new BooleanValueExp representing the Boolean object {@code val}.*/
BooleanValueExp(Boolean val) {
this.val = val.booleanValue();
}
/** Returns the Boolean object representing the value of the BooleanValueExp object.*/
public Boolean getValue() {
return Boolean.valueOf(val);
}
/**
* Returns the string representing the object.
*/
public String toString() {
return String.valueOf(val);
}
/**
* 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;
}
@Deprecated
public void setMBeanServer(MBeanServer s) {
super.setMBeanServer(s);
}
}

View File

@@ -0,0 +1,142 @@
/*
* 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.security.AccessController;
import com.sun.jmx.mbeanserver.GetPropertyAction;
/**
* This class represents the name of the Java implementation class of
* the MBean. It is used for performing queries based on the class of
* the MBean.
* @serial include
*
* <p>The <b>serialVersionUID</b> of this class is <code>-1081892073854801359L</code>.
*
* @since 1.5
*/
@SuppressWarnings("serial") // serialVersionUID is not constant
class ClassAttributeValueExp extends AttributeValueExp {
// 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 = -2212731951078526753L;
//
// Serial version for new serial form
private static final long newSerialVersionUID = -1081892073854801359L;
private static final long serialVersionUID;
static {
boolean compat = false;
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)
serialVersionUID = oldSerialVersionUID;
else
serialVersionUID = newSerialVersionUID;
}
/**
* @serial The name of the attribute
*
* <p>The <b>serialVersionUID</b> of this class is <code>-1081892073854801359L</code>.
*/
private String attr;
/**
* Basic Constructor.
*/
public ClassAttributeValueExp() {
/* Compatibility: we have an attr field that we must hold on to
for serial compatibility, even though our parent has one too. */
super("Class");
attr = "Class";
}
/**
* Applies the ClassAttributeValueExp on an MBean. Returns the name of
* the Java implementation class of the MBean.
*
* @param name The name of the MBean on which the ClassAttributeValueExp will be applied.
*
* @return The ValueExp.
*
* @exception BadAttributeValueExpException
* @exception InvalidApplicationException
*/
public ValueExp apply(ObjectName name)
throws BadStringOperationException, BadBinaryOpValueExpException,
BadAttributeValueExpException, InvalidApplicationException {
// getAttribute(name);
Object result = getValue(name);
if (result instanceof String) {
return new StringValueExp((String)result);
} else {
throw new BadAttributeValueExpException(result);
}
}
/**
* Returns the string "Class" representing its value
*/
public String toString() {
return attr;
}
protected Object getValue(ObjectName name) {
try {
// Get the class of the object
MBeanServer server = QueryEval.getMBeanServer();
return server.getObjectInstance(name).getClassName();
} catch (Exception re) {
return null;
/* In principle the MBean does exist because otherwise we
wouldn't be evaluating the query on it. But it could
potentially have disappeared in between the time we
discovered it and the time the query is evaluated.
Also, the exception could be a SecurityException.
Returning null from here will cause
BadAttributeValueExpException, which will in turn cause
this MBean to be omitted from the query result. */
}
}
}

View File

@@ -0,0 +1,90 @@
/*
* Copyright (c) 1999, 2008, 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;
/**
* <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 {
/**
* 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);
}
/**
* 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);
}
}

View File

@@ -0,0 +1,634 @@
/*
* Copyright (c) 2000, 2013, 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.Locale;
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;
/**
* <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" summary="Descriptor Fields">
*
* <tr><th>Name</th><th>Type</th><th>Used in</th><th>Meaning</th></tr>
*
* <tr id="defaultValue"><td><i>defaultValue</i><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 id="descriptionResourceBundleBaseName">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 id="descriptionResourceKey">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 id="exceptions"><td>exceptions<td>String[]</td>
* <td>MBeanAttributeInfo, MBeanConstructorInfo, MBeanOperationInfo</td>
*
* <td>The class names of the exceptions that can be thrown when invoking a
* constructor or operation, or getting an attribute. The meaning of this field
* is defined by this specification but the field is not set or used by the
* JMX API itself. Exceptions thrown when
* setting an attribute are specified by the field
* <a href="#setExceptions">{@code setExceptions}</a>.
*
* <tr id="immutableInfo"><td><i>immutableInfo</i><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. See also the <a
* href="MBeanInfo.html#info-changed">{@code "jmx.mbean.info.changed"}</a>
* notification.</td>
*
* <tr id="infoTimeout"><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} or it has <a
* href="MBeanInfo.html#info-changed">{@code "jmx.mbean.info.changed"}</a> in
* its {@link MBeanNotificationInfo} array.</td></tr>
*
* <tr id="interfaceClassName"><td><i>interfaceClassName</i></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 id="legalValues"><td><i>legalValues</i></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 id="locale"><td>locale</td>
* <td>String</td><td>Any</td>
*
* <td>The {@linkplain Locale locale} of the description in this
* {@code MBeanInfo}, {@code MBeanAttributeInfo}, etc, as returned
* by {@link Locale#toString()}.</td>
*
* <tr id="maxValue"><td><i>maxValue</i><td>Object</td>
* <td>MBeanAttributeInfo<br>MBeanParameterInfo</td>
*
* <td>Maximum legal value for an attribute or parameter. See
* {@link javax.management.openmbean}.</td>
*
* <tr id="metricType"><td>metricType</td><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 id="minValue"><td><i>minValue</i><td>Object</td>
* <td>MBeanAttributeInfo<br>MBeanParameterInfo</td>
*
* <td>Minimum legal value for an attribute or parameter. See
* {@link javax.management.openmbean}.</td>
*
* <tr id="mxbean"><td><i>mxbean</i><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 id="openType"><td><i>openType</i><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 id="originalType"><td><i>originalType</i><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 id="setExceptions"><td><i>setExceptions</i><td>String[]</td>
* <td>MBeanAttributeInfo</td>
*
* <td>The class names of the exceptions that can be thrown when setting
* an attribute. The meaning of this field
* is defined by this specification but the field is not set or used by the
* JMX API itself. Exceptions thrown when getting an attribute are specified
* by the field <a href="#exceptions">{@code exceptions}</a>.
*
* <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 the
* information for <a href="modelmbean/ModelMBeanInfo.html#descriptor"><!--
* -->{@code ModelMBeanInfo}</a>,
* <a href="modelmbean/ModelMBeanAttributeInfo.html#descriptor"><!--
* -->{@code ModelMBeanAttributeInfo}</a>,
* <a href="modelmbean/ModelMBeanConstructorInfo.html#descriptor"><!--
* -->{@code ModelMBeanConstructorInfo}</a>,
* <a href="modelmbean/ModelMBeanNotificationInfo.html#descriptor"><!--
* -->{@code ModelMBeanNotificationInfo}</a>, and
* <a href="modelmbean/ModelMBeanOperationInfo.html#descriptor"><!--
* -->{@code ModelMBeanOperationInfo}</a>, as
* well as the chapter "Model MBeans" of the <a
* href="http://www.oracle.com/technetwork/java/javase/tech/javamanagement-140525.html">JMX
* Specification</a>. The following table summarizes these fields. Note
* that when the Type in this table is Number, a String that is the decimal
* representation of a Long can also be used.</p>
*
* <p>Nothing prevents the use of these fields in MBeans that are not Model
* MBeans. The <a href="#displayName">displayName</a>, <a href="#severity"><!--
* -->severity</a>, and <a href="#visibility">visibility</a> fields are of
* interest outside Model MBeans, for example. But only Model MBeans have
* a predefined behavior for these fields.</p>
*
* <table border="1" cellpadding="5" summary="ModelMBean Fields">
*
* <tr><th>Name</th><th>Type</th><th>Used in</th><th>Meaning</th></tr>
*
* <tr><td>class</td><td>String</td><td>ModelMBeanOperationInfo</td>
* <td>Class where method is defined (fully qualified).</td></tr>
*
* <tr><td>currencyTimeLimit</td><td>Number</td>
* <td>ModelMBeanInfo<br>ModelMBeanAttributeInfo<br>ModelMBeanOperationInfo</td>
* <td>How long cached value is valid: &lt;0 never, =0 always,
* &gt;0 seconds.</td></tr>
*
* <tr><td>default</td><td>Object</td><td>ModelMBeanAttributeInfo</td>
* <td>Default value for attribute.</td></tr>
*
* <tr><td>descriptorType</td><td>String</td><td>Any</td>
* <td>Type of descriptor, "mbean", "attribute", "constructor", "operation",
* or "notification".</td></tr>
*
* <tr id="displayName"><td>displayName</td><td>String</td><td>Any</td>
* <td>Human readable name of this item.</td></tr>
*
* <tr><td>export</td><td>String</td><td>ModelMBeanInfo</td>
* <td>Name to be used to export/expose this MBean so that it is
* findable by other JMX Agents.</td></tr>
*
* <tr><td>getMethod</td><td>String</td><td>ModelMBeanAttributeInfo</td>
* <td>Name of operation descriptor for get method.</td></tr>
*
* <tr><td>lastUpdatedTimeStamp</td><td>Number</td>
* <td>ModelMBeanAttributeInfo<br>ModelMBeanOperationInfo</td>
* <td>When <a href="#value-field">value</a> was set.</td></tr>
*
* <tr><td>log</td><td>String</td><td>ModelMBeanInfo<br>ModelMBeanNotificationInfo</td>
* <td>t or T: log all notifications, f or F: log no notifications.</td></tr>
*
* <tr><td>logFile</td><td>String</td><td>ModelMBeanInfo<br>ModelMBeanNotificationInfo</td>
* <td>Fully qualified filename to log events to.</td></tr>
*
* <tr><td>messageID</td><td>String</td><td>ModelMBeanNotificationInfo</td>
* <td>Unique key for message text (to allow translation, analysis).</td></tr>
*
* <tr><td>messageText</td><td>String</td><td>ModelMBeanNotificationInfo</td>
* <td>Text of notification.</td></tr>
*
* <tr><td>name</td><td>String</td><td>Any</td>
* <td>Name of this item.</td></tr>
*
* <tr><td>persistFile</td><td>String</td><td>ModelMBeanInfo</td>
* <td>File name into which the MBean should be persisted.</td></tr>
*
* <tr><td>persistLocation</td><td>String</td><td>ModelMBeanInfo</td>
* <td>The fully qualified directory name where the MBean should be
* persisted (if appropriate).</td></tr>
*
* <tr><td>persistPeriod</td><td>Number</td>
* <td>ModelMBeanInfo<br>ModelMBeanAttributeInfo</td>
* <td>Frequency of persist cycle in seconds. Used when persistPolicy is
* "OnTimer" or "NoMoreOftenThan".</td></tr>
*
* <tr><td>persistPolicy</td><td>String</td>
* <td>ModelMBeanInfo<br>ModelMBeanAttributeInfo</td>
* <td>One of: OnUpdate|OnTimer|NoMoreOftenThan|OnUnregister|Always|Never.
* See the section "MBean Descriptor Fields" in the JMX specification
* document.</td></tr>
*
* <tr><td>presentationString</td><td>String</td><td>Any</td>
* <td>XML formatted string to allow presentation of data.</td></tr>
*
* <tr><td>protocolMap</td><td>Descriptor</td><td>ModelMBeanAttributeInfo</td>
* <td>See the section "Protocol Map Support" in the JMX specification
* document. Mappings must be appropriate for the attribute and entries
* can be updated or augmented at runtime.</td></tr>
*
* <tr><td>role</td><td>String</td>
* <td>ModelMBeanConstructorInfo<br>ModelMBeanOperationInfo</td>
* <td>One of "constructor", "operation", "getter", or "setter".</td></tr>
*
* <tr><td>setMethod</td><td>String</td><td>ModelMBeanAttributeInfo</td>
* <td>Name of operation descriptor for set method.</td></tr>
*
* <tr id="severity"><td>severity</td><td>Number</td>
* <td>ModelMBeanNotificationInfo</td>
* <td>0-6 where 0: unknown; 1: non-recoverable;
* 2: critical, failure; 3: major, severe;
* 4: minor, marginal, error; 5: warning;
* 6: normal, cleared, informative</td></tr>
*
* <tr><td>targetObject</td><td>Object</td><td>ModelMBeanOperationInfo</td>
* <td>Object on which to execute this method.</td></tr>
*
* <tr><td>targetType</td><td>String</td><td>ModelMBeanOperationInfo</td>
* <td>type of object reference for targetObject. Can be:
* ObjectReference | Handle | EJBHandle | IOR | RMIReference.</td></tr>
*
* <tr id="value-field"><td>value</td><td>Object</td>
* <td>ModelMBeanAttributeInfo<br>ModelMBeanOperationInfo</td>
* <td>Current (cached) value for attribute or operation.</td></tr>
*
* <tr id="visibility"><td>visibility</td><td>Number</td><td>Any</td>
* <td>1-4 where 1: always visible, 4: rarely visible.</td></tr>
*
* </table>
*
* @since 1.5
*/
public interface Descriptor extends Serializable, Cloneable
{
/**
* 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;
/**
* <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;
/**
* 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();
/**
* 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();
/**
* 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);
/**
* 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);
/**
* <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;
/**
* <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;
/**
* 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;
/**
* <p>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);
/**
* <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();
}

View File

@@ -0,0 +1,57 @@
/*
* 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;
/**
* 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
{
/**
* 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);
}

View File

@@ -0,0 +1,172 @@
/*
* Copyright (c) 2005, 2013, 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.*;
/**
* <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}
* annotation, 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" summary="Descriptor Fields">
* <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" summary="Descriptor Field Types">
* <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();
}

View File

@@ -0,0 +1,41 @@
/*
* Copyright (c) 2004, 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;
/**
* Interface to read the Descriptor of a management interface element
* such as an MBeanInfo.
* @since 1.6
*/
public interface DescriptorRead {
/**
* Returns a copy of Descriptor.
*
* @return Descriptor associated with the component implementing this interface.
* The return value is never null, but the returned descriptor may be empty.
*/
public Descriptor getDescriptor();
}

View File

@@ -0,0 +1,122 @@
/*
* 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;
/**
* Defines the methods that should be implemented by
* a Dynamic MBean (MBean that exposes a dynamic management interface).
*
* @since 1.5
*/
public interface DynamicMBean {
/**
* 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;
/**
* 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 ;
/**
* 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);
/**
* 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);
/**
* 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 ;
/**
* 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();
}

View File

@@ -0,0 +1,556 @@
/*
* Copyright (c) 2004, 2013, 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.Util;
import java.io.InvalidObjectException;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
/**
* An immutable descriptor.
* @since 1.6
*/
public class ImmutableDescriptor implements Descriptor {
private static final long serialVersionUID = 8853308591080540165L;
/**
* The names of the fields in this ImmutableDescriptor with their
* original case. The names must be in alphabetical order as determined
* by {@link String#CASE_INSENSITIVE_ORDER}.
*/
private final String[] names;
/**
* The values of the fields in this ImmutableDescriptor. The
* elements in this array match the corresponding elements in the
* {@code names} array.
*/
private final Object[] values;
private transient int hashCode = -1;
/**
* An empty descriptor.
*/
public static final ImmutableDescriptor EMPTY_DESCRIPTOR =
new ImmutableDescriptor();
/**
* Construct a descriptor containing the given fields and values.
*
* @throws IllegalArgumentException if either array is null, or
* if the arrays have different sizes, or
* if a field name is null or empty, or if the same field name
* appears more than once.
*/
public ImmutableDescriptor(String[] fieldNames, Object[] fieldValues) {
this(makeMap(fieldNames, fieldValues));
}
/**
* Construct a descriptor containing the given fields. Each String
* must be of the form {@code fieldName=fieldValue}. 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}.
*
* @throws IllegalArgumentException if the parameter is null, or
* if a field name is empty, or if the same field name appears
* more than once, or if one of the strings does not contain
* an {@code =} character.
*/
public ImmutableDescriptor(String... fields) {
this(makeMap(fields));
}
/**
* <p>Construct a descriptor where the names and values of the fields
* are the keys and values of the given Map.</p>
*
* @throws IllegalArgumentException if the parameter is null, or
* if a field name is null or empty, or if the same field name appears
* more than once (which can happen because field names are not case
* sensitive).
*/
public ImmutableDescriptor(Map<String, ?> fields) {
if (fields == null)
throw new IllegalArgumentException("Null Map");
SortedMap<String, Object> map =
new TreeMap<String, Object>(String.CASE_INSENSITIVE_ORDER);
for (Map.Entry<String, ?> entry : fields.entrySet()) {
String name = entry.getKey();
if (name == null || name.equals(""))
throw new IllegalArgumentException("Empty or null field name");
if (map.containsKey(name))
throw new IllegalArgumentException("Duplicate name: " + name);
map.put(name, entry.getValue());
}
int size = map.size();
this.names = map.keySet().toArray(new String[size]);
this.values = map.values().toArray(new Object[size]);
}
/**
* This method can replace a deserialized instance of this
* class with another instance. For example, it might replace
* a deserialized empty ImmutableDescriptor with
* {@link #EMPTY_DESCRIPTOR}.
*
* @return the replacement object, which may be {@code this}.
*
* @throws InvalidObjectException if the read object has invalid fields.
*/
private Object readResolve() throws InvalidObjectException {
boolean bad = false;
if (names == null || values == null || names.length != values.length)
bad = true;
if (!bad) {
if (names.length == 0 && getClass() == ImmutableDescriptor.class)
return EMPTY_DESCRIPTOR;
final Comparator<String> compare = String.CASE_INSENSITIVE_ORDER;
String lastName = ""; // also catches illegal null name
for (int i = 0; i < names.length; i++) {
if (names[i] == null ||
compare.compare(lastName, names[i]) >= 0) {
bad = true;
break;
}
lastName = names[i];
}
}
if (bad)
throw new InvalidObjectException("Bad names or values");
return this;
}
private static SortedMap<String, ?> makeMap(String[] fieldNames,
Object[] fieldValues) {
if (fieldNames == null || fieldValues == null)
throw new IllegalArgumentException("Null array parameter");
if (fieldNames.length != fieldValues.length)
throw new IllegalArgumentException("Different size arrays");
SortedMap<String, Object> map =
new TreeMap<String, Object>(String.CASE_INSENSITIVE_ORDER);
for (int i = 0; i < fieldNames.length; i++) {
String name = fieldNames[i];
if (name == null || name.equals(""))
throw new IllegalArgumentException("Empty or null field name");
Object old = map.put(name, fieldValues[i]);
if (old != null) {
throw new IllegalArgumentException("Duplicate field name: " +
name);
}
}
return map;
}
private static SortedMap<String, ?> makeMap(String[] fields) {
if (fields == null)
throw new IllegalArgumentException("Null fields parameter");
String[] fieldNames = new String[fields.length];
String[] fieldValues = new String[fields.length];
for (int i = 0; i < fields.length; i++) {
String field = fields[i];
int eq = field.indexOf('=');
if (eq < 0) {
throw new IllegalArgumentException("Missing = character: " +
field);
}
fieldNames[i] = field.substring(0, eq);
// makeMap will catch the case where the name is empty
fieldValues[i] = field.substring(eq + 1);
}
return makeMap(fieldNames, fieldValues);
}
/**
* <p>Return an {@code ImmutableDescriptor} whose contents are the union of
* the given descriptors. Every field name that appears in any of
* the descriptors will appear in the result with the
* value that it has when the method is called. Subsequent changes
* to any of the descriptors do not affect the ImmutableDescriptor
* returned here.</p>
*
* <p>In the simplest case, there is only one descriptor and the
* returned {@code ImmutableDescriptor} is a copy of its fields at the
* time this method is called:</p>
*
* <pre>
* Descriptor d = something();
* ImmutableDescriptor copy = ImmutableDescriptor.union(d);
* </pre>
*
* @param descriptors the descriptors to be combined. Any of the
* descriptors can be null, in which case it is skipped.
*
* @return an {@code ImmutableDescriptor} that is the union of the given
* descriptors. The returned object may be identical to one of the
* input descriptors if it is an ImmutableDescriptor that contains all of
* the required fields.
*
* @throws IllegalArgumentException if two Descriptors contain the
* same field name with different associated values. Primitive array
* values are considered the same if they are of the same type with
* the same elements. Object array values are considered the same if
* {@link Arrays#deepEquals(Object[],Object[])} returns true.
*/
public static ImmutableDescriptor union(Descriptor... descriptors) {
// Optimize the case where exactly one Descriptor is non-Empty
// and it is immutable - we can just return it.
int index = findNonEmpty(descriptors, 0);
if (index < 0)
return EMPTY_DESCRIPTOR;
if (descriptors[index] instanceof ImmutableDescriptor
&& findNonEmpty(descriptors, index + 1) < 0)
return (ImmutableDescriptor) descriptors[index];
Map<String, Object> map =
new TreeMap<String, Object>(String.CASE_INSENSITIVE_ORDER);
ImmutableDescriptor biggestImmutable = EMPTY_DESCRIPTOR;
for (Descriptor d : descriptors) {
if (d != null) {
String[] names;
if (d instanceof ImmutableDescriptor) {
ImmutableDescriptor id = (ImmutableDescriptor) d;
names = id.names;
if (id.getClass() == ImmutableDescriptor.class
&& names.length > biggestImmutable.names.length)
biggestImmutable = id;
} else
names = d.getFieldNames();
for (String n : names) {
Object v = d.getFieldValue(n);
Object old = map.put(n, v);
if (old != null) {
boolean equal;
if (old.getClass().isArray()) {
equal = Arrays.deepEquals(new Object[] {old},
new Object[] {v});
} else
equal = old.equals(v);
if (!equal) {
final String msg =
"Inconsistent values for descriptor field " +
n + ": " + old + " :: " + v;
throw new IllegalArgumentException(msg);
}
}
}
}
}
if (biggestImmutable.names.length == map.size())
return biggestImmutable;
return new ImmutableDescriptor(map);
}
private static boolean isEmpty(Descriptor d) {
if (d == null)
return true;
else if (d instanceof ImmutableDescriptor)
return ((ImmutableDescriptor) d).names.length == 0;
else
return (d.getFieldNames().length == 0);
}
private static int findNonEmpty(Descriptor[] ds, int start) {
for (int i = start; i < ds.length; i++) {
if (!isEmpty(ds[i]))
return i;
}
return -1;
}
private int fieldIndex(String name) {
return Arrays.binarySearch(names, name, String.CASE_INSENSITIVE_ORDER);
}
public final Object getFieldValue(String fieldName) {
checkIllegalFieldName(fieldName);
int i = fieldIndex(fieldName);
if (i < 0)
return null;
Object v = values[i];
if (v == null || !v.getClass().isArray())
return v;
if (v instanceof Object[])
return ((Object[]) v).clone();
// clone the primitive array, could use an 8-way if/else here
int len = Array.getLength(v);
Object a = Array.newInstance(v.getClass().getComponentType(), len);
System.arraycopy(v, 0, a, 0, len);
return a;
}
public final String[] getFields() {
String[] result = new String[names.length];
for (int i = 0; i < result.length; i++) {
Object value = values[i];
if (value == null)
value = "";
else if (!(value instanceof String))
value = "(" + value + ")";
result[i] = names[i] + "=" + value;
}
return result;
}
public final Object[] getFieldValues(String... fieldNames) {
if (fieldNames == null)
return values.clone();
Object[] result = new Object[fieldNames.length];
for (int i = 0; i < fieldNames.length; i++) {
String name = fieldNames[i];
if (name != null && !name.equals(""))
result[i] = getFieldValue(name);
}
return result;
}
public final String[] getFieldNames() {
return names.clone();
}
/**
* 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:
*
* <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 o the object to compare with.
*
* @return {@code true} if the objects are the same; {@code false}
* otherwise.
*
*/
// Note: this Javadoc is copied from javax.management.Descriptor
// due to 6369229.
@Override
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Descriptor))
return false;
String[] onames;
if (o instanceof ImmutableDescriptor) {
onames = ((ImmutableDescriptor) o).names;
} else {
onames = ((Descriptor) o).getFieldNames();
Arrays.sort(onames, String.CASE_INSENSITIVE_ORDER);
}
if (names.length != onames.length)
return false;
for (int i = 0; i < names.length; i++) {
if (!names[i].equalsIgnoreCase(onames[i]))
return false;
}
Object[] ovalues;
if (o instanceof ImmutableDescriptor)
ovalues = ((ImmutableDescriptor) o).values;
else
ovalues = ((Descriptor) o).getFieldValues(onames);
return Arrays.deepEquals(values, ovalues);
}
/**
* <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.
*
*/
// Note: this Javadoc is copied from javax.management.Descriptor
// due to 6369229.
@Override
public int hashCode() {
if (hashCode == -1) {
hashCode = Util.hashCode(names, values);
}
return hashCode;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("{");
for (int i = 0; i < names.length; i++) {
if (i > 0)
sb.append(", ");
sb.append(names[i]).append("=");
Object v = values[i];
if (v != null && v.getClass().isArray()) {
String s = Arrays.deepToString(new Object[] {v});
s = s.substring(1, s.length() - 1); // remove [...]
v = s;
}
sb.append(String.valueOf(v));
}
return sb.append("}").toString();
}
/**
* Returns true if all of the fields have legal values given their
* names. This method always returns true, but a subclass can
* override it to return false when appropriate.
*
* @return true if the values are legal.
*
* @exception RuntimeOperationsException if the validity checking fails.
* The method returns false if the descriptor is not valid, but throws
* this exception if the attempt to determine validity fails.
*/
public boolean isValid() {
return true;
}
/**
* <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.</p>
*
* <p>This method returns the object on which it is called.
* A subclass can override it
* to return another object provided the contract is respected.
*
* @exception RuntimeOperationsException for illegal value for field Names
* or field Values.
* If the descriptor construction fails for any reason, this exception will
* be thrown.
*/
@Override
public Descriptor clone() {
return this;
}
/**
* This operation is unsupported since this class is immutable. If
* this call would change a mutable descriptor with the same contents,
* then a {@link RuntimeOperationsException} wrapping an
* {@link UnsupportedOperationException} is thrown. Otherwise,
* the behavior is the same as it would be for a mutable descriptor:
* either an exception is thrown because of illegal parameters, or
* there is no effect.
*/
public final void setFields(String[] fieldNames, Object[] fieldValues)
throws RuntimeOperationsException {
if (fieldNames == null || fieldValues == null)
illegal("Null argument");
if (fieldNames.length != fieldValues.length)
illegal("Different array sizes");
for (int i = 0; i < fieldNames.length; i++)
checkIllegalFieldName(fieldNames[i]);
for (int i = 0; i < fieldNames.length; i++)
setField(fieldNames[i], fieldValues[i]);
}
/**
* This operation is unsupported since this class is immutable. If
* this call would change a mutable descriptor with the same contents,
* then a {@link RuntimeOperationsException} wrapping an
* {@link UnsupportedOperationException} is thrown. Otherwise,
* the behavior is the same as it would be for a mutable descriptor:
* either an exception is thrown because of illegal parameters, or
* there is no effect.
*/
public final void setField(String fieldName, Object fieldValue)
throws RuntimeOperationsException {
checkIllegalFieldName(fieldName);
int i = fieldIndex(fieldName);
if (i < 0)
unsupported();
Object value = values[i];
if ((value == null) ?
(fieldValue != null) :
!value.equals(fieldValue))
unsupported();
}
/**
* 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 final void removeField(String fieldName) {
if (fieldName != null && fieldIndex(fieldName) >= 0)
unsupported();
}
static Descriptor nonNullDescriptor(Descriptor d) {
if (d == null)
return EMPTY_DESCRIPTOR;
else
return d;
}
private static void checkIllegalFieldName(String name) {
if (name == null || name.equals(""))
illegal("Null or empty field name");
}
private static void unsupported() {
UnsupportedOperationException uoe =
new UnsupportedOperationException("Descriptor is read-only");
throw new RuntimeOperationsException(uoe);
}
private static void illegal(String message) {
IllegalArgumentException iae = new IllegalArgumentException(message);
throw new RuntimeOperationsException(iae);
}
}

View File

@@ -0,0 +1,143 @@
/*
* Copyright (c) 1999, 2008, 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;
/**
* This class is used by the query-building mechanism to represent binary
* operations.
* @serial include
*
* @since 1.5
*/
class InQueryExp extends QueryEval implements QueryExp {
/* Serial version */
private static final long serialVersionUID = -5801329450358952434L;
/**
* @serial The {@link ValueExp} to be found
*/
private ValueExp val;
/**
* @serial The array of {@link ValueExp} to be searched
*/
private ValueExp[] valueList;
/**
* Basic Constructor.
*/
public InQueryExp() {
}
/**
* Creates a new InQueryExp with the specified ValueExp to be found in
* a specified array of ValueExp.
*/
public InQueryExp(ValueExp v1, ValueExp items[]) {
val = v1;
valueList = items;
}
/**
* Returns the checked value of the query.
*/
public ValueExp getCheckedValue() {
return val;
}
/**
* Returns the array of values of the query.
*/
public ValueExp[] getExplicitValues() {
return valueList;
}
/**
* Applies the InQueryExp on a MBean.
*
* @param name The name of the MBean on which the InQueryExp 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 {
if (valueList != null) {
ValueExp v = val.apply(name);
boolean numeric = v instanceof NumericValueExp;
for (ValueExp element : valueList) {
element = element.apply(name);
if (numeric) {
if (((NumericValueExp) element).doubleValue() ==
((NumericValueExp) v).doubleValue()) {
return true;
}
} else {
if (((StringValueExp) element).getValue().equals(
((StringValueExp) v).getValue())) {
return true;
}
}
}
}
return false;
}
/**
* Returns the string representing the object.
*/
public String toString() {
return val + " in (" + generateValueList() + ")";
}
private String generateValueList() {
if (valueList == null || valueList.length == 0) {
return "";
}
final StringBuilder result =
new StringBuilder(valueList[0].toString());
for (int i = 1; i < valueList.length; i++) {
result.append(", ");
result.append(valueList[i]);
}
return result.toString();
}
}

View File

@@ -0,0 +1,55 @@
/*
* 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;
/**
* The MBean is already registered in the repository.
*
* @since 1.5
*/
public class InstanceAlreadyExistsException extends OperationsException {
/* Serial version */
private static final long serialVersionUID = 8893743928912733931L;
/**
* Default constructor.
*/
public InstanceAlreadyExistsException() {
super();
}
/**
* Constructor that allows a specific error message to be specified.
*
* @param message the detail message.
*/
public InstanceAlreadyExistsException(String message) {
super(message);
}
}

View File

@@ -0,0 +1,54 @@
/*
* 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;
/**
* 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;
/**
* Default constructor.
*/
public InstanceNotFoundException() {
super();
}
/**
* Constructor that allows a specific error message to be specified.
*
* @param message the detail message.
*/
public InstanceNotFoundException(String message) {
super(message);
}
}

View File

@@ -0,0 +1,120 @@
/*
* 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;
/**
* 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;
/**
* @serial The {@link StringValueExp} returning the name of the class
* of which selected MBeans should be instances.
*/
private StringValueExp classNameValue;
/**
* 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;
}
/**
* 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;
}
/**
* 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;
}
}
/**
* Returns a string representation of this InstanceOfQueryExp.
* @return a string representation of this InstanceOfQueryExp.
*/
public String toString() {
return "InstanceOf " + classNameValue.toString();
}
}

View File

@@ -0,0 +1,54 @@
/*
* 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;
/**
* An exception occurred during the introspection of an MBean.
*
* @since 1.5
*/
public class IntrospectionException extends OperationsException {
/* Serial version */
private static final long serialVersionUID = 1054516935875481725L;
/**
* Default constructor.
*/
public IntrospectionException() {
super();
}
/**
* Constructor that allows a specific error message to be specified.
*
* @param message the detail message.
*/
public IntrospectionException(String message) {
super(message);
}
}

View File

@@ -0,0 +1,58 @@
/*
* 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;
/**
* 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;
/**
* @serial The object representing the class of the MBean
*/
private Object val;
/**
* 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;
}
}

View File

@@ -0,0 +1,54 @@
/*
* 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;
/**
* The value specified is not valid for the attribute.
*
* @since 1.5
*/
public class InvalidAttributeValueException extends OperationsException {
/* Serial version */
private static final long serialVersionUID = 2164571879317142449L;
/**
* Default constructor.
*/
public InvalidAttributeValueException() {
super();
}
/**
* Constructor that allows a specific error message to be specified.
*
* @param message the detail message.
*/
public InvalidAttributeValueException(String message) {
super(message);
}
}

View File

@@ -0,0 +1,56 @@
/*
* 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;
/**
* 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;
/**
* Default constructor.
*/
public JMException() {
super();
}
/**
* Constructor that allows a specific error message to be specified.
*
* @param msg the detail message.
*/
public JMException(String msg) {
super(msg);
}
}

View File

@@ -0,0 +1,63 @@
/*
* Copyright (c) 1999, 2008, 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;
/**
* Runtime exceptions emitted by JMX implementations.
*
* @since 1.5
*/
public class JMRuntimeException extends RuntimeException {
/* Serial version */
private static final long serialVersionUID = 6573344628407841861L;
/**
* Default constructor.
*/
public JMRuntimeException() {
super();
}
/**
* Constructor that allows a specific error message to be specified.
*
* @param message the detail message.
*/
public JMRuntimeException(String message) {
super(message);
}
/**
* 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, cause);
}
}

View File

@@ -0,0 +1,436 @@
/*
* Copyright (c) 2005, 2013, 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.Introspector;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Modifier;
import java.lang.reflect.Proxy;
import sun.reflect.misc.ReflectUtil;
/**
* Static methods from the JMX API. There are no instances of this class.
*
* @since 1.6
*/
public class JMX {
/* Code within this package can prove that by providing this instance of
* this class.
*/
static final JMX proof = new JMX();
private JMX() {}
/**
* The name of the <a href="Descriptor.html#defaultValue">{@code
* defaultValue}</a> field.
*/
public static final String DEFAULT_VALUE_FIELD = "defaultValue";
/**
* The name of the <a href="Descriptor.html#immutableInfo">{@code
* immutableInfo}</a> field.
*/
public static final String IMMUTABLE_INFO_FIELD = "immutableInfo";
/**
* The name of the <a href="Descriptor.html#interfaceClassName">{@code
* interfaceClassName}</a> field.
*/
public static final String INTERFACE_CLASS_NAME_FIELD = "interfaceClassName";
/**
* The name of the <a href="Descriptor.html#legalValues">{@code
* legalValues}</a> field.
*/
public static final String LEGAL_VALUES_FIELD = "legalValues";
/**
* The name of the <a href="Descriptor.html#maxValue">{@code
* maxValue}</a> field.
*/
public static final String MAX_VALUE_FIELD = "maxValue";
/**
* The name of the <a href="Descriptor.html#minValue">{@code
* minValue}</a> field.
*/
public static final String MIN_VALUE_FIELD = "minValue";
/**
* The name of the <a href="Descriptor.html#mxbean">{@code
* mxbean}</a> field.
*/
public static final String MXBEAN_FIELD = "mxbean";
/**
* The name of the <a href="Descriptor.html#openType">{@code
* openType}</a> field.
*/
public static final String OPEN_TYPE_FIELD = "openType";
/**
* The name of the <a href="Descriptor.html#originalType">{@code
* originalType}</a> field.
*/
public static final String ORIGINAL_TYPE_FIELD = "originalType";
/**
* <p>Make a proxy for a Standard MBean in a local or remote
* MBean Server.</p>
*
* <p>If you have an MBean Server {@code mbs} containing an MBean
* with {@link ObjectName} {@code name}, and if the MBean's
* management interface is described by the Java interface
* {@code MyMBean}, you can construct a proxy for the MBean like
* this:</p>
*
* <pre>
* MyMBean proxy = JMX.newMBeanProxy(mbs, name, MyMBean.class);
* </pre>
*
* <p>Suppose, for example, {@code MyMBean} looks like this:</p>
*
* <pre>
* public interface MyMBean {
* public String getSomeAttribute();
* public void setSomeAttribute(String value);
* public void someOperation(String param1, int param2);
* }
* </pre>
*
* <p>Then you can execute:</p>
*
* <ul>
*
* <li>{@code proxy.getSomeAttribute()} which will result in a
* call to {@code mbs.}{@link MBeanServerConnection#getAttribute
* getAttribute}{@code (name, "SomeAttribute")}.
*
* <li>{@code proxy.setSomeAttribute("whatever")} which will result
* in a call to {@code mbs.}{@link MBeanServerConnection#setAttribute
* setAttribute}{@code (name, new Attribute("SomeAttribute", "whatever"))}.
*
* <li>{@code proxy.someOperation("param1", 2)} which will be
* translated into a call to {@code mbs.}{@link
* MBeanServerConnection#invoke invoke}{@code (name, "someOperation", <etc>)}.
*
* </ul>
*
* <p>The object returned by this method is a
* {@link Proxy} whose {@code InvocationHandler} is an
* {@link MBeanServerInvocationHandler}.</p>
*
* <p>This method is equivalent to {@link
* #newMBeanProxy(MBeanServerConnection, ObjectName, Class,
* boolean) newMBeanProxy(connection, objectName, interfaceClass,
* false)}.</p>
*
* @param connection the MBean server to forward to.
* @param objectName the name of the MBean within
* {@code connection} to forward to.
* @param interfaceClass the management interface that the MBean
* exports, which will also be implemented by the returned proxy.
*
* @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.
*
* @throws IllegalArgumentException if {@code interfaceClass} is not
* a <a href="package-summary.html#mgIface">compliant MBean
* interface</a>
*/
public static <T> T newMBeanProxy(MBeanServerConnection connection,
ObjectName objectName,
Class<T> interfaceClass) {
return newMBeanProxy(connection, objectName, interfaceClass, false);
}
/**
* <p>Make a proxy for a Standard MBean in a local or remote MBean
* Server that may also support the methods of {@link
* NotificationEmitter}.</p>
*
* <p>This method behaves the same as {@link
* #newMBeanProxy(MBeanServerConnection, ObjectName, Class)}, but
* additionally, if {@code notificationEmitter} is {@code
* true}, then the MBean is assumed to be a {@link
* NotificationBroadcaster} or {@link NotificationEmitter} and the
* returned proxy will implement {@link NotificationEmitter} as
* well as {@code interfaceClass}. 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}.</p>
*
* @param connection the MBean server to forward to.
* @param objectName the name of the MBean within
* {@code connection} to forward to.
* @param interfaceClass the management interface that the MBean
* exports, which will also be implemented by the returned proxy.
* @param notificationEmitter make the returned proxy
* implement {@link NotificationEmitter} by forwarding its methods
* via {@code connection}.
*
* @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.
*
* @throws IllegalArgumentException if {@code interfaceClass} is not
* a <a href="package-summary.html#mgIface">compliant MBean
* interface</a>
*/
public static <T> T newMBeanProxy(MBeanServerConnection connection,
ObjectName objectName,
Class<T> interfaceClass,
boolean notificationEmitter) {
return createProxy(connection, objectName, interfaceClass, notificationEmitter, false);
}
/**
* Make a proxy for an MXBean in a local or remote MBean Server.
*
* <p>If you have an MBean Server {@code mbs} containing an
* MXBean with {@link ObjectName} {@code name}, and if the
* MXBean's management interface is described by the Java
* interface {@code MyMXBean}, you can construct a proxy for
* the MXBean like this:</p>
*
* <pre>
* MyMXBean proxy = JMX.newMXBeanProxy(mbs, name, MyMXBean.class);
* </pre>
*
* <p>Suppose, for example, {@code MyMXBean} looks like this:</p>
*
* <pre>
* public interface MyMXBean {
* public String getSimpleAttribute();
* public void setSimpleAttribute(String value);
* public {@link java.lang.management.MemoryUsage} getMappedAttribute();
* public void setMappedAttribute(MemoryUsage memoryUsage);
* public MemoryUsage someOperation(String param1, MemoryUsage param2);
* }
* </pre>
*
* <p>Then:</p>
*
* <ul>
*
* <li><p>{@code proxy.getSimpleAttribute()} will result in a
* call to {@code mbs.}{@link MBeanServerConnection#getAttribute
* getAttribute}{@code (name, "SimpleAttribute")}.</p>
*
* <li><p>{@code proxy.setSimpleAttribute("whatever")} will result
* in a call to {@code mbs.}{@link
* MBeanServerConnection#setAttribute setAttribute}<code>(name,
* new Attribute("SimpleAttribute", "whatever"))</code>.</p>
*
* <p>Because {@code String} is a <em>simple type</em>, in the
* sense of {@link javax.management.openmbean.SimpleType}, it
* is not changed in the context of an MXBean. The MXBean
* proxy behaves the same as a Standard MBean proxy (see
* {@link #newMBeanProxy(MBeanServerConnection, ObjectName,
* Class) newMBeanProxy}) for the attribute {@code
* SimpleAttribute}.</p>
*
* <li><p>{@code proxy.getMappedAttribute()} will result in a call
* to {@code mbs.getAttribute("MappedAttribute")}. The MXBean
* mapping rules mean that the actual type of the attribute {@code
* MappedAttribute} will be {@link
* javax.management.openmbean.CompositeData CompositeData} and
* that is what the {@code mbs.getAttribute} call will return.
* The proxy will then convert the {@code CompositeData} back into
* the expected type {@code MemoryUsage} using the MXBean mapping
* rules.</p>
*
* <li><p>Similarly, {@code proxy.setMappedAttribute(memoryUsage)}
* will convert the {@code MemoryUsage} argument into a {@code
* CompositeData} before calling {@code mbs.setAttribute}.</p>
*
* <li><p>{@code proxy.someOperation("whatever", memoryUsage)}
* will convert the {@code MemoryUsage} argument into a {@code
* CompositeData} and call {@code mbs.invoke}. The value returned
* by {@code mbs.invoke} will be also be a {@code CompositeData},
* and the proxy will convert this into the expected type {@code
* MemoryUsage} using the MXBean mapping rules.</p>
*
* </ul>
*
* <p>The object returned by this method is a
* {@link Proxy} whose {@code InvocationHandler} is an
* {@link MBeanServerInvocationHandler}.</p>
*
* <p>This method is equivalent to {@link
* #newMXBeanProxy(MBeanServerConnection, ObjectName, Class,
* boolean) newMXBeanProxy(connection, objectName, interfaceClass,
* false)}.</p>
*
* @param connection the MBean server to forward to.
* @param objectName the name of the MBean within
* {@code connection} to forward to.
* @param interfaceClass the MXBean interface,
* which will also be implemented by the returned proxy.
*
* @param <T> allows the compiler to know that if the {@code
* interfaceClass} parameter is {@code MyMXBean.class}, for
* example, then the return type is {@code MyMXBean}.
*
* @return the new proxy instance.
*
* @throws IllegalArgumentException if {@code interfaceClass} is not
* a {@link javax.management.MXBean compliant MXBean interface}
*/
public static <T> T newMXBeanProxy(MBeanServerConnection connection,
ObjectName objectName,
Class<T> interfaceClass) {
return newMXBeanProxy(connection, objectName, interfaceClass, false);
}
/**
* <p>Make a proxy for an MXBean in a local or remote MBean
* Server that may also support the methods of {@link
* NotificationEmitter}.</p>
*
* <p>This method behaves the same as {@link
* #newMXBeanProxy(MBeanServerConnection, ObjectName, Class)}, but
* additionally, if {@code notificationEmitter} is {@code
* true}, then the MXBean is assumed to be a {@link
* NotificationBroadcaster} or {@link NotificationEmitter} and the
* returned proxy will implement {@link NotificationEmitter} as
* well as {@code interfaceClass}. 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}.</p>
*
* @param connection the MBean server to forward to.
* @param objectName the name of the MBean within
* {@code connection} to forward to.
* @param interfaceClass the MXBean interface,
* which will also be implemented by the returned proxy.
* @param notificationEmitter make the returned proxy
* implement {@link NotificationEmitter} by forwarding its methods
* via {@code connection}.
*
* @param <T> allows the compiler to know that if the {@code
* interfaceClass} parameter is {@code MyMXBean.class}, for
* example, then the return type is {@code MyMXBean}.
*
* @return the new proxy instance.
*
* @throws IllegalArgumentException if {@code interfaceClass} is not
* a {@link javax.management.MXBean compliant MXBean interface}
*/
public static <T> T newMXBeanProxy(MBeanServerConnection connection,
ObjectName objectName,
Class<T> interfaceClass,
boolean notificationEmitter) {
return createProxy(connection, objectName, interfaceClass, notificationEmitter, true);
}
/**
* <p>Test whether an interface is an MXBean interface.
* An interface is an MXBean interface if it is public,
* annotated {@link MXBean &#64;MXBean} or {@code @MXBean(true)}
* or if it does not have an {@code @MXBean} annotation
* and its name ends with "{@code MXBean}".</p>
*
* @param interfaceClass The candidate interface.
*
* @return true if {@code interfaceClass} is a
* {@link javax.management.MXBean compliant MXBean interface}
*
* @throws NullPointerException if {@code interfaceClass} is null.
*/
public static boolean isMXBeanInterface(Class<?> interfaceClass) {
if (!interfaceClass.isInterface())
return false;
if (!Modifier.isPublic(interfaceClass.getModifiers()) &&
!Introspector.ALLOW_NONPUBLIC_MBEAN) {
return false;
}
MXBean a = interfaceClass.getAnnotation(MXBean.class);
if (a != null)
return a.value();
return interfaceClass.getName().endsWith("MXBean");
// We don't bother excluding the case where the name is
// exactly the string "MXBean" since that would mean there
// was no package name, which is pretty unlikely in practice.
}
/**
* Centralised M(X)Bean proxy creation code
* @param connection {@linkplain MBeanServerConnection} to use
* @param objectName M(X)Bean object name
* @param interfaceClass M(X)Bean interface class
* @param notificationEmitter Is a notification emitter?
* @param isMXBean Is an MXBean?
* @return Returns an M(X)Bean proxy generated for the provided interface class
* @throws SecurityException
* @throws IllegalArgumentException
*/
private static <T> T createProxy(MBeanServerConnection connection,
ObjectName objectName,
Class<T> interfaceClass,
boolean notificationEmitter,
boolean isMXBean) {
try {
if (isMXBean) {
// Check interface for MXBean compliance
Introspector.testComplianceMXBeanInterface(interfaceClass);
} else {
// Check interface for MBean compliance
Introspector.testComplianceMBeanInterface(interfaceClass);
}
} catch (NotCompliantMBeanException e) {
throw new IllegalArgumentException(e);
}
InvocationHandler handler = new MBeanServerInvocationHandler(
connection, objectName, isMXBean);
final Class<?>[] interfaces;
if (notificationEmitter) {
interfaces =
new Class<?>[] {interfaceClass, NotificationEmitter.class};
} else
interfaces = new Class<?>[] {interfaceClass};
Object proxy = Proxy.newProxyInstance(
interfaceClass.getClassLoader(),
interfaces,
handler);
return interfaceClass.cast(proxy);
}
}

View File

@@ -0,0 +1,55 @@
/*
* 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;
/**
* 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;
/**
* Default constructor.
*/
public ListenerNotFoundException() {
super();
}
/**
* Constructor that allows a specific error message to be specified.
*
* @param message the detail message.
*/
public ListenerNotFoundException(String message) {
super(message);
}
}

View File

@@ -0,0 +1,354 @@
/*
* Copyright (c) 1999, 2013, 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;
import java.util.Objects;
/**
* 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];
/**
* @serial The actual attribute type.
*/
private final String attributeType;
/**
* @serial The attribute write right.
*/
private final boolean isWrite;
/**
* @serial The attribute read right.
*/
private final boolean isRead;
/**
* @serial Indicates if this method is a "is"
*/
private final boolean is;
/**
* 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);
}
/**
* 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;
}
/**
* <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)));
}
/**
* <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;
}
}
/**
* Returns the class name of the attribute.
*
* @return the class name.
*/
public String getType() {
return attributeType;
}
/**
* Whether the value of the attribute can be read.
*
* @return True if the attribute can be read, false otherwise.
*/
public boolean isReadable() {
return isRead;
}
/**
* 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;
}
/**
* 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() +
"]";
}
/**
* 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 (Objects.equals(p.getName(), getName()) &&
Objects.equals(p.getType(), getType()) &&
Objects.equals(p.getDescription(), getDescription()) &&
Objects.equals(p.getDescriptor(), 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 Objects.hash(getName(), getType());
}
private static boolean isIs(Method getter) {
return (getter != null &&
getter.getName().startsWith("is") &&
(getter.getReturnType().equals(Boolean.TYPE) ||
getter.getReturnType().equals(Boolean.class)));
}
/**
* 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();
}
}

View File

@@ -0,0 +1,215 @@
/*
* Copyright (c) 1999, 2013, 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.Introspector;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.util.Arrays;
import java.util.Objects;
/**
* Describes a constructor exposed by an MBean. Instances of this
* class are immutable. Subclasses may be mutable but this is not
* recommended.
*
* @since 1.5
*/
public class MBeanConstructorInfo extends MBeanFeatureInfo implements Cloneable {
/* Serial version */
static final long serialVersionUID = 4433990064191844427L;
static final MBeanConstructorInfo[] NO_CONSTRUCTORS =
new MBeanConstructorInfo[0];
/** @see MBeanInfo#arrayGettersSafe */
private final transient boolean arrayGettersSafe;
/**
* @serial The signature of the method, that is, the class names of the arguments.
*/
private final MBeanParameterInfo[] signature;
/**
* Constructs an <CODE>MBeanConstructorInfo</CODE> 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 operation.
* @param constructor The <CODE>java.lang.reflect.Constructor</CODE>
* object describing the MBean constructor.
*/
public MBeanConstructorInfo(String description, Constructor<?> constructor) {
this(constructor.getName(), description,
constructorSignature(constructor),
Introspector.descriptorForElement(constructor));
}
/**
* Constructs an <CODE>MBeanConstructorInfo</CODE> object.
*
* @param name The name of the constructor.
* @param signature <CODE>MBeanParameterInfo</CODE> objects
* describing the parameters(arguments) of the constructor. This
* may be null with the same effect as a zero-length array.
* @param description A human readable description of the constructor.
*/
public MBeanConstructorInfo(String name,
String description,
MBeanParameterInfo[] signature) {
this(name, description, signature, null);
}
/**
* Constructs an <CODE>MBeanConstructorInfo</CODE> object.
*
* @param name The name of the constructor.
* @param signature <CODE>MBeanParameterInfo</CODE> objects
* describing the parameters(arguments) of the constructor. This
* may be null with the same effect as a zero-length array.
* @param description A human readable description of the constructor.
* @param descriptor The descriptor for the constructor. This may be null
* which is equivalent to an empty descriptor.
*
* @since 1.6
*/
public MBeanConstructorInfo(String name,
String description,
MBeanParameterInfo[] signature,
Descriptor descriptor) {
super(name, description, descriptor);
if (signature == null || signature.length == 0)
signature = MBeanParameterInfo.NO_PARAMS;
else
signature = signature.clone();
this.signature = signature;
this.arrayGettersSafe =
MBeanInfo.arrayGettersSafe(this.getClass(),
MBeanConstructorInfo.class);
}
/**
* <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;
}
}
/**
* <p>Returns the list of parameters for this constructor. Each
* parameter is described by an <CODE>MBeanParameterInfo</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>MBeanParameterInfo</CODE> objects but
* that each referenced <CODE>MBeanParameterInfo</CODE> object is
* not copied.</p>
*
* @return An array of <CODE>MBeanParameterInfo</CODE> objects.
*/
public MBeanParameterInfo[] getSignature() {
if (signature.length == 0)
return signature;
else
return signature.clone();
}
private MBeanParameterInfo[] fastGetSignature() {
if (arrayGettersSafe)
return signature;
else
return getSignature();
}
public String toString() {
return
getClass().getName() + "[" +
"description=" + getDescription() + ", " +
"name=" + getName() + ", " +
"signature=" + Arrays.asList(fastGetSignature()) + ", " +
"descriptor=" + getDescriptor() +
"]";
}
/**
* Compare this MBeanConstructorInfo to another.
*
* @param o the object to compare to.
*
* @return true if and only if <code>o</code> is an MBeanConstructorInfo such
* that its {@link #getName()}, {@link #getDescription()},
* {@link #getSignature()}, and {@link #getDescriptor()}
* values are equal (not necessarily
* identical) to those of this MBeanConstructorInfo. Two
* signature arrays are equal if their elements are pairwise
* equal.
*/
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof MBeanConstructorInfo))
return false;
MBeanConstructorInfo p = (MBeanConstructorInfo) o;
return (Objects.equals(p.getName(), getName()) &&
Objects.equals(p.getDescription(), getDescription()) &&
Arrays.equals(p.fastGetSignature(), fastGetSignature()) &&
Objects.equals(p.getDescriptor(), getDescriptor()));
}
/* Unlike attributes and operations, it's quite likely we'll have
more than one constructor with the same name and even
description, so we include the parameter array in the hashcode.
We don't include the description, though, because it could be
quite long and yet the same between constructors. Likewise for
the descriptor. */
public int hashCode() {
return Objects.hash(getName()) ^ Arrays.hashCode(fastGetSignature());
}
private static MBeanParameterInfo[] constructorSignature(Constructor<?> cn) {
final Class<?>[] classes = cn.getParameterTypes();
final Annotation[][] annots = cn.getParameterAnnotations();
return MBeanOperationInfo.parameters(classes, annots);
}
}

View File

@@ -0,0 +1,89 @@
/*
* 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;
/**
* 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;
/**
* @serial Encapsulated {@link Exception}
*/
private java.lang.Exception exception ;
/**
* 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 ;
}
/**
* 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 ;
}
/**
* Return the actual {@link Exception} thrown.
*
* @return the wrapped exception.
*/
public Exception getTargetException() {
return exception;
}
/**
* Return the actual {@link Exception} thrown.
*
* @return the wrapped exception.
*/
public Throwable getCause() {
return exception;
}
}

View File

@@ -0,0 +1,265 @@
/*
* Copyright (c) 1999, 2013, 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;
import java.util.Objects;
/**
* <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;
/**
* 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;
/**
* 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;
/**
* @serial The Descriptor for this MBeanFeatureInfo. This field
* can be null, which is equivalent to an empty Descriptor.
*/
private transient Descriptor descriptor;
/**
* 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);
}
/**
* 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;
}
/**
* Returns the name of the feature.
*
* @return the name of the feature.
*/
public String getName() {
return name;
}
/**
* Returns the human-readable description of the feature.
*
* @return the human-readable description of the feature.
*/
public String getDescription() {
return description;
}
/**
* 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();
}
/**
* 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 (Objects.equals(p.getName(), getName()) &&
Objects.equals(p.getDescription(), getDescription()) &&
Objects.equals(p.getDescriptor(), getDescriptor()));
}
public int hashCode() {
return getName().hashCode() ^ getDescription().hashCode() ^
getDescriptor().hashCode();
}
/**
* Serializes an {@link MBeanFeatureInfo} to an {@link ObjectOutputStream}.
* @serialData
* For compatibility reasons, an object of this class is serialized as follows.
* <p>
* 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>
*
* @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);
}
}
/**
* Deserializes an {@link MBeanFeatureInfo} from an {@link ObjectInputStream}.
* @serialData
* For compatibility reasons, an object of this class is deserialized as follows.
* <p>
* 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>
*
* @since 1.6
*/
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException {
in.defaultReadObject();
switch (in.read()) {
case 1:
final String[] names = (String[])in.readObject();
final Object[] values = (Object[]) in.readObject();
descriptor = (names.length == 0) ?
ImmutableDescriptor.EMPTY_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.");
}
}
}

View File

@@ -0,0 +1,721 @@
/*
* Copyright (c) 1999, 2013, 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 java.util.Objects;
import static javax.management.ImmutableDescriptor.nonNullDescriptor;
/**
* <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 id="info-changed">Usually the {@code MBeanInfo} for any given MBean does
* not change over the lifetime of that MBean. Dynamic MBeans can change their
* {@code MBeanInfo} and in that case it is recommended that they emit a {@link
* Notification} with a {@linkplain Notification#getType() type} of {@code
* "jmx.mbean.info.changed"} and a {@linkplain Notification#getUserData()
* userData} that is the new {@code MBeanInfo}. This is not required, but
* provides a conventional way for clients of the MBean to discover the change.
* See also the <a href="Descriptor.html#immutableInfo">immutableInfo</a> and
* <a href="Descriptor.html#infoTimeout">infoTimeout</a> fields in the {@code
* MBeanInfo} {@link Descriptor}.</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 (see
* {@link DescriptorKey &#64;DescriptorKey}).
*
* </ul>
*
* <p>The description returned by {@link #getDescription()} and the
* descriptions of the contained attributes and operations 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;
/**
* @serial The Descriptor for the MBean. This field
* can be null, which is equivalent to an empty Descriptor.
*/
private transient Descriptor descriptor;
/**
* @serial The human readable description of the class.
*/
private final String description;
/**
* @serial The MBean qualified name.
*/
private final String className;
/**
* @serial The MBean attribute descriptors.
*/
private final MBeanAttributeInfo[] attributes;
/**
* @serial The MBean operation descriptors.
*/
private final MBeanOperationInfo[] operations;
/**
* @serial The MBean constructor descriptors.
*/
private final MBeanConstructorInfo[] constructors;
/**
* @serial The MBean notification descriptors.
*/
private final MBeanNotificationInfo[] notifications;
private transient int hashCode;
/**
* <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;
/**
* 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);
}
/**
* 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);
}
/**
* <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>
*/
@Override
public Object clone () {
try {
return super.clone() ;
} catch (CloneNotSupportedException e) {
// should not happen as this class is cloneable
return null;
}
}
/**
* 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;
}
/**
* Returns a human readable description of the MBean.
*
* @return the description.
*/
public String getDescription() {
return description;
}
/**
* 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();
}
/**
* 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;
}
/**
* 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;
}
/**
* <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;
}
/**
* 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;
}
/**
* 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();
}
@Override
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() +
"]";
}
/**
* <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.
*/
@Override
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()));
}
@Override
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 = Objects.hash(getClassName(), getDescriptor())
^ Arrays.hashCode(fastGetAttributes())
^ Arrays.hashCode(fastGetOperations())
^ Arrays.hashCode(fastGetConstructors())
^ Arrays.hashCode(fastGetNotifications());
return hashCode;
}
/**
* 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>();
/**
* 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;
}
/**
* Serializes an {@link MBeanInfo} to an {@link ObjectOutputStream}.
* @serialData
* For compatibility reasons, an object of this class is serialized as follows.
* <p>
* 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>
*
* @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);
}
}
/**
* Deserializes an {@link MBeanInfo} from an {@link ObjectInputStream}.
* @serialData
* For compatibility reasons, an object of this class is deserialized as follows.
* <p>
* 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>
*
* @since 1.6
*/
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException {
in.defaultReadObject();
switch (in.read()) {
case 1:
final String[] names = (String[])in.readObject();
final Object[] values = (Object[]) in.readObject();
descriptor = (names.length == 0) ?
ImmutableDescriptor.EMPTY_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.");
}
}
}

View File

@@ -0,0 +1,216 @@
/*
* Copyright (c) 1999, 2013, 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.InvalidObjectException;
import java.io.ObjectInputStream;
import java.util.Arrays;
import java.util.Objects;
/**
* <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];
/**
* @serial The different types of the notification.
*/
private String[] types;
/** @see MBeanInfo#arrayGettersSafe */
private final transient boolean arrayGettersSafe;
/**
* 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);
}
/**
* 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. */
this.types = (notifTypes != null && notifTypes.length > 0) ?
notifTypes.clone() : NO_TYPES;
this.arrayGettersSafe =
MBeanInfo.arrayGettersSafe(this.getClass(),
MBeanNotificationInfo.class);
}
/**
* 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;
}
}
/**
* 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() +
"]";
}
/**
* 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 (Objects.equals(p.getName(), getName()) &&
Objects.equals(p.getDescription(), getDescription()) &&
Objects.equals(p.getDescriptor(), 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;
}
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
ObjectInputStream.GetField gf = ois.readFields();
String[] t = (String[])gf.get("types", null);
types = (t != null && t.length != 0) ? t.clone() : NO_TYPES;
}
}

View File

@@ -0,0 +1,337 @@
/*
* Copyright (c) 1999, 2013, 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.Introspector;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Objects;
/**
* Describes a management 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 MBeanOperationInfo extends MBeanFeatureInfo implements Cloneable {
/* Serial version */
static final long serialVersionUID = -6178860474881375330L;
static final MBeanOperationInfo[] NO_OPERATIONS =
new MBeanOperationInfo[0];
/**
* Indicates that the operation is read-like:
* it returns information but does not change any state.
*/
public static final int INFO = 0;
/**
* Indicates that the operation is write-like: it has an effect but does
* not return any information from the MBean.
*/
public static final int ACTION = 1;
/**
* Indicates that the operation is both read-like and write-like:
* it has an effect, and it also returns information from the MBean.
*/
public static final int ACTION_INFO = 2;
/**
* Indicates that the impact of the operation is unknown or cannot be
* expressed using one of the other values.
*/
public static final int UNKNOWN = 3;
/**
* @serial The method's return value.
*/
private final String type;
/**
* @serial The signature of the method, that is, the class names
* of the arguments.
*/
private final MBeanParameterInfo[] signature;
/**
* @serial The impact of the method, one of
* <CODE>INFO</CODE>,
* <CODE>ACTION</CODE>,
* <CODE>ACTION_INFO</CODE>,
* <CODE>UNKNOWN</CODE>
*/
private final int impact;
/** @see MBeanInfo#arrayGettersSafe */
private final transient boolean arrayGettersSafe;
/**
* Constructs an <CODE>MBeanOperationInfo</CODE> 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 method The <CODE>java.lang.reflect.Method</CODE> object
* describing the MBean operation.
* @param description A human readable description of the operation.
*/
public MBeanOperationInfo(String description, Method method) {
this(method.getName(),
description,
methodSignature(method),
method.getReturnType().getName(),
UNKNOWN,
Introspector.descriptorForElement(method));
}
/**
* Constructs an <CODE>MBeanOperationInfo</CODE> object.
*
* @param name The name of the method.
* @param description A human readable description of the operation.
* @param signature <CODE>MBeanParameterInfo</CODE> objects
* describing the parameters(arguments) of the method. This may be
* null with the same effect as a zero-length array.
* @param type The type of the method's return value.
* @param impact The impact of the method, one of
* {@link #INFO}, {@link #ACTION}, {@link #ACTION_INFO},
* {@link #UNKNOWN}.
*/
public MBeanOperationInfo(String name,
String description,
MBeanParameterInfo[] signature,
String type,
int impact) {
this(name, description, signature, type, impact, (Descriptor) null);
}
/**
* Constructs an <CODE>MBeanOperationInfo</CODE> object.
*
* @param name The name of the method.
* @param description A human readable description of the operation.
* @param signature <CODE>MBeanParameterInfo</CODE> objects
* describing the parameters(arguments) of the method. This may be
* null with the same effect as a zero-length array.
* @param type The type of the method's return value.
* @param impact The impact of the method, one of
* {@link #INFO}, {@link #ACTION}, {@link #ACTION_INFO},
* {@link #UNKNOWN}.
* @param descriptor The descriptor for the operation. This may be null
* which is equivalent to an empty descriptor.
*
* @since 1.6
*/
public MBeanOperationInfo(String name,
String description,
MBeanParameterInfo[] signature,
String type,
int impact,
Descriptor descriptor) {
super(name, description, descriptor);
if (signature == null || signature.length == 0)
signature = MBeanParameterInfo.NO_PARAMS;
else
signature = signature.clone();
this.signature = signature;
this.type = type;
this.impact = impact;
this.arrayGettersSafe =
MBeanInfo.arrayGettersSafe(this.getClass(),
MBeanOperationInfo.class);
}
/**
* <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>
*/
@Override
public Object clone () {
try {
return super.clone() ;
} catch (CloneNotSupportedException e) {
// should not happen as this class is cloneable
return null;
}
}
/**
* Returns the type of the method's return value.
*
* @return the return type.
*/
public String getReturnType() {
return type;
}
/**
* <p>Returns the list of parameters for this operation. Each
* parameter is described by an <CODE>MBeanParameterInfo</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>MBeanParameterInfo</CODE> objects but
* that each referenced <CODE>MBeanParameterInfo</CODE> object is
* not copied.</p>
*
* @return An array of <CODE>MBeanParameterInfo</CODE> objects.
*/
public MBeanParameterInfo[] getSignature() {
// If MBeanOperationInfo was created in our implementation,
// signature cannot be null - because our constructors replace
// null with MBeanParameterInfo.NO_PARAMS;
//
// However, signature could be null if an MBeanOperationInfo is
// deserialized from a byte array produced by another implementation.
// This is not very likely but possible, since the serial form says
// nothing against it. (see 6373150)
//
if (signature == null)
// if signature is null simply return an empty array .
//
return MBeanParameterInfo.NO_PARAMS;
else if (signature.length == 0)
return signature;
else
return signature.clone();
}
private MBeanParameterInfo[] fastGetSignature() {
if (arrayGettersSafe) {
// if signature is null simply return an empty array .
// see getSignature() above.
//
if (signature == null)
return MBeanParameterInfo.NO_PARAMS;
else return signature;
} else return getSignature();
}
/**
* Returns the impact of the method, one of
* <CODE>INFO</CODE>, <CODE>ACTION</CODE>, <CODE>ACTION_INFO</CODE>, <CODE>UNKNOWN</CODE>.
*
* @return the impact code.
*/
public int getImpact() {
return impact;
}
@Override
public String toString() {
String impactString;
switch (getImpact()) {
case ACTION: impactString = "action"; break;
case ACTION_INFO: impactString = "action/info"; break;
case INFO: impactString = "info"; break;
case UNKNOWN: impactString = "unknown"; break;
default: impactString = "(" + getImpact() + ")";
}
return getClass().getName() + "[" +
"description=" + getDescription() + ", " +
"name=" + getName() + ", " +
"returnType=" + getReturnType() + ", " +
"signature=" + Arrays.asList(fastGetSignature()) + ", " +
"impact=" + impactString + ", " +
"descriptor=" + getDescriptor() +
"]";
}
/**
* Compare this MBeanOperationInfo to another.
*
* @param o the object to compare to.
*
* @return true if and only if <code>o</code> is an MBeanOperationInfo such
* that its {@link #getName()}, {@link #getReturnType()}, {@link
* #getDescription()}, {@link #getImpact()}, {@link #getDescriptor()}
* and {@link #getSignature()} values are equal (not necessarily identical)
* to those of this MBeanConstructorInfo. Two signature arrays
* are equal if their elements are pairwise equal.
*/
@Override
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof MBeanOperationInfo))
return false;
MBeanOperationInfo p = (MBeanOperationInfo) o;
return (Objects.equals(p.getName(), getName()) &&
Objects.equals(p.getReturnType(), getReturnType()) &&
Objects.equals(p.getDescription(), getDescription()) &&
p.getImpact() == getImpact() &&
Arrays.equals(p.fastGetSignature(), fastGetSignature()) &&
Objects.equals(p.getDescriptor(), getDescriptor()));
}
/* 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 the
parameter array. */
@Override
public int hashCode() {
return Objects.hash(getName(), getReturnType());
}
private static MBeanParameterInfo[] methodSignature(Method method) {
final Class<?>[] classes = method.getParameterTypes();
final Annotation[][] annots = method.getParameterAnnotations();
return parameters(classes, annots);
}
static MBeanParameterInfo[] parameters(Class<?>[] classes,
Annotation[][] annots) {
final MBeanParameterInfo[] params =
new MBeanParameterInfo[classes.length];
assert(classes.length == annots.length);
for (int i = 0; i < classes.length; i++) {
Descriptor d = Introspector.descriptorForAnnotations(annots[i]);
final String pn = "p" + (i + 1);
params[i] =
new MBeanParameterInfo(pn, classes[i].getName(), "", d);
}
return params;
}
}

View File

@@ -0,0 +1,150 @@
/*
* Copyright (c) 1999, 2013, 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.Objects;
/**
* 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];
/**
* @serial The type or class name of the data.
*/
private final String type;
/**
* 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);
}
/**
* 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;
}
/**
* <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;
}
}
/**
* 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() +
"]";
}
/**
* 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 (Objects.equals(p.getName(), getName()) &&
Objects.equals(p.getType(), getType()) &&
Objects.equals(p.getDescription(), getDescription()) &&
Objects.equals(p.getDescriptor(), getDescriptor()));
}
public int hashCode() {
return Objects.hash(getName(), getType());
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,117 @@
/*
* Copyright (c) 1999, 2008, 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;
/**
* <p>Can be implemented by an MBean in order to
* carry out operations before and after being registered or unregistered from
* the MBean Server. An MBean can also implement this interface in order
* to get a reference to the MBean Server and/or its name within that
* MBean Server.</p>
*
* @since 1.5
*/
public interface MBeanRegistration {
/**
* 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;
/**
* Allows the MBean to perform any operations needed after having been
* registered in the MBean server or after the registration has failed.
* <p>If the implementation of this method throws a {@link RuntimeException}
* or an {@link Error}, the MBean Server will rethrow those inside
* a {@link RuntimeMBeanException} or {@link RuntimeErrorException},
* respectively. However, throwing an exception in {@code postRegister}
* will not change the state of the MBean:
* if the MBean was already registered ({@code registrationDone} is
* {@code true}), the MBean will remain registered. </p>
* <p>This might be confusing for the code calling {@code createMBean()}
* or {@code registerMBean()}, as such code might assume that MBean
* registration has failed when such an exception is raised.
* Therefore it is recommended that implementations of
* {@code postRegister} do not throw Runtime Exceptions or Errors if it
* can be avoided.</p>
* @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);
/**
* 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 ;
/**
* Allows the MBean to perform any operations needed after having been
* unregistered in the MBean server.
* <p>If the implementation of this method throws a {@link RuntimeException}
* or an {@link Error}, the MBean Server will rethrow those inside
* a {@link RuntimeMBeanException} or {@link RuntimeErrorException},
* respectively. However, throwing an exception in {@code postDeregister}
* will not change the state of the MBean:
* the MBean was already successfully deregistered and will remain so. </p>
* <p>This might be confusing for the code calling
* {@code unregisterMBean()}, as it might assume that MBean deregistration
* has failed. Therefore it is recommended that implementations of
* {@code postDeregister} do not throw Runtime Exceptions or Errors if it
* can be avoided.</p>
*/
public void postDeregister();
}

View File

@@ -0,0 +1,61 @@
/*
* 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;
/**
* Wraps exceptions thrown by the preRegister(), preDeregister() methods
* of the <CODE>MBeanRegistration</CODE> interface.
*
* @since 1.5
*/
public class MBeanRegistrationException extends MBeanException {
/* Serial version */
private static final long serialVersionUID = 4482382455277067805L;
/**
* Creates an <CODE>MBeanRegistrationException</CODE> that wraps
* the actual <CODE>java.lang.Exception</CODE>.
*
* @param e the wrapped exception.
*/
public MBeanRegistrationException(java.lang.Exception e) {
super(e) ;
}
/**
* Creates an <CODE>MBeanRegistrationException</CODE> that wraps
* the actual <CODE>java.lang.Exception</CODE> with a detailed
* message.
*
* @param e the wrapped exception.
* @param message the detail message.
*/
public MBeanRegistrationException(java.lang.Exception e, String message) {
super(e, message) ;
}
}

View File

@@ -0,0 +1,795 @@
/*
* Copyright (c) 1999, 2013, 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;
/**
* <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 javax.management.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 id="notif">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, and unless otherwise specified,
* {@code className} 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, null, "queryMBeans")}.
* Additionally, for each MBean <em>n</em> that matches <code>name</code>,
* if the caller's permissions do not imply {@link
* MBeanPermission#MBeanPermission(String,String,ObjectName,String)
* MBeanPermission(className, null, <em>n</em>, "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, null, "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")},
* where {@code className} is the name of the class which is to
* be instantiated.</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")}.
*
* <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 {
/**
* {@inheritDoc}
* <p>If this method successfully creates an MBean, a notification
* is sent as described <a href="#notif">above</a>.</p>
*
* @throws RuntimeOperationsException {@inheritDoc}
* @throws RuntimeMBeanException {@inheritDoc}
* @throws RuntimeErrorException {@inheritDoc}
*/
public ObjectInstance createMBean(String className, ObjectName name)
throws ReflectionException, InstanceAlreadyExistsException,
MBeanRegistrationException, MBeanException,
NotCompliantMBeanException;
/**
* {@inheritDoc}
* <p>If this method successfully creates an MBean, a notification
* is sent as described <a href="#notif">above</a>.</p>
*
* @throws RuntimeOperationsException {@inheritDoc}
* @throws RuntimeMBeanException {@inheritDoc}
* @throws RuntimeErrorException {@inheritDoc}
*/
public ObjectInstance createMBean(String className, ObjectName name,
ObjectName loaderName)
throws ReflectionException, InstanceAlreadyExistsException,
MBeanRegistrationException, MBeanException,
NotCompliantMBeanException, InstanceNotFoundException;
/**
* {@inheritDoc}
* <p>If this method successfully creates an MBean, a notification
* is sent as described <a href="#notif">above</a>.</p>
*
* @throws RuntimeOperationsException {@inheritDoc}
* @throws RuntimeMBeanException {@inheritDoc}
* @throws RuntimeErrorException {@inheritDoc}
*/
public ObjectInstance createMBean(String className, ObjectName name,
Object params[], String signature[])
throws ReflectionException, InstanceAlreadyExistsException,
MBeanRegistrationException, MBeanException,
NotCompliantMBeanException;
/**
* {@inheritDoc}
* <p>If this method successfully creates an MBean, a notification
* is sent as described <a href="#notif">above</a>.</p>
*
* @throws RuntimeOperationsException {@inheritDoc}
* @throws RuntimeMBeanException {@inheritDoc}
* @throws RuntimeErrorException {@inheritDoc}
*/
public ObjectInstance createMBean(String className, ObjectName name,
ObjectName loaderName, Object params[],
String signature[])
throws ReflectionException, InstanceAlreadyExistsException,
MBeanRegistrationException, MBeanException,
NotCompliantMBeanException, InstanceNotFoundException;
/**
* <p>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.
*
* <p>If this method successfully registers an MBean, a notification
* is sent as described <a href="#notif">above</a>.</p>
*
* @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 RuntimeMBeanException If the <CODE>postRegister</CODE>
* (<CODE>MBeanRegistration</CODE> interface) method of the MBean throws a
* <CODE>RuntimeException</CODE>, the <CODE>registerMBean</CODE> method will
* throw a <CODE>RuntimeMBeanException</CODE>, although the MBean
* registration succeeded. In such a case, the MBean will be actually
* registered even though the <CODE>registerMBean</CODE> method
* threw an exception. Note that <CODE>RuntimeMBeanException</CODE> can
* also be thrown by <CODE>preRegister</CODE>, in which case the MBean
* will not be registered.
* @exception RuntimeErrorException If the <CODE>postRegister</CODE>
* (<CODE>MBeanRegistration</CODE> interface) method of the MBean throws an
* <CODE>Error</CODE>, the <CODE>registerMBean</CODE> method will
* throw a <CODE>RuntimeErrorException</CODE>, although the MBean
* registration succeeded. In such a case, the MBean will be actually
* registered even though the <CODE>registerMBean</CODE> method
* threw an exception. Note that <CODE>RuntimeErrorException</CODE> can
* also be thrown by <CODE>preRegister</CODE>, in which case 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.
* @see javax.management.MBeanRegistration
*/
public ObjectInstance registerMBean(Object object, ObjectName name)
throws InstanceAlreadyExistsException, MBeanRegistrationException,
NotCompliantMBeanException;
/**
* {@inheritDoc}
*
* <p>If this method successfully unregisters an MBean, a notification
* is sent as described <a href="#notif">above</a>.</p>
*
* @throws RuntimeOperationsException {@inheritDoc}
* @throws RuntimeMBeanException {@inheritDoc}
* @throws RuntimeErrorException {@inheritDoc}
*/
public void unregisterMBean(ObjectName name)
throws InstanceNotFoundException, MBeanRegistrationException;
// doc comment inherited from MBeanServerConnection
public ObjectInstance getObjectInstance(ObjectName name)
throws InstanceNotFoundException;
/**
* {@inheritDoc}
* @throws RuntimeOperationsException {@inheritDoc}
*/
public Set<ObjectInstance> queryMBeans(ObjectName name, QueryExp query);
/**
* {@inheritDoc}
* @throws RuntimeOperationsException {@inheritDoc}
*/
public Set<ObjectName> queryNames(ObjectName name, QueryExp query);
// doc comment inherited from MBeanServerConnection
/**
* @throws RuntimeOperationsException {@inheritDoc}
*/
public boolean isRegistered(ObjectName name);
/**
* 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
/**
* @throws RuntimeOperationsException {@inheritDoc}
*/
public Object getAttribute(ObjectName name, String attribute)
throws MBeanException, AttributeNotFoundException,
InstanceNotFoundException, ReflectionException;
// doc comment inherited from MBeanServerConnection
/**
* @throws RuntimeOperationsException {@inheritDoc}
*/
public AttributeList getAttributes(ObjectName name, String[] attributes)
throws InstanceNotFoundException, ReflectionException;
// doc comment inherited from MBeanServerConnection
/**
* @throws RuntimeOperationsException {@inheritDoc}
*/
public void setAttribute(ObjectName name, Attribute attribute)
throws InstanceNotFoundException, AttributeNotFoundException,
InvalidAttributeValueException, MBeanException,
ReflectionException;
// doc comment inherited from MBeanServerConnection
/**
* @throws RuntimeOperationsException {@inheritDoc}
*/
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, plus:
/**
* {@inheritDoc}
* If the source of the notification
* is a reference to an MBean object, the MBean server will replace it
* by that MBean's ObjectName. Otherwise the source is unchanged.
*/
public void addNotificationListener(ObjectName name,
NotificationListener listener,
NotificationFilter filter,
Object handback)
throws InstanceNotFoundException;
/**
* {@inheritDoc}
* @throws RuntimeOperationsException {@inheritDoc}
*/
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;
/**
* <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;
/**
* <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;
/**
* <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;
/**
* <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;
/**
* <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;
/**
* <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;
/**
* <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;
/**
* <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;
/**
* <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;
/**
* <p>Return the ClassLoaderRepository for this MBeanServer.
* @return The ClassLoaderRepository for this MBeanServer.
*
*/
public ClassLoaderRepository getClassLoaderRepository();
}

View File

@@ -0,0 +1,113 @@
/*
* 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.JmxMBeanServer;
/**
* <p>This class represents a builder that creates a default
* {@link javax.management.MBeanServer} implementation.
* The JMX {@link javax.management.MBeanServerFactory} allows
* applications to provide their custom MBeanServer
* implementation by providing a subclass of this class.</p>
*
* @see MBeanServer
* @see MBeanServerFactory
*
* @since 1.5
*/
public class MBeanServerBuilder {
/**
* Public default constructor.
**/
public MBeanServerBuilder() {
}
/**
* This method creates a new MBeanServerDelegate for a new MBeanServer.
* When creating a new MBeanServer the
* {@link javax.management.MBeanServerFactory} first calls this method
* in order to create a new MBeanServerDelegate.
* <br>Then it calls
* <code>newMBeanServer(defaultDomain,outer,delegate)</code>
* passing the <var>delegate</var> that should be used by the MBeanServer
* implementation.
* <p>Note that the passed <var>delegate</var> might not be directly the
* MBeanServerDelegate that was returned by this method. It could
* be, for instance, a new object wrapping the previously
* returned object.
*
* @return A new {@link javax.management.MBeanServerDelegate}.
**/
public MBeanServerDelegate newMBeanServerDelegate() {
return JmxMBeanServer.newMBeanServerDelegate();
}
/**
* This method creates a new MBeanServer implementation object.
* When creating a new MBeanServer the
* {@link javax.management.MBeanServerFactory} first calls
* <code>newMBeanServerDelegate()</code> in order to obtain a new
* {@link javax.management.MBeanServerDelegate} for the new
* MBeanServer. Then it calls
* <code>newMBeanServer(defaultDomain,outer,delegate)</code>
* passing the <var>delegate</var> that should be used by the MBeanServer
* implementation.
* <p>Note that the passed <var>delegate</var> might not be directly the
* MBeanServerDelegate that was returned by this implementation. It could
* be, for instance, a new object wrapping the previously
* returned delegate.
* <p>The <var>outer</var> parameter is a pointer to the MBeanServer that
* should be passed to the {@link javax.management.MBeanRegistration}
* interface when registering MBeans inside the MBeanServer.
* If <var>outer</var> is <code>null</code>, then the MBeanServer
* implementation must use its own <code>this</code> reference when
* invoking the {@link javax.management.MBeanRegistration} interface.
* <p>This makes it possible for a MBeanServer implementation to wrap
* another MBeanServer implementation, in order to implement, e.g,
* security checks, or to prevent access to the actual MBeanServer
* implementation by returning a pointer to a wrapping object.
*
* @param defaultDomain Default domain of the new MBeanServer.
* @param outer A pointer to the MBeanServer object that must be
* passed to the MBeans when invoking their
* {@link javax.management.MBeanRegistration} interface.
* @param delegate A pointer to the MBeanServerDelegate associated
* with the new MBeanServer. The new MBeanServer must register
* this MBean in its MBean repository.
*
* @return A new private implementation of an MBeanServer.
**/
public MBeanServer newMBeanServer(String defaultDomain,
MBeanServer outer,
MBeanServerDelegate delegate) {
// By default, MBeanServerInterceptors are disabled.
// Use com.sun.jmx.mbeanserver.MBeanServerBuilder to obtain
// MBeanServers on which MBeanServerInterceptors are enabled.
return JmxMBeanServer.newMBeanServer(defaultDomain,outer,delegate,
false);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,234 @@
/*
* Copyright (c) 1999, 2008, 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.JmxProperties;
import com.sun.jmx.defaults.ServiceName;
import com.sun.jmx.mbeanserver.Util;
/**
* 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 {
/** The MBean server agent identification.*/
private String mbeanServerId ;
/** 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");
}
/**
* Create a MBeanServerDelegate object.
*/
public MBeanServerDelegate () {
stamp = getStamp();
broadcaster = new NotificationBroadcasterSupport() ;
}
/**
* 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) {
JmxProperties.MISC_LOGGER.finest("Can't get local host name, " +
"using \"localhost\" instead. Cause is: "+e);
localHost = "localhost";
}
mbeanServerId = localHost + "_" + stamp;
}
return mbeanServerId;
}
/**
* Returns the full name of the JMX specification implemented
* by this product.
*
* @return the specification name.
*/
public String getSpecificationName() {
return ServiceName.JMX_SPEC_NAME;
}
/**
* Returns the version of the JMX specification implemented
* by this product.
*
* @return the specification version.
*/
public String getSpecificationVersion() {
return ServiceName.JMX_SPEC_VERSION;
}
/**
* Returns the vendor of the JMX specification implemented
* by this product.
*
* @return the specification vendor.
*/
public String getSpecificationVendor() {
return ServiceName.JMX_SPEC_VENDOR;
}
/**
* Returns the JMX implementation name (the name of this product).
*
* @return the implementation name.
*/
public String getImplementationName() {
return ServiceName.JMX_IMPL_NAME;
}
/**
* 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 "";
}
}
/**
* 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) ;
}
/**
* 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);
}
/**
* Defines the default ObjectName of the MBeanServerDelegate.
*
* @since 1.6
*/
public static final ObjectName DELEGATE_NAME =
Util.newObjectName("JMImplementation:type=MBeanServerDelegate");
/* 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;
}
}

View File

@@ -0,0 +1,88 @@
/*
* 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;
/**
* Defines the management interface of an object of class MBeanServerDelegate.
*
* @since 1.5
*/
public interface MBeanServerDelegateMBean {
/**
* Returns the MBean server agent identity.
*
* @return the agent identity.
*/
public String getMBeanServerId();
/**
* Returns the full name of the JMX specification implemented
* by this product.
*
* @return the specification name.
*/
public String getSpecificationName();
/**
* Returns the version of the JMX specification implemented
* by this product.
*
* @return the specification version.
*/
public String getSpecificationVersion();
/**
* Returns the vendor of the JMX specification implemented
* by this product.
*
* @return the specification vendor.
*/
public String getSpecificationVendor();
/**
* Returns the JMX implementation name (the name of this product).
*
* @return the implementation name.
*/
public String getImplementationName();
/**
* Returns the JMX implementation version (the version of this product).
*
* @return the implementation version.
*/
public String getImplementationVersion();
/**
* Returns the JMX implementation vendor (the vendor of this product).
*
* @return the implementation vendor.
*/
public String getImplementationVendor();
}

View File

@@ -0,0 +1,543 @@
/*
* Copyright (c) 1999, 2013, 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.JmxProperties;
import static com.sun.jmx.defaults.JmxProperties.JMX_INITIAL_BUILDER;
import static com.sun.jmx.defaults.JmxProperties.MBEANSERVER_LOGGER;
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;
import sun.reflect.misc.ReflectUtil;
/**
* <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() {
}
/**
* The builder that will be used to construct MBeanServers.
*
**/
private static MBeanServerBuilder builder = null;
/**
* 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;
// }
/**
* 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;
// }
/**
* 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);
}
/**
* <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);
}
/**
* <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;
}
/**
* <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);
}
/**
* <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;
}
}
/**
* <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 = mBeanServerId(mbs);
if (agentId.equals(name))
result.add(mbs);
}
return result;
}
/**
* 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 mBeanServerId(MBeanServer mbs) {
try {
return (String) mbs.getAttribute(MBeanServerDelegate.DELEGATE_NAME,
"MBeanServerId");
} catch (JMException e) {
JmxProperties.MISC_LOGGER.finest(
"Ignoring exception while getting MBeanServerId: "+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>();
/**
* 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 ReflectUtil.forName(builderClassName);
}
/**
* 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 abuilder = builderClass.newInstance();
return (MBeanServerBuilder)abuilder;
} catch (RuntimeException x) {
throw x;
} catch (Exception x) {
final String msg =
"Failed to instantiate a MBeanServerBuilder from " +
builderClass + ": " + x;
throw new JMRuntimeException(msg, x);
}
}
/**
* 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;
}
}
/**
* 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;
}
}

View File

@@ -0,0 +1,497 @@
/*
* Copyright (c) 2002, 2013, 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;
/**
* <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 {
/**
* <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);
}
/**
* <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 (Proxy.isProxyClass(connection.getClass())) {
if (MBeanServerInvocationHandler.class.isAssignableFrom(
Proxy.getInvocationHandler(connection).getClass())) {
throw new IllegalArgumentException("Wrapping MBeanServerInvocationHandler");
}
}
if (objectName == null) {
throw new IllegalArgumentException("Null object name");
}
this.connection = connection;
this.objectName = objectName;
this.isMXBean = isMXBean;
}
/**
* <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;
}
/**
* <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;
}
/**
* <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;
}
/**
* <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, boolean)
*/
public static <T> T newProxyInstance(MBeanServerConnection connection,
ObjectName objectName,
Class<T> interfaceClass,
boolean notificationBroadcaster) {
return JMX.newMBeanProxy(connection, objectName, interfaceClass, notificationBroadcaster);
}
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) {
try {
p = new MXBeanProxy(mxbeanInterface);
} catch (IllegalArgumentException e) {
String msg = "Cannot make MXBean proxy for " +
mxbeanInterface.getName() + ": " + e.getMessage();
IllegalArgumentException iae =
new IllegalArgumentException(msg, e.getCause());
iae.setStackTrace(e.getStackTrace());
throw iae;
}
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;
if (methodName.equals("finalize")
&& method.getParameterTypes().length == 0) {
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();
} else if (methodName.equals("finalize")) {
// ignore the finalizer invocation via proxy
return null;
}
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;
}

View File

@@ -0,0 +1,158 @@
/*
* Copyright (c) 1999, 2013, 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;
/**
* Represents a notification emitted by the MBean Server through the MBeanServerDelegate MBean.
* The MBean Server emits the following types of notifications: MBean registration, MBean
* unregistration.
* <P>
* To receive MBeanServerNotifications, you need to register a listener with
* the {@link MBeanServerDelegate MBeanServerDelegate} MBean
* that represents the MBeanServer. The ObjectName of the MBeanServerDelegate is
* {@link MBeanServerDelegate#DELEGATE_NAME}, which is
* <CODE>JMImplementation:type=MBeanServerDelegate</CODE>.
*
* <p>The following code prints a message every time an MBean is registered
* or unregistered in the MBean Server {@code mbeanServer}:</p>
*
* <pre>
* private static final NotificationListener printListener = new NotificationListener() {
* public void handleNotification(Notification n, Object handback) {
* if (!(n instanceof MBeanServerNotification)) {
* System.out.println("Ignored notification of class " + n.getClass().getName());
* return;
* }
* MBeanServerNotification mbsn = (MBeanServerNotification) n;
* String what;
* if (n.getType().equals(MBeanServerNotification.REGISTRATION_NOTIFICATION))
* what = "MBean registered";
* else if (n.getType().equals(MBeanServerNotification.UNREGISTRATION_NOTIFICATION))
* what = "MBean unregistered";
* else
* what = "Unknown type " + n.getType();
* System.out.println("Received MBean Server notification: " + what + ": " +
* mbsn.getMBeanName());
* }
* };
*
* ...
* mbeanServer.addNotificationListener(
* MBeanServerDelegate.DELEGATE_NAME, printListener, null, null);
* </pre>
*
* <p id="group">
* An MBean which is not an {@link MBeanServerDelegate} may also emit
* MBeanServerNotifications. In particular, there is a convention for
* MBeans to emit an MBeanServerNotification for a group of MBeans.</p>
*
* <p>An MBeanServerNotification emitted to denote the registration or
* unregistration of a group of MBeans has the following characteristics:
* <ul><li>Its {@linkplain Notification#getType() notification type} is
* {@code "JMX.mbean.registered.group"} or
* {@code "JMX.mbean.unregistered.group"}, which can also be written {@link
* MBeanServerNotification#REGISTRATION_NOTIFICATION}{@code + ".group"} or
* {@link
* MBeanServerNotification#UNREGISTRATION_NOTIFICATION}{@code + ".group"}.
* </li>
* <li>Its {@linkplain #getMBeanName() MBean name} is an ObjectName pattern
* that selects the set (or a superset) of the MBeans being registered
* or unregistered</li>
* <li>Its {@linkplain Notification#getUserData() user data} can optionally
* be set to an array of ObjectNames containing the names of all MBeans
* being registered or unregistered.</li>
* </ul>
*
* <p>
* MBeans which emit these group registration/unregistration notifications will
* declare them in their {@link MBeanInfo#getNotifications()
* MBeanNotificationInfo}.
* </p>
*
* @since 1.5
*/
public class MBeanServerNotification extends Notification {
/* Serial version */
private static final long serialVersionUID = 2876477500475969677L;
/**
* Notification type denoting that an MBean has been registered.
* Value is "JMX.mbean.registered".
*/
public static final String REGISTRATION_NOTIFICATION =
"JMX.mbean.registered";
/**
* Notification type denoting that an MBean has been unregistered.
* Value is "JMX.mbean.unregistered".
*/
public static final String UNREGISTRATION_NOTIFICATION =
"JMX.mbean.unregistered";
/**
* @serial The object names of the MBeans concerned by this notification
*/
private final ObjectName objectName;
/**
* 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;
}
/**
* 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;
}
@Override
public String toString() {
return super.toString() + "[mbeanName=" + objectName + "]";
}
}

View File

@@ -0,0 +1,371 @@
/*
* 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;
/** 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;
/** <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);
}
/** <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;
}
/**
* <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);
}
/**
* 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();
}
}
/**
* 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 {
/** @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);
}
}

View File

@@ -0,0 +1,108 @@
/*
* Copyright (c) 2002, 2013, 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.security.BasicPermission;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
/**
* This permission represents "trust" in a signer or codebase.
* <p>
* MBeanTrustPermission contains a target name but no actions list.
* A single target name, "register", is defined for this permission.
* The target "*" is also allowed, permitting "register" and any future
* targets that may be defined.
* Only the null value or the empty string are allowed for the action
* to allow the policy object to create the permissions specified in
* the policy file.
* <p>
* If a signer, or codesource is granted this permission, then it is
* considered a trusted source for MBeans. Only MBeans from trusted
* sources may be registered in the MBeanServer.
*
* @since 1.5
*/
public class MBeanTrustPermission extends BasicPermission {
private static final long serialVersionUID = -2952178077029018140L;
/** <p>Create a new MBeanTrustPermission with the given name.</p>
<p>This constructor is equivalent to
<code>MBeanTrustPermission(name,null)</code>.</p>
@param name the name of the permission. It must be
"register" or "*" for this permission.
*
* @throws NullPointerException if <code>name</code> is <code>null</code>.
* @throws IllegalArgumentException if <code>name</code> is neither
* "register" nor "*".
*/
public MBeanTrustPermission(String name) {
this(name, null);
}
/** <p>Create a new MBeanTrustPermission with the given name.</p>
@param name the name of the permission. It must be
"register" or "*" for this permission.
@param actions the actions for the permission. It must be
null or <code>""</code>.
*
* @throws NullPointerException if <code>name</code> is <code>null</code>.
* @throws IllegalArgumentException if <code>name</code> is neither
* "register" nor "*"; or if <code>actions</code> is a non-null
* non-empty string.
*/
public MBeanTrustPermission(String name, String actions) {
super(name, actions);
validate(name,actions);
}
private static void validate(String name, String actions) {
/* Check that actions is a null empty string */
if (actions != null && actions.length() > 0) {
throw new IllegalArgumentException("MBeanTrustPermission actions must be null: " +
actions);
}
if (!name.equals("register") && !name.equals("*")) {
throw new IllegalArgumentException("MBeanTrustPermission: Unknown target name " +
"[" + name + "]");
}
}
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException {
// Reading private fields of base class
in.defaultReadObject();
try {
validate(super.getName(),super.getActions());
} catch (IllegalArgumentException e) {
throw new InvalidObjectException(e.getMessage());
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,55 @@
/*
* 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;
/**
* 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;
/**
* Default constructor.
*/
public MalformedObjectNameException() {
super();
}
/**
* Constructor that allows a specific error message to be specified.
*
* @param message the detail message.
*/
public MalformedObjectNameException(String message) {
super(message);
}
}

View File

@@ -0,0 +1,182 @@
/*
* Copyright (c) 1999, 2008, 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;
/**
* This class is used by the query-building mechanism to represent binary
* relations.
* @serial include
*
* @since 1.5
*/
class MatchQueryExp extends QueryEval implements QueryExp {
/* Serial version */
private static final long serialVersionUID = -7156603696948215014L;
/**
* @serial The attribute value to be matched
*/
private AttributeValueExp exp;
/**
* @serial The pattern to be matched
*/
private String pattern;
/**
* Basic Constructor.
*/
public MatchQueryExp() {
}
/**
* Creates a new MatchQueryExp where the specified AttributeValueExp matches
* the specified pattern StringValueExp.
*/
public MatchQueryExp(AttributeValueExp a, StringValueExp s) {
exp = a;
pattern = s.getValue();
}
/**
* Returns the attribute of the query.
*/
public AttributeValueExp getAttribute() {
return exp;
}
/**
* Returns the pattern of the query.
*/
public String getPattern() {
return pattern;
}
/**
* Applies the MatchQueryExp on a MBean.
*
* @param name The name of the MBean on which the MatchQueryExp 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 {
ValueExp val = exp.apply(name);
if (!(val instanceof StringValueExp)) {
return false;
}
return wildmatch(((StringValueExp)val).getValue(), pattern);
}
/**
* Returns the string representing the object
*/
public String toString() {
return exp + " like " + new StringValueExp(pattern);
}
/*
* Tests whether string s is matched by pattern p.
* Supports "?", "*", "[", each of which may be escaped with "\";
* character classes may use "!" for negation and "-" for range.
* Not yet supported: internationalization; "\" inside brackets.<P>
* Wildcard matching routine by Karl Heuer. Public Domain.<P>
*/
private static boolean wildmatch(String s, String p) {
char c;
int si = 0, pi = 0;
int slen = s.length();
int plen = p.length();
while (pi < plen) { // While still string
c = p.charAt(pi++);
if (c == '?') {
if (++si > slen)
return false;
} else if (c == '[') { // Start of choice
if (si >= slen)
return false;
boolean wantit = true;
boolean seenit = false;
if (p.charAt(pi) == '!') {
wantit = false;
++pi;
}
while ((c = p.charAt(pi)) != ']' && ++pi < plen) {
if (p.charAt(pi) == '-' &&
pi+1 < plen &&
p.charAt(pi+1) != ']') {
if (s.charAt(si) >= p.charAt(pi-1) &&
s.charAt(si) <= p.charAt(pi+1)) {
seenit = true;
}
++pi;
} else {
if (c == s.charAt(si)) {
seenit = true;
}
}
}
if ((pi >= plen) || (wantit != seenit)) {
return false;
}
++pi;
++si;
} else if (c == '*') { // Wildcard
if (pi >= plen)
return true;
do {
if (wildmatch(s.substring(si), p.substring(pi)))
return true;
} while (++si < slen);
return false;
} else if (c == '\\') {
if (pi >= plen || si >= slen ||
p.charAt(pi++) != s.charAt(si++))
return false;
} else {
if (si >= slen || c != s.charAt(si++)) {
return false;
}
}
}
return (si == slen);
}
}

View File

@@ -0,0 +1,56 @@
/*
* 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;
/**
* 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;
/**
* Default constructor.
*/
public NotCompliantMBeanException() {
super();
}
/**
* Constructor that allows a specific error message to be specified.
*
* @param message the detail message.
*/
public NotCompliantMBeanException(String message) {
super(message);
}
}

View File

@@ -0,0 +1,93 @@
/*
* Copyright (c) 1999, 2008, 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;
/**
* 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;
/**
* @serial The negated {@link QueryExp}
*/
private QueryExp exp;
/**
* Basic Constructor.
*/
public NotQueryExp() {
}
/**
* Creates a new NotQueryExp for negating the specified QueryExp.
*/
public NotQueryExp(QueryExp q) {
exp = q;
}
/**
* Returns the negated query expression of the query.
*/
public QueryExp getNegatedExp() {
return exp;
}
/**
* 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;
}
/**
* Returns the string representing the object.
*/
@Override
public String toString() {
return "not (" + exp + ")";
}
}

View File

@@ -0,0 +1,397 @@
/*
* Copyright (c) 1999, 2008, 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;
/**
* <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;
/**
* @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
/**
* @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;
/**
* @serial The notification sequence number.
* A serial number which identify particular instance
* of notification in the context of the notification source.
*/
private long sequenceNumber;
/**
* @serial The notification timestamp.
* Indicating when the notification was generated
*/
private long timeStamp;
/**
* @serial The notification user data.
* Used for whatever other data the notification
* source wishes to communicate to its consumers
*/
private Object userData = null;
/**
* @serial The notification message.
*/
private String message = "";
/**
* <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;
/**
* 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() ;
}
/**
* 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 ;
}
/**
* 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 ;
}
/**
* 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 ;
}
/**
* 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;
}
/**
* 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 ;
}
/**
* 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;
}
/**
* Get the notification type.
*
* @return The notification type. It's a string expressed in a dot notation
* similar to Java properties. It is recommended that the notification type
* should follow the reverse-domain-name convention used by Java package
* names. An example of a notification type is com.example.alarm.router.
*/
public String getType() {
return type ;
}
/**
* Get the notification timestamp.
*
* @return The notification timestamp.
*
* @see #setTimeStamp
*/
public long getTimeStamp() {
return timeStamp ;
}
/**
* 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;
}
/**
* Get the notification message.
*
* @return The message string of this notification object.
*
*/
public String getMessage() {
return message ;
}
/**
* 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 ;
}
/**
* 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 ;
}
/**
* Returns a String representation of this notification.
*
* @return A String representation of this notification.
*/
@Override
public String toString() {
return super.toString()+"[type="+type+"][message="+message+"]";
}
/**
* 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;
}
/**
* 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();
}
}
}

View File

@@ -0,0 +1,127 @@
/*
* 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;
import java.util.concurrent.CopyOnWriteArrayList; // for Javadoc
/**
* <p>Interface implemented by an MBean that emits Notifications. It
* allows a listener to be registered with the MBean as a notification
* listener.</p>
*
* <h3>Notification dispatch</h3>
*
* <p>When an MBean emits a notification, it considers each listener that has been
* added with {@link #addNotificationListener addNotificationListener} and not
* subsequently removed with {@link #removeNotificationListener removeNotificationListener}.
* If a filter was provided with that listener, and if the filter's
* {@link NotificationFilter#isNotificationEnabled isNotificationEnabled} method returns
* false, the listener is ignored. Otherwise, the listener's
* {@link NotificationListener#handleNotification handleNotification} method is called with
* the notification, as well as the handback object that was provided to
* {@code addNotificationListener}.</p>
*
* <p>If the same listener is added more than once, it is considered as many times as it was
* added. It is often useful to add the same listener with different filters or handback
* objects.</p>
*
* <p>Implementations of this interface can differ regarding the thread in which the methods
* of filters and listeners are called.</p>
*
* <p>If the method call of a filter or listener throws an {@link Exception}, then that
* exception should not prevent other listeners from being invoked. However, if the method
* call throws an {@link Error}, then it is recommended that processing of the notification
* stop at that point, and if it is possible to propagate the {@code Error} to the sender of
* the notification, this should be done.</p>
*
* <p>New code should use the {@link NotificationEmitter} interface
* instead.</p>
*
* <p>Implementations of this interface and of {@code NotificationEmitter}
* should be careful about synchronization. In particular, it is not a good
* idea for an implementation to hold any locks while it is calling a
* listener. To deal with the possibility that the list of listeners might
* change while a notification is being dispatched, a good strategy is to
* use a {@link CopyOnWriteArrayList} for this list.
*
* @since 1.5
*/
public interface NotificationBroadcaster {
/**
* Adds a listener to this MBean.
*
* @param listener The listener object which will handle the
* notifications emitted by the broadcaster.
* @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 Listener parameter is null.
*
* @see #removeNotificationListener
*/
public void addNotificationListener(NotificationListener listener,
NotificationFilter filter,
Object handback)
throws java.lang.IllegalArgumentException;
/**
* Removes a listener from this MBean. If the listener
* has been registered with different handback objects or
* notification filters, all entries corresponding to the listener
* will be removed.
*
* @param listener A listener that was previously added to this
* MBean.
*
* @exception ListenerNotFoundException The listener is not
* registered with the MBean.
*
* @see #addNotificationListener
* @see NotificationEmitter#removeNotificationListener
*/
public void removeNotificationListener(NotificationListener listener)
throws ListenerNotFoundException;
/**
* <p>Returns an array indicating, for each notification this
* MBean may send, the name of the Java class of the notification
* and the notification type.</p>
*
* <p>It is not illegal for the MBean to send notifications not
* described in this array. However, some clients of the MBean
* server may depend on the array being complete for their correct
* functioning.</p>
*
* @return the array of possible notifications.
*/
public MBeanNotificationInfo[] getNotificationInfo();
}

View File

@@ -0,0 +1,367 @@
/*
* Copyright (c) 1999, 2013, 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.Objects;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Executor;
import com.sun.jmx.remote.util.ClassLogger;
/**
* <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 {
/**
* 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);
}
/**
* 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);
}
/**
* <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);
}
/**
* <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();
}
/**
* 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();
}
/**
* 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));
}
}
}
/**
* <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;
}
@Override
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);
}
@Override
public int hashCode() {
return Objects.hashCode(listener);
}
}
private static class WildcardListenerInfo extends ListenerInfo {
WildcardListenerInfo(NotificationListener listener) {
super(listener, null, null);
}
@Override
public boolean equals(Object o) {
assert (!(o instanceof WildcardListenerInfo));
return o.equals(this);
}
@Override
public int hashCode() {
return super.hashCode();
}
}
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");
}

View File

@@ -0,0 +1,98 @@
/*
* 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.util.concurrent.CopyOnWriteArrayList; // for Javadoc
/**
* <p>Interface implemented by an MBean that emits Notifications. It
* allows a listener to be registered with the MBean as a notification
* listener.</p>
*
* <h3>Notification dispatch</h3>
*
*<p>When an MBean emits a notification, it considers each listener that has been
* added with {@link #addNotificationListener addNotificationListener} and not
* subsequently removed with {@link #removeNotificationListener removeNotificationListener}.
* If a filter was provided with that listener, and if the filter's
* {@link NotificationFilter#isNotificationEnabled isNotificationEnabled} method returns
* false, the listener is ignored. Otherwise, the listener's
* {@link NotificationListener#handleNotification handleNotification} method is called with
* the notification, as well as the handback object that was provided to
* {@code addNotificationListener}.</p>
*
* <p>If the same listener is added more than once, it is considered as many times as it was
* added. It is often useful to add the same listener with different filters or handback
* objects.</p>
*
* <p>Implementations of this interface can differ regarding the thread in which the methods
* of filters and listeners are called.</p>
*
* <p>If the method call of a filter or listener throws an {@link Exception}, then that
* exception should not prevent other listeners from being invoked. However, if the method
* call throws an {@link Error}, then it is recommended that processing of the notification
* stop at that point, and if it is possible to propagate the {@code Error} to the sender of
* the notification, this should be done.</p>
*
* <p>This interface should be used by new code in preference to the
* {@link NotificationBroadcaster} interface.</p>
*
* <p>Implementations of this interface and of {@code NotificationBroadcaster}
* should be careful about synchronization. In particular, it is not a good
* idea for an implementation to hold any locks while it is calling a
* listener. To deal with the possibility that the list of listeners might
* change while a notification is being dispatched, a good strategy is to
* use a {@link CopyOnWriteArrayList} for this list.
*
* @since 1.5
*/
public interface NotificationEmitter extends NotificationBroadcaster {
/**
* <p>Removes a listener from this MBean. The MBean must have a
* listener that exactly matches the given <code>listener</code>,
* <code>filter</code>, and <code>handback</code> parameters. If
* there is more than one such listener, only one is removed.</p>
*
* <p>The <code>filter</code> and <code>handback</code> parameters
* may be null if and only if they are null in a listener to be
* removed.</p>
*
* @param listener A listener that was previously added to this
* MBean.
* @param filter The filter that was specified when the listener
* was added.
* @param handback The handback that was specified when the listener was
* added.
*
* @exception ListenerNotFoundException The listener is not
* registered with the MBean, or it is not registered with the
* given filter and handback.
*/
public void removeNotificationListener(NotificationListener listener,
NotificationFilter filter,
Object handback)
throws ListenerNotFoundException;
}

View File

@@ -0,0 +1,44 @@
/*
* 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;
/**
* To be implemented by a any class acting as a notification filter.
* It allows a registered notification listener to filter the notifications of interest.
*
* @since 1.5
*/
public interface NotificationFilter extends java.io.Serializable {
/**
* Invoked before sending the specified notification to the listener.
*
* @param notification The notification to be sent.
* @return <CODE>true</CODE> if the notification has to be sent to the listener, <CODE>false</CODE> otherwise.
*/
public boolean isNotificationEnabled(Notification notification);
}

View File

@@ -0,0 +1,163 @@
/*
* 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;
/**
* 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;
/**
* @serial {@link Vector} that contains the enabled notification types.
* The default value is an empty vector.
*/
private List<String> enabledTypes = new Vector<String>();
/**
* 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;
}
/**
* 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);
}
}
/**
* 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);
}
/**
* Disables all notification types.
*/
public synchronized void disableAllTypes() {
enabledTypes.clear();
}
/**
* 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;
}
}

View File

@@ -0,0 +1,48 @@
/*
* Copyright (c) 1999, 2008, 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;
/**
* Should be implemented by an object that wants to receive notifications.
*
* @since 1.5
*/
public interface NotificationListener extends java.util.EventListener {
/**
* 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
* addNotificationListener call and resent, without modification, to the
* listener.
*/
public void handleNotification(Notification notification, Object handback);
}

View File

@@ -0,0 +1,260 @@
/*
* Copyright (c) 1999, 2013, 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;
/**
* 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;
/**
* @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 = 0.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
/**
* Basic constructor.
*/
public NumericValueExp() {
}
/** Creates a new NumericValue representing the numeric literal @{code val}.*/
NumericValueExp(Number val)
{
this.val = val;
}
/**
* Returns a double numeric value
*/
public double doubleValue() {
if (val instanceof Long || val instanceof Integer)
{
return (double)(val.longValue());
}
return val.doubleValue();
}
/**
* Returns a long numeric value
*/
public long longValue() {
if (val instanceof Long || val instanceof Integer)
{
return val.longValue();
}
return (long)(val.doubleValue());
}
/**
* Returns true is if the numeric value is a long, false otherwise.
*/
public boolean isLong() {
return (val instanceof Long || val instanceof Integer);
}
/**
* Returns the string representing the object
*/
public String toString() {
if (val == null)
return "null";
if (val instanceof Long || val instanceof Integer)
{
return Long.toString(val.longValue());
}
double d = val.doubleValue();
if (Double.isInfinite(d))
return (d > 0) ? "(1.0 / 0.0)" : "(-1.0 / 0.0)";
if (Double.isNaN(d))
return "(0.0 / 0.0)";
return Double.toString(d);
}
/**
* 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;
}
/**
* 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 = longVal;
}
else
{
this.val = doubleVal;
}
}
else
{
// Read an object serialized in the new serial form
//
in.defaultReadObject();
}
}
/**
* 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();
}
}
@Deprecated
public void setMBeanServer(MBeanServer s) {
super.setMBeanServer(s);
}
}

View File

@@ -0,0 +1,154 @@
/*
* 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;
// java import
import java.io.Serializable;
// RI import
import javax.management.ObjectName;
/**
* Used to represent the object name of an MBean and its class name.
* If the MBean is a Dynamic MBean the class name should be retrieved from
* the <CODE>MBeanInfo</CODE> it provides.
*
* @since 1.5
*/
public class ObjectInstance implements Serializable {
/* Serial version */
private static final long serialVersionUID = -4099952623687795850L;
/**
* @serial Object name.
*/
private ObjectName name;
/**
* @serial Class name.
*/
private String className;
/**
* Allows an object instance to be created given a string representation of
* an object name and the full class name, including the package name.
*
* @param objectName A string representation of the object name.
* @param className The full class name, including the package
* name, of the object instance. If the MBean is a Dynamic MBean
* the class name corresponds to its {@link
* DynamicMBean#getMBeanInfo()
* getMBeanInfo()}<code>.getClassName()</code>.
*
* @exception MalformedObjectNameException The string passed as a
* parameter does not have the right format.
*
*/
public ObjectInstance(String objectName, String className)
throws MalformedObjectNameException {
this(new ObjectName(objectName), className);
}
/**
* Allows an object instance to be created given an object name and
* the full class name, including the package name.
*
* @param objectName The object name.
* @param className The full class name, including the package
* name, of the object instance. If the MBean is a Dynamic MBean
* the class name corresponds to its {@link
* DynamicMBean#getMBeanInfo()
* getMBeanInfo()}<code>.getClassName()</code>.
* If the MBean is a Dynamic MBean the class name should be retrieved
* from the <CODE>MBeanInfo</CODE> it provides.
*
*/
public ObjectInstance(ObjectName objectName, String className) {
if (objectName.isPattern()) {
final IllegalArgumentException iae =
new IllegalArgumentException("Invalid name->"+
objectName.toString());
throw new RuntimeOperationsException(iae);
}
this.name= objectName;
this.className= className;
}
/**
* Compares the current object instance with another object instance.
*
* @param object The object instance that the current object instance is
* to be compared with.
*
* @return True if the two object instances are equal, otherwise false.
*/
public boolean equals(Object object) {
if (!(object instanceof ObjectInstance)) {
return false;
}
ObjectInstance val = (ObjectInstance) object;
if (! name.equals(val.getObjectName())) return false;
if (className == null)
return (val.getClassName() == null);
return className.equals(val.getClassName());
}
public int hashCode() {
final int classHash = ((className==null)?0:className.hashCode());
return name.hashCode() ^ classHash;
}
/**
* Returns the object name part.
*
* @return the object name.
*/
public ObjectName getObjectName() {
return name;
}
/**
* Returns the class part.
*
* @return the class name.
*/
public String getClassName() {
return className;
}
/**
* Returns a string representing this ObjectInstance object. The format of this string
* is not specified, but users can expect that two ObjectInstances return the same
* string if and only if they are equal.
*/
public String toString() {
return getClassName() + "[" + getObjectName() + "]";
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,57 @@
/*
* 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;
/**
* 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;
/**
* Default constructor.
*/
public OperationsException() {
super();
}
/**
* Constructor that allows a specific error message to be specified.
*
* @param message the detail message.
*/
public OperationsException(String message) {
super(message);
}
}

View File

@@ -0,0 +1,107 @@
/*
* Copyright (c) 1999, 2008, 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;
/**
* This class is used by the query-building mechanism to represent
* disjunctions of relational expressions.
* @serial include
*
* @since 1.5
*/
class OrQueryExp extends QueryEval implements QueryExp {
/* Serial version */
private static final long serialVersionUID = 2962973084421716523L;
/**
* @serial The left query expression
*/
private QueryExp exp1;
/**
* @serial The right query expression
*/
private QueryExp exp2;
/**
* Basic Constructor.
*/
public OrQueryExp() {
}
/**
* Creates a new OrQueryExp with the specified ValueExps
*/
public OrQueryExp(QueryExp q1, QueryExp q2) {
exp1 = q1;
exp2 = q2;
}
/**
* Returns the left query expression.
*/
public QueryExp getLeftExp() {
return exp1;
}
/**
* Returns the right query expression.
*/
public QueryExp getRightExp() {
return exp2;
}
/**
* Applies the OrQueryExp on a MBean.
*
* @param name The name of the MBean on which the OrQueryExp 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.
*/
public boolean apply(ObjectName name) throws BadStringOperationException,
BadBinaryOpValueExpException, BadAttributeValueExpException,
InvalidApplicationException {
return exp1.apply(name) || exp2.apply(name);
}
/**
* Returns a string representation of this OrQueryExp
*/
@Override
public String toString() {
return "(" + exp1 + ") or (" + exp2 + ")";
}
}

View File

@@ -0,0 +1,94 @@
/*
* Copyright (c) 2000, 2013, 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;
/**
* 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 {
/**
* 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;
/**
* 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>{@literal != "never"
* = "always"
* = "onTimer" and now > 'lastPersistTime' + 'persistPeriod'
* = "NoMoreOftenThan" and now > 'lastPersistTime' + 'persistPeriod'
* = "onUnregister"
* }</PRE>
* <p>
* Do not store the MBean if 'persistPolicy' field is:
* <PRE>{@literal
* = "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;
}

View File

@@ -0,0 +1,122 @@
/*
* Copyright (c) 1999, 2008, 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;
/**
* <p>Represents attributes used as arguments to relational constraints,
* where the attribute must be in an MBean of a specified {@linkplain
* MBeanInfo#getClassName() class}. A 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;
/**
* @serial The attribute class name
*/
private String className;
/**
* Basic Constructor.
* @deprecated see {@link AttributeValueExp#AttributeValueExp()}
*/
@Deprecated
public QualifiedAttributeValueExp() {
}
/**
* 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;
}
/**
* Returns a string representation of the class name of the attribute.
*/
public String getAttrClassName() {
return className;
}
/**
* 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
*/
@Override
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. */
}
}
/**
* Returns the string representing its value
*/
@Override
public String toString() {
if (className != null) {
return className + "." + super.toString();
} else {
return super.toString();
}
}
}

View File

@@ -0,0 +1,654 @@
/*
* Copyright (c) 1999, 2013, 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;
/**
* <p>Constructs query object constraints.</p>
*
* <p>The MBean Server can be queried for MBeans that meet a particular
* condition, using its {@link MBeanServer#queryNames queryNames} or
* {@link MBeanServer#queryMBeans queryMBeans} method. The {@link QueryExp}
* parameter to the method can be any implementation of the interface
* {@code QueryExp}, but it is usually best to obtain the {@code QueryExp}
* value by calling the static methods in this class. This is particularly
* true when querying a remote MBean Server: a custom implementation of the
* {@code QueryExp} interface might not be present in the remote MBean Server,
* but the methods in this class return only standard classes that are
* part of the JMX implementation.</p>
*
* <p>As an example, suppose you wanted to find all MBeans where the {@code
* Enabled} attribute is {@code true} and the {@code Owner} attribute is {@code
* "Duke"}. Here is how you could construct the appropriate {@code QueryExp} by
* chaining together method calls:</p>
*
* <pre>
* QueryExp query =
* Query.and(Query.eq(Query.attr("Enabled"), Query.value(true)),
* Query.eq(Query.attr("Owner"), Query.value("Duke")));
* </pre>
*
* @since 1.5
*/
public class Query extends Object {
/**
* 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;
/**
* 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;
/**
* 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;
/**
* 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;
/**
* 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;
/**
* 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;
/**
* 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;
/**
* 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;
/**
* 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;
/**
* Basic constructor.
*/
public Query() {
}
/**
* 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
* <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);
}
/**
* 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
* <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);
}
/**
* 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
* <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);
}
/**
* 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
* <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);
}
/**
* 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
* <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);
}
/**
* 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
* <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);
}
/**
* 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
* <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);
}
/**
* 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
* <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);
}
/**
* 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
* <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);
}
/**
* <p>Returns a new attribute expression. See {@link AttributeValueExp}
* for a detailed description of the semantics of the 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 {@code name}.
*/
public static AttributeValueExp attr(String name) {
return new AttributeValueExp(name);
}
/**
* <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
* <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);
}
/**
* <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
* <a href="../../serialized-form.html#javax.management.ClassAttributeValueExp">
* javax.management.ClassAttributeValueExp</a>.
*/
public static AttributeValueExp classattr() {
return new ClassAttributeValueExp();
}
/**
* 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
* <a href="../../serialized-form.html#javax.management.NotQueryExp">
* javax.management.NotQueryExp</a>.
*/
public static QueryExp not(QueryExp queryExp) {
return new NotQueryExp(queryExp);
}
/**
* 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
* <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);
}
/**
* 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);
}
/**
* 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
* <a href="../../serialized-form.html#javax.management.NumericValueExp">
* javax.management.NumericValueExp</a>.
*/
public static ValueExp value(Number val) {
return new NumericValueExp(val);
}
/**
* 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
* <a href="../../serialized-form.html#javax.management.NumericValueExp">
* javax.management.NumericValueExp</a>.
*/
public static ValueExp value(int val) {
return new NumericValueExp((long) val);
}
/**
* 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
* <a href="../../serialized-form.html#javax.management.NumericValueExp">
* javax.management.NumericValueExp</a>.
*/
public static ValueExp value(long val) {
return new NumericValueExp(val);
}
/**
* 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
* <a href="../../serialized-form.html#javax.management.NumericValueExp">
* javax.management.NumericValueExp</a>.
*/
public static ValueExp value(float val) {
return new NumericValueExp((double) val);
}
/**
* 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
* <a href="../../serialized-form.html#javax.management.NumericValueExp">
* javax.management.NumericValueExp</a>.
*/
public static ValueExp value(double val) {
return new NumericValueExp(val);
}
/**
* 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
* <a href="../../serialized-form.html#javax.management.BooleanValueExp">
* javax.management.BooleanValueExp</a>.
*/
public static ValueExp value(boolean val) {
return new BooleanValueExp(val);
}
/**
* 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
* <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);
}
/**
* 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
* <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);
}
/**
* 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
* <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);
}
/**
* 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
* <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);
}
/**
* 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
*
* <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()) + "*"));
}
/**
* 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
*
* <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()) + "*"));
}
/**
* 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
*
* <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())));
}
/**
* 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
* <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);
}
/**
* 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;
}
}

View File

@@ -0,0 +1,78 @@
/*
* Copyright (c) 1999, 2008, 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;
/**
* 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>();
/**
* <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);
}
/**
* <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();
}
}

View File

@@ -0,0 +1,71 @@
/*
* Copyright (c) 1999, 2008, 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;
/**
* <p>Represents relational constraints similar to 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.
*
* @see MBeanServer#queryNames MBeanServer.queryNames
* @since 1.5
*/
public interface QueryExp extends Serializable {
/**
* 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 ;
/**
* 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) ;
}

View File

@@ -0,0 +1,87 @@
/*
* 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;
/**
* 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;
/**
* @serial The wrapped {@link Exception}
*/
private java.lang.Exception exception ;
/**
* 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 ;
}
/**
* 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 ;
}
/**
* Returns the actual {@link Exception} thrown.
*
* @return the wrapped {@link Exception}.
*/
public java.lang.Exception getTargetException() {
return exception ;
}
/**
* Returns the actual {@link Exception} thrown.
*
* @return the wrapped {@link Exception}.
*/
public Throwable getCause() {
return exception;
}
}

View File

@@ -0,0 +1,84 @@
/*
* 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;
/**
* 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;
/**
* @serial The encapsulated {@link Error}
*/
private java.lang.Error error ;
/**
* Default constructor.
*
* @param e the wrapped error.
*/
public RuntimeErrorException(java.lang.Error e) {
super();
error = e ;
}
/**
* 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 ;
}
/**
* Returns the actual {@link Error} thrown.
*
* @return the wrapped {@link Error}.
*/
public java.lang.Error getTargetError() {
return error ;
}
/**
* Returns the actual {@link Error} thrown.
*
* @return the wrapped {@link Error}.
*/
public Throwable getCause() {
return error;
}
}

View File

@@ -0,0 +1,87 @@
/*
* 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;
/**
* Represents runtime exceptions thrown by MBean methods in
* the agent. It "wraps" the actual <CODE>java.lang.RuntimeException</CODE> exception thrown.
* This exception will be built by the MBeanServer when a call to an
* MBean method throws a runtime exception.
*
* @since 1.5
*/
public class RuntimeMBeanException extends JMRuntimeException {
/* Serial version */
private static final long serialVersionUID = 5274912751982730171L;
/**
* @serial The encapsulated {@link RuntimeException}
*/
private java.lang.RuntimeException runtimeException ;
/**
* Creates a <CODE>RuntimeMBeanException</CODE> that wraps the actual <CODE>java.lang.RuntimeException</CODE>.
*
* @param e the wrapped exception.
*/
public RuntimeMBeanException(java.lang.RuntimeException e) {
super() ;
runtimeException = e ;
}
/**
* Creates a <CODE>RuntimeMBeanException</CODE> that wraps the actual <CODE>java.lang.RuntimeException</CODE> with
* a detailed message.
*
* @param e the wrapped exception.
* @param message the detail message.
*/
public RuntimeMBeanException(java.lang.RuntimeException e, String message) {
super(message) ;
runtimeException = e ;
}
/**
* Returns the actual {@link RuntimeException} thrown.
*
* @return the wrapped {@link RuntimeException}.
*/
public java.lang.RuntimeException getTargetException() {
return runtimeException ;
}
/**
* Returns the actual {@link RuntimeException} thrown.
*
* @return the wrapped {@link RuntimeException}.
*/
public Throwable getCause() {
return runtimeException;
}
}

View File

@@ -0,0 +1,86 @@
/*
* 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;
/**
* Represents runtime exceptions thrown in the agent when performing operations on MBeans.
* It wraps the actual <CODE>java.lang.RuntimeException</CODE> thrown.
*
* @since 1.5
*/
public class RuntimeOperationsException extends JMRuntimeException {
/* Serial version */
private static final long serialVersionUID = -8408923047489133588L;
/**
* @serial The encapsulated {@link RuntimeException}
*/
private java.lang.RuntimeException runtimeException ;
/**
* Creates a <CODE>RuntimeOperationsException</CODE> that wraps the actual <CODE>java.lang.RuntimeException</CODE>.
*
* @param e the wrapped exception.
*/
public RuntimeOperationsException(java.lang.RuntimeException e) {
super() ;
runtimeException = e ;
}
/**
* Creates a <CODE>RuntimeOperationsException</CODE> that wraps the actual <CODE>java.lang.RuntimeException</CODE>
* with a detailed message.
*
* @param e the wrapped exception.
* @param message the detail message.
*/
public RuntimeOperationsException(java.lang.RuntimeException e, String message) {
super(message);
runtimeException = e ;
}
/**
* Returns the actual {@link RuntimeException} thrown.
*
* @return the wrapped {@link RuntimeException}.
*/
public java.lang.RuntimeException getTargetException() {
return runtimeException ;
}
/**
* Returns the actual {@link RuntimeException} thrown.
*
* @return the wrapped {@link RuntimeException}.
*/
public Throwable getCause() {
return runtimeException;
}
}

View File

@@ -0,0 +1,58 @@
/*
* 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;
/**
* 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;
/**
* Default constructor.
*/
public ServiceNotFoundException() {
super();
}
/**
* Constructor that allows a specific error message to be specified.
*
* @param message the detail message.
*/
public ServiceNotFoundException(String message) {
super(message);
}
}

View File

@@ -0,0 +1,313 @@
/*
* Copyright (c) 2005, 2013, 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;
/**
* <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 static final MBeanNotificationInfo[] NO_NOTIFICATION_INFO =
new MBeanNotificationInfo[0];
private final NotificationEmitter emitter;
private final MBeanNotificationInfo[] notificationInfo;
/**
* <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) {
this(implementation, mbeanInterface, false, emitter);
}
/**
* <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;
MBeanNotificationInfo[] infos = emitter.getNotificationInfo();
if (infos == null || infos.length == 0) {
this.notificationInfo = NO_NOTIFICATION_INFO;
} else {
this.notificationInfo = infos.clone();
}
}
/**
* <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) {
this(mbeanInterface, false, emitter);
}
/**
* <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;
MBeanNotificationInfo[] infos = emitter.getNotificationInfo();
if (infos == null || infos.length == 0) {
this.notificationInfo = NO_NOTIFICATION_INFO;
} else {
this.notificationInfo = infos.clone();
}
}
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() {
// this getter might get called from the super constructor
// when the notificationInfo has not been properly set yet
if (notificationInfo == null) {
return NO_NOTIFICATION_INFO;
}
if (notificationInfo.length == 0) {
return notificationInfo;
} else {
return notificationInfo.clone();
}
}
/**
* <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);
}
}
/**
* <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.
*/
@Override
MBeanNotificationInfo[] getNotifications(MBeanInfo info) {
return getNotificationInfo();
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,107 @@
/*
* Copyright (c) 1999, 2008, 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;
/**
* 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;
/**
* @serial The string literal
*/
private String val;
/**
* Basic constructor.
*/
public StringValueExp() {
}
/**
* 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;
}
/**
* Returns the string represented by the
* <CODE>StringValueExp</CODE> instance.
*
* @return the string.
*/
public String getValue() {
return val;
}
/**
* Returns the string representing the object.
*/
public String toString() {
return "'" + val.replace("'", "''") + "'";
}
/**
* 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. */
@Deprecated
public void setMBeanServer(MBeanServer s) { }
/**
* 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;
}
}

View File

@@ -0,0 +1,103 @@
/*
* 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;
/**
* 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 {
/**
* 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;
/**
* 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) ;
}

View File

@@ -0,0 +1,151 @@
/*
* 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
/**
* <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 {
/**
* <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;
/**
* <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;
/**
* <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;
}

View File

@@ -0,0 +1,120 @@
/*
* Copyright (c) 2000, 2008, 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;
/**
* <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 {
/**
* 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);
}
/**
* 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<MBeanServer> mbsList = MBeanServerFactory.findMBeanServer(null);
for (MBeanServer mbs : mbsList) {
ClassLoaderRepository clr = mbs.getClassLoaderRepository();
try {
return clr.loadClassWithout(without, className);
} catch (ClassNotFoundException e) {
// OK : Try with next one...
}
}
throw new ClassNotFoundException(className);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,239 @@
/*
* 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;
/**
* 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 {
/**
* A map of the attributes of the <CODE>MLET</CODE> tag
* and their values.
*/
private Map<String,String> attributes;
/**
* An ordered list of the TYPE attributes that appeared in nested
* &lt;PARAM&gt; tags.
*/
private List<String> types;
/**
* An ordered list of the VALUE attributes that appeared in nested
* &lt;PARAM&gt; tags.
*/
private List<String> values;
/**
* The MLet text file's base URL.
*/
private URL documentURL;
/**
* The base URL.
*/
private URL baseURL;
/**
* 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
//--------------------
/**
* 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;
}
/**
* Gets the MLet text file's base URL.
* @return The MLet text file's base URL.
*/
public URL getDocumentBase() {
return documentURL;
}
/**
* Gets the code base URL.
* @return The code base URL.
*/
public URL getCodeBase() {
return baseURL;
}
/**
* 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");
}
/**
* 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");
}
/**
* 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");
}
/**
* 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");
}
/**
* 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");
}
/**
* 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;
}
/**
* 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;
}
/**
* 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());
}
}

View File

@@ -0,0 +1,186 @@
/*
* 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.*;
/**
* Exposes the remote management interface of the MLet
* MBean.
*
* @since 1.5
*/
public interface MLetMBean {
/**
* 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;
/**
* 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;
/**
* 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) ;
/**
* 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;
/**
* 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();
/** 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);
/** 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);
/**
* 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;
/**
* 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();
/**
* 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);
}

View File

@@ -0,0 +1,122 @@
/*
* Copyright (c) 1999, 2008, 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;
/**
* This subclass of ObjectInputStream delegates loading of classes to
* an existing MLetClassLoader.
*
* @since 1.5
*/
class MLetObjectInputStream extends ObjectInputStream {
private MLet loader;
/**
* 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 'B':
return Byte.TYPE;
case 'C':
return Character.TYPE;
case 'D':
return Double.TYPE;
case 'F':
return Float.TYPE;
case 'I':
return Integer.TYPE;
case 'J':
return Long.TYPE;
case 'S':
return Short.TYPE;
case 'Z':
return Boolean.TYPE;
}
return null;
}
/**
* Use the given ClassLoader rather than using the system class
*/
@Override
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);
}
}
/**
* Returns the ClassLoader being used
*/
public ClassLoader getClassLoader() {
return loader;
}
}

View File

@@ -0,0 +1,287 @@
/*
* Copyright (c) 1999, 2013, 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;
/**
* This class is used for parsing URLs.
*
* @since 1.5
*/
class MLetParser {
/*
* ------------------------------------------
* PRIVATE VARIABLES
* ------------------------------------------
*/
/**
* The current character
*/
private int c;
/**
* Tag to parse.
*/
private static String tag = "mlet";
/*
* ------------------------------------------
* CONSTRUCTORS
* ------------------------------------------
*/
/**
* Create an MLet parser object
*/
public MLetParser() {
}
/*
* ------------------------------------------
* PUBLIC METHODS
* ------------------------------------------
*/
/**
* Scan spaces.
*/
public void skipSpace(Reader in) throws IOException {
while ((c >= 0) && ((c == ' ') || (c == '\t') || (c == '\n') || (c == '\r'))) {
c = in.read();
}
}
/**
* 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();
}
}
}
/**
* 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;
}
/**
* Scan an html file for {@literal <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);
throw new IOException(requiresCodeWarning);
}
if (atts.get("archive") == null) {
MLET_LOGGER.logp(Level.FINER,
MLetParser.class.getName(),
mth, requiresJarsWarning);
throw new IOException(requiresJarsWarning);
}
}
}
}
}
}
in.close();
return mlets;
}
/**
* Parse the document pointed by the URL urlname
*/
public List<MLetContent> parseURL(String urlname) throws IOException {
// Parse the document
//
URL url;
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);
}
}

View File

@@ -0,0 +1,37 @@
/*
* 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;
/**
* 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 {}

View File

@@ -0,0 +1,99 @@
/*
* 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;
/**
* 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;
/**
* 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);
}
/**
* 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);
}
/**
* 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);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,199 @@
/*
* 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;
/**
* 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;
/**
* @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
/**
* @serial Encapsulated {@link Exception}
*/
Exception exception;
/**
* Default constructor.
*/
public InvalidTargetObjectTypeException ()
{
super("InvalidTargetObjectTypeException: ");
exception = null;
}
/**
* 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;
}
/**
* 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;
}
/**
* 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();
}
}
/**
* 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();
}
}
}

View File

@@ -0,0 +1,123 @@
/*
* 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;
/**
* 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
{
/**
* 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;
/**
* 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 ;
}

View File

@@ -0,0 +1,530 @@
/*
* Copyright (c) 2000, 2013, 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.DescriptorKey;
import javax.management.DescriptorAccess;
import javax.management.MBeanAttributeInfo;
import javax.management.RuntimeOperationsException;
/**
* <p>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>
*
* <P id="descriptor">
* The fields in the descriptor are defined, but not limited to, the following.
* Note that when the Type in this table is Number, a String that is the decimal
* representation of a Long can also be used.</P>
*
* <table border="1" cellpadding="5" summary="ModelMBeanAttributeInfo Fields">
* <tr><th>Name</th><th>Type</th><th>Meaning</th></tr>
* <tr><td>name</td><td>String</td>
* <td>Attribute name.</td></tr>
* <tr><td>descriptorType</td><td>String</td>
* <td>Must be "attribute".</td></tr>
* <tr id="value-field"><td>value</td><td>Object</td>
* <td>Current (cached) value for attribute.</td></tr>
* <tr><td>default</td><td>Object</td>
* <td>Default value for attribute.</td></tr>
* <tr><td>displayName</td><td>String</td>
* <td>Name of attribute to be used in displays.</td></tr>
* <tr><td>getMethod</td><td>String</td>
* <td>Name of operation descriptor for get method.</td></tr>
* <tr><td>setMethod</td><td>String</td>
* <td>Name of operation descriptor for set method.</td></tr>
* <tr><td>protocolMap</td><td>Descriptor</td>
* <td>See the section "Protocol Map Support" in the JMX specification
* document. Mappings must be appropriate for the attribute and entries
* can be updated or augmented at runtime.</td></tr>
* <tr><td>persistPolicy</td><td>String</td>
* <td>One of: OnUpdate|OnTimer|NoMoreOftenThan|OnUnregister|Always|Never.
* See the section "MBean Descriptor Fields" in the JMX specification
* document.</td></tr>
* <tr><td>persistPeriod</td><td>Number</td>
* <td>Frequency of persist cycle in seconds. Used when persistPolicy is
* "OnTimer" or "NoMoreOftenThan".</td></tr>
* <tr><td>currencyTimeLimit</td><td>Number</td>
* <td>How long <a href="#value=field">value</a> is valid: &lt;0 never,
* =0 always, &gt;0 seconds.</td></tr>
* <tr><td>lastUpdatedTimeStamp</td><td>Number</td>
* <td>When <a href="#value-field">value</a> was set.</td></tr>
* <tr><td>visibility</td><td>Number</td>
* <td>1-4 where 1: always visible, 4: rarely visible.</td></tr>
* <tr><td>presentationString</td><td>String</td>
* <td>XML formatted string to allow presentation of data.</td></tr>
* </table>
*
* <p>The default descriptor contains the name, descriptorType and displayName
* fields. The default value of the name and displayName fields is the name of
* the attribute.</p>
*
* <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;
/**
* @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
/**
* @serial The {@link Descriptor} containing the metadata corresponding to
* this attribute
*/
private Descriptor attrDescriptor = validDescriptor(null);
private final static String currClass = "ModelMBeanAttributeInfo";
/**
* 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 javax.management.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 = validDescriptor(null);
// put getter and setter methods in operations list
// create default descriptor
}
/**
* 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 javax.management.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);
}
attrDescriptor = validDescriptor(descriptor);
}
/**
* 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 = validDescriptor(null);
}
/**
* Constructs a ModelMBeanAttributeInfo 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 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);
}
attrDescriptor = validDescriptor(descriptor);
}
/**
* 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();
attrDescriptor = validDescriptor(newDesc);
}
/**
* 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 = validDescriptor(null);
}
return((Descriptor)attrDescriptor.clone());
}
/**
* 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) {
attrDescriptor = validDescriptor(inDescriptor);
}
/**
* 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.
*/
@Override
public Object clone()
{
if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) {
MODELMBEAN_LOGGER.logp(Level.FINER,
ModelMBeanAttributeInfo.class.getName(),
"clone()", "Entry");
}
return(new ModelMBeanAttributeInfo(this));
}
/**
* Returns a human-readable version of the
* ModelMBeanAttributeInfo instance.
*/
@Override
public String toString()
{
return
"ModelMBeanAttributeInfo: " + this.getName() +
" ; Description: " + this.getDescription() +
" ; Types: " + this.getType() +
" ; isReadable: " + this.isReadable() +
" ; isWritable: " + this.isWritable() +
" ; Descriptor: " + this.getDescriptor();
}
/**
* Clones the passed in Descriptor, sets default values, and checks for validity.
* If the Descriptor is invalid (for instance by having the wrong "name"),
* this indicates programming error and a RuntimeOperationsException will be thrown.
*
* The following fields will be defaulted if they are not already set:
* displayName=this.getName(),name=this.getName(),descriptorType = "attribute"
*
* @param in Descriptor to be checked, or null which is equivalent to
* an empty Descriptor.
* @exception RuntimeOperationsException if Descriptor is invalid
*/
private Descriptor validDescriptor(final Descriptor in) throws RuntimeOperationsException {
Descriptor clone;
boolean defaulted = (in == null);
if (defaulted) {
clone = new DescriptorSupport();
MODELMBEAN_LOGGER.finer("Null Descriptor, creating new.");
} else {
clone = (Descriptor) in.clone();
}
//Setting defaults.
if (defaulted && clone.getFieldValue("name")==null) {
clone.setField("name", this.getName());
MODELMBEAN_LOGGER.finer("Defaulting Descriptor name to " + this.getName());
}
if (defaulted && clone.getFieldValue("descriptorType")==null) {
clone.setField("descriptorType", "attribute");
MODELMBEAN_LOGGER.finer("Defaulting descriptorType to \"attribute\"");
}
if (clone.getFieldValue("displayName") == null) {
clone.setField("displayName",this.getName());
MODELMBEAN_LOGGER.finer("Defaulting Descriptor displayName to " + this.getName());
}
//Checking validity
if (!clone.isValid()) {
throw new RuntimeOperationsException(new IllegalArgumentException("Invalid Descriptor argument"),
"The isValid() method of the Descriptor object itself returned false,"+
"one or more required fields are invalid. Descriptor:" + clone.toString());
}
if (!getName().equalsIgnoreCase((String)clone.getFieldValue("name"))) {
throw new RuntimeOperationsException(new IllegalArgumentException("Invalid Descriptor argument"),
"The Descriptor \"name\" field does not match the object described. " +
" Expected: "+ this.getName() + " , was: " + clone.getFieldValue("name"));
}
if (!"attribute".equalsIgnoreCase((String)clone.getFieldValue("descriptorType"))) {
throw new RuntimeOperationsException(new IllegalArgumentException("Invalid Descriptor argument"),
"The Descriptor \"descriptorType\" field does not match the object described. " +
" Expected: \"attribute\" ," + " was: " + clone.getFieldValue("descriptorType"));
}
return clone;
}
/**
* 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();
}
/**
* 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();
}
}
}

View File

@@ -0,0 +1,491 @@
/*
* Copyright (c) 2000, 2013, 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;
/**
* <p>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>
*
* <P id="descriptor">
* The fields in the descriptor are defined, but not limited to, the following.
* Note that when the Type in this table is Number, a String that is the decimal
* representation of a Long can also be used.</P>
*
* <table border="1" cellpadding="5" summary="ModelMBeanConstructorInfo Fields">
* <tr><th>Name</th><th>Type</th><th>Meaning</th></tr>
* <tr><td>name</td><td>String</td>
* <td>Constructor name.</td></tr>
* <tr><td>descriptorType</td><td>String</td>
* <td>Must be "operation".</td></tr>
* <tr><td>role</td><td>String</td>
* <td>Must be "constructor".</td></tr>
* <tr><td>displayName</td><td>String</td>
* <td>Human readable name of constructor.</td></tr>
* <tr><td>visibility</td><td>Number</td>
* <td>1-4 where 1: always visible 4: rarely visible.</td></tr>
* <tr><td>presentationString</td><td>String</td>
* <td>XML formatted string to describe how to present operation</td></tr>
* </table>
*
* <p>The {@code persistPolicy} and {@code currencyTimeLimit} fields
* are meaningless for constructors, but are not considered invalid.</p>
*
* <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;
/**
* @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
/**
* @serial The {@link Descriptor} containing the metadata for this instance
*/
private Descriptor consDescriptor = validDescriptor(null);
private final static String currClass = "ModelMBeanConstructorInfo";
/**
* 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 = validDescriptor(null);
// put getter and setter methods in constructors list
// create default descriptor
}
/**
* 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 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
* present but 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");
}
consDescriptor = validDescriptor(descriptor);
}
/**
* 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 = validDescriptor(null);
}
/**
* 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
* present but 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");
}
consDescriptor = validDescriptor(descriptor);
}
/**
* 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");
}
consDescriptor = validDescriptor(consDescriptor);
}
/**
* Creates and returns a new ModelMBeanConstructorInfo which is a duplicate of this ModelMBeanConstructorInfo.
*
*/
@Override
public Object clone ()
{
if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) {
MODELMBEAN_LOGGER.logp(Level.FINER,
ModelMBeanConstructorInfo.class.getName(),
"clone()", "Entry");
}
return(new ModelMBeanConstructorInfo(this)) ;
}
/**
* Returns a copy of the associated Descriptor.
*
* @return Descriptor associated with the
* ModelMBeanConstructorInfo object.
*
* @see #setDescriptor
*/
@Override
public Descriptor getDescriptor()
{
if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) {
MODELMBEAN_LOGGER.logp(Level.FINER,
ModelMBeanConstructorInfo.class.getName(),
"getDescriptor()", "Entry");
}
if (consDescriptor == null){
consDescriptor = validDescriptor(null);
}
return((Descriptor)consDescriptor.clone());
}
/**
* 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 all the following fields, the missing ones are added with
* their default values: displayName, name, role, descriptorType.
*
* @exception RuntimeOperationsException Wraps an
* IllegalArgumentException. The descriptor is invalid, or
* descriptor field "name" is present but not equal to name
* parameter, or descriptor field "descriptorType" is present
* but not equal to "operation" or descriptor field "role" is
* present but 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");
}
consDescriptor = validDescriptor(inDescriptor);
}
/**
* Returns a string containing the entire contents of the ModelMBeanConstructorInfo in human readable form.
*/
@Override
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;
}
/**
* Clones the passed in Descriptor, sets default values, and checks for validity.
* If the Descriptor is invalid (for instance by having the wrong "name"),
* this indicates programming error and a RuntimeOperationsException will be thrown.
*
* The following fields will be defaulted if they are not already set:
* displayName=this.getName(), name=this.getName(), descriptorType="operation",
* role="constructor"
*
*
* @param in Descriptor to be checked, or null which is equivalent to
* an empty Descriptor.
* @exception RuntimeOperationsException if Descriptor is invalid
*/
private Descriptor validDescriptor(final Descriptor in) throws RuntimeOperationsException {
Descriptor clone;
boolean defaulted = (in == null);
if (defaulted) {
clone = new DescriptorSupport();
MODELMBEAN_LOGGER.finer("Null Descriptor, creating new.");
} else {
clone = (Descriptor) in.clone();
}
//Setting defaults.
if (defaulted && clone.getFieldValue("name")==null) {
clone.setField("name", this.getName());
MODELMBEAN_LOGGER.finer("Defaulting Descriptor name to " + this.getName());
}
if (defaulted && clone.getFieldValue("descriptorType")==null) {
clone.setField("descriptorType", "operation");
MODELMBEAN_LOGGER.finer("Defaulting descriptorType to \"operation\"");
}
if (clone.getFieldValue("displayName") == null) {
clone.setField("displayName",this.getName());
MODELMBEAN_LOGGER.finer("Defaulting Descriptor displayName to " + this.getName());
}
if (clone.getFieldValue("role") == null) {
clone.setField("role","constructor");
MODELMBEAN_LOGGER.finer("Defaulting Descriptor role field to \"constructor\"");
}
//Checking validity
if (!clone.isValid()) {
throw new RuntimeOperationsException(new IllegalArgumentException("Invalid Descriptor argument"),
"The isValid() method of the Descriptor object itself returned false,"+
"one or more required fields are invalid. Descriptor:" + clone.toString());
}
if (!getName().equalsIgnoreCase((String) clone.getFieldValue("name"))) {
throw new RuntimeOperationsException(new IllegalArgumentException("Invalid Descriptor argument"),
"The Descriptor \"name\" field does not match the object described. " +
" Expected: "+ this.getName() + " , was: " + clone.getFieldValue("name"));
}
if (!"operation".equalsIgnoreCase((String) clone.getFieldValue("descriptorType"))) {
throw new RuntimeOperationsException(new IllegalArgumentException("Invalid Descriptor argument"),
"The Descriptor \"descriptorType\" field does not match the object described. " +
" Expected: \"operation\" ," + " was: " + clone.getFieldValue("descriptorType"));
}
if (! ((String)clone.getFieldValue("role")).equalsIgnoreCase("constructor")) {
throw new RuntimeOperationsException(new IllegalArgumentException("Invalid Descriptor argument"),
"The Descriptor \"role\" field does not match the object described. " +
" Expected: \"constructor\" ," + " was: " + clone.getFieldValue("role"));
}
return clone;
}
/**
* 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();
}
/**
* 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();
}
}
}

View File

@@ -0,0 +1,370 @@
/*
* Copyright (c) 2000, 2013, 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;
/**
* 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
{
/**
* 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;
/**
* 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;
/**
* 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;
/**
* 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;
/**
* <p>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>
*
* <P id="descriptor">
* The fields in the descriptor are defined, but not limited to, the
* following. Note that when the Type in this table is Number, a String
* that is the decimal representation of a Long can also be used.</P>
*
* <table border="1" cellpadding="5" summary="ModelMBean Fields">
* <tr><th>Name</th><th>Type</th><th>Meaning</th></tr>
* <tr><td>name</td><td>String</td>
* <td>MBean name.</td></tr>
* <tr><td>descriptorType</td><td>String</td>
* <td>Must be "mbean".</td></tr>
* <tr><td>displayName</td><td>String</td>
* <td>Name of MBean to be used in displays.</td></tr>
* <tr><td>persistPolicy</td><td>String</td>
* <td>One of: OnUpdate|OnTimer|NoMoreOftenThan|OnUnregister|Always|Never.
* See the section "MBean Descriptor Fields" in the JMX specification
* document.</td></tr>
* <tr><td>persistLocation</td><td>String</td>
* <td>The fully qualified directory name where the MBean should be
* persisted (if appropriate).</td></tr>
* <tr><td>persistFile</td><td>String</td>
* <td>File name into which the MBean should be persisted.</td></tr>
* <tr><td>persistPeriod</td><td>Number</td>
* <td>Frequency of persist cycle in seconds, for OnTime and
* NoMoreOftenThan PersistPolicy</td></tr>
* <tr><td>currencyTimeLimit</td><td>Number</td>
* <td>How long cached value is valid: &lt;0 never, =0 always,
* &gt;0 seconds.</td></tr>
* <tr><td>log</td><td>String</td>
* <td>t: log all notifications, f: log no notifications.</td></tr>
* <tr><td>logfile</td><td>String</td>
* <td>Fully qualified filename to log events to.</td></tr>
* <tr><td>visibility</td><td>Number</td>
* <td>1-4 where 1: always visible 4: rarely visible.</td></tr>
* <tr><td>export</td><td>String</td>
* <td>Name to be used to export/expose this MBean so that it is
* findable by other JMX Agents.</td></tr>
* <tr><td>presentationString</td><td>String</td>
* <td>XML formatted string to allow presentation of data to be
* associated with the MBean.</td></tr>
* </table>
*
* <P>
* 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.
*
* <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;
/**
* 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",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;
/**
* 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;
/**
* 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;
/**
* 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;
/**
* Creates and returns a copy of this object.
*/
public java.lang.Object clone();
/**
* 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();
/**
* 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();
/**
* 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();
/**
* Returns a human readable description of the MBean.
*
* @return the description.
*/
public java.lang.String getDescription();
/**
* 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();
/**
* 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();
}

Some files were not shown because too many files have changed in this diff Show More