code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
/*
* Copyright (c) 2000, 2001, 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.print.attribute;
/** {@collect.stats}
* Interface PrintRequestAttributeSet specifies the interface for a set of
* print request attributes, i.e. printing attributes that implement interface
* {@link PrintRequestAttribute PrintRequestAttribute}.
* The client uses a PrintRequestAttributeSet to specify the settings to be
* applied to a whole print job and to all the docs in the print job.
* <P>
* PrintRequestAttributeSet is just an {@link AttributeSet AttributeSet} whose
* constructors and mutating operations guarantee an additional invariant,
* namely that all attribute values in the PrintRequestAttributeSet must be
* instances of interface {@link PrintRequestAttribute PrintRequestAttribute}.
* The {@link #add(Attribute) <CODE>add(Attribute)</CODE>}, and
* {@link #addAll(AttributeSet) <CODE>addAll(AttributeSet)</CODE>} operations
* are respecified below to guarantee this additional invariant.
* <P>
*
* @author Alan Kaminsky
*/
public interface PrintRequestAttributeSet extends AttributeSet {
/** {@collect.stats}
* Adds the specified attribute value to this attribute set if it is not
* already present, first removing any existing value in the same
* attribute category as the specified attribute value (optional
* operation).
*
* @param attribute Attribute value to be added to this attribute set.
*
* @return <tt>true</tt> if this attribute set changed as a result of
* the call, i.e., the given attribute value was not already a
* member of this attribute set.
*
* @throws UnmodifiableSetException
* (unchecked exception) Thrown if this attribute set does not
* support the <CODE>add()</CODE> operation.
* @throws ClassCastException
* (unchecked exception) Thrown if the <CODE>attribute</CODE> is
* not an instance of interface
* {@link PrintRequestAttribute PrintRequestAttribute}.
* @throws NullPointerException
* (unchecked exception) Thrown if the <CODE>attribute</CODE> is null.
*/
public boolean add(Attribute attribute);
/** {@collect.stats}
* Adds all of the elements in the specified set to this attribute.
* The outcome is the same as if the
* {@link #add(Attribute) <CODE>add(Attribute)</CODE>}
* operation had been applied to this attribute set successively with
* each element from the specified set. If none of the categories in the
* specified set are the same as any categories in this attribute set,
* the <tt>addAll()</tt> operation effectively modifies this attribute
* set so that its value is the <i>union</i> of the two sets.
* <P>
* The behavior of the <CODE>addAll()</CODE> operation is unspecified if
* the specified set is modified while the operation is in progress.
* <P>
* If the <CODE>addAll()</CODE> operation throws an exception, the effect
* on this attribute set's state is implementation dependent; elements
* from the specified set before the point of the exception may or
* may not have been added to this attribute set.
*
* @param attributes whose elements are to be added to this attribute
* set.
*
* @return <tt>true</tt> if this attribute set changed as a result of
* the call.
*
* @throws UnmodifiableSetException
* (Unchecked exception) Thrown if this attribute set does not
* support the <tt>addAll()</tt> method.
* @throws ClassCastException
* (Unchecked exception) Thrown if some element in the specified
* set is not an instance of interface {@link PrintRequestAttribute
* PrintRequestAttribute}.
* @throws NullPointerException
* (Unchecked exception) Thrown if the specified set is null.
*
* @see #add(Attribute)
*/
public boolean addAll(AttributeSet attributes);
}
| Java |
/*
* Copyright (c) 2000, 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.print.attribute;
import java.io.Serializable;
/** {@collect.stats}
* Class AttributeSetUtilities provides static methods for manipulating
* AttributeSets.
* <ul>
* <li>Methods for creating unmodifiable and synchronized views of attribute
* sets.
* <li>operations useful for building
* implementations of interface {@link AttributeSet AttributeSet}
* </ul>
* <P>
* An <B>unmodifiable view</B> <I>U</I> of an AttributeSet <I>S</I> provides a
* client with "read-only" access to <I>S</I>. Query operations on <I>U</I>
* "read through" to <I>S</I>; thus, changes in <I>S</I> are reflected in
* <I>U</I>. However, any attempt to modify <I>U</I>,
* results in an UnmodifiableSetException.
* The unmodifiable view object <I>U</I> will be serializable if the
* attribute set object <I>S</I> is serializable.
* <P>
* A <B>synchronized view</B> <I>V</I> of an attribute set <I>S</I> provides a
* client with synchronized (multiple thread safe) access to <I>S</I>. Each
* operation of <I>V</I> is synchronized using <I>V</I> itself as the lock
* object and then merely invokes the corresponding operation of <I>S</I>. In
* order to guarantee mutually exclusive access, it is critical that all
* access to <I>S</I> is accomplished through <I>V</I>. The synchronized view
* object <I>V</I> will be serializable if the attribute set object <I>S</I>
* is serializable.
* <P>
* As mentioned in the package description of javax.print, a null reference
* parameter to methods is
* incorrect unless explicitly documented on the method as having a meaningful
* interpretation. Usage to the contrary is incorrect coding and may result in
* a run time exception either immediately
* or at some later time. IllegalArgumentException and NullPointerException
* are examples of typical and acceptable run time exceptions for such cases.
*
* @author Alan Kaminsky
*/
public final class AttributeSetUtilities {
/* Suppress default constructor, ensuring non-instantiability.
*/
private AttributeSetUtilities() {
}
/** {@collect.stats}
* @serial include
*/
private static class UnmodifiableAttributeSet
implements AttributeSet, Serializable {
private AttributeSet attrset;
/* Unmodifiable view of the underlying attribute set.
*/
public UnmodifiableAttributeSet(AttributeSet attributeSet) {
attrset = attributeSet;
}
public Attribute get(Class<?> key) {
return attrset.get(key);
}
public boolean add(Attribute attribute) {
throw new UnmodifiableSetException();
}
public synchronized boolean remove(Class<?> category) {
throw new UnmodifiableSetException();
}
public boolean remove(Attribute attribute) {
throw new UnmodifiableSetException();
}
public boolean containsKey(Class<?> category) {
return attrset.containsKey(category);
}
public boolean containsValue(Attribute attribute) {
return attrset.containsValue(attribute);
}
public boolean addAll(AttributeSet attributes) {
throw new UnmodifiableSetException();
}
public int size() {
return attrset.size();
}
public Attribute[] toArray() {
return attrset.toArray();
}
public void clear() {
throw new UnmodifiableSetException();
}
public boolean isEmpty() {
return attrset.isEmpty();
}
public boolean equals(Object o) {
return attrset.equals (o);
}
public int hashCode() {
return attrset.hashCode();
}
}
/** {@collect.stats}
* @serial include
*/
private static class UnmodifiableDocAttributeSet
extends UnmodifiableAttributeSet
implements DocAttributeSet, Serializable {
public UnmodifiableDocAttributeSet(DocAttributeSet attributeSet) {
super (attributeSet);
}
}
/** {@collect.stats}
* @serial include
*/
private static class UnmodifiablePrintRequestAttributeSet
extends UnmodifiableAttributeSet
implements PrintRequestAttributeSet, Serializable
{
public UnmodifiablePrintRequestAttributeSet
(PrintRequestAttributeSet attributeSet) {
super (attributeSet);
}
}
/** {@collect.stats}
* @serial include
*/
private static class UnmodifiablePrintJobAttributeSet
extends UnmodifiableAttributeSet
implements PrintJobAttributeSet, Serializable
{
public UnmodifiablePrintJobAttributeSet
(PrintJobAttributeSet attributeSet) {
super (attributeSet);
}
}
/** {@collect.stats}
* @serial include
*/
private static class UnmodifiablePrintServiceAttributeSet
extends UnmodifiableAttributeSet
implements PrintServiceAttributeSet, Serializable
{
public UnmodifiablePrintServiceAttributeSet
(PrintServiceAttributeSet attributeSet) {
super (attributeSet);
}
}
/** {@collect.stats}
* Creates an unmodifiable view of the given attribute set.
*
* @param attributeSet Underlying attribute set.
*
* @return Unmodifiable view of <CODE>attributeSet</CODE>.
*
* @exception NullPointerException
* Thrown if <CODE>attributeSet</CODE> is null. Null is never a
*/
public static AttributeSet unmodifiableView(AttributeSet attributeSet) {
if (attributeSet == null) {
throw new NullPointerException();
}
return new UnmodifiableAttributeSet(attributeSet);
}
/** {@collect.stats}
* Creates an unmodifiable view of the given doc attribute set.
*
* @param attributeSet Underlying doc attribute set.
*
* @return Unmodifiable view of <CODE>attributeSet</CODE>.
*
* @exception NullPointerException
* Thrown if <CODE>attributeSet</CODE> is null.
*/
public static DocAttributeSet unmodifiableView
(DocAttributeSet attributeSet) {
if (attributeSet == null) {
throw new NullPointerException();
}
return new UnmodifiableDocAttributeSet(attributeSet);
}
/** {@collect.stats}
* Creates an unmodifiable view of the given print request attribute set.
*
* @param attributeSet Underlying print request attribute set.
*
* @return Unmodifiable view of <CODE>attributeSet</CODE>.
*
* @exception NullPointerException
* Thrown if <CODE>attributeSet</CODE> is null.
*/
public static PrintRequestAttributeSet
unmodifiableView(PrintRequestAttributeSet attributeSet) {
if (attributeSet == null) {
throw new NullPointerException();
}
return new UnmodifiablePrintRequestAttributeSet(attributeSet);
}
/** {@collect.stats}
* Creates an unmodifiable view of the given print job attribute set.
*
* @param attributeSet Underlying print job attribute set.
*
* @return Unmodifiable view of <CODE>attributeSet</CODE>.
*
* @exception NullPointerException
* Thrown if <CODE>attributeSet</CODE> is null.
*/
public static PrintJobAttributeSet
unmodifiableView(PrintJobAttributeSet attributeSet) {
if (attributeSet == null) {
throw new NullPointerException();
}
return new UnmodifiablePrintJobAttributeSet(attributeSet);
}
/** {@collect.stats}
* Creates an unmodifiable view of the given print service attribute set.
*
* @param attributeSet Underlying print service attribute set.
*
* @return Unmodifiable view of <CODE>attributeSet</CODE>.
*
* @exception NullPointerException
* Thrown if <CODE>attributeSet</CODE> is null.
*/
public static PrintServiceAttributeSet
unmodifiableView(PrintServiceAttributeSet attributeSet) {
if (attributeSet == null) {
throw new NullPointerException();
}
return new UnmodifiablePrintServiceAttributeSet (attributeSet);
}
/** {@collect.stats}
* @serial include
*/
private static class SynchronizedAttributeSet
implements AttributeSet, Serializable {
private AttributeSet attrset;
public SynchronizedAttributeSet(AttributeSet attributeSet) {
attrset = attributeSet;
}
public synchronized Attribute get(Class<?> category) {
return attrset.get(category);
}
public synchronized boolean add(Attribute attribute) {
return attrset.add(attribute);
}
public synchronized boolean remove(Class<?> category) {
return attrset.remove(category);
}
public synchronized boolean remove(Attribute attribute) {
return attrset.remove(attribute);
}
public synchronized boolean containsKey(Class<?> category) {
return attrset.containsKey(category);
}
public synchronized boolean containsValue(Attribute attribute) {
return attrset.containsValue(attribute);
}
public synchronized boolean addAll(AttributeSet attributes) {
return attrset.addAll(attributes);
}
public synchronized int size() {
return attrset.size();
}
public synchronized Attribute[] toArray() {
return attrset.toArray();
}
public synchronized void clear() {
attrset.clear();
}
public synchronized boolean isEmpty() {
return attrset.isEmpty();
}
public synchronized boolean equals(Object o) {
return attrset.equals (o);
}
public synchronized int hashCode() {
return attrset.hashCode();
}
}
/** {@collect.stats}
* @serial include
*/
private static class SynchronizedDocAttributeSet
extends SynchronizedAttributeSet
implements DocAttributeSet, Serializable {
public SynchronizedDocAttributeSet(DocAttributeSet attributeSet) {
super(attributeSet);
}
}
/** {@collect.stats}
* @serial include
*/
private static class SynchronizedPrintRequestAttributeSet
extends SynchronizedAttributeSet
implements PrintRequestAttributeSet, Serializable {
public SynchronizedPrintRequestAttributeSet
(PrintRequestAttributeSet attributeSet) {
super(attributeSet);
}
}
/** {@collect.stats}
* @serial include
*/
private static class SynchronizedPrintJobAttributeSet
extends SynchronizedAttributeSet
implements PrintJobAttributeSet, Serializable {
public SynchronizedPrintJobAttributeSet
(PrintJobAttributeSet attributeSet) {
super(attributeSet);
}
}
/** {@collect.stats}
* @serial include
*/
private static class SynchronizedPrintServiceAttributeSet
extends SynchronizedAttributeSet
implements PrintServiceAttributeSet, Serializable {
public SynchronizedPrintServiceAttributeSet
(PrintServiceAttributeSet attributeSet) {
super(attributeSet);
}
}
/** {@collect.stats}
* Creates a synchronized view of the given attribute set.
*
* @param attributeSet Underlying attribute set.
*
* @return Synchronized view of <CODE>attributeSet</CODE>.
*
* @exception NullPointerException
* Thrown if <CODE>attributeSet</CODE> is null.
*/
public static AttributeSet synchronizedView
(AttributeSet attributeSet) {
if (attributeSet == null) {
throw new NullPointerException();
}
return new SynchronizedAttributeSet(attributeSet);
}
/** {@collect.stats}
* Creates a synchronized view of the given doc attribute set.
*
* @param attributeSet Underlying doc attribute set.
*
* @return Synchronized view of <CODE>attributeSet</CODE>.
*
* @exception NullPointerException
* Thrown if <CODE>attributeSet</CODE> is null.
*/
public static DocAttributeSet
synchronizedView(DocAttributeSet attributeSet) {
if (attributeSet == null) {
throw new NullPointerException();
}
return new SynchronizedDocAttributeSet(attributeSet);
}
/** {@collect.stats}
* Creates a synchronized view of the given print request attribute set.
*
* @param attributeSet Underlying print request attribute set.
*
* @return Synchronized view of <CODE>attributeSet</CODE>.
*
* @exception NullPointerException
* Thrown if <CODE>attributeSet</CODE> is null.
*/
public static PrintRequestAttributeSet
synchronizedView(PrintRequestAttributeSet attributeSet) {
if (attributeSet == null) {
throw new NullPointerException();
}
return new SynchronizedPrintRequestAttributeSet(attributeSet);
}
/** {@collect.stats}
* Creates a synchronized view of the given print job attribute set.
*
* @param attributeSet Underlying print job attribute set.
*
* @return Synchronized view of <CODE>attributeSet</CODE>.
*
* @exception NullPointerException
* Thrown if <CODE>attributeSet</CODE> is null.
*/
public static PrintJobAttributeSet
synchronizedView(PrintJobAttributeSet attributeSet) {
if (attributeSet == null) {
throw new NullPointerException();
}
return new SynchronizedPrintJobAttributeSet(attributeSet);
}
/** {@collect.stats}
* Creates a synchronized view of the given print service attribute set.
*
* @param attributeSet Underlying print service attribute set.
*
* @return Synchronized view of <CODE>attributeSet</CODE>.
*/
public static PrintServiceAttributeSet
synchronizedView(PrintServiceAttributeSet attributeSet) {
if (attributeSet == null) {
throw new NullPointerException();
}
return new SynchronizedPrintServiceAttributeSet(attributeSet);
}
/** {@collect.stats}
* Verify that the given object is a {@link java.lang.Class Class} that
* implements the given interface, which is assumed to be interface {@link
* Attribute Attribute} or a subinterface thereof.
*
* @param object Object to test.
* @param interfaceName Interface the object must implement.
*
* @return If <CODE>object</CODE> is a {@link java.lang.Class Class}
* that implements <CODE>interfaceName</CODE>,
* <CODE>object</CODE> is returned downcast to type {@link
* java.lang.Class Class}; otherwise an exception is thrown.
*
* @exception NullPointerException
* (unchecked exception) Thrown if <CODE>object</CODE> is null.
* @exception ClassCastException
* (unchecked exception) Thrown if <CODE>object</CODE> is not a
* {@link java.lang.Class Class} that implements
* <CODE>interfaceName</CODE>.
*/
public static Class<?>
verifyAttributeCategory(Object object, Class<?> interfaceName) {
Class result = (Class) object;
if (interfaceName.isAssignableFrom (result)) {
return result;
}
else {
throw new ClassCastException();
}
}
/** {@collect.stats}
* Verify that the given object is an instance of the given interface, which
* is assumed to be interface {@link Attribute Attribute} or a subinterface
* thereof.
*
* @param object Object to test.
* @param interfaceName Interface of which the object must be an instance.
*
* @return If <CODE>object</CODE> is an instance of
* <CODE>interfaceName</CODE>, <CODE>object</CODE> is returned
* downcast to type {@link Attribute Attribute}; otherwise an
* exception is thrown.
*
* @exception NullPointerException
* (unchecked exception) Thrown if <CODE>object</CODE> is null.
* @exception ClassCastException
* (unchecked exception) Thrown if <CODE>object</CODE> is not an
* instance of <CODE>interfaceName</CODE>.
*/
public static Attribute
verifyAttributeValue(Object object, Class<?> interfaceName) {
if (object == null) {
throw new NullPointerException();
}
else if (interfaceName.isInstance (object)) {
return (Attribute) object;
} else {
throw new ClassCastException();
}
}
/** {@collect.stats}
* Verify that the given attribute category object is equal to the
* category of the given attribute value object. If so, this method
* returns doing nothing. If not, this method throws an exception.
*
* @param category Attribute category to test.
* @param attribute Attribute value to test.
*
* @exception NullPointerException
* (unchecked exception) Thrown if the <CODE>category</CODE> is
* null or if the <CODE>attribute</CODE> is null.
* @exception IllegalArgumentException
* (unchecked exception) Thrown if the <CODE>category</CODE> is not
* equal to the category of the <CODE>attribute</CODE>.
*/
public static void
verifyCategoryForValue(Class<?> category, Attribute attribute) {
if (!category.equals (attribute.getCategory())) {
throw new IllegalArgumentException();
}
}
}
| Java |
/*
* Copyright (c) 2000, 2001, 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.print;
import java.io.InputStream;
import java.io.IOException;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import javax.print.attribute.AttributeSet;
import javax.print.attribute.DocAttributeSet;
/** {@collect.stats}
* Interface Doc specifies the interface for an object that supplies one piece
* of print data for a Print Job. "Doc" is a short, easy-to-pronounce term
* that means "a piece of print data." The client passes to the Print Job an
* object that implements interface Doc, and the Print Job calls methods on
* that object to obtain the print data. The Doc interface lets a Print Job:
* <UL>
* <LI>
* Determine the format, or "doc flavor" (class {@link DocFlavor DocFlavor}),
* in which the print data is available. A doc flavor designates the print
* data format (a MIME type) and the representation class of the object
* from which the print data comes.
* <P>
* <LI>
* Obtain the print data representation object, which is an instance of the
* doc flavor's representation class. The Print Job can then obtain the actual
* print data from the representation object.
* <P>
* <LI>
* Obtain the printing attributes that specify additional characteristics of
* the doc or that specify processing instructions to be applied to the doc.
* Printing attributes are defined in package {@link javax.print.attribute
* javax.print.attribute}. The doc returns its printing attributes stored in
* an {@link javax.print.attribute.DocAttributeSet javax.print.attribute.DocAttributeSet}.
* </UL>
* <P>
* Each method in an implementation of interface Doc is permitted always to
* return the same object each time the method is called.
* This has implications
* for a Print Job or other caller of a doc object whose print data
* representation object "consumes" the print data as the caller obtains the
* print data, such as a print data representation object which is a stream.
* Once the Print Job has called {@link #getPrintData()
* <CODE>getPrintData()</CODE>} and obtained the stream, any further calls to
* {@link #getPrintData() <CODE>getPrintData()</CODE>} will return the same
* stream object upon which reading may already be in progress, <I>not</I> a new
* stream object that will re-read the print data from the beginning. Specifying
* a doc object to behave this way simplifies the implementation of doc objects,
* and is justified on the grounds that a particular doc is intended to convey
* print data only to one Print Job, not to several different Print Jobs. (To
* convey the same print data to several different Print Jobs, you have to
* create several different doc objects on top of the same print data source.)
* <P>
* Interface Doc affords considerable implementation flexibility. The print data
* might already be in existence when the doc object is constructed. In this
* case the objects returned by the doc's methods can be supplied to the doc's
* constructor, be stored in the doc ahead of time, and simply be returned when
* called for. Alternatively, the print data might not exist yet when the doc
* object is constructed. In this case the doc object might provide a "lazy"
* implementation that generates the print data representation object (and/or
* the print data) only when the Print Job calls for it (when the Print Job
* calls the {@link #getPrintData() <CODE>getPrintData()</CODE>} method).
* <P>
* There is no restriction on the number of client threads that may be
* simultaneously accessing the same doc. Therefore, all implementations of
* interface Doc must be designed to be multiple thread safe.
* <p>
* However there can only be one consumer of the print data obtained from a
* Doc.
* <p>
* If print data is obtained from the client as a stream, by calling Doc's
* <code>getReaderForText()</code> or <code>getStreamForBytes()</code>
* methods, or because the print data source is already an InputStream or
* Reader, then the print service should always close these streams for the
* client on all job completion conditions. With the following caveat.
* If the print data is itself a stream, the service will always close it.
* If the print data is otherwise something that can be requested as a stream,
* the service will only close the stream if it has obtained the stream before
* terminating. That is, just because a print service might request data as
* a stream does not mean that it will, with the implications that Doc
* implementors which rely on the service to close them should create such
* streams only in response to a request from the service.
* <P>
* <HR>
*/
public interface Doc {
/** {@collect.stats}
* Determines the doc flavor in which this doc object will supply its
* piece of print data.
*
* @return Doc flavor.
*/
public DocFlavor getDocFlavor();
/** {@collect.stats}
* Obtains the print data representation object that contains this doc
* object's piece of print data in the format corresponding to the
* supported doc flavor.
* The <CODE>getPrintData()</CODE> method returns an instance of
* the representation class whose name is given by <CODE>{@link
* #getDocFlavor() getDocFlavor()}.{@link
* DocFlavor#getRepresentationClassName()
* getRepresentationClassName()}</CODE>, and the return value can be cast
* from class Object to that representation class.
*
* @return Print data representation object.
*
* @exception IOException
* Thrown if the representation class is a stream and there was an I/O
* error while constructing the stream.
*/
public Object getPrintData() throws IOException;
/** {@collect.stats}
* Obtains the set of printing attributes for this doc object. If the
* returned attribute set includes an instance of a particular attribute
* <I>X,</I> the printer must use that attribute value for this doc,
* overriding any value of attribute <I>X</I> in the job's attribute set.
* If the returned attribute set does not include an instance
* of a particular attribute <I>X</I> or if null is returned, the printer
* must consult the job's attribute set to obtain the value for
* attribute <I>X,</I> and if not found there, the printer must use an
* implementation-dependent default value. The returned attribute set is
* unmodifiable.
*
* @return Unmodifiable set of printing attributes for this doc, or null
* to obtain all attribute values from the job's attribute
* set.
*/
public DocAttributeSet getAttributes();
/** {@collect.stats}
* Obtains a reader for extracting character print data from this doc.
* The Doc implementation is required to support this method if the
* DocFlavor has one of the following print data representation classes,
* and return null otherwise:
* <UL>
* <LI> char[]
* <LI> java.lang.String
* <LI> java.io.Reader
* </UL>
* The doc's print data representation object is used to construct and
* return a Reader for reading the print data as a stream of characters
* from the print data representation object.
* However, if the print data representation object is itself a Reader,
* then the print data representation object is simply returned.
* <P>
* @return Reader for reading the print data characters from this doc.
* If a reader cannot be provided because this doc does not meet
* the criteria stated above, null is returned.
*
* @exception IOException
* Thrown if there was an I/O error while creating the reader.
*/
public Reader getReaderForText() throws IOException;
/** {@collect.stats}
* Obtains an input stream for extracting byte print data from this
* doc. The Doc implementation is required to support this method if
* the DocFlavor has one of the following print data representation
* classes, and return null otherwise:
* <UL>
* <LI> byte[]
* <LI> java.io.InputStream
* </UL>
* This doc's print data representation object is obtained, then an input
* stream for reading the print data from the print data representation
* object as a stream of bytes is created and returned. However, if the
* print data representation object is itself an input stream, then the
* print data representation object is simply returned.
* <P>
* @return Input stream for reading the print data bytes from this doc. If
* an input stream cannot be provided because this doc does not
* meet the criteria stated above, null is returned.
*
* @exception IOException
* Thrown if there was an I/O error while creating the input stream.
*/
public InputStream getStreamForBytes() throws IOException;
}
| Java |
/*
* Copyright (c) 2000, 2001, 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.print;
import java.io.OutputStream;
/** {@collect.stats}
* This class extends {@link PrintService} and represents a
* print service that prints data in different formats to a
* client-provided output stream.
* This is principally intended for services where
* the output format is a document type suitable for viewing
* or archiving.
* The output format must be declared as a mime type.
* This is equivalent to an output document flavor where the
* representation class is always "java.io.OutputStream"
* An instance of the <code>StreamPrintService</code> class is
* obtained from a {@link StreamPrintServiceFactory} instance.
* <p>
* Note that a <code>StreamPrintService</code> is different from a
* <code>PrintService</code>, which supports a
* {@link javax.print.attribute.standard.Destination Destination}
* attribute. A <code>StreamPrintService</code> always requires an output
* stream, whereas a <code>PrintService</code> optionally accepts a
* <code>Destination</code>. A <code>StreamPrintService</code>
* has no default destination for its formatted output.
* Additionally a <code>StreamPrintService</code> is expected to generate
output in
* a format useful in other contexts.
* StreamPrintService's are not expected to support the Destination attribute.
*/
public abstract class StreamPrintService implements PrintService {
private OutputStream outStream;
private boolean disposed = false;
private StreamPrintService() {
};
/** {@collect.stats}
* Constructs a StreamPrintService object.
*
* @param out stream to which to send formatted print data.
*/
protected StreamPrintService(OutputStream out) {
this.outStream = out;
}
/** {@collect.stats}
* Gets the output stream.
*
* @return the stream to which this service will send formatted print data.
*/
public OutputStream getOutputStream() {
return outStream;
}
/** {@collect.stats}
* Returns the document format emitted by this print service.
* Must be in mimetype format, compatible with the mime type
* components of DocFlavors @see DocFlavor.
* @return mime type identifying the output format.
*/
public abstract String getOutputFormat();
/** {@collect.stats}
* Disposes this <code>StreamPrintService</code>.
* If a stream service cannot be re-used, it must be disposed
* to indicate this. Typically the client will call this method.
* Services which write data which cannot meaningfully be appended to
* may also dispose the stream. This does not close the stream. It
* just marks it as not for further use by this service.
*/
public void dispose() {
disposed = true;
}
/** {@collect.stats}
* Returns a <code>boolean</code> indicating whether or not
* this <code>StreamPrintService</code> has been disposed.
* If this object has been disposed, will return true.
* Used by services and client applications to recognize streams
* to which no further data should be written.
* @return if this <code>StreamPrintService</code> has been disposed
*/
public boolean isDisposed() {
return disposed;
}
}
| Java |
/*
* Copyright (c) 2000, 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.print;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Map;
/** {@collect.stats}
* Class <code>DocFlavor</code> encapsulates an object that specifies the
* format in which print data is supplied to a {@link DocPrintJob}.
* "Doc" is a short, easy-to-pronounce term that means "a piece of print data."
* The print data format, or "doc flavor", consists of two things:
* <UL>
* <LI>
* <B>MIME type.</B> This is a Multipurpose Internet Mail Extensions (MIME)
* media type (as defined in <A HREF="http://www.ietf.org/rfc/rfc2045.txt">RFC
* 2045</A> and <A HREF="http://www.ietf.org/rfc/rfc2046.txt">RFC 2046</A>)
* that specifies how the print data is to be interpreted.
* The charset of text data should be the IANA MIME-preferred name, or its
* canonical name if no preferred name is specified. Additionally a few
* historical names supported by earlier versions of the Java platform may
* be recognized.
* See <a href="../../java/lang/package-summary.html#charenc">
* character encodings</a> for more information on the character encodings
* supported on the Java platform.
* <P>
* <LI>
* <B>Representation class name.</B> This specifies the fully-qualified name of
* the class of the object from which the actual print data comes, as returned
* by the {@link java.lang.Class#getName() <CODE>Class.getName()</CODE>} method.
* (Thus the class name for <CODE>byte[]</CODE> is <CODE>"[B"</CODE>, for
* <CODE>char[]</CODE> it is <CODE>"[C"</CODE>.)
* </UL>
* <P>
* A <code>DocPrintJob</code> obtains its print data by means of interface
* {@link Doc Doc}. A <code>Doc</code> object lets the <code>DocPrintJob</code>
* determine the doc flavor the client can supply. A <code>Doc</code> object
* also lets the <code>DocPrintJob</code> obtain an instance of the doc flavor's
* representation class, from which the <code>DocPrintJob</code> then obtains
* the actual print data.
* <P>
* <HR>
* <H3>Client Formatted Print Data</H3>
* There are two broad categories of print data, client formatted print data
* and service formatted print data.
* <P>
* For <B>client formatted print data</B>, the client determines or knows the
* print data format.
* For example the client may have a JPEG encoded image, a URL for
* HTML code, or a disk file containing plain text in some encoding,
* possibly obtained from an external source, and
* requires a way to describe the data format to the print service.
* <p>
* The doc flavor's representation class is a conduit for the JPS
* <code>DocPrintJob</code> to obtain a sequence of characters or
* bytes from the client. The
* doc flavor's MIME type is one of the standard media types telling how to
* interpret the sequence of characters or bytes. For a list of standard media
* types, see the Internet Assigned Numbers Authority's (IANA's) <A
* HREF="http://www.isi.edu/in-notes/iana/assignments/media-types/">Media Types
* Directory</A>. Interface {@link Doc Doc} provides two utility operations,
* {@link Doc#getReaderForText() getReaderForText} and
* {@link Doc#getStreamForBytes() getStreamForBytes()}, to help a
* <code>Doc</code> object's client extract client formatted print data.
* <P>
* For client formatted print data, the print data representation class is
* typically one of the following (although other representation classes are
* permitted):
* <UL>
* <LI>
* Character array (<CODE>char[]</CODE>) -- The print data consists of the
* Unicde characters in the array.
* <P>
* <LI>
* <code>String</code> --
* The print data consists of the Unicode characters in the string.
* <P>
* <LI>
* Character stream ({@link java.io.Reader java.io.Reader})
* -- The print data consists of the Unicode characters read from the stream
* up to the end-of-stream.
* <P>
* <LI>
* Byte array (<CODE>byte[]</CODE>) -- The print data consists of the bytes in
* the array. The bytes are encoded in the character set specified by the doc
* flavor's MIME type. If the MIME type does not specify a character set, the
* default character set is US-ASCII.
* <P>
* <LI>
* Byte stream ({@link java.io.InputStream java.io.InputStream}) --
* The print data consists of the bytes read from the stream up to the
* end-of-stream. The bytes are encoded in the character set specified by the
* doc flavor's MIME type. If the MIME type does not specify a character set,
* the default character set is US-ASCII.
* <LI>
* Uniform Resource Locator ({@link java.net.URL URL})
* -- The print data consists of the bytes read from the URL location.
* The bytes are encoded in the character set specified by the doc flavor's
* MIME type. If the MIME type does not specify a character set, the default
* character set is US-ASCII.
* <P>
* When the representation class is a URL, the print service itself accesses
* and downloads the document directly from its URL address, without involving
* the client. The service may be some form of network print service which
* is executing in a different environment.
* This means you should not use a URL print data flavor to print a
* document at a restricted URL that the client can see but the printer cannot
* see. This also means you should not use a URL print data flavor to print a
* document stored in a local file that is not available at a URL
* accessible independently of the client.
* For example, a file that is not served up by an HTTP server or FTP server.
* To print such documents, let the client open an input stream on the URL
* or file and use an input stream data flavor.
* </UL>
* <p>
* <HR>
* <h3>Default and Platform Encodings</h3>
* <P>
* For byte print data where the doc flavor's MIME type does not include a
* <CODE>charset</CODE> parameter, the Java Print Service instance assumes the
* US-ASCII character set by default. This is in accordance with
* <A HREF="http://www.ietf.org/rfc/rfc2046.txt">RFC 2046</A>, which says the
* default character set is US-ASCII. Note that US-ASCII is a subset of
* UTF-8, so in the future this may be widened if a future RFC endorses
* UTF-8 as the default in a compatible manner.
* <p>
* Also note that this is different than the behaviour of the Java runtime
* when interpreting a stream of bytes as text data. That assumes the
* default encoding for the user's locale. Thus, when spooling a file in local
* encoding to a Java Print Service it is important to correctly specify
* the encoding. Developers working in the English locales should
* be particularly conscious of this, as their platform encoding corresponds
* to the default mime charset. By this coincidence that particular
* case may work without specifying the encoding of platform data.
* <p>
* Every instance of the Java virtual machine has a default character encoding
* determined during virtual-machine startup and typically depends upon the
* locale and charset being used by the underlying operating system.
* In a distributed environment there is no gurantee that two VM's share
* the same default encoding. Thus clients which want to stream platform
* encoded text data from the host platform to a Java Print Service instance
* must explicitly declare the charset and not rely on defaults.
* <p>
* The preferred form is the official IANA primary name for an encoding.
* Applications which stream text data should always specify the charset
* in the mime type, which necessitates obtaining the encoding of the host
* platform for data (eg files) stored in that platform's encoding.
* A CharSet which corresponds to this and is suitable for use in a
* mime-type for a DocFlavor can be obtained
* from {@link DocFlavor#hostEncoding <CODE>DocFlavor.hostEncoding</CODE>}
* This may not always be the primary IANA name but is guaranteed to be
* understood by this VM.
* For common flavors, the pre-defined *HOST DocFlavors may be used.
* <p>
* <p>
* See <a href="../../java/lang/package-summary.html#charenc">
* character encodings</a> for more information on the character encodings
* supported on the Java platform.
* <p>
* <HR>
* <h3>Recommended DocFlavors</h3>
* <P>
* The Java Print Service API does not define any mandatorily supported
* DocFlavors.
* However, here are some examples of MIME types that a Java Print Service
* instance might support for client formatted print data.
* Nested classes inside class DocFlavor declare predefined static
* constant DocFlavor objects for these example doc flavors; class DocFlavor's
* constructor can be used to create an arbitrary doc flavor.
* <UL>
* <LI>Preformatted text
* <P>
* <TABLE BORDER=1 CELLPADDING=0 CELLSPACING=0 SUMMARY="MIME-Types and their descriptions">
* <TR>
* <TH>MIME-Type</TH><TH>Description</TH>
* </TR>
* <TR>
* <TD><CODE>"text/plain"</CODE></TD>
* <TD>Plain text in the default character set (US-ASCII)</TD>
* </TR>
* <TR>
* <TD><CODE>"text/plain; charset=<I>xxx</I>"</CODE></TD>
* <TD>Plain text in character set <I>xxx</I></TD>
* </TR>
* <TR>
* <TD><CODE>"text/html"</CODE></TD>
* <TD>HyperText Markup Language in the default character set (US-ASCII)</TD>
* </TR>
* <TR>
* <TD><CODE>"text/html; charset=<I>xxx</I>"</CODE></TD>
* <TD>HyperText Markup Language in character set <I>xxx</I></TD>
* </TR>
* </TABLE>
* <P>
* In general, preformatted text print data is provided either in a character
* oriented representation class (character array, String, Reader) or in a
* byte oriented representation class (byte array, InputStream, URL).
* <P>
* <LI>Preformatted page description language (PDL) documents
*<P>
* <TABLE BORDER=1 CELLPADDING=0 CELLSPACING=0 SUMMARY="MIME-Types and their descriptions">
* <TR>
* <TH>MIME-Type</TH><TH>Description</TH>
* </TR>
*<TR>
* <TD><CODE>"application/pdf"</CODE></TD>
* <TD>Portable Document Format document</TD>
* </TR>
* <TR>
* <TD><CODE>"application/postscript"</CODE></TD>
* <TD>PostScript document</TD>
* </TR>
* <TR>
* <TD><CODE>"application/vnd.hp-PCL"</CODE></TD>
* <TD>Printer Control Language document</TD>
* </TR>
* </TABLE>
* <P>
* In general, preformatted PDL print data is provided in a byte oriented
* representation class (byte array, InputStream, URL).
* <P>
* <LI>Preformatted images
*<P>
* <TABLE BORDER=1 CELLPADDING=0 CELLSPACING=0 SUMMARY="MIME-Types and their descriptions">
* <TR>
* <TH>MIME-Type</TH><TH>Description</TH>
* </TR>
*
* <TR>
* <TD><CODE>"image/gif"</CODE></TD>
* <TD>Graphics Interchange Format image</TD>
* </TR>
* <TR>
* <TD><CODE>"image/jpeg"</CODE></TD>
* <TD>Joint Photographic Experts Group image</TD>
* </TR>
* <TR>
* <TD><CODE>"image/png"</CODE></TD>
* <TD>Portable Network Graphics image</TD>
* </TR>
* </TABLE>
* <P>
* In general, preformatted image print data is provided in a byte oriented
* representation class (byte array, InputStream, URL).
* <P>
* <LI>Preformatted autosense print data
* <P>
* <TABLE BORDER=1 CELLPADDING=0 CELLSPACING=0 SUMMARY="MIME-Types and their descriptions">
* <TR>
* <TH>MIME-Type</TH><TH>Description</TH>
* </TR>
*
* <TR>
* <TD><CODE>"application/octet-stream"</CODE></TD>
* <TD>The print data format is unspecified (just an octet stream)</TD>
* </TABLE>
* <P>
* The printer decides how to interpret the print data; the way this
* "autosensing" works is implementation dependent. In general, preformatted
* autosense print data is provided in a byte oriented representation class
* (byte array, InputStream, URL).
*
* <P>
* <HR>
* <H3>Service Formatted Print Data</H3>
* <P>
* For <B>service formatted print data</B>, the Java Print Service instance
* determines the print data format. The doc flavor's representation class
* denotes an interface whose methods the <code>DocPrintJob</code> invokes to
* determine the content to be printed -- such as a renderable image
* interface or a Java printable interface.
* The doc flavor's MIME type is the special value
* <CODE>"application/x-java-jvm-local-objectref"</CODE> indicating the client
* will supply a reference to a Java object that implements the interface
* named as the representation class.
* This MIME type is just a placeholder; what's
* important is the print data representation class.
* <P>
* For service formatted print data, the print data representation class is
* typically one of the following (although other representation classes are
* permitted). Nested classes inside class DocFlavor declare predefined static
* constant DocFlavor objects for these example doc flavors; class DocFlavor's
* constructor can be used to create an arbitrary doc flavor.
* <UL>
* <LI>
* Renderable image object -- The client supplies an object that implements
* interface
* {@link java.awt.image.renderable.RenderableImage RenderableImage}. The
* printer calls methods
* in that interface to obtain the image to be printed.
* <P>
* <LI>
* Printable object -- The client supplies an object that implements interface
* {@link java.awt.print.Printable Printable}.
* The printer calls methods in that interface to obtain the pages to be
* printed, one by one.
* For each page, the printer supplies a graphics context, and whatever the
* client draws in that graphics context gets printed.
* <P>
* <LI>
* Pageable object -- The client supplies an object that implements interface
* {@link java.awt.print.Pageable Pageable}. The printer calls
* methods in that interface to obtain the pages to be printed, one by one.
* For each page, the printer supplies a graphics context, and whatever
* the client draws in that graphics context gets printed.
* </UL>
* <P>
* <HR>
* <P>
* <HR>
* <H3>Pre-defined Doc Flavors</H3>
* A Java Print Service instance is not <B><I>required</I></B> to support the
* following print data formats and print data representation classes. In
* fact, a developer using this class should <b>never</b> assume that a
* particular print service supports the document types corresponding to
* these pre-defined doc flavors. Always query the print service
* to determine what doc flavors it supports. However,
* developers who have print services that support these doc flavors are
* encouraged to refer to the predefined singleton instances created here.
* <UL>
* <LI>
* Plain text print data provided through a byte stream. Specifically, the
* following doc flavors are recommended to be supported:
* <BR>·
* <CODE>("text/plain", "java.io.InputStream")</CODE>
* <BR>·
* <CODE>("text/plain; charset=us-ascii", "java.io.InputStream")</CODE>
* <BR>·
* <CODE>("text/plain; charset=utf-8", "java.io.InputStream")</CODE>
* <P>
* <LI>
* Renderable image objects. Specifically, the following doc flavor is
* recommended to be supported:
* <BR>·
* <CODE>("application/x-java-jvm-local-objectref", "java.awt.image.renderable.RenderableImage")</CODE>
* </UL>
* <P>
* A Java Print Service instance is allowed to support any other doc flavors
* (or none) in addition to the above mandatory ones, at the implementation's
* choice.
* <P>
* Support for the above doc flavors is desirable so a printing client can rely
* on being able to print on any JPS printer, regardless of which doc flavors
* the printer supports. If the printer doesn't support the client's preferred
* doc flavor, the client can at least print plain text, or the client can
* convert its data to a renderable image and print the image.
* <P>
* Furthermore, every Java Print Service instance must fulfill these
* requirements for processing plain text print data:
* <UL>
* <LI>
* The character pair carriage return-line feed (CR-LF) means
* "go to column 1 of the next line."
* <LI>
* A carriage return (CR) character standing by itself means
* "go to column 1 of the next line."
* <LI>
* A line feed (LF) character standing by itself means
* "go to column 1 of the next line."
* <LI>
* </UL>
* <P>
* The client must itself perform all plain text print data formatting not
* addressed by the above requirements.
* <P>
* <H3>Design Rationale</H3>
* <P>
* Class DocFlavor in package javax.print.data is similar to class
* {@link java.awt.datatransfer.DataFlavor DataFlavor}. Class
* <code>DataFlavor</code>
* is not used in the Java Print Service (JPS) API
* for three reasons which are all rooted in allowing the JPS API to be
* shared by other print services APIs which may need to run on Java profiles
* which do not include all of the Java Platform, Standard Edition.
* <OL TYPE=1>
* <LI>
* The JPS API is designed to be used in Java profiles which do not support
* AWT.
* <P>
* <LI>
* The implementation of class <code>java.awt.datatransfer.DataFlavor</code>
* does not guarantee that equivalent data flavors will have the same
* serialized representation. DocFlavor does, and can be used in services
* which need this.
* <P>
* <LI>
* The implementation of class <code>java.awt.datatransfer.DataFlavor</code>
* includes a human presentable name as part of the serialized representation.
* This is not appropriate as part of a service matching constraint.
* </OL>
* <P>
* Class DocFlavor's serialized representation uses the following
* canonical form of a MIME type string. Thus, two doc flavors with MIME types
* that are not identical but that are equivalent (that have the same
* canonical form) may be considered equal.
* <UL>
* <LI> The media type, media subtype, and parameters are retained, but all
* comments and whitespace characters are discarded.
* <LI> The media type, media subtype, and parameter names are converted to
* lowercase.
* <LI> The parameter values retain their original case, except a charset
* parameter value for a text media type is converted to lowercase.
* <LI> Quote characters surrounding parameter values are removed.
* <LI> Quoting backslash characters inside parameter values are removed.
* <LI> The parameters are arranged in ascending order of parameter name.
* </UL>
* <P>
* Class DocFlavor's serialized representation also contains the
* fully-qualified class <I>name</I> of the representation class
* (a String object), rather than the representation class itself
* (a Class object). This allows a client to examine the doc flavors a
* Java Print Service instance supports without having
* to load the representation classes, which may be problematic for
* limited-resource clients.
* <P>
*
* @author Alan Kaminsky
*/
public class DocFlavor implements Serializable, Cloneable {
private static final long serialVersionUID = -4512080796965449721L;
/** {@collect.stats}
* A String representing the host operating system encoding.
* This will follow the conventions documented in
* <a href="http://ietf.org/rfc/rfc2278.txt">
* <i>RFC 2278: IANA Charset Registration Procedures</i></a>
* except where historical names are returned for compatibility with
* previous versions of the Java platform.
* The value returned from method is valid only for the VM which
* returns it, for use in a DocFlavor.
* This is the charset for all the "HOST" pre-defined DocFlavors in
* the executing VM.
*/
public static final String hostEncoding;
static {
hostEncoding =
(String)java.security.AccessController.doPrivileged(
new sun.security.action.GetPropertyAction("file.encoding"));
}
/** {@collect.stats}
* MIME type.
*/
private transient MimeType myMimeType;
/** {@collect.stats}
* Representation class name.
* @serial
*/
private String myClassName;
/** {@collect.stats}
* String value for this doc flavor. Computed when needed and cached.
*/
private transient String myStringValue = null;
/** {@collect.stats}
* Constructs a new doc flavor object from the given MIME type and
* representation class name. The given MIME type is converted into
* canonical form and stored internally.
*
* @param mimeType MIME media type string.
* @param className Fully-qualified representation class name.
*
* @exception NullPointerException
* (unchecked exception) Thrown if <CODE>mimeType</CODE> is null or
* <CODE>className</CODE> is null.
* @exception IllegalArgumentException
* (unchecked exception) Thrown if <CODE>mimeType</CODE> does not
* obey the syntax for a MIME media type string.
*/
public DocFlavor(String mimeType, String className) {
if (className == null) {
throw new NullPointerException();
}
myMimeType = new MimeType (mimeType);
myClassName = className;
}
/** {@collect.stats}
* Returns this doc flavor object's MIME type string based on the
* canonical form. Each parameter value is enclosed in quotes.
* @return the mime type
*/
public String getMimeType() {
return myMimeType.getMimeType();
}
/** {@collect.stats}
* Returns this doc flavor object's media type (from the MIME type).
* @return the media type
*/
public String getMediaType() {
return myMimeType.getMediaType();
}
/** {@collect.stats}
* Returns this doc flavor object's media subtype (from the MIME type).
* @return the media sub-type
*/
public String getMediaSubtype() {
return myMimeType.getMediaSubtype();
}
/** {@collect.stats}
* Returns a <code>String</code> representing a MIME
* parameter.
* Mime types may include parameters which are usually optional.
* The charset for text types is a commonly useful example.
* This convenience method will return the value of the specified
* parameter if one was specified in the mime type for this flavor.
* <p>
* @param paramName the name of the paramater. This name is internally
* converted to the canonical lower case format before performing
* the match.
* @return String representing a mime parameter, or
* null if that parameter is not in the mime type string.
* @exception throws NullPointerException if paramName is null.
*/
public String getParameter(String paramName) {
return
(String)myMimeType.getParameterMap().get(paramName.toLowerCase());
}
/** {@collect.stats}
* Returns the name of this doc flavor object's representation class.
* @return the name of the representation class.
*/
public String getRepresentationClassName() {
return myClassName;
}
/** {@collect.stats}
* Converts this <code>DocFlavor</code> to a string.
*
* @return MIME type string based on the canonical form. Each parameter
* value is enclosed in quotes.
* A "class=" parameter is appended to the
* MIME type string to indicate the representation class name.
*/
public String toString() {
return getStringValue();
}
/** {@collect.stats}
* Returns a hash code for this doc flavor object.
*/
public int hashCode() {
return getStringValue().hashCode();
}
/** {@collect.stats}
* Determines if this doc flavor object is equal to the given object.
* The two are equal if the given object is not null, is an instance
* of <code>DocFlavor</code>, has a MIME type equivalent to this doc
* flavor object's MIME type (that is, the MIME types have the same media
* type, media subtype, and parameters), and has the same representation
* class name as this doc flavor object. Thus, if two doc flavor objects'
* MIME types are the same except for comments, they are considered equal.
* However, two doc flavor objects with MIME types of "text/plain" and
* "text/plain; charset=US-ASCII" are not considered equal, even though
* they represent the same media type (because the default character
* set for plain text is US-ASCII).
*
* @param obj Object to test.
*
* @return True if this doc flavor object equals <CODE>obj</CODE>, false
* otherwise.
*/
public boolean equals(Object obj) {
return
obj != null &&
obj instanceof DocFlavor &&
getStringValue().equals (((DocFlavor) obj).getStringValue());
}
/** {@collect.stats}
* Returns this doc flavor object's string value.
*/
private String getStringValue() {
if (myStringValue == null) {
myStringValue = myMimeType + "; class=\"" + myClassName + "\"";
}
return myStringValue;
}
/** {@collect.stats}
* Write the instance to a stream (ie serialize the object).
*/
private void writeObject(ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
s.writeObject(myMimeType.getMimeType());
}
/** {@collect.stats}
* Reconstitute an instance from a stream (that is, deserialize it).
*
* @serialData
* The serialised form of a DocFlavor is the String naming the
* representation class followed by the String representing the canonical
* form of the mime type.
*/
private void readObject(ObjectInputStream s)
throws ClassNotFoundException, IOException {
s.defaultReadObject();
myMimeType = new MimeType((String)s.readObject());
}
/** {@collect.stats}
* Class DocFlavor.BYTE_ARRAY provides predefined static constant
* DocFlavor objects for example doc flavors using a byte array
* (<CODE>byte[]</CODE>) as the print data representation class.
* <P>
*
* @author Alan Kaminsky
*/
public static class BYTE_ARRAY extends DocFlavor {
private static final long serialVersionUID = -9065578006593857475L;
/** {@collect.stats}
* Constructs a new doc flavor with the given MIME type and a print
* data representation class name of <CODE>"[B"</CODE> (byte array).
*
* @param mimeType MIME media type string.
*
* @exception NullPointerException
* (unchecked exception) Thrown if <CODE>mimeType</CODE> is null.
* @exception IllegalArgumentException
* (unchecked exception) Thrown if <CODE>mimeType</CODE> does not
* obey the syntax for a MIME media type string.
*/
public BYTE_ARRAY (String mimeType) {
super (mimeType, "[B");
}
/** {@collect.stats}
* Doc flavor with MIME type = <CODE>"text/plain"</CODE>,
* encoded in the host platform encoding.
* See {@link DocFlavor#hostEncoding <CODE>hostEncoding</CODE>}
* Print data representation class name =
* <CODE>"[B"</CODE> (byte array).
*/
public static final BYTE_ARRAY TEXT_PLAIN_HOST =
new BYTE_ARRAY ("text/plain; charset="+hostEncoding);
/** {@collect.stats}
* Doc flavor with MIME type =
* <CODE>"text/plain; charset=utf-8"</CODE>,
* print data representation class name = <CODE>"[B"</CODE> (byte
* array).
*/
public static final BYTE_ARRAY TEXT_PLAIN_UTF_8 =
new BYTE_ARRAY ("text/plain; charset=utf-8");
/** {@collect.stats}
* Doc flavor with MIME type =
* <CODE>"text/plain; charset=utf-16"</CODE>,
* print data representation class name = <CODE>"[B"</CODE> (byte
* array).
*/
public static final BYTE_ARRAY TEXT_PLAIN_UTF_16 =
new BYTE_ARRAY ("text/plain; charset=utf-16");
/** {@collect.stats}
* Doc flavor with MIME type =
* <CODE>"text/plain; charset=utf-16be"</CODE>
* (big-endian byte ordering),
* print data representation class name = <CODE>"[B"</CODE> (byte
* array).
*/
public static final BYTE_ARRAY TEXT_PLAIN_UTF_16BE =
new BYTE_ARRAY ("text/plain; charset=utf-16be");
/** {@collect.stats}
* Doc flavor with MIME type =
* <CODE>"text/plain; charset=utf-16le"</CODE>
* (little-endian byte ordering),
* print data representation class name = <CODE>"[B"</CODE> (byte
* array).
*/
public static final BYTE_ARRAY TEXT_PLAIN_UTF_16LE =
new BYTE_ARRAY ("text/plain; charset=utf-16le");
/** {@collect.stats}
* Doc flavor with MIME type =
* <CODE>"text/plain; charset=us-ascii"</CODE>,
* print data representation class name =
* <CODE>"[B"</CODE> (byte array).
*/
public static final BYTE_ARRAY TEXT_PLAIN_US_ASCII =
new BYTE_ARRAY ("text/plain; charset=us-ascii");
/** {@collect.stats}
* Doc flavor with MIME type = <CODE>"text/html"</CODE>,
* encoded in the host platform encoding.
* See {@link DocFlavor#hostEncoding <CODE>hostEncoding</CODE>}
* Print data representation class name =
* <CODE>"[B"</CODE> (byte array).
*/
public static final BYTE_ARRAY TEXT_HTML_HOST =
new BYTE_ARRAY ("text/html; charset="+hostEncoding);
/** {@collect.stats}
* Doc flavor with MIME type =
* <CODE>"text/html; charset=utf-8"</CODE>,
* print data representation class name = <CODE>"[B"</CODE> (byte
* array).
*/
public static final BYTE_ARRAY TEXT_HTML_UTF_8 =
new BYTE_ARRAY ("text/html; charset=utf-8");
/** {@collect.stats}
* Doc flavor with MIME type =
* <CODE>"text/html; charset=utf-16"</CODE>,
* print data representation class name = <CODE>"[B"</CODE> (byte
* array).
*/
public static final BYTE_ARRAY TEXT_HTML_UTF_16 =
new BYTE_ARRAY ("text/html; charset=utf-16");
/** {@collect.stats}
* Doc flavor with MIME type =
* <CODE>"text/html; charset=utf-16be"</CODE>
* (big-endian byte ordering),
* print data representation class name = <CODE>"[B"</CODE> (byte
* array).
*/
public static final BYTE_ARRAY TEXT_HTML_UTF_16BE =
new BYTE_ARRAY ("text/html; charset=utf-16be");
/** {@collect.stats}
* Doc flavor with MIME type =
* <CODE>"text/html; charset=utf-16le"</CODE>
* (little-endian byte ordering),
* print data representation class name = <CODE>"[B"</CODE> (byte
* array).
*/
public static final BYTE_ARRAY TEXT_HTML_UTF_16LE =
new BYTE_ARRAY ("text/html; charset=utf-16le");
/** {@collect.stats}
* Doc flavor with MIME type =
* <CODE>"text/html; charset=us-ascii"</CODE>,
* print data representation class name =
* <CODE>"[B"</CODE> (byte array).
*/
public static final BYTE_ARRAY TEXT_HTML_US_ASCII =
new BYTE_ARRAY ("text/html; charset=us-ascii");
/** {@collect.stats}
* Doc flavor with MIME type = <CODE>"application/pdf"</CODE>, print
* data representation class name = <CODE>"[B"</CODE> (byte array).
*/
public static final BYTE_ARRAY PDF = new BYTE_ARRAY ("application/pdf");
/** {@collect.stats}
* Doc flavor with MIME type = <CODE>"application/postscript"</CODE>,
* print data representation class name = <CODE>"[B"</CODE> (byte
* array).
*/
public static final BYTE_ARRAY POSTSCRIPT =
new BYTE_ARRAY ("application/postscript");
/** {@collect.stats}
* Doc flavor with MIME type = <CODE>"application/vnd.hp-PCL"</CODE>,
* print data representation class name = <CODE>"[B"</CODE> (byte
* array).
*/
public static final BYTE_ARRAY PCL =
new BYTE_ARRAY ("application/vnd.hp-PCL");
/** {@collect.stats}
* Doc flavor with MIME type = <CODE>"image/gif"</CODE>, print data
* representation class name = <CODE>"[B"</CODE> (byte array).
*/
public static final BYTE_ARRAY GIF = new BYTE_ARRAY ("image/gif");
/** {@collect.stats}
* Doc flavor with MIME type = <CODE>"image/jpeg"</CODE>, print data
* representation class name = <CODE>"[B"</CODE> (byte array).
*/
public static final BYTE_ARRAY JPEG = new BYTE_ARRAY ("image/jpeg");
/** {@collect.stats}
* Doc flavor with MIME type = <CODE>"image/png"</CODE>, print data
* representation class name = <CODE>"[B"</CODE> (byte array).
*/
public static final BYTE_ARRAY PNG = new BYTE_ARRAY ("image/png");
/** {@collect.stats}
* Doc flavor with MIME type =
* <CODE>"application/octet-stream"</CODE>,
* print data representation class name = <CODE>"[B"</CODE> (byte
* array). The client must determine that data described
* using this DocFlavor is valid for the printer.
*/
public static final BYTE_ARRAY AUTOSENSE =
new BYTE_ARRAY ("application/octet-stream");
}
/** {@collect.stats}
* Class DocFlavor.INPUT_STREAM provides predefined static constant
* DocFlavor objects for example doc flavors using a byte stream ({@link
* java.io.InputStream <CODE>java.io.InputStream</CODE>}) as the print
* data representation class.
* <P>
*
* @author Alan Kaminsky
*/
public static class INPUT_STREAM extends DocFlavor {
private static final long serialVersionUID = -7045842700749194127L;
/** {@collect.stats}
* Constructs a new doc flavor with the given MIME type and a print
* data representation class name of
* <CODE>"java.io.InputStream"</CODE> (byte stream).
*
* @param mimeType MIME media type string.
*
* @exception NullPointerException
* (unchecked exception) Thrown if <CODE>mimeType</CODE> is null.
* @exception IllegalArgumentException
* (unchecked exception) Thrown if <CODE>mimeType</CODE> does not
* obey the syntax for a MIME media type string.
*/
public INPUT_STREAM (String mimeType) {
super (mimeType, "java.io.InputStream");
}
/** {@collect.stats}
* Doc flavor with MIME type = <CODE>"text/plain"</CODE>,
* encoded in the host platform encoding.
* See {@link DocFlavor#hostEncoding <CODE>hostEncoding</CODE>}
* Print data representation class name =
* <CODE>"java.io.InputStream"</CODE> (byte stream).
*/
public static final INPUT_STREAM TEXT_PLAIN_HOST =
new INPUT_STREAM ("text/plain; charset="+hostEncoding);
/** {@collect.stats}
* Doc flavor with MIME type =
* <CODE>"text/plain; charset=utf-8"</CODE>,
* print data representation class name =
* <CODE>"java.io.InputStream"</CODE> (byte stream).
*/
public static final INPUT_STREAM TEXT_PLAIN_UTF_8 =
new INPUT_STREAM ("text/plain; charset=utf-8");
/** {@collect.stats}
* Doc flavor with MIME type =
* <CODE>"text/plain; charset=utf-16"</CODE>,
* print data representation class name =
* <CODE>"java.io.InputStream"</CODE> (byte stream).
*/
public static final INPUT_STREAM TEXT_PLAIN_UTF_16 =
new INPUT_STREAM ("text/plain; charset=utf-16");
/** {@collect.stats}
* Doc flavor with MIME type =
* <CODE>"text/plain; charset=utf-16be"</CODE>
* (big-endian byte ordering),
* print data representation class name =
* <CODE>"java.io.InputStream"</CODE> (byte stream).
*/
public static final INPUT_STREAM TEXT_PLAIN_UTF_16BE =
new INPUT_STREAM ("text/plain; charset=utf-16be");
/** {@collect.stats}
* Doc flavor with MIME type =
* <CODE>"text/plain; charset=utf-16le"</CODE>
* (little-endian byte ordering),
* print data representation class name =
* <CODE>"java.io.InputStream"</CODE> (byte stream).
*/
public static final INPUT_STREAM TEXT_PLAIN_UTF_16LE =
new INPUT_STREAM ("text/plain; charset=utf-16le");
/** {@collect.stats}
* Doc flavor with MIME type =
* <CODE>"text/plain; charset=us-ascii"</CODE>,
* print data representation class name =
* <CODE>"java.io.InputStream"</CODE> (byte stream).
*/
public static final INPUT_STREAM TEXT_PLAIN_US_ASCII =
new INPUT_STREAM ("text/plain; charset=us-ascii");
/** {@collect.stats}
* Doc flavor with MIME type = <CODE>"text/html"</CODE>,
* encoded in the host platform encoding.
* See {@link DocFlavor#hostEncoding <CODE>hostEncoding</CODE>}
* Print data representation class name =
* <CODE>"java.io.InputStream"</CODE> (byte stream).
*/
public static final INPUT_STREAM TEXT_HTML_HOST =
new INPUT_STREAM ("text/html; charset="+hostEncoding);
/** {@collect.stats}
* Doc flavor with MIME type =
* <CODE>"text/html; charset=utf-8"</CODE>,
* print data representation class name =
* <CODE>"java.io.InputStream"</CODE> (byte stream).
*/
public static final INPUT_STREAM TEXT_HTML_UTF_8 =
new INPUT_STREAM ("text/html; charset=utf-8");
/** {@collect.stats}
* Doc flavor with MIME type =
* <CODE>"text/html; charset=utf-16"</CODE>,
* print data representation class name =
* <CODE>"java.io.InputStream"</CODE> (byte stream).
*/
public static final INPUT_STREAM TEXT_HTML_UTF_16 =
new INPUT_STREAM ("text/html; charset=utf-16");
/** {@collect.stats}
* Doc flavor with MIME type =
* <CODE>"text/html; charset=utf-16be"</CODE>
* (big-endian byte ordering),
* print data representation class name =
* <CODE>"java.io.InputStream"</CODE> (byte stream).
*/
public static final INPUT_STREAM TEXT_HTML_UTF_16BE =
new INPUT_STREAM ("text/html; charset=utf-16be");
/** {@collect.stats}
* Doc flavor with MIME type =
* <CODE>"text/html; charset=utf-16le"</CODE>
* (little-endian byte ordering),
* print data representation class name =
* <CODE>"java.io.InputStream"</CODE> (byte stream).
*/
public static final INPUT_STREAM TEXT_HTML_UTF_16LE =
new INPUT_STREAM ("text/html; charset=utf-16le");
/** {@collect.stats}
* Doc flavor with MIME type =
* <CODE>"text/html; charset=us-ascii"</CODE>,
* print data representation class name =
* <CODE>"java.io.InputStream"</CODE> (byte stream).
*/
public static final INPUT_STREAM TEXT_HTML_US_ASCII =
new INPUT_STREAM ("text/html; charset=us-ascii");
/** {@collect.stats}
* Doc flavor with MIME type = <CODE>"application/pdf"</CODE>, print
* data representation class name = <CODE>"java.io.InputStream"</CODE>
* (byte stream).
*/
public static final INPUT_STREAM PDF = new INPUT_STREAM ("application/pdf");
/** {@collect.stats}
* Doc flavor with MIME type = <CODE>"application/postscript"</CODE>,
* print data representation class name =
* <CODE>"java.io.InputStream"</CODE> (byte stream).
*/
public static final INPUT_STREAM POSTSCRIPT =
new INPUT_STREAM ("application/postscript");
/** {@collect.stats}
* Doc flavor with MIME type = <CODE>"application/vnd.hp-PCL"</CODE>,
* print data representation class name =
* <CODE>"java.io.InputStream"</CODE> (byte stream).
*/
public static final INPUT_STREAM PCL =
new INPUT_STREAM ("application/vnd.hp-PCL");
/** {@collect.stats}
* Doc flavor with MIME type = <CODE>"image/gif"</CODE>, print data
* representation class name =
* <CODE>"java.io.InputStream"</CODE> (byte stream).
*/
public static final INPUT_STREAM GIF = new INPUT_STREAM ("image/gif");
/** {@collect.stats}
* Doc flavor with MIME type = <CODE>"image/jpeg"</CODE>, print data
* representation class name =
* <CODE>"java.io.InputStream"</CODE> (byte stream).
*/
public static final INPUT_STREAM JPEG = new INPUT_STREAM ("image/jpeg");
/** {@collect.stats}
* Doc flavor with MIME type = <CODE>"image/png"</CODE>, print data
* representation class name =
* <CODE>"java.io.InputStream"</CODE> (byte stream).
*/
public static final INPUT_STREAM PNG = new INPUT_STREAM ("image/png");
/** {@collect.stats}
* Doc flavor with MIME type =
* <CODE>"application/octet-stream"</CODE>,
* print data representation class name =
* <CODE>"java.io.InputStream"</CODE> (byte stream).
* The client must determine that data described
* using this DocFlavor is valid for the printer.
*/
public static final INPUT_STREAM AUTOSENSE =
new INPUT_STREAM ("application/octet-stream");
}
/** {@collect.stats}
* Class DocFlavor.URL provides predefined static constant DocFlavor
* objects.
* For example doc flavors using a Uniform Resource Locator ({@link
* java.net.URL <CODE>java.net.URL</CODE>}) as the print data
* representation class.
* <P>
*
* @author Alan Kaminsky
*/
public static class URL extends DocFlavor {
/** {@collect.stats}
* Constructs a new doc flavor with the given MIME type and a print
* data representation class name of <CODE>"java.net.URL"</CODE>.
*
* @param mimeType MIME media type string.
*
* @exception NullPointerException
* (unchecked exception) Thrown if <CODE>mimeType</CODE> is null.
* @exception IllegalArgumentException
* (unchecked exception) Thrown if <CODE>mimeType</CODE> does not
* obey the syntax for a MIME media type string.
*/
public URL (String mimeType) {
super (mimeType, "java.net.URL");
}
/** {@collect.stats}
* Doc flavor with MIME type = <CODE>"text/plain"</CODE>,
* encoded in the host platform encoding.
* See {@link DocFlavor#hostEncoding <CODE>hostEncoding</CODE>}
* Print data representation class name =
* <CODE>"java.net.URL"</CODE> (byte stream).
*/
public static final URL TEXT_PLAIN_HOST =
new URL ("text/plain; charset="+hostEncoding);
/** {@collect.stats}
* Doc flavor with MIME type =
* <CODE>"text/plain; charset=utf-8"</CODE>,
* print data representation class name =
* <CODE>"java.net.URL"</CODE> (byte stream).
*/
public static final URL TEXT_PLAIN_UTF_8 =
new URL ("text/plain; charset=utf-8");
/** {@collect.stats}
* Doc flavor with MIME type =
* <CODE>"text/plain; charset=utf-16"</CODE>,
* print data representation class name =
* <CODE>java.net.URL""</CODE> (byte stream).
*/
public static final URL TEXT_PLAIN_UTF_16 =
new URL ("text/plain; charset=utf-16");
/** {@collect.stats}
* Doc flavor with MIME type =
* <CODE>"text/plain; charset=utf-16be"</CODE>
* (big-endian byte ordering),
* print data representation class name =
* <CODE>"java.net.URL"</CODE> (byte stream).
*/
public static final URL TEXT_PLAIN_UTF_16BE =
new URL ("text/plain; charset=utf-16be");
/** {@collect.stats}
* Doc flavor with MIME type =
* <CODE>"text/plain; charset=utf-16le"</CODE>
* (little-endian byte ordering),
* print data representation class name =
* <CODE>"java.net.URL"</CODE> (byte stream).
*/
public static final URL TEXT_PLAIN_UTF_16LE =
new URL ("text/plain; charset=utf-16le");
/** {@collect.stats}
* Doc flavor with MIME type =
* <CODE>"text/plain; charset=us-ascii"</CODE>,
* print data representation class name =
* <CODE>"java.net.URL"</CODE> (byte stream).
*/
public static final URL TEXT_PLAIN_US_ASCII =
new URL ("text/plain; charset=us-ascii");
/** {@collect.stats}
* Doc flavor with MIME type = <CODE>"text/html"</CODE>,
* encoded in the host platform encoding.
* See {@link DocFlavor#hostEncoding <CODE>hostEncoding</CODE>}
* Print data representation class name =
* <CODE>"java.net.URL"</CODE> (byte stream).
*/
public static final URL TEXT_HTML_HOST =
new URL ("text/html; charset="+hostEncoding);
/** {@collect.stats}
* Doc flavor with MIME type =
* <CODE>"text/html; charset=utf-8"</CODE>,
* print data representation class name =
* <CODE>"java.net.URL"</CODE> (byte stream).
*/
public static final URL TEXT_HTML_UTF_8 =
new URL ("text/html; charset=utf-8");
/** {@collect.stats}
* Doc flavor with MIME type =
* <CODE>"text/html; charset=utf-16"</CODE>,
* print data representation class name =
* <CODE>"java.net.URL"</CODE> (byte stream).
*/
public static final URL TEXT_HTML_UTF_16 =
new URL ("text/html; charset=utf-16");
/** {@collect.stats}
* Doc flavor with MIME type =
* <CODE>"text/html; charset=utf-16be"</CODE>
* (big-endian byte ordering),
* print data representation class name =
* <CODE>"java.net.URL"</CODE> (byte stream).
*/
public static final URL TEXT_HTML_UTF_16BE =
new URL ("text/html; charset=utf-16be");
/** {@collect.stats}
* Doc flavor with MIME type =
* <CODE>"text/html; charset=utf-16le"</CODE>
* (little-endian byte ordering),
* print data representation class name =
* <CODE>"java.net.URL"</CODE> (byte stream).
*/
public static final URL TEXT_HTML_UTF_16LE =
new URL ("text/html; charset=utf-16le");
/** {@collect.stats}
* Doc flavor with MIME type =
* <CODE>"text/html; charset=us-ascii"</CODE>,
* print data representation class name =
* <CODE>"java.net.URL"</CODE> (byte stream).
*/
public static final URL TEXT_HTML_US_ASCII =
new URL ("text/html; charset=us-ascii");
/** {@collect.stats}
* Doc flavor with MIME type = <CODE>"application/pdf"</CODE>, print
* data representation class name = <CODE>"java.net.URL"</CODE>.
*/
public static final URL PDF = new URL ("application/pdf");
/** {@collect.stats}
* Doc flavor with MIME type = <CODE>"application/postscript"</CODE>,
* print data representation class name = <CODE>"java.net.URL"</CODE>.
*/
public static final URL POSTSCRIPT = new URL ("application/postscript");
/** {@collect.stats}
* Doc flavor with MIME type = <CODE>"application/vnd.hp-PCL"</CODE>,
* print data representation class name = <CODE>"java.net.URL"</CODE>.
*/
public static final URL PCL = new URL ("application/vnd.hp-PCL");
/** {@collect.stats}
* Doc flavor with MIME type = <CODE>"image/gif"</CODE>, print data
* representation class name = <CODE>"java.net.URL"</CODE>.
*/
public static final URL GIF = new URL ("image/gif");
/** {@collect.stats}
* Doc flavor with MIME type = <CODE>"image/jpeg"</CODE>, print data
* representation class name = <CODE>"java.net.URL"</CODE>.
*/
public static final URL JPEG = new URL ("image/jpeg");
/** {@collect.stats}
* Doc flavor with MIME type = <CODE>"image/png"</CODE>, print data
* representation class name = <CODE>"java.net.URL"</CODE>.
*/
public static final URL PNG = new URL ("image/png");
/** {@collect.stats}
* Doc flavor with MIME type =
* <CODE>"application/octet-stream"</CODE>,
* print data representation class name = <CODE>"java.net.URL"</CODE>.
* The client must determine that data described
* using this DocFlavor is valid for the printer.
*/
public static final URL AUTOSENSE = new URL ("application/octet-stream");
}
/** {@collect.stats}
* Class DocFlavor.CHAR_ARRAY provides predefined static constant
* DocFlavor objects for example doc flavors using a character array
* (<CODE>char[]</CODE>) as the print data representation class. As such,
* the character set is Unicode.
* <P>
*
* @author Alan Kaminsky
*/
public static class CHAR_ARRAY extends DocFlavor {
private static final long serialVersionUID = -8720590903724405128L;
/** {@collect.stats}
* Constructs a new doc flavor with the given MIME type and a print
* data representation class name of
* <CODE>"[C"</CODE> (character array).
*
* @param mimeType MIME media type string. If it is a text media
* type, it is assumed to contain a
* <CODE>"charset=utf-16"</CODE> parameter.
*
* @exception NullPointerException
* (unchecked exception) Thrown if <CODE>mimeType</CODE> is null.
* @exception IllegalArgumentException
* (unchecked exception) Thrown if <CODE>mimeType</CODE> does not
* obey the syntax for a MIME media type string.
*/
public CHAR_ARRAY (String mimeType) {
super (mimeType, "[C");
}
/** {@collect.stats}
* Doc flavor with MIME type = <CODE>"text/plain;
* charset=utf-16"</CODE>, print data representation class name =
* <CODE>"[C"</CODE> (character array).
*/
public static final CHAR_ARRAY TEXT_PLAIN =
new CHAR_ARRAY ("text/plain; charset=utf-16");
/** {@collect.stats}
* Doc flavor with MIME type = <CODE>"text/html;
* charset=utf-16"</CODE>, print data representation class name =
* <CODE>"[C"</CODE> (character array).
*/
public static final CHAR_ARRAY TEXT_HTML =
new CHAR_ARRAY ("text/html; charset=utf-16");
}
/** {@collect.stats}
* Class DocFlavor.STRING provides predefined static constant DocFlavor
* objects for example doc flavors using a string ({@link java.lang.String
* <CODE>java.lang.String</CODE>}) as the print data representation class.
* As such, the character set is Unicode.
* <P>
*
* @author Alan Kaminsky
*/
public static class STRING extends DocFlavor {
private static final long serialVersionUID = 4414407504887034035L;
/** {@collect.stats}
* Constructs a new doc flavor with the given MIME type and a print
* data representation class name of <CODE>"java.lang.String"</CODE>.
*
* @param mimeType MIME media type string. If it is a text media
* type, it is assumed to contain a
* <CODE>"charset=utf-16"</CODE> parameter.
*
* @exception NullPointerException
* (unchecked exception) Thrown if <CODE>mimeType</CODE> is null.
* @exception IllegalArgumentException
* (unchecked exception) Thrown if <CODE>mimeType</CODE> does not
* obey the syntax for a MIME media type string.
*/
public STRING (String mimeType) {
super (mimeType, "java.lang.String");
}
/** {@collect.stats}
* Doc flavor with MIME type = <CODE>"text/plain;
* charset=utf-16"</CODE>, print data representation class name =
* <CODE>"java.lang.String"</CODE>.
*/
public static final STRING TEXT_PLAIN =
new STRING ("text/plain; charset=utf-16");
/** {@collect.stats}
* Doc flavor with MIME type = <CODE>"text/html;
* charset=utf-16"</CODE>, print data representation class name =
* <CODE>"java.lang.String"</CODE>.
*/
public static final STRING TEXT_HTML =
new STRING ("text/html; charset=utf-16");
}
/** {@collect.stats}
* Class DocFlavor.READER provides predefined static constant DocFlavor
* objects for example doc flavors using a character stream ({@link
* java.io.Reader <CODE>java.io.Reader</CODE>}) as the print data
* representation class. As such, the character set is Unicode.
* <P>
*
* @author Alan Kaminsky
*/
public static class READER extends DocFlavor {
private static final long serialVersionUID = 7100295812579351567L;
/** {@collect.stats}
* Constructs a new doc flavor with the given MIME type and a print
* data representation class name of\
* <CODE>"java.io.Reader"</CODE> (character stream).
*
* @param mimeType MIME media type string. If it is a text media
* type, it is assumed to contain a
* <CODE>"charset=utf-16"</CODE> parameter.
*
* @exception NullPointerException
* (unchecked exception) Thrown if <CODE>mimeType</CODE> is null.
* @exception IllegalArgumentException
* (unchecked exception) Thrown if <CODE>mimeType</CODE> does not
* obey the syntax for a MIME media type string.
*/
public READER (String mimeType) {
super (mimeType, "java.io.Reader");
}
/** {@collect.stats}
* Doc flavor with MIME type = <CODE>"text/plain;
* charset=utf-16"</CODE>, print data representation class name =
* <CODE>"java.io.Reader"</CODE> (character stream).
*/
public static final READER TEXT_PLAIN =
new READER ("text/plain; charset=utf-16");
/** {@collect.stats}
* Doc flavor with MIME type = <CODE>"text/html;
* charset=utf-16"</CODE>, print data representation class name =
* <CODE>"java.io.Reader"</CODE> (character stream).
*/
public static final READER TEXT_HTML =
new READER ("text/html; charset=utf-16");
}
/** {@collect.stats}
* Class DocFlavor.SERVICE_FORMATTED provides predefined static constant
* DocFlavor objects for example doc flavors for service formatted print
* data.
* <P>
*
* @author Alan Kaminsky
*/
public static class SERVICE_FORMATTED extends DocFlavor {
private static final long serialVersionUID = 6181337766266637256L;
/** {@collect.stats}
* Constructs a new doc flavor with a MIME type of
* <CODE>"application/x-java-jvm-local-objectref"</CODE> indicating
* service formatted print data and the given print data
* representation class name.
*
* @param className Fully-qualified representation class name.
*
* @exception NullPointerException
* (unchecked exception) Thrown if <CODE>className</CODE> is
* null.
*/
public SERVICE_FORMATTED (String className) {
super ("application/x-java-jvm-local-objectref", className);
}
/** {@collect.stats}
* Service formatted print data doc flavor with print data
* representation class name =
* <CODE>"java.awt.image.renderable.RenderableImage"</CODE>
* (renderable image object).
*/
public static final SERVICE_FORMATTED RENDERABLE_IMAGE =
new SERVICE_FORMATTED("java.awt.image.renderable.RenderableImage");
/** {@collect.stats}
* Service formatted print data doc flavor with print data
* representation class name = <CODE>"java.awt.print.Printable"</CODE>
* (printable object).
*/
public static final SERVICE_FORMATTED PRINTABLE =
new SERVICE_FORMATTED ("java.awt.print.Printable");
/** {@collect.stats}
* Service formatted print data doc flavor with print data
* representation class name = <CODE>"java.awt.print.Pageable"</CODE>
* (pageable object).
*/
public static final SERVICE_FORMATTED PAGEABLE =
new SERVICE_FORMATTED ("java.awt.print.Pageable");
}
}
| Java |
/*
* Copyright (c) 2000, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.print;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import javax.print.DocFlavor;
import sun.awt.AppContext;
import java.util.ServiceLoader;
import java.util.ServiceConfigurationError;
/** {@collect.stats}
* A <code>StreamPrintServiceFactory</code> is the factory for
* {@link StreamPrintService} instances,
* which can print to an output stream in a particular
* document format described as a mime type.
* A typical output document format may be Postscript(TM).
* <p>
* This class is implemented by a service and located by the
* implementation using the
* <a href="../../../technotes/guides/jar/jar.html#Service Provider">
* SPI JAR File specification</a>.
* <p>
* Applications locate instances of this class by calling the
* {@link #lookupStreamPrintServiceFactories(DocFlavor, String)} method.
* <p>
* Applications can use a <code>StreamPrintService</code> obtained from a
* factory in place of a <code>PrintService</code> which represents a
* physical printer device.
*/
public abstract class StreamPrintServiceFactory {
static class Services {
private ArrayList listOfFactories = null;
}
private static Services getServices() {
Services services =
(Services)AppContext.getAppContext().get(Services.class);
if (services == null) {
services = new Services();
AppContext.getAppContext().put(Services.class, services);
}
return services;
}
private static ArrayList getListOfFactories() {
return getServices().listOfFactories;
}
private static ArrayList initListOfFactories() {
ArrayList listOfFactories = new ArrayList();
getServices().listOfFactories = listOfFactories;
return listOfFactories;
}
/** {@collect.stats}
* Locates factories for print services that can be used with
* a print job to output a stream of data in the
* format specified by {@code outputMimeType}.
* <p>
* The {@code outputMimeType} parameter describes the document type that
* you want to create, whereas the {@code flavor} parameter describes the
* format in which the input data will be provided by the application
* to the {@code StreamPrintService}.
* <p>
* Although null is an acceptable value to use in the lookup of stream
* printing services, it's typical to search for a particular
* desired format, such as Postscript(TM).
* <p>
* @param flavor of the input document type - null means match all
* types.
* @param outputMimeType representing the required output format, used to
* identify suitable stream printer factories. A value of null means
* match all formats.
* @return - matching factories for stream print service instance,
* empty if no suitable factories could be located.
*/
public static StreamPrintServiceFactory[]
lookupStreamPrintServiceFactories(DocFlavor flavor,
String outputMimeType) {
ArrayList list = getFactories(flavor, outputMimeType);
return (StreamPrintServiceFactory[])
(list.toArray(new StreamPrintServiceFactory[list.size()]));
}
/** {@collect.stats} Queries the factory for the document format that is emitted
* by printers obtained from this factory.
*
* @return the output format described as a mime type.
*/
public abstract String getOutputFormat();
/** {@collect.stats}
* Queries the factory for the document flavors that can be accepted
* by printers obtained from this factory.
* @return array of supported doc flavors.
*/
public abstract DocFlavor[] getSupportedDocFlavors();
/** {@collect.stats}
* Returns a <code>StreamPrintService</code> that can print to
* the specified output stream.
* The output stream is created and managed by the application.
* It is the application's responsibility to close the stream and
* to ensure that this Printer is not reused.
* The application should not close this stream until any print job
* created from the printer is complete. Doing so earlier may generate
* a <code>PrinterException</code> and an event indicating that the
* job failed.
* <p>
* Whereas a <code>PrintService</code> connected to a physical printer
* can be reused,
* a <code>StreamPrintService</code> connected to a stream cannot.
* The underlying <code>StreamPrintService</code> may be disposed by
* the print system with
* the {@link StreamPrintService#dispose() dispose} method
* before returning from the
* {@link DocPrintJob#print(Doc, javax.print.attribute.PrintRequestAttributeSet) print}
* method of <code>DocPrintJob</code> so that the print system knows
* this printer is no longer usable.
* This is equivalent to a physical printer going offline - permanently.
* Applications may supply a null print stream to create a queryable
* service. It is not valid to create a PrintJob for such a stream.
* Implementations which allocate resources on construction should examine
* the stream and may wish to only allocate resources if the stream is
* non-null.
* <p>
* @param out destination stream for generated output.
* @return a PrintService which will generate the format specified by the
* DocFlavor supported by this Factory.
*/
public abstract StreamPrintService getPrintService(OutputStream out);
private static ArrayList getAllFactories() {
synchronized (StreamPrintServiceFactory.class) {
ArrayList listOfFactories = getListOfFactories();
if (listOfFactories != null) {
return listOfFactories;
} else {
listOfFactories = initListOfFactories();
}
try {
java.security.AccessController.doPrivileged(
new java.security.PrivilegedExceptionAction() {
public Object run() {
Iterator<StreamPrintServiceFactory> iterator =
ServiceLoader.load
(StreamPrintServiceFactory.class).iterator();
ArrayList lof = getListOfFactories();
while (iterator.hasNext()) {
try {
lof.add(iterator.next());
} catch (ServiceConfigurationError err) {
/* In the applet case, we continue */
if (System.getSecurityManager() != null) {
err.printStackTrace();
} else {
throw err;
}
}
}
return null;
}
});
} catch (java.security.PrivilegedActionException e) {
}
return listOfFactories;
}
}
private static boolean isMember(DocFlavor flavor, DocFlavor[] flavors) {
for (int f=0; f<flavors.length; f++ ) {
if (flavor.equals(flavors[f])) {
return true;
}
}
return false;
}
private static ArrayList getFactories(DocFlavor flavor, String outType) {
if (flavor == null && outType == null) {
return getAllFactories();
}
ArrayList list = new ArrayList();
Iterator iterator = getAllFactories().iterator();
while (iterator.hasNext()) {
StreamPrintServiceFactory factory =
(StreamPrintServiceFactory)iterator.next();
if ((outType == null ||
outType.equalsIgnoreCase(factory.getOutputFormat())) &&
(flavor == null ||
isMember(flavor, factory.getSupportedDocFlavors()))) {
list.add(factory);
}
}
return list;
}
}
| Java |
/*
* Copyright (c) 2001, 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.print;
import java.io.ByteArrayInputStream;
import java.io.CharArrayReader;
import java.io.StringReader;
import java.io.InputStream;
import java.io.IOException;
import java.io.Reader;
import javax.print.attribute.AttributeSetUtilities;
import javax.print.attribute.DocAttributeSet;
/** {@collect.stats}
* This class is an implementation of interface <code>Doc</code> that can
* be used in many common printing requests.
* It can handle all of the presently defined "pre-defined" doc flavors
* defined as static variables in the DocFlavor class.
* <p>
* In particular this class implements certain required semantics of the
* Doc specification as follows:
* <ul>
* <li>constructs a stream for the service if requested and appropriate.
* <li>ensures the same object is returned for each call on a method.
* <li>ensures multiple threads can access the Doc
* <li>performs some validation of that the data matches the doc flavor.
* </ul>
* Clients who want to re-use the doc object in other jobs,
* or need a MultiDoc will not want to use this class.
* <p>
* If the print data is a stream, or a print job requests data as a
* stream, then <code>SimpleDoc</code> does not monitor if the service
* properly closes the stream after data transfer completion or job
* termination.
* Clients may prefer to use provide their own implementation of doc that
* adds a listener to monitor job completion and to validate that
* resources such as streams are freed (ie closed).
*/
public final class SimpleDoc implements Doc {
private DocFlavor flavor;
private DocAttributeSet attributes;
private Object printData;
private Reader reader;
private InputStream inStream;
/** {@collect.stats}
* Constructs a <code>SimpleDoc</code> with the specified
* print data, doc flavor and doc attribute set.
* @param printData the print data object
* @param flavor the <code>DocFlavor</code> object
* @param attributes a <code>DocAttributeSet</code>, which can
* be <code>null</code>
* @throws IllegalArgumentException if <code>flavor</code> or
* <code>printData</code> is <code>null</code>, or the
* <code>printData</code> does not correspond
* to the specified doc flavor--for example, the data is
* not of the type specified as the representation in the
* <code>DocFlavor</code>.
*/
public SimpleDoc(Object printData,
DocFlavor flavor, DocAttributeSet attributes) {
if (flavor == null || printData == null) {
throw new IllegalArgumentException("null argument(s)");
}
Class repClass = null;
try {
repClass = Class.forName(flavor.getRepresentationClassName());
} catch (Throwable e) {
throw new IllegalArgumentException("unknown representation class");
}
if (!repClass.isInstance(printData)) {
throw new IllegalArgumentException("data is not of declared type");
}
this.flavor = flavor;
if (attributes != null) {
this.attributes = AttributeSetUtilities.unmodifiableView(attributes);
}
this.printData = printData;
}
/** {@collect.stats}
* Determines the doc flavor in which this doc object will supply its
* piece of print data.
*
* @return Doc flavor.
*/
public DocFlavor getDocFlavor() {
return flavor;
}
/** {@collect.stats}
* Obtains the set of printing attributes for this doc object. If the
* returned attribute set includes an instance of a particular attribute
* <I>X,</I> the printer must use that attribute value for this doc,
* overriding any value of attribute <I>X</I> in the job's attribute set.
* If the returned attribute set does not include an instance
* of a particular attribute <I>X</I> or if null is returned, the printer
* must consult the job's attribute set to obtain the value for
* attribute <I>X,</I> and if not found there, the printer must use an
* implementation-dependent default value. The returned attribute set is
* unmodifiable.
*
* @return Unmodifiable set of printing attributes for this doc, or null
* to obtain all attribute values from the job's attribute
* set.
*/
public DocAttributeSet getAttributes() {
return attributes;
}
/*
* Obtains the print data representation object that contains this doc
* object's piece of print data in the format corresponding to the
* supported doc flavor.
* The <CODE>getPrintData()</CODE> method returns an instance of
* the representation class whose name is given by
* {@link DocFlavor#getRepresentationClassName() getRepresentationClassName},
* and the return value can be cast
* from class Object to that representation class.
*
* @return Print data representation object.
*
* @exception IOException if the representation class is a stream and
* there was an I/O error while constructing the stream.
*/
public Object getPrintData() throws IOException {
return printData;
}
/** {@collect.stats}
* Obtains a reader for extracting character print data from this doc.
* The <code>Doc</code> implementation is required to support this
* method if the <code>DocFlavor</code> has one of the following print
* data representation classes, and return <code>null</code>
* otherwise:
* <UL>
* <LI> <code>char[]</code>
* <LI> <code>java.lang.String</code>
* <LI> <code>java.io.Reader</code>
* </UL>
* The doc's print data representation object is used to construct and
* return a <code>Reader</code> for reading the print data as a stream
* of characters from the print data representation object.
* However, if the print data representation object is itself a
* <code>Reader</code> then the print data representation object is
* simply returned.
* <P>
* @return a <code>Reader</code> for reading the print data
* characters from this doc.
* If a reader cannot be provided because this doc does not meet
* the criteria stated above, <code>null</code> is returned.
*
* @exception IOException if there was an I/O error while creating
* the reader.
*/
public Reader getReaderForText() throws IOException {
if (printData instanceof Reader) {
return (Reader)printData;
}
synchronized (this) {
if (reader != null) {
return reader;
}
if (printData instanceof char[]) {
reader = new CharArrayReader((char[])printData);
}
else if (printData instanceof String) {
reader = new StringReader((String)printData);
}
}
return reader;
}
/** {@collect.stats}
* Obtains an input stream for extracting byte print data from
* this doc.
* The <code>Doc</code> implementation is required to support this
* method if the <code>DocFlavor</code> has one of the following print
* data representation classes; otherwise this method
* returns <code>null</code>:
* <UL>
* <LI> <code>byte[]</code>
* <LI> <code>java.io.InputStream</code>
* </UL>
* The doc's print data representation object is obtained. Then, an
* input stream for reading the print data
* from the print data representation object as a stream of bytes is
* created and returned.
* However, if the print data representation object is itself an
* input stream then the print data representation object is simply
* returned.
* <P>
* @return an <code>InputStream</code> for reading the print data
* bytes from this doc. If an input stream cannot be
* provided because this doc does not meet
* the criteria stated above, <code>null</code> is returned.
*
* @exception IOException
* if there was an I/O error while creating the input stream.
*/
public InputStream getStreamForBytes() throws IOException {
if (printData instanceof InputStream) {
return (InputStream)printData;
}
synchronized (this) {
if (inStream != null) {
return inStream;
}
if (printData instanceof byte[]) {
inStream = new ByteArrayInputStream((byte[])printData);
}
}
return inStream;
}
}
| Java |
/*
* Copyright (c) 2000, 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.print;
import java.io.Serializable;
import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.Vector;
/** {@collect.stats}
* Class MimeType encapsulates a Multipurpose Internet Mail Extensions (MIME)
* media type as defined in <A HREF="http://www.ietf.org/rfc/rfc2045.txt">RFC
* 2045</A> and <A HREF="http://www.ietf.org/rfc/rfc2046.txt">RFC 2046</A>. A
* MIME type object is part of a {@link DocFlavor DocFlavor} object and
* specifies the format of the print data.
* <P>
* Class MimeType is similar to the like-named
* class in package {@link java.awt.datatransfer java.awt.datatransfer}. Class
* java.awt.datatransfer.MimeType is not used in the Jini Print Service API
* for two reasons:
* <OL TYPE=1>
* <LI>
* Since not all Java profiles include the AWT, the Jini Print Service should
* not depend on an AWT class.
* <P>
* <LI>
* The implementation of class java.awt.datatransfer.MimeType does not
* guarantee
* that equivalent MIME types will have the same serialized representation.
* Thus, since the Jini Lookup Service (JLUS) matches service attributes based
* on equality of serialized representations, JLUS searches involving MIME
* types encapsulated in class java.awt.datatransfer.MimeType may incorrectly
* fail to match.
* </OL>
* <P>
* Class MimeType's serialized representation is based on the following
* canonical form of a MIME type string. Thus, two MIME types that are not
* identical but that are equivalent (that have the same canonical form) will
* be considered equal by the JLUS's matching algorithm.
* <UL>
* <LI> The media type, media subtype, and parameters are retained, but all
* comments and whitespace characters are discarded.
* <LI> The media type, media subtype, and parameter names are converted to
* lowercase.
* <LI> The parameter values retain their original case, except a charset
* parameter value for a text media type is converted to lowercase.
* <LI> Quote characters surrounding parameter values are removed.
* <LI> Quoting backslash characters inside parameter values are removed.
* <LI> The parameters are arranged in ascending order of parameter name.
* </UL>
* <P>
*
* @author Alan Kaminsky
*/
class MimeType implements Serializable, Cloneable {
private static final long serialVersionUID = -2785720609362367683L;
/** {@collect.stats}
* Array of strings that hold pieces of this MIME type's canonical form.
* If the MIME type has <I>n</I> parameters, <I>n</I> >= 0, then the
* strings in the array are:
* <BR>Index 0 -- Media type.
* <BR>Index 1 -- Media subtype.
* <BR>Index 2<I>i</I>+2 -- Name of parameter <I>i</I>,
* <I>i</I>=0,1,...,<I>n</I>-1.
* <BR>Index 2<I>i</I>+3 -- Value of parameter <I>i</I>,
* <I>i</I>=0,1,...,<I>n</I>-1.
* <BR>Parameters are arranged in ascending order of parameter name.
* @serial
*/
private String[] myPieces;
/** {@collect.stats}
* String value for this MIME type. Computed when needed and cached.
*/
private transient String myStringValue = null;
/** {@collect.stats}
* Parameter map entry set. Computed when needed and cached.
*/
private transient ParameterMapEntrySet myEntrySet = null;
/** {@collect.stats}
* Parameter map. Computed when needed and cached.
*/
private transient ParameterMap myParameterMap = null;
/** {@collect.stats}
* Parameter map entry.
*/
private class ParameterMapEntry implements Map.Entry {
private int myIndex;
public ParameterMapEntry(int theIndex) {
myIndex = theIndex;
}
public Object getKey(){
return myPieces[myIndex];
}
public Object getValue(){
return myPieces[myIndex+1];
}
public Object setValue (Object value) {
throw new UnsupportedOperationException();
}
public boolean equals(Object o) {
return (o != null &&
o instanceof Map.Entry &&
getKey().equals (((Map.Entry) o).getKey()) &&
getValue().equals(((Map.Entry) o).getValue()));
}
public int hashCode() {
return getKey().hashCode() ^ getValue().hashCode();
}
}
/** {@collect.stats}
* Parameter map entry set iterator.
*/
private class ParameterMapEntrySetIterator implements Iterator {
private int myIndex = 2;
public boolean hasNext() {
return myIndex < myPieces.length;
}
public Object next() {
if (hasNext()) {
ParameterMapEntry result = new ParameterMapEntry (myIndex);
myIndex += 2;
return result;
} else {
throw new NoSuchElementException();
}
}
public void remove() {
throw new UnsupportedOperationException();
}
}
/** {@collect.stats}
* Parameter map entry set.
*/
private class ParameterMapEntrySet extends AbstractSet {
public Iterator iterator() {
return new ParameterMapEntrySetIterator();
}
public int size() {
return (myPieces.length - 2) / 2;
}
}
/** {@collect.stats}
* Parameter map.
*/
private class ParameterMap extends AbstractMap {
public Set entrySet() {
if (myEntrySet == null) {
myEntrySet = new ParameterMapEntrySet();
}
return myEntrySet;
}
}
/** {@collect.stats}
* Construct a new MIME type object from the given string. The given
* string is converted into canonical form and stored internally.
*
* @param s MIME media type string.
*
* @exception NullPointerException
* (unchecked exception) Thrown if <CODE>s</CODE> is null.
* @exception IllegalArgumentException
* (unchecked exception) Thrown if <CODE>s</CODE> does not obey the
* syntax for a MIME media type string.
*/
public MimeType(String s) {
parse (s);
}
/** {@collect.stats}
* Returns this MIME type object's MIME type string based on the canonical
* form. Each parameter value is enclosed in quotes.
*/
public String getMimeType() {
return getStringValue();
}
/** {@collect.stats}
* Returns this MIME type object's media type.
*/
public String getMediaType() {
return myPieces[0];
}
/** {@collect.stats}
* Returns this MIME type object's media subtype.
*/
public String getMediaSubtype() {
return myPieces[1];
}
/** {@collect.stats}
* Returns an unmodifiable map view of the parameters in this MIME type
* object. Each entry in the parameter map view consists of a parameter
* name String (key) mapping to a parameter value String. If this MIME
* type object has no parameters, an empty map is returned.
*
* @return Parameter map for this MIME type object.
*/
public Map getParameterMap() {
if (myParameterMap == null) {
myParameterMap = new ParameterMap();
}
return myParameterMap;
}
/** {@collect.stats}
* Converts this MIME type object to a string.
*
* @return MIME type string based on the canonical form. Each parameter
* value is enclosed in quotes.
*/
public String toString() {
return getStringValue();
}
/** {@collect.stats}
* Returns a hash code for this MIME type object.
*/
public int hashCode() {
return getStringValue().hashCode();
}
/** {@collect.stats}
* Determine if this MIME type object is equal to the given object. The two
* are equal if the given object is not null, is an instance of class
* net.jini.print.data.MimeType, and has the same canonical form as this
* MIME type object (that is, has the same type, subtype, and parameters).
* Thus, if two MIME type objects are the same except for comments, they are
* considered equal. However, "text/plain" and "text/plain;
* charset=us-ascii" are not considered equal, even though they represent
* the same media type (because the default character set for plain text is
* US-ASCII).
*
* @param obj Object to test.
*
* @return True if this MIME type object equals <CODE>obj</CODE>, false
* otherwise.
*/
public boolean equals (Object obj) {
return(obj != null &&
obj instanceof MimeType &&
getStringValue().equals(((MimeType) obj).getStringValue()));
}
/** {@collect.stats}
* Returns this MIME type's string value in canonical form.
*/
private String getStringValue() {
if (myStringValue == null) {
StringBuffer result = new StringBuffer();
result.append (myPieces[0]);
result.append ('/');
result.append (myPieces[1]);
int n = myPieces.length;
for (int i = 2; i < n; i += 2) {
result.append(';');
result.append(' ');
result.append(myPieces[i]);
result.append('=');
result.append(addQuotes (myPieces[i+1]));
}
myStringValue = result.toString();
}
return myStringValue;
}
// Hidden classes, constants, and operations for parsing a MIME media type
// string.
// Lexeme types.
private static final int TOKEN_LEXEME = 0;
private static final int QUOTED_STRING_LEXEME = 1;
private static final int TSPECIAL_LEXEME = 2;
private static final int EOF_LEXEME = 3;
private static final int ILLEGAL_LEXEME = 4;
// Class for a lexical analyzer.
private static class LexicalAnalyzer {
protected String mySource;
protected int mySourceLength;
protected int myCurrentIndex;
protected int myLexemeType;
protected int myLexemeBeginIndex;
protected int myLexemeEndIndex;
public LexicalAnalyzer(String theSource) {
mySource = theSource;
mySourceLength = theSource.length();
myCurrentIndex = 0;
nextLexeme();
}
public int getLexemeType() {
return myLexemeType;
}
public String getLexeme() {
return(myLexemeBeginIndex >= mySourceLength ?
null :
mySource.substring(myLexemeBeginIndex, myLexemeEndIndex));
}
public char getLexemeFirstCharacter() {
return(myLexemeBeginIndex >= mySourceLength ?
'\u0000' :
mySource.charAt(myLexemeBeginIndex));
}
public void nextLexeme() {
int state = 0;
int commentLevel = 0;
char c;
while (state >= 0) {
switch (state) {
// Looking for a token, quoted string, or tspecial
case 0:
if (myCurrentIndex >= mySourceLength) {
myLexemeType = EOF_LEXEME;
myLexemeBeginIndex = mySourceLength;
myLexemeEndIndex = mySourceLength;
state = -1;
} else if (Character.isWhitespace
(c = mySource.charAt (myCurrentIndex ++))) {
state = 0;
} else if (c == '\"') {
myLexemeType = QUOTED_STRING_LEXEME;
myLexemeBeginIndex = myCurrentIndex;
state = 1;
} else if (c == '(') {
++ commentLevel;
state = 3;
} else if (c == '/' || c == ';' || c == '=' ||
c == ')' || c == '<' || c == '>' ||
c == '@' || c == ',' || c == ':' ||
c == '\\' || c == '[' || c == ']' ||
c == '?') {
myLexemeType = TSPECIAL_LEXEME;
myLexemeBeginIndex = myCurrentIndex - 1;
myLexemeEndIndex = myCurrentIndex;
state = -1;
} else {
myLexemeType = TOKEN_LEXEME;
myLexemeBeginIndex = myCurrentIndex - 1;
state = 5;
}
break;
// In a quoted string
case 1:
if (myCurrentIndex >= mySourceLength) {
myLexemeType = ILLEGAL_LEXEME;
myLexemeBeginIndex = mySourceLength;
myLexemeEndIndex = mySourceLength;
state = -1;
} else if ((c = mySource.charAt (myCurrentIndex ++)) == '\"') {
myLexemeEndIndex = myCurrentIndex - 1;
state = -1;
} else if (c == '\\') {
state = 2;
} else {
state = 1;
}
break;
// In a quoted string, backslash seen
case 2:
if (myCurrentIndex >= mySourceLength) {
myLexemeType = ILLEGAL_LEXEME;
myLexemeBeginIndex = mySourceLength;
myLexemeEndIndex = mySourceLength;
state = -1;
} else {
++ myCurrentIndex;
state = 1;
} break;
// In a comment
case 3: if (myCurrentIndex >= mySourceLength) {
myLexemeType = ILLEGAL_LEXEME;
myLexemeBeginIndex = mySourceLength;
myLexemeEndIndex = mySourceLength;
state = -1;
} else if ((c = mySource.charAt (myCurrentIndex ++)) == '(') {
++ commentLevel;
state = 3;
} else if (c == ')') {
-- commentLevel;
state = commentLevel == 0 ? 0 : 3;
} else if (c == '\\') {
state = 4;
} else { state = 3;
}
break;
// In a comment, backslash seen
case 4:
if (myCurrentIndex >= mySourceLength) {
myLexemeType = ILLEGAL_LEXEME;
myLexemeBeginIndex = mySourceLength;
myLexemeEndIndex = mySourceLength;
state = -1;
} else {
++ myCurrentIndex;
state = 3;
}
break;
// In a token
case 5:
if (myCurrentIndex >= mySourceLength) {
myLexemeEndIndex = myCurrentIndex;
state = -1;
} else if (Character.isWhitespace
(c = mySource.charAt (myCurrentIndex ++))) {
myLexemeEndIndex = myCurrentIndex - 1;
state = -1;
} else if (c == '\"' || c == '(' || c == '/' ||
c == ';' || c == '=' || c == ')' ||
c == '<' || c == '>' || c == '@' ||
c == ',' || c == ':' || c == '\\' ||
c == '[' || c == ']' || c == '?') {
-- myCurrentIndex;
myLexemeEndIndex = myCurrentIndex;
state = -1;
} else {
state = 5;
}
break;
}
}
}
}
/** {@collect.stats}
* Returns a lowercase version of the given string. The lowercase version
* is constructed by applying Character.toLowerCase() to each character of
* the given string, which maps characters to lowercase using the rules of
* Unicode. This mapping is the same regardless of locale, whereas the
* mapping of String.toLowerCase() may be different depending on the
* default locale.
*/
private static String toUnicodeLowerCase(String s) {
int n = s.length();
char[] result = new char [n];
for (int i = 0; i < n; ++ i) {
result[i] = Character.toLowerCase (s.charAt (i));
}
return new String (result);
}
/** {@collect.stats}
* Returns a version of the given string with backslashes removed.
*/
private static String removeBackslashes(String s) {
int n = s.length();
char[] result = new char [n];
int i;
int j = 0;
char c;
for (i = 0; i < n; ++ i) {
c = s.charAt (i);
if (c == '\\') {
c = s.charAt (++ i);
}
result[j++] = c;
}
return new String (result, 0, j);
}
/** {@collect.stats}
* Returns a version of the string surrounded by quotes and with interior
* quotes preceded by a backslash.
*/
private static String addQuotes(String s) {
int n = s.length();
int i;
char c;
StringBuffer result = new StringBuffer (n+2);
result.append ('\"');
for (i = 0; i < n; ++ i) {
c = s.charAt (i);
if (c == '\"') {
result.append ('\\');
}
result.append (c);
}
result.append ('\"');
return result.toString();
}
/** {@collect.stats}
* Parses the given string into canonical pieces and stores the pieces in
* {@link #myPieces <CODE>myPieces</CODE>}.
* <P>
* Special rules applied:
* <UL>
* <LI> If the media type is text, the value of a charset parameter is
* converted to lowercase.
* </UL>
*
* @param s MIME media type string.
*
* @exception NullPointerException
* (unchecked exception) Thrown if <CODE>s</CODE> is null.
* @exception IllegalArgumentException
* (unchecked exception) Thrown if <CODE>s</CODE> does not obey the
* syntax for a MIME media type string.
*/
private void parse(String s) {
// Initialize.
if (s == null) {
throw new NullPointerException();
}
LexicalAnalyzer theLexer = new LexicalAnalyzer (s);
int theLexemeType;
Vector thePieces = new Vector();
boolean mediaTypeIsText = false;
boolean parameterNameIsCharset = false;
// Parse media type.
if (theLexer.getLexemeType() == TOKEN_LEXEME) {
String mt = toUnicodeLowerCase (theLexer.getLexeme());
thePieces.add (mt);
theLexer.nextLexeme();
mediaTypeIsText = mt.equals ("text");
} else {
throw new IllegalArgumentException();
}
// Parse slash.
if (theLexer.getLexemeType() == TSPECIAL_LEXEME &&
theLexer.getLexemeFirstCharacter() == '/') {
theLexer.nextLexeme();
} else {
throw new IllegalArgumentException();
}
if (theLexer.getLexemeType() == TOKEN_LEXEME) {
thePieces.add (toUnicodeLowerCase (theLexer.getLexeme()));
theLexer.nextLexeme();
} else {
throw new IllegalArgumentException();
}
// Parse zero or more parameters.
while (theLexer.getLexemeType() == TSPECIAL_LEXEME &&
theLexer.getLexemeFirstCharacter() == ';') {
// Parse semicolon.
theLexer.nextLexeme();
// Parse parameter name.
if (theLexer.getLexemeType() == TOKEN_LEXEME) {
String pn = toUnicodeLowerCase (theLexer.getLexeme());
thePieces.add (pn);
theLexer.nextLexeme();
parameterNameIsCharset = pn.equals ("charset");
} else {
throw new IllegalArgumentException();
}
// Parse equals.
if (theLexer.getLexemeType() == TSPECIAL_LEXEME &&
theLexer.getLexemeFirstCharacter() == '=') {
theLexer.nextLexeme();
} else {
throw new IllegalArgumentException();
}
// Parse parameter value.
if (theLexer.getLexemeType() == TOKEN_LEXEME) {
String pv = theLexer.getLexeme();
thePieces.add(mediaTypeIsText && parameterNameIsCharset ?
toUnicodeLowerCase (pv) :
pv);
theLexer.nextLexeme();
} else if (theLexer.getLexemeType() == QUOTED_STRING_LEXEME) {
String pv = removeBackslashes (theLexer.getLexeme());
thePieces.add(mediaTypeIsText && parameterNameIsCharset ?
toUnicodeLowerCase (pv) :
pv);
theLexer.nextLexeme();
} else {
throw new IllegalArgumentException();
}
}
// Make sure we've consumed everything.
if (theLexer.getLexemeType() != EOF_LEXEME) {
throw new IllegalArgumentException();
}
// Save the pieces. Parameters are not in ascending order yet.
int n = thePieces.size();
myPieces = (String[]) thePieces.toArray (new String [n]);
// Sort the parameters into ascending order using an insertion sort.
int i, j;
String temp;
for (i = 4; i < n; i += 2) {
j = 2;
while (j < i && myPieces[j].compareTo (myPieces[i]) <= 0) {
j += 2;
}
while (j < i) {
temp = myPieces[j];
myPieces[j] = myPieces[i];
myPieces[i] = temp;
temp = myPieces[j+1];
myPieces[j+1] = myPieces[i+1];
myPieces[i+1] = temp;
j += 2;
}
}
}
}
| Java |
/*
* Copyright (c) 2000, 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.print;
/** {@collect.stats}
* Class PrintException encapsulates a printing-related error condition that
* occurred while using a Print Service instance. This base class
* furnishes only a string description of the error. Subclasses furnish more
* detailed information if applicable.
*
*/
public class PrintException extends Exception {
/** {@collect.stats}
* Construct a print exception with no detail message.
*/
public PrintException() {
super();
}
/** {@collect.stats}
* Construct a print exception with the given detail message.
*
* @param s Detail message, or null if no detail message.
*/
public PrintException (String s) {
super (s);
}
/** {@collect.stats}
* Construct a print exception chaining the supplied exception.
*
* @param e Chained exception.
*/
public PrintException (Exception e) {
super ( e);
}
/** {@collect.stats}
* Construct a print exception with the given detail message
* and chained exception.
* @param s Detail message, or null if no detail message.
* @param e Chained exception.
*/
public PrintException (String s, Exception e) {
super (s, e);
}
}
| Java |
/*
* Copyright (c) 2000, 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.print;
import java.util.Map;
import javax.print.attribute.Attribute;
import javax.print.event.PrintServiceAttributeListener;
/** {@collect.stats} Interface MultiPrintService is the factory for a MultiDocPrintJob.
* A MultiPrintService
* describes the capabilities of a Printer and can be queried regarding
* a printer's supported attributes.
*/
public interface MultiDocPrintService extends PrintService {
/** {@collect.stats}
* Create a job which can print a multiDoc.
* @return a MultiDocPrintJob
*/
public MultiDocPrintJob createMultiDocPrintJob();
}
| Java |
/*
* Copyright (c) 2000, 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.print;
import javax.print.attribute.Attribute;
/** {@collect.stats}
* Interface AttributeException is a mixin interface which a subclass of
* {@link
* PrintException PrintException} can implement to report an error condition
* involving one or more printing attributes that a particular Print
* Service instance does not support. Either the attribute is not supported at
* all, or the attribute is supported but the particular specified value is not
* supported. The Print Service API does not define any print exception
* classes that implement interface AttributeException, that being left to the
* Print Service implementor's discretion.
*
*/
public interface AttributeException {
/** {@collect.stats}
* Returns the array of printing attribute classes for which the Print
* Service instance does not support the attribute at all, or null if
* there are no such attributes. The objects in the returned array are
* classes that extend the base interface
* {@link javax.print.attribute.Attribute Attribute}.
*
* @return unsupported attribute classes
*/
public Class[] getUnsupportedAttributes();
/** {@collect.stats}
* Returns the array of printing attributes for which the Print Service
* instance supports the attribute but does not support that particular
* value of the attribute, or null if there are no such attribute values.
*
* @return unsupported attribute values
*/
public Attribute[] getUnsupportedValues();
}
| Java |
/*
* Copyright (c) 2000, 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.print;
import java.io.IOException;
/** {@collect.stats}
* Interface MultiDoc specifies the interface for an object that supplies more
* than one piece of print data for a Print Job. "Doc" is a short,
* easy-to-pronounce term that means "a piece of print data," and a "multidoc"
* is a group of several docs. The client passes to the Print Job an object
* that implements interface MultiDoc, and the Print Job calls methods on
* that object to obtain the print data.
* <P>
* Interface MultiDoc provides an abstraction similar to a "linked list" of
* docs. A multidoc object is like a node in the linked list, containing the
* current doc in the list and a pointer to the next node (multidoc) in the
* list. The Print Job can call the multidoc's {@link #getDoc()
* <CODE>getDoc()</CODE>} method to get the current doc. When it's ready to go
* on to the next doc, the Print Job can call the multidoc's {@link #next()
* <CODE>next()</CODE>} method to get the next multidoc, which contains the
* next doc. So Print Job code for accessing a multidoc might look like this:
* <PRE>
* void processMultiDoc(MultiDoc theMultiDoc) {
*
* MultiDoc current = theMultiDoc;
* while (current != null) {
* processDoc (current.getDoc());
* current = current.next();
* }
* }
* </PRE>
* <P>
* Of course, interface MultiDoc can be implemented in any way that fulfills
* the contract; it doesn't have to use a linked list in the implementation.
* <P>
* To get all the print data for a multidoc print job, a Print Service
* proxy could use either of two patterns:
* <OL TYPE=1>
* <LI>
* The <B>interleaved</B> pattern: Get the doc from the current multidoc. Get
* the print data representation object from the current doc. Get all the print
* data from the print data representation object. Get the next multidoc from
* the current multidoc, and repeat until there are no more. (The code example
* above uses the interleaved pattern.)
* <P>
* <LI>
* The <B>all-at-once</B> pattern: Get the doc from the current multidoc, and
* save the doc in a list. Get the next multidoc from the current multidoc, and
* repeat until there are no more. Then iterate over the list of saved docs. Get
* the print data representation object from the current doc. Get all the print
* data from the print data representation object. Go to the next doc in the
* list, and repeat until there are no more.
* </OL>
* Now, consider a printing client that is generating print data on the fly and
* does not have the resources to store more than one piece of print data at a
* time. If the print service proxy used the all-at-once pattern to get the
* print data, it would pose a problem for such a client; the client would have
* to keep all the docs' print data around until the print service proxy comes
* back and asks for them, which the client is not able to do. To work with such
* a client, the print service proxy must use the interleaved pattern.
* <P>
* To address this problem, and to simplify the design of clients providing
* multiple docs to a Print Job, every Print Service proxy that supports
* multidoc print jobs is required to access a MultiDoc object using the
* interleaved pattern. That is, given a MultiDoc object, the print service
* proxy will call {@link #getDoc() <CODE>getDoc()</CODE>} one or more times
* until it successfully obtains the current Doc object. The print service proxy
* will then obtain the current doc's print data, not proceeding until all the
* print data is obtained or an unrecoverable error occurs. If it is able to
* continue, the print service proxy will then call {@link #next()
* <CODE>next()</CODE>} one or more times until it successfully obtains either
* the next MultiDoc object or an indication that there are no more. An
* implementation of interface MultiDoc can assume the print service proxy will
* follow this interleaved pattern; for any other pattern of usage, the MultiDoc
* implementation's behavior is unspecified.
* <P>
* There is no restriction on the number of client threads that may be
* simultaneously accessing the same multidoc. Therefore, all implementations of
* interface MultiDoc must be designed to be multiple thread safe. In fact, a
* client thread could be adding docs to the end of the (conceptual) list while
* a Print Job thread is simultaneously obtaining docs from the beginning of the
* list; provided the multidoc object synchronizes the threads properly, the two
* threads will not interfere with each other
*/
public interface MultiDoc {
/** {@collect.stats}
* Obtain the current doc object.
*
* @return Current doc object.
*
* @exception IOException
* Thrown if a error ocurred reading the document.
*/
public Doc getDoc() throws IOException;
/** {@collect.stats}
* Go to the multidoc object that contains the next doc object in the
* sequence of doc objects.
*
* @return Multidoc object containing the next doc object, or null if
* there are no further doc objects.
*
* @exception IOException
* Thrown if an error occurred locating the next document
*/
public MultiDoc next() throws IOException;
}
| Java |
/*
* Copyright (c) 2000, 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.print;
/** {@collect.stats}
* Services may optionally provide UIs which allow different styles
* of interaction in different roles.
* One role may be end-user browsing and setting of print options.
* Another role may be administering the print service.
* <p>
* Although the Print Service API does not presently provide standardised
* support for administering a print service, monitoring of the print
* service is possible and a UI may provide for private update mechanisms.
* <p>
* The basic design intent is to allow applications to lazily locate and
* initialize services only when needed without any API dependencies
* except in an environment in which they are used.
* <p>
* Swing UIs are preferred as they provide a more consistent L&F and
* can support accessibility APIs.
* <p>
* Example usage:
* <pre>
* ServiceUIFactory factory = printService.getServiceUIFactory();
* if (factory != null) {
* JComponent swingui = (JComponent)factory.getUI(
* ServiceUIFactory.MAIN_UIROLE,
* ServiceUIFactory.JCOMPONENT_UI);
* if (swingui != null) {
* tabbedpane.add("Custom UI", swingui);
* }
* }
* </pre>
*/
public abstract class ServiceUIFactory {
/** {@collect.stats}
* Denotes a UI implemented as a Swing component.
* The value of the String is the fully qualified classname :
* "javax.swing.JComponent".
*/
public static final String JCOMPONENT_UI = "javax.swing.JComponent";
/** {@collect.stats}
* Denotes a UI implemented as an AWT panel.
* The value of the String is the fully qualified classname :
* "java.awt.Panel"
*/
public static final String PANEL_UI = "java.awt.Panel";
/** {@collect.stats}
* Denotes a UI implemented as an AWT dialog.
* The value of the String is the fully qualified classname :
* "java.awt.Dialog"
*/
public static final String DIALOG_UI = "java.awt.Dialog";
/** {@collect.stats}
* Denotes a UI implemented as a Swing dialog.
* The value of the String is the fully qualified classname :
* "javax.swing.JDialog"
*/
public static final String JDIALOG_UI = "javax.swing.JDialog";
/** {@collect.stats}
* Denotes a UI which performs an informative "About" role.
*/
public static final int ABOUT_UIROLE = 1;
/** {@collect.stats}
* Denotes a UI which performs an administrative role.
*/
public static final int ADMIN_UIROLE = 2;
/** {@collect.stats}
* Denotes a UI which performs the normal end user role.
*/
public static final int MAIN_UIROLE = 3;
/** {@collect.stats}
* Not a valid role but role id's greater than this may be used
* for private roles supported by a service. Knowledge of the
* function performed by this role is required to make proper use
* of it.
*/
public static final int RESERVED_UIROLE = 99;
/** {@collect.stats}
* Get a UI object which may be cast to the requested UI type
* by the application and used in its user interface.
* <P>
* @param role requested. Must be one of the standard roles or
* a private role supported by this factory.
* @param ui type in which the role is requested.
* @return the UI role or null if the requested UI role is not available
* from this factory
* @throws IllegalArgumentException if the role or ui is neither
* one of the standard ones, nor a private one
* supported by the factory.
*/
public abstract Object getUI(int role, String ui) ;
/** {@collect.stats}
* Given a UI role obtained from this factory obtain the UI
* types available from this factory which implement this role.
* The returned Strings should refer to the static variables defined
* in this class so that applications can use equality of reference
* ("==").
* @param role to be looked up.
* @return the UI types supported by this class for the specified role,
* null if no UIs are available for the role.
* @throws IllegalArgumentException is the role is a non-standard
* role not supported by this factory.
*/
public abstract String[] getUIClassNamesForRole(int role) ;
}
| Java |
/*
* Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.print;
import javax.print.attribute.AttributeSet;
import javax.print.attribute.PrintJobAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.event.PrintJobAttributeListener;
import javax.print.event.PrintJobListener;
import javax.print.PrintException;
/** {@collect.stats}
*
* This interface represents a print job that can print a specified
* document with a set of job attributes. An object implementing
* this interface is obtained from a print service.
*
*/
public interface DocPrintJob {
/** {@collect.stats}
* Determines the {@link PrintService} object to which this print job
* object is bound.
*
* @return <code>PrintService</code> object.
*
*/
public PrintService getPrintService();
/** {@collect.stats}
* Obtains this Print Job's set of printing attributes.
* The returned attribute set object is unmodifiable.
* The returned attribute set object is a "snapshot" of this Print Job's
* attribute set at the time of the {@link #getAttributes()} method
* call; that is, the returned attribute set's object's contents will
* not be updated if this Print Job's attribute set's contents change
* in the future. To detect changes in attribute values, call
* <code>getAttributes()</code> again and compare the new attribute
* set to the previous attribute set; alternatively, register a
* listener for print job events.
* The returned value may be an empty set but should not be null.
* @return the print job attributes
*/
public PrintJobAttributeSet getAttributes();
/** {@collect.stats}
* Registers a listener for event occurring during this print job.
* If listener is null, no exception is thrown and no action is
* performed.
* If listener is already registered, it will be registered again.
* @see #removePrintJobListener
*
* @param listener The object implementing the listener interface
*
*/
public void addPrintJobListener(PrintJobListener listener);
/** {@collect.stats}
* Removes a listener from this print job.
* This method performs no function, nor does it throw an exception,
* if the listener specified by the argument was not previously added
* to this component. If listener is null, no exception is thrown and
* no action is performed. If a listener was registered more than once
* only one of the registrations will be removed.
* @see #addPrintJobListener
*
* @param listener The object implementing the listener interface
*/
public void removePrintJobListener(PrintJobListener listener);
/** {@collect.stats}
* Registers a listener for changes in the specified attributes.
* If listener is null, no exception is thrown and no action is
* performed.
* To determine the attribute updates that may be reported by this job,
* a client can call <code>getAttributes()</code> and identify the
* subset that are interesting and likely to be reported to the
* listener. Clients expecting to be updated about changes in a
* specific job attribute should verify it is in that set, but
* updates about an attribute will be made only if it changes and this
* is detected by the job. Also updates may be subject to batching
* by the job. To minimise overhead in print job processing it is
* recommended to listen on only that subset of attributes which
* are likely to change.
* If the specified set is empty no attribute updates will be reported
* to the listener.
* If the attribute set is null, then this means to listen on all
* dynamic attributes that the job supports. This may result in no
* update notifications if a job can not report any attribute updates.
*
* If listener is already registered, it will be registered again.
* @see #removePrintJobAttributeListener
*
* @param listener The object implementing the listener interface
* @param attributes The attributes to listen on, or null to mean
* all attributes that can change, as determined by the job.
*/
public void addPrintJobAttributeListener(
PrintJobAttributeListener listener,
PrintJobAttributeSet attributes);
/** {@collect.stats}
* Removes an attribute listener from this print job.
* This method performs no function, nor does it throw an exception,
* if the listener specified by the argument was not previously added
* to this component. If the listener is null, no exception is thrown
* and no action is performed.
* If a listener is registered more than once, even for a different
* set of attributes, no guarantee is made which listener is removed.
* @see #addPrintJobAttributeListener
*
* @param listener The object implementing the listener interface
*
*/
public void removePrintJobAttributeListener(
PrintJobAttributeListener listener);
/** {@collect.stats}
* Prints a document with the specified job attributes.
* This method should only be called once for a given print job.
* Calling it again will not result in a new job being spooled to
* the printer. The service implementation will define policy
* for service interruption and recovery.
* When the print method returns, printing may not yet have completed as
* printing may happen asynchronously, perhaps in a different thread.
* Application clients which want to monitor the success or failure
* should register a PrintJobListener.
* <p>
* Print service implementors should close any print data streams (ie
* Reader or InputStream implementations) that they obtain
* from the client doc. Robust clients may still wish to verify this.
* An exception is always generated if a <code>DocFlavor</code> cannot
* be printed.
*
* @param doc The document to be printed. If must be a flavor
* supported by this PrintJob.
*
* @param attributes The job attributes to be applied to this print job.
* If this parameter is null then the default attributes are used.
* @throws PrintException The exception additionally may implement
* an interface that more precisely describes the cause of the
* exception
* <ul>
* <li>FlavorException.
* If the document has a flavor not supported by this print job.
* <li>AttributeException.
* If one or more of the attributes are not valid for this print job.
* </ul>
*/
public void print(Doc doc, PrintRequestAttributeSet attributes)
throws PrintException;
}
| Java |
/*
* Copyright (c) 1999, 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management;
import java.util.concurrent.CopyOnWriteArrayList; // for Javadoc
/** {@collect.stats}
* <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 {
/** {@collect.stats}
* 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;
/** {@collect.stats}
* 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;
/** {@collect.stats}
* <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();
}
| Java |
/*
* Copyright (c) 1999, 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management;
// java import
import java.io.Serializable;
/** {@collect.stats}
* 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;
/** {@collect.stats}
* @serial Attribute name.
*/
private String name;
/** {@collect.stats}
* @serial Attribute value
*/
private Object value= null;
/** {@collect.stats}
* 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;
}
/** {@collect.stats}
* Returns a String containing the name of the attribute.
*
* @return the name of the attribute.
*/
public String getName() {
return name;
}
/** {@collect.stats}
* Returns an Object that is the value of this attribute.
*
* @return the value of the attribute.
*/
public Object getValue() {
return value;
}
/** {@collect.stats}
* 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())));
}
/** {@collect.stats}
* 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());
}
/** {@collect.stats}
* 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();
}
}
| Java |
/*
* Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management;
/** {@collect.stats}
* 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;
/** {@collect.stats}
* Default constructor.
*/
public IntrospectionException() {
super();
}
/** {@collect.stats}
* Constructor that allows a specific error message to be specified.
*
* @param message the detail message.
*/
public IntrospectionException(String message) {
super(message);
}
}
| Java |
/*
* 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;
/** {@collect.stats}
* Interface to read the Descriptor of a management interface element
* such as an MBeanInfo.
* @since 1.6
*/
public interface DescriptorRead {
/** {@collect.stats}
* 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();
}
| Java |
/*
* Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management;
/** {@collect.stats}
* 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;
/** {@collect.stats}
* @serial The description of the operation that originated this exception
*/
private String op;
/** {@collect.stats}
* Constructs a <CODE>BadStringOperationException</CODE> with the specified detail
* message.
*
* @param message the detail message.
*/
public BadStringOperationException(String message) {
this.op = message;
}
/** {@collect.stats}
* Returns the string representing the object.
*/
public String toString() {
return "BadStringOperationException: " + op;
}
}
| Java |
/*
* Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management;
/** {@collect.stats}
* This class is used by the query-building mechanism to represent binary
* relations.
* @serial include
*
* @since 1.5
*/
class BetweenQueryExp extends QueryEval implements QueryExp {
/* Serial version */
private static final long serialVersionUID = -2933597532866307444L;
/** {@collect.stats}
* @serial The checked value
*/
private ValueExp exp1;
/** {@collect.stats}
* @serial The lower bound value
*/
private ValueExp exp2;
/** {@collect.stats}
* @serial The upper bound value
*/
private ValueExp exp3;
/** {@collect.stats}
* Basic Constructor.
*/
public BetweenQueryExp() {
}
/** {@collect.stats}
* 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;
}
/** {@collect.stats}
* Returns the checked value of the query.
*/
public ValueExp getCheckedValue() {
return exp1;
}
/** {@collect.stats}
* Returns the lower bound value of the query.
*/
public ValueExp getLowerBound() {
return exp2;
}
/** {@collect.stats}
* Returns the upper bound value of the query.
*/
public ValueExp getUpperBound() {
return exp3;
}
/** {@collect.stats}
* 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);
String sval1;
String sval2;
String sval3;
double dval1;
double dval2;
double dval3;
long lval1;
long lval2;
long lval3;
boolean numeric = val1 instanceof NumericValueExp;
if (numeric) {
if (((NumericValueExp)val1).isLong()) {
lval1 = ((NumericValueExp)val1).longValue();
lval2 = ((NumericValueExp)val2).longValue();
lval3 = ((NumericValueExp)val3).longValue();
return lval2 <= lval1 && lval1 <= lval3;
} else {
dval1 = ((NumericValueExp)val1).doubleValue();
dval2 = ((NumericValueExp)val2).doubleValue();
dval3 = ((NumericValueExp)val3).doubleValue();
return dval2 <= dval1 && dval1 <= dval3;
}
} else {
sval1 = ((StringValueExp)val1).toString();
sval2 = ((StringValueExp)val2).toString();
sval3 = ((StringValueExp)val3).toString();
return sval2.compareTo(sval1) <= 0 && sval1.compareTo(sval3) <= 0;
}
}
/** {@collect.stats}
* Returns the string representing the object.
*/
public String toString() {
return "(" + exp1 + ") between (" + exp2 + ") and (" + exp3 + ")";
}
}
| Java |
/*
* Copyright (c) 1999, 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management;
// java import
import java.io.Serializable;
// RI import
import javax.management.ObjectName;
/** {@collect.stats}
* 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;
/** {@collect.stats}
* @serial Object name.
*/
private ObjectName name;
/** {@collect.stats}
* @serial Class name.
*/
private String className;
/** {@collect.stats}
* 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);
}
/** {@collect.stats}
* 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;
}
/** {@collect.stats}
* 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;
}
/** {@collect.stats}
* Returns the object name part.
*
* @return the object name.
*/
public ObjectName getObjectName() {
return name;
}
/** {@collect.stats}
* Returns the class part.
*
* @return the class name.
*/
public String getClassName() {
return className;
}
/** {@collect.stats}
* 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() + "]";
}
}
| Java |
/*
* Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management;
/** {@collect.stats}
* 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;
/** {@collect.stats}
* 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) ;
}
/** {@collect.stats}
* 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) ;
}
}
| Java |
/*
* Copyright (c) 2004, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management;
import java.io.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;
/** {@collect.stats}
* An immutable descriptor.
* @since 1.6
*/
public class ImmutableDescriptor implements Descriptor {
private static final long serialVersionUID = 8853308591080540165L;
/** {@collect.stats}
* 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;
/** {@collect.stats}
* 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;
/** {@collect.stats}
* An empty descriptor.
*/
public static final ImmutableDescriptor EMPTY_DESCRIPTOR =
new ImmutableDescriptor();
/** {@collect.stats}
* 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));
}
/** {@collect.stats}
* 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));
}
/** {@collect.stats}
* <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]);
}
/** {@collect.stats}
* 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 {
if (names.length == 0 && getClass() == ImmutableDescriptor.class)
return EMPTY_DESCRIPTOR;
boolean bad = false;
if (names == null || values == null || names.length != values.length)
bad = true;
if (!bad) {
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);
}
/** {@collect.stats}
* <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();
}
/** {@collect.stats}
* Compares this descriptor to the given object. The objects are equal if
* the given object is also a Descriptor, and if the two Descriptors have
* the same field names (possibly differing in case) and the same
* associated values. The respective values for a field in the two
* Descriptors are equal if the following conditions hold:</p>
*
* <ul>
* <li>If one value is null then the other must be too.</li>
* <li>If one value is a primitive array then the other must be a primitive
* array of the same type with the same elements.</li>
* <li>If one value is an object array then the other must be too and
* {@link Arrays#deepEquals(Object[],Object[])} must return true.</li>
* <li>Otherwise {@link Object#equals(Object)} must return true.</li>
* </ul>
*
* @param 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.
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);
}
/** {@collect.stats}
* <p>Returns the hash code value for this descriptor. The hash
* code is computed as the sum of the hash codes for each field in
* the descriptor. The hash code of a field with name {@code n}
* and value {@code v} is {@code n.toLowerCase().hashCode() ^ h}.
* Here {@code h} is the hash code of {@code v}, computed as
* follows:</p>
*
* <ul>
* <li>If {@code v} is null then {@code h} is 0.</li>
* <li>If {@code v} is a primitive array then {@code h} is computed using
* the appropriate overloading of {@code java.util.Arrays.hashCode}.</li>
* <li>If {@code v} is an object array then {@code h} is computed using
* {@link Arrays#deepHashCode(Object[])}.</li>
* <li>Otherwise {@code h} is {@code v.hashCode()}.</li>
* </ul>
*
* @return A hash code value for this object.
*
*/
// Note: this Javadoc is copied from javax.management.Descriptor
// due to 6369229.
public int hashCode() {
if (hashCode == -1) {
int hash = 0;
for (int i = 0; i < names.length; i++) {
Object v = values[i];
int h;
if (v == null)
h = 0;
else if (v instanceof Object[])
h = Arrays.deepHashCode((Object[]) v);
else if (v.getClass().isArray()) {
h = Arrays.deepHashCode(new Object[] {v}) - 31;
// hashcode of a list containing just v is
// v.hashCode() + 31, see List.hashCode()
} else
h = v.hashCode();
hash += names[i].toLowerCase().hashCode() ^ h;
}
hashCode = hash;
}
return hashCode;
}
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();
}
/** {@collect.stats}
* 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;
}
/** {@collect.stats}
* <p>Returns a descriptor which is equal to this descriptor.
* Changes to the returned descriptor will have no effect on this
* descriptor, and vice versa.</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.
*/
public Descriptor clone() {
return this;
}
/** {@collect.stats}
* 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]);
}
/** {@collect.stats}
* 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();
}
/** {@collect.stats}
* Removes a field from the descriptor.
*
* @param fieldName String name of the field to be removed.
* If the field name is illegal or the field is not found,
* no exception is thrown.
*
* @exception RuntimeOperationsException if a field of the given name
* exists and the descriptor is immutable. The wrapped exception will
* be an {@link UnsupportedOperationException}.
*/
public 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);
}
}
| Java |
/*
* Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management;
import com.sun.jmx.mbeanserver.Introspector;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
/** {@collect.stats}
* 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() {}
/** {@collect.stats}
* The name of the <a href="Descriptor.html#defaultValue">{@code
* defaultValue}</a> field.
*/
public static final String DEFAULT_VALUE_FIELD = "defaultValue";
/** {@collect.stats}
* The name of the <a href="Descriptor.html#immutableInfo">{@code
* immutableInfo}</a> field.
*/
public static final String IMMUTABLE_INFO_FIELD = "immutableInfo";
/** {@collect.stats}
* The name of the <a href="Descriptor.html#interfaceClassName">{@code
* interfaceClassName}</a> field.
*/
public static final String INTERFACE_CLASS_NAME_FIELD = "interfaceClassName";
/** {@collect.stats}
* The name of the <a href="Descriptor.html#legalValues">{@code
* legalValues}</a> field.
*/
public static final String LEGAL_VALUES_FIELD = "legalValues";
/** {@collect.stats}
* The name of the <a href="Descriptor.html#maxValue">{@code
* maxValue}</a> field.
*/
public static final String MAX_VALUE_FIELD = "maxValue";
/** {@collect.stats}
* The name of the <a href="Descriptor.html#minValue">{@code
* minValue}</a> field.
*/
public static final String MIN_VALUE_FIELD = "minValue";
/** {@collect.stats}
* The name of the <a href="Descriptor.html#mxbean">{@code
* mxbean}</a> field.
*/
public static final String MXBEAN_FIELD = "mxbean";
/** {@collect.stats}
* The name of the <a href="Descriptor.html#openType">{@code
* openType}</a> field.
*/
public static final String OPEN_TYPE_FIELD = "openType";
/** {@collect.stats}
* The name of the <a href="Descriptor.html#originalType">{@code
* originalType}</a> field.
*/
public static final String ORIGINAL_TYPE_FIELD = "originalType";
/** {@collect.stats}
* <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.
*/
public static <T> T newMBeanProxy(MBeanServerConnection connection,
ObjectName objectName,
Class<T> interfaceClass) {
return newMBeanProxy(connection, objectName, interfaceClass, false);
}
/** {@collect.stats}
* <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 notificationBroadcaster} 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 notificationBroadcaster 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.
*/
public static <T> T newMBeanProxy(MBeanServerConnection connection,
ObjectName objectName,
Class<T> interfaceClass,
boolean notificationBroadcaster) {
return MBeanServerInvocationHandler.newProxyInstance(
connection,
objectName,
interfaceClass,
notificationBroadcaster);
}
/** {@collect.stats}
* <p>Make a proxy for an MXBean in a local or remote
* MBean Server.</p>
*
* <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.
*/
public static <T> T newMXBeanProxy(MBeanServerConnection connection,
ObjectName objectName,
Class<T> interfaceClass) {
return newMXBeanProxy(connection, objectName, interfaceClass, false);
}
/** {@collect.stats}
* <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 notificationBroadcaster} 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 notificationBroadcaster 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.
*/
public static <T> T newMXBeanProxy(MBeanServerConnection connection,
ObjectName objectName,
Class<T> interfaceClass,
boolean notificationBroadcaster) {
// Check interface for MXBean compliance
//
try {
Introspector.testComplianceMXBeanInterface(interfaceClass);
} catch (NotCompliantMBeanException e) {
throw new IllegalArgumentException(e);
}
InvocationHandler handler = new MBeanServerInvocationHandler(
connection, objectName, true);
final Class[] interfaces;
if (notificationBroadcaster) {
interfaces =
new Class<?>[] {interfaceClass, NotificationEmitter.class};
} else
interfaces = new Class[] {interfaceClass};
Object proxy = Proxy.newProxyInstance(
interfaceClass.getClassLoader(),
interfaces,
handler);
return interfaceClass.cast(proxy);
}
/** {@collect.stats}
* <p>Test whether an interface is an MXBean interface.
* An interface is an MXBean interface if it is annotated
* {@link MXBean @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 an interface and
* meets the conditions described.
*
* @throws NullPointerException if {@code interfaceClass} is null.
*/
public static boolean isMXBeanInterface(Class<?> interfaceClass) {
if (!interfaceClass.isInterface())
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.
}
}
| Java |
/*
* Copyright (c) 1999, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management;
/** {@collect.stats}
* 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;
/** {@collect.stats}
* @serial The {@link ValueExp} to be found
*/
private ValueExp val;
/** {@collect.stats}
* @serial The array of {@link ValueExp} to be searched
*/
private ValueExp[] valueList;
/** {@collect.stats}
* Basic Constructor.
*/
public InQueryExp() {
}
/** {@collect.stats}
* 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;
}
/** {@collect.stats}
* Returns the checked value of the query.
*/
public ValueExp getCheckedValue() {
return val;
}
/** {@collect.stats}
* Returns the array of values of the query.
*/
public ValueExp[] getExplicitValues() {
return valueList;
}
/** {@collect.stats}
* 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 (int i = 0; i < valueList.length; i++) {
if (numeric) {
if (((NumericValueExp)valueList[i]).doubleValue() ==
((NumericValueExp)v).doubleValue()) {
return true;
}
} else {
if (((StringValueExp)valueList[i]).getValue().equals(
((StringValueExp)v).getValue())) {
return true;
}
}
}
}
return false;
}
/** {@collect.stats}
* 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();
}
}
| Java |
/*
* Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management;
/** {@collect.stats}
* Defines the management interface of an object of class MBeanServerDelegate.
*
* @since 1.5
*/
public interface MBeanServerDelegateMBean {
/** {@collect.stats}
* Returns the MBean server agent identity.
*
* @return the agent identity.
*/
public String getMBeanServerId();
/** {@collect.stats}
* Returns the full name of the JMX specification implemented
* by this product.
*
* @return the specification name.
*/
public String getSpecificationName();
/** {@collect.stats}
* Returns the version of the JMX specification implemented
* by this product.
*
* @return the specification version.
*/
public String getSpecificationVersion();
/** {@collect.stats}
* Returns the vendor of the JMX specification implemented
* by this product.
*
* @return the specification vendor.
*/
public String getSpecificationVendor();
/** {@collect.stats}
* Returns the JMX implementation name (the name of this product).
*
* @return the implementation name.
*/
public String getImplementationName();
/** {@collect.stats}
* Returns the JMX implementation version (the version of this product).
*
* @return the implementation version.
*/
public String getImplementationVersion();
/** {@collect.stats}
* Returns the JMX implementation vendor (the vendor of this product).
*
* @return the implementation vendor.
*/
public String getImplementationVendor();
}
| Java |
/*
* Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management;
/** {@collect.stats}
* The specified attribute does not exist or cannot be retrieved.
*
* @since 1.5
*/
public class AttributeNotFoundException extends OperationsException {
/* Serial version */
private static final long serialVersionUID = 6511584241791106926L;
/** {@collect.stats}
* Default constructor.
*/
public AttributeNotFoundException() {
super();
}
/** {@collect.stats}
* Constructor that allows a specific error message to be specified.
*
* @param message detail message.
*/
public AttributeNotFoundException(String message) {
super(message);
}
}
| Java |
/*
* Copyright (c) 1999, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management;
import com.sun.jmx.mbeanserver.Introspector;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Arrays;
/** {@collect.stats}
* 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];
/** {@collect.stats}
* Indicates that the operation is read-like,
* it basically returns information.
*/
public static final int INFO = 0;
/** {@collect.stats}
* Indicates that the operation is a write-like,
* and would modify the MBean in some way, typically by writing some value
* or changing a configuration.
*/
public static final int ACTION = 1;
/** {@collect.stats}
* Indicates that the operation is both read-like and write-like.
*/
public static final int ACTION_INFO = 2;
/** {@collect.stats}
* Indicates that the operation has an "unknown" nature.
*/
public static final int UNKNOWN = 3;
/** {@collect.stats}
* @serial The method's return value.
*/
private final String type;
/** {@collect.stats}
* @serial The signature of the method, that is, the class names
* of the arguments.
*/
private final MBeanParameterInfo[] signature;
/** {@collect.stats}
* @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;
/** {@collect.stats} @see MBeanInfo#arrayGettersSafe */
private final transient boolean arrayGettersSafe;
/** {@collect.stats}
* 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));
}
/** {@collect.stats}
* 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 <CODE>INFO,
* ACTION, ACTION_INFO, UNKNOWN</CODE>.
*/
public MBeanOperationInfo(String name,
String description,
MBeanParameterInfo[] signature,
String type,
int impact) {
this(name, description, signature, type, impact, (Descriptor) null);
}
/** {@collect.stats}
* 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 <CODE>INFO,
* ACTION, ACTION_INFO, UNKNOWN</CODE>.
* @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);
}
/** {@collect.stats}
* <p>Returns a shallow clone of this instance.
* The clone is obtained by simply calling <tt>super.clone()</tt>,
* thus calling the default native shallow cloning mechanism
* implemented by <tt>Object.clone()</tt>.
* No deeper cloning of any internal field is made.</p>
*
* <p>Since this class is immutable, cloning is chiefly of interest
* to subclasses.</p>
*/
public Object clone () {
try {
return super.clone() ;
} catch (CloneNotSupportedException e) {
// should not happen as this class is cloneable
return null;
}
}
/** {@collect.stats}
* Returns the type of the method's return value.
*
* @return the return type.
*/
public String getReturnType() {
return type;
}
/** {@collect.stats}
* <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();
}
/** {@collect.stats}
* 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;
}
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() +
"]";
}
/** {@collect.stats}
* 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.
*/
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof MBeanOperationInfo))
return false;
MBeanOperationInfo p = (MBeanOperationInfo) o;
return (p.getName().equals(getName()) &&
p.getReturnType().equals(getReturnType()) &&
p.getDescription().equals(getDescription()) &&
p.getImpact() == getImpact() &&
Arrays.equals(p.fastGetSignature(), fastGetSignature()) &&
p.getDescriptor().equals(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. */
public int hashCode() {
return getName().hashCode() ^ getReturnType().hashCode();
}
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;
}
}
| Java |
/*
* Copyright (c) 2002, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management;
import com.sun.jmx.mbeanserver.JmxMBeanServer;
/** {@collect.stats}
* <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 {
/** {@collect.stats}
* Public default constructor.
**/
public MBeanServerBuilder() {
}
/** {@collect.stats}
* 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();
}
/** {@collect.stats}
* 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);
}
}
| Java |
/*
* Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management;
/** {@collect.stats}
* This class is used by the query-building mechanism to represent binary
* operations.
* @serial include
*
* @since 1.5
*/
class BinaryRelQueryExp extends QueryEval implements QueryExp {
/* Serial version */
private static final long serialVersionUID = -5690656271650491000L;
/** {@collect.stats}
* @serial The operator
*/
private int relOp;
/** {@collect.stats}
* @serial The first value
*/
private ValueExp exp1;
/** {@collect.stats}
* @serial The second value
*/
private ValueExp exp2;
/** {@collect.stats}
* Basic Constructor.
*/
public BinaryRelQueryExp() {
}
/** {@collect.stats}
* 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;
}
/** {@collect.stats}
* Returns the operator of the query.
*/
public int getOperator() {
return relOp;
}
/** {@collect.stats}
* Returns the left value of the query.
*/
public ValueExp getLeftValue() {
return exp1;
}
/** {@collect.stats}
* Returns the right value of the query.
*/
public ValueExp getRightValue() {
return exp2;
}
/** {@collect.stats}
* 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);
String sval1;
String sval2;
double dval1;
double dval2;
long lval1;
long lval2;
boolean bval1;
boolean bval2;
boolean numeric = val1 instanceof NumericValueExp;
boolean bool = val1 instanceof BooleanValueExp;
if (numeric) {
if (((NumericValueExp)val1).isLong()) {
lval1 = ((NumericValueExp)val1).longValue();
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 {
dval1 = ((NumericValueExp)val1).doubleValue();
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) {
bval1 = ((BooleanValueExp)val1).getValue().booleanValue();
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 {
sval1 = ((StringValueExp)val1).getValue();
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;
}
/** {@collect.stats}
* Returns the string representing the object.
*/
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 "=";
}
}
| Java |
/*
* Copyright (c) 1999, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management;
/** {@collect.stats}
* 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;
/** {@collect.stats}
* @serial The boolean value
*/
private boolean val = false;
/** {@collect.stats} Creates a new BooleanValueExp representing the boolean literal <val>.*/
BooleanValueExp(boolean val) {
this.val = val;
}
/** {@collect.stats}Creates a new BooleanValueExp representing the Boolean object <val>.*/
BooleanValueExp(Boolean val) {
this.val = val.booleanValue();
}
/** {@collect.stats} Returns the Boolean object representing the value of the BooleanValueExp object.*/
public Boolean getValue() {
return Boolean.valueOf(val);
}
/** {@collect.stats}
* Returns the string representing the object.
*/
public String toString() {
return String.valueOf(val);
}
/** {@collect.stats}
* Applies the ValueExp on a MBean.
*
* @param name The name of the MBean on which the ValueExp will be applied.
*
* @return The <CODE>ValueExp</CODE>.
*
* @exception BadStringOperationException
* @exception BadBinaryOpValueExpException
* @exception BadAttributeValueExpException
* @exception InvalidApplicationException
*/
public ValueExp apply(ObjectName name) throws BadStringOperationException, BadBinaryOpValueExpException,
BadAttributeValueExpException, InvalidApplicationException {
return this;
}
}
| Java |
/*
* Copyright (c) 2003, 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.remote;
import java.security.Principal;
import javax.security.auth.Subject;
/** {@collect.stats}
* <p>Interface to define how remote credentials are converted into a
* JAAS Subject. This interface is used by the RMI Connector Server,
* and can be used by other connector servers.</p>
*
* <p>The user-defined authenticator instance is passed to the
* connector server in the environment map as the value of the
* attribute {@link JMXConnectorServer#AUTHENTICATOR}. For connector
* servers that use only this authentication system, if this attribute
* is not present or its value is <code>null</code> then no user
* authentication will be performed and full access to the methods
* exported by the <code>MBeanServerConnection</code> object will be
* allowed.</p>
*
* <p>If authentication is successful then an authenticated
* {@link Subject subject} filled in with its associated
* {@link Principal principals} is returned. Authorization checks
* will be then performed based on the given set of principals.</p>
*
* @since 1.5
*/
public interface JMXAuthenticator {
/** {@collect.stats}
* <p>Authenticates the <code>MBeanServerConnection</code> client
* with the given client credentials.</p>
*
* @param credentials the user-defined credentials to be passed
* into the server in order to authenticate the user before
* creating the <code>MBeanServerConnection</code>. The actual
* type of this parameter, and whether it can be null, depends on
* the connector.
*
* @return the authenticated subject containing its associated principals.
*
* @exception SecurityException if the server cannot authenticate the user
* with the provided credentials.
*/
public Subject authenticate(Object credentials);
}
| Java |
/*
* Copyright (c) 2002, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management.remote;
import java.io.IOException;
/** {@collect.stats}
* <p>Exception thrown by {@link JMXConnectorFactory} and
* {@link JMXConnectorServerFactory} when a provider exists for
* the required protocol but cannot be used for some reason.</p>
*
* @see JMXConnectorFactory#newJMXConnector
* @see JMXConnectorServerFactory#newJMXConnectorServer
* @since 1.5
*/
public class JMXProviderException extends IOException {
private static final long serialVersionUID = -3166703627550447198L;
/** {@collect.stats}
* <p>Constructs a <code>JMXProviderException</code> with no
* specified detail message.</p>
*/
public JMXProviderException() {
}
/** {@collect.stats}
* <p>Constructs a <code>JMXProviderException</code> with the
* specified detail message.</p>
*
* @param message the detail message
*/
public JMXProviderException(String message) {
super(message);
}
/** {@collect.stats}
* <p>Constructs a <code>JMXProviderException</code> with the
* specified detail message and nested exception.</p>
*
* @param message the detail message
* @param cause the nested exception
*/
public JMXProviderException(String message, Throwable cause) {
super(message);
this.cause = cause;
}
public Throwable getCause() {
return cause;
}
/** {@collect.stats}
* @serial An exception that caused this exception to be thrown.
* This field may be null.
* @see #getCause()
**/
private Throwable cause = null;
}
| Java |
/*
* Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management.remote;
/** {@collect.stats}
* <p>Implemented by objects that can have a {@code JMXServiceURL} address.
* All {@link JMXConnectorServer} objects implement this interface.
* Depending on the connector implementation, a {@link JMXConnector}
* object may implement this interface too. {@code JMXConnector}
* objects for the RMI Connector are instances of
* {@link javax.management.remote.rmi.RMIConnector RMIConnector} which
* implements this interface.</p>
*
* <p>An object implementing this interface might not have an address
* at a given moment. This is indicated by a null return value from
* {@link #getAddress()}.</p>
*
* @since 1.6
*/
public interface JMXAddressable {
/** {@collect.stats}
* <p>The address of this object.</p>
*
* @return the address of this object, or null if it
* does not have one.
*/
public JMXServiceURL getAddress();
}
| Java |
/*
* Copyright (c) 2002, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management.remote;
import com.sun.jmx.remote.util.ClassLogger;
import com.sun.jmx.remote.util.EnvHelp;
import java.io.Serializable;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.UnknownHostException;
import java.util.BitSet;
import java.util.StringTokenizer;
/** {@collect.stats}
* <p>The address of a JMX API connector server. Instances of this class
* are immutable.</p>
*
* <p>The address is an <em>Abstract Service URL</em> for SLP, as
* defined in RFC 2609 and amended by RFC 3111. It must look like
* this:</p>
*
* <blockquote>
*
* <code>service:jmx:<em>protocol</em>:<em>sap</em></code>
*
* </blockquote>
*
* <p>Here, <code><em>protocol</em></code> is the transport
* protocol to be used to connect to the connector server. It is
* a string of one or more ASCII characters, each of which is a
* letter, a digit, or one of the characters <code>+</code> or
* <code>-</code>. The first character must be a letter.
* Uppercase letters are converted into lowercase ones.</p>
*
* <p><code><em>sap</em></code> is the address at which the connector
* server is found. This address uses a subset of the syntax defined
* by RFC 2609 for IP-based protocols. It is a subset because the
* <code>user@host</code> syntax is not supported.</p>
*
* <p>The other syntaxes defined by RFC 2609 are not currently
* supported by this class.</p>
*
* <p>The supported syntax is:</p>
*
* <blockquote>
*
* <code>//<em>[host[</em>:<em>port]][url-path]</em></code>
*
* </blockquote>
*
* <p>Square brackets <code>[]</code> indicate optional parts of
* the address. Not all protocols will recognize all optional
* parts.</p>
*
* <p>The <code><em>host</em></code> is a host name, an IPv4 numeric
* host address, or an IPv6 numeric address enclosed in square
* brackets.</p>
*
* <p>The <code><em>port</em></code> is a decimal port number. 0
* means a default or anonymous port, depending on the protocol.</p>
*
* <p>The <code><em>host</em></code> and <code><em>port</em></code>
* can be omitted. The <code><em>port</em></code> cannot be supplied
* without a <code><em>host</em></code>.</p>
*
* <p>The <code><em>url-path</em></code>, if any, begins with a slash
* (<code>/</code>) or a semicolon (<code>;</code>) and continues to
* the end of the address. It can contain attributes using the
* semicolon syntax specified in RFC 2609. Those attributes are not
* parsed by this class and incorrect attribute syntax is not
* detected.</p>
*
* <p>Although it is legal according to RFC 2609 to have a
* <code><em>url-path</em></code> that begins with a semicolon, not
* all implementations of SLP allow it, so it is recommended to avoid
* that syntax.</p>
*
* <p>Case is not significant in the initial
* <code>service:jmx:<em>protocol</em></code> string or in the host
* part of the address. Depending on the protocol, case can be
* significant in the <code><em>url-path</em></code>.</p>
*
* @see <a
* href="ftp://ftp.rfc-editor.org/in-notes/rfc2609.txt">RFC 2609,
* "Service Templates and <code>Service:</code> Schemes"</a>
* @see <a
* href="ftp://ftp.rfc-editor.org/in-notes/rfc3111.txt">RFC 3111,
* "Service Location Protocol Modifications for IPv6"</a>
*
* @since 1.5
*/
public class JMXServiceURL implements Serializable {
private static final long serialVersionUID = 8173364409860779292L;
/** {@collect.stats}
* <p>Constructs a <code>JMXServiceURL</code> by parsing a Service URL
* string.</p>
*
* @param serviceURL the URL string to be parsed.
*
* @exception NullPointerException if <code>serviceURL</code> is
* null.
*
* @exception MalformedURLException if <code>serviceURL</code>
* does not conform to the syntax for an Abstract Service URL or
* if it is not a valid name for a JMX Remote API service. A
* <code>JMXServiceURL</code> must begin with the string
* <code>"service:jmx:"</code> (case-insensitive). It must not
* contain any characters that are not printable ASCII characters.
*/
public JMXServiceURL(String serviceURL) throws MalformedURLException {
final int serviceURLLength = serviceURL.length();
/* Check that there are no non-ASCII characters in the URL,
following RFC 2609. */
for (int i = 0; i < serviceURLLength; i++) {
char c = serviceURL.charAt(i);
if (c < 32 || c >= 127) {
throw new MalformedURLException("Service URL contains " +
"non-ASCII character 0x" +
Integer.toHexString(c));
}
}
// Parse the required prefix
final String requiredPrefix = "service:jmx:";
final int requiredPrefixLength = requiredPrefix.length();
if (!serviceURL.regionMatches(true, // ignore case
0, // serviceURL offset
requiredPrefix,
0, // requiredPrefix offset
requiredPrefixLength)) {
throw new MalformedURLException("Service URL must start with " +
requiredPrefix);
}
int[] ptr = new int[1];
// Parse the protocol name
final int protoStart = requiredPrefixLength;
final int protoEnd = indexOf(serviceURL, ':', protoStart);
this.protocol =
serviceURL.substring(protoStart, protoEnd).toLowerCase();
if (!serviceURL.regionMatches(protoEnd, "://", 0, 3)) {
throw new MalformedURLException("Missing \"://\" after " +
"protocol name");
}
// Parse the host name
final int hostStart = protoEnd + 3;
final int hostEnd;
if (hostStart < serviceURLLength
&& serviceURL.charAt(hostStart) == '[') {
hostEnd = serviceURL.indexOf(']', hostStart) + 1;
if (hostEnd == 0)
throw new MalformedURLException("Bad host name: [ without ]");
this.host = serviceURL.substring(hostStart + 1, hostEnd - 1);
if (!isNumericIPv6Address(this.host)) {
throw new MalformedURLException("Address inside [...] must " +
"be numeric IPv6 address");
}
} else {
hostEnd =
indexOfFirstNotInSet(serviceURL, hostNameBitSet, hostStart);
this.host = serviceURL.substring(hostStart, hostEnd);
}
// Parse the port number
final int portEnd;
if (hostEnd < serviceURLLength && serviceURL.charAt(hostEnd) == ':') {
if (this.host.length() == 0) {
throw new MalformedURLException("Cannot give port number " +
"without host name");
}
final int portStart = hostEnd + 1;
portEnd =
indexOfFirstNotInSet(serviceURL, numericBitSet, portStart);
final String portString = serviceURL.substring(portStart, portEnd);
try {
this.port = Integer.parseInt(portString);
} catch (NumberFormatException e) {
throw new MalformedURLException("Bad port number: \"" +
portString + "\": " + e);
}
} else {
portEnd = hostEnd;
this.port = 0;
}
// Parse the URL path
final int urlPathStart = portEnd;
if (urlPathStart < serviceURLLength)
this.urlPath = serviceURL.substring(urlPathStart);
else
this.urlPath = "";
validate();
}
/** {@collect.stats}
* <p>Constructs a <code>JMXServiceURL</code> with the given protocol,
* host, and port. This constructor is equivalent to
* {@link #JMXServiceURL(String, String, int, String)
* JMXServiceURL(protocol, host, port, null)}.</p>
*
* @param protocol the protocol part of the URL. If null, defaults
* to <code>jmxmp</code>.
*
* @param host the host part of the URL. If null, defaults to the
* local host name, as determined by
* <code>InetAddress.getLocalHost().getHostName()</code>. If it
* is a numeric IPv6 address, it can optionally be enclosed in
* square brackets <code>[]</code>.
*
* @param port the port part of the URL.
*
* @exception MalformedURLException if one of the parts is
* syntactically incorrect, or if <code>host</code> is null and it
* is not possible to find the local host name, or if
* <code>port</code> is negative.
*/
public JMXServiceURL(String protocol, String host, int port)
throws MalformedURLException {
this(protocol, host, port, null);
}
/** {@collect.stats}
* <p>Constructs a <code>JMXServiceURL</code> with the given parts.
*
* @param protocol the protocol part of the URL. If null, defaults
* to <code>jmxmp</code>.
*
* @param host the host part of the URL. If null, defaults to the
* local host name, as determined by
* <code>InetAddress.getLocalHost().getHostName()</code>. If it
* is a numeric IPv6 address, it can optionally be enclosed in
* square brackets <code>[]</code>.
*
* @param port the port part of the URL.
*
* @param urlPath the URL path part of the URL. If null, defaults to
* the empty string.
*
* @exception MalformedURLException if one of the parts is
* syntactically incorrect, or if <code>host</code> is null and it
* is not possible to find the local host name, or if
* <code>port</code> is negative.
*/
public JMXServiceURL(String protocol, String host, int port,
String urlPath)
throws MalformedURLException {
if (protocol == null)
protocol = "jmxmp";
if (host == null) {
InetAddress local;
try {
local = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
throw new MalformedURLException("Local host name unknown: " +
e);
}
host = local.getHostName();
/* We might have a hostname that violates DNS naming
rules, for example that contains an `_'. While we
could be strict and throw an exception, this is rather
user-hostile. Instead we use its numerical IP address.
We can only reasonably do this for the host==null case.
If we're given an explicit host name that is illegal we
have to reject it. (Bug 5057532.) */
try {
validateHost(host);
} catch (MalformedURLException e) {
if (logger.fineOn()) {
logger.fine("JMXServiceURL",
"Replacing illegal local host name " +
host + " with numeric IP address " +
"(see RFC 1034)", e);
}
host = local.getHostAddress();
/* Use the numeric address, which could be either IPv4
or IPv6. validateHost will accept either. */
}
}
if (host.startsWith("[")) {
if (!host.endsWith("]")) {
throw new MalformedURLException("Host starts with [ but " +
"does not end with ]");
}
host = host.substring(1, host.length() - 1);
if (!isNumericIPv6Address(host)) {
throw new MalformedURLException("Address inside [...] must " +
"be numeric IPv6 address");
}
if (host.startsWith("["))
throw new MalformedURLException("More than one [[...]]");
}
this.protocol = protocol.toLowerCase();
this.host = host;
this.port = port;
if (urlPath == null)
urlPath = "";
this.urlPath = urlPath;
validate();
}
private void validate() throws MalformedURLException {
// Check protocol
final int protoEnd = indexOfFirstNotInSet(protocol, protocolBitSet, 0);
if (protoEnd == 0 || protoEnd < protocol.length()
|| !alphaBitSet.get(protocol.charAt(0))) {
throw new MalformedURLException("Missing or invalid protocol " +
"name: \"" + protocol + "\"");
}
// Check host
validateHost();
// Check port
if (port < 0)
throw new MalformedURLException("Bad port: " + port);
// Check URL path
if (urlPath.length() > 0) {
if (!urlPath.startsWith("/") && !urlPath.startsWith(";"))
throw new MalformedURLException("Bad URL path: " + urlPath);
}
}
private void validateHost() throws MalformedURLException {
if (host.length() == 0) {
if (port != 0) {
throw new MalformedURLException("Cannot give port number " +
"without host name");
}
return;
}
validateHost(host);
}
private static void validateHost(String h)
throws MalformedURLException {
if (isNumericIPv6Address(h)) {
/* We assume J2SE >= 1.4 here. Otherwise you can't
use the address anyway. We can't call
InetAddress.getByName without checking for a
numeric IPv6 address, because we mustn't try to do
a DNS lookup in case the address is not actually
numeric. */
try {
InetAddress.getByName(h);
} catch (Exception e) {
/* We should really catch UnknownHostException
here, but a bug in JDK 1.4 causes it to throw
ArrayIndexOutOfBoundsException, e.g. if the
string is ":". */
MalformedURLException bad =
new MalformedURLException("Bad IPv6 address: " + h);
EnvHelp.initCause(bad, e);
throw bad;
}
} else {
/* Tiny state machine to check valid host name. This
checks the hostname grammar from RFC 1034 (DNS),
page 11. A hostname is a dot-separated list of one
or more labels, where each label consists of
letters, numbers, or hyphens. A label cannot begin
or end with a hyphen. Empty hostnames are not
allowed. Note that numeric IPv4 addresses are a
special case of this grammar.
The state is entirely captured by the last
character seen, with a virtual `.' preceding the
name. We represent any alphanumeric character by
`a'.
We need a special hack to check, as required by the
RFC 2609 (SLP) grammar, that the last component of
the hostname begins with a letter. Respecting the
intent of the RFC, we only do this if there is more
than one component. If your local hostname begins
with a digit, we don't reject it. */
final int hostLen = h.length();
char lastc = '.';
boolean sawDot = false;
char componentStart = 0;
loop:
for (int i = 0; i < hostLen; i++) {
char c = h.charAt(i);
boolean isAlphaNumeric = alphaNumericBitSet.get(c);
if (lastc == '.')
componentStart = c;
if (isAlphaNumeric)
lastc = 'a';
else if (c == '-') {
if (lastc == '.')
break; // will throw exception
lastc = '-';
} else if (c == '.') {
sawDot = true;
if (lastc != 'a')
break; // will throw exception
lastc = '.';
} else {
lastc = '.'; // will throw exception
break;
}
}
try {
if (lastc != 'a')
throw randomException;
if (sawDot && !alphaBitSet.get(componentStart)) {
/* Must be a numeric IPv4 address. In addition to
the explicitly-thrown exceptions, we can get
NoSuchElementException from the calls to
tok.nextToken and NumberFormatException from
the call to Integer.parseInt. Using exceptions
for control flow this way is a bit evil but it
does simplify things enormously. */
StringTokenizer tok = new StringTokenizer(h, ".", true);
for (int i = 0; i < 4; i++) {
String ns = tok.nextToken();
int n = Integer.parseInt(ns);
if (n < 0 || n > 255)
throw randomException;
if (i < 3 && !tok.nextToken().equals("."))
throw randomException;
}
if (tok.hasMoreTokens())
throw randomException;
}
} catch (Exception e) {
throw new MalformedURLException("Bad host: \"" + h + "\"");
}
}
}
private static final Exception randomException = new Exception();
/** {@collect.stats}
* <p>The protocol part of the Service URL.
*
* @return the protocol part of the Service URL. This is never null.
*/
public String getProtocol() {
return protocol;
}
/** {@collect.stats}
* <p>The host part of the Service URL. If the Service URL was
* constructed with the constructor that takes a URL string
* parameter, the result is the substring specifying the host in
* that URL. If the Service URL was constructed with a
* constructor that takes a separate host parameter, the result is
* the string that was specified. If that string was null, the
* result is
* <code>InetAddress.getLocalHost().getHostName()</code>.</p>
*
* <p>In either case, if the host was specified using the
* <code>[...]</code> syntax for numeric IPv6 addresses, the
* square brackets are not included in the return value here.</p>
*
* @return the host part of the Service URL. This is never null.
*/
public String getHost() {
return host;
}
/** {@collect.stats}
* <p>The port of the Service URL. If no port was
* specified, the returned value is 0.</p>
*
* @return the port of the Service URL, or 0 if none.
*/
public int getPort() {
return port;
}
/** {@collect.stats}
* <p>The URL Path part of the Service URL. This is an empty
* string, or a string beginning with a slash (<code>/</code>), or
* a string beginning with a semicolon (<code>;</code>).
*
* @return the URL Path part of the Service URL. This is never
* null.
*/
public String getURLPath() {
return urlPath;
}
/** {@collect.stats}
* <p>The string representation of this Service URL. If the value
* returned by this method is supplied to the
* <code>JMXServiceURL</code> constructor, the resultant object is
* equal to this one.</p>
*
* <p>The <code><em>host</em></code> part of the returned string
* is the value returned by {@link #getHost()}. If that value
* specifies a numeric IPv6 address, it is surrounded by square
* brackets <code>[]</code>.</p>
*
* <p>The <code><em>port</em></code> part of the returned string
* is the value returned by {@link #getPort()} in its shortest
* decimal form. If the value is zero, it is omitted.</p>
*
* @return the string representation of this Service URL.
*/
public String toString() {
/* We don't bother synchronizing the access to toString. At worst,
n threads will independently compute and store the same value. */
if (toString != null)
return toString;
StringBuilder buf = new StringBuilder("service:jmx:");
buf.append(getProtocol()).append("://");
final String getHost = getHost();
if (isNumericIPv6Address(getHost))
buf.append('[').append(getHost).append(']');
else
buf.append(getHost);
final int getPort = getPort();
if (getPort != 0)
buf.append(':').append(getPort);
buf.append(getURLPath());
toString = buf.toString();
return toString;
}
/** {@collect.stats}
* <p>Indicates whether some other object is equal to this one.
* This method returns true if and only if <code>obj</code> is an
* instance of <code>JMXServiceURL</code> whose {@link
* #getProtocol()}, {@link #getHost()}, {@link #getPort()}, and
* {@link #getURLPath()} methods return the same values as for
* this object. The values for {@link #getProtocol()} and {@link
* #getHost()} can differ in case without affecting equality.
*
* @param obj the reference object with which to compare.
*
* @return <code>true</code> if this object is the same as the
* <code>obj</code> argument; <code>false</code> otherwise.
*/
public boolean equals(Object obj) {
if (!(obj instanceof JMXServiceURL))
return false;
JMXServiceURL u = (JMXServiceURL) obj;
return
(u.getProtocol().equalsIgnoreCase(getProtocol()) &&
u.getHost().equalsIgnoreCase(getHost()) &&
u.getPort() == getPort() &&
u.getURLPath().equals(getURLPath()));
}
public int hashCode() {
return toString().hashCode();
}
/* True if this string, assumed to be a valid argument to
* InetAddress.getByName, is a numeric IPv6 address.
*/
private static boolean isNumericIPv6Address(String s) {
// address contains colon if and only if it's a numeric IPv6 address
return (s.indexOf(':') >= 0);
}
// like String.indexOf but returns string length not -1 if not present
private static int indexOf(String s, char c, int fromIndex) {
int index = s.indexOf(c, fromIndex);
if (index < 0)
return s.length();
else
return index;
}
private static int indexOfFirstNotInSet(String s, BitSet set,
int fromIndex) {
final int slen = s.length();
int i = fromIndex;
while (true) {
if (i >= slen)
break;
char c = s.charAt(i);
if (c >= 128)
break; // not ASCII
if (!set.get(c))
break;
i++;
}
return i;
}
private final static BitSet alphaBitSet = new BitSet(128);
private final static BitSet numericBitSet = new BitSet(128);
private final static BitSet alphaNumericBitSet = new BitSet(128);
private final static BitSet protocolBitSet = new BitSet(128);
private final static BitSet hostNameBitSet = new BitSet(128);
static {
/* J2SE 1.4 adds lots of handy methods to BitSet that would
allow us to simplify here, e.g. by not writing loops, but
we want to work on J2SE 1.3 too. */
for (char c = '0'; c <= '9'; c++)
numericBitSet.set(c);
for (char c = 'A'; c <= 'Z'; c++)
alphaBitSet.set(c);
for (char c = 'a'; c <= 'z'; c++)
alphaBitSet.set(c);
alphaNumericBitSet.or(alphaBitSet);
alphaNumericBitSet.or(numericBitSet);
protocolBitSet.or(alphaNumericBitSet);
protocolBitSet.set('+');
protocolBitSet.set('-');
hostNameBitSet.or(alphaNumericBitSet);
hostNameBitSet.set('-');
hostNameBitSet.set('.');
}
private static void addCharsToBitSet(BitSet set, String chars) {
for (int i = 0; i < chars.length(); i++)
set.set(chars.charAt(i));
}
/** {@collect.stats}
* The value returned by {@link #getProtocol()}.
*/
private final String protocol;
/** {@collect.stats}
* The value returned by {@link #getHost()}.
*/
private final String host;
/** {@collect.stats}
* The value returned by {@link #getPort()}.
*/
private final int port;
/** {@collect.stats}
* The value returned by {@link #getURLPath()}.
*/
private final String urlPath;
/** {@collect.stats}
* Cached result of {@link #toString()}.
*/
private transient String toString;
private static final ClassLogger logger =
new ClassLogger("javax.management.remote.misc", "JMXServiceURL");
}
| Java |
/*
* Copyright (c) 2002, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management.remote;
import java.io.IOException;
// imports for javadoc
import javax.management.MBeanServer;
/** {@collect.stats}
* Exception thrown as the result of a remote {@link MBeanServer}
* method invocation when an <code>Error</code> is thrown while
* processing the invocation in the remote MBean server. A
* <code>JMXServerErrorException</code> instance contains the original
* <code>Error</code> that occurred as its cause.
*
* @see java.rmi.ServerError
* @since 1.5
*/
public class JMXServerErrorException extends IOException {
private static final long serialVersionUID = 3996732239558744666L;
/** {@collect.stats}
* Constructs a <code>JMXServerErrorException</code> with the specified
* detail message and nested error.
*
* @param s the detail message.
* @param err the nested error. An instance of this class can be
* constructed where this parameter is null, but the standard
* connectors will never do so.
*/
public JMXServerErrorException(String s, Error err) {
super(s);
cause = err;
}
public Throwable getCause() {
return cause;
}
/** {@collect.stats}
* @serial An {@link Error} that caused this exception to be thrown.
* @see #getCause()
**/
private final Error cause;
}
| Java |
/*
* Copyright (c) 2003, 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.remote;
import com.sun.jmx.remote.util.ClassLogger;
import com.sun.jmx.remote.util.EnvHelp;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.ServiceLoader;
import javax.management.MBeanServer;
import javax.management.ObjectName;
/** {@collect.stats}
* <p>Factory to create JMX API connector servers. There
* are no instances of this class.</p>
*
* <p>Each connector server is created by an instance of {@link
* JMXConnectorServerProvider}. This instance is found as follows. Suppose
* the given {@link JMXServiceURL} looks like
* <code>"service:jmx:<em>protocol</em>:<em>remainder</em>"</code>.
* Then the factory will attempt to find the appropriate {@link
* JMXConnectorServerProvider} for <code><em>protocol</em></code>. Each
* occurrence of the character <code>+</code> or <code>-</code> in
* <code><em>protocol</em></code> is replaced by <code>.</code> or
* <code>_</code>, respectively.</p>
*
* <p>A <em>provider package list</em> is searched for as follows:</p>
*
* <ol>
*
* <li>If the <code>environment</code> parameter to {@link
* #newJMXConnectorServer(JMXServiceURL,Map,MBeanServer)
* newJMXConnectorServer} contains the key
* <code>jmx.remote.protocol.provider.pkgs</code> then the associated
* value is the provider package list.
*
* <li>Otherwise, if the system property
* <code>jmx.remote.protocol.provider.pkgs</code> exists, then its value
* is the provider package list.
*
* <li>Otherwise, there is no provider package list.
*
* </ol>
*
* <p>The provider package list is a string that is interpreted as a
* list of non-empty Java package names separated by vertical bars
* (<code>|</code>). If the string is empty, then so is the provider
* package list. If the provider package list is not a String, or if
* it contains an element that is an empty string, a {@link
* JMXProviderException} is thrown.</p>
*
* <p>If the provider package list exists and is not empty, then for
* each element <code><em>pkg</em></code> of the list, the factory
* will attempt to load the class
*
* <blockquote>
* <code><em>pkg</em>.<em>protocol</em>.ServerProvider</code>
* </blockquote>
* <p>If the <code>environment</code> parameter to {@link
* #newJMXConnectorServer(JMXServiceURL, Map, MBeanServer)
* newJMXConnectorServer} contains the key
* <code>jmx.remote.protocol.provider.class.loader</code> then the
* associated value is the class loader to use to load the provider.
* If the associated value is not an instance of {@link
* java.lang.ClassLoader}, an {@link
* java.lang.IllegalArgumentException} is thrown.</p>
*
* <p>If the <code>jmx.remote.protocol.provider.class.loader</code>
* key is not present in the <code>environment</code> parameter, the
* calling thread's context class loader is used.</p>
*
* <p>If the attempt to load this class produces a {@link
* ClassNotFoundException}, the search for a handler continues with
* the next element of the list.</p>
*
* <p>Otherwise, a problem with the provider found is signalled by a
* {@link JMXProviderException} whose {@link
* JMXProviderException#getCause() <em>cause</em>} indicates the
* underlying exception, as follows:</p>
*
* <ul>
*
* <li>if the attempt to load the class produces an exception other
* than <code>ClassNotFoundException</code>, that is the
* <em>cause</em>;
*
* <li>if {@link Class#newInstance()} for the class produces an
* exception, that is the <em>cause</em>.
*
* </ul>
*
* <p>If no provider is found by the above steps, including the
* default case where there is no provider package list, then the
* implementation will use its own provider for
* <code><em>protocol</em></code>, or it will throw a
* <code>MalformedURLException</code> if there is none. An
* implementation may choose to find providers by other means. For
* example, it may support the <a
* href="{@docRoot}/../technotes/guides/jar/jar.html#Service Provider">
* JAR conventions for service providers</a>, where the service
* interface is <code>JMXConnectorServerProvider</code>.</p>
*
* <p>Every implementation must support the RMI connector protocols,
* specified with the string <code>rmi</code> or
* <code>iiop</code>.</p>
*
* <p>Once a provider is found, the result of the
* <code>newJMXConnectorServer</code> method is the result of calling
* {@link
* JMXConnectorServerProvider#newJMXConnectorServer(JMXServiceURL,
* Map, MBeanServer) newJMXConnectorServer} on the provider.</p>
*
* <p>The <code>Map</code> parameter passed to the
* <code>JMXConnectorServerProvider</code> is a new read-only
* <code>Map</code> that contains all the entries that were in the
* <code>environment</code> parameter to {@link
* #newJMXConnectorServer(JMXServiceURL,Map,MBeanServer)
* JMXConnectorServerFactory.newJMXConnectorServer}, if there was one.
* Additionally, if the
* <code>jmx.remote.protocol.provider.class.loader</code> key is not
* present in the <code>environment</code> parameter, it is added to
* the new read-only <code>Map</code>. The associated value is the
* calling thread's context class loader.</p>
*
* @since 1.5
*/
public class JMXConnectorServerFactory {
/** {@collect.stats}
* <p>Name of the attribute that specifies the default class
* loader. This class loader is used to deserialize objects in
* requests received from the client, possibly after consulting an
* MBean-specific class loader. The value associated with this
* attribute is an instance of {@link ClassLoader}.</p>
*/
public static final String DEFAULT_CLASS_LOADER =
JMXConnectorFactory.DEFAULT_CLASS_LOADER;
/** {@collect.stats}
* <p>Name of the attribute that specifies the default class
* loader MBean name. This class loader is used to deserialize objects in
* requests received from the client, possibly after consulting an
* MBean-specific class loader. The value associated with this
* attribute is an instance of {@link ObjectName}.</p>
*/
public static final String DEFAULT_CLASS_LOADER_NAME =
"jmx.remote.default.class.loader.name";
/** {@collect.stats}
* <p>Name of the attribute that specifies the provider packages
* that are consulted when looking for the handler for a protocol.
* The value associated with this attribute is a string with
* package names separated by vertical bars (<code>|</code>).</p>
*/
public static final String PROTOCOL_PROVIDER_PACKAGES =
"jmx.remote.protocol.provider.pkgs";
/** {@collect.stats}
* <p>Name of the attribute that specifies the class
* loader for loading protocol providers.
* The value associated with this attribute is an instance
* of {@link ClassLoader}.</p>
*/
public static final String PROTOCOL_PROVIDER_CLASS_LOADER =
"jmx.remote.protocol.provider.class.loader";
private static final String PROTOCOL_PROVIDER_DEFAULT_PACKAGE =
"com.sun.jmx.remote.protocol";
private static final ClassLogger logger =
new ClassLogger("javax.management.remote.misc","JMXConnectorServerFactory");
/** {@collect.stats} There are no instances of this class. */
private JMXConnectorServerFactory() {
}
private static JMXConnectorServer
getConnectorServerAsService(ClassLoader loader,
JMXServiceURL url,
Map<String, ?> map,
MBeanServer mbs)
throws IOException {
Iterator<JMXConnectorServerProvider> providers =
JMXConnectorFactory.
getProviderIterator(JMXConnectorServerProvider.class, loader);
JMXConnectorServer connection = null;
IOException exception = null;
while (providers.hasNext()) {
try {
connection = providers.next().newJMXConnectorServer(url, map, mbs);
return connection;
} catch (JMXProviderException e) {
throw e;
} catch (Exception e) {
if (logger.traceOn())
logger.trace("getConnectorAsService",
"URL[" + url +
"] Service provider exception: " + e);
if (!(e instanceof MalformedURLException)) {
if (exception == null) {
if (exception instanceof IOException) {
exception = (IOException) e;
} else {
exception = EnvHelp.initCause(
new IOException(e.getMessage()), e);
}
}
}
continue;
}
}
if (exception == null)
return null;
else
throw exception;
}
/** {@collect.stats}
* <p>Creates a connector server at the given address. The
* resultant server is not started until its {@link
* JMXConnectorServer#start() start} method is called.</p>
*
* @param serviceURL the address of the new connector server. The
* actual address of the new connector server, as returned by its
* {@link JMXConnectorServer#getAddress() getAddress} method, will
* not necessarily be exactly the same. For example, it might
* include a port number if the original address did not.
*
* @param environment a set of attributes to control the new
* connector server's behavior. This parameter can be null.
* Keys in this map must be Strings. The appropriate type of each
* associated value depends on the attribute. The contents of
* <code>environment</code> are not changed by this call.
*
* @param mbeanServer the MBean server that this connector server
* is attached to. Null if this connector server will be attached
* to an MBean server by being registered in it.
*
* @return a <code>JMXConnectorServer</code> representing the new
* connector server. Each successful call to this method produces
* a different object.
*
* @exception NullPointerException if <code>serviceURL</code> is null.
*
* @exception IOException if the connector server cannot be made
* because of a communication problem.
*
* @exception MalformedURLException if there is no provider for the
* protocol in <code>serviceURL</code>.
*
* @exception JMXProviderException if there is a provider for the
* protocol in <code>serviceURL</code> but it cannot be used for
* some reason.
*/
public static JMXConnectorServer
newJMXConnectorServer(JMXServiceURL serviceURL,
Map<String,?> environment,
MBeanServer mbeanServer)
throws IOException {
Map<String, Object> envcopy;
if (environment == null)
envcopy = new HashMap<String, Object>();
else {
EnvHelp.checkAttributes(environment);
envcopy = new HashMap<String, Object>(environment);
}
final Class<JMXConnectorServerProvider> targetInterface =
JMXConnectorServerProvider.class;
final ClassLoader loader =
JMXConnectorFactory.resolveClassLoader(envcopy);
final String protocol = serviceURL.getProtocol();
final String providerClassName = "ServerProvider";
JMXConnectorServerProvider provider =
JMXConnectorFactory.getProvider(serviceURL,
envcopy,
providerClassName,
targetInterface,
loader);
IOException exception = null;
if (provider == null) {
// Loader is null when context class loader is set to null
// and no loader has been provided in map.
// com.sun.jmx.remote.util.Service class extracted from j2se
// provider search algorithm doesn't handle well null classloader.
if (loader != null) {
try {
JMXConnectorServer connection =
getConnectorServerAsService(loader,
serviceURL,
envcopy,
mbeanServer);
if (connection != null)
return connection;
} catch (JMXProviderException e) {
throw e;
} catch (IOException e) {
exception = e;
}
}
provider =
JMXConnectorFactory.getProvider(
protocol,
PROTOCOL_PROVIDER_DEFAULT_PACKAGE,
JMXConnectorFactory.class.getClassLoader(),
providerClassName,
targetInterface);
}
if (provider == null) {
MalformedURLException e =
new MalformedURLException("Unsupported protocol: " + protocol);
if (exception == null) {
throw e;
} else {
throw EnvHelp.initCause(e, exception);
}
}
envcopy = Collections.unmodifiableMap(envcopy);
return provider.newJMXConnectorServer(serviceURL,
envcopy,
mbeanServer);
}
}
| Java |
/*
* Copyright (c) 2002, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management.remote.rmi;
import java.io.Closeable;
import java.io.IOException;
import java.rmi.MarshalledObject;
import java.rmi.Remote;
import java.util.Set;
import javax.management.Attribute;
import javax.management.AttributeList;
import javax.management.AttributeNotFoundException;
import javax.management.InstanceAlreadyExistsException;
import javax.management.InstanceNotFoundException;
import javax.management.IntrospectionException;
import javax.management.InvalidAttributeValueException;
import javax.management.ListenerNotFoundException;
import javax.management.MBeanException;
import javax.management.MBeanInfo;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServerConnection;
import javax.management.NotCompliantMBeanException;
import javax.management.NotificationFilter;
import javax.management.ObjectInstance;
import javax.management.ObjectName;
import javax.management.QueryExp;
import javax.management.ReflectionException;
import javax.management.remote.NotificationResult;
import javax.security.auth.Subject;
/** {@collect.stats}
* <p>RMI object used to forward an MBeanServer request from a client
* to its MBeanServer implementation on the server side. There is one
* Remote object implementing this interface for each remote client
* connected to an RMI connector.</p>
*
* <p>User code does not usually refer to this interface. It is
* specified as part of the public API so that different
* implementations of that API will interoperate.</p>
*
* <p>To ensure that client parameters will be deserialized at the
* server side with the correct classloader, client parameters such as
* parameters used to invoke a method are wrapped in a {@link
* MarshalledObject}. An implementation of this interface must first
* get the appropriate class loader for the operation and its target,
* then deserialize the marshalled parameters with this classloader.
* Except as noted, a parameter that is a
* <code>MarshalledObject</code> or <code>MarshalledObject[]</code>
* must not be null; the behavior is unspecified if it is.</p>
*
* <p>Class loading aspects are detailed in the
* <a href="{@docRoot}/../technotes/guides/jmx/JMX_1_4_specification.pdf">
* JMX Specification, version 1.4</a> PDF document.</p>
*
* <p>Most methods in this interface parallel methods in the {@link
* MBeanServerConnection} interface. Where an aspect of the behavior
* of a method is not specified here, it is the same as in the
* corresponding <code>MBeanServerConnection</code> method.
*
* @since 1.5
*/
/*
* Notice that we omit the type parameter from MarshalledObject everywhere,
* even though it would add useful information to the documentation. The
* reason is that it was only added in Mustang (Java SE 6), whereas versions
* 1.4 and 2.0 of the JMX API must be implementable on Tiger per our
* commitments for JSR 255.
*/
public interface RMIConnection extends Closeable, Remote {
/** {@collect.stats}
* <p>Returns the connection ID. This string is different for
* every open connection to a given RMI connector server.</p>
*
* @return the connection ID
*
* @see RMIConnector#connect RMIConnector.connect
*
* @throws IOException if a general communication exception occurred.
*/
public String getConnectionId() throws IOException;
/** {@collect.stats}
* <p>Closes this connection. On return from this method, the RMI
* object implementing this interface is unexported, so further
* remote calls to it will fail.</p>
*
* @throws IOException if the connection could not be closed,
* or the Remote object could not be unexported, or there was a
* communication failure when transmitting the remote close
* request.
*/
public void close() throws IOException;
/** {@collect.stats}
* Handles the method {@link
* javax.management.MBeanServerConnection#createMBean(String,
* ObjectName)}.
*
* @param className The class name of the MBean to be instantiated.
* @param name The object name of the MBean. May be null.
* @param delegationSubject The <code>Subject</code> containing the
* delegation principals or <code>null</code> if the authentication
* principal is used instead.
*
* @return An <code>ObjectInstance</code>, containing the
* <code>ObjectName</code> and the Java class name of the newly
* instantiated MBean. If the contained <code>ObjectName</code>
* is <code>n</code>, the contained Java class name is
* <code>{@link #getMBeanInfo getMBeanInfo(n)}.getClassName()</code>.
*
* @throws ReflectionException Wraps a
* <code>java.lang.ClassNotFoundException</code> or a
* <code>java.lang.Exception</code> that occurred
* when trying to invoke the MBean's constructor.
* @throws InstanceAlreadyExistsException The MBean is already
* under the control of the MBean server.
* @throws MBeanRegistrationException The
* <code>preRegister</code> (<code>MBeanRegistration</code>
* interface) method of the MBean has thrown an exception. The
* MBean will not be registered.
* @throws MBeanException The constructor of the MBean has
* thrown an exception.
* @throws NotCompliantMBeanException This class is not a JMX
* compliant MBean.
* @throws RuntimeOperationsException Wraps a
* <code>java.lang.IllegalArgumentException</code>: The className
* passed in parameter is null, the <code>ObjectName</code> passed
* in parameter contains a pattern or no <code>ObjectName</code>
* is specified for the MBean.
* @throws SecurityException if the client, or the delegated Subject
* if any, does not have permission to perform this operation.
* @throws IOException if a general communication exception occurred.
*/
public ObjectInstance createMBean(String className,
ObjectName name,
Subject delegationSubject)
throws
ReflectionException,
InstanceAlreadyExistsException,
MBeanRegistrationException,
MBeanException,
NotCompliantMBeanException,
IOException;
/** {@collect.stats}
* Handles the method {@link
* javax.management.MBeanServerConnection#createMBean(String,
* ObjectName, ObjectName)}.
*
* @param className The class name of the MBean to be instantiated.
* @param name The object name of the MBean. May be null.
* @param loaderName The object name of the class loader to be used.
* @param delegationSubject The <code>Subject</code> containing the
* delegation principals or <code>null</code> if the authentication
* principal is used instead.
*
* @return An <code>ObjectInstance</code>, containing the
* <code>ObjectName</code> and the Java class name of the newly
* instantiated MBean. If the contained <code>ObjectName</code>
* is <code>n</code>, the contained Java class name is
* <code>{@link #getMBeanInfo getMBeanInfo(n)}.getClassName()</code>.
*
* @throws ReflectionException Wraps a
* <code>java.lang.ClassNotFoundException</code> or a
* <code>java.lang.Exception</code> that occurred when trying to
* invoke the MBean's constructor.
* @throws InstanceAlreadyExistsException The MBean is already
* under the control of the MBean server.
* @throws MBeanRegistrationException The
* <code>preRegister</code> (<code>MBeanRegistration</code>
* interface) method of the MBean has thrown an exception. The
* MBean will not be registered.
* @throws MBeanException The constructor of the MBean has
* thrown an exception.
* @throws NotCompliantMBeanException This class is not a JMX
* compliant MBean.
* @throws InstanceNotFoundException The specified class loader
* is not registered in the MBean server.
* @throws RuntimeOperationsException Wraps a
* <code>java.lang.IllegalArgumentException</code>: The className
* passed in parameter is null, the <code>ObjectName</code> passed
* in parameter contains a pattern or no <code>ObjectName</code>
* is specified for the MBean.
* @throws SecurityException if the client, or the delegated Subject
* if any, does not have permission to perform this operation.
* @throws IOException if a general communication exception occurred.
*/
public ObjectInstance createMBean(String className,
ObjectName name,
ObjectName loaderName,
Subject delegationSubject)
throws
ReflectionException,
InstanceAlreadyExistsException,
MBeanRegistrationException,
MBeanException,
NotCompliantMBeanException,
InstanceNotFoundException,
IOException;
/** {@collect.stats}
* Handles the method {@link
* javax.management.MBeanServerConnection#createMBean(String,
* ObjectName, Object[], String[])}. The <code>Object[]</code>
* parameter is wrapped in a <code>MarshalledObject</code>.
*
* @param className The class name of the MBean to be instantiated.
* @param name The object name of the MBean. May be null.
* @param params An array containing the parameters of the
* constructor to be invoked, encapsulated into a
* <code>MarshalledObject</code>. The encapsulated array can be
* null, equivalent to an empty array.
* @param signature An array containing the signature of the
* constructor to be invoked. Can be null, equivalent to an empty
* array.
* @param delegationSubject The <code>Subject</code> containing the
* delegation principals or <code>null</code> if the authentication
* principal is used instead.
*
* @return An <code>ObjectInstance</code>, containing the
* <code>ObjectName</code> and the Java class name of the newly
* instantiated MBean. If the contained <code>ObjectName</code>
* is <code>n</code>, the contained Java class name is
* <code>{@link #getMBeanInfo getMBeanInfo(n)}.getClassName()</code>.
*
* @throws ReflectionException Wraps a
* <code>java.lang.ClassNotFoundException</code> or a
* <code>java.lang.Exception</code> that occurred when trying to
* invoke the MBean's constructor.
* @throws InstanceAlreadyExistsException The MBean is already
* under the control of the MBean server.
* @throws MBeanRegistrationException The
* <code>preRegister</code> (<code>MBeanRegistration</code>
* interface) method of the MBean has thrown an exception. The
* MBean will not be registered.
* @throws MBeanException The constructor of the MBean has
* thrown an exception.
* @throws NotCompliantMBeanException This class is not a JMX
* compliant MBean.
* @throws RuntimeOperationsException Wraps a
* <code>java.lang.IllegalArgumentException</code>: The className
* passed in parameter is null, the <code>ObjectName</code> passed
* in parameter contains a pattern, or no <code>ObjectName</code>
* is specified for the MBean.
* @throws SecurityException if the client, or the delegated Subject
* if any, does not have permission to perform this operation.
* @throws IOException if a general communication exception occurred.
*/
public ObjectInstance createMBean(String className,
ObjectName name,
MarshalledObject params,
String signature[],
Subject delegationSubject)
throws
ReflectionException,
InstanceAlreadyExistsException,
MBeanRegistrationException,
MBeanException,
NotCompliantMBeanException,
IOException;
/** {@collect.stats}
* Handles the method {@link
* javax.management.MBeanServerConnection#createMBean(String,
* ObjectName, ObjectName, Object[], String[])}. The
* <code>Object[]</code> parameter is wrapped in a
* <code>MarshalledObject</code>.
*
* @param className The class name of the MBean to be instantiated.
* @param name The object name of the MBean. May be null.
* @param loaderName The object name of the class loader to be used.
* @param params An array containing the parameters of the
* constructor to be invoked, encapsulated into a
* <code>MarshalledObject</code>. The encapsulated array can be
* null, equivalent to an empty array.
* @param signature An array containing the signature of the
* constructor to be invoked. Can be null, equivalent to an empty
* array.
* @param delegationSubject The <code>Subject</code> containing the
* delegation principals or <code>null</code> if the authentication
* principal is used instead.
*
* @return An <code>ObjectInstance</code>, containing the
* <code>ObjectName</code> and the Java class name of the newly
* instantiated MBean. If the contained <code>ObjectName</code>
* is <code>n</code>, the contained Java class name is
* <code>{@link #getMBeanInfo getMBeanInfo(n)}.getClassName()</code>.
*
* @throws ReflectionException Wraps a
* <code>java.lang.ClassNotFoundException</code> or a
* <code>java.lang.Exception</code> that occurred when trying to
* invoke the MBean's constructor.
* @throws InstanceAlreadyExistsException The MBean is already
* under the control of the MBean server.
* @throws MBeanRegistrationException The
* <code>preRegister</code> (<code>MBeanRegistration</code>
* interface) method of the MBean has thrown an exception. The
* MBean will not be registered.
* @throws MBeanException The constructor of the MBean has
* thrown an exception.
* @throws NotCompliantMBeanException This class is not a JMX
* compliant MBean.
* @throws InstanceNotFoundException The specified class loader
* is not registered in the MBean server.
* @throws RuntimeOperationsException Wraps a
* <code>java.lang.IllegalArgumentException</code>: The className
* passed in parameter is null, the <code>ObjectName</code> passed
* in parameter contains a pattern, or no <code>ObjectName</code>
* is specified for the MBean.
* @throws SecurityException if the client, or the delegated Subject
* if any, does not have permission to perform this operation.
* @throws IOException if a general communication exception occurred.
*/
public ObjectInstance createMBean(String className,
ObjectName name,
ObjectName loaderName,
MarshalledObject params,
String signature[],
Subject delegationSubject)
throws
ReflectionException,
InstanceAlreadyExistsException,
MBeanRegistrationException,
MBeanException,
NotCompliantMBeanException,
InstanceNotFoundException,
IOException;
/** {@collect.stats}
* Handles the method
* {@link javax.management.MBeanServerConnection#unregisterMBean(ObjectName)}.
*
* @param name The object name of the MBean to be unregistered.
* @param delegationSubject The <code>Subject</code> containing the
* delegation principals or <code>null</code> if the authentication
* principal is used instead.
*
* @throws InstanceNotFoundException The MBean specified is not
* registered in the MBean server.
* @throws MBeanRegistrationException The preDeregister
* ((<code>MBeanRegistration</code> interface) method of the MBean
* has thrown an exception.
* @throws RuntimeOperationsException Wraps a
* <code>java.lang.IllegalArgumentException</code>: The object
* name in parameter is null or the MBean you are when trying to
* unregister is the {@link javax.management.MBeanServerDelegate
* MBeanServerDelegate} MBean.
* @throws SecurityException if the client, or the delegated Subject
* if any, does not have permission to perform this operation.
* @throws IOException if a general communication exception occurred.
*/
public void unregisterMBean(ObjectName name, Subject delegationSubject)
throws
InstanceNotFoundException,
MBeanRegistrationException,
IOException;
/** {@collect.stats}
* Handles the method
* {@link javax.management.MBeanServerConnection#getObjectInstance(ObjectName)}.
*
* @param name The object name of the MBean.
* @param delegationSubject The <code>Subject</code> containing the
* delegation principals or <code>null</code> if the authentication
* principal is used instead.
*
* @return The <code>ObjectInstance</code> associated with the MBean
* specified by <var>name</var>. The contained <code>ObjectName</code>
* is <code>name</code> and the contained class name is
* <code>{@link #getMBeanInfo getMBeanInfo(name)}.getClassName()</code>.
*
* @throws InstanceNotFoundException The MBean specified is not
* registered in the MBean server.
* @throws RuntimeOperationsException Wraps a
* <code>java.lang.IllegalArgumentException</code>: The object
* name in parameter is null.
* @throws SecurityException if the client, or the delegated Subject
* if any, does not have permission to perform this operation.
* @throws IOException if a general communication exception occurred.
*/
public ObjectInstance getObjectInstance(ObjectName name,
Subject delegationSubject)
throws InstanceNotFoundException, IOException;
/** {@collect.stats}
* Handles the method {@link
* javax.management.MBeanServerConnection#queryMBeans(ObjectName,
* QueryExp)}. The <code>QueryExp</code> is wrapped in a
* <code>MarshalledObject</code>.
*
* @param name The object name pattern identifying the MBeans to
* be retrieved. If null or no domain and key properties are
* specified, all the MBeans registered will be retrieved.
* @param query The query expression to be applied for selecting
* MBeans, encapsulated into a <code>MarshalledObject</code>. If
* the <code>MarshalledObject</code> encapsulates a null value no
* query expression will be applied for selecting MBeans.
* @param delegationSubject The <code>Subject</code> containing the
* delegation principals or <code>null</code> if the authentication
* principal is used instead.
*
* @return A set containing the <code>ObjectInstance</code>
* objects for the selected MBeans. If no MBean satisfies the
* query an empty list is returned.
*
* @throws SecurityException if the client, or the delegated Subject
* if any, does not have permission to perform this operation.
* @throws IOException if a general communication exception occurred.
*/
public Set<ObjectInstance>
queryMBeans(ObjectName name,
MarshalledObject query,
Subject delegationSubject)
throws IOException;
/** {@collect.stats}
* Handles the method {@link
* javax.management.MBeanServerConnection#queryNames(ObjectName,
* QueryExp)}. The <code>QueryExp</code> is wrapped in a
* <code>MarshalledObject</code>.
*
* @param name The object name pattern identifying the MBean names
* to be retrieved. If null or no domain and key properties are
* specified, the name of all registered MBeans will be retrieved.
* @param query The query expression to be applied for selecting
* MBeans, encapsulated into a <code>MarshalledObject</code>. If
* the <code>MarshalledObject</code> encapsulates a null value no
* query expression will be applied for selecting MBeans.
* @param delegationSubject The <code>Subject</code> containing the
* delegation principals or <code>null</code> if the authentication
* principal is used instead.
*
* @return A set containing the ObjectNames for the MBeans
* selected. If no MBean satisfies the query, an empty list is
* returned.
*
* @throws SecurityException if the client, or the delegated Subject
* if any, does not have permission to perform this operation.
* @throws IOException if a general communication exception occurred.
*/
public Set<ObjectName>
queryNames(ObjectName name,
MarshalledObject query,
Subject delegationSubject)
throws IOException;
/** {@collect.stats}
* Handles the method
* {@link javax.management.MBeanServerConnection#isRegistered(ObjectName)}.
*
* @param name The object name of the MBean to be checked.
* @param delegationSubject The <code>Subject</code> containing the
* delegation principals or <code>null</code> if the authentication
* principal is used instead.
*
* @return True if the MBean is already registered in the MBean
* server, false otherwise.
*
* @throws RuntimeOperationsException Wraps a
* <code>java.lang.IllegalArgumentException</code>: The object
* name in parameter is null.
* @throws SecurityException if the client, or the delegated Subject
* if any, does not have permission to perform this operation.
* @throws IOException if a general communication exception occurred.
*/
public boolean isRegistered(ObjectName name, Subject delegationSubject)
throws IOException;
/** {@collect.stats}
* Handles the method
* {@link javax.management.MBeanServerConnection#getMBeanCount()}.
*
* @param delegationSubject The <code>Subject</code> containing the
* delegation principals or <code>null</code> if the authentication
* principal is used instead.
*
* @return the number of MBeans registered.
*
* @throws SecurityException if the client, or the delegated Subject
* if any, does not have permission to perform this operation.
* @throws IOException if a general communication exception occurred.
*/
public Integer getMBeanCount(Subject delegationSubject)
throws IOException;
/** {@collect.stats}
* Handles the method {@link
* javax.management.MBeanServerConnection#getAttribute(ObjectName,
* String)}.
*
* @param name The object name of the MBean from which the
* attribute is to be retrieved.
* @param attribute A String specifying the name of the attribute
* to be retrieved.
* @param delegationSubject The <code>Subject</code> containing the
* delegation principals or <code>null</code> if the authentication
* principal is used instead.
*
* @return The value of the retrieved attribute.
*
* @throws AttributeNotFoundException The attribute specified
* is not accessible in the MBean.
* @throws MBeanException Wraps an exception thrown by the
* MBean's getter.
* @throws InstanceNotFoundException The MBean specified is not
* registered in the MBean server.
* @throws ReflectionException Wraps a
* <code>java.lang.Exception</code> thrown when trying to invoke
* the getter.
* @throws RuntimeOperationsException Wraps a
* <code>java.lang.IllegalArgumentException</code>: The object
* name in parameter is null or the attribute in parameter is
* null.
* @throws RuntimeMBeanException Wraps a runtime exception thrown
* by the MBean's getter.
* @throws SecurityException if the client, or the delegated Subject
* if any, does not have permission to perform this operation.
* @throws IOException if a general communication exception occurred.
*
* @see #setAttribute
*/
public Object getAttribute(ObjectName name,
String attribute,
Subject delegationSubject)
throws
MBeanException,
AttributeNotFoundException,
InstanceNotFoundException,
ReflectionException,
IOException;
/** {@collect.stats}
* Handles the method {@link
* javax.management.MBeanServerConnection#getAttributes(ObjectName,
* String[])}.
*
* @param name The object name of the MBean from which the
* attributes are retrieved.
* @param attributes A list of the attributes to be retrieved.
* @param delegationSubject The <code>Subject</code> containing the
* delegation principals or <code>null</code> if the authentication
* principal is used instead.
*
* @return The list of the retrieved attributes.
*
* @throws InstanceNotFoundException The MBean specified is not
* registered in the MBean server.
* @throws ReflectionException An exception occurred when
* trying to invoke the getAttributes method of a Dynamic MBean.
* @throws RuntimeOperationsException Wrap a
* <code>java.lang.IllegalArgumentException</code>: The object
* name in parameter is null or attributes in parameter is null.
* @throws SecurityException if the client, or the delegated Subject
* if any, does not have permission to perform this operation.
* @throws IOException if a general communication exception occurred.
*
* @see #setAttributes
*/
public AttributeList getAttributes(ObjectName name,
String[] attributes,
Subject delegationSubject)
throws
InstanceNotFoundException,
ReflectionException,
IOException;
/** {@collect.stats}
* Handles the method {@link
* javax.management.MBeanServerConnection#setAttribute(ObjectName,
* Attribute)}. The <code>Attribute</code> parameter is wrapped
* in a <code>MarshalledObject</code>.
*
* @param name The name of the MBean within which the attribute is
* to be set.
* @param attribute The identification of the attribute to be set
* and the value it is to be set to, encapsulated into a
* <code>MarshalledObject</code>.
* @param delegationSubject The <code>Subject</code> containing the
* delegation principals or <code>null</code> if the authentication
* principal is used instead.
*
* @throws InstanceNotFoundException The MBean specified is not
* registered in the MBean server.
* @throws AttributeNotFoundException The attribute specified
* is not accessible in the MBean.
* @throws InvalidAttributeValueException The value specified
* for the attribute is not valid.
* @throws MBeanException Wraps an exception thrown by the
* MBean's setter.
* @throws ReflectionException Wraps a
* <code>java.lang.Exception</code> thrown when trying to invoke
* the setter.
* @throws RuntimeOperationsException Wraps a
* <code>java.lang.IllegalArgumentException</code>: The object
* name in parameter is null or the attribute in parameter is
* null.
* @throws SecurityException if the client, or the delegated Subject
* if any, does not have permission to perform this operation.
* @throws IOException if a general communication exception occurred.
*
* @see #getAttribute
*/
public void setAttribute(ObjectName name,
MarshalledObject attribute,
Subject delegationSubject)
throws
InstanceNotFoundException,
AttributeNotFoundException,
InvalidAttributeValueException,
MBeanException,
ReflectionException,
IOException;
/** {@collect.stats}
* Handles the method {@link
* javax.management.MBeanServerConnection#setAttributes(ObjectName,
* AttributeList)}. The <code>AttributeList</code> parameter is
* wrapped in a <code>MarshalledObject</code>.
*
* @param name The object name of the MBean within which the
* attributes are to be set.
* @param attributes A list of attributes: The identification of
* the attributes to be set and the values they are to be set to,
* encapsulated into a <code>MarshalledObject</code>.
* @param delegationSubject The <code>Subject</code> containing the
* delegation principals or <code>null</code> if the authentication
* principal is used instead.
*
* @return The list of attributes that were set, with their new
* values.
*
* @throws InstanceNotFoundException The MBean specified is not
* registered in the MBean server.
* @throws ReflectionException An exception occurred when
* trying to invoke the getAttributes method of a Dynamic MBean.
* @throws RuntimeOperationsException Wraps a
* <code>java.lang.IllegalArgumentException</code>: The object
* name in parameter is null or attributes in parameter is null.
* @throws SecurityException if the client, or the delegated Subject
* if any, does not have permission to perform this operation.
* @throws IOException if a general communication exception occurred.
*
* @see #getAttributes
*/
public AttributeList setAttributes(ObjectName name,
MarshalledObject attributes,
Subject delegationSubject)
throws
InstanceNotFoundException,
ReflectionException,
IOException;
/** {@collect.stats}
* Handles the method {@link
* javax.management.MBeanServerConnection#invoke(ObjectName,
* String, Object[], String[])}. The <code>Object[]</code>
* parameter is wrapped in a <code>MarshalledObject</code>.
*
* @param name The object name of the MBean on which the method is
* to be invoked.
* @param operationName The name of the operation to be invoked.
* @param params An array containing the parameters to be set when
* the operation is invoked, encapsulated into a
* <code>MarshalledObject</code>. The encapsulated array can be
* null, equivalent to an empty array.
* @param signature An array containing the signature of the
* operation. The class objects will be loaded using the same
* class loader as the one used for loading the MBean on which the
* operation was invoked. Can be null, equivalent to an empty
* array.
* @param delegationSubject The <code>Subject</code> containing the
* delegation principals or <code>null</code> if the authentication
* principal is used instead.
*
* @return The object returned by the operation, which represents
* the result of invoking the operation on the MBean specified.
*
* @throws InstanceNotFoundException The MBean specified is not
* registered in the MBean server.
* @throws MBeanException Wraps an exception thrown by the
* MBean's invoked method.
* @throws ReflectionException Wraps a
* <code>java.lang.Exception</code> thrown while trying to invoke
* the method.
* @throws SecurityException if the client, or the delegated Subject
* if any, does not have permission to perform this operation.
* @throws IOException if a general communication exception occurred.
* @throws RuntimeOperationsException Wraps an {@link
* IllegalArgumentException} when <code>name</code> or
* <code>operationName</code> is null.
*/
public Object invoke(ObjectName name,
String operationName,
MarshalledObject params,
String signature[],
Subject delegationSubject)
throws
InstanceNotFoundException,
MBeanException,
ReflectionException,
IOException;
/** {@collect.stats}
* Handles the method
* {@link javax.management.MBeanServerConnection#getDefaultDomain()}.
*
* @param delegationSubject The <code>Subject</code> containing the
* delegation principals or <code>null</code> if the authentication
* principal is used instead.
*
* @return the default domain.
*
* @throws SecurityException if the client, or the delegated Subject
* if any, does not have permission to perform this operation.
* @throws IOException if a general communication exception occurred.
*/
public String getDefaultDomain(Subject delegationSubject)
throws IOException;
/** {@collect.stats}
* Handles the method
* {@link javax.management.MBeanServerConnection#getDomains()}.
*
* @param delegationSubject The <code>Subject</code> containing the
* delegation principals or <code>null</code> if the authentication
* principal is used instead.
*
* @return the list of domains.
*
* @throws SecurityException if the client, or the delegated Subject
* if any, does not have permission to perform this operation.
* @throws IOException if a general communication exception occurred.
*/
public String[] getDomains(Subject delegationSubject)
throws IOException;
/** {@collect.stats}
* Handles the method
* {@link javax.management.MBeanServerConnection#getMBeanInfo(ObjectName)}.
*
* @param name The name of the MBean to analyze
* @param delegationSubject The <code>Subject</code> containing the
* delegation principals or <code>null</code> if the authentication
* principal is used instead.
*
* @return An instance of <code>MBeanInfo</code> allowing the
* retrieval of all attributes and operations of this MBean.
*
* @throws IntrospectionException An exception occurred during
* introspection.
* @throws InstanceNotFoundException The MBean specified was
* not found.
* @throws ReflectionException An exception occurred when
* trying to invoke the getMBeanInfo of a Dynamic MBean.
* @throws SecurityException if the client, or the delegated Subject
* if any, does not have permission to perform this operation.
* @throws IOException if a general communication exception occurred.
* @throws RuntimeOperationsException Wraps a
* <code>java.lang.IllegalArgumentException</code>: The object
* name in parameter is null.
*/
public MBeanInfo getMBeanInfo(ObjectName name, Subject delegationSubject)
throws
InstanceNotFoundException,
IntrospectionException,
ReflectionException,
IOException;
/** {@collect.stats}
* Handles the method {@link
* javax.management.MBeanServerConnection#isInstanceOf(ObjectName,
* String)}.
*
* @param name The <code>ObjectName</code> of the MBean.
* @param className The name of the class.
* @param delegationSubject The <code>Subject</code> containing the
* delegation principals or <code>null</code> if the authentication
* principal is used instead.
*
* @return true if the MBean specified is an instance of the
* specified class according to the rules above, false otherwise.
*
* @throws InstanceNotFoundException The MBean specified is not
* registered in the MBean server.
* @throws SecurityException if the client, or the delegated Subject
* if any, does not have permission to perform this operation.
* @throws IOException if a general communication exception occurred.
* @throws RuntimeOperationsException Wraps a
* <code>java.lang.IllegalArgumentException</code>: The object
* name in parameter is null.
*/
public boolean isInstanceOf(ObjectName name,
String className,
Subject delegationSubject)
throws InstanceNotFoundException, IOException;
/** {@collect.stats}
* Handles the method {@link
* javax.management.MBeanServerConnection#addNotificationListener(ObjectName,
* ObjectName, NotificationFilter, Object)}. The
* <code>NotificationFilter</code> parameter is wrapped in a
* <code>MarshalledObject</code>. The <code>Object</code>
* (handback) parameter is also wrapped in a
* <code>MarshalledObject</code>.
*
* @param name The name of the MBean on which the listener should
* be added.
* @param listener The object name of the listener which will
* handle the notifications emitted by the registered MBean.
* @param filter The filter object, encapsulated into a
* <code>MarshalledObject</code>. If filter encapsulated in the
* <code>MarshalledObject</code> has a null value, no filtering
* will be performed before handling notifications.
* @param handback The context to be sent to the listener when a
* notification is emitted, encapsulated into a
* <code>MarshalledObject</code>.
* @param delegationSubject The <code>Subject</code> containing the
* delegation principals or <code>null</code> if the authentication
* principal is used instead.
*
* @throws InstanceNotFoundException The MBean name of the
* notification listener or of the notification broadcaster does
* not match any of the registered MBeans.
* @throws RuntimeOperationsException Wraps an {@link
* IllegalArgumentException}. The MBean named by
* <code>listener</code> exists but does not implement the
* {@link javax.management.NotificationListener} interface,
* or <code>name</code> or <code>listener</code> is null.
* @throws SecurityException if the client, or the delegated Subject
* if any, does not have permission to perform this operation.
* @throws IOException if a general communication exception occurred.
*
* @see #removeNotificationListener(ObjectName, ObjectName, Subject)
* @see #removeNotificationListener(ObjectName, ObjectName,
* MarshalledObject, MarshalledObject, Subject)
*/
public void addNotificationListener(ObjectName name,
ObjectName listener,
MarshalledObject filter,
MarshalledObject handback,
Subject delegationSubject)
throws InstanceNotFoundException, IOException;
/** {@collect.stats}
* Handles the method {@link
* javax.management.MBeanServerConnection#removeNotificationListener(ObjectName,
* ObjectName)}.
*
* @param name The name of the MBean on which the listener should
* be removed.
* @param listener The object name of the listener to be removed.
* @param delegationSubject The <code>Subject</code> containing the
* delegation principals or <code>null</code> if the authentication
* principal is used instead.
*
* @throws InstanceNotFoundException The MBean name provided
* does not match any of the registered MBeans.
* @throws ListenerNotFoundException The listener is not
* registered in the MBean.
* @throws SecurityException if the client, or the delegated Subject
* if any, does not have permission to perform this operation.
* @throws IOException if a general communication exception occurred.
* @throws RuntimeOperationsException Wraps an {@link
* IllegalArgumentException} when <code>name</code> or
* <code>listener</code> is null.
*
* @see #addNotificationListener
*/
public void removeNotificationListener(ObjectName name,
ObjectName listener,
Subject delegationSubject)
throws
InstanceNotFoundException,
ListenerNotFoundException,
IOException;
/** {@collect.stats}
* Handles the method {@link
* javax.management.MBeanServerConnection#removeNotificationListener(ObjectName,
* ObjectName, NotificationFilter, Object)}. The
* <code>NotificationFilter</code> parameter is wrapped in a
* <code>MarshalledObject</code>. The <code>Object</code>
* parameter is also wrapped in a <code>MarshalledObject</code>.
*
* @param name The name of the MBean on which the listener should
* be removed.
* @param listener A listener that was previously added to this
* MBean.
* @param filter The filter that was specified when the listener
* was added, encapsulated into a <code>MarshalledObject</code>.
* @param handback The handback that was specified when the
* listener was added, encapsulated into a <code>MarshalledObject</code>.
* @param delegationSubject The <code>Subject</code> containing the
* delegation principals or <code>null</code> if the authentication
* principal is used instead.
*
* @throws InstanceNotFoundException The MBean name provided
* does not match any of the registered MBeans.
* @throws ListenerNotFoundException The listener is not
* registered in the MBean, or it is not registered with the given
* filter and handback.
* @throws SecurityException if the client, or the delegated Subject
* if any, does not have permission to perform this operation.
* @throws IOException if a general communication exception occurred.
* @throws RuntimeOperationsException Wraps an {@link
* IllegalArgumentException} when <code>name</code> or
* <code>listener</code> is null.
*
* @see #addNotificationListener
*/
public void removeNotificationListener(ObjectName name,
ObjectName listener,
MarshalledObject filter,
MarshalledObject handback,
Subject delegationSubject)
throws
InstanceNotFoundException,
ListenerNotFoundException,
IOException;
// Special Handling of Notifications -------------------------------------
/** {@collect.stats}
* <p>Handles the method {@link
* javax.management.MBeanServerConnection#addNotificationListener(ObjectName,
* NotificationListener, NotificationFilter, Object)}.</p>
*
* <p>Register for notifications from the given MBeans that match
* the given filters. The remote client can subsequently retrieve
* the notifications using the {@link #fetchNotifications
* fetchNotifications} method.</p>
*
* <p>For each listener, the original
* <code>NotificationListener</code> and <code>handback</code> are
* kept on the client side; in order for the client to be able to
* identify them, the server generates and returns a unique
* <code>listenerID</code>. This <code>listenerID</code> is
* forwarded with the <code>Notifications</code> to the remote
* client.</p>
*
* <p>If any one of the given (name, filter) pairs cannot be
* registered, then the operation fails with an exception, and no
* names or filters are registered.</p>
*
* @param names the <code>ObjectNames</code> identifying the
* MBeans emitting the Notifications.
* @param filters an array of marshalled representations of the
* <code>NotificationFilters</code>. Elements of this array can
* be null.
* @param delegationSubjects the <code>Subjects</code> on behalf
* of which the listeners are being added. Elements of this array
* can be null. Also, the <code>delegationSubjects</code>
* parameter itself can be null, which is equivalent to an array
* of null values with the same size as the <code>names</code> and
* <code>filters</code> arrays.
*
* @return an array of <code>listenerIDs</code> identifying the
* local listeners. This array has the same number of elements as
* the parameters.
*
* @throws IllegalArgumentException if <code>names</code> or
* <code>filters</code> is null, or if <code>names</code> contains
* a null element, or if the three arrays do not all have the same
* size.
* @throws ClassCastException if one of the elements of
* <code>filters</code> unmarshalls as a non-null object that is
* not a <code>NotificationFilter</code>.
* @throws InstanceNotFoundException if one of the
* <code>names</code> does not correspond to any registered MBean.
* @throws SecurityException if, for one of the MBeans, the
* client, or the delegated Subject if any, does not have
* permission to add a listener.
* @throws IOException if a general communication exception occurred.
*/
public Integer[] addNotificationListeners(ObjectName[] names,
MarshalledObject[] filters,
Subject[] delegationSubjects)
throws InstanceNotFoundException, IOException;
/** {@collect.stats}
* <p>Handles the
* {@link javax.management.MBeanServerConnection#removeNotificationListener(ObjectName,NotificationListener)
* removeNotificationListener(ObjectName, NotificationListener)} and
* {@link javax.management.MBeanServerConnection#removeNotificationListener(ObjectName,NotificationListener,NotificationFilter,Object)
* removeNotificationListener(ObjectName, NotificationListener, NotificationFilter, Object)} methods.</p>
*
* <p>This method removes one or more
* <code>NotificationListener</code>s from a given MBean in the
* MBean server.</p>
*
* <p>The <code>NotificationListeners</code> are identified by the
* IDs which were returned by the {@link
* #addNotificationListeners(ObjectName[], MarshalledObject[],
* Subject[])} method.</p>
*
* @param name the <code>ObjectName</code> identifying the MBean
* emitting the Notifications.
* @param listenerIDs the list of the IDs corresponding to the
* listeners to remove.
* @param delegationSubject The <code>Subject</code> containing the
* delegation principals or <code>null</code> if the authentication
* principal is used instead.
*
* @throws InstanceNotFoundException if the given
* <code>name</code> does not correspond to any registered MBean.
* @throws ListenerNotFoundException if one of the listeners was
* not found on the server side. This exception can happen if the
* MBean discarded a listener for some reason other than a call to
* <code>MBeanServer.removeNotificationListener</code>.
* @throws SecurityException if the client, or the delegated Subject
* if any, does not have permission to remove the listeners.
* @throws IOException if a general communication exception occurred.
* @throws IllegalArgumentException if <code>ObjectName</code> or
* <code>listenerIds</code> is null or if <code>listenerIds</code>
* contains a null element.
*/
public void removeNotificationListeners(ObjectName name,
Integer[] listenerIDs,
Subject delegationSubject)
throws
InstanceNotFoundException,
ListenerNotFoundException,
IOException;
/** {@collect.stats}
* <p>Retrieves notifications from the connector server. This
* method can block until there is at least one notification or
* until the specified timeout is reached. The method can also
* return at any time with zero notifications.</p>
*
* <p>A notification can be included in the result if its sequence
* number is no less than <code>clientSequenceNumber</code> and
* this client has registered at least one listener for the MBean
* generating the notification, with a filter that accepts the
* notification. Each listener that is interested in the
* notification is identified by an Integer ID that was returned
* by {@link #addNotificationListeners(ObjectName[],
* MarshalledObject[], Subject[])}.</p>
*
* @param clientSequenceNumber the first sequence number that the
* client is interested in. If negative, it is interpreted as
* meaning the sequence number that the next notification will
* have.
*
* @param maxNotifications the maximum number of different
* notifications to return. The <code>TargetedNotification</code>
* array in the returned <code>NotificationResult</code> can have
* more elements than this if the same notification appears more
* than once. The behavior is unspecified if this parameter is
* negative.
*
* @param timeout the maximum time in milliseconds to wait for a
* notification to arrive. This can be 0 to indicate that the
* method should not wait if there are no notifications, but
* should return at once. It can be <code>Long.MAX_VALUE</code>
* to indicate that there is no timeout. The behavior is
* unspecified if this parameter is negative.
*
* @return A <code>NotificationResult</code>.
*
* @throws IOException if a general communication exception occurred.
*/
public NotificationResult fetchNotifications(long clientSequenceNumber,
int maxNotifications,
long timeout)
throws IOException;
}
| Java |
/*
* Copyright (c) 2003, 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.remote.rmi;
import java.io.IOException;
import java.rmi.Remote;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.Map;
import java.util.Collections;
import javax.rmi.PortableRemoteObject;
import javax.security.auth.Subject;
/** {@collect.stats}
* <p>An {@link RMIServerImpl} that is exported through IIOP and that
* creates client connections as RMI objects exported through IIOP.
* User code does not usually reference this class directly.</p>
*
* @see RMIServerImpl
*
* @since 1.5
*/
public class RMIIIOPServerImpl extends RMIServerImpl {
/** {@collect.stats}
* <p>Creates a new {@link RMIServerImpl}.</p>
*
* @param env the environment containing attributes for the new
* <code>RMIServerImpl</code>. Can be null, which is equivalent
* to an empty Map.
*
* @exception IOException if the RMI object cannot be created.
*/
public RMIIIOPServerImpl(Map<String,?> env)
throws IOException {
super(env);
this.env = (env == null) ? Collections.<String, Object>emptyMap() : env;
callerACC = AccessController.getContext();
}
protected void export() throws IOException {
PortableRemoteObject.exportObject(this);
}
protected String getProtocol() {
return "iiop";
}
/** {@collect.stats}
* <p>Returns an IIOP stub.</p>
* The stub might not yet be connected to the ORB. The stub will
* be serializable only if it is connected to the ORB.
* @return an IIOP stub.
* @exception IOException if the stub cannot be created - e.g the
* RMIIIOPServerImpl has not been exported yet.
**/
public Remote toStub() throws IOException {
// javax.rmi.CORBA.Stub stub =
// (javax.rmi.CORBA.Stub) PortableRemoteObject.toStub(this);
final Remote stub = PortableRemoteObject.toStub(this);
// java.lang.System.out.println("NON CONNECTED STUB " + stub);
// org.omg.CORBA.ORB orb =
// org.omg.CORBA.ORB.init((String[])null, (Properties)null);
// stub.connect(orb);
// java.lang.System.out.println("CONNECTED STUB " + stub);
return stub;
}
/** {@collect.stats}
* <p>Creates a new client connection as an RMI object exported
* through IIOP.
*
* @param connectionId the ID of the new connection. Every
* connection opened by this connector server will have a
* different ID. The behavior is unspecified if this parameter is
* null.
*
* @param subject the authenticated subject. Can be null.
*
* @return the newly-created <code>RMIConnection</code>.
*
* @exception IOException if the new client object cannot be
* created or exported.
*/
protected RMIConnection makeClient(String connectionId, Subject subject)
throws IOException {
if (connectionId == null)
throw new NullPointerException("Null connectionId");
RMIConnection client =
new RMIConnectionImpl(this, connectionId, getDefaultClassLoader(),
subject, env);
PortableRemoteObject.exportObject(client);
return client;
}
protected void closeClient(RMIConnection client) throws IOException {
PortableRemoteObject.unexportObject(client);
}
/** {@collect.stats}
* <p>Called by {@link #close()} to close the connector server by
* unexporting this object. After returning from this method, the
* connector server must not accept any new connections.</p>
*
* @exception IOException if the attempt to close the connector
* server failed.
*/
protected void closeServer() throws IOException {
PortableRemoteObject.unexportObject(this);
}
@Override
RMIConnection doNewClient(final Object credentials) throws IOException {
if (callerACC == null) {
throw new SecurityException("AccessControlContext cannot be null");
}
try {
return AccessController.doPrivileged(
new PrivilegedExceptionAction<RMIConnection>() {
public RMIConnection run() throws IOException {
return superDoNewClient(credentials);
}
}, callerACC);
} catch (PrivilegedActionException pae) {
throw (IOException) pae.getCause();
}
}
RMIConnection superDoNewClient(Object credentials) throws IOException {
return super.doNewClient(credentials);
}
private final Map<String, ?> env;
private final AccessControlContext callerACC;
}
| Java |
/*
* Copyright (c) 2002, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management.remote.rmi;
import com.sun.jmx.remote.internal.ArrayNotificationBuffer;
import com.sun.jmx.remote.internal.NotificationBuffer;
import com.sun.jmx.remote.security.JMXPluggableAuthenticator;
import com.sun.jmx.remote.util.ClassLogger;
import java.io.Closeable;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.rmi.Remote;
import java.rmi.server.RemoteServer;
import java.rmi.server.ServerNotActiveException;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.management.MBeanServer;
import javax.management.remote.JMXAuthenticator;
import javax.management.remote.JMXConnectorServer;
import javax.security.auth.Subject;
/** {@collect.stats}
* <p>An RMI object representing a connector server. Remote clients
* can make connections using the {@link #newClient(Object)} method. This
* method returns an RMI object representing the connection.</p>
*
* <p>User code does not usually reference this class directly.
* RMI connection servers are usually created with the class {@link
* RMIConnectorServer}. Remote clients usually create connections
* either with {@link javax.management.remote.JMXConnectorFactory}
* or by instantiating {@link RMIConnector}.</p>
*
* <p>This is an abstract class. Concrete subclasses define the
* details of the client connection objects, such as whether they use
* JRMP or IIOP.</p>
*
* @since 1.5
*/
public abstract class RMIServerImpl implements Closeable, RMIServer {
/** {@collect.stats}
* <p>Constructs a new <code>RMIServerImpl</code>.</p>
*
* @param env the environment containing attributes for the new
* <code>RMIServerImpl</code>. Can be null, which is equivalent
* to an empty Map.
*/
public RMIServerImpl(Map<String,?> env) {
this.env = (env == null) ? Collections.EMPTY_MAP : env;
}
void setRMIConnectorServer(RMIConnectorServer connServer)
throws IOException {
this.connServer = connServer;
}
/** {@collect.stats}
* <p>Exports this RMI object.</p>
*
* @exception IOException if this RMI object cannot be exported.
*/
protected abstract void export() throws IOException;
/** {@collect.stats}
* Returns a remotable stub for this server object.
* @return a remotable stub.
* @exception IOException if the stub cannot be obtained - e.g the
* RMIServerImpl has not been exported yet.
**/
public abstract Remote toStub() throws IOException;
/** {@collect.stats}
* <p>Sets the default <code>ClassLoader</code> for this connector
* server. New client connections will use this classloader.
* Existing client connections are unaffected.</p>
*
* @param cl the new <code>ClassLoader</code> to be used by this
* connector server.
*
* @see #getDefaultClassLoader
*/
public synchronized void setDefaultClassLoader(ClassLoader cl) {
this.cl = cl;
}
/** {@collect.stats}
* <p>Gets the default <code>ClassLoader</code> used by this connector
* server.</p>
*
* @return the default <code>ClassLoader</code> used by this
* connector server.</p>
*
* @see #setDefaultClassLoader
*/
public synchronized ClassLoader getDefaultClassLoader() {
return cl;
}
/** {@collect.stats}
* <p>Sets the <code>MBeanServer</code> to which this connector
* server is attached. New client connections will interact
* with this <code>MBeanServer</code>. Existing client connections are
* unaffected.</p>
*
* @param mbs the new <code>MBeanServer</code>. Can be null, but
* new client connections will be refused as long as it is.
*
* @see #getMBeanServer
*/
public synchronized void setMBeanServer(MBeanServer mbs) {
this.mbeanServer = mbs;
}
/** {@collect.stats}
* <p>The <code>MBeanServer</code> to which this connector server
* is attached. This is the last value passed to {@link
* #setMBeanServer} on this object, or null if that method has
* never been called.</p>
*
* @return the <code>MBeanServer</code> to which this connector
* is attached.
*
* @see #setMBeanServer
*/
public synchronized MBeanServer getMBeanServer() {
return mbeanServer;
}
public String getVersion() {
// Expected format is: "protocol-version implementation-name"
try {
return "1.0 java_runtime_" +
System.getProperty("java.runtime.version");
} catch (SecurityException e) {
return "1.0 ";
}
}
/** {@collect.stats}
* <p>Creates a new client connection. This method calls {@link
* #makeClient makeClient} and adds the returned client connection
* object to an internal list. When this
* <code>RMIServerImpl</code> is shut down via its {@link
* #close()} method, the {@link RMIConnection#close() close()}
* method of each object remaining in the list is called.</p>
*
* <p>The fact that a client connection object is in this internal
* list does not prevent it from being garbage collected.</p>
*
* @param credentials this object specifies the user-defined
* credentials to be passed in to the server in order to
* authenticate the caller before creating the
* <code>RMIConnection</code>. Can be null.
*
* @return the newly-created <code>RMIConnection</code>. This is
* usually the object created by <code>makeClient</code>, though
* an implementation may choose to wrap that object in another
* object implementing <code>RMIConnection</code>.
*
* @exception IOException if the new client object cannot be
* created or exported.
*
* @exception SecurityException if the given credentials do not allow
* the server to authenticate the user successfully.
*
* @exception IllegalStateException if {@link #getMBeanServer()}
* is null.
*/
public RMIConnection newClient(Object credentials) throws IOException {
return doNewClient(credentials);
}
/** {@collect.stats}
* This method could be overridden by subclasses defined in this package
* to perform additional operations specific to the underlying transport
* before creating the new client connection.
*/
RMIConnection doNewClient(Object credentials) throws IOException {
final boolean tracing = logger.traceOn();
if (tracing) logger.trace("newClient","making new client");
if (getMBeanServer() == null)
throw new IllegalStateException("Not attached to an MBean server");
Subject subject = null;
JMXAuthenticator authenticator =
(JMXAuthenticator) env.get(JMXConnectorServer.AUTHENTICATOR);
if (authenticator == null) {
/*
* Create the JAAS-based authenticator only if authentication
* has been enabled
*/
if (env.get("jmx.remote.x.password.file") != null ||
env.get("jmx.remote.x.login.config") != null) {
authenticator = new JMXPluggableAuthenticator(env);
}
}
if (authenticator != null) {
if (tracing) logger.trace("newClient","got authenticator: " +
authenticator.getClass().getName());
try {
subject = authenticator.authenticate(credentials);
} catch (SecurityException e) {
logger.trace("newClient", "Authentication failed: " + e);
throw e;
}
}
if (tracing) {
if (subject != null)
logger.trace("newClient","subject is not null");
else logger.trace("newClient","no subject");
}
final String connectionId = makeConnectionId(getProtocol(), subject);
if (tracing)
logger.trace("newClient","making new connection: " + connectionId);
RMIConnection client = makeClient(connectionId, subject);
connServer.connectionOpened(connectionId, "Connection opened", null);
dropDeadReferences();
WeakReference<RMIConnection> wr = new WeakReference<RMIConnection>(client);
synchronized (clientList) {
clientList.add(wr);
}
if (tracing)
logger.trace("newClient","new connection done: " + connectionId );
return client;
}
/** {@collect.stats}
* <p>Creates a new client connection. This method is called by
* the public method {@link #newClient(Object)}.</p>
*
* @param connectionId the ID of the new connection. Every
* connection opened by this connector server will have a
* different ID. The behavior is unspecified if this parameter is
* null.
*
* @param subject the authenticated subject. Can be null.
*
* @return the newly-created <code>RMIConnection</code>.
*
* @exception IOException if the new client object cannot be
* created or exported.
*/
protected abstract RMIConnection makeClient(String connectionId,
Subject subject)
throws IOException;
/** {@collect.stats}
* <p>Closes a client connection made by {@link #makeClient makeClient}.
*
* @param client a connection previously returned by
* <code>makeClient</code> on which the <code>closeClient</code>
* method has not previously been called. The behavior is
* unspecified if these conditions are violated, including the
* case where <code>client</code> is null.
*
* @exception IOException if the client connection cannot be
* closed.
*/
protected abstract void closeClient(RMIConnection client)
throws IOException;
/** {@collect.stats}
* <p>Returns the protocol string for this object. The string is
* <code>rmi</code> for RMI/JRMP and <code>iiop</code> for RMI/IIOP.
*
* @return the protocol string for this object.
*/
protected abstract String getProtocol();
/** {@collect.stats}
* <p>Method called when a client connection created by {@link
* #makeClient makeClient} is closed. A subclass that defines
* <code>makeClient</code> must arrange for this method to be
* called when the resultant object's {@link RMIConnection#close()
* close} method is called. This enables it to be removed from
* the <code>RMIServerImpl</code>'s list of connections. It is
* not an error for <code>client</code> not to be in that
* list.</p>
*
* <p>After removing <code>client</code> from the list of
* connections, this method calls {@link #closeClient
* closeClient(client)}.</p>
*
* @param client the client connection that has been closed.
*
* @exception IOException if {@link #closeClient} throws this
* exception.
*
* @exception NullPointerException if <code>client</code> is null.
*/
protected void clientClosed(RMIConnection client) throws IOException {
final boolean debug = logger.debugOn();
if (debug) logger.trace("clientClosed","client="+client);
if (client == null)
throw new NullPointerException("Null client");
synchronized (clientList) {
dropDeadReferences();
for (Iterator it = clientList.iterator(); it.hasNext(); ) {
WeakReference wr = (WeakReference) it.next();
if (wr.get() == client) {
it.remove();
break;
}
}
/* It is not a bug for this loop not to find the client. In
our close() method, we remove a client from the list before
calling its close() method. */
}
if (debug) logger.trace("clientClosed", "closing client.");
closeClient(client);
if (debug) logger.trace("clientClosed", "sending notif");
connServer.connectionClosed(client.getConnectionId(),
"Client connection closed", null);
if (debug) logger.trace("clientClosed","done");
}
/** {@collect.stats}
* <p>Closes this connection server. This method first calls the
* {@link #closeServer()} method so that no new client connections
* will be accepted. Then, for each remaining {@link
* RMIConnection} object returned by {@link #makeClient
* makeClient}, its {@link RMIConnection#close() close} method is
* called.</p>
*
* <p>The behavior when this method is called more than once is
* unspecified.</p>
*
* <p>If {@link #closeServer()} throws an
* <code>IOException</code>, the individual connections are
* nevertheless closed, and then the <code>IOException</code> is
* thrown from this method.</p>
*
* <p>If {@link #closeServer()} returns normally but one or more
* of the individual connections throws an
* <code>IOException</code>, then, after closing all the
* connections, one of those <code>IOException</code>s is thrown
* from this method. If more than one connection throws an
* <code>IOException</code>, it is unspecified which one is thrown
* from this method.</p>
*
* @exception IOException if {@link #closeServer()} or one of the
* {@link RMIConnection#close()} calls threw
* <code>IOException</code>.
*/
public synchronized void close() throws IOException {
final boolean tracing = logger.traceOn();
final boolean debug = logger.debugOn();
if (tracing) logger.trace("close","closing");
IOException ioException = null;
try {
if (debug) logger.debug("close","closing Server");
closeServer();
} catch (IOException e) {
if (tracing) logger.trace("close","Failed to close server: " + e);
if (debug) logger.debug("close",e);
ioException = e;
}
if (debug) logger.debug("close","closing Clients");
// Loop to close all clients
while (true) {
synchronized (clientList) {
if (debug) logger.debug("close","droping dead references");
dropDeadReferences();
if (debug) logger.debug("close","client count: "+clientList.size());
if (clientList.size() == 0)
break;
/* Loop until we find a non-null client. Because we called
dropDeadReferences(), this will usually be the first
element of the list, but a garbage collection could have
happened in between. */
for (Iterator it = clientList.iterator(); it.hasNext(); ) {
WeakReference wr = (WeakReference) it.next();
RMIConnection client = (RMIConnection) wr.get();
it.remove();
if (client != null) {
try {
client.close();
} catch (IOException e) {
if (tracing)
logger.trace("close","Failed to close client: " + e);
if (debug) logger.debug("close",e);
if (ioException == null)
ioException = e;
}
break;
}
}
}
}
if(notifBuffer != null)
notifBuffer.dispose();
if (ioException != null) {
if (tracing) logger.trace("close","close failed.");
throw ioException;
}
if (tracing) logger.trace("close","closed.");
}
/** {@collect.stats}
* <p>Called by {@link #close()} to close the connector server.
* After returning from this method, the connector server must
* not accept any new connections.</p>
*
* @exception IOException if the attempt to close the connector
* server failed.
*/
protected abstract void closeServer() throws IOException;
private static synchronized String makeConnectionId(String protocol,
Subject subject) {
connectionIdNumber++;
String clientHost = "";
try {
clientHost = RemoteServer.getClientHost();
} catch (ServerNotActiveException e) {
logger.trace("makeConnectionId", "getClientHost", e);
}
final StringBuilder buf = new StringBuilder();
buf.append(protocol).append(":");
if (clientHost.length() > 0)
buf.append("//").append(clientHost);
buf.append(" ");
if (subject != null) {
Set principals = subject.getPrincipals();
String sep = "";
for (Iterator it = principals.iterator(); it.hasNext(); ) {
Principal p = (Principal) it.next();
String name = p.getName().replace(' ', '_').replace(';', ':');
buf.append(sep).append(name);
sep = ";";
}
}
buf.append(" ").append(connectionIdNumber);
if (logger.traceOn())
logger.trace("newConnectionId","connectionId="+buf);
return buf.toString();
}
private void dropDeadReferences() {
synchronized (clientList) {
for (Iterator it = clientList.iterator(); it.hasNext(); ) {
WeakReference wr = (WeakReference) it.next();
if (wr.get() == null)
it.remove();
}
}
}
synchronized NotificationBuffer getNotifBuffer() {
//Notification buffer is lazily created when the first client connects
if(notifBuffer == null)
notifBuffer =
ArrayNotificationBuffer.getNotificationBuffer(mbeanServer,
env);
return notifBuffer;
}
private static final ClassLogger logger =
new ClassLogger("javax.management.remote.rmi", "RMIServerImpl");
/** {@collect.stats} List of WeakReference values. Each one references an
RMIConnection created by this object, or null if the
RMIConnection has been garbage-collected. */
private final List<WeakReference<RMIConnection>> clientList =
new ArrayList<WeakReference<RMIConnection>>();
private ClassLoader cl;
private MBeanServer mbeanServer;
private final Map env;
private RMIConnectorServer connServer;
private static int connectionIdNumber;
private NotificationBuffer notifBuffer;
}
| Java |
/*
* Copyright (c) 2002, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management.remote.rmi;
import com.sun.jmx.remote.internal.ClientCommunicatorAdmin;
import com.sun.jmx.remote.internal.ClientListenerInfo;
import com.sun.jmx.remote.internal.ClientNotifForwarder;
import com.sun.jmx.remote.internal.ProxyInputStream;
import com.sun.jmx.remote.internal.ProxyRef;
import com.sun.jmx.remote.util.ClassLogger;
import com.sun.jmx.remote.util.EnvHelp;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InvalidObjectException;
import java.io.NotSerializableException;
import java.io.ObjectInputStream;
import java.io.ObjectStreamClass;
import java.io.Serializable;
import java.io.WriteAbortedException;
import java.lang.ref.WeakReference;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Proxy;
import java.net.MalformedURLException;
import java.rmi.MarshalException;
import java.rmi.MarshalledObject;
import java.rmi.NoSuchObjectException;
import java.rmi.Remote;
import java.rmi.ServerException;
import java.rmi.UnmarshalException;
import java.rmi.server.RMIClientSocketFactory;
import java.rmi.server.RemoteObject;
import java.rmi.server.RemoteObjectInvocationHandler;
import java.rmi.server.RemoteRef;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.PrivilegedExceptionAction;
import java.security.ProtectionDomain;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.WeakHashMap;
import javax.management.Attribute;
import javax.management.AttributeList;
import javax.management.AttributeNotFoundException;
import javax.management.InstanceAlreadyExistsException;
import javax.management.InstanceNotFoundException;
import javax.management.IntrospectionException;
import javax.management.InvalidAttributeValueException;
import javax.management.ListenerNotFoundException;
import javax.management.MBeanException;
import javax.management.MBeanInfo;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServerConnection;
import javax.management.MBeanServerDelegate;
import javax.management.MBeanServerNotification;
import javax.management.NotCompliantMBeanException;
import javax.management.Notification;
import javax.management.NotificationBroadcasterSupport;
import javax.management.NotificationFilter;
import javax.management.NotificationFilterSupport;
import javax.management.NotificationListener;
import javax.management.ObjectInstance;
import javax.management.ObjectName;
import javax.management.QueryExp;
import javax.management.ReflectionException;
import javax.management.remote.JMXConnectionNotification;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import javax.management.remote.NotificationResult;
import javax.management.remote.JMXAddressable;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.rmi.CORBA.Stub;
import javax.rmi.PortableRemoteObject;
import javax.rmi.ssl.SslRMIClientSocketFactory;
import javax.security.auth.Subject;
import org.omg.CORBA.BAD_OPERATION;
import org.omg.CORBA.ORB;
import sun.rmi.server.UnicastRef2;
import sun.rmi.transport.LiveRef;
/** {@collect.stats}
* <p>A connection to a remote RMI connector. Usually, such
* connections are made using {@link
* javax.management.remote.JMXConnectorFactory JMXConnectorFactory}.
* However, specialized applications can use this class directly, for
* example with an {@link RMIServer} stub obtained without going
* through JNDI.</p>
*
* @since 1.5
*/
public class RMIConnector implements JMXConnector, Serializable, JMXAddressable {
private static final ClassLogger logger =
new ClassLogger("javax.management.remote.rmi", "RMIConnector");
private static final long serialVersionUID = 817323035842634473L;
private RMIConnector(RMIServer rmiServer, JMXServiceURL address,
Map<String, ?> environment) {
if (rmiServer == null && address == null) throw new
IllegalArgumentException("rmiServer and jmxServiceURL both null");
initTransients();
this.rmiServer = rmiServer;
this.jmxServiceURL = address;
if (environment == null) {
this.env = Collections.emptyMap();
} else {
EnvHelp.checkAttributes(environment);
this.env = Collections.unmodifiableMap(environment);
}
}
/** {@collect.stats}
* <p>Constructs an <code>RMIConnector</code> that will connect
* the RMI connector server with the given address.</p>
*
* <p>The address can refer directly to the connector server,
* using one of the following syntaxes:</p>
*
* <pre>
* service:jmx:rmi://<em>[host[:port]]</em>/stub/<em>encoded-stub</em>
* service:jmx:iiop://<em>[host[:port]]</em>/ior/<em>encoded-IOR</em>
* </pre>
*
* <p>(Here, the square brackets <code>[]</code> are not part of the
* address but indicate that the host and port are optional.)</p>
*
* <p>The address can instead indicate where to find an RMI stub
* through JNDI, using one of the following syntaxes:</p>
*
* <pre>
* service:jmx:rmi://<em>[host[:port]]</em>/jndi/<em>jndi-name</em>
* service:jmx:iiop://<em>[host[:port]]</em>/jndi/<em>jndi-name</em>
* </pre>
*
* <p>An implementation may also recognize additional address
* syntaxes, for example:</p>
*
* <pre>
* service:jmx:iiop://<em>[host[:port]]</em>/stub/<em>encoded-stub</em>
* </pre>
*
* @param url the address of the RMI connector server.
*
* @param environment additional attributes specifying how to make
* the connection. For JNDI-based addresses, these attributes can
* usefully include JNDI attributes recognized by {@link
* InitialContext#InitialContext(Hashtable) InitialContext}. This
* parameter can be null, which is equivalent to an empty Map.
*
* @exception IllegalArgumentException if <code>url</code>
* is null.
*/
public RMIConnector(JMXServiceURL url, Map<String,?> environment) {
this(null, url, environment);
}
/** {@collect.stats}
* <p>Constructs an <code>RMIConnector</code> using the given RMI stub.
*
* @param rmiServer an RMI stub representing the RMI connector server.
* @param environment additional attributes specifying how to make
* the connection. This parameter can be null, which is
* equivalent to an empty Map.
*
* @exception IllegalArgumentException if <code>rmiServer</code>
* is null.
*/
public RMIConnector(RMIServer rmiServer, Map<String,?> environment) {
this(rmiServer, null, environment);
}
/** {@collect.stats}
* <p>Returns a string representation of this object. In general,
* the <code>toString</code> method returns a string that
* "textually represents" this object. The result should be a
* concise but informative representation that is easy for a
* person to read.</p>
*
* @return a String representation of this object.
**/
public String toString() {
final StringBuilder b = new StringBuilder(this.getClass().getName());
b.append(":");
if (rmiServer != null) {
b.append(" rmiServer=").append(rmiServer.toString());
}
if (jmxServiceURL != null) {
if (rmiServer!=null) b.append(",");
b.append(" jmxServiceURL=").append(jmxServiceURL.toString());
}
return b.toString();
}
/** {@collect.stats}
* <p>The address of this connector.</p>
*
* @return the address of this connector, or null if it
* does not have one.
*
* @since 1.6
*/
public JMXServiceURL getAddress() {
return jmxServiceURL;
}
//--------------------------------------------------------------------
// implements JMXConnector interface
//--------------------------------------------------------------------
public void connect() throws IOException {
connect(null);
}
public synchronized void connect(Map<String,?> environment)
throws IOException {
final boolean tracing = logger.traceOn();
String idstr = (tracing?"["+this.toString()+"]":null);
if (terminated) {
logger.trace("connect",idstr + " already closed.");
throw new IOException("Connector closed");
}
if (connected) {
logger.trace("connect",idstr + " already connected.");
return;
}
try {
if (tracing) logger.trace("connect",idstr + " connecting...");
final Map<String, Object> usemap =
new HashMap<String, Object>((this.env==null) ?
Collections.<String, Object>emptyMap() : this.env);
if (environment != null) {
EnvHelp.checkAttributes(environment);
usemap.putAll(environment);
}
// Get RMIServer stub from directory or URL encoding if needed.
if (tracing) logger.trace("connect",idstr + " finding stub...");
RMIServer stub = (rmiServer!=null)?rmiServer:
findRMIServer(jmxServiceURL, usemap);
// Check for secure RMIServer stub if the corresponding
// client-side environment property is set to "true".
//
boolean checkStub = EnvHelp.computeBooleanFromString(
usemap,
"jmx.remote.x.check.stub");
if (checkStub) checkStub(stub, rmiServerImplStubClass);
// Connect IIOP Stub if needed.
if (tracing) logger.trace("connect",idstr + " connecting stub...");
stub = connectStub(stub,usemap);
idstr = (tracing?"["+this.toString()+"]":null);
// Calling newClient on the RMIServer stub.
if (tracing)
logger.trace("connect",idstr + " getting connection...");
Object credentials = usemap.get(CREDENTIALS);
connection = getConnection(stub, credentials, checkStub);
// Always use one of:
// ClassLoader provided in Map at connect time,
// or contextClassLoader at connect time.
if (tracing)
logger.trace("connect",idstr + " getting class loader...");
defaultClassLoader = EnvHelp.resolveClientClassLoader(usemap);
usemap.put(JMXConnectorFactory.DEFAULT_CLASS_LOADER,
defaultClassLoader);
rmiNotifClient = new RMINotifClient(defaultClassLoader, usemap);
env = usemap;
final long checkPeriod = EnvHelp.getConnectionCheckPeriod(usemap);
communicatorAdmin = new RMIClientCommunicatorAdmin(checkPeriod);
connected = true;
// The connectionId variable is used in doStart(), when
// reconnecting, to identify the "old" connection.
//
connectionId = getConnectionId();
Notification connectedNotif =
new JMXConnectionNotification(JMXConnectionNotification.OPENED,
this,
connectionId,
clientNotifSeqNo++,
"Successful connection",
null);
sendNotification(connectedNotif);
if (tracing) logger.trace("connect",idstr + " done...");
} catch (IOException e) {
if (tracing)
logger.trace("connect",idstr + " failed to connect: " + e);
throw e;
} catch (RuntimeException e) {
if (tracing)
logger.trace("connect",idstr + " failed to connect: " + e);
throw e;
} catch (NamingException e) {
final String msg = "Failed to retrieve RMIServer stub: " + e;
if (tracing) logger.trace("connect",idstr + " " + msg);
throw EnvHelp.initCause(new IOException(msg),e);
}
}
public synchronized String getConnectionId() throws IOException {
if (terminated || !connected) {
if (logger.traceOn())
logger.trace("getConnectionId","["+this.toString()+
"] not connected.");
throw new IOException("Not connected");
}
// we do a remote call to have an IOException if the connection is broken.
// see the bug 4939578
return connection.getConnectionId();
}
public synchronized MBeanServerConnection getMBeanServerConnection()
throws IOException {
return getMBeanServerConnection(null);
}
public synchronized MBeanServerConnection
getMBeanServerConnection(Subject delegationSubject)
throws IOException {
if (terminated) {
if (logger.traceOn())
logger.trace("getMBeanServerConnection","[" + this.toString() +
"] already closed.");
throw new IOException("Connection closed");
} else if (!connected) {
if (logger.traceOn())
logger.trace("getMBeanServerConnection","[" + this.toString() +
"] is not connected.");
throw new IOException("Not connected");
}
MBeanServerConnection mbsc = rmbscMap.get(delegationSubject);
if (mbsc != null)
return mbsc;
mbsc = new RemoteMBeanServerConnection(delegationSubject);
rmbscMap.put(delegationSubject, mbsc);
return mbsc;
}
public void
addConnectionNotificationListener(NotificationListener listener,
NotificationFilter filter,
Object handback) {
if (listener == null)
throw new NullPointerException("listener");
connectionBroadcaster.addNotificationListener(listener, filter,
handback);
}
public void
removeConnectionNotificationListener(NotificationListener listener)
throws ListenerNotFoundException {
if (listener == null)
throw new NullPointerException("listener");
connectionBroadcaster.removeNotificationListener(listener);
}
public void
removeConnectionNotificationListener(NotificationListener listener,
NotificationFilter filter,
Object handback)
throws ListenerNotFoundException {
if (listener == null)
throw new NullPointerException("listener");
connectionBroadcaster.removeNotificationListener(listener, filter,
handback);
}
private void sendNotification(Notification n) {
connectionBroadcaster.sendNotification(n);
}
public synchronized void close() throws IOException {
close(false);
}
// allows to do close after setting the flag "terminated" to true.
// It is necessary to avoid a deadlock, see 6296324
private synchronized void close(boolean intern) throws IOException {
final boolean tracing = logger.traceOn();
final boolean debug = logger.debugOn();
final String idstr = (tracing?"["+this.toString()+"]":null);
if (!intern) {
// Return if already cleanly closed.
//
if (terminated) {
if (closeException == null) {
if (tracing) logger.trace("close",idstr + " already closed.");
return;
}
} else {
terminated = true;
}
}
if (closeException != null && tracing) {
// Already closed, but not cleanly. Attempt again.
//
if (tracing) {
logger.trace("close",idstr + " had failed: " + closeException);
logger.trace("close",idstr + " attempting to close again.");
}
}
String savedConnectionId = null;
if (connected) {
savedConnectionId = connectionId;
}
closeException = null;
if (tracing) logger.trace("close",idstr + " closing.");
if (communicatorAdmin != null) {
communicatorAdmin.terminate();
}
if (rmiNotifClient != null) {
try {
rmiNotifClient.terminate();
if (tracing) logger.trace("close",idstr +
" RMI Notification client terminated.");
} catch (RuntimeException x) {
closeException = x;
if (tracing) logger.trace("close",idstr +
" Failed to terminate RMI Notification client: " + x);
if (debug) logger.debug("close",x);
}
}
if (connection != null) {
try {
connection.close();
if (tracing) logger.trace("close",idstr + " closed.");
} catch (NoSuchObjectException nse) {
// OK, the server maybe closed itself.
} catch (IOException e) {
closeException = e;
if (tracing) logger.trace("close",idstr +
" Failed to close RMIServer: " + e);
if (debug) logger.debug("close",e);
}
}
// Clean up MBeanServerConnection table
//
rmbscMap.clear();
/* Send notification of closure. We don't do this if the user
* never called connect() on the connector, because there's no
* connection id in that case. */
if (savedConnectionId != null) {
Notification closedNotif =
new JMXConnectionNotification(JMXConnectionNotification.CLOSED,
this,
savedConnectionId,
clientNotifSeqNo++,
"Client has been closed",
null);
sendNotification(closedNotif);
}
// throw exception if needed
//
if (closeException != null) {
if (tracing) logger.trace("close",idstr + " failed to close: " +
closeException);
if (closeException instanceof IOException)
throw (IOException) closeException;
if (closeException instanceof RuntimeException)
throw (RuntimeException) closeException;
final IOException x =
new IOException("Failed to close: " + closeException);
throw EnvHelp.initCause(x,closeException);
}
}
// added for re-connection
private Integer addListenerWithSubject(ObjectName name,
MarshalledObject filter,
Subject delegationSubject,
boolean reconnect)
throws InstanceNotFoundException, IOException {
final boolean debug = logger.debugOn();
if (debug)
logger.debug("addListenerWithSubject",
"(ObjectName,MarshalledObject,Subject)");
final ObjectName[] names = new ObjectName[] {name};
final MarshalledObject[] filters = new MarshalledObject[] {filter};
final Subject[] delegationSubjects = new Subject[] {
delegationSubject
};
final Integer[] listenerIDs =
addListenersWithSubjects(names,filters,delegationSubjects,
reconnect);
if (debug) logger.debug("addListenerWithSubject","listenerID="
+ listenerIDs[0]);
return listenerIDs[0];
}
// added for re-connection
private Integer[] addListenersWithSubjects(ObjectName[] names,
MarshalledObject[] filters,
Subject[] delegationSubjects,
boolean reconnect)
throws InstanceNotFoundException, IOException {
final boolean debug = logger.debugOn();
if (debug)
logger.debug("addListenersWithSubjects",
"(ObjectName[],MarshalledObject[],Subject[])");
final ClassLoader old = pushDefaultClassLoader();
Integer[] listenerIDs = null;
try {
listenerIDs = connection.addNotificationListeners(names,
filters,
delegationSubjects);
} catch (NoSuchObjectException noe) {
// maybe reconnect
if (reconnect) {
communicatorAdmin.gotIOException(noe);
listenerIDs = connection.addNotificationListeners(names,
filters,
delegationSubjects);
} else {
throw noe;
}
} catch (IOException ioe) {
// send a failed notif if necessary
communicatorAdmin.gotIOException(ioe);
} finally {
popDefaultClassLoader(old);
}
if (debug) logger.debug("addListenersWithSubjects","registered "
+ listenerIDs.length + " listener(s)");
return listenerIDs;
}
//--------------------------------------------------------------------
// Implementation of MBeanServerConnection
//--------------------------------------------------------------------
private class RemoteMBeanServerConnection
implements MBeanServerConnection {
private Subject delegationSubject;
public RemoteMBeanServerConnection() {
this(null);
}
public RemoteMBeanServerConnection(Subject delegationSubject) {
this.delegationSubject = delegationSubject;
}
public ObjectInstance createMBean(String className,
ObjectName name)
throws ReflectionException,
InstanceAlreadyExistsException,
MBeanRegistrationException,
MBeanException,
NotCompliantMBeanException,
IOException {
if (logger.debugOn())
logger.debug("createMBean(String,ObjectName)",
"className=" + className + ", name=" +
name);
final ClassLoader old = pushDefaultClassLoader();
try {
return connection.createMBean(className,
name,
delegationSubject);
} catch (IOException ioe) {
communicatorAdmin.gotIOException(ioe);
return connection.createMBean(className,
name,
delegationSubject);
} finally {
popDefaultClassLoader(old);
}
}
public ObjectInstance createMBean(String className,
ObjectName name,
ObjectName loaderName)
throws ReflectionException,
InstanceAlreadyExistsException,
MBeanRegistrationException,
MBeanException,
NotCompliantMBeanException,
InstanceNotFoundException,
IOException {
if (logger.debugOn())
logger.debug("createMBean(String,ObjectName,ObjectName)",
"className=" + className + ", name="
+ name + ", loaderName="
+ loaderName + ")");
final ClassLoader old = pushDefaultClassLoader();
try {
return connection.createMBean(className,
name,
loaderName,
delegationSubject);
} catch (IOException ioe) {
communicatorAdmin.gotIOException(ioe);
return connection.createMBean(className,
name,
loaderName,
delegationSubject);
} finally {
popDefaultClassLoader(old);
}
}
public ObjectInstance createMBean(String className,
ObjectName name,
Object params[],
String signature[])
throws ReflectionException,
InstanceAlreadyExistsException,
MBeanRegistrationException,
MBeanException,
NotCompliantMBeanException,
IOException {
if (logger.debugOn())
logger.debug("createMBean(String,ObjectName,Object[],String[])",
"className=" + className + ", name="
+ name + ", params="
+ objects(params) + ", signature="
+ strings(signature));
final MarshalledObject<Object[]> sParams =
new MarshalledObject<Object[]>(params);
final ClassLoader old = pushDefaultClassLoader();
try {
return connection.createMBean(className,
name,
sParams,
signature,
delegationSubject);
} catch (IOException ioe) {
communicatorAdmin.gotIOException(ioe);
return connection.createMBean(className,
name,
sParams,
signature,
delegationSubject);
} finally {
popDefaultClassLoader(old);
}
}
public ObjectInstance createMBean(String className,
ObjectName name,
ObjectName loaderName,
Object params[],
String signature[])
throws ReflectionException,
InstanceAlreadyExistsException,
MBeanRegistrationException,
MBeanException,
NotCompliantMBeanException,
InstanceNotFoundException,
IOException {
if (logger.debugOn()) logger.debug(
"createMBean(String,ObjectName,ObjectName,Object[],String[])",
"className=" + className + ", name=" + name + ", loaderName="
+ loaderName + ", params=" + objects(params)
+ ", signature=" + strings(signature));
final MarshalledObject<Object[]> sParams =
new MarshalledObject<Object[]>(params);
final ClassLoader old = pushDefaultClassLoader();
try {
return connection.createMBean(className,
name,
loaderName,
sParams,
signature,
delegationSubject);
} catch (IOException ioe) {
communicatorAdmin.gotIOException(ioe);
return connection.createMBean(className,
name,
loaderName,
sParams,
signature,
delegationSubject);
} finally {
popDefaultClassLoader(old);
}
}
public void unregisterMBean(ObjectName name)
throws InstanceNotFoundException,
MBeanRegistrationException,
IOException {
if (logger.debugOn())
logger.debug("unregisterMBean", "name=" + name);
final ClassLoader old = pushDefaultClassLoader();
try {
connection.unregisterMBean(name, delegationSubject);
} catch (IOException ioe) {
communicatorAdmin.gotIOException(ioe);
connection.unregisterMBean(name, delegationSubject);
} finally {
popDefaultClassLoader(old);
}
}
public ObjectInstance getObjectInstance(ObjectName name)
throws InstanceNotFoundException,
IOException {
if (logger.debugOn())
logger.debug("getObjectInstance", "name=" + name);
final ClassLoader old = pushDefaultClassLoader();
try {
return connection.getObjectInstance(name, delegationSubject);
} catch (IOException ioe) {
communicatorAdmin.gotIOException(ioe);
return connection.getObjectInstance(name, delegationSubject);
} finally {
popDefaultClassLoader(old);
}
}
public Set<ObjectInstance> queryMBeans(ObjectName name,
QueryExp query)
throws IOException {
if (logger.debugOn()) logger.debug("queryMBeans",
"name=" + name + ", query=" + query);
final MarshalledObject<QueryExp> sQuery =
new MarshalledObject<QueryExp>(query);
final ClassLoader old = pushDefaultClassLoader();
try {
return connection.queryMBeans(name, sQuery, delegationSubject);
} catch (IOException ioe) {
communicatorAdmin.gotIOException(ioe);
return connection.queryMBeans(name, sQuery, delegationSubject);
} finally {
popDefaultClassLoader(old);
}
}
public Set<ObjectName> queryNames(ObjectName name,
QueryExp query)
throws IOException {
if (logger.debugOn()) logger.debug("queryNames",
"name=" + name + ", query=" + query);
final MarshalledObject<QueryExp> sQuery =
new MarshalledObject<QueryExp>(query);
final ClassLoader old = pushDefaultClassLoader();
try {
return connection.queryNames(name, sQuery, delegationSubject);
} catch (IOException ioe) {
communicatorAdmin.gotIOException(ioe);
return connection.queryNames(name, sQuery, delegationSubject);
} finally {
popDefaultClassLoader(old);
}
}
public boolean isRegistered(ObjectName name)
throws IOException {
if (logger.debugOn())
logger.debug("isRegistered", "name=" + name);
final ClassLoader old = pushDefaultClassLoader();
try {
return connection.isRegistered(name, delegationSubject);
} catch (IOException ioe) {
communicatorAdmin.gotIOException(ioe);
return connection.isRegistered(name, delegationSubject);
} finally {
popDefaultClassLoader(old);
}
}
public Integer getMBeanCount()
throws IOException {
if (logger.debugOn()) logger.debug("getMBeanCount", "");
final ClassLoader old = pushDefaultClassLoader();
try {
return connection.getMBeanCount(delegationSubject);
} catch (IOException ioe) {
communicatorAdmin.gotIOException(ioe);
return connection.getMBeanCount(delegationSubject);
} finally {
popDefaultClassLoader(old);
}
}
public Object getAttribute(ObjectName name,
String attribute)
throws MBeanException,
AttributeNotFoundException,
InstanceNotFoundException,
ReflectionException,
IOException {
if (logger.debugOn()) logger.debug("getAttribute",
"name=" + name + ", attribute="
+ attribute);
final ClassLoader old = pushDefaultClassLoader();
try {
return connection.getAttribute(name,
attribute,
delegationSubject);
} catch (IOException ioe) {
communicatorAdmin.gotIOException(ioe);
return connection.getAttribute(name,
attribute,
delegationSubject);
} finally {
popDefaultClassLoader(old);
}
}
public AttributeList getAttributes(ObjectName name,
String[] attributes)
throws InstanceNotFoundException,
ReflectionException,
IOException {
if (logger.debugOn()) logger.debug("getAttributes",
"name=" + name + ", attributes="
+ strings(attributes));
final ClassLoader old = pushDefaultClassLoader();
try {
return connection.getAttributes(name,
attributes,
delegationSubject);
} catch (IOException ioe) {
communicatorAdmin.gotIOException(ioe);
return connection.getAttributes(name,
attributes,
delegationSubject);
} finally {
popDefaultClassLoader(old);
}
}
public void setAttribute(ObjectName name,
Attribute attribute)
throws InstanceNotFoundException,
AttributeNotFoundException,
InvalidAttributeValueException,
MBeanException,
ReflectionException,
IOException {
if (logger.debugOn()) logger.debug("setAttribute",
"name=" + name + ", attribute="
+ attribute);
final MarshalledObject<Attribute> sAttribute =
new MarshalledObject<Attribute>(attribute);
final ClassLoader old = pushDefaultClassLoader();
try {
connection.setAttribute(name, sAttribute, delegationSubject);
} catch (IOException ioe) {
communicatorAdmin.gotIOException(ioe);
connection.setAttribute(name, sAttribute, delegationSubject);
} finally {
popDefaultClassLoader(old);
}
}
public AttributeList setAttributes(ObjectName name,
AttributeList attributes)
throws InstanceNotFoundException,
ReflectionException,
IOException {
if (logger.debugOn()) logger.debug("setAttributes",
"name=" + name + ", attributes="
+ attributes);
final MarshalledObject<AttributeList> sAttributes =
new MarshalledObject<AttributeList>(attributes);
final ClassLoader old = pushDefaultClassLoader();
try {
return connection.setAttributes(name,
sAttributes,
delegationSubject);
} catch (IOException ioe) {
communicatorAdmin.gotIOException(ioe);
return connection.setAttributes(name,
sAttributes,
delegationSubject);
} finally {
popDefaultClassLoader(old);
}
}
public Object invoke(ObjectName name,
String operationName,
Object params[],
String signature[])
throws InstanceNotFoundException,
MBeanException,
ReflectionException,
IOException {
if (logger.debugOn()) logger.debug("invoke",
"name=" + name
+ ", operationName=" + operationName
+ ", params=" + objects(params)
+ ", signature=" + strings(signature));
final MarshalledObject<Object[]> sParams =
new MarshalledObject<Object[]>(params);
final ClassLoader old = pushDefaultClassLoader();
try {
return connection.invoke(name,
operationName,
sParams,
signature,
delegationSubject);
} catch (IOException ioe) {
communicatorAdmin.gotIOException(ioe);
return connection.invoke(name,
operationName,
sParams,
signature,
delegationSubject);
} finally {
popDefaultClassLoader(old);
}
}
public String getDefaultDomain()
throws IOException {
if (logger.debugOn()) logger.debug("getDefaultDomain", "");
final ClassLoader old = pushDefaultClassLoader();
try {
return connection.getDefaultDomain(delegationSubject);
} catch (IOException ioe) {
communicatorAdmin.gotIOException(ioe);
return connection.getDefaultDomain(delegationSubject);
} finally {
popDefaultClassLoader(old);
}
}
public String[] getDomains() throws IOException {
if (logger.debugOn()) logger.debug("getDomains", "");
final ClassLoader old = pushDefaultClassLoader();
try {
return connection.getDomains(delegationSubject);
} catch (IOException ioe) {
communicatorAdmin.gotIOException(ioe);
return connection.getDomains(delegationSubject);
} finally {
popDefaultClassLoader(old);
}
}
public MBeanInfo getMBeanInfo(ObjectName name)
throws InstanceNotFoundException,
IntrospectionException,
ReflectionException,
IOException {
if (logger.debugOn()) logger.debug("getMBeanInfo", "name=" + name);
final ClassLoader old = pushDefaultClassLoader();
try {
return connection.getMBeanInfo(name, delegationSubject);
} catch (IOException ioe) {
communicatorAdmin.gotIOException(ioe);
return connection.getMBeanInfo(name, delegationSubject);
} finally {
popDefaultClassLoader(old);
}
}
public boolean isInstanceOf(ObjectName name,
String className)
throws InstanceNotFoundException,
IOException {
if (logger.debugOn())
logger.debug("isInstanceOf", "name=" + name +
", className=" + className);
final ClassLoader old = pushDefaultClassLoader();
try {
return connection.isInstanceOf(name,
className,
delegationSubject);
} catch (IOException ioe) {
communicatorAdmin.gotIOException(ioe);
return connection.isInstanceOf(name,
className,
delegationSubject);
} finally {
popDefaultClassLoader(old);
}
}
public void addNotificationListener(ObjectName name,
ObjectName listener,
NotificationFilter filter,
Object handback)
throws InstanceNotFoundException,
IOException {
if (logger.debugOn())
logger.debug("addNotificationListener" +
"(ObjectName,ObjectName,NotificationFilter,Object)",
"name=" + name + ", listener=" + listener
+ ", filter=" + filter + ", handback=" + handback);
final MarshalledObject<NotificationFilter> sFilter =
new MarshalledObject<NotificationFilter>(filter);
final MarshalledObject<Object> sHandback =
new MarshalledObject<Object>(handback);
final ClassLoader old = pushDefaultClassLoader();
try {
connection.addNotificationListener(name,
listener,
sFilter,
sHandback,
delegationSubject);
} catch (IOException ioe) {
communicatorAdmin.gotIOException(ioe);
connection.addNotificationListener(name,
listener,
sFilter,
sHandback,
delegationSubject);
} finally {
popDefaultClassLoader(old);
}
}
public void removeNotificationListener(ObjectName name,
ObjectName listener)
throws InstanceNotFoundException,
ListenerNotFoundException,
IOException {
if (logger.debugOn()) logger.debug("removeNotificationListener" +
"(ObjectName,ObjectName)",
"name=" + name
+ ", listener=" + listener);
final ClassLoader old = pushDefaultClassLoader();
try {
connection.removeNotificationListener(name,
listener,
delegationSubject);
} catch (IOException ioe) {
communicatorAdmin.gotIOException(ioe);
connection.removeNotificationListener(name,
listener,
delegationSubject);
} finally {
popDefaultClassLoader(old);
}
}
public void removeNotificationListener(ObjectName name,
ObjectName listener,
NotificationFilter filter,
Object handback)
throws InstanceNotFoundException,
ListenerNotFoundException,
IOException {
if (logger.debugOn())
logger.debug("removeNotificationListener" +
"(ObjectName,ObjectName,NotificationFilter,Object)",
"name=" + name
+ ", listener=" + listener
+ ", filter=" + filter
+ ", handback=" + handback);
final MarshalledObject<NotificationFilter> sFilter =
new MarshalledObject<NotificationFilter>(filter);
final MarshalledObject<Object> sHandback =
new MarshalledObject<Object>(handback);
final ClassLoader old = pushDefaultClassLoader();
try {
connection.removeNotificationListener(name,
listener,
sFilter,
sHandback,
delegationSubject);
} catch (IOException ioe) {
communicatorAdmin.gotIOException(ioe);
connection.removeNotificationListener(name,
listener,
sFilter,
sHandback,
delegationSubject);
} finally {
popDefaultClassLoader(old);
}
}
// Specific Notification Handle ----------------------------------
public void addNotificationListener(ObjectName name,
NotificationListener listener,
NotificationFilter filter,
Object handback)
throws InstanceNotFoundException,
IOException {
final boolean debug = logger.debugOn();
if (debug)
logger.debug("addNotificationListener" +
"(ObjectName,NotificationListener,"+
"NotificationFilter,Object)",
"name=" + name
+ ", listener=" + listener
+ ", filter=" + filter
+ ", handback=" + handback);
final Integer listenerID =
addListenerWithSubject(name,
new MarshalledObject<NotificationFilter>(filter),
delegationSubject,true);
rmiNotifClient.addNotificationListener(listenerID, name, listener,
filter, handback,
delegationSubject);
}
public void removeNotificationListener(ObjectName name,
NotificationListener listener)
throws InstanceNotFoundException,
ListenerNotFoundException,
IOException {
final boolean debug = logger.debugOn();
if (debug) logger.debug("removeNotificationListener"+
"(ObjectName,NotificationListener)",
"name=" + name
+ ", listener=" + listener);
final Integer[] ret =
rmiNotifClient.removeNotificationListener(name, listener);
if (debug) logger.debug("removeNotificationListener",
"listenerIDs=" + objects(ret));
final ClassLoader old = pushDefaultClassLoader();
try {
connection.removeNotificationListeners(name,
ret,
delegationSubject);
} catch (IOException ioe) {
communicatorAdmin.gotIOException(ioe);
connection.removeNotificationListeners(name,
ret,
delegationSubject);
} finally {
popDefaultClassLoader(old);
}
}
public void removeNotificationListener(ObjectName name,
NotificationListener listener,
NotificationFilter filter,
Object handback)
throws InstanceNotFoundException,
ListenerNotFoundException,
IOException {
final boolean debug = logger.debugOn();
if (debug)
logger.debug("removeNotificationListener"+
"(ObjectName,NotificationListener,"+
"NotificationFilter,Object)",
"name=" + name
+ ", listener=" + listener
+ ", filter=" + filter
+ ", handback=" + handback);
final Integer ret =
rmiNotifClient.removeNotificationListener(name, listener,
filter, handback);
if (debug) logger.debug("removeNotificationListener",
"listenerID=" + ret);
final ClassLoader old = pushDefaultClassLoader();
try {
connection.removeNotificationListeners(name,
new Integer[] {ret},
delegationSubject);
} catch (IOException ioe) {
communicatorAdmin.gotIOException(ioe);
connection.removeNotificationListeners(name,
new Integer[] {ret},
delegationSubject);
} finally {
popDefaultClassLoader(old);
}
}
}
//--------------------------------------------------------------------
private class RMINotifClient extends ClientNotifForwarder {
public RMINotifClient(ClassLoader cl, Map env) {
super(cl, env);
}
protected NotificationResult fetchNotifs(long clientSequenceNumber,
int maxNotifications,
long timeout)
throws IOException, ClassNotFoundException {
IOException org;
while (true) { // used for a successful re-connection
try {
return connection.fetchNotifications(clientSequenceNumber,
maxNotifications,
timeout);
} catch (IOException ioe) {
org = ioe;
// inform of IOException
try {
communicatorAdmin.gotIOException(ioe);
// The connection should be re-established.
continue;
} catch (IOException ee) {
// No more fetch, the Exception will be re-thrown.
break;
} // never reached
} // never reached
}
// specially treating for an UnmarshalException
if (org instanceof UnmarshalException) {
UnmarshalException ume = (UnmarshalException)org;
if (ume.detail instanceof ClassNotFoundException)
throw (ClassNotFoundException) ume.detail;
/* In Sun's RMI implementation, if a method return
contains an unserializable object, then we get
UnmarshalException wrapping WriteAbortedException
wrapping NotSerializableException. In that case we
extract the NotSerializableException so that our
caller can realize it should try to skip past the
notification that presumably caused it. It's not
certain that every other RMI implementation will
generate this exact exception sequence. If not, we
will not detect that the problem is due to an
unserializable object, and we will stop trying to
receive notifications from the server. It's not
clear we can do much better. */
if (ume.detail instanceof WriteAbortedException) {
WriteAbortedException wae =
(WriteAbortedException) ume.detail;
if (wae.detail instanceof IOException)
throw (IOException) wae.detail;
}
} else if (org instanceof MarshalException) {
// IIOP will throw MarshalException wrapping a NotSerializableException
// when a server fails to serialize a response.
MarshalException me = (MarshalException)org;
if (me.detail instanceof NotSerializableException) {
throw (NotSerializableException)me.detail;
}
}
// Not serialization problem, simply re-throw the orginal exception
throw org;
}
protected Integer addListenerForMBeanRemovedNotif()
throws IOException, InstanceNotFoundException {
MarshalledObject<NotificationFilter> sFilter = null;
NotificationFilterSupport clientFilter =
new NotificationFilterSupport();
clientFilter.enableType(
MBeanServerNotification.UNREGISTRATION_NOTIFICATION);
sFilter = new MarshalledObject<NotificationFilter>(clientFilter);
Integer[] listenerIDs;
final ObjectName[] names =
new ObjectName[] {MBeanServerDelegate.DELEGATE_NAME};
final MarshalledObject[] filters =
new MarshalledObject[] {sFilter};
final Subject[] subjects = new Subject[] {null};
try {
listenerIDs =
connection.addNotificationListeners(names,
filters,
subjects);
} catch (IOException ioe) {
communicatorAdmin.gotIOException(ioe);
listenerIDs =
connection.addNotificationListeners(names,
filters,
subjects);
}
return listenerIDs[0];
}
protected void removeListenerForMBeanRemovedNotif(Integer id)
throws IOException, InstanceNotFoundException,
ListenerNotFoundException {
try {
connection.removeNotificationListeners(
MBeanServerDelegate.DELEGATE_NAME,
new Integer[] {id},
null);
} catch (IOException ioe) {
communicatorAdmin.gotIOException(ioe);
connection.removeNotificationListeners(
MBeanServerDelegate.DELEGATE_NAME,
new Integer[] {id},
null);
}
}
protected void lostNotifs(String message, long number) {
final String notifType = JMXConnectionNotification.NOTIFS_LOST;
final JMXConnectionNotification n =
new JMXConnectionNotification(notifType,
RMIConnector.this,
connectionId,
clientNotifCounter++,
message,
new Long(number));
sendNotification(n);
}
}
private class RMIClientCommunicatorAdmin extends ClientCommunicatorAdmin {
public RMIClientCommunicatorAdmin(long period) {
super(period);
}
public void gotIOException (IOException ioe) throws IOException {
if (ioe instanceof NoSuchObjectException) {
// need to restart
super.gotIOException(ioe);
return;
}
// check if the connection is broken
try {
connection.getDefaultDomain(null);
} catch (IOException ioexc) {
boolean toClose = false;
synchronized(this) {
if (!terminated) {
terminated = true;
toClose = true;
}
}
if (toClose) {
// we should close the connection,
// but send a failed notif at first
final Notification failedNotif =
new JMXConnectionNotification(
JMXConnectionNotification.FAILED,
this,
connectionId,
clientNotifSeqNo++,
"Failed to communicate with the server: "+ioe.toString(),
ioe);
sendNotification(failedNotif);
try {
close(true);
} catch (Exception e) {
// OK.
// We are closing
}
}
}
// forward the exception
if (ioe instanceof ServerException) {
/* Need to unwrap the exception.
Some user-thrown exception at server side will be wrapped by
rmi into a ServerException.
For example, a RMIConnnectorServer will wrap a
ClassNotFoundException into a UnmarshalException, and rmi
will throw a ServerException at client side which wraps this
UnmarshalException.
No failed notif here.
*/
Throwable tt = ((ServerException)ioe).detail;
if (tt instanceof IOException) {
throw (IOException)tt;
} else if (tt instanceof RuntimeException) {
throw (RuntimeException)tt;
}
}
throw ioe;
}
public void reconnectNotificationListeners(ClientListenerInfo[] old) throws IOException {
final int len = old.length;
int i;
ClientListenerInfo[] clis = new ClientListenerInfo[len];
final Subject[] subjects = new Subject[len];
final ObjectName[] names = new ObjectName[len];
final NotificationListener[] listeners = new NotificationListener[len];
final NotificationFilter[] filters = new NotificationFilter[len];
final MarshalledObject[] mFilters = new MarshalledObject[len];
final Object[] handbacks = new Object[len];
for (i=0;i<len;i++) {
subjects[i] = old[i].getDelegationSubject();
names[i] = old[i].getObjectName();
listeners[i] = old[i].getListener();
filters[i] = old[i].getNotificationFilter();
mFilters[i] = new MarshalledObject<NotificationFilter>(filters[i]);
handbacks[i] = old[i].getHandback();
}
try {
Integer[] ids = addListenersWithSubjects(names,mFilters,subjects,false);
for (i=0;i<len;i++) {
clis[i] = new ClientListenerInfo(ids[i],
names[i],
listeners[i],
filters[i],
handbacks[i],
subjects[i]);
}
rmiNotifClient.postReconnection(clis);
return;
} catch (InstanceNotFoundException infe) {
// OK, we will do one by one
}
int j = 0;
for (i=0;i<len;i++) {
try {
Integer id = addListenerWithSubject(names[i],
new MarshalledObject<NotificationFilter>(filters[i]),
subjects[i],
false);
clis[j++] = new ClientListenerInfo(id,
names[i],
listeners[i],
filters[i],
handbacks[i],
subjects[i]);
} catch (InstanceNotFoundException infe) {
logger.warning("reconnectNotificationListeners",
"Can't reconnect listener for " +
names[i]);
}
}
if (j != len) {
ClientListenerInfo[] tmp = clis;
clis = new ClientListenerInfo[j];
System.arraycopy(tmp, 0, clis, 0, j);
}
rmiNotifClient.postReconnection(clis);
}
protected void checkConnection() throws IOException {
if (logger.debugOn())
logger.debug("RMIClientCommunicatorAdmin-checkConnection",
"Calling the method getDefaultDomain.");
connection.getDefaultDomain(null);
}
protected void doStart() throws IOException {
// Get RMIServer stub from directory or URL encoding if needed.
RMIServer stub = null;
try {
stub = (rmiServer!=null)?rmiServer:
findRMIServer(jmxServiceURL, env);
} catch (NamingException ne) {
throw new IOException("Failed to get a RMI stub: "+ne);
}
// Connect IIOP Stub if needed.
stub = connectStub(stub,env);
// Calling newClient on the RMIServer stub.
Object credentials = env.get(CREDENTIALS);
connection = stub.newClient(credentials);
// notif issues
final ClientListenerInfo[] old = rmiNotifClient.preReconnection();
reconnectNotificationListeners(old);
connectionId = getConnectionId();
Notification reconnectedNotif =
new JMXConnectionNotification(JMXConnectionNotification.OPENED,
this,
connectionId,
clientNotifSeqNo++,
"Reconnected to server",
null);
sendNotification(reconnectedNotif);
}
protected void doStop() {
try {
close();
} catch (IOException ioe) {
logger.warning("RMIClientCommunicatorAdmin-doStop",
"Failed to call the method close():" + ioe);
logger.debug("RMIClientCommunicatorAdmin-doStop",ioe);
}
}
}
//--------------------------------------------------------------------
// Private stuff - Serialization
//--------------------------------------------------------------------
/** {@collect.stats}
* <p>In order to be usable, an IIOP stub must be connected to an ORB.
* The stub is automatically connected to the ORB if:
* <ul>
* <li> It was returned by the COS naming</li>
* <li> Its server counterpart has been registered in COS naming
* through JNDI.</li>
* </ul>
* Otherwise, it is not connected. A stub which is deserialized
* from Jini is not connected. A stub which is obtained from a
* non registered RMIIIOPServerImpl is not a connected.<br>
* A stub which is not connected can't be serialized, and thus
* can't be registered in Jini. A stub which is not connected can't
* be used to invoke methods on the server.
* <p>
* In order to palliate this, this method will connect the
* given stub if it is not yet connected. If the given
* <var>RMIServer</var> is not an instance of
* {@link javax.rmi.CORBA.Stub javax.rmi.CORBA.Stub}, then the
* method do nothing and simply returns that stub. Otherwise,
* this method will attempt to connect the stub to an ORB as
* follows:
* <ul>
* <p>This method looks in the provided <var>environment</var> for
* the "java.naming.corba.orb" property. If it is found, the
* referenced object (an {@link org.omg.CORBA.ORB ORB}) is used to
* connect the stub. Otherwise, a new org.omg.CORBA.ORB is created
* by calling {@link
* org.omg.CORBA.ORB#init(String[], Properties)
* org.omg.CORBA.ORB.init((String[])null,(Properties)null)}
* <p>The new created ORB is kept in a static
* {@link WeakReference} and can be reused for connecting other
* stubs. However, no reference is ever kept on the ORB provided
* in the <var>environment</var> map, if any.
* </ul>
* @param rmiServer A RMI Server Stub.
* @param environment An environment map, possibly containing an ORB.
* @return the given stub.
* @exception IllegalArgumentException if the
* <tt>java.naming.corba.orb</tt> property is specified and
* does not point to an {@link org.omg.CORBA.ORB ORB}.
* @exception IOException if the connection to the ORB failed.
**/
static RMIServer connectStub(RMIServer rmiServer,
Map environment)
throws IOException {
if (rmiServer instanceof javax.rmi.CORBA.Stub) {
javax.rmi.CORBA.Stub stub = (javax.rmi.CORBA.Stub) rmiServer;
try {
stub._orb();
} catch (BAD_OPERATION x) {
stub.connect(resolveOrb(environment));
}
}
return rmiServer;
}
/** {@collect.stats}
* Get the ORB specified by <var>environment</var>, or create a
* new one.
* <p>This method looks in the provided <var>environment</var> for
* the "java.naming.corba.orb" property. If it is found, the
* referenced object (an {@link org.omg.CORBA.ORB ORB}) is
* returned. Otherwise, a new org.omg.CORBA.ORB is created
* by calling {@link
* org.omg.CORBA.ORB#init(String[], java.util.Properties)
* org.omg.CORBA.ORB.init((String[])null,(Properties)null)}
* <p>The new created ORB is kept in a static
* {@link WeakReference} and can be reused for connecting other
* stubs. However, no reference is ever kept on the ORB provided
* in the <var>environment</var> map, if any.
* @param environment An environment map, possibly containing an ORB.
* @return An ORB.
* @exception IllegalArgumentException if the
* <tt>java.naming.corba.orb</tt> property is specified and
* does not point to an {@link org.omg.CORBA.ORB ORB}.
* @exception IOException if the ORB initialization failed.
**/
static ORB resolveOrb(Map environment)
throws IOException {
if (environment != null) {
final Object orb = environment.get(EnvHelp.DEFAULT_ORB);
if (orb != null && !(orb instanceof ORB))
throw new IllegalArgumentException(EnvHelp.DEFAULT_ORB +
" must be an instance of org.omg.CORBA.ORB.");
if (orb != null) return (ORB)orb;
}
final ORB orb =
(RMIConnector.orb==null)?null:RMIConnector.orb.get();
if (orb != null) return orb;
final ORB newOrb =
ORB.init((String[])null, (Properties)null);
RMIConnector.orb = new WeakReference<ORB>(newOrb);
return newOrb;
}
/** {@collect.stats}
* Read RMIConnector fields from an {@link java.io.ObjectInputStream
* ObjectInputStream}.
* Calls <code>s.defaultReadObject()</code> and then initializes
* all transient variables that need initializing.
* @param s The ObjectInputStream to read from.
* @exception InvalidObjectException if none of <var>rmiServer</var> stub
* or <var>jmxServiceURL</var> are set.
* @see #RMIConnector(JMXServiceURL,Map)
* @see #RMIConnector(RMIServer,Map)
**/
private void readObject(java.io.ObjectInputStream s)
throws IOException, ClassNotFoundException {
s.defaultReadObject();
if (rmiServer == null && jmxServiceURL == null) throw new
InvalidObjectException("rmiServer and jmxServiceURL both null");
initTransients();
}
/** {@collect.stats}
* Writes the RMIConnector fields to an {@link java.io.ObjectOutputStream
* ObjectOutputStream}.
* <p>Connects the underlying RMIServer stub to an ORB, if needed,
* before serializing it. This is done using the environment
* map that was provided to the constructor, if any, and as documented
* in {@link javax.management.remote.rmi}.</p>
* <p>This method then calls <code>s.defaultWriteObject()</code>.
* Usually, <var>rmiServer</var> is null if this object
* was constructed with a JMXServiceURL, and <var>jmxServiceURL</var>
* is null if this object is constructed with a RMIServer stub.
* <p>Note that the environment Map is not serialized, since the objects
* it contains are assumed to be contextual and relevant only
* with respect to the local environment (class loader, ORB, etc...).</p>
* <p>After an RMIConnector is deserialized, it is assumed that the
* user will call {@link #connect(Map)}, providing a new Map that
* can contain values which are contextually relevant to the new
* local environment.</p>
* <p>Since connection to the ORB is needed prior to serializing, and
* since the ORB to connect to is one of those contextual parameters,
* it is not recommended to re-serialize a just de-serialized object -
* as the de-serialized object has no map. Thus, when an RMIConnector
* object is needed for serialization or transmission to a remote
* application, it is recommended to obtain a new RMIConnector stub
* by calling {@link RMIConnectorServer#toJMXConnector(Map)}.</p>
* @param s The ObjectOutputStream to write to.
* @exception InvalidObjectException if none of <var>rmiServer</var> stub
* or <var>jmxServiceURL</var> are set.
* @see #RMIConnector(JMXServiceURL,Map)
* @see #RMIConnector(RMIServer,Map)
**/
private void writeObject(java.io.ObjectOutputStream s)
throws IOException {
if (rmiServer == null && jmxServiceURL == null) throw new
InvalidObjectException("rmiServer and jmxServiceURL both null.");
connectStub(this.rmiServer,env);
s.defaultWriteObject();
}
// Initialization of transient variables.
private void initTransients() {
rmbscMap = new WeakHashMap<Subject, MBeanServerConnection>();
connected = false;
terminated = false;
connectionBroadcaster = new NotificationBroadcasterSupport();
}
//--------------------------------------------------------------------
// Private stuff - Check if stub can be trusted.
//--------------------------------------------------------------------
private static void checkStub(Remote stub,
Class<?> stubClass) {
// Check remote stub is from the expected class.
//
if (stub.getClass() != stubClass) {
if (!Proxy.isProxyClass(stub.getClass())) {
throw new SecurityException(
"Expecting a " + stubClass.getName() + " stub!");
} else {
InvocationHandler handler = Proxy.getInvocationHandler(stub);
if (handler.getClass() != RemoteObjectInvocationHandler.class)
throw new SecurityException(
"Expecting a dynamic proxy instance with a " +
RemoteObjectInvocationHandler.class.getName() +
" invocation handler!");
else
stub = (Remote) handler;
}
}
// Check RemoteRef in stub is from the expected class
// "sun.rmi.server.UnicastRef2".
//
RemoteRef ref = ((RemoteObject)stub).getRef();
if (ref.getClass() != UnicastRef2.class)
throw new SecurityException(
"Expecting a " + UnicastRef2.class.getName() +
" remote reference in stub!");
// Check RMIClientSocketFactory in stub is from the expected class
// "javax.rmi.ssl.SslRMIClientSocketFactory".
//
LiveRef liveRef = ((UnicastRef2)ref).getLiveRef();
RMIClientSocketFactory csf = liveRef.getClientSocketFactory();
if (csf == null || csf.getClass() != SslRMIClientSocketFactory.class)
throw new SecurityException(
"Expecting a " + SslRMIClientSocketFactory.class.getName() +
" RMI client socket factory in stub!");
}
//--------------------------------------------------------------------
// Private stuff - RMIServer creation
//--------------------------------------------------------------------
private RMIServer findRMIServer(JMXServiceURL directoryURL,
Map<String, Object> environment)
throws NamingException, IOException {
final boolean isIiop = RMIConnectorServer.isIiopURL(directoryURL,true);
if (isIiop) {
// Make sure java.naming.corba.orb is in the Map.
environment.put(EnvHelp.DEFAULT_ORB,resolveOrb(environment));
}
String path = directoryURL.getURLPath();
int end = path.indexOf(';');
if (end < 0) end = path.length();
if (path.startsWith("/jndi/"))
return findRMIServerJNDI(path.substring(6,end), environment, isIiop);
else if (path.startsWith("/stub/"))
return findRMIServerJRMP(path.substring(6,end), environment, isIiop);
else if (path.startsWith("/ior/"))
return findRMIServerIIOP(path.substring(5,end), environment, isIiop);
else {
final String msg = "URL path must begin with /jndi/ or /stub/ " +
"or /ior/: " + path;
throw new MalformedURLException(msg);
}
}
/** {@collect.stats}
* Lookup the RMIServer stub in a directory.
* @param jndiURL A JNDI URL indicating the location of the Stub
* (see {@link javax.management.remote.rmi}), e.g.:
* <ul><li><tt>rmi://registry-host:port/rmi-stub-name</tt></li>
* <li>or <tt>iiop://cosnaming-host:port/iiop-stub-name</tt></li>
* <li>or <tt>ldap://ldap-host:port/java-container-dn</tt></li>
* </ul>
* @param env the environment Map passed to the connector.
* @param isIiop true if the stub is expected to be an IIOP stub.
* @return The retrieved RMIServer stub.
* @exception NamingException if the stub couldn't be found.
**/
private RMIServer findRMIServerJNDI(String jndiURL, Map<String, ?> env,
boolean isIiop)
throws NamingException {
InitialContext ctx = new InitialContext(EnvHelp.mapToHashtable(env));
Object objref = ctx.lookup(jndiURL);
ctx.close();
if (isIiop)
return narrowIIOPServer(objref);
else
return narrowJRMPServer(objref);
}
private static RMIServer narrowJRMPServer(Object objref) {
return (RMIServer) objref;
}
private static RMIServer narrowIIOPServer(Object objref) {
try {
return (RMIServer)
PortableRemoteObject.narrow(objref, RMIServer.class);
} catch (ClassCastException e) {
if (logger.traceOn())
logger.trace("narrowIIOPServer","Failed to narrow objref=" +
objref + ": " + e);
if (logger.debugOn()) logger.debug("narrowIIOPServer",e);
return null;
}
}
private RMIServer findRMIServerIIOP(String ior, Map env, boolean isIiop) {
// could forbid "rmi:" URL here -- but do we need to?
final ORB orb = (ORB)
env.get(EnvHelp.DEFAULT_ORB);
final Object stub = orb.string_to_object(ior);
return (RMIServer) PortableRemoteObject.narrow(stub, RMIServer.class);
}
private RMIServer findRMIServerJRMP(String base64, Map env, boolean isIiop)
throws IOException {
// could forbid "iiop:" URL here -- but do we need to?
final byte[] serialized;
try {
serialized = base64ToByteArray(base64);
} catch (IllegalArgumentException e) {
throw new MalformedURLException("Bad BASE64 encoding: " +
e.getMessage());
}
final ByteArrayInputStream bin = new ByteArrayInputStream(serialized);
final ClassLoader loader = EnvHelp.resolveClientClassLoader(env);
final ObjectInputStream oin =
(loader == null) ?
new ObjectInputStream(bin) :
new ObjectInputStreamWithLoader(bin, loader);
final Object stub;
try {
stub = oin.readObject();
} catch (ClassNotFoundException e) {
throw new MalformedURLException("Class not found: " + e);
}
return (RMIServer) PortableRemoteObject.narrow(stub, RMIServer.class);
}
private static final class ObjectInputStreamWithLoader
extends ObjectInputStream {
ObjectInputStreamWithLoader(InputStream in, ClassLoader cl)
throws IOException {
super(in);
this.loader = cl;
}
protected Class resolveClass(ObjectStreamClass classDesc)
throws IOException, ClassNotFoundException {
return Class.forName(classDesc.getName(), false, loader);
}
private final ClassLoader loader;
}
/*
The following section of code avoids a class loading problem
with RMI. The problem is that an RMI stub, when deserializing
a remote method return value or exception, will first of all
consult the first non-bootstrap class loader it finds in the
call stack. This can lead to behavior that is not portable
between implementations of the JMX Remote API. Notably, an
implementation on J2SE 1.4 will find the RMI stub's loader on
the stack. But in J2SE 5, this stub is loaded by the
bootstrap loader, so RMI will find the loader of the user code
that called an MBeanServerConnection method.
To avoid this problem, we take advantage of what the RMI stub
is doing internally. Each remote call will end up calling
ref.invoke(...), where ref is the RemoteRef parameter given to
the RMI stub's constructor. It is within this call that the
deserialization will happen. So we fabricate our own RemoteRef
that delegates everything to the "real" one but that is loaded
by a class loader that knows no other classes. The class
loader NoCallStackClassLoader does this: the RemoteRef is an
instance of the class named by proxyRefClassName, which is
fabricated by the class loader using byte code that is defined
by the string below.
The call stack when the deserialization happens is thus this:
MBeanServerConnection.getAttribute (or whatever)
-> RMIConnectionImpl_Stub.getAttribute
-> ProxyRef.invoke(...getAttribute...)
-> UnicastRef.invoke(...getAttribute...)
-> internal RMI stuff
Here UnicastRef is the RemoteRef created when the stub was
deserialized (which is of some RMI internal class). It and the
"internal RMI stuff" are loaded by the bootstrap loader, so are
transparent to the stack search. The first non-bootstrap
loader found is our ProxyRefLoader, as required.
In a future version of this code as integrated into J2SE 5,
this workaround could be replaced by direct access to the
internals of RMI. For now, we use the same code base for J2SE
and for the standalone Reference Implementation.
The byte code below encodes the following class, compiled using
J2SE 1.4.2 with the -g:none option.
package com.sun.jmx.remote.internal;
import java.lang.reflect.Method;
import java.rmi.Remote;
import java.rmi.server.RemoteRef;
import com.sun.jmx.remote.internal.ProxyRef;
public class PRef extends ProxyRef {
public PRef(RemoteRef ref) {
super(ref);
}
public Object invoke(Remote obj, Method method,
Object[] params, long opnum)
throws Exception {
return ref.invoke(obj, method, params, opnum);
}
}
*/
private static final String rmiServerImplStubClassName =
RMIServer.class.getName() + "Impl_Stub";
private static final Class rmiServerImplStubClass;
private static final String rmiConnectionImplStubClassName =
RMIConnection.class.getName() + "Impl_Stub";
private static final Class<?> rmiConnectionImplStubClass;
private static final String pRefClassName =
"com.sun.jmx.remote.internal.PRef";
private static final Constructor proxyRefConstructor;
static {
final String pRefByteCodeString =
"\312\376\272\276\0\0\0.\0\27\12\0\5\0\15\11\0\4\0\16\13\0\17\0"+
"\20\7\0\21\7\0\22\1\0\6<init>\1\0\36(Ljava/rmi/server/RemoteRef;"+
")V\1\0\4Code\1\0\6invoke\1\0S(Ljava/rmi/Remote;Ljava/lang/reflec"+
"t/Method;[Ljava/lang/Object;J)Ljava/lang/Object;\1\0\12Exception"+
"s\7\0\23\14\0\6\0\7\14\0\24\0\25\7\0\26\14\0\11\0\12\1\0\40com/"+
"sun/jmx/remote/internal/PRef\1\0$com/sun/jmx/remote/internal/Pr"+
"oxyRef\1\0\23java/lang/Exception\1\0\3ref\1\0\33Ljava/rmi/serve"+
"r/RemoteRef;\1\0\31java/rmi/server/RemoteRef\0!\0\4\0\5\0\0\0\0"+
"\0\2\0\1\0\6\0\7\0\1\0\10\0\0\0\22\0\2\0\2\0\0\0\6*+\267\0\1\261"+
"\0\0\0\0\0\1\0\11\0\12\0\2\0\10\0\0\0\33\0\6\0\6\0\0\0\17*\264\0"+
"\2+,-\26\4\271\0\3\6\0\260\0\0\0\0\0\13\0\0\0\4\0\1\0\14\0\0";
final byte[] pRefByteCode =
NoCallStackClassLoader.stringToBytes(pRefByteCodeString);
PrivilegedExceptionAction<Constructor<?>> action =
new PrivilegedExceptionAction<Constructor<?>>() {
public Constructor<?> run() throws Exception {
Class thisClass = RMIConnector.class;
ClassLoader thisLoader = thisClass.getClassLoader();
ProtectionDomain thisProtectionDomain =
thisClass.getProtectionDomain();
String[] otherClassNames = {ProxyRef.class.getName()};
ClassLoader cl =
new NoCallStackClassLoader(pRefClassName,
pRefByteCode,
otherClassNames,
thisLoader,
thisProtectionDomain);
Class<?> c = cl.loadClass(pRefClassName);
return c.getConstructor(RemoteRef.class);
}
};
Class serverStubClass;
try {
serverStubClass = Class.forName(rmiServerImplStubClassName);
} catch (Exception e) {
logger.error("<clinit>",
"Failed to instantiate " +
rmiServerImplStubClassName + ": " + e);
logger.debug("<clinit>",e);
serverStubClass = null;
}
rmiServerImplStubClass = serverStubClass;
Class<?> stubClass;
Constructor constr;
try {
stubClass = Class.forName(rmiConnectionImplStubClassName);
constr = (Constructor) AccessController.doPrivileged(action);
} catch (Exception e) {
logger.error("<clinit>",
"Failed to initialize proxy reference constructor "+
"for " + rmiConnectionImplStubClassName + ": " + e);
logger.debug("<clinit>",e);
stubClass = null;
constr = null;
}
rmiConnectionImplStubClass = stubClass;
proxyRefConstructor = constr;
}
private static RMIConnection shadowJrmpStub(RemoteObject stub)
throws InstantiationException, IllegalAccessException,
InvocationTargetException, ClassNotFoundException,
NoSuchMethodException {
RemoteRef ref = stub.getRef();
RemoteRef proxyRef = (RemoteRef)
proxyRefConstructor.newInstance(new Object[] {ref});
final Class[] constrTypes = {RemoteRef.class};
final Constructor rmiConnectionImplStubConstructor =
rmiConnectionImplStubClass.getConstructor(constrTypes);
Object[] args = {proxyRef};
RMIConnection proxyStub = (RMIConnection)
rmiConnectionImplStubConstructor.newInstance(args);
return proxyStub;
}
/*
The following code performs a similar trick for RMI/IIOP to the
one described above for RMI/JRMP. Unlike JRMP, though, we
can't easily insert an object between the RMIConnection stub
and the RMI/IIOP deserialization code, as explained below.
A method in an RMI/IIOP stub does the following. It makes an
org.omg.CORBA_2_3.portable.OutputStream for each request, and
writes the parameters to it. Then it calls
_invoke(OutputStream) which it inherits from CORBA's
ObjectImpl. That returns an
org.omg.CORBA_2_3.portable.InputStream. The return value is
read from this InputStream. So the stack during
deserialization looks like this:
MBeanServerConnection.getAttribute (or whatever)
-> _RMIConnection_Stub.getAttribute
-> Util.readAny (a CORBA method)
-> InputStream.read_any
-> internal CORBA stuff
What we would have *liked* to have done would be the same thing
as for RMI/JRMP. We create a "ProxyDelegate" that is an
org.omg.CORBA.portable.Delegate that simply forwards every
operation to the real original Delegate from the RMIConnection
stub, except that the InputStream returned by _invoke is
wrapped by a "ProxyInputStream" that is loaded by our
NoCallStackClassLoader.
Unfortunately, this doesn't work, at least with Sun's J2SE
1.4.2, because the CORBA code is not designed to allow you to
change Delegates arbitrarily. You get a ClassCastException
from code that expects the Delegate to implement an internal
interface.
So instead we do the following. We create a subclass of the
stub that overrides the _invoke method so as to wrap the
returned InputStream in a ProxyInputStream. We create a
subclass of ProxyInputStream using the NoCallStackClassLoader
and override its read_any and read_value(Class) methods.
(These are the only methods called during deserialization of
MBeanServerConnection return values.) We extract the Delegate
from the original stub and insert it into our subclass stub,
and away we go. The state of a stub consists solely of its
Delegate.
We also need to catch ApplicationException, which will encode
any exceptions declared in the throws clause of the called
method. Its InputStream needs to be wrapped in a
ProxyInputSteam too.
We override _releaseReply in the stub subclass so that it
replaces a ProxyInputStream argument with the original
InputStream. This avoids problems if the implementation of
_releaseReply ends up casting this InputStream to an
implementation-specific interface (which in Sun's J2SE 5 it
does).
It is not strictly necessary for the stub subclass to be loaded
by a NoCallStackClassLoader, since the call-stack search stops
at the ProxyInputStream subclass. However, it is convenient
for two reasons. One is that it means that the
ProxyInputStream subclass can be accessed directly, without
using reflection. The other is that it avoids build problems,
since usually stubs are created after other classes are
compiled, so we can't access them from this class without,
again, using reflection.
The strings below encode the following two Java classes,
compiled using J2SE 1.4.2 with javac -g:none.
package com.sun.jmx.remote.internal;
import org.omg.stub.javax.management.remote.rmi._RMIConnection_Stub;
import org.omg.CORBA.portable.ApplicationException;
import org.omg.CORBA.portable.InputStream;
import org.omg.CORBA.portable.OutputStream;
import org.omg.CORBA.portable.RemarshalException;
public class ProxyStub extends _RMIConnection_Stub {
public InputStream _invoke(OutputStream out)
throws ApplicationException, RemarshalException {
try {
return new PInputStream(super._invoke(out));
} catch (ApplicationException e) {
InputStream pis = new PInputStream(e.getInputStream());
throw new ApplicationException(e.getId(), pis);
}
}
public void _releaseReply(InputStream in) {
PInputStream pis = (PInputStream) in;
super._releaseReply(pis.getProxiedInputStream());
}
}
package com.sun.jmx.remote.internal;
public class PInputStream extends ProxyInputStream {
public PInputStream(org.omg.CORBA.portable.InputStream in) {
super(in);
}
public org.omg.CORBA.Any read_any() {
return in.read_any();
}
public java.io.Serializable read_value(Class clz) {
return narrow().read_value(clz);
}
}
*/
private static final String iiopConnectionStubClassName =
"org.omg.stub.javax.management.remote.rmi._RMIConnection_Stub";
private static final String proxyStubClassName =
"com.sun.jmx.remote.internal.ProxyStub";
private static final String pInputStreamClassName =
"com.sun.jmx.remote.internal.PInputStream";
private static final Class proxyStubClass;
static {
final String proxyStubByteCodeString =
"\312\376\272\276\0\0\0.\0)\12\0\14\0\26\7\0\27\12\0\14\0\30\12"+
"\0\2\0\31\7\0\32\12\0\5\0\33\12\0\5\0\34\12\0\5\0\35\12\0\2\0"+
"\36\12\0\14\0\37\7\0\40\7\0!\1\0\6<init>\1\0\3()V\1\0\4Code\1"+
"\0\7_invoke\1\0K(Lorg/omg/CORBA/portable/OutputStream;)Lorg/o"+
"mg/CORBA/portable/InputStream;\1\0\12Exceptions\7\0\"\1\0\15_"+
"releaseReply\1\0'(Lorg/omg/CORBA/portable/InputStream;)V\14\0"+
"\15\0\16\1\0(com/sun/jmx/remote/internal/PInputStream\14\0\20"+
"\0\21\14\0\15\0\25\1\0+org/omg/CORBA/portable/ApplicationExce"+
"ption\14\0#\0$\14\0%\0&\14\0\15\0'\14\0(\0$\14\0\24\0\25\1\0%"+
"com/sun/jmx/remote/internal/ProxyStub\1\0<org/omg/stub/javax/"+
"management/remote/rmi/_RMIConnection_Stub\1\0)org/omg/CORBA/p"+
"ortable/RemarshalException\1\0\16getInputStream\1\0&()Lorg/om"+
"g/CORBA/portable/InputStream;\1\0\5getId\1\0\24()Ljava/lang/S"+
"tring;\1\09(Ljava/lang/String;Lorg/omg/CORBA/portable/InputSt"+
"ream;)V\1\0\25getProxiedInputStream\0!\0\13\0\14\0\0\0\0\0\3\0"+
"\1\0\15\0\16\0\1\0\17\0\0\0\21\0\1\0\1\0\0\0\5*\267\0\1\261\0"+
"\0\0\0\0\1\0\20\0\21\0\2\0\17\0\0\0;\0\4\0\4\0\0\0'\273\0\2Y*"+
"+\267\0\3\267\0\4\260M\273\0\2Y,\266\0\6\267\0\4N\273\0\5Y,\266"+
"\0\7-\267\0\10\277\0\1\0\0\0\14\0\15\0\5\0\0\0\22\0\0\0\6\0\2"+
"\0\5\0\23\0\1\0\24\0\25\0\1\0\17\0\0\0\36\0\2\0\2\0\0\0\22+\306"+
"\0\13+\300\0\2\266\0\11L*+\267\0\12\261\0\0\0\0\0\0";
final String pInputStreamByteCodeString =
"\312\376\272\276\0\0\0.\0\36\12\0\7\0\17\11\0\6\0\20\12\0\21\0"+
"\22\12\0\6\0\23\12\0\24\0\25\7\0\26\7\0\27\1\0\6<init>\1\0'(L"+
"org/omg/CORBA/portable/InputStream;)V\1\0\4Code\1\0\10read_an"+
"y\1\0\25()Lorg/omg/CORBA/Any;\1\0\12read_value\1\0)(Ljava/lan"+
"g/Class;)Ljava/io/Serializable;\14\0\10\0\11\14\0\30\0\31\7\0"+
"\32\14\0\13\0\14\14\0\33\0\34\7\0\35\14\0\15\0\16\1\0(com/sun"+
"/jmx/remote/internal/PInputStream\1\0,com/sun/jmx/remote/inte"+
"rnal/ProxyInputStream\1\0\2in\1\0$Lorg/omg/CORBA/portable/Inp"+
"utStream;\1\0\"org/omg/CORBA/portable/InputStream\1\0\6narrow"+
"\1\0*()Lorg/omg/CORBA_2_3/portable/InputStream;\1\0&org/omg/C"+
"ORBA_2_3/portable/InputStream\0!\0\6\0\7\0\0\0\0\0\3\0\1\0\10"+
"\0\11\0\1\0\12\0\0\0\22\0\2\0\2\0\0\0\6*+\267\0\1\261\0\0\0\0"+
"\0\1\0\13\0\14\0\1\0\12\0\0\0\24\0\1\0\1\0\0\0\10*\264\0\2\266"+
"\0\3\260\0\0\0\0\0\1\0\15\0\16\0\1\0\12\0\0\0\25\0\2\0\2\0\0\0"+
"\11*\266\0\4+\266\0\5\260\0\0\0\0\0\0";
final byte[] proxyStubByteCode =
NoCallStackClassLoader.stringToBytes(proxyStubByteCodeString);
final byte[] pInputStreamByteCode =
NoCallStackClassLoader.stringToBytes(pInputStreamByteCodeString);
final String[] classNames={proxyStubClassName, pInputStreamClassName};
final byte[][] byteCodes = {proxyStubByteCode, pInputStreamByteCode};
final String[] otherClassNames = {
iiopConnectionStubClassName,
ProxyInputStream.class.getName(),
};
PrivilegedExceptionAction<Class<?>> action =
new PrivilegedExceptionAction<Class<?>>() {
public Class<?> run() throws Exception {
Class thisClass = RMIConnector.class;
ClassLoader thisLoader = thisClass.getClassLoader();
ProtectionDomain thisProtectionDomain =
thisClass.getProtectionDomain();
ClassLoader cl =
new NoCallStackClassLoader(classNames,
byteCodes,
otherClassNames,
thisLoader,
thisProtectionDomain);
return cl.loadClass(proxyStubClassName);
}
};
Class<?> stubClass;
try {
stubClass = AccessController.doPrivileged(action);
} catch (Exception e) {
logger.error("<clinit>",
"Unexpected exception making shadow IIOP stub class: "+e);
logger.debug("<clinit>",e);
stubClass = null;
}
proxyStubClass = stubClass;
}
private static RMIConnection shadowIiopStub(Stub stub)
throws InstantiationException, IllegalAccessException {
Stub proxyStub = (Stub) proxyStubClass.newInstance();
proxyStub._set_delegate(stub._get_delegate());
return (RMIConnection) proxyStub;
}
private static RMIConnection getConnection(RMIServer server,
Object credentials,
boolean checkStub)
throws IOException {
RMIConnection c = server.newClient(credentials);
if (checkStub) checkStub(c, rmiConnectionImplStubClass);
try {
if (c.getClass() == rmiConnectionImplStubClass)
return shadowJrmpStub((RemoteObject) c);
if (c.getClass().getName().equals(iiopConnectionStubClassName))
return shadowIiopStub((Stub) c);
logger.trace("getConnection",
"Did not wrap " + c.getClass() + " to foil " +
"stack search for classes: class loading semantics " +
"may be incorrect");
} catch (Exception e) {
logger.error("getConnection",
"Could not wrap " + c.getClass() + " to foil " +
"stack search for classes: class loading semantics " +
"may be incorrect: " + e);
logger.debug("getConnection",e);
// so just return the original stub, which will work for all
// but the most exotic class loading situations
}
return c;
}
private static byte[] base64ToByteArray(String s) {
int sLen = s.length();
int numGroups = sLen/4;
if (4*numGroups != sLen)
throw new IllegalArgumentException(
"String length must be a multiple of four.");
int missingBytesInLastGroup = 0;
int numFullGroups = numGroups;
if (sLen != 0) {
if (s.charAt(sLen-1) == '=') {
missingBytesInLastGroup++;
numFullGroups--;
}
if (s.charAt(sLen-2) == '=')
missingBytesInLastGroup++;
}
byte[] result = new byte[3*numGroups - missingBytesInLastGroup];
// Translate all full groups from base64 to byte array elements
int inCursor = 0, outCursor = 0;
for (int i=0; i<numFullGroups; i++) {
int ch0 = base64toInt(s.charAt(inCursor++));
int ch1 = base64toInt(s.charAt(inCursor++));
int ch2 = base64toInt(s.charAt(inCursor++));
int ch3 = base64toInt(s.charAt(inCursor++));
result[outCursor++] = (byte) ((ch0 << 2) | (ch1 >> 4));
result[outCursor++] = (byte) ((ch1 << 4) | (ch2 >> 2));
result[outCursor++] = (byte) ((ch2 << 6) | ch3);
}
// Translate partial group, if present
if (missingBytesInLastGroup != 0) {
int ch0 = base64toInt(s.charAt(inCursor++));
int ch1 = base64toInt(s.charAt(inCursor++));
result[outCursor++] = (byte) ((ch0 << 2) | (ch1 >> 4));
if (missingBytesInLastGroup == 1) {
int ch2 = base64toInt(s.charAt(inCursor++));
result[outCursor++] = (byte) ((ch1 << 4) | (ch2 >> 2));
}
}
// assert inCursor == s.length()-missingBytesInLastGroup;
// assert outCursor == result.length;
return result;
}
/** {@collect.stats}
* Translates the specified character, which is assumed to be in the
* "Base 64 Alphabet" into its equivalent 6-bit positive integer.
*
* @throws IllegalArgumentException if
* c is not in the Base64 Alphabet.
*/
private static int base64toInt(char c) {
int result;
if (c >= base64ToInt.length)
result = -1;
else
result = base64ToInt[c];
if (result < 0)
throw new IllegalArgumentException("Illegal character " + c);
return result;
}
/** {@collect.stats}
* This array is a lookup table that translates unicode characters
* drawn from the "Base64 Alphabet" (as specified in Table 1 of RFC 2045)
* into their 6-bit positive integer equivalents. Characters that
* are not in the Base64 alphabet but fall within the bounds of the
* array are translated to -1.
*/
private static final byte base64ToInt[] = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54,
55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4,
5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34,
35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51
};
//--------------------------------------------------------------------
// Private stuff - Find / Set default class loader
//--------------------------------------------------------------------
private ClassLoader pushDefaultClassLoader() {
final Thread t = Thread.currentThread();
final ClassLoader old = t.getContextClassLoader();
if (defaultClassLoader != null)
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
t.setContextClassLoader(defaultClassLoader);
return null;
}
});
return old;
}
private void popDefaultClassLoader(final ClassLoader old) {
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
Thread.currentThread().setContextClassLoader(old);
return null;
}
});
}
//--------------------------------------------------------------------
// Private variables
//--------------------------------------------------------------------
/** {@collect.stats}
* @serial The RMIServer stub of the RMI JMX Connector server to
* which this client connector is (or will be) connected. This
* field can be null when <var>jmxServiceURL</var> is not
* null. This includes the case where <var>jmxServiceURL</var>
* contains a serialized RMIServer stub. If both
* <var>rmiServer</var> and <var>jmxServiceURL</var> are null then
* serialization will fail.
*
* @see #RMIConnector(RMIServer,Map)
**/
private final RMIServer rmiServer;
/** {@collect.stats}
* @serial The JMXServiceURL of the RMI JMX Connector server to
* which this client connector will be connected. This field can
* be null when <var>rmiServer</var> is not null. If both
* <var>rmiServer</var> and <var>jmxServiceURL</var> are null then
* serialization will fail.
*
* @see #RMIConnector(JMXServiceURL,Map)
**/
private final JMXServiceURL jmxServiceURL;
// ---------------------------------------------------------
// WARNING - WARNING - WARNING - WARNING - WARNING - WARNING
// ---------------------------------------------------------
// Any transient variable which needs to be initialized should
// be initialized in the method initTransient()
private transient Map<String, Object> env;
private transient ClassLoader defaultClassLoader;
private transient RMIConnection connection;
private transient String connectionId;
private transient long clientNotifSeqNo = 0;
private transient WeakHashMap<Subject, MBeanServerConnection> rmbscMap;
private transient RMINotifClient rmiNotifClient;
// = new RMINotifClient(new Integer(0));
private transient long clientNotifCounter = 0;
private transient boolean connected;
// = false;
private transient boolean terminated;
// = false;
private transient Exception closeException;
private transient NotificationBroadcasterSupport connectionBroadcaster;
private transient ClientCommunicatorAdmin communicatorAdmin;
/** {@collect.stats}
* A static WeakReference to an {@link org.omg.CORBA.ORB ORB} to
* connect unconnected stubs.
**/
private static WeakReference<ORB> orb = null;
// TRACES & DEBUG
//---------------
private static String objects(final Object[] objs) {
if (objs == null)
return "null";
else
return Arrays.asList(objs).toString();
}
private static String strings(final String[] strs) {
return objects(strs);
}
}
| Java |
/*
* Copyright (c) 2002, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management.remote.rmi;
import com.sun.jmx.remote.security.MBeanServerFileAccessController;
import com.sun.jmx.remote.util.ClassLogger;
import com.sun.jmx.remote.util.EnvHelp;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.MalformedURLException;
import java.rmi.server.RMIClientSocketFactory;
import java.rmi.server.RMIServerSocketFactory;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Map;
import java.util.Set;
import javax.management.InstanceNotFoundException;
import javax.management.MBeanServer;
import javax.management.remote.JMXConnectionNotification;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorServer;
import javax.management.remote.JMXServiceURL;
import javax.management.remote.MBeanServerForwarder;
import javax.naming.InitialContext;
import javax.naming.NamingException;
/** {@collect.stats}
* <p>A JMX API connector server that creates RMI-based connections
* from remote clients. Usually, such connector servers are made
* using {@link javax.management.remote.JMXConnectorServerFactory
* JMXConnectorServerFactory}. However, specialized applications can
* use this class directly, for example with an {@link RMIServerImpl}
* object.</p>
*
* @since 1.5
*/
public class RMIConnectorServer extends JMXConnectorServer {
/** {@collect.stats}
* <p>Name of the attribute that specifies whether the {@link
* RMIServer} stub that represents an RMI connector server should
* override an existing stub at the same address. The value
* associated with this attribute, if any, should be a string that
* is equal, ignoring case, to <code>"true"</code> or
* <code>"false"</code>. The default value is false.</p>
*/
public static final String JNDI_REBIND_ATTRIBUTE =
"jmx.remote.jndi.rebind";
/** {@collect.stats}
* <p>Name of the attribute that specifies the {@link
* RMIClientSocketFactory} for the RMI objects created in
* conjunction with this connector. The value associated with this
* attribute must be of type <code>RMIClientSocketFactory</code> and can
* only be specified in the <code>Map</code> argument supplied when
* creating a connector server.</p>
*/
public static final String RMI_CLIENT_SOCKET_FACTORY_ATTRIBUTE =
"jmx.remote.rmi.client.socket.factory";
/** {@collect.stats}
* <p>Name of the attribute that specifies the {@link
* RMIServerSocketFactory} for the RMI objects created in
* conjunction with this connector. The value associated with this
* attribute must be of type <code>RMIServerSocketFactory</code> and can
* only be specified in the <code>Map</code> argument supplied when
* creating a connector server.</p>
*/
public static final String RMI_SERVER_SOCKET_FACTORY_ATTRIBUTE =
"jmx.remote.rmi.server.socket.factory";
/** {@collect.stats}
* <p>Makes an <code>RMIConnectorServer</code>.
* This is equivalent to calling {@link #RMIConnectorServer(
* JMXServiceURL,Map,RMIServerImpl,MBeanServer)
* RMIConnectorServer(directoryURL,environment,null,null)}</p>
*
* @param url the URL defining how to create the connector server.
* Cannot be null.
*
* @param environment attributes governing the creation and
* storing of the RMI object. Can be null, which is equivalent to
* an empty Map.
*
* @exception IllegalArgumentException if <code>url</code> is null.
*
* @exception MalformedURLException if <code>url</code> does not
* conform to the syntax for an RMI connector, or if its protocol
* is not recognized by this implementation. Only "rmi" and "iiop"
* are valid when this constructor is used.
*
* @exception IOException if the connector server cannot be created
* for some reason or if it is inevitable that its {@link #start()
* start} method will fail.
*/
public RMIConnectorServer(JMXServiceURL url, Map<String,?> environment)
throws IOException {
this(url, environment, (MBeanServer) null);
}
/** {@collect.stats}
* <p>Makes an <code>RMIConnectorServer</code> for the given MBean
* server.
* This is equivalent to calling {@link #RMIConnectorServer(
* JMXServiceURL,Map,RMIServerImpl,MBeanServer)
* RMIConnectorServer(directoryURL,environment,null,mbeanServer)}</p>
*
* @param url the URL defining how to create the connector server.
* Cannot be null.
*
* @param environment attributes governing the creation and
* storing of the RMI object. Can be null, which is equivalent to
* an empty Map.
*
* @param mbeanServer the MBean server to which the new connector
* server is attached, or null if it will be attached by being
* registered as an MBean in the MBean server.
*
* @exception IllegalArgumentException if <code>url</code> is null.
*
* @exception MalformedURLException if <code>url</code> does not
* conform to the syntax for an RMI connector, or if its protocol
* is not recognized by this implementation. Only "rmi" and "iiop"
* are valid when this constructor is used.
*
* @exception IOException if the connector server cannot be created
* for some reason or if it is inevitable that its {@link #start()
* start} method will fail.
*/
public RMIConnectorServer(JMXServiceURL url, Map<String,?> environment,
MBeanServer mbeanServer)
throws IOException {
this(url, environment, (RMIServerImpl) null, mbeanServer);
}
/** {@collect.stats}
* <p>Makes an <code>RMIConnectorServer</code> for the given MBean
* server.</p>
*
* @param url the URL defining how to create the connector server.
* Cannot be null.
*
* @param environment attributes governing the creation and
* storing of the RMI object. Can be null, which is equivalent to
* an empty Map.
*
* @param rmiServerImpl An implementation of the RMIServer interface,
* consistent with the protocol type specified in <var>url</var>.
* If this parameter is non null, the protocol type specified by
* <var>url</var> is not constrained, and is assumed to be valid.
* Otherwise, only "rmi" and "iiop" will be recognized.
*
* @param mbeanServer the MBean server to which the new connector
* server is attached, or null if it will be attached by being
* registered as an MBean in the MBean server.
*
* @exception IllegalArgumentException if <code>url</code> is null.
*
* @exception MalformedURLException if <code>url</code> does not
* conform to the syntax for an RMI connector, or if its protocol
* is not recognized by this implementation. Only "rmi" and "iiop"
* are recognized when <var>rmiServerImpl</var> is null.
*
* @exception IOException if the connector server cannot be created
* for some reason or if it is inevitable that its {@link #start()
* start} method will fail.
*
* @see #start
*/
public RMIConnectorServer(JMXServiceURL url, Map<String,?> environment,
RMIServerImpl rmiServerImpl,
MBeanServer mbeanServer)
throws IOException {
super(mbeanServer);
if (url == null) throw new
IllegalArgumentException("Null JMXServiceURL");
if (rmiServerImpl == null) {
final String prt = url.getProtocol();
if (prt == null || !(prt.equals("rmi") || prt.equals("iiop"))) {
final String msg = "Invalid protocol type: " + prt;
throw new MalformedURLException(msg);
}
final String urlPath = url.getURLPath();
if (!urlPath.equals("")
&& !urlPath.equals("/")
&& !urlPath.startsWith("/jndi/")) {
final String msg = "URL path must be empty or start with " +
"/jndi/";
throw new MalformedURLException(msg);
}
}
if (environment == null)
this.attributes = Collections.emptyMap();
else {
EnvHelp.checkAttributes(environment);
this.attributes = Collections.unmodifiableMap(environment);
}
this.address = url;
this.rmiServerImpl = rmiServerImpl;
}
/** {@collect.stats}
* <p>Returns a client stub for this connector server. A client
* stub is a serializable object whose {@link
* JMXConnector#connect(Map) connect} method can be used to make
* one new connection to this connector server.</p>
*
* @param env client connection parameters of the same sort that
* could be provided to {@link JMXConnector#connect(Map)
* JMXConnector.connect(Map)}. Can be null, which is equivalent
* to an empty map.
*
* @return a client stub that can be used to make a new connection
* to this connector server.
*
* @exception UnsupportedOperationException if this connector
* server does not support the generation of client stubs.
*
* @exception IllegalStateException if the JMXConnectorServer is
* not started (see {@link #isActive()}).
*
* @exception IOException if a communications problem means that a
* stub cannot be created.
**/
public JMXConnector toJMXConnector(Map<String,?> env) throws IOException {
// The serialized for of rmiServerImpl is automatically
// a RMI server stub.
if (!isActive()) throw new
IllegalStateException("Connector is not active");
// Merge maps
Map<String, Object> usemap = new HashMap<String, Object>(
(this.attributes==null)?Collections.<String, Object>emptyMap():
this.attributes);
if (env != null) {
EnvHelp.checkAttributes(env);
usemap.putAll(env);
}
usemap = EnvHelp.filterAttributes(usemap);
final RMIServer stub=(RMIServer)rmiServerImpl.toStub();
return new RMIConnector(stub, usemap);
}
/** {@collect.stats}
* <p>Activates the connector server, that is starts listening for
* client connections. Calling this method when the connector
* server is already active has no effect. Calling this method
* when the connector server has been stopped will generate an
* <code>IOException</code>.</p>
*
* <p>The behavior of this method when called for the first time
* depends on the parameters that were supplied at construction,
* as described below.</p>
*
* <p>First, an object of a subclass of {@link RMIServerImpl} is
* required, to export the connector server through RMI:</p>
*
* <ul>
*
* <li>If an <code>RMIServerImpl</code> was supplied to the
* constructor, it is used.
*
* <li>Otherwise, if the protocol part of the
* <code>JMXServiceURL</code> supplied to the constructor was
* <code>iiop</code>, an object of type {@link RMIIIOPServerImpl}
* is created.
*
* <li>Otherwise, if the <code>JMXServiceURL</code>
* was null, or its protocol part was <code>rmi</code>, an object
* of type {@link RMIJRMPServerImpl} is created.
*
* <li>Otherwise, the implementation can create an
* implementation-specific {@link RMIServerImpl} or it can throw
* {@link MalformedURLException}.
*
* </ul>
*
* <p>If the given address includes a JNDI directory URL as
* specified in the package documentation for {@link
* javax.management.remote.rmi}, then this
* <code>RMIConnectorServer</code> will bootstrap by binding the
* <code>RMIServerImpl</code> to the given address.</p>
*
* <p>If the URL path part of the <code>JMXServiceURL</code> was
* empty or a single slash (<code>/</code>), then the RMI object
* will not be bound to a directory. Instead, a reference to it
* will be encoded in the URL path of the RMIConnectorServer
* address (returned by {@link #getAddress()}). The encodings for
* <code>rmi</code> and <code>iiop</code> are described in the
* package documentation for {@link
* javax.management.remote.rmi}.</p>
*
* <p>The behavior when the URL path is neither empty nor a JNDI
* directory URL, or when the protocol is neither <code>rmi</code>
* nor <code>iiop</code>, is implementation defined, and may
* include throwing {@link MalformedURLException} when the
* connector server is created or when it is started.</p>
*
* @exception IllegalStateException if the connector server has
* not been attached to an MBean server.
* @exception IOException if the connector server cannot be
* started.
*/
public synchronized void start() throws IOException {
final boolean tracing = logger.traceOn();
if (state == STARTED) {
if (tracing) logger.trace("start", "already started");
return;
} else if (state == STOPPED) {
if (tracing) logger.trace("start", "already stopped");
throw new IOException("The server has been stopped.");
}
if (getMBeanServer() == null)
throw new IllegalStateException("This connector server is not " +
"attached to an MBean server");
// Check the internal access file property to see
// if an MBeanServerForwarder is to be provided
//
if (attributes != null) {
// Check if access file property is specified
//
String accessFile =
(String) attributes.get("jmx.remote.x.access.file");
if (accessFile != null) {
// Access file property specified, create an instance
// of the MBeanServerFileAccessController class
//
MBeanServerForwarder mbsf = null;
try {
mbsf = new MBeanServerFileAccessController(accessFile);
} catch (IOException e) {
throw EnvHelp.initCause(
new IllegalArgumentException(e.getMessage()), e);
}
// Set the MBeanServerForwarder
//
setMBeanServerForwarder(mbsf);
}
}
try {
if (tracing) logger.trace("start", "setting default class loader");
defaultClassLoader =
EnvHelp.resolveServerClassLoader(attributes, getMBeanServer());
} catch (InstanceNotFoundException infc) {
IllegalArgumentException x = new
IllegalArgumentException("ClassLoader not found: "+infc);
throw EnvHelp.initCause(x,infc);
}
if (tracing) logger.trace("start", "setting RMIServer object");
final RMIServerImpl rmiServer;
if (rmiServerImpl != null)
rmiServer = rmiServerImpl;
else
rmiServer = newServer();
rmiServer.setMBeanServer(getMBeanServer());
rmiServer.setDefaultClassLoader(defaultClassLoader);
rmiServer.setRMIConnectorServer(this);
rmiServer.export();
try {
if (tracing) logger.trace("start", "getting RMIServer object to export");
final RMIServer objref = objectToBind(rmiServer, attributes);
if (address != null && address.getURLPath().startsWith("/jndi/")) {
final String jndiUrl = address.getURLPath().substring(6);
if (tracing)
logger.trace("start", "Using external directory: " + jndiUrl);
final boolean rebind = EnvHelp.computeBooleanFromString(
attributes,
JNDI_REBIND_ATTRIBUTE);
if (tracing)
logger.trace("start", JNDI_REBIND_ATTRIBUTE + "=" + rebind);
try {
if (tracing) logger.trace("start", "binding to " + jndiUrl);
final Hashtable usemap = EnvHelp.mapToHashtable(attributes);
bind(jndiUrl, usemap, objref, rebind);
boundJndiUrl = jndiUrl;
} catch (NamingException e) {
// fit e in the nested exception if we are on 1.4
throw newIOException("Cannot bind to URL ["+jndiUrl+"]: "
+ e, e);
}
} else {
// if jndiURL is null, we must encode the stub into the URL.
if (tracing) logger.trace("start", "Encoding URL");
encodeStubInAddress(objref, attributes);
if (tracing) logger.trace("start", "Encoded URL: " + this.address);
}
} catch (Exception e) {
try {
rmiServer.close();
} catch (Exception x) {
// OK: we are already throwing another exception
}
if (e instanceof RuntimeException)
throw (RuntimeException) e;
else if (e instanceof IOException)
throw (IOException) e;
else
throw newIOException("Got unexpected exception while " +
"starting the connector server: "
+ e, e);
}
rmiServerImpl = rmiServer;
synchronized(openedServers) {
openedServers.add(this);
}
state = STARTED;
if (tracing) {
logger.trace("start", "Connector Server Address = " + address);
logger.trace("start", "started.");
}
}
/** {@collect.stats}
* <p>Deactivates the connector server, that is, stops listening for
* client connections. Calling this method will also close all
* client connections that were made by this server. After this
* method returns, whether normally or with an exception, the
* connector server will not create any new client
* connections.</p>
*
* <p>Once a connector server has been stopped, it cannot be started
* again.</p>
*
* <p>Calling this method when the connector server has already
* been stopped has no effect. Calling this method when the
* connector server has not yet been started will disable the
* connector server object permanently.</p>
*
* <p>If closing a client connection produces an exception, that
* exception is not thrown from this method. A {@link
* JMXConnectionNotification} is emitted from this MBean with the
* connection ID of the connection that could not be closed.</p>
*
* <p>Closing a connector server is a potentially slow operation.
* For example, if a client machine with an open connection has
* crashed, the close operation might have to wait for a network
* protocol timeout. Callers that do not want to block in a close
* operation should do it in a separate thread.</p>
*
* <p>This method calls the method {@link RMIServerImpl#close()
* close} on the connector server's <code>RMIServerImpl</code>
* object.</p>
*
* <p>If the <code>RMIServerImpl</code> was bound to a JNDI
* directory by the {@link #start() start} method, it is unbound
* from the directory by this method.</p>
*
* @exception IOException if the server cannot be closed cleanly,
* or if the <code>RMIServerImpl</code> cannot be unbound from the
* directory. When this exception is thrown, the server has
* already attempted to close all client connections, if
* appropriate; to call {@link RMIServerImpl#close()}; and to
* unbind the <code>RMIServerImpl</code> from its directory, if
* appropriate. All client connections are closed except possibly
* those that generated exceptions when the server attempted to
* close them.
*/
public void stop() throws IOException {
final boolean tracing = logger.traceOn();
synchronized (this) {
if (state == STOPPED) {
if (tracing) logger.trace("stop","already stopped.");
return;
} else if (state == CREATED) {
if (tracing) logger.trace("stop","not started yet.");
}
if (tracing) logger.trace("stop", "stopping.");
state = STOPPED;
}
synchronized(openedServers) {
openedServers.remove(this);
}
IOException exception = null;
// rmiServerImpl can be null if stop() called without start()
if (rmiServerImpl != null) {
try {
if (tracing) logger.trace("stop", "closing RMI server.");
rmiServerImpl.close();
} catch (IOException e) {
if (tracing) logger.trace("stop", "failed to close RMI server: " + e);
if (logger.debugOn()) logger.debug("stop",e);
exception = e;
}
}
if (boundJndiUrl != null) {
try {
if (tracing)
logger.trace("stop",
"unbind from external directory: " + boundJndiUrl);
final Hashtable usemap = EnvHelp.mapToHashtable(attributes);
InitialContext ctx =
new InitialContext(usemap);
ctx.unbind(boundJndiUrl);
ctx.close();
} catch (NamingException e) {
if (tracing) logger.trace("stop", "failed to unbind RMI server: "+e);
if (logger.debugOn()) logger.debug("stop",e);
// fit e in as the nested exception if we are on 1.4
if (exception == null)
exception = newIOException("Cannot bind to URL: " + e, e);
}
}
if (exception != null) throw exception;
if (tracing) logger.trace("stop", "stopped");
}
public synchronized boolean isActive() {
return (state == STARTED);
}
public JMXServiceURL getAddress() {
if (!isActive())
return null;
return address;
}
public Map<String,?> getAttributes() {
Map<String, ?> map = EnvHelp.filterAttributes(attributes);
return Collections.unmodifiableMap(map);
}
public synchronized
void setMBeanServerForwarder(MBeanServerForwarder mbsf) {
super.setMBeanServerForwarder(mbsf);
if (rmiServerImpl != null)
rmiServerImpl.setMBeanServer(getMBeanServer());
}
/* We repeat the definitions of connection{Opened,Closed,Failed}
here so that they are accessible to other classes in this package
even though they have protected access. */
protected void connectionOpened(String connectionId, String message,
Object userData) {
super.connectionOpened(connectionId, message, userData);
}
protected void connectionClosed(String connectionId, String message,
Object userData) {
super.connectionClosed(connectionId, message, userData);
}
protected void connectionFailed(String connectionId, String message,
Object userData) {
super.connectionFailed(connectionId, message, userData);
}
/** {@collect.stats}
* Bind a stub to a registry.
* @param jndiUrl URL of the stub in the registry, extracted
* from the <code>JMXServiceURL</code>.
* @param attributes A Hashtable containing environment parameters,
* built from the Map specified at this object creation.
* @param rmiServer The object to bind in the registry
* @param rebind true if the object must be rebound.
**/
void bind(String jndiUrl, Hashtable attributes,
RMIServer rmiServer, boolean rebind)
throws NamingException, MalformedURLException {
// if jndiURL is not null, we nust bind the stub to a
// directory.
InitialContext ctx =
new InitialContext(attributes);
if (rebind)
ctx.rebind(jndiUrl, rmiServer);
else
ctx.bind(jndiUrl, rmiServer);
ctx.close();
}
/** {@collect.stats}
* Creates a new RMIServerImpl.
**/
RMIServerImpl newServer() throws IOException {
final boolean iiop = isIiopURL(address,true);
final int port;
if (address == null)
port = 0;
else
port = address.getPort();
if (iiop)
return newIIOPServer(attributes);
else
return newJRMPServer(attributes, port);
}
/** {@collect.stats}
* Encode a stub into the JMXServiceURL.
* @param rmiServer The stub object to encode in the URL
* @param attributes A Map containing environment parameters,
* built from the Map specified at this object creation.
**/
private void encodeStubInAddress(RMIServer rmiServer, Map attributes)
throws IOException {
final String protocol, host;
final int port;
if (address == null) {
if (rmiServer instanceof javax.rmi.CORBA.Stub)
protocol = "iiop";
else
protocol = "rmi";
host = null; // will default to local host name
port = 0;
} else {
protocol = address.getProtocol();
host = (address.getHost().equals("")) ? null : address.getHost();
port = address.getPort();
}
final String urlPath = encodeStub(rmiServer, attributes);
address = new JMXServiceURL(protocol, host, port, urlPath);
}
static boolean isIiopURL(JMXServiceURL directoryURL, boolean strict)
throws MalformedURLException {
String protocol = directoryURL.getProtocol();
if (protocol.equals("rmi"))
return false;
else if (protocol.equals("iiop"))
return true;
else if (strict) {
throw new MalformedURLException("URL must have protocol " +
"\"rmi\" or \"iiop\": \"" +
protocol + "\"");
}
return false;
}
/** {@collect.stats}
* Returns the IOR of the given rmiServer.
**/
static String encodeStub(RMIServer rmiServer, Map env) throws IOException {
if (rmiServer instanceof javax.rmi.CORBA.Stub)
return "/ior/" + encodeIIOPStub(rmiServer, env);
else
return "/stub/" + encodeJRMPStub(rmiServer, env);
}
static String encodeJRMPStub(RMIServer rmiServer, Map env)
throws IOException {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream oout = new ObjectOutputStream(bout);
oout.writeObject(rmiServer);
oout.close();
byte[] bytes = bout.toByteArray();
return byteArrayToBase64(bytes);
}
static String encodeIIOPStub(RMIServer rmiServer, Map env)
throws IOException {
try {
javax.rmi.CORBA.Stub stub =
(javax.rmi.CORBA.Stub) rmiServer;
return stub._orb().object_to_string(stub);
} catch (org.omg.CORBA.BAD_OPERATION x) {
throw newIOException(x.getMessage(), x);
}
}
/** {@collect.stats}
* Object that we will bind to the registry.
* This object is a stub connected to our RMIServerImpl.
**/
private static RMIServer objectToBind(RMIServerImpl rmiServer, Map env)
throws IOException {
return RMIConnector.
connectStub((RMIServer)rmiServer.toStub(),env);
}
private static RMIServerImpl newJRMPServer(Map<String, ?> env, int port)
throws IOException {
RMIClientSocketFactory csf = (RMIClientSocketFactory)
env.get(RMI_CLIENT_SOCKET_FACTORY_ATTRIBUTE);
RMIServerSocketFactory ssf = (RMIServerSocketFactory)
env.get(RMI_SERVER_SOCKET_FACTORY_ATTRIBUTE);
return new RMIJRMPServerImpl(port, csf, ssf, env);
}
private static RMIServerImpl newIIOPServer(Map<String, ?> env)
throws IOException {
return new RMIIIOPServerImpl(env);
}
private static String byteArrayToBase64(byte[] a) {
int aLen = a.length;
int numFullGroups = aLen/3;
int numBytesInPartialGroup = aLen - 3*numFullGroups;
int resultLen = 4*((aLen + 2)/3);
final StringBuilder result = new StringBuilder(resultLen);
// Translate all full groups from byte array elements to Base64
int inCursor = 0;
for (int i=0; i<numFullGroups; i++) {
int byte0 = a[inCursor++] & 0xff;
int byte1 = a[inCursor++] & 0xff;
int byte2 = a[inCursor++] & 0xff;
result.append(intToAlpha[byte0 >> 2]);
result.append(intToAlpha[(byte0 << 4)&0x3f | (byte1 >> 4)]);
result.append(intToAlpha[(byte1 << 2)&0x3f | (byte2 >> 6)]);
result.append(intToAlpha[byte2 & 0x3f]);
}
// Translate partial group if present
if (numBytesInPartialGroup != 0) {
int byte0 = a[inCursor++] & 0xff;
result.append(intToAlpha[byte0 >> 2]);
if (numBytesInPartialGroup == 1) {
result.append(intToAlpha[(byte0 << 4) & 0x3f]);
result.append("==");
} else {
// assert numBytesInPartialGroup == 2;
int byte1 = a[inCursor++] & 0xff;
result.append(intToAlpha[(byte0 << 4)&0x3f | (byte1 >> 4)]);
result.append(intToAlpha[(byte1 << 2)&0x3f]);
result.append('=');
}
}
// assert inCursor == a.length;
// assert result.length() == resultLen;
return result.toString();
}
/** {@collect.stats}
* This array is a lookup table that translates 6-bit positive integer
* index values into their "Base64 Alphabet" equivalents as specified
* in Table 1 of RFC 2045.
*/
private static final char intToAlpha[] = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'
};
/** {@collect.stats}
* Construct a new IOException with a nested exception.
* The nested exception is set only if JDK >= 1.4
*/
private static IOException newIOException(String message,
Throwable cause) {
final IOException x = new IOException(message);
return EnvHelp.initCause(x,cause);
}
// Private variables
// -----------------
private static ClassLogger logger =
new ClassLogger("javax.management.remote.rmi", "RMIConnectorServer");
private JMXServiceURL address;
private RMIServerImpl rmiServerImpl;
private final Map<String, ?> attributes;
private ClassLoader defaultClassLoader = null;
private String boundJndiUrl;
// state
private static final int CREATED = 0;
private static final int STARTED = 1;
private static final int STOPPED = 2;
private int state = CREATED;
private final static Set<RMIConnectorServer> openedServers =
new HashSet<RMIConnectorServer>();
}
| Java |
/*
* Copyright (c) 2002, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management.remote.rmi;
import java.io.IOException;
import java.rmi.NoSuchObjectException;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.server.RMIClientSocketFactory;
import java.rmi.server.RMIServerSocketFactory;
import java.rmi.server.UnicastRemoteObject;
import java.rmi.server.RemoteObject;
import java.util.Map;
import java.util.Collections;
import javax.security.auth.Subject;
import com.sun.jmx.remote.internal.RMIExporter;
/** {@collect.stats}
* <p>An {@link RMIServer} object that is exported through JRMP and that
* creates client connections as RMI objects exported through JRMP.
* User code does not usually reference this class directly.</p>
*
* @see RMIServerImpl
*
* @since 1.5
*/
public class RMIJRMPServerImpl extends RMIServerImpl {
/** {@collect.stats}
* <p>Creates a new {@link RMIServer} object that will be exported
* on the given port using the given socket factories.</p>
*
* @param port the port on which this object and the {@link
* RMIConnectionImpl} objects it creates will be exported. Can be
* zero, to indicate any available port.
*
* @param csf the client socket factory for the created RMI
* objects. Can be null.
*
* @param ssf the server socket factory for the created RMI
* objects. Can be null.
*
* @param env the environment map. Can be null.
*
* @exception IOException if the {@link RMIServer} object
* cannot be created.
*
* @exception IllegalArgumentException if <code>port</code> is
* negative.
*/
public RMIJRMPServerImpl(int port,
RMIClientSocketFactory csf,
RMIServerSocketFactory ssf,
Map<String,?> env)
throws IOException {
super(env);
if (port < 0)
throw new IllegalArgumentException("Negative port: " + port);
this.port = port;
this.csf = csf;
this.ssf = ssf;
this.env = (env == null) ? Collections.<String, Object>emptyMap() : env;
}
protected void export() throws IOException {
export(this);
}
private void export(Remote obj) throws RemoteException {
RMIExporter exporter =
(RMIExporter) env.get(RMIExporter.EXPORTER_ATTRIBUTE);
if (exporter == null)
UnicastRemoteObject.exportObject(obj, port, csf, ssf);
else
exporter.exportObject(obj, port, csf, ssf);
}
private void unexport(Remote obj, boolean force)
throws NoSuchObjectException {
RMIExporter exporter =
(RMIExporter) env.get(RMIExporter.EXPORTER_ATTRIBUTE);
if (exporter == null)
UnicastRemoteObject.unexportObject(obj, force);
else
exporter.unexportObject(obj, force);
}
protected String getProtocol() {
return "rmi";
}
/** {@collect.stats}
* <p>Returns a serializable stub for this {@link RMIServer} object.</p>
*
* @return a serializable stub.
*
* @exception IOException if the stub cannot be obtained - e.g the
* RMIJRMPServerImpl has not been exported yet.
*/
public Remote toStub() throws IOException {
return RemoteObject.toStub(this);
}
/** {@collect.stats}
* <p>Creates a new client connection as an RMI object exported
* through JRMP. The port and socket factories for the new
* {@link RMIConnection} object are the ones supplied
* to the <code>RMIJRMPServerImpl</code> constructor.</p>
*
* @param connectionId the ID of the new connection. Every
* connection opened by this connector server will have a
* different id. The behavior is unspecified if this parameter is
* null.
*
* @param subject the authenticated subject. Can be null.
*
* @return the newly-created <code>RMIConnection</code>.
*
* @exception IOException if the new {@link RMIConnection}
* object cannot be created or exported.
*/
protected RMIConnection makeClient(String connectionId, Subject subject)
throws IOException {
if (connectionId == null)
throw new NullPointerException("Null connectionId");
RMIConnection client =
new RMIConnectionImpl(this, connectionId, getDefaultClassLoader(),
subject, env);
export(client);
return client;
}
protected void closeClient(RMIConnection client) throws IOException {
unexport(client, true);
}
/** {@collect.stats}
* <p>Called by {@link #close()} to close the connector server by
* unexporting this object. After returning from this method, the
* connector server must not accept any new connections.</p>
*
* @exception IOException if the attempt to close the connector
* server failed.
*/
protected void closeServer() throws IOException {
unexport(this, true);
}
private final int port;
private final RMIClientSocketFactory csf;
private final RMIServerSocketFactory ssf;
private final Map<String, ?> env;
}
| Java |
/*
* Copyright (c) 2002, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management.remote.rmi;
import static com.sun.jmx.mbeanserver.Util.cast;
import com.sun.jmx.remote.internal.ServerCommunicatorAdmin;
import com.sun.jmx.remote.internal.ServerNotifForwarder;
import com.sun.jmx.remote.security.JMXSubjectDomainCombiner;
import com.sun.jmx.remote.security.SubjectDelegator;
import com.sun.jmx.remote.util.ClassLoaderWithRepository;
import com.sun.jmx.remote.util.ClassLogger;
import com.sun.jmx.remote.util.EnvHelp;
import com.sun.jmx.remote.util.OrderClassLoaders;
import java.io.IOException;
import java.rmi.MarshalledObject;
import java.rmi.UnmarshalException;
import java.rmi.server.Unreferenced;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import javax.management.Attribute;
import javax.management.AttributeList;
import javax.management.AttributeNotFoundException;
import javax.management.InstanceAlreadyExistsException;
import javax.management.InstanceNotFoundException;
import javax.management.IntrospectionException;
import javax.management.InvalidAttributeValueException;
import javax.management.ListenerNotFoundException;
import javax.management.MBeanException;
import javax.management.MBeanInfo;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServer;
import javax.management.NotCompliantMBeanException;
import javax.management.NotificationFilter;
import javax.management.ObjectInstance;
import javax.management.ObjectName;
import javax.management.QueryExp;
import javax.management.ReflectionException;
import javax.management.RuntimeOperationsException;
import javax.management.loading.ClassLoaderRepository;
import javax.management.remote.JMXServerErrorException;
import javax.management.remote.NotificationResult;
import javax.management.remote.TargetedNotification;
import javax.security.auth.Subject;
/** {@collect.stats}
* <p>Implementation of the {@link RMIConnection} interface. User
* code will not usually reference this class.</p>
*
* @since 1.5
*/
/*
* Notice that we omit the type parameter from MarshalledObject everywhere,
* even though it would add useful information to the documentation. The
* reason is that it was only added in Mustang (Java SE 6), whereas versions
* 1.4 and 2.0 of the JMX API must be implementable on Tiger per our
* commitments for JSR 255.
*/
public class RMIConnectionImpl implements RMIConnection, Unreferenced {
/** {@collect.stats}
* Constructs a new {@link RMIConnection}. This connection can be
* used with either the JRMP or IIOP transport. This object does
* not export itself: it is the responsibility of the caller to
* export it appropriately (see {@link
* RMIJRMPServerImpl#makeClient(String,Subject)} and {@link
* RMIIIOPServerImpl#makeClient(String,Subject)}.
*
* @param rmiServer The RMIServerImpl object for which this
* connection is created. The behavior is unspecified if this
* parameter is null.
* @param connectionId The ID for this connection. The behavior
* is unspecified if this parameter is null.
* @param defaultClassLoader The default ClassLoader to be used
* when deserializing marshalled objects. Can be null, to signify
* the bootstrap class loader.
* @param subject the authenticated subject to be used for
* authorization. Can be null, to signify that no subject has
* been authenticated.
* @param env the environment containing attributes for the new
* <code>RMIServerImpl</code>. Can be null, equivalent to an
* empty map.
*/
public RMIConnectionImpl(RMIServerImpl rmiServer,
String connectionId,
ClassLoader defaultClassLoader,
Subject subject,
Map<String,?> env) {
if (rmiServer == null || connectionId == null)
throw new NullPointerException("Illegal null argument");
if (env == null)
env = Collections.emptyMap();
this.rmiServer = rmiServer;
this.connectionId = connectionId;
this.defaultClassLoader = defaultClassLoader;
this.subjectDelegator = new SubjectDelegator();
this.subject = subject;
if (subject == null) {
this.acc = null;
this.removeCallerContext = false;
} else {
this.removeCallerContext =
SubjectDelegator.checkRemoveCallerContext(subject);
if (this.removeCallerContext) {
this.acc =
JMXSubjectDomainCombiner.getDomainCombinerContext(subject);
} else {
this.acc =
JMXSubjectDomainCombiner.getContext(subject);
}
}
this.mbeanServer = rmiServer.getMBeanServer();
final ClassLoader dcl = defaultClassLoader;
this.classLoaderWithRepository =
AccessController.doPrivileged(
new PrivilegedAction<ClassLoaderWithRepository>() {
public ClassLoaderWithRepository run() {
return new ClassLoaderWithRepository(
getClassLoaderRepository(),
dcl);
}
});
serverCommunicatorAdmin = new
RMIServerCommunicatorAdmin(EnvHelp.getServerConnectionTimeout(env));
this.env = env;
}
private synchronized ServerNotifForwarder getServerNotifFwd() {
// Lazily created when first use. Mainly when
// addNotificationListener is first called.
if (serverNotifForwarder == null)
serverNotifForwarder =
new ServerNotifForwarder(mbeanServer,
env,
rmiServer.getNotifBuffer(),
connectionId);
return serverNotifForwarder;
}
public String getConnectionId() throws IOException {
// We should call reqIncomming() here... shouldn't we?
return connectionId;
}
public void close() throws IOException {
final boolean debug = logger.debugOn();
final String idstr = (debug?"["+this.toString()+"]":null);
synchronized (this) {
if (terminated) {
if (debug) logger.debug("close",idstr + " already terminated.");
return;
}
if (debug) logger.debug("close",idstr + " closing.");
terminated = true;
if (serverCommunicatorAdmin != null) {
serverCommunicatorAdmin.terminate();
}
if (serverNotifForwarder != null) {
serverNotifForwarder.terminate();
}
}
rmiServer.clientClosed(this);
if (debug) logger.debug("close",idstr + " closed.");
}
public void unreferenced() {
logger.debug("unreferenced", "called");
try {
close();
logger.debug("unreferenced", "done");
} catch (IOException e) {
logger.fine("unreferenced", e);
}
}
//-------------------------------------------------------------------------
// MBeanServerConnection Wrapper
//-------------------------------------------------------------------------
public ObjectInstance createMBean(String className,
ObjectName name,
Subject delegationSubject)
throws
ReflectionException,
InstanceAlreadyExistsException,
MBeanRegistrationException,
MBeanException,
NotCompliantMBeanException,
IOException {
try {
final Object params[] =
new Object[] { className, name };
if (logger.debugOn())
logger.debug("createMBean(String,ObjectName)",
"connectionId=" + connectionId +", className=" +
className+", name=" + name);
return (ObjectInstance)
doPrivilegedOperation(
CREATE_MBEAN,
params,
delegationSubject);
} catch (PrivilegedActionException pe) {
Exception e = extractException(pe);
if (e instanceof ReflectionException)
throw (ReflectionException) e;
if (e instanceof InstanceAlreadyExistsException)
throw (InstanceAlreadyExistsException) e;
if (e instanceof MBeanRegistrationException)
throw (MBeanRegistrationException) e;
if (e instanceof MBeanException)
throw (MBeanException) e;
if (e instanceof NotCompliantMBeanException)
throw (NotCompliantMBeanException) e;
if (e instanceof IOException)
throw (IOException) e;
throw newIOException("Got unexpected server exception: " + e, e);
}
}
public ObjectInstance createMBean(String className,
ObjectName name,
ObjectName loaderName,
Subject delegationSubject)
throws
ReflectionException,
InstanceAlreadyExistsException,
MBeanRegistrationException,
MBeanException,
NotCompliantMBeanException,
InstanceNotFoundException,
IOException {
try {
final Object params[] =
new Object[] { className, name, loaderName };
if (logger.debugOn())
logger.debug("createMBean(String,ObjectName,ObjectName)",
"connectionId=" + connectionId
+", className=" + className
+", name=" + name
+", loaderName=" + loaderName);
return (ObjectInstance)
doPrivilegedOperation(
CREATE_MBEAN_LOADER,
params,
delegationSubject);
} catch (PrivilegedActionException pe) {
Exception e = extractException(pe);
if (e instanceof ReflectionException)
throw (ReflectionException) e;
if (e instanceof InstanceAlreadyExistsException)
throw (InstanceAlreadyExistsException) e;
if (e instanceof MBeanRegistrationException)
throw (MBeanRegistrationException) e;
if (e instanceof MBeanException)
throw (MBeanException) e;
if (e instanceof NotCompliantMBeanException)
throw (NotCompliantMBeanException) e;
if (e instanceof InstanceNotFoundException)
throw (InstanceNotFoundException) e;
if (e instanceof IOException)
throw (IOException) e;
throw newIOException("Got unexpected server exception: " + e, e);
}
}
public ObjectInstance createMBean(String className,
ObjectName name,
MarshalledObject params,
String signature[],
Subject delegationSubject)
throws
ReflectionException,
InstanceAlreadyExistsException,
MBeanRegistrationException,
MBeanException,
NotCompliantMBeanException,
IOException {
final Object[] values;
final boolean debug = logger.debugOn();
if (debug) logger.debug(
"createMBean(String,ObjectName,Object[],String[])",
"connectionId=" + connectionId
+", unwrapping parameters using classLoaderWithRepository.");
values =
nullIsEmpty(unwrap(params, classLoaderWithRepository, Object[].class));
try {
final Object params2[] =
new Object[] { className, name, values,
nullIsEmpty(signature) };
if (debug)
logger.debug("createMBean(String,ObjectName,Object[],String[])",
"connectionId=" + connectionId
+", className=" + className
+", name=" + name
+", params=" + objects(values)
+", signature=" + strings(signature));
return (ObjectInstance)
doPrivilegedOperation(
CREATE_MBEAN_PARAMS,
params2,
delegationSubject);
} catch (PrivilegedActionException pe) {
Exception e = extractException(pe);
if (e instanceof ReflectionException)
throw (ReflectionException) e;
if (e instanceof InstanceAlreadyExistsException)
throw (InstanceAlreadyExistsException) e;
if (e instanceof MBeanRegistrationException)
throw (MBeanRegistrationException) e;
if (e instanceof MBeanException)
throw (MBeanException) e;
if (e instanceof NotCompliantMBeanException)
throw (NotCompliantMBeanException) e;
if (e instanceof IOException)
throw (IOException) e;
throw newIOException("Got unexpected server exception: " + e, e);
}
}
public ObjectInstance createMBean(String className,
ObjectName name,
ObjectName loaderName,
MarshalledObject params,
String signature[],
Subject delegationSubject)
throws
ReflectionException,
InstanceAlreadyExistsException,
MBeanRegistrationException,
MBeanException,
NotCompliantMBeanException,
InstanceNotFoundException,
IOException {
final Object[] values;
final boolean debug = logger.debugOn();
if (debug) logger.debug(
"createMBean(String,ObjectName,ObjectName,Object[],String[])",
"connectionId=" + connectionId
+", unwrapping params with MBean extended ClassLoader.");
values = nullIsEmpty(unwrap(params,
getClassLoader(loaderName),
defaultClassLoader,
Object[].class));
try {
final Object params2[] =
new Object[] { className, name, loaderName, values,
nullIsEmpty(signature) };
if (debug) logger.debug(
"createMBean(String,ObjectName,ObjectName,Object[],String[])",
"connectionId=" + connectionId
+", className=" + className
+", name=" + name
+", loaderName=" + loaderName
+", params=" + objects(values)
+", signature=" + strings(signature));
return (ObjectInstance)
doPrivilegedOperation(
CREATE_MBEAN_LOADER_PARAMS,
params2,
delegationSubject);
} catch (PrivilegedActionException pe) {
Exception e = extractException(pe);
if (e instanceof ReflectionException)
throw (ReflectionException) e;
if (e instanceof InstanceAlreadyExistsException)
throw (InstanceAlreadyExistsException) e;
if (e instanceof MBeanRegistrationException)
throw (MBeanRegistrationException) e;
if (e instanceof MBeanException)
throw (MBeanException) e;
if (e instanceof NotCompliantMBeanException)
throw (NotCompliantMBeanException) e;
if (e instanceof InstanceNotFoundException)
throw (InstanceNotFoundException) e;
if (e instanceof IOException)
throw (IOException) e;
throw newIOException("Got unexpected server exception: " + e, e);
}
}
public void unregisterMBean(ObjectName name, Subject delegationSubject)
throws
InstanceNotFoundException,
MBeanRegistrationException,
IOException {
try {
final Object params[] = new Object[] { name };
if (logger.debugOn()) logger.debug("unregisterMBean",
"connectionId=" + connectionId
+", name="+name);
doPrivilegedOperation(
UNREGISTER_MBEAN,
params,
delegationSubject);
} catch (PrivilegedActionException pe) {
Exception e = extractException(pe);
if (e instanceof InstanceNotFoundException)
throw (InstanceNotFoundException) e;
if (e instanceof MBeanRegistrationException)
throw (MBeanRegistrationException) e;
if (e instanceof IOException)
throw (IOException) e;
throw newIOException("Got unexpected server exception: " + e, e);
}
}
public ObjectInstance getObjectInstance(ObjectName name,
Subject delegationSubject)
throws
InstanceNotFoundException,
IOException {
checkNonNull("ObjectName", name);
try {
final Object params[] = new Object[] { name };
if (logger.debugOn()) logger.debug("getObjectInstance",
"connectionId=" + connectionId
+", name="+name);
return (ObjectInstance)
doPrivilegedOperation(
GET_OBJECT_INSTANCE,
params,
delegationSubject);
} catch (PrivilegedActionException pe) {
Exception e = extractException(pe);
if (e instanceof InstanceNotFoundException)
throw (InstanceNotFoundException) e;
if (e instanceof IOException)
throw (IOException) e;
throw newIOException("Got unexpected server exception: " + e, e);
}
}
public Set<ObjectInstance>
queryMBeans(ObjectName name,
MarshalledObject query,
Subject delegationSubject)
throws IOException {
final QueryExp queryValue;
final boolean debug=logger.debugOn();
if (debug) logger.debug("queryMBeans",
"connectionId=" + connectionId
+" unwrapping query with defaultClassLoader.");
queryValue = unwrap(query, defaultClassLoader, QueryExp.class);
try {
final Object params[] = new Object[] { name, queryValue };
if (debug) logger.debug("queryMBeans",
"connectionId=" + connectionId
+", name="+name +", query="+query);
return cast(
doPrivilegedOperation(
QUERY_MBEANS,
params,
delegationSubject));
} catch (PrivilegedActionException pe) {
Exception e = extractException(pe);
if (e instanceof IOException)
throw (IOException) e;
throw newIOException("Got unexpected server exception: " + e, e);
}
}
public Set<ObjectName>
queryNames(ObjectName name,
MarshalledObject query,
Subject delegationSubject)
throws IOException {
final QueryExp queryValue;
final boolean debug=logger.debugOn();
if (debug) logger.debug("queryNames",
"connectionId=" + connectionId
+" unwrapping query with defaultClassLoader.");
queryValue = unwrap(query, defaultClassLoader, QueryExp.class);
try {
final Object params[] = new Object[] { name, queryValue };
if (debug) logger.debug("queryNames",
"connectionId=" + connectionId
+", name="+name +", query="+query);
return cast(
doPrivilegedOperation(
QUERY_NAMES,
params,
delegationSubject));
} catch (PrivilegedActionException pe) {
Exception e = extractException(pe);
if (e instanceof IOException)
throw (IOException) e;
throw newIOException("Got unexpected server exception: " + e, e);
}
}
public boolean isRegistered(ObjectName name,
Subject delegationSubject) throws IOException {
try {
final Object params[] = new Object[] { name };
return ((Boolean)
doPrivilegedOperation(
IS_REGISTERED,
params,
delegationSubject)).booleanValue();
} catch (PrivilegedActionException pe) {
Exception e = extractException(pe);
if (e instanceof IOException)
throw (IOException) e;
throw newIOException("Got unexpected server exception: " + e, e);
}
}
public Integer getMBeanCount(Subject delegationSubject)
throws IOException {
try {
final Object params[] = new Object[] { };
if (logger.debugOn()) logger.debug("getMBeanCount",
"connectionId=" + connectionId);
return (Integer)
doPrivilegedOperation(
GET_MBEAN_COUNT,
params,
delegationSubject);
} catch (PrivilegedActionException pe) {
Exception e = extractException(pe);
if (e instanceof IOException)
throw (IOException) e;
throw newIOException("Got unexpected server exception: " + e, e);
}
}
public Object getAttribute(ObjectName name,
String attribute,
Subject delegationSubject)
throws
MBeanException,
AttributeNotFoundException,
InstanceNotFoundException,
ReflectionException,
IOException {
try {
final Object params[] = new Object[] { name, attribute };
if (logger.debugOn()) logger.debug("getAttribute",
"connectionId=" + connectionId
+", name=" + name
+", attribute="+ attribute);
return
doPrivilegedOperation(
GET_ATTRIBUTE,
params,
delegationSubject);
} catch (PrivilegedActionException pe) {
Exception e = extractException(pe);
if (e instanceof MBeanException)
throw (MBeanException) e;
if (e instanceof AttributeNotFoundException)
throw (AttributeNotFoundException) e;
if (e instanceof InstanceNotFoundException)
throw (InstanceNotFoundException) e;
if (e instanceof ReflectionException)
throw (ReflectionException) e;
if (e instanceof IOException)
throw (IOException) e;
throw newIOException("Got unexpected server exception: " + e, e);
}
}
public AttributeList getAttributes(ObjectName name,
String[] attributes,
Subject delegationSubject)
throws
InstanceNotFoundException,
ReflectionException,
IOException {
try {
final Object params[] = new Object[] { name, attributes };
if (logger.debugOn()) logger.debug("getAttributes",
"connectionId=" + connectionId
+", name=" + name
+", attributes="+ strings(attributes));
return (AttributeList)
doPrivilegedOperation(
GET_ATTRIBUTES,
params,
delegationSubject);
} catch (PrivilegedActionException pe) {
Exception e = extractException(pe);
if (e instanceof InstanceNotFoundException)
throw (InstanceNotFoundException) e;
if (e instanceof ReflectionException)
throw (ReflectionException) e;
if (e instanceof IOException)
throw (IOException) e;
throw newIOException("Got unexpected server exception: " + e, e);
}
}
public void setAttribute(ObjectName name,
MarshalledObject attribute,
Subject delegationSubject)
throws
InstanceNotFoundException,
AttributeNotFoundException,
InvalidAttributeValueException,
MBeanException,
ReflectionException,
IOException {
final Attribute attr;
final boolean debug=logger.debugOn();
if (debug) logger.debug("setAttribute",
"connectionId=" + connectionId
+" unwrapping attribute with MBean extended ClassLoader.");
attr = unwrap(attribute,
getClassLoaderFor(name),
defaultClassLoader,
Attribute.class);
try {
final Object params[] = new Object[] { name, attr };
if (debug) logger.debug("setAttribute",
"connectionId=" + connectionId
+", name="+name
+", attribute="+attr);
doPrivilegedOperation(
SET_ATTRIBUTE,
params,
delegationSubject);
} catch (PrivilegedActionException pe) {
Exception e = extractException(pe);
if (e instanceof InstanceNotFoundException)
throw (InstanceNotFoundException) e;
if (e instanceof AttributeNotFoundException)
throw (AttributeNotFoundException) e;
if (e instanceof InvalidAttributeValueException)
throw (InvalidAttributeValueException) e;
if (e instanceof MBeanException)
throw (MBeanException) e;
if (e instanceof ReflectionException)
throw (ReflectionException) e;
if (e instanceof IOException)
throw (IOException) e;
throw newIOException("Got unexpected server exception: " + e, e);
}
}
public AttributeList setAttributes(ObjectName name,
MarshalledObject attributes,
Subject delegationSubject)
throws
InstanceNotFoundException,
ReflectionException,
IOException {
final AttributeList attrlist;
final boolean debug=logger.debugOn();
if (debug) logger.debug("setAttributes",
"connectionId=" + connectionId
+" unwrapping attributes with MBean extended ClassLoader.");
attrlist =
unwrap(attributes,
getClassLoaderFor(name),
defaultClassLoader,
AttributeList.class);
try {
final Object params[] = new Object[] { name, attrlist };
if (debug) logger.debug("setAttributes",
"connectionId=" + connectionId
+", name="+name
+", attributes="+attrlist);
return (AttributeList)
doPrivilegedOperation(
SET_ATTRIBUTES,
params,
delegationSubject);
} catch (PrivilegedActionException pe) {
Exception e = extractException(pe);
if (e instanceof InstanceNotFoundException)
throw (InstanceNotFoundException) e;
if (e instanceof ReflectionException)
throw (ReflectionException) e;
if (e instanceof IOException)
throw (IOException) e;
throw newIOException("Got unexpected server exception: " + e, e);
}
}
public Object invoke(ObjectName name,
String operationName,
MarshalledObject params,
String signature[],
Subject delegationSubject)
throws
InstanceNotFoundException,
MBeanException,
ReflectionException,
IOException {
checkNonNull("ObjectName", name);
checkNonNull("Operation name", operationName);
final Object[] values;
final boolean debug=logger.debugOn();
if (debug) logger.debug("invoke",
"connectionId=" + connectionId
+" unwrapping params with MBean extended ClassLoader.");
values = nullIsEmpty(unwrap(params,
getClassLoaderFor(name),
defaultClassLoader,
Object[].class));
try {
final Object params2[] =
new Object[] { name, operationName, values,
nullIsEmpty(signature) };
if (debug) logger.debug("invoke",
"connectionId=" + connectionId
+", name="+name
+", operationName="+operationName
+", params="+objects(values)
+", signature="+strings(signature));
return
doPrivilegedOperation(
INVOKE,
params2,
delegationSubject);
} catch (PrivilegedActionException pe) {
Exception e = extractException(pe);
if (e instanceof InstanceNotFoundException)
throw (InstanceNotFoundException) e;
if (e instanceof MBeanException)
throw (MBeanException) e;
if (e instanceof ReflectionException)
throw (ReflectionException) e;
if (e instanceof IOException)
throw (IOException) e;
throw newIOException("Got unexpected server exception: " + e, e);
}
}
public String getDefaultDomain(Subject delegationSubject)
throws IOException {
try {
final Object params[] = new Object[] { };
if (logger.debugOn()) logger.debug("getDefaultDomain",
"connectionId=" + connectionId);
return (String)
doPrivilegedOperation(
GET_DEFAULT_DOMAIN,
params,
delegationSubject);
} catch (PrivilegedActionException pe) {
Exception e = extractException(pe);
if (e instanceof IOException)
throw (IOException) e;
throw newIOException("Got unexpected server exception: " + e, e);
}
}
public String[] getDomains(Subject delegationSubject) throws IOException {
try {
final Object params[] = new Object[] { };
if (logger.debugOn()) logger.debug("getDomains",
"connectionId=" + connectionId);
return (String[])
doPrivilegedOperation(
GET_DOMAINS,
params,
delegationSubject);
} catch (PrivilegedActionException pe) {
Exception e = extractException(pe);
if (e instanceof IOException)
throw (IOException) e;
throw newIOException("Got unexpected server exception: " + e, e);
}
}
public MBeanInfo getMBeanInfo(ObjectName name, Subject delegationSubject)
throws
InstanceNotFoundException,
IntrospectionException,
ReflectionException,
IOException {
checkNonNull("ObjectName", name);
try {
final Object params[] = new Object[] { name };
if (logger.debugOn()) logger.debug("getMBeanInfo",
"connectionId=" + connectionId
+", name="+name);
return (MBeanInfo)
doPrivilegedOperation(
GET_MBEAN_INFO,
params,
delegationSubject);
} catch (PrivilegedActionException pe) {
Exception e = extractException(pe);
if (e instanceof InstanceNotFoundException)
throw (InstanceNotFoundException) e;
if (e instanceof IntrospectionException)
throw (IntrospectionException) e;
if (e instanceof ReflectionException)
throw (ReflectionException) e;
if (e instanceof IOException)
throw (IOException) e;
throw newIOException("Got unexpected server exception: " + e, e);
}
}
public boolean isInstanceOf(ObjectName name,
String className,
Subject delegationSubject)
throws InstanceNotFoundException, IOException {
checkNonNull("ObjectName", name);
try {
final Object params[] = new Object[] { name, className };
if (logger.debugOn()) logger.debug("isInstanceOf",
"connectionId=" + connectionId
+", name="+name
+", className="+className);
return ((Boolean)
doPrivilegedOperation(
IS_INSTANCE_OF,
params,
delegationSubject)).booleanValue();
} catch (PrivilegedActionException pe) {
Exception e = extractException(pe);
if (e instanceof InstanceNotFoundException)
throw (InstanceNotFoundException) e;
if (e instanceof IOException)
throw (IOException) e;
throw newIOException("Got unexpected server exception: " + e, e);
}
}
public Integer[] addNotificationListeners(ObjectName[] names,
MarshalledObject[] filters,
Subject[] delegationSubjects)
throws InstanceNotFoundException, IOException {
if (names == null || filters == null) {
throw new IllegalArgumentException("Got null arguments.");
}
Subject[] sbjs = (delegationSubjects != null) ? delegationSubjects :
new Subject[names.length];
if (names.length != filters.length || filters.length != sbjs.length) {
final String msg =
"The value lengths of 3 parameters are not same.";
throw new IllegalArgumentException(msg);
}
for (int i=0; i<names.length; i++) {
if (names[i] == null) {
throw new IllegalArgumentException("Null Object name.");
}
}
int i=0;
ClassLoader targetCl;
NotificationFilter[] filterValues =
new NotificationFilter[names.length];
Object params[];
Integer[] ids = new Integer[names.length];
final boolean debug=logger.debugOn();
try {
for (; i<names.length; i++) {
targetCl = getClassLoaderFor(names[i]);
if (debug) logger.debug("addNotificationListener"+
"(ObjectName,NotificationFilter)",
"connectionId=" + connectionId +
" unwrapping filter with target extended ClassLoader.");
filterValues[i] =
unwrap(filters[i], targetCl, defaultClassLoader,
NotificationFilter.class);
if (debug) logger.debug("addNotificationListener"+
"(ObjectName,NotificationFilter)",
"connectionId=" + connectionId
+", name=" + names[i]
+", filter=" + filterValues[i]);
ids[i] = (Integer)
doPrivilegedOperation(ADD_NOTIFICATION_LISTENERS,
new Object[] { names[i],
filterValues[i] },
sbjs[i]);
}
return ids;
} catch (Exception e) {
// remove all registered listeners
for (int j=0; j<i; j++) {
try {
getServerNotifFwd().removeNotificationListener(names[j],
ids[j]);
} catch (Exception eee) {
// strange
}
}
if (e instanceof PrivilegedActionException) {
e = extractException(e);
}
if (e instanceof ClassCastException) {
throw (ClassCastException) e;
} else if (e instanceof IOException) {
throw (IOException)e;
} else if (e instanceof InstanceNotFoundException) {
throw (InstanceNotFoundException) e;
} else if (e instanceof RuntimeException) {
throw (RuntimeException) e;
} else {
throw newIOException("Got unexpected server exception: "+e,e);
}
}
}
public void addNotificationListener(ObjectName name,
ObjectName listener,
MarshalledObject filter,
MarshalledObject handback,
Subject delegationSubject)
throws InstanceNotFoundException, IOException {
checkNonNull("Target MBean name", name);
checkNonNull("Listener MBean name", listener);
final NotificationFilter filterValue;
final Object handbackValue;
final boolean debug=logger.debugOn();
final ClassLoader targetCl = getClassLoaderFor(name);
if (debug) logger.debug("addNotificationListener"+
"(ObjectName,ObjectName,NotificationFilter,Object)",
"connectionId=" + connectionId
+" unwrapping filter with target extended ClassLoader.");
filterValue =
unwrap(filter, targetCl, defaultClassLoader, NotificationFilter.class);
if (debug) logger.debug("addNotificationListener"+
"(ObjectName,ObjectName,NotificationFilter,Object)",
"connectionId=" + connectionId
+" unwrapping handback with target extended ClassLoader.");
handbackValue =
unwrap(handback, targetCl, defaultClassLoader, Object.class);
try {
final Object params[] =
new Object[] { name, listener, filterValue, handbackValue };
if (debug) logger.debug("addNotificationListener"+
"(ObjectName,ObjectName,NotificationFilter,Object)",
"connectionId=" + connectionId
+", name=" + name
+", listenerName=" + listener
+", filter=" + filterValue
+", handback=" + handbackValue);
doPrivilegedOperation(
ADD_NOTIFICATION_LISTENER_OBJECTNAME,
params,
delegationSubject);
} catch (PrivilegedActionException pe) {
Exception e = extractException(pe);
if (e instanceof InstanceNotFoundException)
throw (InstanceNotFoundException) e;
if (e instanceof IOException)
throw (IOException) e;
throw newIOException("Got unexpected server exception: " + e, e);
}
}
public void removeNotificationListeners(ObjectName name,
Integer[] listenerIDs,
Subject delegationSubject)
throws
InstanceNotFoundException,
ListenerNotFoundException,
IOException {
if (name == null || listenerIDs == null)
throw new IllegalArgumentException("Illegal null parameter");
for (int i = 0; i < listenerIDs.length; i++) {
if (listenerIDs[i] == null)
throw new IllegalArgumentException("Null listener ID");
}
try {
final Object params[] = new Object[] { name, listenerIDs };
if (logger.debugOn()) logger.debug("removeNotificationListener"+
"(ObjectName,Integer[])",
"connectionId=" + connectionId
+", name=" + name
+", listenerIDs=" + objects(listenerIDs));
doPrivilegedOperation(
REMOVE_NOTIFICATION_LISTENER,
params,
delegationSubject);
} catch (PrivilegedActionException pe) {
Exception e = extractException(pe);
if (e instanceof InstanceNotFoundException)
throw (InstanceNotFoundException) e;
if (e instanceof ListenerNotFoundException)
throw (ListenerNotFoundException) e;
if (e instanceof IOException)
throw (IOException) e;
throw newIOException("Got unexpected server exception: " + e, e);
}
}
public void removeNotificationListener(ObjectName name,
ObjectName listener,
Subject delegationSubject)
throws
InstanceNotFoundException,
ListenerNotFoundException,
IOException {
checkNonNull("Target MBean name", name);
checkNonNull("Listener MBean name", listener);
try {
final Object params[] = new Object[] { name, listener };
if (logger.debugOn()) logger.debug("removeNotificationListener"+
"(ObjectName,ObjectName)",
"connectionId=" + connectionId
+", name=" + name
+", listenerName=" + listener);
doPrivilegedOperation(
REMOVE_NOTIFICATION_LISTENER_OBJECTNAME,
params,
delegationSubject);
} catch (PrivilegedActionException pe) {
Exception e = extractException(pe);
if (e instanceof InstanceNotFoundException)
throw (InstanceNotFoundException) e;
if (e instanceof ListenerNotFoundException)
throw (ListenerNotFoundException) e;
if (e instanceof IOException)
throw (IOException) e;
throw newIOException("Got unexpected server exception: " + e, e);
}
}
public void removeNotificationListener(ObjectName name,
ObjectName listener,
MarshalledObject filter,
MarshalledObject handback,
Subject delegationSubject)
throws
InstanceNotFoundException,
ListenerNotFoundException,
IOException {
checkNonNull("Target MBean name", name);
checkNonNull("Listener MBean name", listener);
final NotificationFilter filterValue;
final Object handbackValue;
final boolean debug=logger.debugOn();
final ClassLoader targetCl = getClassLoaderFor(name);
if (debug) logger.debug("removeNotificationListener"+
"(ObjectName,ObjectName,NotificationFilter,Object)",
"connectionId=" + connectionId
+" unwrapping filter with target extended ClassLoader.");
filterValue =
unwrap(filter, targetCl, defaultClassLoader, NotificationFilter.class);
if (debug) logger.debug("removeNotificationListener"+
"(ObjectName,ObjectName,NotificationFilter,Object)",
"connectionId=" + connectionId
+" unwrapping handback with target extended ClassLoader.");
handbackValue =
unwrap(handback, targetCl, defaultClassLoader, Object.class);
try {
final Object params[] =
new Object[] { name, listener, filterValue, handbackValue };
if (debug) logger.debug("removeNotificationListener"+
"(ObjectName,ObjectName,NotificationFilter,Object)",
"connectionId=" + connectionId
+", name=" + name
+", listenerName=" + listener
+", filter=" + filterValue
+", handback=" + handbackValue);
doPrivilegedOperation(
REMOVE_NOTIFICATION_LISTENER_OBJECTNAME_FILTER_HANDBACK,
params,
delegationSubject);
} catch (PrivilegedActionException pe) {
Exception e = extractException(pe);
if (e instanceof InstanceNotFoundException)
throw (InstanceNotFoundException) e;
if (e instanceof ListenerNotFoundException)
throw (ListenerNotFoundException) e;
if (e instanceof IOException)
throw (IOException) e;
throw newIOException("Got unexpected server exception: " + e, e);
}
}
public NotificationResult fetchNotifications(long clientSequenceNumber,
int maxNotifications,
long timeout)
throws IOException {
if (logger.debugOn()) logger.debug("fetchNotifications",
"connectionId=" + connectionId
+", timeout=" + timeout);
if (maxNotifications < 0 || timeout < 0)
throw new IllegalArgumentException("Illegal negative argument");
final boolean serverTerminated =
serverCommunicatorAdmin.reqIncoming();
try {
if (serverTerminated) {
// we must not call fetchNotifs() if the server is
// terminated (timeout elapsed).
//
return new NotificationResult(0L, 0L,
new TargetedNotification[0]);
}
final long csn = clientSequenceNumber;
final int mn = maxNotifications;
final long t = timeout;
PrivilegedAction<NotificationResult> action =
new PrivilegedAction<NotificationResult>() {
public NotificationResult run() {
return getServerNotifFwd().fetchNotifs(csn, t, mn);
}
};
if (acc == null)
return action.run();
else
return AccessController.doPrivileged(action, acc);
} finally {
serverCommunicatorAdmin.rspOutgoing();
}
}
/** {@collect.stats}
* <p>Returns a string representation of this object. In general,
* the <code>toString</code> method returns a string that
* "textually represents" this object. The result should be a
* concise but informative representation that is easy for a
* person to read.</p>
*
* @return a String representation of this object.
**/
@Override
public String toString() {
return super.toString() + ": connectionId=" + connectionId;
}
//------------------------------------------------------------------------
// private classes
//------------------------------------------------------------------------
private class PrivilegedOperation
implements PrivilegedExceptionAction<Object> {
public PrivilegedOperation(int operation, Object[] params) {
this.operation = operation;
this.params = params;
}
public Object run() throws Exception {
return doOperation(operation, params);
}
private int operation;
private Object[] params;
}
//------------------------------------------------------------------------
// private classes
//------------------------------------------------------------------------
private class RMIServerCommunicatorAdmin extends ServerCommunicatorAdmin {
public RMIServerCommunicatorAdmin(long timeout) {
super(timeout);
}
protected void doStop() {
try {
close();
} catch (IOException ie) {
logger.warning("RMIServerCommunicatorAdmin-doStop",
"Failed to close: " + ie);
logger.debug("RMIServerCommunicatorAdmin-doStop",ie);
}
}
}
//------------------------------------------------------------------------
// private methods
//------------------------------------------------------------------------
private ClassLoaderRepository getClassLoaderRepository() {
return
AccessController.doPrivileged(
new PrivilegedAction<ClassLoaderRepository>() {
public ClassLoaderRepository run() {
return mbeanServer.getClassLoaderRepository();
}
});
}
private ClassLoader getClassLoader(final ObjectName name)
throws InstanceNotFoundException {
try {
return
AccessController.doPrivileged(
new PrivilegedExceptionAction<ClassLoader>() {
public ClassLoader run() throws InstanceNotFoundException {
return mbeanServer.getClassLoader(name);
}
});
} catch (PrivilegedActionException pe) {
throw (InstanceNotFoundException) extractException(pe);
}
}
private ClassLoader getClassLoaderFor(final ObjectName name)
throws InstanceNotFoundException {
try {
return (ClassLoader)
AccessController.doPrivileged(
new PrivilegedExceptionAction<Object>() {
public Object run() throws InstanceNotFoundException {
return mbeanServer.getClassLoaderFor(name);
}
});
} catch (PrivilegedActionException pe) {
throw (InstanceNotFoundException) extractException(pe);
}
}
private Object doPrivilegedOperation(final int operation,
final Object[] params,
final Subject delegationSubject)
throws PrivilegedActionException, IOException {
serverCommunicatorAdmin.reqIncoming();
try {
final AccessControlContext reqACC;
if (delegationSubject == null)
reqACC = acc;
else {
if (subject == null) {
final String msg =
"Subject delegation cannot be enabled unless " +
"an authenticated subject is put in place";
throw new SecurityException(msg);
}
reqACC = subjectDelegator.delegatedContext(
acc, delegationSubject, removeCallerContext);
}
PrivilegedOperation op =
new PrivilegedOperation(operation, params);
if (reqACC == null) {
try {
return op.run();
} catch (Exception e) {
if (e instanceof RuntimeException)
throw (RuntimeException) e;
throw new PrivilegedActionException(e);
}
} else {
return AccessController.doPrivileged(op, reqACC);
}
} catch (Error e) {
throw new JMXServerErrorException(e.toString(),e);
} finally {
serverCommunicatorAdmin.rspOutgoing();
}
}
private Object doOperation(int operation, Object[] params)
throws Exception {
switch (operation) {
case CREATE_MBEAN:
return mbeanServer.createMBean((String)params[0],
(ObjectName)params[1]);
case CREATE_MBEAN_LOADER:
return mbeanServer.createMBean((String)params[0],
(ObjectName)params[1],
(ObjectName)params[2]);
case CREATE_MBEAN_PARAMS:
return mbeanServer.createMBean((String)params[0],
(ObjectName)params[1],
(Object[])params[2],
(String[])params[3]);
case CREATE_MBEAN_LOADER_PARAMS:
return mbeanServer.createMBean((String)params[0],
(ObjectName)params[1],
(ObjectName)params[2],
(Object[])params[3],
(String[])params[4]);
case GET_ATTRIBUTE:
return mbeanServer.getAttribute((ObjectName)params[0],
(String)params[1]);
case GET_ATTRIBUTES:
return mbeanServer.getAttributes((ObjectName)params[0],
(String[])params[1]);
case GET_DEFAULT_DOMAIN:
return mbeanServer.getDefaultDomain();
case GET_DOMAINS:
return mbeanServer.getDomains();
case GET_MBEAN_COUNT:
return mbeanServer.getMBeanCount();
case GET_MBEAN_INFO:
return mbeanServer.getMBeanInfo((ObjectName)params[0]);
case GET_OBJECT_INSTANCE:
return mbeanServer.getObjectInstance((ObjectName)params[0]);
case INVOKE:
return mbeanServer.invoke((ObjectName)params[0],
(String)params[1],
(Object[])params[2],
(String[])params[3]);
case IS_INSTANCE_OF:
return mbeanServer.isInstanceOf((ObjectName)params[0],
(String)params[1])
? Boolean.TRUE : Boolean.FALSE;
case IS_REGISTERED:
return mbeanServer.isRegistered((ObjectName)params[0])
? Boolean.TRUE : Boolean.FALSE;
case QUERY_MBEANS:
return mbeanServer.queryMBeans((ObjectName)params[0],
(QueryExp)params[1]);
case QUERY_NAMES:
return mbeanServer.queryNames((ObjectName)params[0],
(QueryExp)params[1]);
case SET_ATTRIBUTE:
mbeanServer.setAttribute((ObjectName)params[0],
(Attribute)params[1]);
return null;
case SET_ATTRIBUTES:
return mbeanServer.setAttributes((ObjectName)params[0],
(AttributeList)params[1]);
case UNREGISTER_MBEAN:
mbeanServer.unregisterMBean((ObjectName)params[0]);
return null;
case ADD_NOTIFICATION_LISTENERS:
return getServerNotifFwd().addNotificationListener(
(ObjectName)params[0],
(NotificationFilter)params[1]);
case ADD_NOTIFICATION_LISTENER_OBJECTNAME:
mbeanServer.addNotificationListener((ObjectName)params[0],
(ObjectName)params[1],
(NotificationFilter)params[2],
params[3]);
return null;
case REMOVE_NOTIFICATION_LISTENER:
getServerNotifFwd().removeNotificationListener(
(ObjectName)params[0],
(Integer[])params[1]);
return null;
case REMOVE_NOTIFICATION_LISTENER_OBJECTNAME:
mbeanServer.removeNotificationListener((ObjectName)params[0],
(ObjectName)params[1]);
return null;
case REMOVE_NOTIFICATION_LISTENER_OBJECTNAME_FILTER_HANDBACK:
mbeanServer.removeNotificationListener(
(ObjectName)params[0],
(ObjectName)params[1],
(NotificationFilter)params[2],
params[3]);
return null;
default:
throw new IllegalArgumentException("Invalid operation");
}
}
private static class SetCcl implements PrivilegedExceptionAction<ClassLoader> {
private final ClassLoader classLoader;
SetCcl(ClassLoader classLoader) {
this.classLoader = classLoader;
}
public ClassLoader run() {
Thread currentThread = Thread.currentThread();
ClassLoader old = currentThread.getContextClassLoader();
currentThread.setContextClassLoader(classLoader);
return old;
}
}
private static <T> T unwrap(final MarshalledObject mo,
final ClassLoader cl,
final Class<T> wrappedClass)
throws IOException {
if (mo == null) {
return null;
}
try {
final ClassLoader old = AccessController.doPrivileged(new SetCcl(cl));
try {
return wrappedClass.cast(mo.get());
} catch (ClassNotFoundException cnfe) {
throw new UnmarshalException(cnfe.toString(), cnfe);
} finally {
AccessController.doPrivileged(new SetCcl(old));
}
} catch (PrivilegedActionException pe) {
Exception e = extractException(pe);
if (e instanceof IOException) {
throw (IOException) e;
}
if (e instanceof ClassNotFoundException) {
throw new UnmarshalException(e.toString(), e);
}
logger.warning("unwrap", "Failed to unmarshall object: " + e);
logger.debug("unwrap", e);
}
return null;
}
private static <T> T unwrap(final MarshalledObject mo,
final ClassLoader cl1,
final ClassLoader cl2,
final Class<T> wrappedClass)
throws IOException {
if (mo == null) {
return null;
}
try {
ClassLoader orderCL = AccessController.doPrivileged(
new PrivilegedExceptionAction<ClassLoader>() {
public ClassLoader run() throws Exception {
return new OrderClassLoaders(cl1, cl2);
}
}
);
return unwrap(mo, orderCL, wrappedClass);
} catch (PrivilegedActionException pe) {
Exception e = extractException(pe);
if (e instanceof IOException) {
throw (IOException) e;
}
if (e instanceof ClassNotFoundException) {
throw new UnmarshalException(e.toString(), e);
}
logger.warning("unwrap", "Failed to unmarshall object: " + e);
logger.debug("unwrap", e);
}
return null;
}
/** {@collect.stats}
* Construct a new IOException with a nested exception.
* The nested exception is set only if JDK >= 1.4
*/
private static IOException newIOException(String message,
Throwable cause) {
final IOException x = new IOException(message);
return EnvHelp.initCause(x,cause);
}
/** {@collect.stats}
* Iterate until we extract the real exception
* from a stack of PrivilegedActionExceptions.
*/
private static Exception extractException(Exception e) {
while (e instanceof PrivilegedActionException) {
e = ((PrivilegedActionException)e).getException();
}
return e;
}
private static final Object[] NO_OBJECTS = new Object[0];
private static final String[] NO_STRINGS = new String[0];
/*
* The JMX spec doesn't explicitly say that a null Object[] or
* String[] in e.g. MBeanServer.invoke is equivalent to an empty
* array, but the RI behaves that way. In the interests of
* maximal interoperability, we make it so even when we're
* connected to some other JMX implementation that might not do
* that. This should be clarified in the next version of JMX.
*/
private static Object[] nullIsEmpty(Object[] array) {
return (array == null) ? NO_OBJECTS : array;
}
private static String[] nullIsEmpty(String[] array) {
return (array == null) ? NO_STRINGS : array;
}
/*
* Similarly, the JMX spec says for some but not all methods in
* MBeanServer that take an ObjectName target, that if it's null
* you get this exception. We specify it for all of them, and
* make it so for the ones where it's not specified in JMX even if
* the JMX implementation doesn't do so.
*/
private static void checkNonNull(String what, Object x) {
if (x == null) {
RuntimeException wrapped =
new IllegalArgumentException(what + " must not be null");
throw new RuntimeOperationsException(wrapped);
}
}
//------------------------------------------------------------------------
// private variables
//------------------------------------------------------------------------
private final Subject subject;
private final SubjectDelegator subjectDelegator;
private final boolean removeCallerContext;
private final AccessControlContext acc;
private final RMIServerImpl rmiServer;
private final MBeanServer mbeanServer;
private final ClassLoader defaultClassLoader;
private final ClassLoaderWithRepository classLoaderWithRepository;
private boolean terminated = false;
private final String connectionId;
private final ServerCommunicatorAdmin serverCommunicatorAdmin;
// Method IDs for doOperation
//---------------------------
private final static int
ADD_NOTIFICATION_LISTENERS = 1;
private final static int
ADD_NOTIFICATION_LISTENER_OBJECTNAME = 2;
private final static int
CREATE_MBEAN = 3;
private final static int
CREATE_MBEAN_PARAMS = 4;
private final static int
CREATE_MBEAN_LOADER = 5;
private final static int
CREATE_MBEAN_LOADER_PARAMS = 6;
private final static int
GET_ATTRIBUTE = 7;
private final static int
GET_ATTRIBUTES = 8;
private final static int
GET_DEFAULT_DOMAIN = 9;
private final static int
GET_DOMAINS = 10;
private final static int
GET_MBEAN_COUNT = 11;
private final static int
GET_MBEAN_INFO = 12;
private final static int
GET_OBJECT_INSTANCE = 13;
private final static int
INVOKE = 14;
private final static int
IS_INSTANCE_OF = 15;
private final static int
IS_REGISTERED = 16;
private final static int
QUERY_MBEANS = 17;
private final static int
QUERY_NAMES = 18;
private final static int
REMOVE_NOTIFICATION_LISTENER = 19;
private final static int
REMOVE_NOTIFICATION_LISTENER_FILTER_HANDBACK = 20;
private final static int
REMOVE_NOTIFICATION_LISTENER_OBJECTNAME = 21;
private final static int
REMOVE_NOTIFICATION_LISTENER_OBJECTNAME_FILTER_HANDBACK = 22;
private final static int
SET_ATTRIBUTE = 23;
private final static int
SET_ATTRIBUTES = 24;
private final static int
UNREGISTER_MBEAN = 25;
// SERVER NOTIFICATION
//--------------------
private ServerNotifForwarder serverNotifForwarder;
private Map env;
// TRACES & DEBUG
//---------------
private static String objects(final Object[] objs) {
if (objs == null)
return "null";
else
return Arrays.asList(objs).toString();
}
private static String strings(final String[] strs) {
return objects(strs);
}
private static final ClassLogger logger =
new ClassLogger("javax.management.remote.rmi", "RMIConnectionImpl");
}
| Java |
/*
* Copyright (c) 2002, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management.remote.rmi;
import java.io.IOException;
import java.rmi.Remote;
import java.rmi.RemoteException;
/** {@collect.stats}
* <p>RMI object used to establish connections to an RMI connector.
* There is one Remote object implementing this interface for each RMI
* connector.</p>
*
* <p>User code does not usually refer to this interface. It is
* specified as part of the public API so that different
* implementations of that API will interoperate.</p>
*
* @since 1.5
*/
public interface RMIServer extends Remote {
/** {@collect.stats}
* <p>The version of the RMI Connector Protocol understood by this
* connector server. This is a string with the following format:</p>
*
* <pre>
* <em>protocol-version</em> <em>implementation-name</em>
* </pre>
*
* <p>The <code><em>protocol-version</em></code> is a series of
* two or more non-negative integers separated by periods
* (<code>.</code>). An implementation of the version described
* by this documentation must use the string <code>1.0</code>
* here.</p>
*
* <p>After the protocol version there must be a space, followed
* by the implementation name. The format of the implementation
* name is unspecified. It is recommended that it include an
* implementation version number. An implementation can use an
* empty string as its implementation name, for example for
* security reasons.</p>
*
* @return a string with the format described here.
*
* @exception RemoteException if there is a communication
* exception during the remote method call.
*/
public String getVersion() throws RemoteException;
/** {@collect.stats}
* <p>Makes a new connection through this RMI connector. Each
* remote client calls this method to obtain a new RMI object
* representing its connection.</p>
*
* @param credentials this object specifies the user-defined credentials
* to be passed in to the server in order to authenticate the user before
* creating the <code>RMIConnection</code>. Can be null.
*
* @return the newly-created connection object.
*
* @exception IOException if the new client object cannot be
* created or exported, or if there is a communication exception
* during the remote method call.
*
* @exception SecurityException if the given credentials do not
* allow the server to authenticate the caller successfully.
*/
public RMIConnection newClient(Object credentials) throws IOException;
}
| Java |
/*
* Copyright (c) 2003, 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.remote.rmi;
import java.security.ProtectionDomain;
/** {@collect.stats}
<p>A class loader that only knows how to define a limited number
of classes, and load a limited number of other classes through
delegation to another loader. It is used to get around a problem
with Serialization, in particular as used by RMI (including
RMI/IIOP). The JMX Remote API defines exactly what class loader
must be used to deserialize arguments on the server, and return
values on the client. We communicate this class loader to RMI by
setting it as the context class loader. RMI uses the context
class loader to load classes as it deserializes, which is what we
want. However, before consulting the context class loader, it
looks up the call stack for a class with a non-null class loader,
and uses that if it finds one. So, in the standalone version of
javax.management.remote, if the class you're looking for is known
to the loader of jmxremote.jar (typically the system class loader)
then that loader will load it. This contradicts the class-loading
semantics required.
<p>We get around the problem by ensuring that the search up the
call stack will find a non-null class loader that doesn't load any
classes of interest, namely this one. So even though this loader
is indeed consulted during deserialization, it never finds the
class being deserialized. RMI then proceeds to use the context
class loader, as we require.
<p>This loader is constructed with the name and byte-code of one
or more classes that it defines, and a class-loader to which it
will delegate certain other classes required by that byte-code.
We construct the byte-code somewhat painstakingly, by compiling
the Java code directly, converting into a string, copying that
string into the class that needs this loader, and using the
stringToBytes method to convert it into the byte array. We
compile with -g:none because there's not much point in having
line-number information and the like in these directly-encoded
classes.
<p>The referencedClassNames should contain the names of all
classes that are referenced by the classes defined by this loader.
It is not necessary to include standard J2SE classes, however.
Here, a class is referenced if it is the superclass or a
superinterface of a defined class, or if it is the type of a
field, parameter, or return value. A class is not referenced if
it only appears in the throws clause of a method or constructor.
Of course, referencedClassNames should not contain any classes
that the user might want to deserialize, because the whole point
of this loader is that it does not find such classes.
*/
class NoCallStackClassLoader extends ClassLoader {
/** {@collect.stats} Simplified constructor when this loader only defines one class. */
public NoCallStackClassLoader(String className,
byte[] byteCode,
String[] referencedClassNames,
ClassLoader referencedClassLoader,
ProtectionDomain protectionDomain) {
this(new String[] {className}, new byte[][] {byteCode},
referencedClassNames, referencedClassLoader, protectionDomain);
}
public NoCallStackClassLoader(String[] classNames,
byte[][] byteCodes,
String[] referencedClassNames,
ClassLoader referencedClassLoader,
ProtectionDomain protectionDomain) {
super(null);
/* Validation. */
if (classNames == null || classNames.length == 0
|| byteCodes == null || classNames.length != byteCodes.length
|| referencedClassNames == null || protectionDomain == null)
throw new IllegalArgumentException();
for (int i = 0; i < classNames.length; i++) {
if (classNames[i] == null || byteCodes[i] == null)
throw new IllegalArgumentException();
}
for (int i = 0; i < referencedClassNames.length; i++) {
if (referencedClassNames[i] == null)
throw new IllegalArgumentException();
}
this.classNames = classNames;
this.byteCodes = byteCodes;
this.referencedClassNames = referencedClassNames;
this.referencedClassLoader = referencedClassLoader;
this.protectionDomain = protectionDomain;
}
/* This method is called at most once per name. Define the name
* if it is one of the classes whose byte code we have, or
* delegate the load if it is one of the referenced classes.
*/
protected Class findClass(String name) throws ClassNotFoundException {
for (int i = 0; i < classNames.length; i++) {
if (name.equals(classNames[i])) {
return defineClass(classNames[i], byteCodes[i], 0,
byteCodes[i].length, protectionDomain);
}
}
/* If the referencedClassLoader is null, it is the bootstrap
* class loader, and there's no point in delegating to it
* because it's already our parent class loader.
*/
if (referencedClassLoader != null) {
for (int i = 0; i < referencedClassNames.length; i++) {
if (name.equals(referencedClassNames[i]))
return referencedClassLoader.loadClass(name);
}
}
throw new ClassNotFoundException(name);
}
private final String[] classNames;
private final byte[][] byteCodes;
private final String[] referencedClassNames;
private final ClassLoader referencedClassLoader;
private final ProtectionDomain protectionDomain;
/** {@collect.stats}
* <p>Construct a <code>byte[]</code> using the characters of the
* given <code>String</code>. Only the low-order byte of each
* character is used. This method is useful to reduce the
* footprint of classes that include big byte arrays (e.g. the
* byte code of other classes), because a string takes up much
* less space in a class file than the byte code to initialize a
* <code>byte[]</code> with the same number of bytes.</p>
*
* <p>We use just one byte per character even though characters
* contain two bytes. The resultant output length is much the
* same: using one byte per character is shorter because it has
* more characters in the optimal 1-127 range but longer because
* it has more zero bytes (which are frequent, and are encoded as
* two bytes in classfile UTF-8). But one byte per character has
* two key advantages: (1) you can see the string constants, which
* is reassuring, (2) you don't need to know whether the class
* file length is odd.</p>
*
* <p>This method differs from {@link String#getBytes()} in that
* it does not use any encoding. So it is guaranteed that each
* byte of the result is numerically identical (mod 256) to the
* corresponding character of the input.
*/
public static byte[] stringToBytes(String s) {
final int slen = s.length();
byte[] bytes = new byte[slen];
for (int i = 0; i < slen; i++)
bytes[i] = (byte) s.charAt(i);
return bytes;
}
}
/*
You can use the following Emacs function to convert class files into
strings to be used by the stringToBytes method above. Select the
whole (defun...) with the mouse and type M-x eval-region, or save it
to a file and do M-x load-file. Then visit the *.class file and do
M-x class-string.
;; class-string.el
;; visit the *.class file with emacs, then invoke this function
(defun class-string ()
"Construct a Java string whose bytes are the same as the current
buffer. The resultant string is put in a buffer called *string*,
possibly with a numeric suffix like <2>. From there it can be
insert-buffer'd into a Java program."
(interactive)
(let* ((s (buffer-string))
(slen (length s))
(i 0)
(buf (generate-new-buffer "*string*")))
(set-buffer buf)
(insert "\"")
(while (< i slen)
(if (> (current-column) 61)
(insert "\"+\n\""))
(let ((c (aref s i)))
(insert (cond
((> c 126) (format "\\%o" c))
((= c ?\") "\\\"")
((= c ?\\) "\\\\")
((< c 33)
(let ((nextc (if (< (1+ i) slen)
(aref s (1+ i))
?\0)))
(cond
((and (<= nextc ?7) (>= nextc ?0))
(format "\\%03o" c))
(t
(format "\\%o" c)))))
(t c))))
(setq i (1+ i)))
(insert "\"")
(switch-to-buffer buf)))
*/
| Java |
/*
* Copyright (c) 2003, 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.remote;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.management.MBeanNotificationInfo;
import javax.management.MBeanRegistration;
import javax.management.MBeanServer;
import javax.management.Notification;
import javax.management.NotificationBroadcasterSupport;
import javax.management.ObjectName;
/** {@collect.stats}
* <p>Superclass of every connector server. A connector server is
* attached to an MBean server. It listens for client connection
* requests and creates a connection for each one.</p>
*
* <p>A connector server is associated with an MBean server either by
* registering it in that MBean server, or by passing the MBean server
* to its constructor.</p>
*
* <p>A connector server is inactive when created. It only starts
* listening for client connections when the {@link #start() start}
* method is called. A connector server stops listening for client
* connections when the {@link #stop() stop} method is called or when
* the connector server is unregistered from its MBean server.</p>
*
* <p>Stopping a connector server does not unregister it from its
* MBean server. A connector server once stopped cannot be
* restarted.</p>
*
* <p>Each time a client connection is made or broken, a notification
* of class {@link JMXConnectionNotification} is emitted.</p>
*
* @since 1.5
*/
public abstract class JMXConnectorServer
extends NotificationBroadcasterSupport
implements JMXConnectorServerMBean, MBeanRegistration, JMXAddressable {
/** {@collect.stats}
* <p>Name of the attribute that specifies the authenticator for a
* connector server. The value associated with this attribute, if
* any, must be an object that implements the interface {@link
* JMXAuthenticator}.</p>
*/
public static final String AUTHENTICATOR =
"jmx.remote.authenticator";
/** {@collect.stats}
* <p>Constructs a connector server that will be registered as an
* MBean in the MBean server it is attached to. This constructor
* is typically called by one of the <code>createMBean</code>
* methods when creating, within an MBean server, a connector
* server that makes it available remotely.</p>
*/
public JMXConnectorServer() {
this(null);
}
/** {@collect.stats}
* <p>Constructs a connector server that is attached to the given
* MBean server. A connector server that is created in this way
* can be registered in a different MBean server.</p>
*
* @param mbeanServer the MBean server that this connector server
* is attached to. Null if this connector server will be attached
* to an MBean server by being registered in it.
*/
public JMXConnectorServer(MBeanServer mbeanServer) {
this.mbeanServer = mbeanServer;
}
/** {@collect.stats}
* <p>Returns the MBean server that this connector server is
* attached to.</p>
*
* @return the MBean server that this connector server is attached
* to, or null if it is not yet attached to an MBean server.
*/
public synchronized MBeanServer getMBeanServer() {
return mbeanServer;
}
public synchronized void setMBeanServerForwarder(MBeanServerForwarder mbsf)
{
if (mbsf == null)
throw new IllegalArgumentException("Invalid null argument: mbsf");
if (mbeanServer != null) mbsf.setMBeanServer(mbeanServer);
mbeanServer = mbsf;
}
public String[] getConnectionIds() {
synchronized (connectionIds) {
return connectionIds.toArray(new String[connectionIds.size()]);
}
}
/** {@collect.stats}
* <p>Returns a client stub for this connector server. A client
* stub is a serializable object whose {@link
* JMXConnector#connect(Map) connect} method can be used to make
* one new connection to this connector server.</p>
*
* <p>A given connector need not support the generation of client
* stubs. However, the connectors specified by the JMX Remote API do
* (JMXMP Connector and RMI Connector).</p>
*
* <p>The default implementation of this method uses {@link
* #getAddress} and {@link JMXConnectorFactory} to generate the
* stub, with code equivalent to the following:</p>
*
* <pre>
* JMXServiceURL addr = {@link #getAddress() getAddress()};
* return {@link JMXConnectorFactory#newJMXConnector(JMXServiceURL, Map)
* JMXConnectorFactory.newJMXConnector(addr, env)};
* </pre>
*
* <p>A connector server for which this is inappropriate must
* override this method so that it either implements the
* appropriate logic or throws {@link
* UnsupportedOperationException}.</p>
*
* @param env client connection parameters of the same sort that
* could be provided to {@link JMXConnector#connect(Map)
* JMXConnector.connect(Map)}. Can be null, which is equivalent
* to an empty map.
*
* @return a client stub that can be used to make a new connection
* to this connector server.
*
* @exception UnsupportedOperationException if this connector
* server does not support the generation of client stubs.
*
* @exception IllegalStateException if the JMXConnectorServer is
* not started (see {@link JMXConnectorServerMBean#isActive()}).
*
* @exception IOException if a communications problem means that a
* stub cannot be created.
**/
public JMXConnector toJMXConnector(Map<String,?> env)
throws IOException
{
if (!isActive()) throw new
IllegalStateException("Connector is not active");
JMXServiceURL addr = getAddress();
return JMXConnectorFactory.newJMXConnector(addr, env);
}
/** {@collect.stats}
* <p>Returns an array indicating the notifications that this MBean
* sends. The implementation in <code>JMXConnectorServer</code>
* returns an array with one element, indicating that it can emit
* notifications of class {@link JMXConnectionNotification} with
* the types defined in that class. A subclass that can emit other
* notifications should return an array that contains this element
* plus descriptions of the other notifications.</p>
*
* @return the array of possible notifications.
*/
public MBeanNotificationInfo[] getNotificationInfo() {
final String[] types = {
JMXConnectionNotification.OPENED,
JMXConnectionNotification.CLOSED,
JMXConnectionNotification.FAILED,
};
final String className = JMXConnectionNotification.class.getName();
final String description =
"A client connection has been opened or closed";
return new MBeanNotificationInfo[] {
new MBeanNotificationInfo(types, className, description),
};
}
/** {@collect.stats}
* <p>Called by a subclass when a new client connection is opened.
* Adds <code>connectionId</code> to the list returned by {@link
* #getConnectionIds()}, then emits a {@link
* JMXConnectionNotification} with type {@link
* JMXConnectionNotification#OPENED}.</p>
*
* @param connectionId the ID of the new connection. This must be
* different from the ID of any connection previously opened by
* this connector server.
*
* @param message the message for the emitted {@link
* JMXConnectionNotification}. Can be null. See {@link
* Notification#getMessage()}.
*
* @param userData the <code>userData</code> for the emitted
* {@link JMXConnectionNotification}. Can be null. See {@link
* Notification#getUserData()}.
*
* @exception NullPointerException if <code>connectionId</code> is
* null.
*/
protected void connectionOpened(String connectionId,
String message,
Object userData) {
if (connectionId == null)
throw new NullPointerException("Illegal null argument");
synchronized (connectionIds) {
connectionIds.add(connectionId);
}
sendNotification(JMXConnectionNotification.OPENED, connectionId,
message, userData);
}
/** {@collect.stats}
* <p>Called by a subclass when a client connection is closed
* normally. Removes <code>connectionId</code> from the list returned
* by {@link #getConnectionIds()}, then emits a {@link
* JMXConnectionNotification} with type {@link
* JMXConnectionNotification#CLOSED}.</p>
*
* @param connectionId the ID of the closed connection.
*
* @param message the message for the emitted {@link
* JMXConnectionNotification}. Can be null. See {@link
* Notification#getMessage()}.
*
* @param userData the <code>userData</code> for the emitted
* {@link JMXConnectionNotification}. Can be null. See {@link
* Notification#getUserData()}.
*
* @exception NullPointerException if <code>connectionId</code>
* is null.
*/
protected void connectionClosed(String connectionId,
String message,
Object userData) {
if (connectionId == null)
throw new NullPointerException("Illegal null argument");
synchronized (connectionIds) {
connectionIds.remove(connectionId);
}
sendNotification(JMXConnectionNotification.CLOSED, connectionId,
message, userData);
}
/** {@collect.stats}
* <p>Called by a subclass when a client connection fails.
* Removes <code>connectionId</code> from the list returned by
* {@link #getConnectionIds()}, then emits a {@link
* JMXConnectionNotification} with type {@link
* JMXConnectionNotification#FAILED}.</p>
*
* @param connectionId the ID of the failed connection.
*
* @param message the message for the emitted {@link
* JMXConnectionNotification}. Can be null. See {@link
* Notification#getMessage()}.
*
* @param userData the <code>userData</code> for the emitted
* {@link JMXConnectionNotification}. Can be null. See {@link
* Notification#getUserData()}.
*
* @exception NullPointerException if <code>connectionId</code> is
* null.
*/
protected void connectionFailed(String connectionId,
String message,
Object userData) {
if (connectionId == null)
throw new NullPointerException("Illegal null argument");
synchronized (connectionIds) {
connectionIds.remove(connectionId);
}
sendNotification(JMXConnectionNotification.FAILED, connectionId,
message, userData);
}
private void sendNotification(String type, String connectionId,
String message, Object userData) {
Notification notif =
new JMXConnectionNotification(type,
getNotificationSource(),
connectionId,
nextSequenceNumber(),
message,
userData);
sendNotification(notif);
}
private synchronized Object getNotificationSource() {
if (myName != null)
return myName;
else
return this;
}
private static long nextSequenceNumber() {
synchronized (sequenceNumberLock) {
return sequenceNumber++;
}
}
// implements MBeanRegistration
/** {@collect.stats}
* <p>Called by an MBean server when this connector server is
* registered in that MBean server. This connector server becomes
* attached to the MBean server and its {@link #getMBeanServer()}
* method will return <code>mbs</code>.</p>
*
* <p>If this connector server is already attached to an MBean
* server, this method has no effect. The MBean server it is
* attached to is not necessarily the one it is being registered
* in.</p>
*
* @param mbs the MBean server in which this connection server is
* being registered.
*
* @param name The object name of the MBean.
*
* @return The name under which the MBean is to be registered.
*
* @exception NullPointerException if <code>mbs</code> or
* <code>name</code> is null.
*/
public synchronized ObjectName preRegister(MBeanServer mbs,
ObjectName name) {
if (mbs == null || name == null)
throw new NullPointerException("Null MBeanServer or ObjectName");
if (mbeanServer == null) {
mbeanServer = mbs;
myName = name;
}
return name;
}
public void postRegister(Boolean registrationDone) {
// do nothing
}
/** {@collect.stats}
* <p>Called by an MBean server when this connector server is
* unregistered from that MBean server. If this connector server
* was attached to that MBean server by being registered in it,
* and if the connector server is still active,
* then unregistering it will call the {@link #stop stop} method.
* If the <code>stop</code> method throws an exception, the
* unregistration attempt will fail. It is recommended to call
* the <code>stop</code> method explicitly before unregistering
* the MBean.</p>
*
* @exception IOException if thrown by the {@link #stop stop} method.
*/
public synchronized void preDeregister() throws Exception {
if (myName != null && isActive()) {
stop();
myName = null; // just in case stop is buggy and doesn't stop
}
}
public void postDeregister() {
myName = null;
}
/** {@collect.stats}
* The MBeanServer used by this server to execute a client request.
*/
private MBeanServer mbeanServer = null;
/** {@collect.stats}
* The name used to registered this server in an MBeanServer.
* It is null if the this server is not registered or has been unregistered.
*/
private ObjectName myName;
private List<String> connectionIds = new ArrayList<String>();
private static final int[] sequenceNumberLock = new int[0];
private static long sequenceNumber;
}
| Java |
/*
* Copyright (c) 2003, 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.remote;
import javax.management.MBeanServer;
/** {@collect.stats}
* <p>An object of this class implements the MBeanServer interface and
* wraps another object that also implements that interface.
* Typically, an implementation of this interface performs some action
* in some or all methods of the <code>MBeanServer</code> interface
* before and/or after forwarding the method to the wrapped object.
* Examples include security checking and logging.</p>
*
* @since 1.5
*/
public interface MBeanServerForwarder extends MBeanServer {
/** {@collect.stats}
* Returns the MBeanServer object to which requests will be forwarded.
*
* @return the MBeanServer object to which requests will be forwarded,
* or null if there is none.
*
* @see #setMBeanServer
*/
public MBeanServer getMBeanServer();
/** {@collect.stats}
* Sets the MBeanServer object to which requests will be forwarded
* after treatment by this object.
*
* @param mbs the MBeanServer object to which requests will be forwarded.
*
* @exception IllegalArgumentException if this object is already
* forwarding to an MBeanServer object or if <code>mbs</code> is
* null or if <code>mbs</code> is identical to this object.
*
* @see #getMBeanServer
*/
public void setMBeanServer(MBeanServer mbs);
}
| Java |
/*
* Copyright (c) 2002, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management.remote;
import com.sun.jmx.mbeanserver.Util;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Iterator;
import java.util.ServiceLoader;
import java.util.StringTokenizer;
import java.security.AccessController;
import java.security.PrivilegedAction;
import com.sun.jmx.remote.util.ClassLogger;
import com.sun.jmx.remote.util.EnvHelp;
/** {@collect.stats}
* <p>Factory to create JMX API connector clients. There
* are no instances of this class.</p>
*
* <p>Connections are usually made using the {@link
* #connect(JMXServiceURL) connect} method of this class. More
* advanced applications can separate the creation of the connector
* client, using {@link #newJMXConnector(JMXServiceURL, Map)
* newJMXConnector} and the establishment of the connection itself, using
* {@link JMXConnector#connect(Map)}.</p>
*
* <p>Each client is created by an instance of {@link
* JMXConnectorProvider}. This instance is found as follows. Suppose
* the given {@link JMXServiceURL} looks like
* <code>"service:jmx:<em>protocol</em>:<em>remainder</em>"</code>.
* Then the factory will attempt to find the appropriate {@link
* JMXConnectorProvider} for <code><em>protocol</em></code>. Each
* occurrence of the character <code>+</code> or <code>-</code> in
* <code><em>protocol</em></code> is replaced by <code>.</code> or
* <code>_</code>, respectively.</p>
*
* <p>A <em>provider package list</em> is searched for as follows:</p>
*
* <ol>
*
* <li>If the <code>environment</code> parameter to {@link
* #newJMXConnector(JMXServiceURL, Map) newJMXConnector} contains the
* key <code>jmx.remote.protocol.provider.pkgs</code> then the
* associated value is the provider package list.
*
* <li>Otherwise, if the system property
* <code>jmx.remote.protocol.provider.pkgs</code> exists, then its value
* is the provider package list.
*
* <li>Otherwise, there is no provider package list.
*
* </ol>
*
* <p>The provider package list is a string that is interpreted as a
* list of non-empty Java package names separated by vertical bars
* (<code>|</code>). If the string is empty, then so is the provider
* package list. If the provider package list is not a String, or if
* it contains an element that is an empty string, a {@link
* JMXProviderException} is thrown.</p>
*
* <p>If the provider package list exists and is not empty, then for
* each element <code><em>pkg</em></code> of the list, the factory
* will attempt to load the class
*
* <blockquote>
* <code><em>pkg</em>.<em>protocol</em>.ClientProvider</code>
* </blockquote>
* <p>If the <code>environment</code> parameter to {@link
* #newJMXConnector(JMXServiceURL, Map) newJMXConnector} contains the
* key <code>jmx.remote.protocol.provider.class.loader</code> then the
* associated value is the class loader to use to load the provider.
* If the associated value is not an instance of {@link
* java.lang.ClassLoader}, an {@link
* java.lang.IllegalArgumentException} is thrown.</p>
*
* <p>If the <code>jmx.remote.protocol.provider.class.loader</code>
* key is not present in the <code>environment</code> parameter, the
* calling thread's context class loader is used.</p>
*
* <p>If the attempt to load this class produces a {@link
* ClassNotFoundException}, the search for a handler continues with
* the next element of the list.</p>
*
* <p>Otherwise, a problem with the provider found is signalled by a
* {@link JMXProviderException} whose {@link
* JMXProviderException#getCause() <em>cause</em>} indicates the underlying
* exception, as follows:</p>
*
* <ul>
*
* <li>if the attempt to load the class produces an exception other
* than <code>ClassNotFoundException</code>, that is the
* <em>cause</em>;
*
* <li>if {@link Class#newInstance()} for the class produces an
* exception, that is the <em>cause</em>.
*
* </ul>
*
* <p>If no provider is found by the above steps, including the
* default case where there is no provider package list, then the
* implementation will use its own provider for
* <code><em>protocol</em></code>, or it will throw a
* <code>MalformedURLException</code> if there is none. An
* implementation may choose to find providers by other means. For
* example, it may support the <a
* href="{@docRoot}/../technotes/guides/jar/jar.html#Service Provider">
* JAR conventions for service providers</a>, where the service
* interface is <code>JMXConnectorProvider</code>.</p>
*
* <p>Every implementation must support the RMI connector protocols,
* specified with the string <code>rmi</code> or
* <code>iiop</code>.</p>
*
* <p>Once a provider is found, the result of the
* <code>newJMXConnector</code> method is the result of calling {@link
* JMXConnectorProvider#newJMXConnector(JMXServiceURL,Map) newJMXConnector}
* on the provider.</p>
*
* <p>The <code>Map</code> parameter passed to the
* <code>JMXConnectorProvider</code> is a new read-only
* <code>Map</code> that contains all the entries that were in the
* <code>environment</code> parameter to {@link
* #newJMXConnector(JMXServiceURL,Map)
* JMXConnectorFactory.newJMXConnector}, if there was one.
* Additionally, if the
* <code>jmx.remote.protocol.provider.class.loader</code> key is not
* present in the <code>environment</code> parameter, it is added to
* the new read-only <code>Map</code>. The associated value is the
* calling thread's context class loader.</p>
*
* @since 1.5
*/
public class JMXConnectorFactory {
/** {@collect.stats}
* <p>Name of the attribute that specifies the default class
* loader. This class loader is used to deserialize return values and
* exceptions from remote <code>MBeanServerConnection</code>
* calls. The value associated with this attribute is an instance
* of {@link ClassLoader}.</p>
*/
public static final String DEFAULT_CLASS_LOADER =
"jmx.remote.default.class.loader";
/** {@collect.stats}
* <p>Name of the attribute that specifies the provider packages
* that are consulted when looking for the handler for a protocol.
* The value associated with this attribute is a string with
* package names separated by vertical bars (<code>|</code>).</p>
*/
public static final String PROTOCOL_PROVIDER_PACKAGES =
"jmx.remote.protocol.provider.pkgs";
/** {@collect.stats}
* <p>Name of the attribute that specifies the class
* loader for loading protocol providers.
* The value associated with this attribute is an instance
* of {@link ClassLoader}.</p>
*/
public static final String PROTOCOL_PROVIDER_CLASS_LOADER =
"jmx.remote.protocol.provider.class.loader";
private static final String PROTOCOL_PROVIDER_DEFAULT_PACKAGE =
"com.sun.jmx.remote.protocol";
private static final ClassLogger logger =
new ClassLogger("javax.management.remote.misc", "JMXConnectorFactory");
/** {@collect.stats} There are no instances of this class. */
private JMXConnectorFactory() {
}
/** {@collect.stats}
* <p>Creates a connection to the connector server at the given
* address.</p>
*
* <p>This method is equivalent to {@link
* #connect(JMXServiceURL,Map) connect(serviceURL, null)}.</p>
*
* @param serviceURL the address of the connector server to
* connect to.
*
* @return a <code>JMXConnector</code> whose {@link
* JMXConnector#connect connect} method has been called.
*
* @exception NullPointerException if <code>serviceURL</code> is null.
*
* @exception IOException if the connector client or the
* connection cannot be made because of a communication problem.
*
* @exception SecurityException if the connection cannot be made
* for security reasons.
*/
public static JMXConnector connect(JMXServiceURL serviceURL)
throws IOException {
return connect(serviceURL, null);
}
/** {@collect.stats}
* <p>Creates a connection to the connector server at the given
* address.</p>
*
* <p>This method is equivalent to:</p>
*
* <pre>
* JMXConnector conn = JMXConnectorFactory.newJMXConnector(serviceURL,
* environment);
* conn.connect(environment);
* </pre>
*
* @param serviceURL the address of the connector server to connect to.
*
* @param environment a set of attributes to determine how the
* connection is made. This parameter can be null. Keys in this
* map must be Strings. The appropriate type of each associated
* value depends on the attribute. The contents of
* <code>environment</code> are not changed by this call.
*
* @return a <code>JMXConnector</code> representing the newly-made
* connection. Each successful call to this method produces a
* different object.
*
* @exception NullPointerException if <code>serviceURL</code> is null.
*
* @exception IOException if the connector client or the
* connection cannot be made because of a communication problem.
*
* @exception SecurityException if the connection cannot be made
* for security reasons.
*/
public static JMXConnector connect(JMXServiceURL serviceURL,
Map<String,?> environment)
throws IOException {
if (serviceURL == null)
throw new NullPointerException("Null JMXServiceURL");
JMXConnector conn = newJMXConnector(serviceURL, environment);
conn.connect(environment);
return conn;
}
/** {@collect.stats}
* <p>Creates a connector client for the connector server at the
* given address. The resultant client is not connected until its
* {@link JMXConnector#connect(Map) connect} method is called.</p>
*
* @param serviceURL the address of the connector server to connect to.
*
* @param environment a set of attributes to determine how the
* connection is made. This parameter can be null. Keys in this
* map must be Strings. The appropriate type of each associated
* value depends on the attribute. The contents of
* <code>environment</code> are not changed by this call.
*
* @return a <code>JMXConnector</code> representing the new
* connector client. Each successful call to this method produces
* a different object.
*
* @exception NullPointerException if <code>serviceURL</code> is null.
*
* @exception IOException if the connector client cannot be made
* because of a communication problem.
*
* @exception MalformedURLException if there is no provider for the
* protocol in <code>serviceURL</code>.
*
* @exception JMXProviderException if there is a provider for the
* protocol in <code>serviceURL</code> but it cannot be used for
* some reason.
*/
public static JMXConnector newJMXConnector(JMXServiceURL serviceURL,
Map<String,?> environment)
throws IOException {
Map<String, Object> envcopy;
if (environment == null)
envcopy = new HashMap<String, Object>();
else {
EnvHelp.checkAttributes(environment);
envcopy = new HashMap<String, Object>(environment);
}
final ClassLoader loader = resolveClassLoader(envcopy);
final Class<JMXConnectorProvider> targetInterface = JMXConnectorProvider.class;
final String protocol = serviceURL.getProtocol();
final String providerClassName = "ClientProvider";
JMXConnectorProvider provider =
getProvider(serviceURL, envcopy, providerClassName,
targetInterface, loader);
IOException exception = null;
if (provider == null) {
// Loader is null when context class loader is set to null
// and no loader has been provided in map.
// com.sun.jmx.remote.util.Service class extracted from j2se
// provider search algorithm doesn't handle well null classloader.
if (loader != null) {
try {
JMXConnector connection =
getConnectorAsService(loader, serviceURL, envcopy);
if (connection != null)
return connection;
} catch (JMXProviderException e) {
throw e;
} catch (IOException e) {
exception = e;
}
}
provider =
getProvider(protocol, PROTOCOL_PROVIDER_DEFAULT_PACKAGE,
JMXConnectorFactory.class.getClassLoader(),
providerClassName, targetInterface);
}
if (provider == null) {
MalformedURLException e =
new MalformedURLException("Unsupported protocol: " + protocol);
if (exception == null) {
throw e;
} else {
throw EnvHelp.initCause(e, exception);
}
}
envcopy = Collections.unmodifiableMap(envcopy);
return provider.newJMXConnector(serviceURL, envcopy);
}
private static String resolvePkgs(Map env) throws JMXProviderException {
Object pkgsObject = null;
if (env != null)
pkgsObject = env.get(PROTOCOL_PROVIDER_PACKAGES);
if (pkgsObject == null)
pkgsObject =
AccessController.doPrivileged(new PrivilegedAction<Object>() {
public Object run() {
return System.getProperty(PROTOCOL_PROVIDER_PACKAGES);
}
});
if (pkgsObject == null)
return null;
if (!(pkgsObject instanceof String)) {
final String msg = "Value of " + PROTOCOL_PROVIDER_PACKAGES +
" parameter is not a String: " +
pkgsObject.getClass().getName();
throw new JMXProviderException(msg);
}
final String pkgs = (String) pkgsObject;
if (pkgs.trim().equals(""))
return null;
// pkgs may not contain an empty element
if (pkgs.startsWith("|") || pkgs.endsWith("|") ||
pkgs.indexOf("||") >= 0) {
final String msg = "Value of " + PROTOCOL_PROVIDER_PACKAGES +
" contains an empty element: " + pkgs;
throw new JMXProviderException(msg);
}
return pkgs;
}
static <T> T getProvider(JMXServiceURL serviceURL,
Map<String, Object> environment,
String providerClassName,
Class<T> targetInterface,
ClassLoader loader)
throws IOException {
final String protocol = serviceURL.getProtocol();
final String pkgs = resolvePkgs(environment);
T instance = null;
if (pkgs != null) {
environment.put(PROTOCOL_PROVIDER_CLASS_LOADER, loader);
instance =
getProvider(protocol, pkgs, loader, providerClassName,
targetInterface);
}
return instance;
}
static <T> Iterator<T> getProviderIterator(final Class<T> providerClass,
final ClassLoader loader) {
ServiceLoader<T> serviceLoader =
ServiceLoader.load(providerClass,
loader);
return serviceLoader.iterator();
}
private static JMXConnector getConnectorAsService(ClassLoader loader,
JMXServiceURL url,
Map<String, ?> map)
throws IOException {
Iterator<JMXConnectorProvider> providers =
getProviderIterator(JMXConnectorProvider.class, loader);
JMXConnector connection = null;
IOException exception = null;
while(providers.hasNext()) {
try {
connection = providers.next().newJMXConnector(url, map);
return connection;
} catch (JMXProviderException e) {
throw e;
} catch (Exception e) {
if (logger.traceOn())
logger.trace("getConnectorAsService",
"URL[" + url +
"] Service provider exception: " + e);
if (!(e instanceof MalformedURLException)) {
if (exception == null) {
if (exception instanceof IOException) {
exception = (IOException) e;
} else {
exception = EnvHelp.initCause(
new IOException(e.getMessage()), e);
}
}
}
continue;
}
}
if (exception == null)
return null;
else
throw exception;
}
static <T> T getProvider(String protocol,
String pkgs,
ClassLoader loader,
String providerClassName,
Class<T> targetInterface)
throws IOException {
StringTokenizer tokenizer = new StringTokenizer(pkgs, "|");
while (tokenizer.hasMoreTokens()) {
String pkg = tokenizer.nextToken();
String className = (pkg + "." + protocol2package(protocol) +
"." + providerClassName);
Class<?> providerClass;
try {
providerClass = Class.forName(className, true, loader);
} catch (ClassNotFoundException e) {
//Add trace.
continue;
}
if (!targetInterface.isAssignableFrom(providerClass)) {
final String msg =
"Provider class does not implement " +
targetInterface.getName() + ": " +
providerClass.getName();
throw new JMXProviderException(msg);
}
// We have just proved that this cast is correct
Class<? extends T> providerClassT = Util.cast(providerClass);
try {
return providerClassT.newInstance();
} catch (Exception e) {
final String msg =
"Exception when instantiating provider [" + className +
"]";
throw new JMXProviderException(msg, e);
}
}
return null;
}
static ClassLoader resolveClassLoader(Map environment) {
ClassLoader loader = null;
if (environment != null) {
try {
loader = (ClassLoader)
environment.get(PROTOCOL_PROVIDER_CLASS_LOADER);
} catch (ClassCastException e) {
final String msg =
"The ClassLoader supplied in the environment map using " +
"the " + PROTOCOL_PROVIDER_CLASS_LOADER +
" attribute is not an instance of java.lang.ClassLoader";
throw new IllegalArgumentException(msg);
}
}
if (loader == null)
loader =
AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
public ClassLoader run() {
return
Thread.currentThread().getContextClassLoader();
}
});
return loader;
}
private static String protocol2package(String protocol) {
return protocol.replace('+', '.').replace('-', '_');
}
}
| Java |
/*
* Copyright (c) 2003, 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.remote;
import javax.management.Notification;
import javax.management.ObjectName;
/** {@collect.stats}
* <p>Notification emitted when a client connection is opened or
* closed or when notifications are lost. These notifications are
* sent by connector servers (instances of {@link JMXConnectorServer})
* and by connector clients (instances of {@link JMXConnector}). For
* certain connectors, a session can consist of a sequence of
* connections. Connection-opened and connection-closed notifications
* will be sent for each one.</p>
*
* <p>The notification type is one of the following:</p>
*
* <table>
*
* <tr>
* <th align=left>Type</th>
* <th align=left>Meaning</th>
* </tr>
*
* <tr>
* <td><code>jmx.remote.connection.opened</code></td>
* <td>A new client connection has been opened.</td>
* </tr>
*
* <tr>
* <td><code>jmx.remote.connection.closed</code></td>
* <td>A client connection has been closed.</td>
* </tr>
*
* <tr>
* <td><code>jmx.remote.connection.failed</code></td>
* <td>A client connection has failed unexpectedly.</td>
* </tr>
*
* <tr>
* <td><code>jmx.remote.connection.notifs.lost</code></td>
* <td>A client connection has potentially lost notifications. This
* notification only appears on the client side.</td>
* </tr>
* </table>
*
* <p>The <code>timeStamp</code> of the notification is a time value
* (consistent with {@link System#currentTimeMillis()}) indicating
* when the notification was constructed.</p>
*
* @since 1.5
*/
public class JMXConnectionNotification extends Notification {
private static final long serialVersionUID = -2331308725952627538L;
/** {@collect.stats}
* <p>Notification type string for a connection-opened notification.
*/
public static final String OPENED = "jmx.remote.connection.opened";
/** {@collect.stats}
* <p>Notification type string for a connection-closed notification.
*/
public static final String CLOSED = "jmx.remote.connection.closed";
/** {@collect.stats}
* <p>Notification type string for a connection-failed notification.
*/
public static final String FAILED = "jmx.remote.connection.failed";
/** {@collect.stats}
* <p>Notification type string for a connection that has possibly
* lost notifications.</p>
*/
public static final String NOTIFS_LOST =
"jmx.remote.connection.notifs.lost";
/** {@collect.stats}
* Constructs a new connection notification. The {@link
* #getSource() source} of the notification depends on whether it
* is being sent by a connector server or a connector client:
*
* <ul>
*
* <li>For a connector server, if it is registered in an MBean
* server, the source is the {@link ObjectName} under which it is
* registered. Otherwise, it is a reference to the connector
* server object itself, an instance of a subclass of {@link
* JMXConnectorServer}.
*
* <li>For a connector client, the source is a reference to the
* connector client object, an instance of a class implementing
* {@link JMXConnector}.
*
* </ul>
*
* @param type the type of the notification. This is usually one
* of the constants {@link #OPENED}, {@link #CLOSED}, {@link
* #FAILED}, {@link #NOTIFS_LOST}. It is not an error for it to
* be a different string.
*
* @param source the connector server or client emitting the
* notification.
*
* @param connectionId the ID of the connection within its
* connector server.
*
* @param sequenceNumber a non-negative integer. It is expected
* but not required that this number will be greater than any
* previous <code>sequenceNumber</code> in a notification from
* this source.
*
* @param message an unspecified text message, typically containing
* a human-readable description of the event. Can be null.
*
* @param userData an object whose type and meaning is defined by
* the connector server. Can be null.
*
* @exception NullPointerException if <code>type</code>,
* <code>source</code>, or <code>connectionId</code> is null.
*
* @exception IllegalArgumentException if
* <code>sequenceNumber</code> is negative.
*/
public JMXConnectionNotification(String type,
Object source,
String connectionId,
long sequenceNumber,
String message,
Object userData) {
/* We don't know whether the parent class (Notification) will
throw an exception if the type or source is null, because
JMX 1.2 doesn't specify that. So we make sure it is not
null, in case it would throw the wrong exception
(e.g. IllegalArgumentException instead of
NullPointerException). Likewise for the sequence number. */
super((String) nonNull(type),
nonNull(source),
Math.max(0, sequenceNumber),
System.currentTimeMillis(),
message);
if (type == null || source == null || connectionId == null)
throw new NullPointerException("Illegal null argument");
if (sequenceNumber < 0)
throw new IllegalArgumentException("Negative sequence number");
this.connectionId = connectionId;
setUserData(userData);
}
private static Object nonNull(Object arg) {
if (arg == null)
return "";
else
return arg;
}
/** {@collect.stats}
* <p>The connection ID to which this notification pertains.
*
* @return the connection ID.
*/
public String getConnectionId() {
return connectionId;
}
/** {@collect.stats}
* @serial The connection ID to which this notification pertains.
* @see #getConnectionId()
**/
private final String connectionId;
}
| Java |
/*
* Copyright (c) 2002, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management.remote;
import java.io.IOException;
import java.util.Map;
/** {@collect.stats}
* <p>A provider for creating JMX API connector clients using a given
* protocol. Instances of this interface are created by {@link
* JMXConnectorFactory} as part of its {@link
* JMXConnectorFactory#newJMXConnector(JMXServiceURL, Map)
* newJMXConnector} method.</p>
*
* @since 1.5
*/
public interface JMXConnectorProvider {
/** {@collect.stats}
* <p>Creates a new connector client that is ready to connect
* to the connector server at the given address. Each successful
* call to this method produces a different
* <code>JMXConnector</code> object.</p>
*
* @param serviceURL the address of the connector server to connect to.
*
* @param environment a read-only Map containing named attributes
* to determine how the connection is made. Keys in this map must
* be Strings. The appropriate type of each associated value
* depends on the attribute.</p>
*
* @return a <code>JMXConnector</code> representing the new
* connector client. Each successful call to this method produces
* a different object.
*
* @exception NullPointerException if <code>serviceURL</code> or
* <code>environment</code> is null.
*
* @exception IOException It is recommended for a provider
* implementation to throw {@code MalformedURLException} if the
* protocol in the {@code serviceURL} is not recognized by this
* provider, {@code JMXProviderException} if this is a provider
* for the protocol in {@code serviceURL} but it cannot be used
* for some reason or any other {@code IOException} if the
* connection cannot be made because of a communication problem.
*/
public JMXConnector newJMXConnector(JMXServiceURL serviceURL,
Map<String,?> environment)
throws IOException;
}
| Java |
/*
* Copyright (c) 2003, 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.remote;
import java.security.BasicPermission;
/** {@collect.stats}
* <p>Permission required by an authentication identity to perform
* operations on behalf of an authorization identity.</p>
*
* <p>A SubjectDelegationPermission contains a name (also referred
* to as a "target name") but no actions list; you either have the
* named permission or you don't.</p>
*
* <p>The target name is the name of the authorization principal
* classname followed by a period and the authorization principal
* name, that is
* <code>"<em>PrincipalClassName</em>.<em>PrincipalName</em>"</code>.</p>
*
* <p>An asterisk may appear by itself, or if immediately preceded
* by a "." may appear at the end of the target name, to signify a
* wildcard match.</p>
*
* <p>For example, "*", "javax.management.remote.JMXPrincipal.*" and
* "javax.management.remote.JMXPrincipal.delegate" are valid target
* names. The first one denotes any principal name from any principal
* class, the second one denotes any principal name of the concrete
* principal class <code>javax.management.remote.JMXPrincipal</code>
* and the third one denotes a concrete principal name
* <code>delegate</code> of the concrete principal class
* <code>javax.management.remote.JMXPrincipal</code>.</p>
*
* @since 1.5
*/
public final class SubjectDelegationPermission extends BasicPermission {
private static final long serialVersionUID = 1481618113008682343L;
/** {@collect.stats}
* Creates a new SubjectDelegationPermission with the specified name.
* The name is the symbolic name of the SubjectDelegationPermission.
*
* @param name the name of the SubjectDelegationPermission
*
* @throws NullPointerException if <code>name</code> is
* <code>null</code>.
* @throws IllegalArgumentException if <code>name</code> is empty.
*/
public SubjectDelegationPermission(String name) {
super(name);
}
/** {@collect.stats}
* Creates a new SubjectDelegationPermission object with the
* specified name. The name is the symbolic name of the
* SubjectDelegationPermission, and the actions String is
* currently unused and must be null.
*
* @param name the name of the SubjectDelegationPermission
* @param actions must be null.
*
* @throws NullPointerException if <code>name</code> is
* <code>null</code>.
* @throws IllegalArgumentException if <code>name</code> is empty
* or <code>actions</code> is not null.
*/
public SubjectDelegationPermission(String name, String actions) {
super(name, actions);
if (actions != null)
throw new IllegalArgumentException("Non-null actions");
}
}
| Java |
/*
* Copyright (c) 2003, 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.remote;
import java.io.IOException;
import java.util.Map;
import javax.management.MBeanServer;
/** {@collect.stats}
* <p>A provider for creating JMX API connector servers using a given
* protocol. Instances of this interface are created by {@link
* JMXConnectorServerFactory} as part of its {@link
* JMXConnectorServerFactory#newJMXConnectorServer(JMXServiceURL,Map,MBeanServer)
* newJMXConnectorServer} method.</p>
*
* @since 1.5
*/
public interface JMXConnectorServerProvider {
/** {@collect.stats}
* <p>Creates a new connector server at the given address. Each
* successful call to this method produces a different
* <code>JMXConnectorServer</code> object.</p>
*
* @param serviceURL the address of the new connector server. The
* actual address of the new connector server, as returned by its
* {@link JMXConnectorServer#getAddress() getAddress} method, will
* not necessarily be exactly the same. For example, it might
* include a port number if the original address did not.
*
* @param environment a read-only Map containing named attributes
* to control the new connector server's behavior. Keys in this
* map must be Strings. The appropriate type of each associated
* value depends on the attribute.
*
* @param mbeanServer the MBean server that this connector server
* is attached to. Null if this connector server will be attached
* to an MBean server by being registered in it.
*
* @return a <code>JMXConnectorServer</code> representing the new
* connector server. Each successful call to this method produces
* a different object.
*
* @exception NullPointerException if <code>serviceURL</code> or
* <code>environment</code> is null.
*
* @exception IOException It is recommended for a provider
* implementation to throw {@code MalformedURLException} if the
* protocol in the {@code serviceURL} is not recognized by this
* provider, {@code JMXProviderException} if this is a provider
* for the protocol in {@code serviceURL} but it cannot be used
* for some reason or any other {@code IOException} if the
* connector server cannot be created.
*/
public JMXConnectorServer newJMXConnectorServer(JMXServiceURL serviceURL,
Map<String,?> environment,
MBeanServer mbeanServer)
throws IOException;
}
| Java |
/*
* Copyright (c) 2002, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management.remote;
import java.io.Closeable;
import java.io.IOException;
import java.util.Map;
import javax.management.ListenerNotFoundException;
import javax.management.MBeanServerConnection;
import javax.management.NotificationFilter;
import javax.management.NotificationListener;
import javax.security.auth.Subject;
/** {@collect.stats}
* <p>The client end of a JMX API connector. An object of this type can
* be used to establish a connection to a connector server.</p>
*
* <p>A newly-created object of this type is unconnected. Its {@link
* #connect connect} method must be called before it can be used.
* However, objects created by {@link
* JMXConnectorFactory#connect(JMXServiceURL, Map)
* JMXConnectorFactory.connect} are already connected.</p>
*
* @since 1.5
*/
public interface JMXConnector extends Closeable {
/** {@collect.stats}
* <p>Name of the attribute that specifies the credentials to send
* to the connector server during connection. The value
* associated with this attribute, if any, is a serializable
* object of an appropriate type for the server's {@link
* JMXAuthenticator}.
*/
public static final String CREDENTIALS =
"jmx.remote.credentials";
/** {@collect.stats}
* <p>Establishes the connection to the connector server. This
* method is equivalent to {@link #connect(Map)
* connect(null)}.</p>
*
* @exception IOException if the connection could not be made
* because of a communication problem.
*
* @exception SecurityException if the connection could not be
* made for security reasons.
*/
public void connect() throws IOException;
/** {@collect.stats}
* <p>Establishes the connection to the connector server.</p>
*
* <p>If <code>connect</code> has already been called successfully
* on this object, calling it again has no effect. If, however,
* {@link #close} was called after <code>connect</code>, the new
* <code>connect</code> will throw an <code>IOException</code>.<p>
*
* <p>Otherwise, either <code>connect</code> has never been called
* on this object, or it has been called but produced an
* exception. Then calling <code>connect</code> will attempt to
* establish a connection to the connector server.</p>
*
* @param env the properties of the connection. Properties in
* this map override properties in the map specified when the
* <code>JMXConnector</code> was created, if any. This parameter
* can be null, which is equivalent to an empty map.
*
* @exception IOException if the connection could not be made
* because of a communication problem.
*
* @exception SecurityException if the connection could not be
* made for security reasons.
*/
public void connect(Map<String,?> env) throws IOException;
/** {@collect.stats}
* <p>Returns an <code>MBeanServerConnection</code> object
* representing a remote MBean server. For a given
* <code>JMXConnector</code>, two successful calls to this method
* will usually return the same <code>MBeanServerConnection</code>
* object, though this is not required.</p>
*
* <p>For each method in the returned
* <code>MBeanServerConnection</code>, calling the method causes
* the corresponding method to be called in the remote MBean
* server. The value returned by the MBean server method is the
* value returned to the client. If the MBean server method
* produces an <code>Exception</code>, the same
* <code>Exception</code> is seen by the client. If the MBean
* server method, or the attempt to call it, produces an
* <code>Error</code>, the <code>Error</code> is wrapped in a
* {@link JMXServerErrorException}, which is seen by the
* client.</p>
*
* <p>Calling this method is equivalent to calling
* {@link #getMBeanServerConnection(Subject) getMBeanServerConnection(null)}
* meaning that no delegation subject is specified and that all the
* operations called on the <code>MBeanServerConnection</code> must
* use the authenticated subject, if any.</p>
*
* @return an object that implements the
* <code>MBeanServerConnection</code> interface by forwarding its
* methods to the remote MBean server.
*
* @exception IOException if a valid
* <code>MBeanServerConnection</code> cannot be created, for
* instance because the connection to the remote MBean server has
* not yet been established (with the {@link #connect(Map)
* connect} method), or it has been closed, or it has broken.
*/
public MBeanServerConnection getMBeanServerConnection()
throws IOException;
/** {@collect.stats}
* <p>Returns an <code>MBeanServerConnection</code> object representing
* a remote MBean server on which operations are performed on behalf of
* the supplied delegation subject. For a given <code>JMXConnector</code>
* and <code>Subject</code>, two successful calls to this method will
* usually return the same <code>MBeanServerConnection</code> object,
* though this is not required.</p>
*
* <p>For each method in the returned
* <code>MBeanServerConnection</code>, calling the method causes
* the corresponding method to be called in the remote MBean
* server on behalf of the given delegation subject instead of the
* authenticated subject. The value returned by the MBean server
* method is the value returned to the client. If the MBean server
* method produces an <code>Exception</code>, the same
* <code>Exception</code> is seen by the client. If the MBean
* server method, or the attempt to call it, produces an
* <code>Error</code>, the <code>Error</code> is wrapped in a
* {@link JMXServerErrorException}, which is seen by the
* client.</p>
*
* @param delegationSubject the <code>Subject</code> on behalf of
* which requests will be performed. Can be null, in which case
* requests will be performed on behalf of the authenticated
* Subject, if any.
*
* @return an object that implements the <code>MBeanServerConnection</code>
* interface by forwarding its methods to the remote MBean server on behalf
* of a given delegation subject.
*
* @exception IOException if a valid <code>MBeanServerConnection</code>
* cannot be created, for instance because the connection to the remote
* MBean server has not yet been established (with the {@link #connect(Map)
* connect} method), or it has been closed, or it has broken.
*/
public MBeanServerConnection getMBeanServerConnection(
Subject delegationSubject)
throws IOException;
/** {@collect.stats}
* <p>Closes the client connection to its server. Any ongoing or new
* request using the MBeanServerConnection returned by {@link
* #getMBeanServerConnection()} will get an
* <code>IOException</code>.</p>
*
* <p>If <code>close</code> has already been called successfully
* on this object, calling it again has no effect. If
* <code>close</code> has never been called, or if it was called
* but produced an exception, an attempt will be made to close the
* connection. This attempt can succeed, in which case
* <code>close</code> will return normally, or it can generate an
* exception.</p>
*
* <p>Closing a connection is a potentially slow operation. For
* example, if the server has crashed, the close operation might
* have to wait for a network protocol timeout. Callers that do
* not want to block in a close operation should do it in a
* separate thread.</p>
*
* @exception IOException if the connection cannot be closed
* cleanly. If this exception is thrown, it is not known whether
* the server end of the connection has been cleanly closed.
*/
public void close() throws IOException;
/** {@collect.stats}
* <p>Adds a listener to be informed of changes in connection
* status. The listener will receive notifications of type {@link
* JMXConnectionNotification}. An implementation can send other
* types of notifications too.</p>
*
* <p>Any number of listeners can be added with this method. The
* same listener can be added more than once with the same or
* different values for the filter and handback. There is no
* special treatment of a duplicate entry. For example, if a
* listener is registered twice with no filter, then its
* <code>handleNotification</code> method will be called twice for
* each notification.</p>
*
* @param listener a listener to receive connection status
* notifications.
* @param filter a filter to select which notifications are to be
* delivered to the listener, or null if all notifications are to
* be delivered.
* @param handback an object to be given to the listener along
* with each notification. Can be null.
*
* @exception NullPointerException if <code>listener</code> is
* null.
*
* @see #removeConnectionNotificationListener
* @see javax.management.NotificationBroadcaster#addNotificationListener
*/
public void
addConnectionNotificationListener(NotificationListener listener,
NotificationFilter filter,
Object handback);
/** {@collect.stats}
* <p>Removes a listener from the list to be informed of changes
* in status. The listener must previously have been added. If
* there is more than one matching listener, all are removed.</p>
*
* @param listener a listener to receive connection status
* notifications.
*
* @exception NullPointerException if <code>listener</code> is
* null.
*
* @exception ListenerNotFoundException if the listener is not
* registered with this <code>JMXConnector</code>.
*
* @see #removeConnectionNotificationListener(NotificationListener,
* NotificationFilter, Object)
* @see #addConnectionNotificationListener
* @see javax.management.NotificationEmitter#removeNotificationListener
*/
public void
removeConnectionNotificationListener(NotificationListener listener)
throws ListenerNotFoundException;
/** {@collect.stats}
* <p>Removes a listener from the list to be informed of changes
* in status. The listener must previously have been added with
* the same three parameters. If there is more than one matching
* listener, only one is removed.</p>
*
* @param l a listener to receive connection status notifications.
* @param f a filter to select which notifications are to be
* delivered to the listener. Can be null.
* @param handback an object to be given to the listener along
* with each notification. Can be null.
*
* @exception ListenerNotFoundException if the listener is not
* registered with this <code>JMXConnector</code>, or is not
* registered with the given filter and handback.
*
* @see #removeConnectionNotificationListener(NotificationListener)
* @see #addConnectionNotificationListener
* @see javax.management.NotificationEmitter#removeNotificationListener
*/
public void removeConnectionNotificationListener(NotificationListener l,
NotificationFilter f,
Object handback)
throws ListenerNotFoundException;
/** {@collect.stats}
* <p>Gets this connection's ID from the connector server. For a
* given connector server, every connection will have a unique id
* which does not change during the lifetime of the
* connection.</p>
*
* @return the unique ID of this connection. This is the same as
* the ID that the connector server includes in its {@link
* JMXConnectionNotification}s. The {@link
* javax.management.remote package description} describes the
* conventions for connection IDs.
*
* @exception IOException if the connection ID cannot be obtained,
* for instance because the connection is closed or broken.
*/
public String getConnectionId() throws IOException;
}
| Java |
/*
* Copyright (c) 2003, 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.remote;
import java.io.Serializable;
import javax.management.Notification;
/** {@collect.stats}
* <p>A (Notification, Listener ID) pair.</p>
* <p>This class is used to associate an emitted notification
* with the listener ID to which it is targeted.</p>
*
* @since 1.5
*/
public class TargetedNotification implements Serializable {
private static final long serialVersionUID = 7676132089779300926L;
// If we replace Integer with int...
// /** {@collect.stats}
// * <p>Constructs a <code>TargetedNotification</code> object. The
// * object contains a pair (Notification, Listener ID).
// * The Listener ID identifies the client listener to which that
// * notification is targeted. The client listener ID is one
// * previously returned by the connector server in response to an
// * <code>addNotificationListener</code> request.</p>
// * @param notification Notification emitted from the MBean server.
// * @param listenerID The ID of the listener to which this
// * notification is targeted.
// */
// public TargetedNotification(Notification notification,
// int listenerID) {
// this.notif = notification;
// this.id = listenerID;
// }
/** {@collect.stats}
* <p>Constructs a <code>TargetedNotification</code> object. The
* object contains a pair (Notification, Listener ID).
* The Listener ID identifies the client listener to which that
* notification is targeted. The client listener ID is one
* previously returned by the connector server in response to an
* <code>addNotificationListener</code> request.</p>
* @param notification Notification emitted from the MBean server.
* @param listenerID The ID of the listener to which this
* notification is targeted.
* @exception IllegalArgumentException if the <var>listenerID</var>
* or <var>notification</var> is null.
*/
public TargetedNotification(Notification notification,
Integer listenerID) {
// If we replace integer with int...
// this(notification,intValue(listenerID));
if (notification == null) throw new
IllegalArgumentException("Invalid notification: null");
if (listenerID == null) throw new
IllegalArgumentException("Invalid listener ID: null");
this.notif = notification;
this.id = listenerID;
}
/** {@collect.stats}
* <p>The emitted notification.</p>
*
* @return The notification.
*/
public Notification getNotification() {
return notif;
}
/** {@collect.stats}
* <p>The ID of the listener to which the notification is
* targeted.</p>
*
* @return The listener ID.
*/
public Integer getListenerID() {
return id;
}
/** {@collect.stats}
* Returns a textual representation of this Targeted Notification.
*
* @return a String representation of this Targeted Notification.
**/
public String toString() {
return "{" + notif + ", " + id + "}";
}
/** {@collect.stats}
* @serial A notification to transmit to the other side.
* @see #getNotification()
**/
private final Notification notif;
/** {@collect.stats}
* @serial The ID of the listener to which the notification is
* targeted.
* @see #getListenerID()
**/
private final Integer id;
//private final int id;
// Needed if we use int instead of Integer...
// private static int intValue(Integer id) {
// if (id == null) throw new
// IllegalArgumentException("Invalid listener ID: null");
// return id.intValue();
// }
}
| Java |
/*
* Copyright (c) 2002, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management.remote;
import java.io.IOException;
import java.util.Map;
/** {@collect.stats}
* <p>MBean interface for connector servers. A JMX API connector server
* is attached to an MBean server, and establishes connections to that
* MBean server for remote clients.</p>
*
* <p>A newly-created connector server is <em>inactive</em>, and does
* not yet listen for connections. Only when its {@link #start start}
* method has been called does it start listening for connections.</p>
*
* @since 1.5
*/
public interface JMXConnectorServerMBean {
/** {@collect.stats}
* <p>Activates the connector server, that is, starts listening for
* client connections. Calling this method when the connector
* server is already active has no effect. Calling this method
* when the connector server has been stopped will generate an
* {@link IOException}.</p>
*
* @exception IOException if it is not possible to start listening
* or if the connector server has been stopped.
*
* @exception IllegalStateException if the connector server has
* not been attached to an MBean server.
*/
public void start() throws IOException;
/** {@collect.stats}
* <p>Deactivates the connector server, that is, stops listening for
* client connections. Calling this method will also close all
* client connections that were made by this server. After this
* method returns, whether normally or with an exception, the
* connector server will not create any new client
* connections.</p>
*
* <p>Once a connector server has been stopped, it cannot be started
* again.</p>
*
* <p>Calling this method when the connector server has already
* been stopped has no effect. Calling this method when the
* connector server has not yet been started will disable the
* connector server object permanently.</p>
*
* <p>If closing a client connection produces an exception, that
* exception is not thrown from this method. A {@link
* JMXConnectionNotification} with type {@link
* JMXConnectionNotification#FAILED} is emitted from this MBean
* with the connection ID of the connection that could not be
* closed.</p>
*
* <p>Closing a connector server is a potentially slow operation.
* For example, if a client machine with an open connection has
* crashed, the close operation might have to wait for a network
* protocol timeout. Callers that do not want to block in a close
* operation should do it in a separate thread.</p>
*
* @exception IOException if the server cannot be closed cleanly.
* When this exception is thrown, the server has already attempted
* to close all client connections. All client connections are
* closed except possibly those that generated exceptions when the
* server attempted to close them.
*/
public void stop() throws IOException;
/** {@collect.stats}
* <p>Determines whether the connector server is active. A connector
* server starts being active when its {@link #start start} method
* returns successfully and remains active until either its
* {@link #stop stop} method is called or the connector server
* fails.</p>
*
* @return true if the connector server is active.
*/
public boolean isActive();
/** {@collect.stats}
* <p>Adds an object that intercepts requests for the MBean server
* that arrive through this connector server. This object will be
* supplied as the <code>MBeanServer</code> for any new connection
* created by this connector server. Existing connections are
* unaffected.</p>
*
* <p>If this connector server is already associated with an
* <code>MBeanServer</code> object, then that object is given to
* {@link MBeanServerForwarder#setMBeanServer
* mbsf.setMBeanServer}. If doing so produces an exception, this
* method throws the same exception without any other effect.</p>
*
* <p>If this connector is not already associated with an
* <code>MBeanServer</code> object, or if the
* <code>mbsf.setMBeanServer</code> call just mentioned succeeds,
* then <code>mbsf</code> becomes this connector server's
* <code>MBeanServer</code>.</p>
*
* @param mbsf the new <code>MBeanServerForwarder</code>.
*
* @exception IllegalArgumentException if the call to {@link
* MBeanServerForwarder#setMBeanServer mbsf.setMBeanServer} fails
* with <code>IllegalArgumentException</code>. This includes the
* case where <code>mbsf</code> is null.
*/
public void setMBeanServerForwarder(MBeanServerForwarder mbsf);
/** {@collect.stats}
* <p>The list of IDs for currently-open connections to this
* connector server.</p>
*
* @return a new string array containing the list of IDs. If
* there are no currently-open connections, this array will be
* empty.
*/
public String[] getConnectionIds();
/** {@collect.stats}
* <p>The address of this connector server.</p>
* <p>
* The address returned may not be the exact original {@link JMXServiceURL}
* that was supplied when creating the connector server, since the original
* address may not always be complete. For example the port number may be
* dynamically allocated when starting the connector server. Instead the
* address returned is the actual {@link JMXServiceURL} of the
* {@link JMXConnectorServer}. This is the address that clients supply
* to {@link JMXConnectorFactory#connect(JMXServiceURL)}.
* </p>
* <p>Note that the address returned may be {@code null} if
* the {@code JMXConnectorServer} is not yet {@link #isActive active}.
* </p>
*
* @return the address of this connector server, or null if it
* does not have one.
*/
public JMXServiceURL getAddress();
/** {@collect.stats}
* <p>The attributes for this connector server.</p>
*
* @return a read-only map containing the attributes for this
* connector server. Attributes whose values are not serializable
* are omitted from this map. If there are no serializable
* attributes, the returned map is empty.
*/
public Map<String,?> getAttributes();
/** {@collect.stats}
* <p>Returns a client stub for this connector server. A client
* stub is a serializable object whose {@link
* JMXConnector#connect(Map) connect} method can be used to make
* one new connection to this connector server.</p>
*
* <p>A given connector need not support the generation of client
* stubs. However, the connectors specified by the JMX Remote API do
* (JMXMP Connector and RMI Connector).</p>
*
* @param env client connection parameters of the same sort that
* can be provided to {@link JMXConnector#connect(Map)
* JMXConnector.connect(Map)}. Can be null, which is equivalent
* to an empty map.
*
* @return a client stub that can be used to make a new connection
* to this connector server.
*
* @exception UnsupportedOperationException if this connector
* server does not support the generation of client stubs.
*
* @exception IllegalStateException if the JMXConnectorServer is
* not started (see {@link JMXConnectorServerMBean#isActive()}).
*
* @exception IOException if a communications problem means that a
* stub cannot be created.
*
*/
public JMXConnector toJMXConnector(Map<String,?> env)
throws IOException;
}
| Java |
/*
* Copyright (c) 2003, 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.remote;
import java.io.Serializable;
/** {@collect.stats}
* <p>Result of a query for buffered notifications. Notifications in
* a notification buffer have positive, monotonically increasing
* sequence numbers. The result of a notification query contains the
* following elements:</p>
*
* <ul>
*
* <li>The sequence number of the earliest notification still in
* the buffer.
*
* <li>The sequence number of the next notification available for
* querying. This will be the starting sequence number for the next
* notification query.
*
* <li>An array of (Notification,listenerID) pairs corresponding to
* the returned notifications and the listeners they correspond to.
*
* </ul>
*
* <p>It is possible for the <code>nextSequenceNumber</code> to be less
* than the <code>earliestSequenceNumber</code>. This signifies that
* notifications between the two might have been lost.</p>
*
* @since 1.5
*/
public class NotificationResult implements Serializable {
private static final long serialVersionUID = 1191800228721395279L;
/** {@collect.stats}
* <p>Constructs a notification query result.</p>
*
* @param earliestSequenceNumber the sequence number of the
* earliest notification still in the buffer.
* @param nextSequenceNumber the sequence number of the next
* notification available for querying.
* @param targetedNotifications the notifications resulting from
* the query, and the listeners they correspond to. This array
* can be empty.
*
* @exception IllegalArgumentException if
* <code>targetedNotifications</code> is null or if
* <code>earliestSequenceNumber</code> or
* <code>nextSequenceNumber</code> is negative.
*/
public NotificationResult(long earliestSequenceNumber,
long nextSequenceNumber,
TargetedNotification[] targetedNotifications) {
if (targetedNotifications == null) {
final String msg = "Notifications null";
throw new IllegalArgumentException(msg);
}
if (earliestSequenceNumber < 0 || nextSequenceNumber < 0)
throw new IllegalArgumentException("Bad sequence numbers");
/* We used to check nextSequenceNumber >= earliestSequenceNumber
here. But in fact the opposite can legitimately be true if
notifications have been lost. */
this.earliestSequenceNumber = earliestSequenceNumber;
this.nextSequenceNumber = nextSequenceNumber;
this.targetedNotifications = targetedNotifications;
}
/** {@collect.stats}
* Returns the sequence number of the earliest notification still
* in the buffer.
*
* @return the sequence number of the earliest notification still
* in the buffer.
*/
public long getEarliestSequenceNumber() {
return earliestSequenceNumber;
}
/** {@collect.stats}
* Returns the sequence number of the next notification available
* for querying.
*
* @return the sequence number of the next notification available
* for querying.
*/
public long getNextSequenceNumber() {
return nextSequenceNumber;
}
/** {@collect.stats}
* Returns the notifications resulting from the query, and the
* listeners they correspond to.
*
* @return the notifications resulting from the query, and the
* listeners they correspond to. This array can be empty.
*/
public TargetedNotification[] getTargetedNotifications() {
return targetedNotifications;
}
/** {@collect.stats}
* Returns a string representation of the object. The result
* should be a concise but informative representation that is easy
* for a person to read.
*
* @return a string representation of the object.
*/
public String toString() {
return "NotificationResult: earliest=" + getEarliestSequenceNumber() +
"; next=" + getNextSequenceNumber() + "; nnotifs=" +
getTargetedNotifications().length;
}
private final long earliestSequenceNumber;
private final long nextSequenceNumber;
private final TargetedNotification[] targetedNotifications;
}
| Java |
/*
* Copyright (c) 2002, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management.remote;
import java.io.Serializable;
import java.security.Principal;
/** {@collect.stats}
* <p>The identity of a remote client of the JMX Remote API.</p>
*
* <p>Principals such as this <code>JMXPrincipal</code>
* may be associated with a particular <code>Subject</code>
* to augment that <code>Subject</code> with an additional
* identity. Refer to the {@link javax.security.auth.Subject}
* class for more information on how to achieve this.
* Authorization decisions can then be based upon
* the Principals associated with a <code>Subject</code>.
*
* @see java.security.Principal
* @see javax.security.auth.Subject
* @since 1.5
*/
public class JMXPrincipal implements Principal, Serializable {
private static final long serialVersionUID = -4184480100214577411L;
/** {@collect.stats}
* @serial The JMX Remote API name for the identity represented by
* this <code>JMXPrincipal</code> object.
* @see #getName()
*/
private String name;
/** {@collect.stats}
* <p>Creates a JMXPrincipal for a given identity.</p>
*
* @param name the JMX Remote API name for this identity.
*
* @exception NullPointerException if the <code>name</code> is
* <code>null</code>.
*/
public JMXPrincipal(String name) {
if (name == null)
throw new NullPointerException("illegal null input");
this.name = name;
}
/** {@collect.stats}
* Returns the name of this principal.
*
* <p>
*
* @return the name of this <code>JMXPrincipal</code>.
*/
public String getName() {
return name;
}
/** {@collect.stats}
* Returns a string representation of this <code>JMXPrincipal</code>.
*
* <p>
*
* @return a string representation of this <code>JMXPrincipal</code>.
*/
public String toString() {
return("JMXPrincipal: " + name);
}
/** {@collect.stats}
* Compares the specified Object with this <code>JMXPrincipal</code>
* for equality. Returns true if the given object is also a
* <code>JMXPrincipal</code> and the two JMXPrincipals
* have the same name.
*
* <p>
*
* @param o Object to be compared for equality with this
* <code>JMXPrincipal</code>.
*
* @return true if the specified Object is equal to this
* <code>JMXPrincipal</code>.
*/
public boolean equals(Object o) {
if (o == null)
return false;
if (this == o)
return true;
if (!(o instanceof JMXPrincipal))
return false;
JMXPrincipal that = (JMXPrincipal)o;
return (this.getName().equals(that.getName()));
}
/** {@collect.stats}
* Returns a hash code for this <code>JMXPrincipal</code>.
*
* <p>
*
* @return a hash code for this <code>JMXPrincipal</code>.
*/
public int hashCode() {
return name.hashCode();
}
}
| Java |
/*
* Copyright (c) 1999, 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/** {@collect.stats}
* Represents a list of values for attributes of an MBean. The methods
* used for the insertion of {@link javax.management.Attribute
* Attribute} objects in the <CODE>AttributeList</CODE> overrides the
* corresponding methods in the superclass
* <CODE>ArrayList</CODE>. This is needed in order to insure that the
* objects contained in the <CODE>AttributeList</CODE> are only
* <CODE>Attribute</CODE> objects. This avoids getting an exception
* when retrieving elements from the <CODE>AttributeList</CODE>.
*
* @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 boolean typeSafe;
private transient boolean tainted;
/* Serial version */
private static final long serialVersionUID = -4077085769279709076L;
/** {@collect.stats}
* Constructs an empty <CODE>AttributeList</CODE>.
*/
public AttributeList() {
super();
}
/** {@collect.stats}
* 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);
}
/** {@collect.stats}
* 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);
}
/** {@collect.stats}
* 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
//
checkTypeSafe(list);
// Build the List<Attribute>
//
super.addAll(list);
}
/** {@collect.stats}
* 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() {
if (!typeSafe) {
if (tainted)
checkTypeSafe(this);
typeSafe = true;
}
return (List<Attribute>) (List) this;
}
/** {@collect.stats}
* 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);
}
/** {@collect.stats}
* 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 (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");
}
}
/** {@collect.stats}
* 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 (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");
}
}
/** {@collect.stats}
* 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));
}
/** {@collect.stats}
* 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 (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.
*/
@Override
public boolean add(Object o) {
if (!tainted)
tainted = isTainted(o);
if (typeSafe)
checkTypeSafe(o);
return super.add(o);
}
@Override
public void add(int index, Object element) {
if (!tainted)
tainted = isTainted(element);
if (typeSafe)
checkTypeSafe(element);
super.add(index, element);
}
@Override
public boolean addAll(Collection<?> c) {
if (!tainted)
tainted = isTainted(c);
if (typeSafe)
checkTypeSafe(c);
return super.addAll(c);
}
@Override
public boolean addAll(int index, Collection<?> c) {
if (!tainted)
tainted = isTainted(c);
if (typeSafe)
checkTypeSafe(c);
return super.addAll(index, c);
}
@Override
public Object set(int index, Object element) {
if (!tainted)
tainted = isTainted(element);
if (typeSafe)
checkTypeSafe(element);
return super.set(index, element);
}
/** {@collect.stats}
* IllegalArgumentException if o is a non-Attribute object.
*/
private static void checkTypeSafe(Object o) {
try {
o = (Attribute) o;
} catch (ClassCastException e) {
throw new IllegalArgumentException(e);
}
}
/** {@collect.stats}
* IllegalArgumentException if c contains any non-Attribute objects.
*/
private static void checkTypeSafe(Collection<?> c) {
try {
Attribute a;
for (Object o : c)
a = (Attribute) o;
} catch (ClassCastException e) {
throw new IllegalArgumentException(e);
}
}
/** {@collect.stats}
* Returns true if o is a non-Attribute object.
*/
private static boolean isTainted(Object o) {
try {
checkTypeSafe(o);
} catch (IllegalArgumentException e) {
return true;
}
return false;
}
/** {@collect.stats}
* Returns true if c contains any non-Attribute objects.
*/
private static boolean isTainted(Collection<?> c) {
try {
checkTypeSafe(c);
} catch (IllegalArgumentException e) {
return true;
}
return false;
}
}
| Java |
/*
* Copyright (c) 1999, 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management;
/** {@collect.stats}
* 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;
/** {@collect.stats}
* @serial The attribute value to be matched
*/
private AttributeValueExp exp;
/** {@collect.stats}
* @serial The pattern to be matched
*/
private String pattern;
/** {@collect.stats}
* Basic Constructor.
*/
public MatchQueryExp() {
}
/** {@collect.stats}
* Creates a new MatchQueryExp where the specified AttributeValueExp matches
* the specified pattern StringValueExp.
*/
public MatchQueryExp(AttributeValueExp a, StringValueExp s) {
exp = a;
pattern = s.getValue();
}
/** {@collect.stats}
* Returns the attribute of the query.
*/
public AttributeValueExp getAttribute() {
return exp;
}
/** {@collect.stats}
* Returns the pattern of the query.
*/
public String getPattern() {
return pattern;
}
/** {@collect.stats}
* 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);
}
/** {@collect.stats}
* Returns the string representing the object
*/
public String toString() {
return exp + " like " + new StringValueExp(likeTranslate(pattern));
}
private static String likeTranslate(String s) {
return s.replace('?', '_').replace('*', '%');
}
/*
* 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);
}
}
| Java |
/*
* Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management;
/** {@collect.stats}
* Represents 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;
/** {@collect.stats}
* @serial The encapsulated {@link RuntimeException}
*/
private java.lang.RuntimeException runtimeException ;
/** {@collect.stats}
* 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 ;
}
/** {@collect.stats}
* 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 ;
}
/** {@collect.stats}
* Returns the actual {@link RuntimeException} thrown.
*
* @return the wrapped {@link RuntimeException}.
*/
public java.lang.RuntimeException getTargetException() {
return runtimeException ;
}
/** {@collect.stats}
* Returns the actual {@link RuntimeException} thrown.
*
* @return the wrapped {@link RuntimeException}.
*/
public Throwable getCause() {
return runtimeException;
}
}
| Java |
/*
* Copyright (c) 1999, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management;
import com.sun.jmx.mbeanserver.Introspector;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.util.Arrays;
/** {@collect.stats}
* 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];
/** {@collect.stats} @see MBeanInfo#arrayGettersSafe */
private final transient boolean arrayGettersSafe;
/** {@collect.stats}
* @serial The signature of the method, that is, the class names of the arguments.
*/
private final MBeanParameterInfo[] signature;
/** {@collect.stats}
* 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));
}
/** {@collect.stats}
* 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);
}
/** {@collect.stats}
* 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);
}
/** {@collect.stats}
* <p>Returns a shallow clone of this instance. The clone is
* obtained by simply calling <tt>super.clone()</tt>, thus calling
* the default native shallow cloning mechanism implemented by
* <tt>Object.clone()</tt>. No deeper cloning of any internal
* field is made.</p>
*
* <p>Since this class is immutable, cloning is chiefly of
* interest to subclasses.</p>
*/
public Object clone () {
try {
return super.clone() ;
} catch (CloneNotSupportedException e) {
// should not happen as this class is cloneable
return null;
}
}
/** {@collect.stats}
* <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() +
"]";
}
/** {@collect.stats}
* 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 (p.getName().equals(getName()) &&
p.getDescription().equals(getDescription()) &&
Arrays.equals(p.fastGetSignature(), fastGetSignature()) &&
p.getDescriptor().equals(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() {
int hash = getName().hashCode();
MBeanParameterInfo[] sig = fastGetSignature();
for (int i = 0; i < sig.length; i++)
hash ^= sig[i].hashCode();
return hash;
}
private static MBeanParameterInfo[] constructorSignature(Constructor cn) {
final Class[] classes = cn.getParameterTypes();
final Annotation[][] annots = cn.getParameterAnnotations();
return MBeanOperationInfo.parameters(classes, annots);
}
}
| Java |
/*
* Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management;
/** {@collect.stats}
* 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;
/** {@collect.stats}
* @serial the {@link ValueExp} that originated this exception
*/
private ValueExp exp;
/** {@collect.stats}
* 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;
}
/** {@collect.stats}
* Returns the <CODE>ValueExp</CODE> that originated the exception.
*
* @return the problematic {@link ValueExp}.
*/
public ValueExp getExp() {
return exp;
}
/** {@collect.stats}
* Returns the string representing the object.
*/
public String toString() {
return "BadBinaryOpValueExpException: " + exp;
}
}
| Java |
/*
* Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management;
/** {@collect.stats}
* 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 {
/** {@collect.stats}
* 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);
}
| Java |
/*
* Copyright (c) 2002, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management;
// java import
import java.io.IOException;
import java.util.Set;
/** {@collect.stats}
* This interface represents a way to talk to an MBean server, whether
* local or remote. The {@link MBeanServer} interface, representing a
* local MBean server, extends this interface.
*
*
* @since 1.5
*/
public interface MBeanServerConnection {
/** {@collect.stats}
* <p>Instantiates and registers an MBean in the MBean server. The
* MBean server will use its {@link
* javax.management.loading.ClassLoaderRepository Default Loader
* Repository} to load the class of the MBean. An object name is
* associated to the MBean. 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>
*
* <p>This method is equivalent to {@link
* #createMBean(String,ObjectName,Object[],String[])
* createMBean(className, name, (Object[]) null, (String[])
* null)}.</p>
*
* @param className The class name of the MBean to be instantiated.
* @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
* instantiated 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 ReflectionException Wraps a
* <CODE>java.lang.ClassNotFoundException</CODE> or a
* <CODE>java.lang.Exception</CODE> that occurred
* when trying to invoke the MBean's constructor.
* @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 MBeanException The constructor of the MBean has
* thrown an exception
* @exception NotCompliantMBeanException This class is not a JMX
* compliant MBean
* @exception RuntimeOperationsException Wraps a
* <CODE>java.lang.IllegalArgumentException</CODE>: The className
* passed in parameter is null, the <CODE>ObjectName</CODE> passed
* in parameter contains a pattern or no <CODE>ObjectName</CODE>
* is specified for the MBean.
* @exception IOException A communication problem occurred when
* talking to the MBean server.
*
*/
public ObjectInstance createMBean(String className, ObjectName name)
throws ReflectionException, InstanceAlreadyExistsException,
MBeanRegistrationException, MBeanException,
NotCompliantMBeanException, IOException;
/** {@collect.stats}
* <p>Instantiates and registers an MBean in the MBean server. The
* class loader to be used is identified by its object name. An
* object name is associated to the MBean. If the object name of
* the loader is null, the ClassLoader that loaded the MBean
* server will be used. If the MBean's 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>
*
* <p>This method is equivalent to {@link
* #createMBean(String,ObjectName,ObjectName,Object[],String[])
* createMBean(className, name, loaderName, (Object[]) null,
* (String[]) null)}.</p>
*
* @param className The class name of the MBean to be instantiated.
* @param name The object name of the MBean. May be null.
* @param loaderName The object name of the class loader to be used.
*
* @return An <CODE>ObjectInstance</CODE>, containing the
* <CODE>ObjectName</CODE> and the Java class name of the newly
* instantiated 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 ReflectionException Wraps a
* <CODE>java.lang.ClassNotFoundException</CODE> or a
* <CODE>java.lang.Exception</CODE> that occurred when trying to
* invoke the MBean's constructor.
* @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 MBeanException The constructor of the MBean has
* thrown an exception
* @exception NotCompliantMBeanException This class is not a JMX
* compliant MBean
* @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, the <CODE>ObjectName</CODE> passed
* in parameter contains a pattern or no <CODE>ObjectName</CODE>
* is specified for the MBean.
* @exception IOException A communication problem occurred when
* talking to the MBean server.
*/
public ObjectInstance createMBean(String className, ObjectName name,
ObjectName loaderName)
throws ReflectionException, InstanceAlreadyExistsException,
MBeanRegistrationException, MBeanException,
NotCompliantMBeanException, InstanceNotFoundException,
IOException;
/** {@collect.stats}
* Instantiates and registers an MBean in the MBean server. The
* MBean server will use its {@link
* javax.management.loading.ClassLoaderRepository Default Loader
* Repository} to load the class of the MBean. An object name is
* associated to the MBean. If the object name given is null, the
* MBean must provide its own name by implementing the {@link
* javax.management.MBeanRegistration MBeanRegistration} interface
* and returning the name from the {@link
* MBeanRegistration#preRegister preRegister} method.
*
* @param className The class name of the MBean to be instantiated.
* @param name The object name of the MBean. May be null.
* @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 An <CODE>ObjectInstance</CODE>, containing the
* <CODE>ObjectName</CODE> and the Java class name of the newly
* instantiated 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 ReflectionException Wraps a
* <CODE>java.lang.ClassNotFoundException</CODE> or a
* <CODE>java.lang.Exception</CODE> that occurred when trying to
* invoke the MBean's constructor.
* @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 MBeanException The constructor of the MBean has
* thrown an exception
* @exception NotCompliantMBeanException This class is not a JMX
* compliant MBean
* @exception RuntimeOperationsException Wraps a
* <CODE>java.lang.IllegalArgumentException</CODE>: The className
* passed in parameter is null, the <CODE>ObjectName</CODE> passed
* in parameter contains a pattern or no <CODE>ObjectName</CODE>
* is specified for the MBean.
* @exception IOException A communication problem occurred when
* talking to the MBean server.
*
*/
public ObjectInstance createMBean(String className, ObjectName name,
Object params[], String signature[])
throws ReflectionException, InstanceAlreadyExistsException,
MBeanRegistrationException, MBeanException,
NotCompliantMBeanException, IOException;
/** {@collect.stats}
* Instantiates and registers an MBean in the MBean server. The
* class loader to be used is identified by its object name. An
* object name is associated to the MBean. If the object name of
* the loader is not specified, the ClassLoader that loaded the
* MBean server will be used. If the MBean object name given is
* null, the MBean must provide its own name by implementing the
* {@link javax.management.MBeanRegistration MBeanRegistration}
* interface and returning the name from the {@link
* MBeanRegistration#preRegister preRegister} method.
*
* @param className The class name of the MBean to be instantiated.
* @param name The object name of the MBean. May be null.
* @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 An <CODE>ObjectInstance</CODE>, containing the
* <CODE>ObjectName</CODE> and the Java class name of the newly
* instantiated 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 ReflectionException Wraps a
* <CODE>java.lang.ClassNotFoundException</CODE> or a
* <CODE>java.lang.Exception</CODE> that occurred when trying to
* invoke the MBean's constructor.
* @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 MBeanException The constructor of the MBean has
* thrown an exception
* @exception NotCompliantMBeanException This class is not a JMX
* compliant MBean
* @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, the <CODE>ObjectName</CODE> passed
* in parameter contains a pattern or no <CODE>ObjectName</CODE>
* is specified for the MBean.
* @exception IOException A communication problem occurred when
* talking to the MBean server.
*
*/
public ObjectInstance createMBean(String className, ObjectName name,
ObjectName loaderName, Object params[],
String signature[])
throws ReflectionException, InstanceAlreadyExistsException,
MBeanRegistrationException, MBeanException,
NotCompliantMBeanException, InstanceNotFoundException,
IOException;
/** {@collect.stats}
* Unregisters an MBean from the MBean server. The MBean is
* identified by its object name. Once the method has been
* invoked, the MBean may no longer be accessed by its object
* name.
*
* @param name The object name of the MBean to be unregistered.
*
* @exception InstanceNotFoundException The MBean specified is not
* registered in the MBean server.
* @exception MBeanRegistrationException The preDeregister
* ((<CODE>MBeanRegistration</CODE> interface) method of the MBean
* has thrown an exception.
* @exception RuntimeOperationsException Wraps a
* <CODE>java.lang.IllegalArgumentException</CODE>: The object
* name in parameter is null or the MBean you are when trying to
* unregister is the {@link javax.management.MBeanServerDelegate
* MBeanServerDelegate} MBean.
* @exception IOException A communication problem occurred when
* talking to the MBean server.
*
*/
public void unregisterMBean(ObjectName name)
throws InstanceNotFoundException, MBeanRegistrationException,
IOException;
/** {@collect.stats}
* Gets the <CODE>ObjectInstance</CODE> for a given MBean
* registered with the MBean server.
*
* @param name The object name of the MBean.
*
* @return The <CODE>ObjectInstance</CODE> associated with the MBean
* specified by <VAR>name</VAR>. The contained <code>ObjectName</code>
* is <code>name</code> and the contained class name is
* <code>{@link #getMBeanInfo getMBeanInfo(name)}.getClassName()</code>.
*
* @exception InstanceNotFoundException The MBean specified is not
* registered in the MBean server.
* @exception IOException A communication problem occurred when
* talking to the MBean server.
*/
public ObjectInstance getObjectInstance(ObjectName name)
throws InstanceNotFoundException, IOException;
/** {@collect.stats}
* Gets MBeans controlled by the MBean server. This method allows
* any of the following to be obtained: All MBeans, a set of
* MBeans specified by pattern matching on the
* <CODE>ObjectName</CODE> and/or a Query expression, a specific
* MBean. When the object name is null or no domain and key
* properties are specified, all objects are to be selected (and
* filtered if a query is specified). It returns the set of
* <CODE>ObjectInstance</CODE> objects (containing the
* <CODE>ObjectName</CODE> and the Java Class name) for the
* selected MBeans.
*
* @param name The object name pattern identifying the MBeans to
* be retrieved. If null or no domain and key properties are
* specified, all the MBeans registered will be retrieved.
* @param query The query expression to be applied for selecting
* MBeans. If null no query expression will be applied for
* selecting MBeans.
*
* @return A set containing the <CODE>ObjectInstance</CODE>
* objects for the selected MBeans. If no MBean satisfies the
* query an empty list is returned.
*
* @exception IOException A communication problem occurred when
* talking to the MBean server.
*/
public Set<ObjectInstance> queryMBeans(ObjectName name, QueryExp query)
throws IOException;
/** {@collect.stats}
* Gets the names of MBeans controlled by the MBean server. This
* method enables any of the following to be obtained: The names
* of all MBeans, the names of a set of MBeans specified by
* pattern matching on the <CODE>ObjectName</CODE> and/or a Query
* expression, a specific MBean name (equivalent to testing
* whether an MBean is registered). When the object name is null
* or no domain and key properties are specified, all objects are
* selected (and filtered if a query is specified). It returns the
* set of ObjectNames for the MBeans selected.
*
* @param name The object name pattern identifying the MBean names
* to be retrieved. If null or no domain and key properties are
* specified, the name of all registered MBeans will be retrieved.
* @param query The query expression to be applied for selecting
* MBeans. If null no query expression will be applied for
* selecting MBeans.
*
* @return A set containing the ObjectNames for the MBeans
* selected. If no MBean satisfies the query, an empty list is
* returned.
*
* @exception IOException A communication problem occurred when
* talking to the MBean server.
*/
public Set<ObjectName> queryNames(ObjectName name, QueryExp query)
throws IOException;
/** {@collect.stats}
* Checks whether an MBean, identified by its object name, is
* already registered with the MBean server.
*
* @param name The object name of the MBean to be checked.
*
* @return True if the MBean is already registered in the MBean
* server, false otherwise.
*
* @exception RuntimeOperationsException Wraps a
* <CODE>java.lang.IllegalArgumentException</CODE>: The object
* name in parameter is null.
* @exception IOException A communication problem occurred when
* talking to the MBean server.
*/
public boolean isRegistered(ObjectName name)
throws IOException;
/** {@collect.stats}
* Returns the number of MBeans registered in the MBean server.
*
* @return the number of MBeans registered.
*
* @exception IOException A communication problem occurred when
* talking to the MBean server.
*/
public Integer getMBeanCount()
throws IOException;
/** {@collect.stats}
* Gets the value of a specific attribute of a named MBean. The MBean
* is identified by its object name.
*
* @param name The object name of the MBean from which the
* attribute is to be retrieved.
* @param attribute A String specifying the name of the attribute
* to be retrieved.
*
* @return The value of the retrieved attribute.
*
* @exception AttributeNotFoundException The attribute specified
* is not accessible in the MBean.
* @exception MBeanException Wraps an exception thrown by the
* MBean's getter.
* @exception InstanceNotFoundException The MBean specified is not
* registered in the MBean server.
* @exception ReflectionException Wraps a
* <CODE>java.lang.Exception</CODE> thrown when trying to invoke
* the setter.
* @exception RuntimeOperationsException Wraps a
* <CODE>java.lang.IllegalArgumentException</CODE>: The object
* name in parameter is null or the attribute in parameter is
* null.
* @exception IOException A communication problem occurred when
* talking to the MBean server.
*
* @see #setAttribute
*/
public Object getAttribute(ObjectName name, String attribute)
throws MBeanException, AttributeNotFoundException,
InstanceNotFoundException, ReflectionException,
IOException;
/** {@collect.stats}
* Enables the values of several attributes of a named MBean. The MBean
* is identified by its object name.
*
* @param name The object name of the MBean from which the
* attributes are retrieved.
* @param attributes A list of the attributes to be retrieved.
*
* @return The list of the retrieved attributes.
*
* @exception InstanceNotFoundException The MBean specified is not
* registered in the MBean server.
* @exception ReflectionException An exception occurred when
* trying to invoke the getAttributes method of a Dynamic MBean.
* @exception RuntimeOperationsException Wrap a
* <CODE>java.lang.IllegalArgumentException</CODE>: The object
* name in parameter is null or attributes in parameter is null.
* @exception IOException A communication problem occurred when
* talking to the MBean server.
*
* @see #setAttributes
*/
public AttributeList getAttributes(ObjectName name, String[] attributes)
throws InstanceNotFoundException, ReflectionException,
IOException;
/** {@collect.stats}
* Sets the value of a specific attribute of a named MBean. The MBean
* is identified by its object name.
*
* @param name The name of the MBean within which the attribute is
* to be set.
* @param attribute The identification of the attribute to be set
* and the value it is to be set to.
*
* @exception InstanceNotFoundException The MBean specified is not
* registered in the MBean server.
* @exception AttributeNotFoundException The attribute specified
* is not accessible in the MBean.
* @exception InvalidAttributeValueException The value specified
* for the attribute is not valid.
* @exception MBeanException Wraps an exception thrown by the
* MBean's setter.
* @exception ReflectionException Wraps a
* <CODE>java.lang.Exception</CODE> thrown when trying to invoke
* the setter.
* @exception RuntimeOperationsException Wraps a
* <CODE>java.lang.IllegalArgumentException</CODE>: The object
* name in parameter is null or the attribute in parameter is
* null.
* @exception IOException A communication problem occurred when
* talking to the MBean server.
*
* @see #getAttribute
*/
public void setAttribute(ObjectName name, Attribute attribute)
throws InstanceNotFoundException, AttributeNotFoundException,
InvalidAttributeValueException, MBeanException,
ReflectionException, IOException;
/** {@collect.stats}
* Sets the values of several attributes of a named MBean. The MBean is
* identified by its object name.
*
* @param name The object name of the MBean within which the
* attributes are to be set.
* @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.
*
* @exception InstanceNotFoundException The MBean specified is not
* registered in the MBean server.
* @exception ReflectionException An exception occurred when
* trying to invoke the getAttributes method of a Dynamic MBean.
* @exception RuntimeOperationsException Wraps a
* <CODE>java.lang.IllegalArgumentException</CODE>: The object
* name in parameter is null or attributes in parameter is null.
* @exception IOException A communication problem occurred when
* talking to the MBean server.
*
* @see #getAttributes
*/
public AttributeList setAttributes(ObjectName name,
AttributeList attributes)
throws InstanceNotFoundException, ReflectionException, IOException;
/** {@collect.stats}
* Invokes an operation on an MBean.
*
* @param name The object name of the MBean on which the method is
* to be invoked.
* @param operationName The name of the operation to be invoked.
* @param params An array containing the parameters to be set when
* the operation is invoked
* @param signature An array containing the signature of the
* operation. The class objects will be loaded using the same
* class loader as the one used for loading the MBean on which the
* operation was invoked.
*
* @return The object returned by the operation, which represents
* the result of invoking the operation on the MBean specified.
*
* @exception InstanceNotFoundException The MBean specified is not
* registered in the MBean server.
* @exception MBeanException Wraps an exception thrown by the
* MBean's invoked method.
* @exception ReflectionException Wraps a
* <CODE>java.lang.Exception</CODE> thrown while trying to invoke
* the method.
* @exception IOException A communication problem occurred when
* talking to the MBean server.
*
*/
public Object invoke(ObjectName name, String operationName,
Object params[], String signature[])
throws InstanceNotFoundException, MBeanException,
ReflectionException, IOException;
/** {@collect.stats}
* Returns the default domain used for naming the MBean.
* The default domain name is used as the domain part in the ObjectName
* of MBeans if no domain is specified by the user.
*
* @return the default domain.
*
* @exception IOException A communication problem occurred when
* talking to the MBean server.
*/
public String getDefaultDomain()
throws IOException;
/** {@collect.stats}
* <p>Returns the list of domains in which any MBean is currently
* registered. A string is in the returned array if and only if
* there is at least one MBean registered with an ObjectName whose
* {@link ObjectName#getDomain() getDomain()} is equal to that
* string. The order of strings within the returned array is
* not defined.</p>
*
* @return the list of domains.
*
* @exception IOException A communication problem occurred when
* talking to the MBean server.
*
*/
public String[] getDomains()
throws IOException;
/** {@collect.stats}
* <p>Adds a listener to a registered MBean.</p>
*
* <P> A notification emitted by an MBean will be forwarded by the
* MBeanServer to the listener. 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.
*
* @param name The name of the MBean on which the listener should
* be added.
* @param listener The listener object which will handle the
* notifications emitted by the registered MBean.
* @param filter The filter object. If filter is null, no
* filtering will be performed before handling notifications.
* @param handback The context to be sent to the listener when a
* notification is emitted.
*
* @exception InstanceNotFoundException The MBean name provided
* does not match any of the registered MBeans.
* @exception IOException A communication problem occurred when
* talking to the MBean server.
*
* @see #removeNotificationListener(ObjectName, NotificationListener)
* @see #removeNotificationListener(ObjectName, NotificationListener,
* NotificationFilter, Object)
*/
public void addNotificationListener(ObjectName name,
NotificationListener listener,
NotificationFilter filter,
Object handback)
throws InstanceNotFoundException, IOException;
/** {@collect.stats}
* <p>Adds a listener to a registered MBean.</p>
*
* <p>A notification emitted by an MBean will be forwarded by the
* MBeanServer to the listener. 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.</p>
*
* <p>The listener object that receives notifications is the one
* that is registered with the given name at the time this method
* is called. Even if it is subsequently unregistered, it will
* continue to receive notifications.</p>
*
* @param name The name of the MBean on which the listener should
* be added.
* @param listener The object name of the listener which will
* handle the notifications emitted by the registered MBean.
* @param filter The filter object. If filter is null, no
* filtering will be performed before handling notifications.
* @param handback The context to be sent to the listener when a
* notification is emitted.
*
* @exception InstanceNotFoundException The MBean name of the
* notification listener or of the notification broadcaster does
* not match any of the registered MBeans.
* @exception RuntimeOperationsException Wraps an {@link
* IllegalArgumentException}. The MBean named by
* <code>listener</code> exists but does not implement the {@link
* NotificationListener} interface.
* @exception IOException A communication problem occurred when
* talking to the MBean server.
*
* @see #removeNotificationListener(ObjectName, ObjectName)
* @see #removeNotificationListener(ObjectName, ObjectName,
* NotificationFilter, Object)
*/
public void addNotificationListener(ObjectName name,
ObjectName listener,
NotificationFilter filter,
Object handback)
throws InstanceNotFoundException, IOException;
/** {@collect.stats}
* Removes a listener from a registered MBean.
*
* <P> If the listener is registered more than once, perhaps with
* different filters or callbacks, this method will remove all
* those registrations.
*
* @param name The name of the MBean on which the listener should
* be removed.
* @param listener The object name of the listener to be removed.
*
* @exception InstanceNotFoundException The MBean name provided
* does not match any of the registered MBeans.
* @exception ListenerNotFoundException The listener is not
* registered in the MBean.
* @exception IOException A communication problem occurred when
* talking to the MBean server.
*
* @see #addNotificationListener(ObjectName, ObjectName,
* NotificationFilter, Object)
*/
public void removeNotificationListener(ObjectName name,
ObjectName listener)
throws InstanceNotFoundException, ListenerNotFoundException,
IOException;
/** {@collect.stats}
* <p>Removes a listener from a registered MBean.</p>
*
* <p>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 name The name of the MBean on which the listener should
* be removed.
* @param listener The object name of the listener to be removed.
* @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 InstanceNotFoundException The MBean name provided
* does not match any of the registered MBeans.
* @exception ListenerNotFoundException The listener is not
* registered in the MBean, or it is not registered with the given
* filter and handback.
* @exception IOException A communication problem occurred when
* talking to the MBean server.
*
* @see #addNotificationListener(ObjectName, ObjectName,
* NotificationFilter, Object)
*
*/
public void removeNotificationListener(ObjectName name,
ObjectName listener,
NotificationFilter filter,
Object handback)
throws InstanceNotFoundException, ListenerNotFoundException,
IOException;
/** {@collect.stats}
* <p>Removes a listener from a registered MBean.</p>
*
* <P> If the listener is registered more than once, perhaps with
* different filters or callbacks, this method will remove all
* those registrations.
*
* @param name The name of the MBean on which the listener should
* be removed.
* @param listener The listener to be removed.
*
* @exception InstanceNotFoundException The MBean name provided
* does not match any of the registered MBeans.
* @exception ListenerNotFoundException The listener is not
* registered in the MBean.
* @exception IOException A communication problem occurred when
* talking to the MBean server.
*
* @see #addNotificationListener(ObjectName, NotificationListener,
* NotificationFilter, Object)
*/
public void removeNotificationListener(ObjectName name,
NotificationListener listener)
throws InstanceNotFoundException, ListenerNotFoundException,
IOException;
/** {@collect.stats}
* <p>Removes a listener from a registered MBean.</p>
*
* <p>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 name The name of the MBean on which the listener should
* be removed.
* @param listener The listener to be removed.
* @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 InstanceNotFoundException The MBean name provided
* does not match any of the registered MBeans.
* @exception ListenerNotFoundException The listener is not
* registered in the MBean, or it is not registered with the given
* filter and handback.
* @exception IOException A communication problem occurred when
* talking to the MBean server.
*
* @see #addNotificationListener(ObjectName, NotificationListener,
* NotificationFilter, Object)
*
*/
public void removeNotificationListener(ObjectName name,
NotificationListener listener,
NotificationFilter filter,
Object handback)
throws InstanceNotFoundException, ListenerNotFoundException,
IOException;
/** {@collect.stats}
* This method discovers the attributes and operations that an
* MBean exposes for management.
*
* @param name The name of the MBean to analyze
*
* @return An instance of <CODE>MBeanInfo</CODE> allowing the
* retrieval of all attributes and operations of this MBean.
*
* @exception IntrospectionException An exception occurred during
* introspection.
* @exception InstanceNotFoundException The MBean specified was
* not found.
* @exception ReflectionException An exception occurred when
* trying to invoke the getMBeanInfo of a Dynamic MBean.
* @exception IOException A communication problem occurred when
* talking to the MBean server.
*/
public MBeanInfo getMBeanInfo(ObjectName name)
throws InstanceNotFoundException, IntrospectionException,
ReflectionException, IOException;
/** {@collect.stats}
* <p>Returns true if the MBean specified is an instance of the
* specified class, false otherwise.</p>
*
* <p>If <code>name</code> does not name an MBean, this method
* throws {@link InstanceNotFoundException}.</p>
*
* <p>Otherwise, let<br>
* X be the MBean named by <code>name</code>,<br>
* L be the ClassLoader of X,<br>
* N be the class name in X's {@link MBeanInfo}.</p>
*
* <p>If N equals <code>className</code>, the result is true.</p>
*
* <p>Otherwise, if L successfully loads <code>className</code>
* and X is an instance of this class, the result is true.
*
* <p>Otherwise, if L successfully loads both N and
* <code>className</code>, and the second class is assignable from
* the first, the result is true.</p>
*
* <p>Otherwise, the result is false.</p>
*
* @param name The <CODE>ObjectName</CODE> of the MBean.
* @param className The name of the class.
*
* @return true if the MBean specified is an instance of the
* specified class according to the rules above, false otherwise.
*
* @exception InstanceNotFoundException The MBean specified is not
* registered in the MBean server.
* @exception IOException A communication problem occurred when
* talking to the MBean server.
*
* @see Class#isInstance
*/
public boolean isInstanceOf(ObjectName name, String className)
throws InstanceNotFoundException, IOException;
}
| Java |
/*
* Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management;
/** {@collect.stats}
* The value specified is not valid for the attribute.
*
* @since 1.5
*/
public class InvalidAttributeValueException extends OperationsException {
/* Serial version */
private static final long serialVersionUID = 2164571879317142449L;
/** {@collect.stats}
* Default constructor.
*/
public InvalidAttributeValueException() {
super();
}
/** {@collect.stats}
* Constructor that allows a specific error message to be specified.
*
* @param message the detail message.
*/
public InvalidAttributeValueException(String message) {
super(message);
}
}
| Java |
/*
* Copyright (c) 2002, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management;
import static com.sun.jmx.defaults.JmxProperties.MISC_LOGGER;
import com.sun.jmx.mbeanserver.DescriptorCache;
import com.sun.jmx.mbeanserver.Introspector;
import com.sun.jmx.mbeanserver.MBeanSupport;
import com.sun.jmx.mbeanserver.MXBeanSupport;
import com.sun.jmx.mbeanserver.StandardMBeanSupport;
import com.sun.jmx.mbeanserver.Util;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.HashMap;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.logging.Level;
import javax.management.openmbean.OpenMBeanAttributeInfo;
import javax.management.openmbean.OpenMBeanAttributeInfoSupport;
import javax.management.openmbean.OpenMBeanConstructorInfo;
import javax.management.openmbean.OpenMBeanConstructorInfoSupport;
import javax.management.openmbean.OpenMBeanOperationInfo;
import javax.management.openmbean.OpenMBeanOperationInfoSupport;
import javax.management.openmbean.OpenMBeanParameterInfo;
import javax.management.openmbean.OpenMBeanParameterInfoSupport;
/** {@collect.stats}
* <p>An MBean whose management interface is determined by reflection
* on a Java interface.</p>
*
* <p>This class brings more flexibility to the notion of Management
* Interface in the use of Standard MBeans. Straightforward use of
* the patterns for Standard MBeans described in the JMX Specification
* means that there is a fixed relationship between the implementation
* class of an MBean and its management interface (i.e., if the
* implementation class is Thing, the management interface must be
* ThingMBean). This class makes it possible to keep the convenience
* of specifying the management interface with a Java interface,
* without requiring that there be any naming relationship between the
* implementation and interface classes.</p>
*
* <p>By making a DynamicMBean out of an MBean, this class makes
* it possible to select any interface implemented by the MBean as its
* management interface, provided that it complies with JMX patterns
* (i.e., attributes defined by getter/setter etc...).</p>
*
* <p> This class also provides hooks that make it possible to supply
* custom descriptions and names for the {@link MBeanInfo} returned by
* the DynamicMBean interface.</p>
*
* <p>Using this class, an MBean can be created with any
* implementation class name <i>Impl</i> and with a management
* interface defined (as for current Standard MBeans) by any interface
* <i>Intf</i>, in one of two general ways:</p>
*
* <ul>
*
* <li>Using the public constructor
* {@link #StandardMBean(java.lang.Object, java.lang.Class, boolean)
* StandardMBean(impl,interface)}:
* <pre>
* MBeanServer mbs;
* ...
* Impl impl = new Impl(...);
* StandardMBean mbean = new StandardMBean(impl, Intf.class, false);
* mbs.registerMBean(mbean, objectName);
* </pre></li>
*
* <li>Subclassing StandardMBean:
* <pre>
* public class Impl extends StandardMBean implements Intf {
* public Impl() {
* super(Intf.class, false);
* }
* // implement methods of Intf
* }
*
* [...]
*
* MBeanServer mbs;
* ....
* Impl impl = new Impl();
* mbs.registerMBean(impl, objectName);
* </pre></li>
*
* </ul>
*
* <p>In either case, the class <i>Impl</i> must implement the
* interface <i>Intf</i>.</p>
*
* <p>Standard MBeans based on the naming relationship between
* implementation and interface classes are of course still
* available.</p>
*
* <p>This class may also be used to construct MXBeans. The usage
* is exactly the same as for Standard MBeans except that in the
* examples above, the {@code false} parameter to the constructor or
* {@code super(...)} invocation is instead {@code true}.</p>
*
* @since 1.5
*/
public class StandardMBean implements DynamicMBean, MBeanRegistration {
private final static DescriptorCache descriptors =
DescriptorCache.getInstance(JMX.proof);
/** {@collect.stats}
* The DynamicMBean that wraps the MXBean or Standard MBean implementation.
**/
private volatile MBeanSupport<?> mbean;
/** {@collect.stats}
* The cached MBeanInfo.
**/
private volatile MBeanInfo cachedMBeanInfo;
/** {@collect.stats}
* Make a DynamicMBean out of <var>implementation</var>, using the
* specified <var>mbeanInterface</var> class.
* @param implementation The implementation of this MBean.
* If <code>null</code>, and null implementation is allowed,
* then the implementation is assumed to be <var>this</var>.
* @param mbeanInterface The Management Interface exported by this
* MBean's implementation. If <code>null</code>, then this
* object will use standard JMX design pattern to determine
* the management interface associated with the given
* implementation.
* @param nullImplementationAllowed <code>true</code> if a null
* implementation is allowed. If null implementation is allowed,
* and a null implementation is passed, then the implementation
* is assumed to be <var>this</var>.
* @exception IllegalArgumentException if the given
* <var>implementation</var> is null, and null is not allowed.
**/
private <T> void construct(T implementation, Class<T> mbeanInterface,
boolean nullImplementationAllowed,
boolean isMXBean)
throws NotCompliantMBeanException {
if (implementation == null) {
// Have to use (T)this rather than mbeanInterface.cast(this)
// because mbeanInterface might be null.
if (nullImplementationAllowed)
implementation = Util.<T>cast(this);
else throw new IllegalArgumentException("implementation is null");
}
if (isMXBean) {
if (mbeanInterface == null) {
mbeanInterface = Util.cast(Introspector.getMXBeanInterface(
implementation.getClass()));
}
this.mbean = new MXBeanSupport(implementation, mbeanInterface);
} else {
if (mbeanInterface == null) {
mbeanInterface = Util.cast(Introspector.getStandardMBeanInterface(
implementation.getClass()));
}
this.mbean =
new StandardMBeanSupport(implementation, mbeanInterface);
}
}
/** {@collect.stats}
* <p>Make a DynamicMBean out of the object
* <var>implementation</var>, using the specified
* <var>mbeanInterface</var> class.</p>
*
* @param implementation The implementation of this MBean.
* @param mbeanInterface The Management Interface exported by this
* MBean's implementation. If <code>null</code>, then this
* object will use standard JMX design pattern to determine
* the management interface associated with the given
* implementation.
* @param <T> Allows the compiler to check
* that {@code implementation} does indeed implement the class
* described by {@code mbeanInterface}. The compiler can only
* check this if {@code mbeanInterface} is a class literal such
* as {@code MyMBean.class}.
*
* @exception IllegalArgumentException if the given
* <var>implementation</var> is null.
* @exception NotCompliantMBeanException if the <var>mbeanInterface</var>
* does not follow JMX design patterns for Management Interfaces, or
* if the given <var>implementation</var> does not implement the
* specified interface.
**/
public <T> StandardMBean(T implementation, Class<T> mbeanInterface)
throws NotCompliantMBeanException {
construct(implementation, mbeanInterface, false, false);
}
/** {@collect.stats}
* <p>Make a DynamicMBean out of <var>this</var>, using the specified
* <var>mbeanInterface</var> class.</p>
*
* <p>Call {@link #StandardMBean(java.lang.Object, java.lang.Class)
* this(this,mbeanInterface)}.
* This constructor is reserved to subclasses.</p>
*
* @param mbeanInterface The Management Interface exported by this
* MBean.
*
* @exception NotCompliantMBeanException if the <var>mbeanInterface</var>
* does not follow JMX design patterns for Management Interfaces, or
* if <var>this</var> does not implement the specified interface.
**/
protected StandardMBean(Class<?> mbeanInterface)
throws NotCompliantMBeanException {
construct(null, mbeanInterface, true, false);
}
/** {@collect.stats}
* <p>Make a DynamicMBean out of the object
* <var>implementation</var>, using the specified
* <var>mbeanInterface</var> class. This constructor can be used
* to make either Standard MBeans or MXBeans. Unlike the
* constructor {@link #StandardMBean(Object, Class)}, it
* does not throw NotCompliantMBeanException.</p>
*
* @param implementation The implementation of this MBean.
* @param mbeanInterface The Management Interface exported by this
* MBean's implementation. If <code>null</code>, then this
* object will use standard JMX design pattern to determine
* the management interface associated with the given
* implementation.
* @param isMXBean If true, the {@code mbeanInterface} parameter
* names an MXBean interface and the resultant MBean is an MXBean.
* @param <T> Allows the compiler to check
* that {@code implementation} does indeed implement the class
* described by {@code mbeanInterface}. The compiler can only
* check this if {@code mbeanInterface} is a class literal such
* as {@code MyMBean.class}.
*
* @exception IllegalArgumentException if the given
* <var>implementation</var> is null, or if the <var>mbeanInterface</var>
* does not follow JMX design patterns for Management Interfaces, or
* if the given <var>implementation</var> does not implement the
* specified interface.
*
* @since 1.6
**/
public <T> StandardMBean(T implementation, Class<T> mbeanInterface,
boolean isMXBean) {
try {
construct(implementation, mbeanInterface, false, isMXBean);
} catch (NotCompliantMBeanException e) {
throw new IllegalArgumentException(e);
}
}
/** {@collect.stats}
* <p>Make a DynamicMBean out of <var>this</var>, using the specified
* <var>mbeanInterface</var> class. This constructor can be used
* to make either Standard MBeans or MXBeans. Unlike the
* constructor {@link #StandardMBean(Object, Class)}, it
* does not throw NotCompliantMBeanException.</p>
*
* <p>Call {@link #StandardMBean(java.lang.Object, java.lang.Class, boolean)
* this(this, mbeanInterface, isMXBean)}.
* This constructor is reserved to subclasses.</p>
*
* @param mbeanInterface The Management Interface exported by this
* MBean.
* @param isMXBean If true, the {@code mbeanInterface} parameter
* names an MXBean interface and the resultant MBean is an MXBean.
*
* @exception IllegalArgumentException if the <var>mbeanInterface</var>
* does not follow JMX design patterns for Management Interfaces, or
* if <var>this</var> does not implement the specified interface.
*
* @since 1.6
**/
protected StandardMBean(Class<?> mbeanInterface, boolean isMXBean) {
try {
construct(null, mbeanInterface, true, isMXBean);
} catch (NotCompliantMBeanException e) {
throw new IllegalArgumentException(e);
}
}
/** {@collect.stats}
* <p>Replace the implementation object wrapped in this object.</p>
*
* @param implementation The new implementation of this Standard MBean
* (or MXBean). The <code>implementation</code> object must implement
* the Standard MBean (or MXBean) interface that was supplied when this
* <code>StandardMBean</code> was constructed.
*
* @exception IllegalArgumentException if the given
* <var>implementation</var> is null.
*
* @exception NotCompliantMBeanException if the given
* <var>implementation</var> does not implement the
* Standard MBean (or MXBean) interface that was
* supplied at construction.
*
* @see #getImplementation
**/
public void setImplementation(Object implementation)
throws NotCompliantMBeanException {
if (implementation == null)
throw new IllegalArgumentException("implementation is null");
if (isMXBean()) {
this.mbean = new MXBeanSupport(implementation,
Util.<Class<Object>>cast(getMBeanInterface()));
} else {
this.mbean = new StandardMBeanSupport(implementation,
Util.<Class<Object>>cast(getMBeanInterface()));
}
}
/** {@collect.stats}
* Get the implementation of this Standard MBean (or MXBean).
* @return The implementation of this Standard MBean (or MXBean).
*
* @see #setImplementation
**/
public Object getImplementation() {
return mbean.getResource();
}
/** {@collect.stats}
* Get the Management Interface of this Standard MBean (or MXBean).
* @return The management interface of this Standard MBean (or MXBean).
**/
public final Class<?> getMBeanInterface() {
return mbean.getMBeanInterface();
}
/** {@collect.stats}
* Get the class of the implementation of this Standard MBean (or MXBean).
* @return The class of the implementation of this Standard MBean (or MXBean).
**/
public Class<?> getImplementationClass() {
return mbean.getResource().getClass();
}
// ------------------------------------------------------------------
// From the DynamicMBean interface.
// ------------------------------------------------------------------
public Object getAttribute(String attribute)
throws AttributeNotFoundException,
MBeanException,
ReflectionException {
return mbean.getAttribute(attribute);
}
// ------------------------------------------------------------------
// From the DynamicMBean interface.
// ------------------------------------------------------------------
public void setAttribute(Attribute attribute)
throws AttributeNotFoundException,
InvalidAttributeValueException,
MBeanException,
ReflectionException {
mbean.setAttribute(attribute);
}
// ------------------------------------------------------------------
// From the DynamicMBean interface.
// ------------------------------------------------------------------
public AttributeList getAttributes(String[] attributes) {
return mbean.getAttributes(attributes);
}
// ------------------------------------------------------------------
// From the DynamicMBean interface.
// ------------------------------------------------------------------
public AttributeList setAttributes(AttributeList attributes) {
return mbean.setAttributes(attributes);
}
// ------------------------------------------------------------------
// From the DynamicMBean interface.
// ------------------------------------------------------------------
public Object invoke(String actionName, Object params[], String signature[])
throws MBeanException, ReflectionException {
return mbean.invoke(actionName, params, signature);
}
/** {@collect.stats}
* Get the {@link MBeanInfo} for this MBean.
* <p>
* This method implements
* {@link javax.management.DynamicMBean#getMBeanInfo()
* DynamicMBean.getMBeanInfo()}.
* <p>
* This method first calls {@link #getCachedMBeanInfo()} in order to
* retrieve the cached MBeanInfo for this MBean, if any. If the
* MBeanInfo returned by {@link #getCachedMBeanInfo()} is not null,
* then it is returned.<br>
* Otherwise, this method builds a default MBeanInfo for this MBean,
* using the Management Interface specified for this MBean.
* <p>
* While building the MBeanInfo, this method calls the customization
* hooks that make it possible for subclasses to supply their custom
* descriptions, parameter names, etc...<br>
* Finally, it calls {@link #cacheMBeanInfo(javax.management.MBeanInfo)
* cacheMBeanInfo()} in order to cache the new MBeanInfo.
* @return The cached MBeanInfo for that MBean, if not null, or a
* newly built MBeanInfo if none was cached.
**/
public MBeanInfo getMBeanInfo() {
try {
final MBeanInfo cached = getCachedMBeanInfo();
if (cached != null) return cached;
} catch (RuntimeException x) {
if (MISC_LOGGER.isLoggable(Level.FINEST)) {
MISC_LOGGER.logp(Level.FINEST,
MBeanServerFactory.class.getName(), "getMBeanInfo",
"Failed to get cached MBeanInfo", x);
}
}
if (MISC_LOGGER.isLoggable(Level.FINER)) {
MISC_LOGGER.logp(Level.FINER,
MBeanServerFactory.class.getName(), "getMBeanInfo",
"Building MBeanInfo for " +
getImplementationClass().getName());
}
MBeanSupport msupport = mbean;
final MBeanInfo bi = msupport.getMBeanInfo();
final Object impl = msupport.getResource();
final boolean immutableInfo = immutableInfo(this.getClass());
final String cname = getClassName(bi);
final String text = getDescription(bi);
final MBeanConstructorInfo[] ctors = getConstructors(bi,impl);
final MBeanAttributeInfo[] attrs = getAttributes(bi);
final MBeanOperationInfo[] ops = getOperations(bi);
final MBeanNotificationInfo[] ntfs = getNotifications(bi);
final Descriptor desc = getDescriptor(bi, immutableInfo);
final MBeanInfo nmbi = new MBeanInfo(
cname, text, attrs, ctors, ops, ntfs, desc);
try {
cacheMBeanInfo(nmbi);
} catch (RuntimeException x) {
if (MISC_LOGGER.isLoggable(Level.FINEST)) {
MISC_LOGGER.logp(Level.FINEST,
MBeanServerFactory.class.getName(), "getMBeanInfo",
"Failed to cache MBeanInfo", x);
}
}
return nmbi;
}
/** {@collect.stats}
* Customization hook:
* Get the className that will be used in the MBeanInfo returned by
* this MBean.
* <br>
* Subclasses may redefine this method in order to supply their
* custom class name. The default implementation returns
* {@link MBeanInfo#getClassName() info.getClassName()}.
* @param info The default MBeanInfo derived by reflection.
* @return the class name for the new MBeanInfo.
**/
protected String getClassName(MBeanInfo info) {
if (info == null) return getImplementationClass().getName();
return info.getClassName();
}
/** {@collect.stats}
* Customization hook:
* Get the description that will be used in the MBeanInfo returned by
* this MBean.
* <br>
* Subclasses may redefine this method in order to supply their
* custom MBean description. The default implementation returns
* {@link MBeanInfo#getDescription() info.getDescription()}.
* @param info The default MBeanInfo derived by reflection.
* @return the description for the new MBeanInfo.
**/
protected String getDescription(MBeanInfo info) {
if (info == null) return null;
return info.getDescription();
}
/** {@collect.stats}
* <p>Customization hook:
* Get the description that will be used in the MBeanFeatureInfo
* returned by this MBean.</p>
*
* <p>Subclasses may redefine this method in order to supply
* their custom description. The default implementation returns
* {@link MBeanFeatureInfo#getDescription()
* info.getDescription()}.</p>
*
* <p>This method is called by
* {@link #getDescription(MBeanAttributeInfo)},
* {@link #getDescription(MBeanOperationInfo)},
* {@link #getDescription(MBeanConstructorInfo)}.</p>
*
* @param info The default MBeanFeatureInfo derived by reflection.
* @return the description for the given MBeanFeatureInfo.
**/
protected String getDescription(MBeanFeatureInfo info) {
if (info == null) return null;
return info.getDescription();
}
/** {@collect.stats}
* Customization hook:
* Get the description that will be used in the MBeanAttributeInfo
* returned by this MBean.
*
* <p>Subclasses may redefine this method in order to supply their
* custom description. The default implementation returns {@link
* #getDescription(MBeanFeatureInfo)
* getDescription((MBeanFeatureInfo) info)}.
* @param info The default MBeanAttributeInfo derived by reflection.
* @return the description for the given MBeanAttributeInfo.
**/
protected String getDescription(MBeanAttributeInfo info) {
return getDescription((MBeanFeatureInfo)info);
}
/** {@collect.stats}
* Customization hook:
* Get the description that will be used in the MBeanConstructorInfo
* returned by this MBean.
* <br>
* Subclasses may redefine this method in order to supply their
* custom description.
* The default implementation returns {@link
* #getDescription(MBeanFeatureInfo)
* getDescription((MBeanFeatureInfo) info)}.
* @param info The default MBeanConstructorInfo derived by reflection.
* @return the description for the given MBeanConstructorInfo.
**/
protected String getDescription(MBeanConstructorInfo info) {
return getDescription((MBeanFeatureInfo)info);
}
/** {@collect.stats}
* Customization hook:
* Get the description that will be used for the <var>sequence</var>
* MBeanParameterInfo of the MBeanConstructorInfo returned by this MBean.
* <br>
* Subclasses may redefine this method in order to supply their
* custom description. The default implementation returns
* {@link MBeanParameterInfo#getDescription() param.getDescription()}.
*
* @param ctor The default MBeanConstructorInfo derived by reflection.
* @param param The default MBeanParameterInfo derived by reflection.
* @param sequence The sequence number of the parameter considered
* ("0" for the first parameter, "1" for the second parameter,
* etc...).
* @return the description for the given MBeanParameterInfo.
**/
protected String getDescription(MBeanConstructorInfo ctor,
MBeanParameterInfo param,
int sequence) {
if (param == null) return null;
return param.getDescription();
}
/** {@collect.stats}
* Customization hook:
* Get the name that will be used for the <var>sequence</var>
* MBeanParameterInfo of the MBeanConstructorInfo returned by this MBean.
* <br>
* Subclasses may redefine this method in order to supply their
* custom parameter name. The default implementation returns
* {@link MBeanParameterInfo#getName() param.getName()}.
*
* @param ctor The default MBeanConstructorInfo derived by reflection.
* @param param The default MBeanParameterInfo derived by reflection.
* @param sequence The sequence number of the parameter considered
* ("0" for the first parameter, "1" for the second parameter,
* etc...).
* @return the name for the given MBeanParameterInfo.
**/
protected String getParameterName(MBeanConstructorInfo ctor,
MBeanParameterInfo param,
int sequence) {
if (param == null) return null;
return param.getName();
}
/** {@collect.stats}
* Customization hook:
* Get the description that will be used in the MBeanOperationInfo
* returned by this MBean.
* <br>
* Subclasses may redefine this method in order to supply their
* custom description. The default implementation returns
* {@link #getDescription(MBeanFeatureInfo)
* getDescription((MBeanFeatureInfo) info)}.
* @param info The default MBeanOperationInfo derived by reflection.
* @return the description for the given MBeanOperationInfo.
**/
protected String getDescription(MBeanOperationInfo info) {
return getDescription((MBeanFeatureInfo)info);
}
/** {@collect.stats}
* Customization hook:
* Get the <var>impact</var> flag of the operation that will be used in
* the MBeanOperationInfo returned by this MBean.
* <br>
* Subclasses may redefine this method in order to supply their
* custom impact flag. The default implementation returns
* {@link MBeanOperationInfo#getImpact() info.getImpact()}.
* @param info The default MBeanOperationInfo derived by reflection.
* @return the impact flag for the given MBeanOperationInfo.
**/
protected int getImpact(MBeanOperationInfo info) {
if (info == null) return MBeanOperationInfo.UNKNOWN;
return info.getImpact();
}
/** {@collect.stats}
* Customization hook:
* Get the name that will be used for the <var>sequence</var>
* MBeanParameterInfo of the MBeanOperationInfo returned by this MBean.
* <br>
* Subclasses may redefine this method in order to supply their
* custom parameter name. The default implementation returns
* {@link MBeanParameterInfo#getName() param.getName()}.
*
* @param op The default MBeanOperationInfo derived by reflection.
* @param param The default MBeanParameterInfo derived by reflection.
* @param sequence The sequence number of the parameter considered
* ("0" for the first parameter, "1" for the second parameter,
* etc...).
* @return the name to use for the given MBeanParameterInfo.
**/
protected String getParameterName(MBeanOperationInfo op,
MBeanParameterInfo param,
int sequence) {
if (param == null) return null;
return param.getName();
}
/** {@collect.stats}
* Customization hook:
* Get the description that will be used for the <var>sequence</var>
* MBeanParameterInfo of the MBeanOperationInfo returned by this MBean.
* <br>
* Subclasses may redefine this method in order to supply their
* custom description. The default implementation returns
* {@link MBeanParameterInfo#getDescription() param.getDescription()}.
*
* @param op The default MBeanOperationInfo derived by reflection.
* @param param The default MBeanParameterInfo derived by reflection.
* @param sequence The sequence number of the parameter considered
* ("0" for the first parameter, "1" for the second parameter,
* etc...).
* @return the description for the given MBeanParameterInfo.
**/
protected String getDescription(MBeanOperationInfo op,
MBeanParameterInfo param,
int sequence) {
if (param == null) return null;
return param.getDescription();
}
/** {@collect.stats}
* Customization hook:
* Get the MBeanConstructorInfo[] that will be used in the MBeanInfo
* returned by this MBean.
* <br>
* By default, this method returns <code>null</code> if the wrapped
* implementation is not <var>this</var>. Indeed, if the wrapped
* implementation is not this object itself, it will not be possible
* to recreate a wrapped implementation by calling the implementation
* constructors through <code>MBeanServer.createMBean(...)</code>.<br>
* Otherwise, if the wrapped implementation is <var>this</var>,
* <var>ctors</var> is returned.
* <br>
* Subclasses may redefine this method in order to modify this
* behavior, if needed.
* @param ctors The default MBeanConstructorInfo[] derived by reflection.
* @param impl The wrapped implementation. If <code>null</code> is
* passed, the wrapped implementation is ignored and
* <var>ctors</var> is returned.
* @return the MBeanConstructorInfo[] for the new MBeanInfo.
**/
protected MBeanConstructorInfo[]
getConstructors(MBeanConstructorInfo[] ctors, Object impl) {
if (ctors == null) return null;
if (impl != null && impl != this) return null;
return ctors;
}
/** {@collect.stats}
* Customization hook:
* Get the MBeanNotificationInfo[] that will be used in the MBeanInfo
* returned by this MBean.
* <br>
* Subclasses may redefine this method in order to supply their
* custom notifications.
* @param info The default MBeanInfo derived by reflection.
* @return the MBeanNotificationInfo[] for the new MBeanInfo.
**/
MBeanNotificationInfo[] getNotifications(MBeanInfo info) {
return null;
}
/** {@collect.stats}
* <p>Get the Descriptor that will be used in the MBeanInfo
* returned by this MBean.</p>
*
* <p>Subclasses may redefine this method in order to supply
* their custom descriptor.</p>
*
* <p>The default implementation of this method returns a Descriptor
* that contains at least the field {@code interfaceClassName}, with
* value {@link #getMBeanInterface()}.getName(). It may also contain
* the field {@code immutableInfo}, with a value that is the string
* {@code "true"} if the implementation can determine that the
* {@code MBeanInfo} returned by {@link #getMBeanInfo()} will always
* be the same. It may contain other fields: fields defined by the
* JMX specification must have appropriate values, and other fields
* must follow the conventions for non-standard field names.</p>
*
* @param info The default MBeanInfo derived by reflection.
* @return the Descriptor for the new MBeanInfo.
*/
Descriptor getDescriptor(MBeanInfo info, boolean immutableInfo) {
ImmutableDescriptor desc = null;
if (info == null ||
info.getDescriptor() == null ||
info.getDescriptor().getFieldNames().length == 0) {
final String interfaceClassNameS =
"interfaceClassName=" + getMBeanInterface().getName();
final String immutableInfoS =
"immutableInfo=" + immutableInfo;
desc = new ImmutableDescriptor(interfaceClassNameS, immutableInfoS);
desc = descriptors.get(desc);
} else {
Descriptor d = info.getDescriptor();
Map<String,Object> fields = new HashMap<String,Object>();
for (String fieldName : d.getFieldNames()) {
if (fieldName.equals("immutableInfo")) {
// Replace immutableInfo as the underlying MBean/MXBean
// could already implement NotificationBroadcaster and
// return immutableInfo=true in its MBeanInfo.
fields.put(fieldName, Boolean.toString(immutableInfo));
} else {
fields.put(fieldName, d.getFieldValue(fieldName));
}
}
desc = new ImmutableDescriptor(fields);
}
return desc;
}
/** {@collect.stats}
* Customization hook:
* Return the MBeanInfo cached for this object.
*
* <p>Subclasses may redefine this method in order to implement their
* own caching policy. The default implementation stores one
* {@link MBeanInfo} object per instance.
*
* @return The cached MBeanInfo, or null if no MBeanInfo is cached.
*
* @see #cacheMBeanInfo(MBeanInfo)
**/
protected MBeanInfo getCachedMBeanInfo() {
return cachedMBeanInfo;
}
/** {@collect.stats}
* Customization hook:
* cache the MBeanInfo built for this object.
*
* <p>Subclasses may redefine this method in order to implement
* their own caching policy. The default implementation stores
* <code>info</code> in this instance. A subclass can define
* other policies, such as not saving <code>info</code> (so it is
* reconstructed every time {@link #getMBeanInfo()} is called) or
* sharing a unique {@link MBeanInfo} object when several
* <code>StandardMBean</code> instances have equal {@link
* MBeanInfo} values.
*
* @param info the new <code>MBeanInfo</code> to cache. Any
* previously cached value is discarded. This parameter may be
* null, in which case there is no new cached value.
**/
protected void cacheMBeanInfo(MBeanInfo info) {
cachedMBeanInfo = info;
}
private boolean isMXBean() {
return mbean.isMXBean();
}
private static <T> boolean identicalArrays(T[] a, T[] b) {
if (a == b)
return true;
if (a == null || b == null || a.length != b.length)
return false;
for (int i = 0; i < a.length; i++) {
if (a[i] != b[i])
return false;
}
return true;
}
private static <T> boolean equal(T a, T b) {
if (a == b)
return true;
if (a == null || b == null)
return false;
return a.equals(b);
}
private static MBeanParameterInfo
customize(MBeanParameterInfo pi,
String name,
String description) {
if (equal(name, pi.getName()) &&
equal(description, pi.getDescription()))
return pi;
else if (pi instanceof OpenMBeanParameterInfo) {
OpenMBeanParameterInfo opi = (OpenMBeanParameterInfo) pi;
return new OpenMBeanParameterInfoSupport(name,
description,
opi.getOpenType(),
pi.getDescriptor());
} else {
return new MBeanParameterInfo(name,
pi.getType(),
description,
pi.getDescriptor());
}
}
private static MBeanConstructorInfo
customize(MBeanConstructorInfo ci,
String description,
MBeanParameterInfo[] signature) {
if (equal(description, ci.getDescription()) &&
identicalArrays(signature, ci.getSignature()))
return ci;
if (ci instanceof OpenMBeanConstructorInfo) {
OpenMBeanParameterInfo[] oparams =
paramsToOpenParams(signature);
return new OpenMBeanConstructorInfoSupport(ci.getName(),
description,
oparams,
ci.getDescriptor());
} else {
return new MBeanConstructorInfo(ci.getName(),
description,
signature,
ci.getDescriptor());
}
}
private static MBeanOperationInfo
customize(MBeanOperationInfo oi,
String description,
MBeanParameterInfo[] signature,
int impact) {
if (equal(description, oi.getDescription()) &&
identicalArrays(signature, oi.getSignature()) &&
impact == oi.getImpact())
return oi;
if (oi instanceof OpenMBeanOperationInfo) {
OpenMBeanOperationInfo ooi = (OpenMBeanOperationInfo) oi;
OpenMBeanParameterInfo[] oparams =
paramsToOpenParams(signature);
return new OpenMBeanOperationInfoSupport(oi.getName(),
description,
oparams,
ooi.getReturnOpenType(),
impact,
oi.getDescriptor());
} else {
return new MBeanOperationInfo(oi.getName(),
description,
signature,
oi.getReturnType(),
impact,
oi.getDescriptor());
}
}
private static MBeanAttributeInfo
customize(MBeanAttributeInfo ai,
String description) {
if (equal(description, ai.getDescription()))
return ai;
if (ai instanceof OpenMBeanAttributeInfo) {
OpenMBeanAttributeInfo oai = (OpenMBeanAttributeInfo) ai;
return new OpenMBeanAttributeInfoSupport(ai.getName(),
description,
oai.getOpenType(),
ai.isReadable(),
ai.isWritable(),
ai.isIs(),
ai.getDescriptor());
} else {
return new MBeanAttributeInfo(ai.getName(),
ai.getType(),
description,
ai.isReadable(),
ai.isWritable(),
ai.isIs(),
ai.getDescriptor());
}
}
private static OpenMBeanParameterInfo[]
paramsToOpenParams(MBeanParameterInfo[] params) {
if (params instanceof OpenMBeanParameterInfo[])
return (OpenMBeanParameterInfo[]) params;
OpenMBeanParameterInfo[] oparams =
new OpenMBeanParameterInfoSupport[params.length];
System.arraycopy(params, 0, oparams, 0, params.length);
return oparams;
}
// ------------------------------------------------------------------
// Build the custom MBeanConstructorInfo[]
// ------------------------------------------------------------------
private MBeanConstructorInfo[]
getConstructors(MBeanInfo info, Object impl) {
final MBeanConstructorInfo[] ctors =
getConstructors(info.getConstructors(), impl);
if (ctors == null)
return null;
final int ctorlen = ctors.length;
final MBeanConstructorInfo[] nctors = new MBeanConstructorInfo[ctorlen];
for (int i=0; i<ctorlen; i++) {
final MBeanConstructorInfo c = ctors[i];
final MBeanParameterInfo[] params = c.getSignature();
final MBeanParameterInfo[] nps;
if (params != null) {
final int plen = params.length;
nps = new MBeanParameterInfo[plen];
for (int ii=0;ii<plen;ii++) {
MBeanParameterInfo p = params[ii];
nps[ii] = customize(p,
getParameterName(c,p,ii),
getDescription(c,p,ii));
}
} else {
nps = null;
}
nctors[i] =
customize(c, getDescription(c), nps);
}
return nctors;
}
// ------------------------------------------------------------------
// Build the custom MBeanOperationInfo[]
// ------------------------------------------------------------------
private MBeanOperationInfo[] getOperations(MBeanInfo info) {
final MBeanOperationInfo[] ops = info.getOperations();
if (ops == null)
return null;
final int oplen = ops.length;
final MBeanOperationInfo[] nops = new MBeanOperationInfo[oplen];
for (int i=0; i<oplen; i++) {
final MBeanOperationInfo o = ops[i];
final MBeanParameterInfo[] params = o.getSignature();
final MBeanParameterInfo[] nps;
if (params != null) {
final int plen = params.length;
nps = new MBeanParameterInfo[plen];
for (int ii=0;ii<plen;ii++) {
MBeanParameterInfo p = params[ii];
nps[ii] = customize(p,
getParameterName(o,p,ii),
getDescription(o,p,ii));
}
} else {
nps = null;
}
nops[i] = customize(o, getDescription(o), nps, getImpact(o));
}
return nops;
}
// ------------------------------------------------------------------
// Build the custom MBeanAttributeInfo[]
// ------------------------------------------------------------------
private MBeanAttributeInfo[] getAttributes(MBeanInfo info) {
final MBeanAttributeInfo[] atts = info.getAttributes();
if (atts == null)
return null; // should not happen
final MBeanAttributeInfo[] natts;
final int attlen = atts.length;
natts = new MBeanAttributeInfo[attlen];
for (int i=0; i<attlen; i++) {
final MBeanAttributeInfo a = atts[i];
natts[i] = customize(a, getDescription(a));
}
return natts;
}
/** {@collect.stats}
* <p>Allows the MBean to perform any operations it needs before
* being registered in the MBean server. If the name of the MBean
* is not specified, the MBean can provide a name for its
* registration. If any exception is raised, the MBean will not be
* registered in the MBean server.</p>
*
* <p>The default implementation of this method returns the {@code name}
* parameter. It does nothing else for
* Standard MBeans. For MXBeans, it records the {@code MBeanServer}
* and {@code ObjectName} parameters so they can be used to translate
* inter-MXBean references.</p>
*
* <p>It is good practice for a subclass that overrides this method
* to call the overridden method via {@code super.preRegister(...)}.
* This is necessary if this object is an MXBean that is referenced
* by attributes or operations in other MXBeans.</p>
*
* @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.
*
* @throws IllegalArgumentException if this is an MXBean and
* {@code name} is null.
*
* @throws InstanceAlreadyExistsException if this is an MXBean and
* it has already been registered under another name (in this
* MBean Server or another).
*
* @throws Exception no other checked exceptions are thrown by
* this method but {@code Exception} is declared so that subclasses
* can override the method and throw their own exceptions.
*
* @since 1.6
*/
public ObjectName preRegister(MBeanServer server, ObjectName name)
throws Exception {
mbean.register(server, name);
return name;
}
/** {@collect.stats}
* <p>Allows the MBean to perform any operations needed after having been
* registered in the MBean server or after the registration has failed.</p>
*
* <p>The default implementation of this method does nothing for
* Standard MBeans. For MXBeans, it undoes any work done by
* {@link #preRegister preRegister} if registration fails.</p>
*
* <p>It is good practice for a subclass that overrides this method
* to call the overridden method via {@code super.postRegister(...)}.
* This is necessary if this object is an MXBean that is referenced
* by attributes or operations in other MXBeans.</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.
*
* @since 1.6
*/
public void postRegister(Boolean registrationDone) {
if (!registrationDone)
mbean.unregister();
}
/** {@collect.stats}
* <p>Allows the MBean to perform any operations it needs before
* being unregistered by the MBean server.</p>
*
* <p>The default implementation of this method does nothing.</p>
*
* <p>It is good practice for a subclass that overrides this method
* to call the overridden method via {@code super.preDeegister(...)}.</p>
*
* @throws Exception no checked exceptions are throw by this method
* but {@code Exception} is declared so that subclasses can override
* this method and throw their own exceptions.
*
* @since 1.6
*/
public void preDeregister() throws Exception {
}
/** {@collect.stats}
* <p>Allows the MBean to perform any operations needed after having been
* unregistered in the MBean server.</p>
*
* <p>The default implementation of this method does nothing for
* Standard MBeans. For MXBeans, it removes any information that
* was recorded by the {@link #preRegister preRegister} method.</p>
*
* <p>It is good practice for a subclass that overrides this method
* to call the overridden method via {@code super.postRegister(...)}.
* This is necessary if this object is an MXBean that is referenced
* by attributes or operations in other MXBeans.</p>
*
* @since 1.6
*/
public void postDeregister() {
mbean.unregister();
}
//
// MBeanInfo immutability
//
/** {@collect.stats}
* Cached results of previous calls to immutableInfo. This is
* a WeakHashMap so that we don't prevent a class from being
* garbage collected just because we know whether its MBeanInfo
* is immutable.
*/
private static final Map<Class, Boolean> mbeanInfoSafeMap =
new WeakHashMap<Class, Boolean>();
/** {@collect.stats}
* Return true if {@code subclass} is known to preserve the immutability
* of the {@code MBeanInfo}. The {@code subclass} is considered to have
* an immutable {@code MBeanInfo} if it does not override any of the
* getMBeanInfo, getCachedMBeanInfo, cacheMBeanInfo and getNotificationInfo
* methods.
*/
static boolean immutableInfo(Class<? extends StandardMBean> subclass) {
if (subclass == StandardMBean.class ||
subclass == StandardEmitterMBean.class)
return true;
synchronized (mbeanInfoSafeMap) {
Boolean safe = mbeanInfoSafeMap.get(subclass);
if (safe == null) {
try {
MBeanInfoSafeAction action =
new MBeanInfoSafeAction(subclass);
safe = AccessController.doPrivileged(action);
} catch (Exception e) { // e.g. SecurityException
/* We don't know, so we assume it isn't. */
safe = false;
}
mbeanInfoSafeMap.put(subclass, safe);
}
return safe;
}
}
static boolean overrides(Class<?> subclass, Class<?> superclass,
String name, Class<?>... params) {
for (Class<?> c = subclass; c != superclass; c = c.getSuperclass()) {
try {
c.getDeclaredMethod(name, params);
return true;
} catch (NoSuchMethodException e) {
// OK: this class doesn't override it
}
}
return false;
}
private static class MBeanInfoSafeAction
implements PrivilegedAction<Boolean> {
private final Class subclass;
MBeanInfoSafeAction(Class subclass) {
this.subclass = subclass;
}
public Boolean run() {
// Check for "void cacheMBeanInfo(MBeanInfo)" method.
//
if (overrides(subclass, StandardMBean.class,
"cacheMBeanInfo", MBeanInfo.class))
return false;
// Check for "MBeanInfo getCachedMBeanInfo()" method.
//
if (overrides(subclass, StandardMBean.class,
"getCachedMBeanInfo", (Class[]) null))
return false;
// Check for "MBeanInfo getMBeanInfo()" method.
//
if (overrides(subclass, StandardMBean.class,
"getMBeanInfo", (Class[]) null))
return false;
// Check for "MBeanNotificationInfo[] getNotificationInfo()"
// method.
//
// This method is only taken into account for the MBeanInfo
// immutability checks if and only if the given subclass is
// StandardEmitterMBean itself or can be assigned to
// StandardEmitterMBean.
//
if (StandardEmitterMBean.class.isAssignableFrom(subclass))
if (overrides(subclass, StandardEmitterMBean.class,
"getNotificationInfo", (Class[]) null))
return false;
return true;
}
}
}
| Java |
/*
* Copyright (c) 2002, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management;
import java.util.concurrent.CopyOnWriteArrayList; // for Javadoc
/** {@collect.stats}
* <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 {
/** {@collect.stats}
* <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;
}
| Java |
/*
* Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management.timer;
// java imports
//
import java.util.Date;
import java.util.Vector;
// NPCTE fix for bugId 4464388, esc 0, MR , to be added after modification of jmx spec
//import java.io.Serializable;
// end of NPCTE fix for bugId 4464388
// jmx imports
//
import javax.management.InstanceNotFoundException;
/** {@collect.stats}
* Exposes the management interface of the timer MBean.
*
* @since 1.5
*/
public interface TimerMBean {
/** {@collect.stats}
* Starts the timer.
* <P>
* If there is one or more timer notifications before the time in the list of notifications, the notification
* is sent according to the <CODE>sendPastNotifications</CODE> flag and then, updated
* according to its period and remaining number of occurrences.
* If the timer notification date remains earlier than the current date, this notification is just removed
* from the list of notifications.
*/
public void start();
/** {@collect.stats}
* Stops the timer.
*/
public void stop();
/** {@collect.stats}
* Creates a new timer notification with the specified <CODE>type</CODE>, <CODE>message</CODE>
* and <CODE>userData</CODE> and inserts it into the list of notifications with a given date,
* period and number of occurrences.
* <P>
* If the timer notification to be inserted has a date that is before the current date,
* the method behaves as if the specified date were the current date. <BR>
* For once-off notifications, the notification is delivered immediately. <BR>
* For periodic notifications, the first notification is delivered immediately and the
* subsequent ones are spaced as specified by the period parameter.
* <P>
* Note that once the timer notification has been added into the list of notifications,
* its associated date, period and number of occurrences cannot be updated.
* <P>
* In the case of a periodic notification, the value of parameter <i>fixedRate</i> is used to
* specify the execution scheme, as specified in {@link java.util.Timer}.
*
* @param type The timer notification type.
* @param message The timer notification detailed message.
* @param userData The timer notification user data object.
* @param date The date when the notification occurs.
* @param period The period of the timer notification (in milliseconds).
* @param nbOccurences The total number the timer notification will be emitted.
* @param fixedRate If <code>true</code> and if the notification is periodic, the notification
* is scheduled with a <i>fixed-rate</i> execution scheme. If
* <code>false</code> and if the notification is periodic, the notification
* is scheduled with a <i>fixed-delay</i> execution scheme. Ignored if the
* notification is not periodic.
*
* @return The identifier of the new created timer notification.
*
* @exception java.lang.IllegalArgumentException The date is {@code null} or
* the period or the number of occurrences is negative.
*
* @see #addNotification(String, String, Object, Date, long, long)
*/
// NPCTE fix for bugId 4464388, esc 0, MR, to be added after modification of jmx spec
// public synchronized Integer addNotification(String type, String message, Serializable userData,
// Date date, long period, long nbOccurences)
// end of NPCTE fix for bugId 4464388
public Integer addNotification(String type, String message, Object userData,
Date date, long period, long nbOccurences, boolean fixedRate)
throws java.lang.IllegalArgumentException;
/** {@collect.stats}
* Creates a new timer notification with the specified <CODE>type</CODE>, <CODE>message</CODE>
* and <CODE>userData</CODE> and inserts it into the list of notifications with a given date,
* period and number of occurrences.
* <P>
* If the timer notification to be inserted has a date that is before the current date,
* the method behaves as if the specified date were the current date. <BR>
* For once-off notifications, the notification is delivered immediately. <BR>
* For periodic notifications, the first notification is delivered immediately and the
* subsequent ones are spaced as specified by the period parameter.
* <P>
* Note that once the timer notification has been added into the list of notifications,
* its associated date, period and number of occurrences cannot be updated.
* <P>
* In the case of a periodic notification, uses a <i>fixed-delay</i> execution scheme, as specified in
* {@link java.util.Timer}. In order to use a <i>fixed-rate</i> execution scheme, use
* {@link #addNotification(String, String, Object, Date, long, long, boolean)} instead.
*
* @param type The timer notification type.
* @param message The timer notification detailed message.
* @param userData The timer notification user data object.
* @param date The date when the notification occurs.
* @param period The period of the timer notification (in milliseconds).
* @param nbOccurences The total number the timer notification will be emitted.
*
* @return The identifier of the new created timer notification.
*
* @exception java.lang.IllegalArgumentException The date is {@code null} or
* the period or the number of occurrences is negative.
*
* @see #addNotification(String, String, Object, Date, long, long, boolean)
*/
// NPCTE fix for bugId 4464388, esc 0, MR , to be added after modification of jmx spec
// public synchronized Integer addNotification(String type, String message, Serializable userData,
// Date date, long period)
// end of NPCTE fix for bugId 4464388 */
public Integer addNotification(String type, String message, Object userData,
Date date, long period, long nbOccurences)
throws java.lang.IllegalArgumentException;
/** {@collect.stats}
* Creates a new timer notification with the specified <CODE>type</CODE>, <CODE>message</CODE>
* and <CODE>userData</CODE> and inserts it into the list of notifications with a given date
* and period and a null number of occurrences.
* <P>
* The timer notification will repeat continuously using the timer period using a <i>fixed-delay</i>
* execution scheme, as specified in {@link java.util.Timer}. In order to use a <i>fixed-rate</i>
* execution scheme, use {@link #addNotification(String, String, Object, Date, long, long,
* boolean)} instead.
* <P>
* If the timer notification to be inserted has a date that is before the current date,
* the method behaves as if the specified date were the current date. The
* first notification is delivered immediately and the subsequent ones are
* spaced as specified by the period parameter.
*
* @param type The timer notification type.
* @param message The timer notification detailed message.
* @param userData The timer notification user data object.
* @param date The date when the notification occurs.
* @param period The period of the timer notification (in milliseconds).
*
* @return The identifier of the new created timer notification.
*
* @exception java.lang.IllegalArgumentException The date is {@code null} or
* the period is negative.
*/
// NPCTE fix for bugId 4464388, esc 0, MR , to be added after modification of jmx spec
// public synchronized Integer addNotification(String type, String message, Serializable userData,
// Date date, long period)
// end of NPCTE fix for bugId 4464388 */
public Integer addNotification(String type, String message, Object userData,
Date date, long period)
throws java.lang.IllegalArgumentException;
/** {@collect.stats}
* Creates a new timer notification with the specified <CODE>type</CODE>, <CODE>message</CODE>
* and <CODE>userData</CODE> and inserts it into the list of notifications with a given date
* and a null period and number of occurrences.
* <P>
* The timer notification will be handled once at the specified date.
* <P>
* If the timer notification to be inserted has a date that is before the current date,
* the method behaves as if the specified date were the current date and the
* notification is delivered immediately.
*
* @param type The timer notification type.
* @param message The timer notification detailed message.
* @param userData The timer notification user data object.
* @param date The date when the notification occurs.
*
* @return The identifier of the new created timer notification.
*
* @exception java.lang.IllegalArgumentException The date is {@code null}.
*/
// NPCTE fix for bugId 4464388, esc 0, MR, to be added after modification of jmx spec
// public synchronized Integer addNotification(String type, String message, Serializable userData, Date date)
// throws java.lang.IllegalArgumentException {
// end of NPCTE fix for bugId 4464388
public Integer addNotification(String type, String message, Object userData, Date date)
throws java.lang.IllegalArgumentException;
/** {@collect.stats}
* Removes the timer notification corresponding to the specified identifier from the list of notifications.
*
* @param id The timer notification identifier.
*
* @exception InstanceNotFoundException The specified identifier does not correspond to any timer notification
* in the list of notifications of this timer MBean.
*/
public void removeNotification(Integer id) throws InstanceNotFoundException;
/** {@collect.stats}
* Removes all the timer notifications corresponding to the specified type from the list of notifications.
*
* @param type The timer notification type.
*
* @exception InstanceNotFoundException The specified type does not correspond to any timer notification
* in the list of notifications of this timer MBean.
*/
public void removeNotifications(String type) throws InstanceNotFoundException;
/** {@collect.stats}
* Removes all the timer notifications from the list of notifications
* and resets the counter used to update the timer notification identifiers.
*/
public void removeAllNotifications();
// GETTERS AND SETTERS
//--------------------
/** {@collect.stats}
* Gets the number of timer notifications registered into the list of notifications.
*
* @return The number of timer notifications.
*/
public int getNbNotifications();
/** {@collect.stats}
* Gets all timer notification identifiers registered into the list of notifications.
*
* @return A vector of <CODE>Integer</CODE> objects containing all the timer notification identifiers.
* <BR>The vector is empty if there is no timer notification registered for this timer MBean.
*/
public Vector<Integer> getAllNotificationIDs();
/** {@collect.stats}
* Gets all the identifiers of timer notifications corresponding to the specified type.
*
* @param type The timer notification type.
*
* @return A vector of <CODE>Integer</CODE> objects containing all the identifiers of
* timer notifications with the specified <CODE>type</CODE>.
* <BR>The vector is empty if there is no timer notifications registered for this timer MBean
* with the specified <CODE>type</CODE>.
*/
public Vector<Integer> getNotificationIDs(String type);
/** {@collect.stats}
* Gets the timer notification type corresponding to the specified identifier.
*
* @param id The timer notification identifier.
*
* @return The timer notification type or null if the identifier is not mapped to any
* timer notification registered for this timer MBean.
*/
public String getNotificationType(Integer id);
/** {@collect.stats}
* Gets the timer notification detailed message corresponding to the specified identifier.
*
* @param id The timer notification identifier.
*
* @return The timer notification detailed message or null if the identifier is not mapped to any
* timer notification registered for this timer MBean.
*/
public String getNotificationMessage(Integer id);
/** {@collect.stats}
* Gets the timer notification user data object corresponding to the specified identifier.
*
* @param id The timer notification identifier.
*
* @return The timer notification user data object or null if the identifier is not mapped to any
* timer notification registered for this timer MBean.
*/
// NPCTE fix for bugId 4464388, esc 0 , MR , 03 sept 2001 , to be added after modification of jmx spec
//public Serializable getNotificationUserData(Integer id);
// end of NPCTE fix for bugId 4464388
public Object getNotificationUserData(Integer id);
/** {@collect.stats}
* Gets a copy of the date associated to a timer notification.
*
* @param id The timer notification identifier.
*
* @return A copy of the date or null if the identifier is not mapped to any
* timer notification registered for this timer MBean.
*/
public Date getDate(Integer id);
/** {@collect.stats}
* Gets a copy of the period (in milliseconds) associated to a timer notification.
*
* @param id The timer notification identifier.
*
* @return A copy of the period or null if the identifier is not mapped to any
* timer notification registered for this timer MBean.
*/
public Long getPeriod(Integer id);
/** {@collect.stats}
* Gets a copy of the remaining number of occurrences associated to a timer notification.
*
* @param id The timer notification identifier.
*
* @return A copy of the remaining number of occurrences or null if the identifier is not mapped to any
* timer notification registered for this timer MBean.
*/
public Long getNbOccurences(Integer id);
/** {@collect.stats}
* Gets a copy of the flag indicating whether a periodic notification is
* executed at <i>fixed-delay</i> or at <i>fixed-rate</i>.
*
* @param id The timer notification identifier.
*
* @return A copy of the flag indicating whether a periodic notification is
* executed at <i>fixed-delay</i> or at <i>fixed-rate</i>.
*/
public Boolean getFixedRate(Integer id);
/** {@collect.stats}
* Gets the flag indicating whether or not the timer sends past notifications.
*
* @return The past notifications sending on/off flag value.
*
* @see #setSendPastNotifications
*/
public boolean getSendPastNotifications();
/** {@collect.stats}
* Sets the flag indicating whether the timer sends past notifications or not.
*
* @param value The past notifications sending on/off flag value.
*
* @see #getSendPastNotifications
*/
public void setSendPastNotifications(boolean value);
/** {@collect.stats}
* Tests whether the timer MBean is active.
* A timer MBean is marked active when the {@link #start start} method is called.
* It becomes inactive when the {@link #stop stop} method is called.
*
* @return <CODE>true</CODE> if the timer MBean is active, <CODE>false</CODE> otherwise.
*/
public boolean isActive();
/** {@collect.stats}
* Tests whether the list of timer notifications is empty.
*
* @return <CODE>true</CODE> if the list of timer notifications is empty, <CODE>false</CODE> otherwise.
*/
public boolean isEmpty();
}
| Java |
/*
* Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management.timer;
/** {@collect.stats}
* This class provides definitions of the notifications sent by timer MBeans.
* <BR>It defines a timer notification identifier which allows to retrieve a timer notification
* from the list of notifications of a timer MBean.
* <P>
* The timer notifications are created and handled by the timer MBean.
*
* @since 1.5
*/
public class TimerNotification extends javax.management.Notification {
/* Serial version */
private static final long serialVersionUID = 1798492029603825750L;
/*
* ------------------------------------------
* PRIVATE VARIABLES
* ------------------------------------------
*/
/** {@collect.stats}
* @serial Timer notification identifier.
* This identifier is used to retrieve a timer notification from the timer list of notifications.
*/
private Integer notificationID;
/*
* ------------------------------------------
* CONSTRUCTORS
* ------------------------------------------
*/
/** {@collect.stats}
* Creates a timer notification object.
*
* @param type The notification type.
* @param source The notification producer.
* @param sequenceNumber The notification sequence number within the source object.
* @param timeStamp The notification emission date.
* @param msg The notification message.
* @param id The notification identifier.
*
*/
public TimerNotification(String type, Object source, long sequenceNumber, long timeStamp, String msg, Integer id) {
super(type, source, sequenceNumber, timeStamp, msg);
this.notificationID = id;
}
/*
* ------------------------------------------
* PUBLIC METHODS
* ------------------------------------------
*/
// GETTERS AND SETTERS
//--------------------
/** {@collect.stats}
* Gets the identifier of this timer notification.
*
* @return The identifier.
*/
public Integer getNotificationID() {
return notificationID;
}
/*
* ------------------------------------------
* PACKAGE METHODS
* ------------------------------------------
*/
/** {@collect.stats}
* Creates and returns a copy of this object.
*
*/
Object cloneTimerNotification() {
TimerNotification clone = new TimerNotification(this.getType(), this.getSource(), this.getSequenceNumber(),
this.getTimeStamp(), this.getMessage(), notificationID);
clone.setUserData(this.getUserData());
return clone;
}
}
| Java |
/*
* Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management.timer;
import static com.sun.jmx.defaults.JmxProperties.TIMER_LOGGER;
import java.util.Date;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.Vector;
import java.util.logging.Level;
// jmx imports
//
import javax.management.InstanceNotFoundException;
import javax.management.MBeanNotificationInfo;
import javax.management.MBeanRegistration;
import javax.management.MBeanServer;
import javax.management.NotificationBroadcasterSupport;
import javax.management.ObjectName;
/** {@collect.stats}
*
* Provides the implementation of the timer MBean.
* The timer MBean sends out an alarm at a specified time
* that wakes up all the listeners registered to receive timer notifications.
* <P>
*
* This class manages a list of dated timer notifications.
* A method allows users to add/remove as many notifications as required.
* When a timer notification is emitted by the timer and becomes obsolete,
* it is automatically removed from the list of timer notifications.
* <BR>Additional timer notifications can be added into regularly repeating notifications.
* <P>
*
* Note:
* <OL>
* <LI>When sending timer notifications, the timer updates the notification sequence number
* irrespective of the notification type.
* <LI>The timer service relies on the system date of the host where the <CODE>Timer</CODE> class is loaded.
* Listeners may receive untimely notifications
* if their host has a different system date.
* To avoid such problems, synchronize the system date of all host machines where timing is needed.
* <LI>The default behavior for periodic notifications is <i>fixed-delay execution</i>, as
* specified in {@link java.util.Timer}. In order to use <i>fixed-rate execution</i>, use the
* overloaded {@link #addNotification(String, String, Object, Date, long, long, boolean)} method.
* <LI>Notification listeners are potentially all executed in the same
* thread. Therefore, they should execute rapidly to avoid holding up
* other listeners or perturbing the regularity of fixed-delay
* executions. See {@link NotificationBroadcasterSupport}.
* </OL>
*
* @since 1.5
*/
public class Timer extends NotificationBroadcasterSupport
implements TimerMBean, MBeanRegistration {
/*
* ------------------------------------------
* PUBLIC VARIABLES
* ------------------------------------------
*/
/** {@collect.stats}
* Number of milliseconds in one second.
* Useful constant for the <CODE>addNotification</CODE> method.
*/
public static final long ONE_SECOND = 1000;
/** {@collect.stats}
* Number of milliseconds in one minute.
* Useful constant for the <CODE>addNotification</CODE> method.
*/
public static final long ONE_MINUTE = 60*ONE_SECOND;
/** {@collect.stats}
* Number of milliseconds in one hour.
* Useful constant for the <CODE>addNotification</CODE> method.
*/
public static final long ONE_HOUR = 60*ONE_MINUTE;
/** {@collect.stats}
* Number of milliseconds in one day.
* Useful constant for the <CODE>addNotification</CODE> method.
*/
public static final long ONE_DAY = 24*ONE_HOUR;
/** {@collect.stats}
* Number of milliseconds in one week.
* Useful constant for the <CODE>addNotification</CODE> method.
*/
public static final long ONE_WEEK = 7*ONE_DAY;
/*
* ------------------------------------------
* PRIVATE VARIABLES
* ------------------------------------------
*/
/** {@collect.stats}
* Table containing all the timer notifications of this timer,
* with the associated date, period and number of occurrences.
*/
private Map<Integer,Object[]> timerTable =
new Hashtable<Integer,Object[]>();
/** {@collect.stats}
* Past notifications sending on/off flag value.
* This attribute is used to specify if the timer has to send past notifications after start.
* <BR>The default value is set to <CODE>false</CODE>.
*/
private boolean sendPastNotifications = false;
/** {@collect.stats}
* Timer state.
* The default value is set to <CODE>false</CODE>.
*/
private transient boolean isActive = false;
/** {@collect.stats}
* Timer sequence number.
* The default value is set to 0.
*/
private transient long sequenceNumber = 0;
// Flags needed to keep the indexes of the objects in the array.
//
private static final int TIMER_NOTIF_INDEX = 0;
private static final int TIMER_DATE_INDEX = 1;
private static final int TIMER_PERIOD_INDEX = 2;
private static final int TIMER_NB_OCCUR_INDEX = 3;
private static final int ALARM_CLOCK_INDEX = 4;
private static final int FIXED_RATE_INDEX = 5;
/** {@collect.stats}
* The notification counter ID.
* Used to keep the max key value inserted into the timer table.
*/
private int counterID = 0;
private java.util.Timer timer;
/*
* ------------------------------------------
* CONSTRUCTORS
* ------------------------------------------
*/
/** {@collect.stats}
* Default constructor.
*/
public Timer() {
}
/*
* ------------------------------------------
* PUBLIC METHODS
* ------------------------------------------
*/
/** {@collect.stats}
* Allows the timer MBean to perform any operations it needs before being registered
* in the MBean server.
* <P>
* Not used in this context.
*
* @param server The MBean server in which the timer MBean will be registered.
* @param name The object name of the timer MBean.
*
* @return The name of the timer MBean registered.
*
* @exception java.lang.Exception
*/
public ObjectName preRegister(MBeanServer server, ObjectName name)
throws java.lang.Exception {
return name;
}
/** {@collect.stats}
* Allows the timer MBean to perform any operations needed after having been
* registered in the MBean server or after the registration has failed.
* <P>
* Not used in this context.
*/
public void postRegister (Boolean registrationDone) {
}
/** {@collect.stats}
* Allows the timer MBean to perform any operations it needs before being unregistered
* by the MBean server.
* <P>
* Stops the timer.
*
* @exception java.lang.Exception
*/
public void preDeregister() throws java.lang.Exception {
TIMER_LOGGER.logp(Level.FINER, Timer.class.getName(),
"preDeregister", "stop the timer");
// Stop the timer.
//
stop();
}
/** {@collect.stats}
* Allows the timer MBean to perform any operations needed after having been
* unregistered by the MBean server.
* <P>
* Not used in this context.
*/
public void postDeregister() {
}
/*
* This overrides the method in NotificationBroadcasterSupport.
* Return the MBeanNotificationInfo[] array for this MBean.
* The returned array has one element to indicate that the MBean
* can emit TimerNotification. The array of type strings
* associated with this entry is a snapshot of the current types
* that were given to addNotification.
*/
public synchronized MBeanNotificationInfo[] getNotificationInfo() {
Set<String> notifTypes = new TreeSet<String>();
for (Iterator it = timerTable.values().iterator(); it.hasNext(); ) {
Object[] entry = (Object[]) it.next();
TimerNotification notif = (TimerNotification)
entry[TIMER_NOTIF_INDEX];
notifTypes.add(notif.getType());
}
String[] notifTypesArray =
notifTypes.toArray(new String[0]);
return new MBeanNotificationInfo[] {
new MBeanNotificationInfo(notifTypesArray,
TimerNotification.class.getName(),
"Notification sent by Timer MBean")
};
}
/** {@collect.stats}
* Starts the timer.
* <P>
* If there is one or more timer notifications before the time in the list of notifications, the notification
* is sent according to the <CODE>sendPastNotifications</CODE> flag and then, updated
* according to its period and remaining number of occurrences.
* If the timer notification date remains earlier than the current date, this notification is just removed
* from the list of notifications.
*/
public synchronized void start() {
TIMER_LOGGER.logp(Level.FINER, Timer.class.getName(),
"start", "starting the timer");
// Start the TimerAlarmClock.
//
if (isActive == false) {
timer = new java.util.Timer();
TimerAlarmClock alarmClock;
Date date;
Date currentDate = new Date();
// Send or not past notifications depending on the flag.
// Update the date and the number of occurrences of past notifications
// to make them later than the current date.
//
sendPastNotifications(currentDate, sendPastNotifications);
// Update and start all the TimerAlarmClocks.
// Here, all the notifications in the timer table are later than the current date.
//
for (Object[] obj : timerTable.values()) {
// Retrieve the date notification and the TimerAlarmClock.
//
date = (Date)obj[TIMER_DATE_INDEX];
// Update all the TimerAlarmClock timeouts and start them.
//
boolean fixedRate = ((Boolean)obj[FIXED_RATE_INDEX]).booleanValue();
if (fixedRate)
{
alarmClock = new TimerAlarmClock(this, date);
obj[ALARM_CLOCK_INDEX] = (Object)alarmClock;
timer.schedule(alarmClock, alarmClock.next);
}
else
{
alarmClock = new TimerAlarmClock(this, (date.getTime() - currentDate.getTime()));
obj[ALARM_CLOCK_INDEX] = (Object)alarmClock;
timer.schedule(alarmClock, alarmClock.timeout);
}
}
// Set the state to ON.
//
isActive = true;
TIMER_LOGGER.logp(Level.FINER, Timer.class.getName(),
"start", "timer started");
} else {
TIMER_LOGGER.logp(Level.FINER, Timer.class.getName(),
"start", "the timer is already activated");
}
}
/** {@collect.stats}
* Stops the timer.
*/
public synchronized void stop() {
TIMER_LOGGER.logp(Level.FINER, Timer.class.getName(),
"stop", "stopping the timer");
// Stop the TimerAlarmClock.
//
if (isActive == true) {
TimerAlarmClock alarmClock;
for (Object[] obj : timerTable.values()) {
// Stop all the TimerAlarmClock.
//
alarmClock = (TimerAlarmClock)obj[ALARM_CLOCK_INDEX];
if (alarmClock != null) {
// alarmClock.interrupt();
// try {
// // Wait until the thread die.
// //
// alarmClock.join();
// } catch (InterruptedException ex) {
// // Ignore...
// }
// // Remove the reference on the TimerAlarmClock.
// //
alarmClock.cancel();
alarmClock = null;
}
}
timer.cancel();
// Set the state to OFF.
//
isActive = false;
TIMER_LOGGER.logp(Level.FINER, Timer.class.getName(),
"stop", "timer stopped");
} else {
TIMER_LOGGER.logp(Level.FINER, Timer.class.getName(),
"stop", "the timer is already deactivated");
}
}
/** {@collect.stats}
* Creates a new timer notification with the specified <CODE>type</CODE>, <CODE>message</CODE>
* and <CODE>userData</CODE> and inserts it into the list of notifications with a given date,
* period and number of occurrences.
* <P>
* If the timer notification to be inserted has a date that is before the current date,
* the method behaves as if the specified date were the current date. <BR>
* For once-off notifications, the notification is delivered immediately. <BR>
* For periodic notifications, the first notification is delivered immediately and the
* subsequent ones are spaced as specified by the period parameter.
* <P>
* Note that once the timer notification has been added into the list of notifications,
* its associated date, period and number of occurrences cannot be updated.
* <P>
* In the case of a periodic notification, the value of parameter <i>fixedRate</i> is used to
* specify the execution scheme, as specified in {@link java.util.Timer}.
*
* @param type The timer notification type.
* @param message The timer notification detailed message.
* @param userData The timer notification user data object.
* @param date The date when the notification occurs.
* @param period The period of the timer notification (in milliseconds).
* @param nbOccurences The total number the timer notification will be emitted.
* @param fixedRate If <code>true</code> and if the notification is periodic, the notification
* is scheduled with a <i>fixed-rate</i> execution scheme. If
* <code>false</code> and if the notification is periodic, the notification
* is scheduled with a <i>fixed-delay</i> execution scheme. Ignored if the
* notification is not periodic.
*
* @return The identifier of the new created timer notification.
*
* @exception java.lang.IllegalArgumentException The date is {@code null} or
* the period or the number of occurrences is negative.
*
* @see #addNotification(String, String, Object, Date, long, long)
*/
// NPCTE fix for bugId 4464388, esc 0, MR, to be added after modification of jmx spec
// public synchronized Integer addNotification(String type, String message, Serializable userData,
// Date date, long period, long nbOccurences)
// end of NPCTE fix for bugId 4464388
public synchronized Integer addNotification(String type, String message, Object userData,
Date date, long period, long nbOccurences, boolean fixedRate)
throws java.lang.IllegalArgumentException {
if (date == null) {
throw new java.lang.IllegalArgumentException("Timer notification date cannot be null.");
}
// Check that all the timer notification attributes are valid.
//
// Invalid timer period value exception:
// Check that the period and the nbOccurences are POSITIVE VALUES.
//
if ((period < 0) || (nbOccurences < 0)) {
throw new java.lang.IllegalArgumentException("Negative values for the periodicity");
}
Date currentDate = new Date();
// Update the date if it is before the current date.
//
if (currentDate.after(date)) {
date.setTime(currentDate.getTime());
if (TIMER_LOGGER.isLoggable(Level.FINER)) {
TIMER_LOGGER.logp(Level.FINER, Timer.class.getName(),
"addNotification",
"update timer notification to add with:" +
"\n\tNotification date = " + date);
}
}
// Create and add the timer notification into the timer table.
//
Integer notifID = null;
notifID = new Integer(++counterID);
// The sequenceNumber and the timeStamp attributes are updated
// when the notification is emitted by the timer.
//
TimerNotification notif = new TimerNotification(type, this, 0, 0, message, notifID);
notif.setUserData(userData);
Object[] obj = new Object[6];
TimerAlarmClock alarmClock;
if (fixedRate)
{
alarmClock = new TimerAlarmClock(this, date);
}
else
{
alarmClock = new TimerAlarmClock(this, (date.getTime() - currentDate.getTime()));
}
// Fix bug 00417.B
// The date registered into the timer is a clone from the date parameter.
//
Date d = new Date(date.getTime());
obj[TIMER_NOTIF_INDEX] = (Object)notif;
obj[TIMER_DATE_INDEX] = (Object)d;
obj[TIMER_PERIOD_INDEX] = (Object) new Long(period);
obj[TIMER_NB_OCCUR_INDEX] = (Object) new Long(nbOccurences);
obj[ALARM_CLOCK_INDEX] = (Object)alarmClock;
obj[FIXED_RATE_INDEX] = Boolean.valueOf(fixedRate);
if (TIMER_LOGGER.isLoggable(Level.FINER)) {
StringBuilder strb = new StringBuilder()
.append("adding timer notification:\n\t")
.append("Notification source = ")
.append(notif.getSource())
.append("\n\tNotification type = ")
.append(notif.getType())
.append("\n\tNotification ID = ")
.append(notifID)
.append("\n\tNotification date = ")
.append(d)
.append("\n\tNotification period = ")
.append(period)
.append("\n\tNotification nb of occurrences = ")
.append(nbOccurences)
.append("\n\tNotification executes at fixed rate = ")
.append(fixedRate);
TIMER_LOGGER.logp(Level.FINER, Timer.class.getName(),
"addNotification", strb.toString());
}
timerTable.put(notifID, obj);
// Update and start the TimerAlarmClock.
//
if (isActive == true) {
if (fixedRate)
{
timer.schedule(alarmClock, alarmClock.next);
}
else
{
timer.schedule(alarmClock, alarmClock.timeout);
}
}
TIMER_LOGGER.logp(Level.FINER, Timer.class.getName(),
"addNotification", "timer notification added");
return notifID;
}
/** {@collect.stats}
* Creates a new timer notification with the specified <CODE>type</CODE>, <CODE>message</CODE>
* and <CODE>userData</CODE> and inserts it into the list of notifications with a given date,
* period and number of occurrences.
* <P>
* If the timer notification to be inserted has a date that is before the current date,
* the method behaves as if the specified date were the current date. <BR>
* For once-off notifications, the notification is delivered immediately. <BR>
* For periodic notifications, the first notification is delivered immediately and the
* subsequent ones are spaced as specified by the period parameter.
* <P>
* Note that once the timer notification has been added into the list of notifications,
* its associated date, period and number of occurrences cannot be updated.
* <P>
* In the case of a periodic notification, uses a <i>fixed-delay</i> execution scheme, as specified in
* {@link java.util.Timer}. In order to use a <i>fixed-rate</i> execution scheme, use
* {@link #addNotification(String, String, Object, Date, long, long, boolean)} instead.
*
* @param type The timer notification type.
* @param message The timer notification detailed message.
* @param userData The timer notification user data object.
* @param date The date when the notification occurs.
* @param period The period of the timer notification (in milliseconds).
* @param nbOccurences The total number the timer notification will be emitted.
*
* @return The identifier of the new created timer notification.
*
* @exception java.lang.IllegalArgumentException The date is {@code null} or
* the period or the number of occurrences is negative.
*
* @see #addNotification(String, String, Object, Date, long, long, boolean)
*/
// NPCTE fix for bugId 4464388, esc 0, MR , to be added after modification of jmx spec
// public synchronized Integer addNotification(String type, String message, Serializable userData,
// Date date, long period)
// end of NPCTE fix for bugId 4464388 */
public synchronized Integer addNotification(String type, String message, Object userData,
Date date, long period, long nbOccurences)
throws java.lang.IllegalArgumentException {
return addNotification(type, message, userData, date, period, nbOccurences, false);
}
/** {@collect.stats}
* Creates a new timer notification with the specified <CODE>type</CODE>, <CODE>message</CODE>
* and <CODE>userData</CODE> and inserts it into the list of notifications with a given date
* and period and a null number of occurrences.
* <P>
* The timer notification will repeat continuously using the timer period using a <i>fixed-delay</i>
* execution scheme, as specified in {@link java.util.Timer}. In order to use a <i>fixed-rate</i>
* execution scheme, use {@link #addNotification(String, String, Object, Date, long, long,
* boolean)} instead.
* <P>
* If the timer notification to be inserted has a date that is before the current date,
* the method behaves as if the specified date were the current date. The
* first notification is delivered immediately and the subsequent ones are
* spaced as specified by the period parameter.
*
* @param type The timer notification type.
* @param message The timer notification detailed message.
* @param userData The timer notification user data object.
* @param date The date when the notification occurs.
* @param period The period of the timer notification (in milliseconds).
*
* @return The identifier of the new created timer notification.
*
* @exception java.lang.IllegalArgumentException The date is {@code null} or
* the period is negative.
*/
// NPCTE fix for bugId 4464388, esc 0, MR , to be added after modification of jmx spec
// public synchronized Integer addNotification(String type, String message, Serializable userData,
// Date date, long period)
// end of NPCTE fix for bugId 4464388 */
public synchronized Integer addNotification(String type, String message, Object userData,
Date date, long period)
throws java.lang.IllegalArgumentException {
return (addNotification(type, message, userData, date, period, 0));
}
/** {@collect.stats}
* Creates a new timer notification with the specified <CODE>type</CODE>, <CODE>message</CODE>
* and <CODE>userData</CODE> and inserts it into the list of notifications with a given date
* and a null period and number of occurrences.
* <P>
* The timer notification will be handled once at the specified date.
* <P>
* If the timer notification to be inserted has a date that is before the current date,
* the method behaves as if the specified date were the current date and the
* notification is delivered immediately.
*
* @param type The timer notification type.
* @param message The timer notification detailed message.
* @param userData The timer notification user data object.
* @param date The date when the notification occurs.
*
* @return The identifier of the new created timer notification.
*
* @exception java.lang.IllegalArgumentException The date is {@code null}.
*/
// NPCTE fix for bugId 4464388, esc 0, MR, to be added after modification of jmx spec
// public synchronized Integer addNotification(String type, String message, Serializable userData, Date date)
// throws java.lang.IllegalArgumentException {
// end of NPCTE fix for bugId 4464388
public synchronized Integer addNotification(String type, String message, Object userData, Date date)
throws java.lang.IllegalArgumentException {
return (addNotification(type, message, userData, date, 0, 0));
}
/** {@collect.stats}
* Removes the timer notification corresponding to the specified identifier from the list of notifications.
*
* @param id The timer notification identifier.
*
* @exception InstanceNotFoundException The specified identifier does not correspond to any timer notification
* in the list of notifications of this timer MBean.
*/
public synchronized void removeNotification(Integer id) throws InstanceNotFoundException {
// Check that the notification to remove is effectively in the timer table.
//
if (timerTable.containsKey(id) == false) {
throw new InstanceNotFoundException("Timer notification to remove not in the list of notifications");
}
// Stop the TimerAlarmClock.
//
Object[] obj = timerTable.get(id);
TimerAlarmClock alarmClock = (TimerAlarmClock)obj[ALARM_CLOCK_INDEX];
if (alarmClock != null) {
// alarmClock.interrupt();
// try {
// // Wait until the thread die.
// //
// alarmClock.join();
// } catch (InterruptedException e) {
// // Ignore...
// }
// // Remove the reference on the TimerAlarmClock.
// //
alarmClock.cancel();
alarmClock = null;
}
// Remove the timer notification from the timer table.
//
if (TIMER_LOGGER.isLoggable(Level.FINER)) {
StringBuilder strb = new StringBuilder()
.append("removing timer notification:")
.append("\n\tNotification source = ")
.append(((TimerNotification)obj[TIMER_NOTIF_INDEX]).getSource())
.append("\n\tNotification type = ")
.append(((TimerNotification)obj[TIMER_NOTIF_INDEX]).getType())
.append("\n\tNotification ID = ")
.append(((TimerNotification)obj[TIMER_NOTIF_INDEX]).getNotificationID())
.append("\n\tNotification date = ")
.append(obj[TIMER_DATE_INDEX])
.append("\n\tNotification period = ")
.append(obj[TIMER_PERIOD_INDEX])
.append("\n\tNotification nb of occurrences = ")
.append(obj[TIMER_NB_OCCUR_INDEX])
.append("\n\tNotification executes at fixed rate = ")
.append(obj[FIXED_RATE_INDEX]);
TIMER_LOGGER.logp(Level.FINER, Timer.class.getName(),
"removeNotification", strb.toString());
}
timerTable.remove(id);
TIMER_LOGGER.logp(Level.FINER, Timer.class.getName(),
"removeNotification", "timer notification removed");
}
/** {@collect.stats}
* Removes all the timer notifications corresponding to the specified type from the list of notifications.
*
* @param type The timer notification type.
*
* @exception InstanceNotFoundException The specified type does not correspond to any timer notification
* in the list of notifications of this timer MBean.
*/
public synchronized void removeNotifications(String type) throws InstanceNotFoundException {
Vector<Integer> v = getNotificationIDs(type);
if (v.isEmpty())
throw new InstanceNotFoundException("Timer notifications to remove not in the list of notifications");
for (Integer i : v)
removeNotification(i);
}
/** {@collect.stats}
* Removes all the timer notifications from the list of notifications
* and resets the counter used to update the timer notification identifiers.
*/
public synchronized void removeAllNotifications() {
TimerAlarmClock alarmClock;
for (Object[] obj : timerTable.values()) {
// Stop the TimerAlarmClock.
//
alarmClock = (TimerAlarmClock)obj[ALARM_CLOCK_INDEX];
// if (alarmClock != null) {
// alarmClock.interrupt();
// try {
// // Wait until the thread die.
// //
// alarmClock.join();
// } catch (InterruptedException ex) {
// // Ignore...
// }
// Remove the reference on the TimerAlarmClock.
//
// }
alarmClock.cancel();
alarmClock = null;
}
// Remove all the timer notifications from the timer table.
TIMER_LOGGER.logp(Level.FINER, Timer.class.getName(),
"removeAllNotifications", "removing all timer notifications");
timerTable.clear();
TIMER_LOGGER.logp(Level.FINER, Timer.class.getName(),
"removeAllNotifications", "all timer notifications removed");
// Reset the counterID.
//
counterID = 0;
TIMER_LOGGER.logp(Level.FINER, Timer.class.getName(),
"removeAllNotifications", "timer notification counter ID reset");
}
// GETTERS AND SETTERS
//--------------------
/** {@collect.stats}
* Gets the number of timer notifications registered into the list of notifications.
*
* @return The number of timer notifications.
*/
public int getNbNotifications() {
return timerTable.size();
}
/** {@collect.stats}
* Gets all timer notification identifiers registered into the list of notifications.
*
* @return A vector of <CODE>Integer</CODE> objects containing all the timer notification identifiers.
* <BR>The vector is empty if there is no timer notification registered for this timer MBean.
*/
public synchronized Vector<Integer> getAllNotificationIDs() {
return new Vector<Integer>(timerTable.keySet());
}
/** {@collect.stats}
* Gets all the identifiers of timer notifications corresponding to the specified type.
*
* @param type The timer notification type.
*
* @return A vector of <CODE>Integer</CODE> objects containing all the identifiers of
* timer notifications with the specified <CODE>type</CODE>.
* <BR>The vector is empty if there is no timer notifications registered for this timer MBean
* with the specified <CODE>type</CODE>.
*/
public synchronized Vector<Integer> getNotificationIDs(String type) {
String s;
Vector<Integer> v = new Vector<Integer>();
for (Map.Entry<Integer,Object[]> entry : timerTable.entrySet()) {
Object[] obj = entry.getValue();
s = ((TimerNotification)obj[TIMER_NOTIF_INDEX]).getType();
if ((type == null) ? s == null : type.equals(s))
v.addElement(entry.getKey());
}
return v;
}
// 5089997: return is Vector<Integer> not Vector<TimerNotification>
/** {@collect.stats}
* Gets the timer notification type corresponding to the specified identifier.
*
* @param id The timer notification identifier.
*
* @return The timer notification type or null if the identifier is not mapped to any
* timer notification registered for this timer MBean.
*/
public String getNotificationType(Integer id) {
Object[] obj = timerTable.get(id);
if (obj != null) {
return ( ((TimerNotification)obj[TIMER_NOTIF_INDEX]).getType() );
}
return null;
}
/** {@collect.stats}
* Gets the timer notification detailed message corresponding to the specified identifier.
*
* @param id The timer notification identifier.
*
* @return The timer notification detailed message or null if the identifier is not mapped to any
* timer notification registered for this timer MBean.
*/
public String getNotificationMessage(Integer id) {
Object[] obj = timerTable.get(id);
if (obj != null) {
return ( ((TimerNotification)obj[TIMER_NOTIF_INDEX]).getMessage() );
}
return null;
}
/** {@collect.stats}
* Gets the timer notification user data object corresponding to the specified identifier.
*
* @param id The timer notification identifier.
*
* @return The timer notification user data object or null if the identifier is not mapped to any
* timer notification registered for this timer MBean.
*/
// NPCTE fix for bugId 4464388, esc 0, MR, 03 sept 2001, to be added after modification of jmx spec
//public Serializable getNotificationUserData(Integer id) {
// end of NPCTE fix for bugId 4464388
public Object getNotificationUserData(Integer id) {
Object[] obj = timerTable.get(id);
if (obj != null) {
return ( ((TimerNotification)obj[TIMER_NOTIF_INDEX]).getUserData() );
}
return null;
}
/** {@collect.stats}
* Gets a copy of the date associated to a timer notification.
*
* @param id The timer notification identifier.
*
* @return A copy of the date or null if the identifier is not mapped to any
* timer notification registered for this timer MBean.
*/
public Date getDate(Integer id) {
Object[] obj = timerTable.get(id);
if (obj != null) {
Date date = (Date)obj[TIMER_DATE_INDEX];
return (new Date(date.getTime()));
}
return null;
}
/** {@collect.stats}
* Gets a copy of the period (in milliseconds) associated to a timer notification.
*
* @param id The timer notification identifier.
*
* @return A copy of the period or null if the identifier is not mapped to any
* timer notification registered for this timer MBean.
*/
public Long getPeriod(Integer id) {
Object[] obj = timerTable.get(id);
if (obj != null) {
Long period = (Long)obj[TIMER_PERIOD_INDEX];
return (new Long(period.longValue()));
}
return null;
}
/** {@collect.stats}
* Gets a copy of the remaining number of occurrences associated to a timer notification.
*
* @param id The timer notification identifier.
*
* @return A copy of the remaining number of occurrences or null if the identifier is not mapped to any
* timer notification registered for this timer MBean.
*/
public Long getNbOccurences(Integer id) {
Object[] obj = timerTable.get(id);
if (obj != null) {
Long nbOccurences = (Long)obj[TIMER_NB_OCCUR_INDEX];
return (new Long(nbOccurences.longValue()));
}
return null;
}
/** {@collect.stats}
* Gets a copy of the flag indicating whether a periodic notification is
* executed at <i>fixed-delay</i> or at <i>fixed-rate</i>.
*
* @param id The timer notification identifier.
*
* @return A copy of the flag indicating whether a periodic notification is
* executed at <i>fixed-delay</i> or at <i>fixed-rate</i>.
*/
public Boolean getFixedRate(Integer id) {
Object[] obj = timerTable.get(id);
if (obj != null) {
Boolean fixedRate = (Boolean)obj[FIXED_RATE_INDEX];
return (Boolean.valueOf(fixedRate.booleanValue()));
}
return null;
}
/** {@collect.stats}
* Gets the flag indicating whether or not the timer sends past notifications.
* <BR>The default value of the past notifications sending on/off flag is <CODE>false</CODE>.
*
* @return The past notifications sending on/off flag value.
*
* @see #setSendPastNotifications
*/
public boolean getSendPastNotifications() {
return sendPastNotifications;
}
/** {@collect.stats}
* Sets the flag indicating whether the timer sends past notifications or not.
* <BR>The default value of the past notifications sending on/off flag is <CODE>false</CODE>.
*
* @param value The past notifications sending on/off flag value.
*
* @see #getSendPastNotifications
*/
public void setSendPastNotifications(boolean value) {
sendPastNotifications = value;
}
/** {@collect.stats}
* Tests whether the timer MBean is active.
* A timer MBean is marked active when the {@link #start start} method is called.
* It becomes inactive when the {@link #stop stop} method is called.
* <BR>The default value of the active on/off flag is <CODE>false</CODE>.
*
* @return <CODE>true</CODE> if the timer MBean is active, <CODE>false</CODE> otherwise.
*/
public boolean isActive() {
return isActive;
}
/** {@collect.stats}
* Tests whether the list of timer notifications is empty.
*
* @return <CODE>true</CODE> if the list of timer notifications is empty, <CODE>false</CODE> otherwise.
*/
public boolean isEmpty() {
return (timerTable.isEmpty());
}
/*
* ------------------------------------------
* PRIVATE METHODS
* ------------------------------------------
*/
/** {@collect.stats}
* Sends or not past notifications depending on the specified flag.
*
* @param currentDate The current date.
* @param currentFlag The flag indicating if past notifications must be sent or not.
*/
private synchronized void sendPastNotifications(Date currentDate, boolean currentFlag) {
TimerNotification notif;
Integer notifID;
Date date;
for (Object[] obj : timerTable.values()) {
// Retrieve the timer notification and the date notification.
//
notif = (TimerNotification)obj[TIMER_NOTIF_INDEX];
notifID = notif.getNotificationID();
date = (Date)obj[TIMER_DATE_INDEX];
// Update the timer notification while:
// - the timer notification date is earlier than the current date
// - the timer notification has not been removed from the timer table.
//
while ( (currentDate.after(date)) && (timerTable.containsKey(notifID)) ) {
if (currentFlag == true) {
if (TIMER_LOGGER.isLoggable(Level.FINER)) {
StringBuilder strb = new StringBuilder()
.append("sending past timer notification:")
.append("\n\tNotification source = ")
.append(notif.getSource())
.append("\n\tNotification type = ")
.append(notif.getType())
.append("\n\tNotification ID = ")
.append(notif.getNotificationID())
.append("\n\tNotification date = ")
.append(date)
.append("\n\tNotification period = ")
.append(obj[TIMER_PERIOD_INDEX])
.append("\n\tNotification nb of occurrences = ")
.append(obj[TIMER_NB_OCCUR_INDEX])
.append("\n\tNotification executes at fixed rate = ")
.append(obj[FIXED_RATE_INDEX]);
TIMER_LOGGER.logp(Level.FINER, Timer.class.getName(),
"sendPastNotifications", strb.toString());
}
sendNotification(date, notif);
TIMER_LOGGER.logp(Level.FINER, Timer.class.getName(),
"sendPastNotifications", "past timer notification sent");
}
// Update the date and the number of occurrences of the timer notification.
//
updateTimerTable(notif.getNotificationID());
}
}
}
/** {@collect.stats}
* If the timer notification is not periodic, it is removed from the list of notifications.
* <P>
* If the timer period of the timer notification has a non null periodicity,
* the date of the timer notification is updated by adding the periodicity.
* The associated TimerAlarmClock is updated by setting its timeout to the period value.
* <P>
* If the timer period has a defined number of occurrences, the timer
* notification is updated if the number of occurrences has not yet been reached.
* Otherwise it is removed from the list of notifications.
*
* @param notifID The timer notification identifier to update.
*/
private synchronized void updateTimerTable(Integer notifID) {
// Retrieve the timer notification and the TimerAlarmClock.
//
Object[] obj = timerTable.get(notifID);
Date date = (Date)obj[TIMER_DATE_INDEX];
Long period = (Long)obj[TIMER_PERIOD_INDEX];
Long nbOccurences = (Long)obj[TIMER_NB_OCCUR_INDEX];
Boolean fixedRate = (Boolean)obj[FIXED_RATE_INDEX];
TimerAlarmClock alarmClock = (TimerAlarmClock)obj[ALARM_CLOCK_INDEX];
if (period.longValue() != 0) {
// Update the date and the number of occurrences of the timer notification
// and the TimerAlarmClock time out.
// NOTES :
// nbOccurences = 0 notifies an infinite periodicity.
// nbOccurences = 1 notifies a finite periodicity that has reached its end.
// nbOccurences > 1 notifies a finite periodicity that has not yet reached its end.
//
if ((nbOccurences.longValue() == 0) || (nbOccurences.longValue() > 1)) {
date.setTime(date.getTime() + period.longValue());
obj[TIMER_NB_OCCUR_INDEX] = new Long(java.lang.Math.max(0L, (nbOccurences.longValue() - 1)));
nbOccurences = (Long)obj[TIMER_NB_OCCUR_INDEX];
if (isActive == true) {
if (fixedRate.booleanValue())
{
alarmClock = new TimerAlarmClock(this, date);
obj[ALARM_CLOCK_INDEX] = (Object)alarmClock;
timer.schedule(alarmClock, alarmClock.next);
}
else
{
alarmClock = new TimerAlarmClock(this, period.longValue());
obj[ALARM_CLOCK_INDEX] = (Object)alarmClock;
timer.schedule(alarmClock, alarmClock.timeout);
}
}
if (TIMER_LOGGER.isLoggable(Level.FINER)) {
TimerNotification notif = (TimerNotification)obj[TIMER_NOTIF_INDEX];
StringBuilder strb = new StringBuilder()
.append("update timer notification with:")
.append("\n\tNotification source = ")
.append(notif.getSource())
.append("\n\tNotification type = ")
.append(notif.getType())
.append("\n\tNotification ID = ")
.append(notifID)
.append("\n\tNotification date = ")
.append(date)
.append("\n\tNotification period = ")
.append(period)
.append("\n\tNotification nb of occurrences = ")
.append(nbOccurences)
.append("\n\tNotification executes at fixed rate = ")
.append(fixedRate);
TIMER_LOGGER.logp(Level.FINER, Timer.class.getName(),
"updateTimerTable", strb.toString());
}
}
else {
if (alarmClock != null) {
// alarmClock.interrupt();
// try {
// // Wait until the thread die.
// //
// alarmClock.join();
// } catch (InterruptedException e) {
// // Ignore...
// }
alarmClock.cancel();
// Remove the reference on the TimerAlarmClock.
//
alarmClock = null;
}
timerTable.remove(notifID);
}
}
else {
if (alarmClock != null) {
// alarmClock.interrupt();
// try {
// // Wait until the thread die.
// //
// alarmClock.join();
// } catch (InterruptedException e) {
// // Ignore...
// }
alarmClock.cancel();
// Remove the reference on the TimerAlarmClock.
//
alarmClock = null;
}
timerTable.remove(notifID);
}
}
/*
* ------------------------------------------
* PACKAGE METHODS
* ------------------------------------------
*/
/** {@collect.stats}
* This method is called by the timer each time
* the TimerAlarmClock has exceeded its timeout.
*
* @param notification The TimerAlarmClock notification.
*/
@SuppressWarnings("deprecation")
void notifyAlarmClock(TimerAlarmClockNotification notification) {
TimerNotification timerNotification = null;
Date timerDate = null;
// Retrieve the timer notification associated to the alarm-clock.
//
TimerAlarmClock alarmClock = (TimerAlarmClock)notification.getSource();
for (Object[] obj : timerTable.values()) {
if (obj[ALARM_CLOCK_INDEX] == alarmClock) {
timerNotification = (TimerNotification)obj[TIMER_NOTIF_INDEX];
timerDate = (Date)obj[TIMER_DATE_INDEX];
break;
}
}
// Notify the timer.
//
sendNotification(timerDate, timerNotification);
// Update the notification and the TimerAlarmClock timeout.
//
updateTimerTable(timerNotification.getNotificationID());
}
/** {@collect.stats}
* This method is used by the timer MBean to update and send a timer
* notification to all the listeners registered for this kind of notification.
*
* @param timeStamp The notification emission date.
* @param notification The timer notification to send.
*/
void sendNotification(Date timeStamp, TimerNotification notification) {
if (TIMER_LOGGER.isLoggable(Level.FINER)) {
StringBuilder strb = new StringBuilder()
.append("sending timer notification:")
.append("\n\tNotification source = ")
.append(notification.getSource())
.append("\n\tNotification type = ")
.append(notification.getType())
.append("\n\tNotification ID = ")
.append(notification.getNotificationID())
.append("\n\tNotification date = ")
.append(timeStamp);
TIMER_LOGGER.logp(Level.FINER, Timer.class.getName(),
"sendNotification", strb.toString());
}
long curSeqNumber;
synchronized(this) {
sequenceNumber = sequenceNumber + 1;
curSeqNumber = sequenceNumber;
}
synchronized (notification) {
notification.setTimeStamp(timeStamp.getTime());
notification.setSequenceNumber(curSeqNumber);
this.sendNotification((TimerNotification)notification.cloneTimerNotification());
}
TIMER_LOGGER.logp(Level.FINER, Timer.class.getName(),
"sendNotification", "timer notification sent");
}
}
/** {@collect.stats}
* TimerAlarmClock inner class:
* This class provides a simple implementation of an alarm clock MBean.
* The aim of this MBean is to set up an alarm which wakes up the timer every timeout (fixed-delay)
* or at the specified date (fixed-rate).
*/
class TimerAlarmClock extends java.util.TimerTask {
Timer listener = null;
long timeout = 10000;
Date next = null;
/*
* ------------------------------------------
* CONSTRUCTORS
* ------------------------------------------
*/
public TimerAlarmClock(Timer listener, long timeout) {
this.listener = listener;
this.timeout = Math.max(0L, timeout);
}
public TimerAlarmClock(Timer listener, Date next) {
this.listener = listener;
this.next = next;
}
/*
* ------------------------------------------
* PUBLIC METHODS
* ------------------------------------------
*/
/** {@collect.stats}
* This method is called by the timer when it is started.
*/
public void run() {
try {
//this.sleep(timeout);
TimerAlarmClockNotification notif = new TimerAlarmClockNotification(this);
listener.notifyAlarmClock(notif);
} catch (Exception e) {
TIMER_LOGGER.logp(Level.FINEST, Timer.class.getName(), "run",
"Got unexpected exception when sending a notification", e);
}
}
}
| Java |
/*
* Copyright (c) 2002, 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.timer;
/** {@collect.stats}
* <p>Definitions of the notifications sent by TimerAlarmClock
* MBeans.</p>
*/
class TimerAlarmClockNotification
extends javax.management.Notification {
/* Serial version */
private static final long serialVersionUID = -4841061275673620641L;
/*
* ------------------------------------------
* CONSTRUCTORS
* ------------------------------------------
*/
/** {@collect.stats}
* Constructor.
*
* @param source the source.
*/
public TimerAlarmClockNotification(TimerAlarmClock source) {
super("", source, 0);
}
}
| Java |
/*
* Copyright (c) 1999, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management;
import java.security.AccessController;
import com.sun.jmx.mbeanserver.GetPropertyAction;
/** {@collect.stats}
* 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;
}
/** {@collect.stats}
* @serial The name of the attribute
*
* <p>The <b>serialVersionUID</b> of this class is <code>-1081892073854801359L</code>.
*/
private String attr;
/** {@collect.stats}
* 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";
}
/** {@collect.stats}
* 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);
}
}
/** {@collect.stats}
* 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. */
}
}
}
| Java |
/*
* Copyright (c) 2002, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management;
import java.security.BasicPermission;
/** {@collect.stats}
* 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;
/** {@collect.stats} <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);
}
/** {@collect.stats} <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);
/* 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 + "]");
}
}
| Java |
/*
* Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management;
/** {@collect.stats}
* 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;
/** {@collect.stats}
* @serial The attribute value that originated this exception
*/
private Object val;
/** {@collect.stats}
* Constructs an <CODE>BadAttributeValueExpException</CODE> with the specified Object.
*
* @param val the inappropriate value.
*/
public BadAttributeValueExpException (Object val) {
this.val = val;
}
/** {@collect.stats}
* Returns the string representing the object.
*/
public String toString() {
return "BadAttributeValueException: " + val;
}
}
| Java |
/*
* Copyright (c) 1999, 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management;
/** {@collect.stats}
* Represents 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;
/** {@collect.stats}
* @serial The encapsulated {@link RuntimeException}
*/
private java.lang.RuntimeException runtimeException ;
/** {@collect.stats}
* 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 ;
}
/** {@collect.stats}
* 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 ;
}
/** {@collect.stats}
* Returns the actual {@link RuntimeException} thrown.
*
* @return the wrapped {@link RuntimeException}.
*/
public java.lang.RuntimeException getTargetException() {
return runtimeException ;
}
/** {@collect.stats}
* Returns the actual {@link RuntimeException} thrown.
*
* @return the wrapped {@link RuntimeException}.
*/
public Throwable getCause() {
return runtimeException;
}
}
| Java |
/*
* Copyright (c) 2000, 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management.relation;
/** {@collect.stats}
* This exception is raised when an invalid Relation Service is provided.
*
* @since 1.5
*/
public class InvalidRelationServiceException extends RelationException {
/* Serial version */
private static final long serialVersionUID = 3400722103759507559L;
/** {@collect.stats}
* Default constructor, no message put in exception.
*/
public InvalidRelationServiceException() {
super();
}
/** {@collect.stats}
* Constructor with given message put in exception.
*
* @param message the detail message.
*/
public InvalidRelationServiceException(String message) {
super(message);
}
}
| Java |
/*
* Copyright (c) 2000, 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management.relation;
/** {@collect.stats}
* This exception is raised when a role in a relation does not exist, or is not
* readable, or is not settable.
*
* @since 1.5
*/
public class RoleNotFoundException extends RelationException {
/* Serial version */
private static final long serialVersionUID = -2986406101364031481L;
/** {@collect.stats}
* Default constructor, no message put in exception.
*/
public RoleNotFoundException() {
super();
}
/** {@collect.stats}
* Constructor with given message put in exception.
*
* @param message the detail message.
*/
public RoleNotFoundException(String message) {
super(message);
}
}
| Java |
/*
* Copyright (c) 2000, 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management.relation;
/** {@collect.stats}
* This exception is raised when relation id provided for a relation is already
* used.
*
* @since 1.5
*/
public class InvalidRelationIdException extends RelationException {
/* Serial version */
private static final long serialVersionUID = -7115040321202754171L;
/** {@collect.stats}
* Default constructor, no message put in exception.
*/
public InvalidRelationIdException() {
super();
}
/** {@collect.stats}
* Constructor with given message put in exception.
*
* @param message the detail message.
*/
public InvalidRelationIdException(String message) {
super(message);
}
}
| Java |
/*
* Copyright (c) 2000, 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management.relation;
/** {@collect.stats}
* This exception is raised when there is no relation for a given relation id
* in a Relation Service.
*
* @since 1.5
*/
public class RelationNotFoundException extends RelationException {
/* Serial version */
private static final long serialVersionUID = -3793951411158559116L;
/** {@collect.stats}
* Default constructor, no message put in exception.
*/
public RelationNotFoundException() {
super();
}
/** {@collect.stats}
* Constructor with given message put in exception.
*
* @param message the detail message.
*/
public RelationNotFoundException(String message) {
super(message);
}
}
| Java |
/*
* Copyright (c) 2000, 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management.relation;
import java.util.ArrayList; // for Javadoc
import java.util.List;
import java.io.Serializable;
/** {@collect.stats}
* The RelationType interface has to be implemented by any class expected to
* represent a relation type.
*
* @since 1.5
*/
public interface RelationType extends Serializable {
//
// Accessors
//
/** {@collect.stats}
* Returns the relation type name.
*
* @return the relation type name.
*/
public String getRelationTypeName();
/** {@collect.stats}
* Returns the list of role definitions (ArrayList of RoleInfo objects).
*
* @return an {@link ArrayList} of {@link RoleInfo}.
*/
public List<RoleInfo> getRoleInfos();
/** {@collect.stats}
* Returns the role info (RoleInfo object) for the given role info name
* (null if not found).
*
* @param roleInfoName role info name
*
* @return RoleInfo object providing role definition
* does not exist
*
* @exception IllegalArgumentException if null parameter
* @exception RoleInfoNotFoundException if no role info with that name in
* relation type.
*/
public RoleInfo getRoleInfo(String roleInfoName)
throws IllegalArgumentException,
RoleInfoNotFoundException;
}
| Java |
/*
* Copyright (c) 2000, 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management.relation;
/** {@collect.stats}
* This class describes the various problems which can be encountered when
* accessing a role.
*
* @since 1.5
*/
public class RoleStatus {
//
// Possible problems
//
/** {@collect.stats}
* Problem type when trying to access an unknown role.
*/
public static final int NO_ROLE_WITH_NAME = 1;
/** {@collect.stats}
* Problem type when trying to read a non-readable attribute.
*/
public static final int ROLE_NOT_READABLE = 2;
/** {@collect.stats}
* Problem type when trying to update a non-writable attribute.
*/
public static final int ROLE_NOT_WRITABLE = 3;
/** {@collect.stats}
* Problem type when trying to set a role value with less ObjectNames than
* the minimum expected cardinality.
*/
public static final int LESS_THAN_MIN_ROLE_DEGREE = 4;
/** {@collect.stats}
* Problem type when trying to set a role value with more ObjectNames than
* the maximum expected cardinality.
*/
public static final int MORE_THAN_MAX_ROLE_DEGREE = 5;
/** {@collect.stats}
* Problem type when trying to set a role value including the ObjectName of
* a MBean not of the class expected for that role.
*/
public static final int REF_MBEAN_OF_INCORRECT_CLASS = 6;
/** {@collect.stats}
* Problem type when trying to set a role value including the ObjectName of
* a MBean not registered in the MBean Server.
*/
public static final int REF_MBEAN_NOT_REGISTERED = 7;
/** {@collect.stats}
* Returns true if given value corresponds to a known role status, false
* otherwise.
*
* @param status a status code.
*
* @return true if this value is a known role status.
*/
public static boolean isRoleStatus(int status) {
if (status != NO_ROLE_WITH_NAME &&
status != ROLE_NOT_READABLE &&
status != ROLE_NOT_WRITABLE &&
status != LESS_THAN_MIN_ROLE_DEGREE &&
status != MORE_THAN_MAX_ROLE_DEGREE &&
status != REF_MBEAN_OF_INCORRECT_CLASS &&
status != REF_MBEAN_NOT_REGISTERED) {
return false;
}
return true;
}
}
| Java |
/*
* Copyright (c) 2000, 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management.relation;
/** {@collect.stats}
* Role value is invalid.
* This exception is raised when, in a role, the number of referenced MBeans
* in given value is less than expected minimum degree, or the number of
* referenced MBeans in provided value exceeds expected maximum degree, or
* one referenced MBean in the value is not an Object of the MBean
* class expected for that role, or an MBean provided for that role does not
* exist.
*
* @since 1.5
*/
public class InvalidRoleValueException extends RelationException {
/* Serial version */
private static final long serialVersionUID = -2066091747301983721L;
/** {@collect.stats}
* Default constructor, no message put in exception.
*/
public InvalidRoleValueException() {
super();
}
/** {@collect.stats}
* Constructor with given message put in exception.
*
* @param message the detail message.
*/
public InvalidRoleValueException(String message) {
super(message);
}
}
| Java |
/*
* Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management.relation;
import java.util.List;
import java.util.Map;
import javax.management.ObjectName;
/** {@collect.stats}
* This interface has to be implemented by any MBean class expected to
* represent a relation managed using the Relation Service.
* <P>Simple relations, i.e. having only roles, no properties or methods, can
* be created directly by the Relation Service (represented as RelationSupport
* objects, internally handled by the Relation Service).
* <P>If the user wants to represent more complex relations, involving
* properties and/or methods, he has to provide his own class implementing the
* Relation interface. This can be achieved either by inheriting from
* RelationSupport class, or by implementing the interface (fully or delegation to
* a RelationSupport object member).
* <P>Specifying such user relation class is to introduce properties and/or
* methods. Those have to be exposed for remote management. So this means that
* any user relation class must be a MBean class.
*
* @since 1.5
*/
public interface Relation {
/** {@collect.stats}
* Retrieves role value for given role name.
* <P>Checks if the role exists and is readable according to the relation
* type.
*
* @param roleName name of role
*
* @return the ArrayList of ObjectName objects being the role value
*
* @exception IllegalArgumentException if null role name
* @exception RoleNotFoundException if:
* <P>- there is no role with given name
* <P>- the role is not readable.
* @exception RelationServiceNotRegisteredException if the Relation
* Service is not registered in the MBean Server
*
* @see #setRole
*/
public List<ObjectName> getRole(String roleName)
throws IllegalArgumentException,
RoleNotFoundException,
RelationServiceNotRegisteredException;
/** {@collect.stats}
* Retrieves values of roles with given names.
* <P>Checks for each role if it exists and is readable according to the
* relation type.
*
* @param roleNameArray array of names of roles to be retrieved
*
* @return a RoleResult object, including a RoleList (for roles
* successfully retrieved) and a RoleUnresolvedList (for roles not
* retrieved).
*
* @exception IllegalArgumentException if null role name
* @exception RelationServiceNotRegisteredException if the Relation
* Service is not registered in the MBean Server
*
* @see #setRoles
*/
public RoleResult getRoles(String[] roleNameArray)
throws IllegalArgumentException,
RelationServiceNotRegisteredException;
/** {@collect.stats}
* Returns the number of MBeans currently referenced in the given role.
*
* @param roleName name of role
*
* @return the number of currently referenced MBeans in that role
*
* @exception IllegalArgumentException if null role name
* @exception RoleNotFoundException if there is no role with given name
*/
public Integer getRoleCardinality(String roleName)
throws IllegalArgumentException,
RoleNotFoundException;
/** {@collect.stats}
* Returns all roles present in the relation.
*
* @return a RoleResult object, including a RoleList (for roles
* successfully retrieved) and a RoleUnresolvedList (for roles not
* readable).
*
* @exception RelationServiceNotRegisteredException if the Relation
* Service is not registered in the MBean Server
*/
public RoleResult getAllRoles()
throws RelationServiceNotRegisteredException;
/** {@collect.stats}
* Returns all roles in the relation without checking read mode.
*
* @return a RoleList.
*/
public RoleList retrieveAllRoles();
/** {@collect.stats}
* Sets the given role.
* <P>Will check the role according to its corresponding role definition
* provided in relation's relation type
* <P>Will send a notification (RelationNotification with type
* RELATION_BASIC_UPDATE or RELATION_MBEAN_UPDATE, depending if the
* relation is a MBean or not).
*
* @param role role to be set (name and new value)
*
* @exception IllegalArgumentException if null role
* @exception RoleNotFoundException if there is no role with the supplied
* role's name or if the role is not writable (no test on the write access
* mode performed when initializing the role)
* @exception InvalidRoleValueException if value provided for
* role is not valid, i.e.:
* <P>- the number of referenced MBeans in given value is less than
* expected minimum degree
* <P>- the number of referenced MBeans in provided value exceeds expected
* maximum degree
* <P>- one referenced MBean in the value is not an Object of the MBean
* class expected for that role
* <P>- a MBean provided for that role does not exist.
* @exception RelationServiceNotRegisteredException if the Relation
* Service is not registered in the MBean Server
* @exception RelationTypeNotFoundException if the relation type has not
* been declared in the Relation Service.
* @exception RelationNotFoundException if the relation has not been
* added in the Relation Service.
*
* @see #getRole
*/
public void setRole(Role role)
throws IllegalArgumentException,
RoleNotFoundException,
RelationTypeNotFoundException,
InvalidRoleValueException,
RelationServiceNotRegisteredException,
RelationNotFoundException;
/** {@collect.stats}
* Sets the given roles.
* <P>Will check the role according to its corresponding role definition
* provided in relation's relation type
* <P>Will send one notification (RelationNotification with type
* RELATION_BASIC_UPDATE or RELATION_MBEAN_UPDATE, depending if the
* relation is a MBean or not) per updated role.
*
* @param roleList list of roles to be set
*
* @return a RoleResult object, including a RoleList (for roles
* successfully set) and a RoleUnresolvedList (for roles not
* set).
*
* @exception IllegalArgumentException if null role list
* @exception RelationServiceNotRegisteredException if the Relation
* Service is not registered in the MBean Server
* @exception RelationTypeNotFoundException if the relation type has not
* been declared in the Relation Service.
* @exception RelationNotFoundException if the relation MBean has not been
* added in the Relation Service.
*
* @see #getRoles
*/
public RoleResult setRoles(RoleList roleList)
throws IllegalArgumentException,
RelationServiceNotRegisteredException,
RelationTypeNotFoundException,
RelationNotFoundException;
/** {@collect.stats}
* Callback used by the Relation Service when a MBean referenced in a role
* is unregistered.
* <P>The Relation Service will call this method to let the relation
* take action to reflect the impact of such unregistration.
* <P>BEWARE. the user is not expected to call this method.
* <P>Current implementation is to set the role with its current value
* (list of ObjectNames of referenced MBeans) without the unregistered
* one.
*
* @param objectName ObjectName of unregistered MBean
* @param roleName name of role where the MBean is referenced
*
* @exception IllegalArgumentException if null parameter
* @exception RoleNotFoundException if role does not exist in the
* relation or is not writable
* @exception InvalidRoleValueException if role value does not conform to
* the associated role info (this will never happen when called from the
* Relation Service)
* @exception RelationServiceNotRegisteredException if the Relation
* Service is not registered in the MBean Server
* @exception RelationTypeNotFoundException if the relation type has not
* been declared in the Relation Service.
* @exception RelationNotFoundException if this method is called for a
* relation MBean not added in the Relation Service.
*/
public void handleMBeanUnregistration(ObjectName objectName,
String roleName)
throws IllegalArgumentException,
RoleNotFoundException,
InvalidRoleValueException,
RelationServiceNotRegisteredException,
RelationTypeNotFoundException,
RelationNotFoundException;
/** {@collect.stats}
* Retrieves MBeans referenced in the various roles of the relation.
*
* @return a HashMap mapping:
* <P> ObjectName -> ArrayList of String (role names)
*/
public Map<ObjectName,List<String>> getReferencedMBeans();
/** {@collect.stats}
* Returns name of associated relation type.
*
* @return the name of the relation type.
*/
public String getRelationTypeName();
/** {@collect.stats}
* Returns ObjectName of the Relation Service handling the relation.
*
* @return the ObjectName of the Relation Service.
*/
public ObjectName getRelationServiceName();
/** {@collect.stats}
* Returns relation identifier (used to uniquely identify the relation
* inside the Relation Service).
*
* @return the relation id.
*/
public String getRelationId();
}
| Java |
/*
* Copyright (c) 2000, 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management.relation;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/** {@collect.stats}
* A RoleUnresolvedList represents a list of RoleUnresolved objects,
* representing roles not retrieved from a relation due to a problem
* encountered when trying to access (read or write) the roles.
*
* @since 1.5
*/
/* We cannot extend ArrayList<RoleUnresolved> because our legacy
add(RoleUnresolved) 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,RoleUnresolved). Grrr. We cannot use covariance
to override the most important methods and have them return
RoleUnresolved, either, because that would break subclasses that
override those methods in turn (using the original return type
of Object). Finally, we cannot implement Iterable<RoleUnresolved>
so you could write
for (RoleUnresolved r : roleUnresolvedList)
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 (RoleUnresolved r : roleUnresolvedList.asList())
*/
public class RoleUnresolvedList extends ArrayList<Object> {
private transient boolean typeSafe;
private transient boolean tainted;
/* Serial version */
private static final long serialVersionUID = 4054902803091433324L;
//
// Constructors
//
/** {@collect.stats}
* Constructs an empty RoleUnresolvedList.
*/
public RoleUnresolvedList() {
super();
}
/** {@collect.stats}
* Constructs an empty RoleUnresolvedList with the initial capacity
* specified.
*
* @param initialCapacity initial capacity
*/
public RoleUnresolvedList(int initialCapacity) {
super(initialCapacity);
}
/** {@collect.stats}
* Constructs a {@code RoleUnresolvedList} containing the elements of the
* {@code List} specified, in the order in which they are returned by
* the {@code List}'s iterator. The {@code RoleUnresolvedList} instance has
* an initial capacity of 110% of the size of the {@code List}
* specified.
*
* @param list the {@code List} that defines the initial contents of
* the new {@code RoleUnresolvedList}.
*
* @exception IllegalArgumentException if the {@code list} parameter
* is {@code null} or if the {@code list} parameter contains any
* non-RoleUnresolved objects.
*
* @see ArrayList#ArrayList(java.util.Collection)
*/
public RoleUnresolvedList(List<RoleUnresolved> list)
throws IllegalArgumentException {
// Check for null parameter
//
if (list == null)
throw new IllegalArgumentException("Null parameter");
// Check for non-RoleUnresolved objects
//
checkTypeSafe(list);
// Build the List<RoleUnresolved>
//
super.addAll(list);
}
/** {@collect.stats}
* Return a view of this list as a {@code List<RoleUnresolved>}.
* Changes to the returned value are reflected by changes
* to the original {@code RoleUnresolvedList} and vice versa.
*
* @return a {@code List<RoleUnresolved>} whose contents
* reflect the contents of this {@code RoleUnresolvedList}.
*
* <p>If this method has ever been called on a given
* {@code RoleUnresolvedList} instance, a subsequent attempt to add
* an object to that instance which is not a {@code RoleUnresolved}
* will fail with an {@code IllegalArgumentException}. For compatibility
* reasons, a {@code RoleUnresolvedList} on which this method has never
* been called does allow objects other than {@code RoleUnresolved}s to
* be added.</p>
*
* @throws IllegalArgumentException if this {@code RoleUnresolvedList}
* contains an element that is not a {@code RoleUnresolved}.
*
* @since 1.6
*/
@SuppressWarnings("unchecked")
public List<RoleUnresolved> asList() {
if (!typeSafe) {
if (tainted)
checkTypeSafe(this);
typeSafe = true;
}
return (List<RoleUnresolved>) (List) this;
}
//
// Accessors
//
/** {@collect.stats}
* Adds the RoleUnresolved specified as the last element of the list.
*
* @param role - the unresolved role to be added.
*
* @exception IllegalArgumentException if the unresolved role is null.
*/
public void add(RoleUnresolved role)
throws IllegalArgumentException {
if (role == null) {
String excMsg = "Invalid parameter";
throw new IllegalArgumentException(excMsg);
}
super.add(role);
}
/** {@collect.stats}
* Inserts the unresolved role specified as an element at the position
* specified.
* Elements with an index greater than or equal to the current position are
* shifted up.
*
* @param index - The position in the list where the new
* RoleUnresolved object is to be inserted.
* @param role - The RoleUnresolved object to be inserted.
*
* @exception IllegalArgumentException if the unresolved role is null.
* @exception IndexOutOfBoundsException if index is out of range
* (<code>index < 0 || index > size()</code>).
*/
public void add(int index,
RoleUnresolved role)
throws IllegalArgumentException,
IndexOutOfBoundsException {
if (role == null) {
String excMsg = "Invalid parameter";
throw new IllegalArgumentException(excMsg);
}
super.add(index, role);
}
/** {@collect.stats}
* Sets the element at the position specified to be the unresolved role
* specified.
* The previous element at that position is discarded.
*
* @param index - The position specified.
* @param role - The value to which the unresolved role element
* should be set.
*
* @exception IllegalArgumentException if the unresolved role is null.
* @exception IndexOutOfBoundsException if index is out of range
* (<code>index < 0 || index >= size()</code>).
*/
public void set(int index,
RoleUnresolved role)
throws IllegalArgumentException,
IndexOutOfBoundsException {
if (role == null) {
String excMsg = "Invalid parameter";
throw new IllegalArgumentException(excMsg);
}
super.set(index, role);
}
/** {@collect.stats}
* Appends all the elements in the RoleUnresolvedList specified to the end
* of the list, in the order in which they are returned by the Iterator of
* the RoleUnresolvedList specified.
*
* @param roleList - Elements to be inserted into the list
* (can be null).
*
* @return true if this list changed as a result of the call.
*
* @exception IndexOutOfBoundsException if accessing with an index
* outside of the list.
*/
public boolean addAll(RoleUnresolvedList roleList)
throws IndexOutOfBoundsException {
if (roleList == null) {
return true;
}
return (super.addAll(roleList));
}
/** {@collect.stats}
* Inserts all of the elements in the RoleUnresolvedList specified into
* this list, starting at the specified position, in the order in which
* they are returned by the Iterator of the RoleUnresolvedList specified.
*
* @param index - Position at which to insert the first element from the
* RoleUnresolvedList specified.
* @param roleList - Elements to be inserted into the list.
*
* @return true if this list changed as a result of the call.
*
* @exception IllegalArgumentException if the role is null.
* @exception IndexOutOfBoundsException if index is out of range
* (<code>index < 0 || index > size()</code>).
*/
public boolean addAll(int index,
RoleUnresolvedList roleList)
throws IllegalArgumentException,
IndexOutOfBoundsException {
if (roleList == null) {
String excMsg = "Invalid parameter";
throw new IllegalArgumentException(excMsg);
}
return (super.addAll(index, roleList));
}
/*
* Override all of the methods from ArrayList<Object> that might add
* a non-RoleUnresolved to the List, and disallow that if asList has
* ever been called on this instance.
*/
@Override
public boolean add(Object o) {
if (!tainted)
tainted = isTainted(o);
if (typeSafe)
checkTypeSafe(o);
return super.add(o);
}
@Override
public void add(int index, Object element) {
if (!tainted)
tainted = isTainted(element);
if (typeSafe)
checkTypeSafe(element);
super.add(index, element);
}
@Override
public boolean addAll(Collection<?> c) {
if (!tainted)
tainted = isTainted(c);
if (typeSafe)
checkTypeSafe(c);
return super.addAll(c);
}
@Override
public boolean addAll(int index, Collection<?> c) {
if (!tainted)
tainted = isTainted(c);
if (typeSafe)
checkTypeSafe(c);
return super.addAll(index, c);
}
@Override
public Object set(int index, Object element) {
if (!tainted)
tainted = isTainted(element);
if (typeSafe)
checkTypeSafe(element);
return super.set(index, element);
}
/** {@collect.stats}
* IllegalArgumentException if o is a non-RoleUnresolved object.
*/
private static void checkTypeSafe(Object o) {
try {
o = (RoleUnresolved) o;
} catch (ClassCastException e) {
throw new IllegalArgumentException(e);
}
}
/** {@collect.stats}
* IllegalArgumentException if c contains any non-RoleUnresolved objects.
*/
private static void checkTypeSafe(Collection<?> c) {
try {
RoleUnresolved r;
for (Object o : c)
r = (RoleUnresolved) o;
} catch (ClassCastException e) {
throw new IllegalArgumentException(e);
}
}
/** {@collect.stats}
* Returns true if o is a non-RoleUnresolved object.
*/
private static boolean isTainted(Object o) {
try {
checkTypeSafe(o);
} catch (IllegalArgumentException e) {
return true;
}
return false;
}
/** {@collect.stats}
* Returns true if c contains any non-RoleUnresolved objects.
*/
private static boolean isTainted(Collection<?> c) {
try {
checkTypeSafe(c);
} catch (IllegalArgumentException e) {
return true;
}
return false;
}
}
| Java |
/*
* Copyright (c) 2000, 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management.relation;
/** {@collect.stats}
* This exception is raised when there is no role info with given name in a
* given relation type.
*
* @since 1.5
*/
public class RoleInfoNotFoundException extends RelationException {
/* Serial version */
private static final long serialVersionUID = 4394092234999959939L;
/** {@collect.stats}
* Default constructor, no message put in exception.
*/
public RoleInfoNotFoundException() {
super();
}
/** {@collect.stats}
* Constructor with given message put in exception.
*
* @param message the detail message.
*/
public RoleInfoNotFoundException(String message) {
super(message);
}
}
| Java |
/*
* Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management.relation;
import static com.sun.jmx.defaults.JmxProperties.RELATION_LOGGER;
import static com.sun.jmx.mbeanserver.Util.cast;
import com.sun.jmx.mbeanserver.GetPropertyAction;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamField;
import java.security.AccessController;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
/** {@collect.stats}
* A RelationTypeSupport object implements the RelationType interface.
* <P>It represents a relation type, providing role information for each role
* expected to be supported in every relation of that type.
*
* <P>A relation type includes a relation type name and a list of
* role infos (represented by RoleInfo objects).
*
* <P>A relation type has to be declared in the Relation Service:
* <P>- either using the createRelationType() method, where a RelationTypeSupport
* object will be created and kept in the Relation Service
* <P>- either using the addRelationType() method where the user has to create
* an object implementing the RelationType interface, and this object will be
* used as representing a relation type in the Relation Service.
*
* <p>The <b>serialVersionUID</b> of this class is <code>4611072955724144607L</code>.
*
* @since 1.5
*/
@SuppressWarnings("serial") // serialVersionUID not constant
public class RelationTypeSupport implements RelationType {
// 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 = -8179019472410837190L;
//
// Serial version for new serial form
private static final long newSerialVersionUID = 4611072955724144607L;
//
// Serializable fields in old serial form
private static final ObjectStreamField[] oldSerialPersistentFields =
{
new ObjectStreamField("myTypeName", String.class),
new ObjectStreamField("myRoleName2InfoMap", HashMap.class),
new ObjectStreamField("myIsInRelServFlg", boolean.class)
};
//
// Serializable fields in new serial form
private static final ObjectStreamField[] newSerialPersistentFields =
{
new ObjectStreamField("typeName", String.class),
new ObjectStreamField("roleName2InfoMap", Map.class),
new ObjectStreamField("isInRelationService", boolean.class)
};
//
// Actual serial version and serial form
private static final long serialVersionUID;
/** {@collect.stats}
* @serialField typeName String Relation type name
* @serialField roleName2InfoMap Map {@link Map} holding the mapping:
* <role name ({@link String})> -> <role info ({@link RoleInfo} object)>
* @serialField isInRelationService boolean Flag specifying whether the relation type has been declared in the
* Relation Service (so can no longer be updated)
*/
private static final ObjectStreamField[] serialPersistentFields;
private static boolean compat = false;
static {
try {
GetPropertyAction act = new GetPropertyAction("jmx.serial.form");
String form = AccessController.doPrivileged(act);
compat = (form != null && form.equals("1.0"));
} catch (Exception e) {
// OK : Too bad, no compat with 1.0
}
if (compat) {
serialPersistentFields = oldSerialPersistentFields;
serialVersionUID = oldSerialVersionUID;
} else {
serialPersistentFields = newSerialPersistentFields;
serialVersionUID = newSerialVersionUID;
}
}
//
// END Serialization compatibility stuff
//
// Private members
//
/** {@collect.stats}
* @serial Relation type name
*/
private String typeName = null;
/** {@collect.stats}
* @serial {@link Map} holding the mapping:
* <role name ({@link String})> -> <role info ({@link RoleInfo} object)>
*/
private Map<String,RoleInfo> roleName2InfoMap =
new HashMap<String,RoleInfo>();
/** {@collect.stats}
* @serial Flag specifying whether the relation type has been declared in the
* Relation Service (so can no longer be updated)
*/
private boolean isInRelationService = false;
//
// Constructors
//
/** {@collect.stats}
* Constructor where all role definitions are dynamically created and
* passed as parameter.
*
* @param relationTypeName Name of relation type
* @param roleInfoArray List of role definitions (RoleInfo objects)
*
* @exception IllegalArgumentException if null parameter
* @exception InvalidRelationTypeException if:
* <P>- the same name has been used for two different roles
* <P>- no role info provided
* <P>- one null role info provided
*/
public RelationTypeSupport(String relationTypeName,
RoleInfo[] roleInfoArray)
throws IllegalArgumentException,
InvalidRelationTypeException {
if (relationTypeName == null || roleInfoArray == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationTypeSupport.class.getName(),
"RelationTypeSupport", relationTypeName);
// Can throw InvalidRelationTypeException, ClassNotFoundException
// and NotCompliantMBeanException
initMembers(relationTypeName, roleInfoArray);
RELATION_LOGGER.exiting(RelationTypeSupport.class.getName(),
"RelationTypeSupport");
return;
}
/** {@collect.stats}
* Constructor to be used for subclasses.
*
* @param relationTypeName Name of relation type.
*
* @exception IllegalArgumentException if null parameter.
*/
protected RelationTypeSupport(String relationTypeName)
{
if (relationTypeName == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationTypeSupport.class.getName(),
"RelationTypeSupport", relationTypeName);
typeName = relationTypeName;
RELATION_LOGGER.exiting(RelationTypeSupport.class.getName(),
"RelationTypeSupport");
return;
}
//
// Accessors
//
/** {@collect.stats}
* Returns the relation type name.
*
* @return the relation type name.
*/
public String getRelationTypeName() {
return typeName;
}
/** {@collect.stats}
* Returns the list of role definitions (ArrayList of RoleInfo objects).
*/
public List<RoleInfo> getRoleInfos() {
return new ArrayList<RoleInfo>(roleName2InfoMap.values());
}
/** {@collect.stats}
* Returns the role info (RoleInfo object) for the given role info name
* (null if not found).
*
* @param roleInfoName role info name
*
* @return RoleInfo object providing role definition
* does not exist
*
* @exception IllegalArgumentException if null parameter
* @exception RoleInfoNotFoundException if no role info with that name in
* relation type.
*/
public RoleInfo getRoleInfo(String roleInfoName)
throws IllegalArgumentException,
RoleInfoNotFoundException {
if (roleInfoName == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationTypeSupport.class.getName(),
"getRoleInfo", roleInfoName);
// No null RoleInfo allowed, so use get()
RoleInfo result = roleName2InfoMap.get(roleInfoName);
if (result == null) {
StringBuilder excMsgStrB = new StringBuilder();
String excMsg = "No role info for role ";
excMsgStrB.append(excMsg);
excMsgStrB.append(roleInfoName);
throw new RoleInfoNotFoundException(excMsgStrB.toString());
}
RELATION_LOGGER.exiting(RelationTypeSupport.class.getName(),
"getRoleInfo");
return result;
}
//
// Misc
//
/** {@collect.stats}
* Add a role info.
* This method of course should not be used after the creation of the
* relation type, because updating it would invalidate that the relations
* created associated to that type still conform to it.
* Can throw a RuntimeException if trying to update a relation type
* declared in the Relation Service.
*
* @param roleInfo role info to be added.
*
* @exception IllegalArgumentException if null parameter.
* @exception InvalidRelationTypeException if there is already a role
* info in current relation type with the same name.
*/
protected void addRoleInfo(RoleInfo roleInfo)
throws IllegalArgumentException,
InvalidRelationTypeException {
if (roleInfo == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationTypeSupport.class.getName(),
"addRoleInfo", roleInfo);
if (isInRelationService) {
// Trying to update a declared relation type
String excMsg = "Relation type cannot be updated as it is declared in the Relation Service.";
throw new RuntimeException(excMsg);
}
String roleName = roleInfo.getName();
// Checks if the role info has already been described
if (roleName2InfoMap.containsKey(roleName)) {
StringBuilder excMsgStrB = new StringBuilder();
String excMsg = "Two role infos provided for role ";
excMsgStrB.append(excMsg);
excMsgStrB.append(roleName);
throw new InvalidRelationTypeException(excMsgStrB.toString());
}
roleName2InfoMap.put(roleName, new RoleInfo(roleInfo));
RELATION_LOGGER.exiting(RelationTypeSupport.class.getName(),
"addRoleInfo");
return;
}
// Sets the internal flag to specify that the relation type has been
// declared in the Relation Service
void setRelationServiceFlag(boolean flag) {
isInRelationService = flag;
return;
}
// Initializes the members, i.e. type name and role info list.
//
// -param relationTypeName Name of relation type
// -param roleInfoArray List of role definitions (RoleInfo objects)
//
// -exception IllegalArgumentException if null parameter
// -exception InvalidRelationTypeException If:
// - the same name has been used for two different roles
// - no role info provided
// - one null role info provided
private void initMembers(String relationTypeName,
RoleInfo[] roleInfoArray)
throws IllegalArgumentException,
InvalidRelationTypeException {
if (relationTypeName == null || roleInfoArray == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationTypeSupport.class.getName(),
"initMembers", relationTypeName);
typeName = relationTypeName;
// Verifies role infos before setting them
// Can throw InvalidRelationTypeException
checkRoleInfos(roleInfoArray);
for (int i = 0; i < roleInfoArray.length; i++) {
RoleInfo currRoleInfo = roleInfoArray[i];
roleName2InfoMap.put(currRoleInfo.getName(),
new RoleInfo(currRoleInfo));
}
RELATION_LOGGER.exiting(RelationTypeSupport.class.getName(),
"initMembers");
return;
}
// Checks the given RoleInfo array to verify that:
// - the array is not empty
// - it does not contain a null element
// - a given role name is used only for one RoleInfo
//
// -param roleInfoArray array to be checked
//
// -exception IllegalArgumentException
// -exception InvalidRelationTypeException If:
// - the same name has been used for two different roles
// - no role info provided
// - one null role info provided
static void checkRoleInfos(RoleInfo[] roleInfoArray)
throws IllegalArgumentException,
InvalidRelationTypeException {
if (roleInfoArray == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
if (roleInfoArray.length == 0) {
// No role info provided
String excMsg = "No role info provided.";
throw new InvalidRelationTypeException(excMsg);
}
Set<String> roleNames = new HashSet<String>();
for (int i = 0; i < roleInfoArray.length; i++) {
RoleInfo currRoleInfo = roleInfoArray[i];
if (currRoleInfo == null) {
String excMsg = "Null role info provided.";
throw new InvalidRelationTypeException(excMsg);
}
String roleName = currRoleInfo.getName();
// Checks if the role info has already been described
if (roleNames.contains(roleName)) {
StringBuilder excMsgStrB = new StringBuilder();
String excMsg = "Two role infos provided for role ";
excMsgStrB.append(excMsg);
excMsgStrB.append(roleName);
throw new InvalidRelationTypeException(excMsgStrB.toString());
}
roleNames.add(roleName);
}
return;
}
/** {@collect.stats}
* Deserializes a {@link RelationTypeSupport} 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();
typeName = (String) fields.get("myTypeName", null);
if (fields.defaulted("myTypeName"))
{
throw new NullPointerException("myTypeName");
}
roleName2InfoMap = cast(fields.get("myRoleName2InfoMap", null));
if (fields.defaulted("myRoleName2InfoMap"))
{
throw new NullPointerException("myRoleName2InfoMap");
}
isInRelationService = fields.get("myIsInRelServFlg", false);
if (fields.defaulted("myIsInRelServFlg"))
{
throw new NullPointerException("myIsInRelServFlg");
}
}
else
{
// Read an object serialized in the new serial form
//
in.defaultReadObject();
}
}
/** {@collect.stats}
* Serializes a {@link RelationTypeSupport} 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("myTypeName", typeName);
fields.put("myRoleName2InfoMap", roleName2InfoMap);
fields.put("myIsInRelServFlg", isInRelationService);
out.writeFields();
}
else
{
// Serializes this instance in the new serial form
//
out.defaultWriteObject();
}
}
}
| Java |
/*
* Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management.relation;
import javax.management.Notification;
import javax.management.ObjectName;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamField;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.sun.jmx.mbeanserver.GetPropertyAction;
import static com.sun.jmx.mbeanserver.Util.cast;
/** {@collect.stats}
* A notification of a change in the Relation Service.
* A RelationNotification notification is sent when a relation is created via
* the Relation Service, or an MBean is added as a relation in the Relation
* Service, or a role is updated in a relation, or a relation is removed from
* the Relation Service.
*
* <p>The <b>serialVersionUID</b> of this class is <code>-6871117877523310399L</code>.
*
* @since 1.5
*/
@SuppressWarnings("serial") // serialVersionUID not constant
public class RelationNotification extends Notification {
// 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 = -2126464566505527147L;
//
// Serial version for new serial form
private static final long newSerialVersionUID = -6871117877523310399L;
//
// Serializable fields in old serial form
private static final ObjectStreamField[] oldSerialPersistentFields =
{
new ObjectStreamField("myNewRoleValue", ArrayList.class),
new ObjectStreamField("myOldRoleValue", ArrayList.class),
new ObjectStreamField("myRelId", String.class),
new ObjectStreamField("myRelObjName", ObjectName.class),
new ObjectStreamField("myRelTypeName", String.class),
new ObjectStreamField("myRoleName", String.class),
new ObjectStreamField("myUnregMBeanList", ArrayList.class)
};
//
// Serializable fields in new serial form
private static final ObjectStreamField[] newSerialPersistentFields =
{
new ObjectStreamField("newRoleValue", List.class),
new ObjectStreamField("oldRoleValue", List.class),
new ObjectStreamField("relationId", String.class),
new ObjectStreamField("relationObjName", ObjectName.class),
new ObjectStreamField("relationTypeName", String.class),
new ObjectStreamField("roleName", String.class),
new ObjectStreamField("unregisterMBeanList", List.class)
};
//
// Actual serial version and serial form
private static final long serialVersionUID;
/** {@collect.stats}
* @serialField relationId String Relation identifier of
* created/removed/updated relation
* @serialField relationTypeName String Relation type name of
* created/removed/updated relation
* @serialField relationObjName ObjectName {@link ObjectName} of
* the relation MBean of created/removed/updated relation (only if
* the relation is represented by an MBean)
* @serialField unregisterMBeanList List List of {@link
* ObjectName}s of referenced MBeans to be unregistered due to
* relation removal
* @serialField roleName String Name of updated role (only for role update)
* @serialField oldRoleValue List Old role value ({@link
* ArrayList} of {@link ObjectName}s) (only for role update)
* @serialField newRoleValue List New role value ({@link
* ArrayList} of {@link ObjectName}s) (only for role update)
*/
private static final ObjectStreamField[] serialPersistentFields;
private static boolean compat = false;
static {
try {
GetPropertyAction act = new GetPropertyAction("jmx.serial.form");
String form = AccessController.doPrivileged(act);
compat = (form != null && form.equals("1.0"));
} catch (Exception e) {
// OK : Too bad, no compat with 1.0
}
if (compat) {
serialPersistentFields = oldSerialPersistentFields;
serialVersionUID = oldSerialVersionUID;
} else {
serialPersistentFields = newSerialPersistentFields;
serialVersionUID = newSerialVersionUID;
}
}
//
// END Serialization compatibility stuff
//
// Notification types
//
/** {@collect.stats}
* Type for the creation of an internal relation.
*/
public static final String RELATION_BASIC_CREATION = "jmx.relation.creation.basic";
/** {@collect.stats}
* Type for the relation MBean added into the Relation Service.
*/
public static final String RELATION_MBEAN_CREATION = "jmx.relation.creation.mbean";
/** {@collect.stats}
* Type for an update of an internal relation.
*/
public static final String RELATION_BASIC_UPDATE = "jmx.relation.update.basic";
/** {@collect.stats}
* Type for the update of a relation MBean.
*/
public static final String RELATION_MBEAN_UPDATE = "jmx.relation.update.mbean";
/** {@collect.stats}
* Type for the removal from the Relation Service of an internal relation.
*/
public static final String RELATION_BASIC_REMOVAL = "jmx.relation.removal.basic";
/** {@collect.stats}
* Type for the removal from the Relation Service of a relation MBean.
*/
public static final String RELATION_MBEAN_REMOVAL = "jmx.relation.removal.mbean";
//
// Private members
//
/** {@collect.stats}
* @serial Relation identifier of created/removed/updated relation
*/
private String relationId = null;
/** {@collect.stats}
* @serial Relation type name of created/removed/updated relation
*/
private String relationTypeName = null;
/** {@collect.stats}
* @serial {@link ObjectName} of the relation MBean of created/removed/updated relation
* (only if the relation is represented by an MBean)
*/
private ObjectName relationObjName = null;
/** {@collect.stats}
* @serial List of {@link ObjectName}s of referenced MBeans to be unregistered due to
* relation removal
*/
private List<ObjectName> unregisterMBeanList = null;
/** {@collect.stats}
* @serial Name of updated role (only for role update)
*/
private String roleName = null;
/** {@collect.stats}
* @serial Old role value ({@link ArrayList} of {@link ObjectName}s) (only for role update)
*/
private List<ObjectName> oldRoleValue = null;
/** {@collect.stats}
* @serial New role value ({@link ArrayList} of {@link ObjectName}s) (only for role update)
*/
private List<ObjectName> newRoleValue = null;
//
// Constructors
//
/** {@collect.stats}
* Creates a notification for either a relation creation (RelationSupport
* object created internally in the Relation Service, or an MBean added as a
* relation) or for a relation removal from the Relation Service.
*
* @param notifType type of the notification; either:
* <P>- RELATION_BASIC_CREATION
* <P>- RELATION_MBEAN_CREATION
* <P>- RELATION_BASIC_REMOVAL
* <P>- RELATION_MBEAN_REMOVAL
* @param sourceObj source object, sending the notification. This is either
* an ObjectName or a RelationService object. In the latter case it must be
* the MBean emitting the notification; the MBean Server will rewrite the
* source to be the ObjectName under which that MBean is registered.
* @param sequence sequence number to identify the notification
* @param timeStamp time stamp
* @param message human-readable message describing the notification
* @param id relation id identifying the relation in the Relation
* Service
* @param typeName name of the relation type
* @param objectName ObjectName of the relation object if it is an MBean
* (null for relations internally handled by the Relation Service)
* @param unregMBeanList list of ObjectNames of referenced MBeans
* expected to be unregistered due to relation removal (only for removal,
* due to CIM qualifiers, can be null)
*
* @exception IllegalArgumentException if:
* <P>- no value for the notification type
* <P>- the notification type is not RELATION_BASIC_CREATION,
* RELATION_MBEAN_CREATION, RELATION_BASIC_REMOVAL or
* RELATION_MBEAN_REMOVAL
* <P>- no source object
* <P>- the source object is not a Relation Service
* <P>- no relation id
* <P>- no relation type name
*/
public RelationNotification(String notifType,
Object sourceObj,
long sequence,
long timeStamp,
String message,
String id,
String typeName,
ObjectName objectName,
List<ObjectName> unregMBeanList)
throws IllegalArgumentException {
super(notifType, sourceObj, sequence, timeStamp, message);
// Can throw IllegalArgumentException
initMembers(1,
notifType,
sourceObj,
sequence,
timeStamp,
message,
id,
typeName,
objectName,
unregMBeanList,
null,
null,
null);
return;
}
/** {@collect.stats}
* Creates a notification for a role update in a relation.
*
* @param notifType type of the notification; either:
* <P>- RELATION_BASIC_UPDATE
* <P>- RELATION_MBEAN_UPDATE
* @param sourceObj source object, sending the notification. This is either
* an ObjectName or a RelationService object. In the latter case it must be
* the MBean emitting the notification; the MBean Server will rewrite the
* source to be the ObjectName under which that MBean is registered.
* @param sequence sequence number to identify the notification
* @param timeStamp time stamp
* @param message human-readable message describing the notification
* @param id relation id identifying the relation in the Relation
* Service
* @param typeName name of the relation type
* @param objectName ObjectName of the relation object if it is an MBean
* (null for relations internally handled by the Relation Service)
* @param name name of the updated role
* @param newValue new role value (List of ObjectName objects)
* @param oldValue old role value (List of ObjectName objects)
*
* @exception IllegalArgumentException if null parameter
*/
public RelationNotification(String notifType,
Object sourceObj,
long sequence,
long timeStamp,
String message,
String id,
String typeName,
ObjectName objectName,
String name,
List<ObjectName> newValue,
List<ObjectName> oldValue
)
throws IllegalArgumentException {
super(notifType, sourceObj, sequence, timeStamp, message);
// Can throw IllegalArgumentException
initMembers(2,
notifType,
sourceObj,
sequence,
timeStamp,
message,
id,
typeName,
objectName,
null,
name,
newValue,
oldValue);
return;
}
//
// Accessors
//
/** {@collect.stats}
* Returns the relation identifier of created/removed/updated relation.
*
* @return the relation id.
*/
public String getRelationId() {
return relationId;
}
/** {@collect.stats}
* Returns the relation type name of created/removed/updated relation.
*
* @return the relation type name.
*/
public String getRelationTypeName() {
return relationTypeName;
}
/** {@collect.stats}
* Returns the ObjectName of the
* created/removed/updated relation.
*
* @return the ObjectName if the relation is an MBean, otherwise null.
*/
public ObjectName getObjectName() {
return relationObjName;
}
/** {@collect.stats}
* Returns the list of ObjectNames of MBeans expected to be unregistered
* due to a relation removal (only for relation removal).
*
* @return a {@link List} of {@link ObjectName}.
*/
public List<ObjectName> getMBeansToUnregister() {
List<ObjectName> result = null;
if (unregisterMBeanList != null) {
result = new ArrayList<ObjectName>(unregisterMBeanList);
} else {
result = Collections.emptyList();
}
return result;
}
/** {@collect.stats}
* Returns name of updated role of updated relation (only for role update).
*
* @return the name of the updated role.
*/
public String getRoleName() {
String result = null;
if (roleName != null) {
result = roleName;
}
return result;
}
/** {@collect.stats}
* Returns old value of updated role (only for role update).
*
* @return the old value of the updated role.
*/
public List<ObjectName> getOldRoleValue() {
List<ObjectName> result = null;
if (oldRoleValue != null) {
result = new ArrayList<ObjectName>(oldRoleValue);
} else {
result = Collections.emptyList();
}
return result;
}
/** {@collect.stats}
* Returns new value of updated role (only for role update).
*
* @return the new value of the updated role.
*/
public List<ObjectName> getNewRoleValue() {
List<ObjectName> result = null;
if (newRoleValue != null) {
result = new ArrayList<ObjectName>(newRoleValue);
} else {
result = Collections.emptyList();
}
return result;
}
//
// Misc
//
// Initializes members
//
// -param notifKind 1 for creation/removal, 2 for update
// -param notifType type of the notification; either:
// - RELATION_BASIC_UPDATE
// - RELATION_MBEAN_UPDATE
// for an update, or:
// - RELATION_BASIC_CREATION
// - RELATION_MBEAN_CREATION
// - RELATION_BASIC_REMOVAL
// - RELATION_MBEAN_REMOVAL
// for a creation or removal
// -param sourceObj source object, sending the notification. Will always
// be a RelationService object.
// -param sequence sequence number to identify the notification
// -param timeStamp time stamp
// -param message human-readable message describing the notification
// -param id relation id identifying the relation in the Relation
// Service
// -param typeName name of the relation type
// -param objectName ObjectName of the relation object if it is an MBean
// (null for relations internally handled by the Relation Service)
// -param unregMBeanList list of ObjectNames of MBeans expected to be
// removed due to relation removal
// -param name name of the updated role
// -param newValue new value (List of ObjectName objects)
// -param oldValue old value (List of ObjectName objects)
//
// -exception IllegalArgumentException if:
// - no value for the notification type
// - incorrect notification type
// - no source object
// - the source object is not a Relation Service
// - no relation id
// - no relation type name
// - no role name (for role update)
// - no role old value (for role update)
// - no role new value (for role update)
private void initMembers(int notifKind,
String notifType,
Object sourceObj,
long sequence,
long timeStamp,
String message,
String id,
String typeName,
ObjectName objectName,
List<ObjectName> unregMBeanList,
String name,
List<ObjectName> newValue,
List<ObjectName> oldValue)
throws IllegalArgumentException {
boolean badInitFlg = false;
if (notifType == null ||
sourceObj == null ||
(!(sourceObj instanceof RelationService) &&
!(sourceObj instanceof ObjectName)) ||
id == null ||
typeName == null) {
badInitFlg = true;
}
if (notifKind == 1) {
if ((!(notifType.equals(RelationNotification.RELATION_BASIC_CREATION)))
&&
(!(notifType.equals(RelationNotification.RELATION_MBEAN_CREATION)))
&&
(!(notifType.equals(RelationNotification.RELATION_BASIC_REMOVAL)))
&&
(!(notifType.equals(RelationNotification.RELATION_MBEAN_REMOVAL)))
) {
// Creation/removal
badInitFlg = true;
}
} else if (notifKind == 2) {
if (((!(notifType.equals(RelationNotification.RELATION_BASIC_UPDATE)))
&&
(!(notifType.equals(RelationNotification.RELATION_MBEAN_UPDATE))))
|| name == null ||
oldValue == null ||
newValue == null) {
// Role update
badInitFlg = true;
}
}
if (badInitFlg) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
relationId = id;
relationTypeName = typeName;
relationObjName = objectName;
if (unregMBeanList != null) {
unregisterMBeanList = new ArrayList<ObjectName>(unregMBeanList);
}
if (name != null) {
roleName = name;
}
if (oldValue != null) {
oldRoleValue = new ArrayList<ObjectName>(oldValue);
}
if (newValue != null) {
newRoleValue = new ArrayList<ObjectName>(newValue);
}
return;
}
/** {@collect.stats}
* Deserializes a {@link RelationNotification} 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();
newRoleValue = cast(fields.get("myNewRoleValue", null));
if (fields.defaulted("myNewRoleValue"))
{
throw new NullPointerException("newRoleValue");
}
oldRoleValue = cast(fields.get("myOldRoleValue", null));
if (fields.defaulted("myOldRoleValue"))
{
throw new NullPointerException("oldRoleValue");
}
relationId = (String) fields.get("myRelId", null);
if (fields.defaulted("myRelId"))
{
throw new NullPointerException("relationId");
}
relationObjName = (ObjectName) fields.get("myRelObjName", null);
if (fields.defaulted("myRelObjName"))
{
throw new NullPointerException("relationObjName");
}
relationTypeName = (String) fields.get("myRelTypeName", null);
if (fields.defaulted("myRelTypeName"))
{
throw new NullPointerException("relationTypeName");
}
roleName = (String) fields.get("myRoleName", null);
if (fields.defaulted("myRoleName"))
{
throw new NullPointerException("roleName");
}
unregisterMBeanList = cast(fields.get("myUnregMBeanList", null));
if (fields.defaulted("myUnregMBeanList"))
{
throw new NullPointerException("unregisterMBeanList");
}
}
else
{
// Read an object serialized in the new serial form
//
in.defaultReadObject();
}
}
/** {@collect.stats}
* Serializes a {@link RelationNotification} 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("myNewRoleValue", newRoleValue);
fields.put("myOldRoleValue", oldRoleValue);
fields.put("myRelId", relationId);
fields.put("myRelObjName", relationObjName);
fields.put("myRelTypeName", relationTypeName);
fields.put("myRoleName",roleName);
fields.put("myUnregMBeanList", unregisterMBeanList);
out.writeFields();
}
else
{
// Serializes this instance in the new serial form
//
out.defaultWriteObject();
}
}
}
| Java |
/*
* Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management.relation;
import static com.sun.jmx.mbeanserver.Util.cast;
import com.sun.jmx.mbeanserver.GetPropertyAction;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamField;
import java.io.Serializable;
import java.security.AccessController;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.management.ObjectName;
/** {@collect.stats}
* Represents an unresolved role: a role not retrieved from a relation due
* to a problem. It provides the role name, value (if problem when trying to
* set the role) and an integer defining the problem (constants defined in
* RoleStatus).
*
* <p>The <b>serialVersionUID</b> of this class is <code>-48350262537070138L</code>.
*
* @since 1.5
*/
@SuppressWarnings("serial") // serialVersionUID not constant
public class RoleUnresolved implements Serializable {
// Serialization compatibility stuff:
// Two serial forms are supported in this class. The selected form depends
// on system property "jmx.serial.form":
// - "1.0" for JMX 1.0
// - any other value for JMX 1.1 and higher
//
// Serial version for old serial form
private static final long oldSerialVersionUID = -9026457686611660144L;
//
// Serial version for new serial form
private static final long newSerialVersionUID = -48350262537070138L;
//
// Serializable fields in old serial form
private static final ObjectStreamField[] oldSerialPersistentFields =
{
new ObjectStreamField("myRoleName", String.class),
new ObjectStreamField("myRoleValue", ArrayList.class),
new ObjectStreamField("myPbType", int.class)
};
//
// Serializable fields in new serial form
private static final ObjectStreamField[] newSerialPersistentFields =
{
new ObjectStreamField("roleName", String.class),
new ObjectStreamField("roleValue", List.class),
new ObjectStreamField("problemType", int.class)
};
//
// Actual serial version and serial form
private static final long serialVersionUID;
/** {@collect.stats} @serialField roleName String Role name
* @serialField roleValue List Role value ({@link List} of {@link ObjectName} objects)
* @serialField problemType int Problem type
*/
private static final ObjectStreamField[] serialPersistentFields;
private static boolean compat = false;
static {
try {
GetPropertyAction act = new GetPropertyAction("jmx.serial.form");
String form = AccessController.doPrivileged(act);
compat = (form != null && form.equals("1.0"));
} catch (Exception e) {
// OK : Too bad, no compat with 1.0
}
if (compat) {
serialPersistentFields = oldSerialPersistentFields;
serialVersionUID = oldSerialVersionUID;
} else {
serialPersistentFields = newSerialPersistentFields;
serialVersionUID = newSerialVersionUID;
}
}
//
// END Serialization compatibility stuff
//
// Private members
//
/** {@collect.stats}
* @serial Role name
*/
private String roleName = null;
/** {@collect.stats}
* @serial Role value ({@link List} of {@link ObjectName} objects)
*/
private List<ObjectName> roleValue = null;
/** {@collect.stats}
* @serial Problem type
*/
private int problemType;
//
// Constructor
//
/** {@collect.stats}
* Constructor.
*
* @param name name of the role
* @param value value of the role (if problem when setting the
* role)
* @param pbType type of problem (according to known problem types,
* listed as static final members).
*
* @exception IllegalArgumentException if null parameter or incorrect
* problem type
*/
public RoleUnresolved(String name,
List<ObjectName> value,
int pbType)
throws IllegalArgumentException {
if (name == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
setRoleName(name);
setRoleValue(value);
// Can throw IllegalArgumentException
setProblemType(pbType);
return;
}
//
// Accessors
//
/** {@collect.stats}
* Retrieves role name.
*
* @return the role name.
*
* @see #setRoleName
*/
public String getRoleName() {
return roleName;
}
/** {@collect.stats}
* Retrieves role value.
*
* @return an ArrayList of ObjectName objects, the one provided to be set
* in given role. Null if the unresolved role is returned for a read
* access.
*
* @see #setRoleValue
*/
public List<ObjectName> getRoleValue() {
return roleValue;
}
/** {@collect.stats}
* Retrieves problem type.
*
* @return an integer corresponding to a problem, those being described as
* static final members of current class.
*
* @see #setProblemType
*/
public int getProblemType() {
return problemType;
}
/** {@collect.stats}
* Sets role name.
*
* @param name the new role name.
*
* @exception IllegalArgumentException if null parameter
*
* @see #getRoleName
*/
public void setRoleName(String name)
throws IllegalArgumentException {
if (name == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
roleName = name;
return;
}
/** {@collect.stats}
* Sets role value.
*
* @param value List of ObjectName objects for referenced
* MBeans not set in role.
*
* @see #getRoleValue
*/
public void setRoleValue(List<ObjectName> value) {
if (value != null) {
roleValue = new ArrayList<ObjectName>(value);
} else {
roleValue = null;
}
return;
}
/** {@collect.stats}
* Sets problem type.
*
* @param pbType integer corresponding to a problem. Must be one of
* those described as static final members of current class.
*
* @exception IllegalArgumentException if incorrect problem type
*
* @see #getProblemType
*/
public void setProblemType(int pbType)
throws IllegalArgumentException {
if (!(RoleStatus.isRoleStatus(pbType))) {
String excMsg = "Incorrect problem type.";
throw new IllegalArgumentException(excMsg);
}
problemType = pbType;
return;
}
/** {@collect.stats}
* Clone this object.
*
* @return an independent clone.
*/
public Object clone() {
try {
return new RoleUnresolved(roleName, roleValue, problemType);
} catch (IllegalArgumentException exc) {
return null; // :)
}
}
/** {@collect.stats}
* Return a string describing this object.
*
* @return a description of this RoleUnresolved object.
*/
public String toString() {
StringBuilder result = new StringBuilder();
result.append("role name: " + roleName);
if (roleValue != null) {
result.append("; value: ");
for (Iterator objNameIter = roleValue.iterator();
objNameIter.hasNext();) {
ObjectName currObjName = (ObjectName)(objNameIter.next());
result.append(currObjName.toString());
if (objNameIter.hasNext()) {
result.append(", ");
}
}
}
result.append("; problem type: " + problemType);
return result.toString();
}
/** {@collect.stats}
* Deserializes a {@link RoleUnresolved} 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();
roleName = (String) fields.get("myRoleName", null);
if (fields.defaulted("myRoleName"))
{
throw new NullPointerException("myRoleName");
}
roleValue = cast(fields.get("myRoleValue", null));
if (fields.defaulted("myRoleValue"))
{
throw new NullPointerException("myRoleValue");
}
problemType = fields.get("myPbType", 0);
if (fields.defaulted("myPbType"))
{
throw new NullPointerException("myPbType");
}
}
else
{
// Read an object serialized in the new serial form
//
in.defaultReadObject();
}
}
/** {@collect.stats}
* Serializes a {@link RoleUnresolved} 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("myRoleName", roleName);
fields.put("myRoleValue", (ArrayList)roleValue);
fields.put("myPbType", problemType);
out.writeFields();
}
else
{
// Serializes this instance in the new serial form
//
out.defaultWriteObject();
}
}
}
| Java |
/*
* Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management.relation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.List;
import static com.sun.jmx.defaults.JmxProperties.RELATION_LOGGER;
import static com.sun.jmx.mbeanserver.Util.cast;
import javax.management.InstanceNotFoundException;
import javax.management.MBeanException;
import javax.management.MBeanRegistration;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.management.ReflectionException;
/** {@collect.stats}
* A RelationSupport object is used internally by the Relation Service to
* represent simple relations (only roles, no properties or methods), with an
* unlimited number of roles, of any relation type. As internal representation,
* it is not exposed to the user.
* <P>RelationSupport class conforms to the design patterns of standard MBean. So
* the user can decide to instantiate a RelationSupport object himself as
* a MBean (as it follows the MBean design patterns), to register it in the
* MBean Server, and then to add it in the Relation Service.
* <P>The user can also, when creating his own MBean relation class, have it
* extending RelationSupport, to retrieve the implementations of required
* interfaces (see below).
* <P>It is also possible to have in a user relation MBean class a member
* being a RelationSupport object, and to implement the required interfaces by
* delegating all to this member.
* <P> RelationSupport implements the Relation interface (to be handled by the
* Relation Service).
* <P>It implements also the MBeanRegistration interface to be able to retrieve
* the MBean Server where it is registered (if registered as a MBean) to access
* to its Relation Service.
*
* @since 1.5
*/
public class RelationSupport
implements RelationSupportMBean, MBeanRegistration {
//
// Private members
//
// Relation identifier (expected to be unique in the Relation Service where
// the RelationSupport object will be added)
private String myRelId = null;
// ObjectName of the Relation Service where the relation will be added
// REQUIRED if the RelationSupport is created by the user to be registered as
// a MBean, as it will have to access the Relation Service via the MBean
// Server to perform the check regarding the relation type.
// Is null if current object is directly created by the Relation Service,
// as the object will directly access it.
private ObjectName myRelServiceName = null;
// Reference to the MBean Server where the Relation Service is
// registered
// REQUIRED if the RelationSupport is created by the user to be registered as
// a MBean, as it will have to access the Relation Service via the MBean
// Server to perform the check regarding the relation type.
// If the Relationbase object is created by the Relation Service (use of
// createRelation() method), this is null as not needed, direct access to
// the Relation Service.
// If the Relationbase object is created by the user and registered as a
// MBean, this is set by the preRegister() method below.
private MBeanServer myRelServiceMBeanServer = null;
// Relation type name (must be known in the Relation Service where the
// relation will be added)
private String myRelTypeName = null;
// Role map, mapping <role-name> -> <Role>
// Initialized by role list in the constructor, then updated:
// - if the relation is a MBean, via setRole() and setRoles() methods, or
// via Relation Service setRole() and setRoles() methods
// - if the relation is internal to the Relation Service, via
// setRoleInt() and setRolesInt() methods.
private Map<String,Role> myRoleName2ValueMap = new HashMap<String,Role>();
// Flag to indicate if the object has been added in the Relation Service
private Boolean myInRelServFlg = null;
//
// Constructors
//
/** {@collect.stats}
* Creates a {@code RelationSupport} object.
* <P>This constructor has to be used when the RelationSupport object will
* be registered as a MBean by the user, or when creating a user relation
* MBean whose class extends RelationSupport.
* <P>Nothing is done at the Relation Service level, i.e.
* the {@code RelationSupport} object is not added to the
* {@code RelationService} and no checks are performed to
* see if the provided values are correct.
* The object is always created, EXCEPT if:
* <P>- any of the required parameters is {@code null}.
* <P>- the same name is used for two roles.
* <P>To be handled as a relation, the {@code RelationSupport} object has
* to be added to the Relation Service using the Relation Service method
* addRelation().
*
* @param relationId relation identifier, to identify the relation in the
* Relation Service.
* <P>Expected to be unique in the given Relation Service.
* @param relationServiceName ObjectName of the Relation Service where
* the relation will be registered.
* <P>This parameter is required as it is the Relation Service that is
* aware of the definition of the relation type of the given relation,
* so that will be able to check update operations (set).
* @param relationTypeName Name of relation type.
* <P>Expected to have been created in the given Relation Service.
* @param list list of roles (Role objects) to initialize the
* relation. Can be {@code null}.
* <P>Expected to conform to relation info in associated relation type.
*
* @exception InvalidRoleValueException if the same name is used for two
* roles.
* @exception IllegalArgumentException if any of the required parameters
* (relation id, relation service ObjectName, or relation type name) is
* {@code null}.
*/
public RelationSupport(String relationId,
ObjectName relationServiceName,
String relationTypeName,
RoleList list)
throws InvalidRoleValueException,
IllegalArgumentException {
super();
RELATION_LOGGER.entering(RelationSupport.class.getName(),
"RelationSupport");
// Can throw InvalidRoleValueException and IllegalArgumentException
initMembers(relationId,
relationServiceName,
null,
relationTypeName,
list);
RELATION_LOGGER.exiting(RelationSupport.class.getName(),
"RelationSupport");
}
/** {@collect.stats}
* Creates a {@code RelationSupport} object.
* <P>This constructor has to be used when the user relation MBean
* implements the interfaces expected to be supported by a relation by
* delegating to a RelationSupport object.
* <P>This object needs to know the Relation Service expected to handle the
* relation. So it has to know the MBean Server where the Relation Service
* is registered.
* <P>According to a limitation, a relation MBean must be registered in the
* same MBean Server as the Relation Service expected to handle it. So the
* user relation MBean has to be created and registered, and then the
* wrapped RelationSupport object can be created within the identified MBean
* Server.
* <P>Nothing is done at the Relation Service level, i.e.
* the {@code RelationSupport} object is not added to the
* {@code RelationService} and no checks are performed to
* see if the provided values are correct.
* The object is always created, EXCEPT if:
* <P>- any of the required parameters is {@code null}.
* <P>- the same name is used for two roles.
* <P>To be handled as a relation, the {@code RelationSupport} object has
* to be added to the Relation Service using the Relation Service method
* addRelation().
*
* @param relationId relation identifier, to identify the relation in the
* Relation Service.
* <P>Expected to be unique in the given Relation Service.
* @param relationServiceName ObjectName of the Relation Service where
* the relation will be registered.
* <P>This parameter is required as it is the Relation Service that is
* aware of the definition of the relation type of the given relation,
* so that will be able to check update operations (set).
* @param relationServiceMBeanServer MBean Server where the wrapping MBean
* is or will be registered.
* <P>Expected to be the MBean Server where the Relation Service is or will
* be registered.
* @param relationTypeName Name of relation type.
* <P>Expected to have been created in the given Relation Service.
* @param list list of roles (Role objects) to initialize the
* relation. Can be {@code null}.
* <P>Expected to conform to relation info in associated relation type.
*
* @exception InvalidRoleValueException if the same name is used for two
* roles.
* @exception IllegalArgumentException if any of the required parameters
* (relation id, relation service ObjectName, relation service MBeanServer,
* or relation type name) is {@code null}.
*/
public RelationSupport(String relationId,
ObjectName relationServiceName,
MBeanServer relationServiceMBeanServer,
String relationTypeName,
RoleList list)
throws InvalidRoleValueException,
IllegalArgumentException {
super();
if (relationServiceMBeanServer == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationSupport.class.getName(),
"RelationSupport");
// Can throw InvalidRoleValueException and
// IllegalArgumentException
initMembers(relationId,
relationServiceName,
relationServiceMBeanServer,
relationTypeName,
list);
RELATION_LOGGER.exiting(RelationSupport.class.getName(),
"RelationSupport");
}
//
// Relation Interface
//
/** {@collect.stats}
* Retrieves role value for given role name.
* <P>Checks if the role exists and is readable according to the relation
* type.
*
* @param roleName name of role
*
* @return the ArrayList of ObjectName objects being the role value
*
* @exception IllegalArgumentException if null role name
* @exception RoleNotFoundException if:
* <P>- there is no role with given name
* <P>- the role is not readable.
* @exception RelationServiceNotRegisteredException if the Relation
* Service is not registered in the MBean Server
*
* @see #setRole
*/
public List<ObjectName> getRole(String roleName)
throws IllegalArgumentException,
RoleNotFoundException,
RelationServiceNotRegisteredException {
if (roleName == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationSupport.class.getName(),
"getRole", roleName);
// Can throw RoleNotFoundException and
// RelationServiceNotRegisteredException
List<ObjectName> result = cast(
getRoleInt(roleName, false, null, false));
RELATION_LOGGER.exiting(RelationSupport.class.getName(), "getRole");
return result;
}
/** {@collect.stats}
* Retrieves values of roles with given names.
* <P>Checks for each role if it exists and is readable according to the
* relation type.
*
* @param roleNameArray array of names of roles to be retrieved
*
* @return a RoleResult object, including a RoleList (for roles
* successfully retrieved) and a RoleUnresolvedList (for roles not
* retrieved).
*
* @exception IllegalArgumentException if null role name
* @exception RelationServiceNotRegisteredException if the Relation
* Service is not registered in the MBean Server
*
* @see #setRoles
*/
public RoleResult getRoles(String[] roleNameArray)
throws IllegalArgumentException,
RelationServiceNotRegisteredException {
if (roleNameArray == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationSupport.class.getName(), "getRoles");
// Can throw RelationServiceNotRegisteredException
RoleResult result = getRolesInt(roleNameArray, false, null);
RELATION_LOGGER.exiting(RelationSupport.class.getName(), "getRoles");
return result;
}
/** {@collect.stats}
* Returns all roles present in the relation.
*
* @return a RoleResult object, including a RoleList (for roles
* successfully retrieved) and a RoleUnresolvedList (for roles not
* readable).
*
* @exception RelationServiceNotRegisteredException if the Relation
* Service is not registered in the MBean Server
*/
public RoleResult getAllRoles()
throws RelationServiceNotRegisteredException {
RELATION_LOGGER.entering(RelationSupport.class.getName(),
"getAllRoles");
RoleResult result = null;
try {
result = getAllRolesInt(false, null);
} catch (IllegalArgumentException exc) {
// OK : Invalid parameters, ignore...
}
RELATION_LOGGER.exiting(RelationSupport.class.getName(), "getAllRoles");
return result;
}
/** {@collect.stats}
* Returns all roles in the relation without checking read mode.
*
* @return a RoleList
*/
public RoleList retrieveAllRoles() {
RELATION_LOGGER.entering(RelationSupport.class.getName(),
"retrieveAllRoles");
RoleList result;
synchronized(myRoleName2ValueMap) {
result =
new RoleList(new ArrayList<Role>(myRoleName2ValueMap.values()));
}
RELATION_LOGGER.exiting(RelationSupport.class.getName(),
"retrieveAllRoles");
return result;
}
/** {@collect.stats}
* Returns the number of MBeans currently referenced in the given role.
*
* @param roleName name of role
*
* @return the number of currently referenced MBeans in that role
*
* @exception IllegalArgumentException if null role name
* @exception RoleNotFoundException if there is no role with given name
*/
public Integer getRoleCardinality(String roleName)
throws IllegalArgumentException,
RoleNotFoundException {
if (roleName == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationSupport.class.getName(),
"getRoleCardinality", roleName);
// Try to retrieve the role
Role role = null;
synchronized(myRoleName2ValueMap) {
// No null Role is allowed, so direct use of get()
role = (myRoleName2ValueMap.get(roleName));
}
if (role == null) {
int pbType = RoleStatus.NO_ROLE_WITH_NAME;
// Will throw a RoleNotFoundException
//
// Will not throw InvalidRoleValueException, so catch it for the
// compiler
try {
RelationService.throwRoleProblemException(pbType,
roleName);
} catch (InvalidRoleValueException exc) {
// OK : Do not throw InvalidRoleValueException as
// a RoleNotFoundException will be thrown.
}
}
ArrayList roleValue = (ArrayList)(role.getRoleValue());
RELATION_LOGGER.exiting(RelationSupport.class.getName(),
"getRoleCardinality");
return new Integer(roleValue.size());
}
/** {@collect.stats}
* Sets the given role.
* <P>Will check the role according to its corresponding role definition
* provided in relation's relation type
* <P>Will send a notification (RelationNotification with type
* RELATION_BASIC_UPDATE or RELATION_MBEAN_UPDATE, depending if the
* relation is a MBean or not).
*
* @param role role to be set (name and new value)
*
* @exception IllegalArgumentException if null role
* @exception RoleNotFoundException if there is no role with the supplied
* role's name or if the role is not writable (no test on the write access
* mode performed when initializing the role)
* @exception InvalidRoleValueException if value provided for
* role is not valid, i.e.:
* <P>- the number of referenced MBeans in given value is less than
* expected minimum degree
* <P>- the number of referenced MBeans in provided value exceeds expected
* maximum degree
* <P>- one referenced MBean in the value is not an Object of the MBean
* class expected for that role
* <P>- a MBean provided for that role does not exist
* @exception RelationServiceNotRegisteredException if the Relation
* Service is not registered in the MBean Server
* @exception RelationTypeNotFoundException if the relation type has not
* been declared in the Relation Service
* @exception RelationNotFoundException if the relation has not been
* added in the Relation Service.
*
* @see #getRole
*/
public void setRole(Role role)
throws IllegalArgumentException,
RoleNotFoundException,
RelationTypeNotFoundException,
InvalidRoleValueException,
RelationServiceNotRegisteredException,
RelationNotFoundException {
if (role == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationSupport.class.getName(),
"setRole", role);
// Will return null :)
Object result = setRoleInt(role, false, null, false);
RELATION_LOGGER.exiting(RelationSupport.class.getName(), "setRole");
return;
}
/** {@collect.stats}
* Sets the given roles.
* <P>Will check the role according to its corresponding role definition
* provided in relation's relation type
* <P>Will send one notification (RelationNotification with type
* RELATION_BASIC_UPDATE or RELATION_MBEAN_UPDATE, depending if the
* relation is a MBean or not) per updated role.
*
* @param list list of roles to be set
*
* @return a RoleResult object, including a RoleList (for roles
* successfully set) and a RoleUnresolvedList (for roles not
* set).
*
* @exception IllegalArgumentException if null role list
* @exception RelationServiceNotRegisteredException if the Relation
* Service is not registered in the MBean Server
* @exception RelationTypeNotFoundException if the relation type has not
* been declared in the Relation Service.
* @exception RelationNotFoundException if the relation MBean has not been
* added in the Relation Service.
*
* @see #getRoles
*/
public RoleResult setRoles(RoleList list)
throws IllegalArgumentException,
RelationServiceNotRegisteredException,
RelationTypeNotFoundException,
RelationNotFoundException {
if (list == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationSupport.class.getName(),
"setRoles", list);
RoleResult result = setRolesInt(list, false, null);
RELATION_LOGGER.exiting(RelationSupport.class.getName(), "setRoles");
return result;
}
/** {@collect.stats}
* Callback used by the Relation Service when a MBean referenced in a role
* is unregistered.
* <P>The Relation Service will call this method to let the relation
* take action to reflect the impact of such unregistration.
* <P>BEWARE. the user is not expected to call this method.
* <P>Current implementation is to set the role with its current value
* (list of ObjectNames of referenced MBeans) without the unregistered
* one.
*
* @param objectName ObjectName of unregistered MBean
* @param roleName name of role where the MBean is referenced
*
* @exception IllegalArgumentException if null parameter
* @exception RoleNotFoundException if role does not exist in the
* relation or is not writable
* @exception InvalidRoleValueException if role value does not conform to
* the associated role info (this will never happen when called from the
* Relation Service)
* @exception RelationServiceNotRegisteredException if the Relation
* Service is not registered in the MBean Server
* @exception RelationTypeNotFoundException if the relation type has not
* been declared in the Relation Service.
* @exception RelationNotFoundException if this method is called for a
* relation MBean not added in the Relation Service.
*/
public void handleMBeanUnregistration(ObjectName objectName,
String roleName)
throws IllegalArgumentException,
RoleNotFoundException,
InvalidRoleValueException,
RelationServiceNotRegisteredException,
RelationTypeNotFoundException,
RelationNotFoundException {
if (objectName == null || roleName == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationSupport.class.getName(),
"handleMBeanUnregistration",
new Object[]{objectName, roleName});
// Can throw RoleNotFoundException, InvalidRoleValueException,
// or RelationTypeNotFoundException
handleMBeanUnregistrationInt(objectName,
roleName,
false,
null);
RELATION_LOGGER.exiting(RelationSupport.class.getName(),
"handleMBeanUnregistration");
return;
}
/** {@collect.stats}
* Retrieves MBeans referenced in the various roles of the relation.
*
* @return a HashMap mapping:
* <P> ObjectName -> ArrayList of String (role names)
*/
public Map<ObjectName,List<String>> getReferencedMBeans() {
RELATION_LOGGER.entering(RelationSupport.class.getName(),
"getReferencedMBeans");
Map<ObjectName,List<String>> refMBeanMap =
new HashMap<ObjectName,List<String>>();
synchronized(myRoleName2ValueMap) {
for (Role currRole : myRoleName2ValueMap.values()) {
String currRoleName = currRole.getRoleName();
// Retrieves ObjectNames of MBeans referenced in current role
List<ObjectName> currRefMBeanList = currRole.getRoleValue();
for (ObjectName currRoleObjName : currRefMBeanList) {
// Sees if current MBean has been already referenced in
// roles already seen
List<String> mbeanRoleNameList =
refMBeanMap.get(currRoleObjName);
boolean newRefFlg = false;
if (mbeanRoleNameList == null) {
newRefFlg = true;
mbeanRoleNameList = new ArrayList<String>();
}
mbeanRoleNameList.add(currRoleName);
if (newRefFlg) {
refMBeanMap.put(currRoleObjName, mbeanRoleNameList);
}
}
}
}
RELATION_LOGGER.exiting(RelationSupport.class.getName(),
"getReferencedMBeans");
return refMBeanMap;
}
/** {@collect.stats}
* Returns name of associated relation type.
*/
public String getRelationTypeName() {
return myRelTypeName;
}
/** {@collect.stats}
* Returns ObjectName of the Relation Service handling the relation.
*
* @return the ObjectName of the Relation Service.
*/
public ObjectName getRelationServiceName() {
return myRelServiceName;
}
/** {@collect.stats}
* Returns relation identifier (used to uniquely identify the relation
* inside the Relation Service).
*
* @return the relation id.
*/
public String getRelationId() {
return myRelId;
}
//
// MBeanRegistration interface
//
// Pre-registration: retrieves the MBean Server (useful to access to the
// Relation Service)
// This is the way to retrieve the MBean Server when the relation object is
// a MBean created by the user outside of the Relation Service.
//
// No exception thrown.
public ObjectName preRegister(MBeanServer server,
ObjectName name)
throws Exception {
myRelServiceMBeanServer = server;
return name;
}
// Post-registration: does nothing
public void postRegister(Boolean registrationDone) {
return;
}
// Pre-unregistration: does nothing
public void preDeregister()
throws Exception {
return;
}
// Post-unregistration: does nothing
public void postDeregister() {
return;
}
//
// Others
//
/** {@collect.stats}
* Returns an internal flag specifying if the object is still handled by
* the Relation Service.
*/
public Boolean isInRelationService() {
Boolean result = null;
synchronized(myInRelServFlg) {
result = Boolean.valueOf(myInRelServFlg.booleanValue());
}
return result;
}
public void setRelationServiceManagementFlag(Boolean flag)
throws IllegalArgumentException {
if (flag == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
synchronized(myInRelServFlg) {
myInRelServFlg = Boolean.valueOf(flag.booleanValue());
}
return;
}
//
// Misc
//
// Gets the role with given name
// Checks if the role exists and is readable according to the relation
// type.
//
// This method is called in getRole() above.
// It is also called in the Relation Service getRole() method.
// It is also called in getRolesInt() below (used for getRoles() above
// and for Relation Service getRoles() method).
//
// Depending on parameters reflecting its use (either in the scope of
// getting a single role or of getting several roles), will return:
// - in case of success:
// - for single role retrieval, the ArrayList of ObjectNames being the
// role value
// - for multi-role retrieval, the Role object itself
// - in case of failure (except critical exceptions):
// - for single role retrieval, if role does not exist or is not
// readable, an RoleNotFoundException exception is raised
// - for multi-role retrieval, a RoleUnresolved object
//
// -param roleName name of role to be retrieved
// -param relationServCallFlg true if call from the Relation Service; this
// will happen if the current RelationSupport object has been created by
// the Relation Service (via createRelation()) method, so direct access is
// possible.
// -param relationServ reference to Relation Service object, if object
// created by Relation Service.
// -param multiRoleFlg true if getting the role in the scope of a
// multiple retrieval.
//
// -return:
// - for single role retrieval (multiRoleFlg false):
// - ArrayList of ObjectName objects, value of role with given name, if
// the role can be retrieved
// - raise a RoleNotFoundException exception else
// - for multi-role retrieval (multiRoleFlg true):
// - the Role object for given role name if role can be retrieved
// - a RoleUnresolved object with problem.
//
// -exception IllegalArgumentException if null parameter
// -exception RoleNotFoundException if multiRoleFlg is false and:
// - there is no role with given name
// or
// - the role is not readable.
// -exception RelationServiceNotRegisteredException if the Relation
// Service is not registered in the MBean Server
Object getRoleInt(String roleName,
boolean relationServCallFlg,
RelationService relationServ,
boolean multiRoleFlg)
throws IllegalArgumentException,
RoleNotFoundException,
RelationServiceNotRegisteredException {
if (roleName == null ||
(relationServCallFlg && relationServ == null)) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationSupport.class.getName(),
"getRoleInt", roleName);
int pbType = 0;
Role role = null;
synchronized(myRoleName2ValueMap) {
// No null Role is allowed, so direct use of get()
role = (myRoleName2ValueMap.get(roleName));
}
if (role == null) {
pbType = RoleStatus.NO_ROLE_WITH_NAME;
} else {
// Checks if the role is readable
Integer status = null;
if (relationServCallFlg) {
// Call from the Relation Service, so direct access to it,
// avoiding MBean Server
// Shall not throw a RelationTypeNotFoundException
try {
status = relationServ.checkRoleReading(roleName,
myRelTypeName);
} catch (RelationTypeNotFoundException exc) {
throw new RuntimeException(exc.getMessage());
}
} else {
// Call from getRole() method above
// So we have a MBean. We must access the Relation Service
// via the MBean Server.
Object[] params = new Object[2];
params[0] = roleName;
params[1] = myRelTypeName;
String[] signature = new String[2];
signature[0] = "java.lang.String";
signature[1] = "java.lang.String";
// Can throw InstanceNotFoundException if the Relation
// Service is not registered (to be catched in any case and
// transformed into RelationServiceNotRegisteredException).
//
// Shall not throw a MBeanException, or a ReflectionException
// or an InstanceNotFoundException
try {
status = (Integer)
(myRelServiceMBeanServer.invoke(myRelServiceName,
"checkRoleReading",
params,
signature));
} catch (MBeanException exc1) {
throw new RuntimeException("incorrect relation type");
} catch (ReflectionException exc2) {
throw new RuntimeException(exc2.getMessage());
} catch (InstanceNotFoundException exc3) {
throw new RelationServiceNotRegisteredException(
exc3.getMessage());
}
}
pbType = status.intValue();
}
Object result = null;
if (pbType == 0) {
// Role can be retrieved
if (!(multiRoleFlg)) {
// Single role retrieved: returns its value
// Note: no need to test if role value (list) not null before
// cloning, null value not allowed, empty list if
// nothing.
result = (ArrayList)
(((ArrayList)(role.getRoleValue())).clone());
} else {
// Role retrieved during multi-role retrieval: returns the
// role
result = (Role)(role.clone());
}
} else {
// Role not retrieved
if (!(multiRoleFlg)) {
// Problem when retrieving a simple role: either role not
// found or not readable, so raises a RoleNotFoundException.
try {
RelationService.throwRoleProblemException(pbType,
roleName);
// To keep compiler happy :)
return null;
} catch (InvalidRoleValueException exc) {
throw new RuntimeException(exc.getMessage());
}
} else {
// Problem when retrieving a role in a multi-role retrieval:
// returns a RoleUnresolved object
result = new RoleUnresolved(roleName, null, pbType);
}
}
RELATION_LOGGER.exiting(RelationSupport.class.getName(), "getRoleInt");
return result;
}
// Gets the given roles
// For each role, verifies if the role exists and is readable according to
// the relation type.
//
// This method is called in getRoles() above and in Relation Service
// getRoles() method.
//
// -param roleNameArray array of names of roles to be retrieved
// -param relationServCallFlg true if call from the Relation Service; this
// will happen if the current RelationSupport object has been created by
// the Relation Service (via createRelation()) method, so direct access is
// possible.
// -param relationServ reference to Relation Service object, if object
// created by Relation Service.
//
// -return a RoleResult object
//
// -exception IllegalArgumentException if null parameter
// -exception RelationServiceNotRegisteredException if the Relation
// Service is not registered in the MBean Server
RoleResult getRolesInt(String[] roleNameArray,
boolean relationServCallFlg,
RelationService relationServ)
throws IllegalArgumentException,
RelationServiceNotRegisteredException {
if (roleNameArray == null ||
(relationServCallFlg && relationServ == null)) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationSupport.class.getName(),
"getRolesInt");
RoleList roleList = new RoleList();
RoleUnresolvedList roleUnresList = new RoleUnresolvedList();
for (int i = 0; i < roleNameArray.length; i++) {
String currRoleName = roleNameArray[i];
Object currResult = null;
// Can throw RelationServiceNotRegisteredException
//
// RoleNotFoundException: not possible but catch it for compiler :)
try {
currResult = getRoleInt(currRoleName,
relationServCallFlg,
relationServ,
true);
} catch (RoleNotFoundException exc) {
return null; // :)
}
if (currResult instanceof Role) {
// Can throw IllegalArgumentException if role is null
// (normally should not happen :(
try {
roleList.add((Role)currResult);
} catch (IllegalArgumentException exc) {
throw new RuntimeException(exc.getMessage());
}
} else if (currResult instanceof RoleUnresolved) {
// Can throw IllegalArgumentException if role is null
// (normally should not happen :(
try {
roleUnresList.add((RoleUnresolved)currResult);
} catch (IllegalArgumentException exc) {
throw new RuntimeException(exc.getMessage());
}
}
}
RoleResult result = new RoleResult(roleList, roleUnresList);
RELATION_LOGGER.exiting(RelationSupport.class.getName(),
"getRolesInt");
return result;
}
// Returns all roles present in the relation
//
// -return a RoleResult object, including a RoleList (for roles
// successfully retrieved) and a RoleUnresolvedList (for roles not
// readable).
//
// -exception IllegalArgumentException if null parameter
// -exception RelationServiceNotRegisteredException if the Relation
// Service is not registered in the MBean Server
//
RoleResult getAllRolesInt(boolean relationServCallFlg,
RelationService relationServ)
throws IllegalArgumentException,
RelationServiceNotRegisteredException {
if (relationServCallFlg && relationServ == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationSupport.class.getName(),
"getAllRolesInt");
List<String> roleNameList;
synchronized(myRoleName2ValueMap) {
roleNameList =
new ArrayList<String>(myRoleName2ValueMap.keySet());
}
String[] roleNames = new String[roleNameList.size()];
roleNameList.toArray(roleNames);
RoleResult result = getRolesInt(roleNames,
relationServCallFlg,
relationServ);
RELATION_LOGGER.exiting(RelationSupport.class.getName(),
"getAllRolesInt");
return result;
}
// Sets the role with given value
//
// This method is called in setRole() above.
// It is also called by the Relation Service setRole() method.
// It is also called in setRolesInt() method below (used in setRoles()
// above and in RelationService setRoles() method).
//
// Will check the role according to its corresponding role definition
// provided in relation's relation type
// Will send a notification (RelationNotification with type
// RELATION_BASIC_UPDATE or RELATION_MBEAN_UPDATE, depending if the
// relation is a MBean or not) if not initialization of role.
//
// -param aRole role to be set (name and new value)
// -param relationServCallFlg true if call from the Relation Service; this
// will happen if the current RelationSupport object has been created by
// the Relation Service (via createRelation()) method, so direct access is
// possible.
// -param relationServ reference to Relation Service object, if internal
// relation
// -param multiRoleFlg true if getting the role in the scope of a
// multiple retrieval.
//
// -return (except other "critical" exceptions):
// - for single role retrieval (multiRoleFlg false):
// - null if the role has been set
// - raise an InvalidRoleValueException
// else
// - for multi-role retrieval (multiRoleFlg true):
// - the Role object for given role name if role has been set
// - a RoleUnresolved object with problem else.
//
// -exception IllegalArgumentException if null parameter
// -exception RoleNotFoundException if multiRoleFlg is false and:
// - internal relation and the role does not exist
// or
// - existing role (i.e. not initializing it) and the role is not
// writable.
// -exception InvalidRoleValueException ifmultiRoleFlg is false and
// value provided for:
// - the number of referenced MBeans in given value is less than
// expected minimum degree
// or
// - the number of referenced MBeans in provided value exceeds expected
// maximum degree
// or
// - one referenced MBean in the value is not an Object of the MBean
// class expected for that role
// or
// - a MBean provided for that role does not exist
// -exception RelationServiceNotRegisteredException if the Relation
// Service is not registered in the MBean Server
// -exception RelationTypeNotFoundException if relation type unknown
// -exception RelationNotFoundException if a relation MBean has not been
// added in the Relation Service
Object setRoleInt(Role aRole,
boolean relationServCallFlg,
RelationService relationServ,
boolean multiRoleFlg)
throws IllegalArgumentException,
RoleNotFoundException,
InvalidRoleValueException,
RelationServiceNotRegisteredException,
RelationTypeNotFoundException,
RelationNotFoundException {
if (aRole == null ||
(relationServCallFlg && relationServ == null)) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationSupport.class.getName(),
"setRoleInt", new Object[] {aRole, relationServCallFlg,
relationServ, multiRoleFlg});
String roleName = aRole.getRoleName();
int pbType = 0;
// Checks if role exists in the relation
// No error if the role does not exist in the relation, to be able to
// handle initialization of role when creating the relation
// (roles provided in the RoleList parameter are directly set but
// roles automatically initialized are set using setRole())
Role role = null;
synchronized(myRoleName2ValueMap) {
role = (myRoleName2ValueMap.get(roleName));
}
List<ObjectName> oldRoleValue;
Boolean initFlg = null;
if (role == null) {
initFlg = true;
oldRoleValue = new ArrayList<ObjectName>();
} else {
initFlg = false;
oldRoleValue = role.getRoleValue();
}
// Checks if the role can be set: is writable (except if
// initialization) and correct value
try {
Integer status = null;
if (relationServCallFlg) {
// Call from the Relation Service, so direct access to it,
// avoiding MBean Server
//
// Shall not raise a RelationTypeNotFoundException
status = relationServ.checkRoleWriting(aRole,
myRelTypeName,
initFlg);
} else {
// Call from setRole() method above
// So we have a MBean. We must access the Relation Service
// via the MBean Server.
Object[] params = new Object[3];
params[0] = aRole;
params[1] = myRelTypeName;
params[2] = initFlg;
String[] signature = new String[3];
signature[0] = "javax.management.relation.Role";
signature[1] = "java.lang.String";
signature[2] = "java.lang.Boolean";
// Can throw InstanceNotFoundException if the Relation Service
// is not registered (to be transformed into
// RelationServiceNotRegisteredException in any case).
//
// Can throw a MBeanException wrapping a
// RelationTypeNotFoundException:
// throw wrapped exception.
//
// Shall not throw a ReflectionException
status = (Integer)
(myRelServiceMBeanServer.invoke(myRelServiceName,
"checkRoleWriting",
params,
signature));
}
pbType = status.intValue();
} catch (MBeanException exc2) {
// Retrieves underlying exception
Exception wrappedExc = exc2.getTargetException();
if (wrappedExc instanceof RelationTypeNotFoundException) {
throw ((RelationTypeNotFoundException)wrappedExc);
} else {
throw new RuntimeException(wrappedExc.getMessage());
}
} catch (ReflectionException exc3) {
throw new RuntimeException(exc3.getMessage());
} catch (RelationTypeNotFoundException exc4) {
throw new RuntimeException(exc4.getMessage());
} catch (InstanceNotFoundException exc5) {
throw new RelationServiceNotRegisteredException(exc5.getMessage());
}
Object result = null;
if (pbType == 0) {
// Role can be set
if (!(initFlg.booleanValue())) {
// Not initializing the role
// If role being initialized:
// - do not send an update notification
// - do not try to update internal map of Relation Service
// listing referenced MBeans, as role is initialized to an
// empty list
// Sends a notification (RelationNotification)
// Can throw a RelationNotFoundException
sendRoleUpdateNotification(aRole,
oldRoleValue,
relationServCallFlg,
relationServ);
// Updates the role map of the Relation Service
// Can throw RelationNotFoundException
updateRelationServiceMap(aRole,
oldRoleValue,
relationServCallFlg,
relationServ);
}
// Sets the role
synchronized(myRoleName2ValueMap) {
myRoleName2ValueMap.put(roleName,
(Role)(aRole.clone()));
}
// Single role set: returns null: nothing to set in result
if (multiRoleFlg) {
// Multi-roles retrieval: returns the role
result = aRole;
}
} else {
// Role not set
if (!(multiRoleFlg)) {
// Problem when setting a simple role: either role not
// found, not writable, or incorrect value:
// raises appropriate exception, RoleNotFoundException or
// InvalidRoleValueException
RelationService.throwRoleProblemException(pbType,
roleName);
// To keep compiler happy :)
return null;
} else {
// Problem when retrieving a role in a multi-role retrieval:
// returns a RoleUnresolved object
result = new RoleUnresolved(roleName,
aRole.getRoleValue(),
pbType);
}
}
RELATION_LOGGER.exiting(RelationSupport.class.getName(), "setRoleInt");
return result;
}
// Requires the Relation Service to send a notification
// RelationNotification, with type being either:
// - RelationNotification.RELATION_BASIC_UPDATE if the updated relation is
// a relation internal to the Relation Service
// - RelationNotification.RELATION_MBEAN_UPDATE if the updated relation is
// a relation MBean.
//
// -param newRole new role
// -param oldRoleValue old role value (ArrayList of ObjectNames)
// -param relationServCallFlg true if call from the Relation Service; this
// will happen if the current RelationSupport object has been created by
// the Relation Service (via createRelation()) method, so direct access is
// possible.
// -param relationServ reference to Relation Service object, if object
// created by Relation Service.
//
// -exception IllegalArgumentException if null parameter provided
// -exception RelationServiceNotRegisteredException if the Relation
// Service is not registered in the MBean Server
// -exception RelationNotFoundException if:
// - relation MBean
// and
// - it has not been added into the Relation Service
private void sendRoleUpdateNotification(Role newRole,
List<ObjectName> oldRoleValue,
boolean relationServCallFlg,
RelationService relationServ)
throws IllegalArgumentException,
RelationServiceNotRegisteredException,
RelationNotFoundException {
if (newRole == null ||
oldRoleValue == null ||
(relationServCallFlg && relationServ == null)) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationSupport.class.getName(),
"sendRoleUpdateNotification", new Object[] {newRole,
oldRoleValue, relationServCallFlg, relationServ});
if (relationServCallFlg) {
// Direct call to the Relation Service
// Shall not throw a RelationNotFoundException for an internal
// relation
try {
relationServ.sendRoleUpdateNotification(myRelId,
newRole,
oldRoleValue);
} catch (RelationNotFoundException exc) {
throw new RuntimeException(exc.getMessage());
}
} else {
Object[] params = new Object[3];
params[0] = myRelId;
params[1] = newRole;
params[2] = ((ArrayList)oldRoleValue);
String[] signature = new String[3];
signature[0] = "java.lang.String";
signature[1] = "javax.management.relation.Role";
signature[2] = "java.util.List";
// Can throw InstanceNotFoundException if the Relation Service
// is not registered (to be transformed).
//
// Can throw a MBeanException wrapping a
// RelationNotFoundException (to be raised in any case): wrapped
// exception to be thrown
//
// Shall not throw a ReflectionException
try {
myRelServiceMBeanServer.invoke(myRelServiceName,
"sendRoleUpdateNotification",
params,
signature);
} catch (ReflectionException exc1) {
throw new RuntimeException(exc1.getMessage());
} catch (InstanceNotFoundException exc2) {
throw new RelationServiceNotRegisteredException(
exc2.getMessage());
} catch (MBeanException exc3) {
Exception wrappedExc = exc3.getTargetException();
if (wrappedExc instanceof RelationNotFoundException) {
throw ((RelationNotFoundException)wrappedExc);
} else {
throw new RuntimeException(wrappedExc.getMessage());
}
}
}
RELATION_LOGGER.exiting(RelationSupport.class.getName(),
"sendRoleUpdateNotification");
return;
}
// Requires the Relation Service to update its internal map handling
// MBeans referenced in relations.
// The Relation Service will also update its recording as a listener to
// be informed about unregistration of new referenced MBeans, and no longer
// informed of MBeans no longer referenced.
//
// -param newRole new role
// -param oldRoleValue old role value (ArrayList of ObjectNames)
// -param relationServCallFlg true if call from the Relation Service; this
// will happen if the current RelationSupport object has been created by
// the Relation Service (via createRelation()) method, so direct access is
// possible.
// -param relationServ reference to Relation Service object, if object
// created by Relation Service.
//
// -exception IllegalArgumentException if null parameter
// -exception RelationServiceNotRegisteredException if the Relation
// Service is not registered in the MBean Server
// -exception RelationNotFoundException if:
// - relation MBean
// and
// - the relation is not added in the Relation Service
private void updateRelationServiceMap(Role newRole,
List<ObjectName> oldRoleValue,
boolean relationServCallFlg,
RelationService relationServ)
throws IllegalArgumentException,
RelationServiceNotRegisteredException,
RelationNotFoundException {
if (newRole == null ||
oldRoleValue == null ||
(relationServCallFlg && relationServ == null)) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationSupport.class.getName(),
"updateRelationServiceMap", new Object[] {newRole,
oldRoleValue, relationServCallFlg, relationServ});
if (relationServCallFlg) {
// Direct call to the Relation Service
// Shall not throw a RelationNotFoundException
try {
relationServ.updateRoleMap(myRelId,
newRole,
oldRoleValue);
} catch (RelationNotFoundException exc) {
throw new RuntimeException(exc.getMessage());
}
} else {
Object[] params = new Object[3];
params[0] = myRelId;
params[1] = newRole;
params[2] = oldRoleValue;
String[] signature = new String[3];
signature[0] = "java.lang.String";
signature[1] = "javax.management.relation.Role";
signature[2] = "java.util.List";
// Can throw InstanceNotFoundException if the Relation Service
// is not registered (to be transformed).
// Can throw a MBeanException wrapping a RelationNotFoundException:
// wrapped exception to be thrown
//
// Shall not throw a ReflectionException
try {
myRelServiceMBeanServer.invoke(myRelServiceName,
"updateRoleMap",
params,
signature);
} catch (ReflectionException exc1) {
throw new RuntimeException(exc1.getMessage());
} catch (InstanceNotFoundException exc2) {
throw new
RelationServiceNotRegisteredException(exc2.getMessage());
} catch (MBeanException exc3) {
Exception wrappedExc = exc3.getTargetException();
if (wrappedExc instanceof RelationNotFoundException) {
throw ((RelationNotFoundException)wrappedExc);
} else {
throw new RuntimeException(wrappedExc.getMessage());
}
}
}
RELATION_LOGGER.exiting(RelationSupport.class.getName(),
"updateRelationServiceMap");
return;
}
// Sets the given roles
// For each role:
// - will check the role according to its corresponding role definition
// provided in relation's relation type
// - will send a notification (RelationNotification with type
// RELATION_BASIC_UPDATE or RELATION_MBEAN_UPDATE, depending if the
// relation is a MBean or not) for each updated role.
//
// This method is called in setRoles() above and in Relation Service
// setRoles() method.
//
// -param list list of roles to be set
// -param relationServCallFlg true if call from the Relation Service; this
// will happen if the current RelationSupport object has been created by
// the Relation Service (via createRelation()) method, so direct access is
// possible.
// -param relationServ reference to Relation Service object, if object
// created by Relation Service.
//
// -return a RoleResult object
//
// -exception IllegalArgumentException if null parameter
// -exception RelationServiceNotRegisteredException if the Relation
// Service is not registered in the MBean Server
// -exception RelationTypeNotFoundException if:
// - relation MBean
// and
// - unknown relation type
// -exception RelationNotFoundException if:
// - relation MBean
// and
// - not added in the RS
RoleResult setRolesInt(RoleList list,
boolean relationServCallFlg,
RelationService relationServ)
throws IllegalArgumentException,
RelationServiceNotRegisteredException,
RelationTypeNotFoundException,
RelationNotFoundException {
if (list == null ||
(relationServCallFlg && relationServ == null)) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationSupport.class.getName(),
"setRolesInt",
new Object[] {list, relationServCallFlg, relationServ});
RoleList roleList = new RoleList();
RoleUnresolvedList roleUnresList = new RoleUnresolvedList();
for (Iterator roleIter = list.iterator();
roleIter.hasNext();) {
Role currRole = (Role)(roleIter.next());
Object currResult = null;
// Can throw:
// RelationServiceNotRegisteredException,
// RelationTypeNotFoundException
//
// Will not throw, due to parameters, RoleNotFoundException or
// InvalidRoleValueException, but catch them to keep compiler
// happy
try {
currResult = setRoleInt(currRole,
relationServCallFlg,
relationServ,
true);
} catch (RoleNotFoundException exc1) {
// OK : Do not throw a RoleNotFoundException.
} catch (InvalidRoleValueException exc2) {
// OK : Do not throw an InvalidRoleValueException.
}
if (currResult instanceof Role) {
// Can throw IllegalArgumentException if role is null
// (normally should not happen :(
try {
roleList.add((Role)currResult);
} catch (IllegalArgumentException exc) {
throw new RuntimeException(exc.getMessage());
}
} else if (currResult instanceof RoleUnresolved) {
// Can throw IllegalArgumentException if role is null
// (normally should not happen :(
try {
roleUnresList.add((RoleUnresolved)currResult);
} catch (IllegalArgumentException exc) {
throw new RuntimeException(exc.getMessage());
}
}
}
RoleResult result = new RoleResult(roleList, roleUnresList);
RELATION_LOGGER.exiting(RelationSupport.class.getName(), "setRolesInt");
return result;
}
// Initializes all members
//
// -param relationId relation identifier, to identify the relation in the
// Relation Service.
// Expected to be unique in the given Relation Service.
// -param relationServiceName ObjectName of the Relation Service where
// the relation will be registered.
// It is required as this is the Relation Service that is aware of the
// definition of the relation type of given relation, so that will be able
// to check update operations (set). Direct access via the Relation
// Service (RelationService.setRole()) do not need this information but
// as any user relation is a MBean, setRole() is part of its management
// interface and can be called directly on the user relation MBean. So the
// user relation MBean must be aware of the Relation Service where it will
// be added.
// -param relationTypeName Name of relation type.
// Expected to have been created in given Relation Service.
// -param list list of roles (Role objects) to initialized the
// relation. Can be null.
// Expected to conform to relation info in associated relation type.
//
// -exception InvalidRoleValueException if the same name is used for two
// roles.
// -exception IllegalArgumentException if a required value (Relation
// Service Object Name, etc.) is not provided as parameter.
private void initMembers(String relationId,
ObjectName relationServiceName,
MBeanServer relationServiceMBeanServer,
String relationTypeName,
RoleList list)
throws InvalidRoleValueException,
IllegalArgumentException {
if (relationId == null ||
relationServiceName == null ||
relationTypeName == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationSupport.class.getName(),
"initMembers", new Object[] {relationId, relationServiceName,
relationServiceMBeanServer, relationTypeName, list});
myRelId = relationId;
myRelServiceName = relationServiceName;
myRelServiceMBeanServer = relationServiceMBeanServer;
myRelTypeName = relationTypeName;
// Can throw InvalidRoleValueException
initRoleMap(list);
myInRelServFlg = Boolean.FALSE;
RELATION_LOGGER.exiting(RelationSupport.class.getName(), "initMembers");
return;
}
// Initialize the internal role map from given RoleList parameter
//
// -param list role list. Can be null.
// As it is a RoleList object, it cannot include null (rejected).
//
// -exception InvalidRoleValueException if the same role name is used for
// several roles.
//
private void initRoleMap(RoleList list)
throws InvalidRoleValueException {
if (list == null) {
return;
}
RELATION_LOGGER.entering(RelationSupport.class.getName(),
"initRoleMap", list);
synchronized(myRoleName2ValueMap) {
for (Iterator roleIter = list.iterator();
roleIter.hasNext();) {
// No need to check if role is null, it is not allowed to store
// a null role in a RoleList :)
Role currRole = (Role)(roleIter.next());
String currRoleName = currRole.getRoleName();
if (myRoleName2ValueMap.containsKey(currRoleName)) {
// Role already provided in current list
StringBuilder excMsgStrB = new StringBuilder("Role name ");
excMsgStrB.append(currRoleName);
excMsgStrB.append(" used for two roles.");
throw new InvalidRoleValueException(excMsgStrB.toString());
}
myRoleName2ValueMap.put(currRoleName,
(Role)(currRole.clone()));
}
}
RELATION_LOGGER.exiting(RelationSupport.class.getName(), "initRoleMap");
return;
}
// Callback used by the Relation Service when a MBean referenced in a role
// is unregistered.
// The Relation Service will call this method to let the relation
// take action to reflect the impact of such unregistration.
// Current implementation is to set the role with its current value
// (list of ObjectNames of referenced MBeans) without the unregistered
// one.
//
// -param objectName ObjectName of unregistered MBean
// -param roleName name of role where the MBean is referenced
// -param relationServCallFlg true if call from the Relation Service; this
// will happen if the current RelationSupport object has been created by
// the Relation Service (via createRelation()) method, so direct access is
// possible.
// -param relationServ reference to Relation Service object, if internal
// relation
//
// -exception IllegalArgumentException if null parameter
// -exception RoleNotFoundException if:
// - the role does not exist
// or
// - role not writable.
// -exception InvalidRoleValueException if value provided for:
// - the number of referenced MBeans in given value is less than
// expected minimum degree
// or
// - the number of referenced MBeans in provided value exceeds expected
// maximum degree
// or
// - one referenced MBean in the value is not an Object of the MBean
// class expected for that role
// or
// - a MBean provided for that role does not exist
// -exception RelationServiceNotRegisteredException if the Relation
// Service is not registered in the MBean Server
// -exception RelationTypeNotFoundException if unknown relation type
// -exception RelationNotFoundException if current relation has not been
// added in the RS
void handleMBeanUnregistrationInt(ObjectName objectName,
String roleName,
boolean relationServCallFlg,
RelationService relationServ)
throws IllegalArgumentException,
RoleNotFoundException,
InvalidRoleValueException,
RelationServiceNotRegisteredException,
RelationTypeNotFoundException,
RelationNotFoundException {
if (objectName == null ||
roleName == null ||
(relationServCallFlg && relationServ == null)) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationSupport.class.getName(),
"handleMBeanUnregistrationInt", new Object[] {objectName,
roleName, relationServCallFlg, relationServ});
// Retrieves current role value
Role role = null;
synchronized(myRoleName2ValueMap) {
role = (myRoleName2ValueMap.get(roleName));
}
if (role == null) {
StringBuilder excMsgStrB = new StringBuilder();
String excMsg = "No role with name ";
excMsgStrB.append(excMsg);
excMsgStrB.append(roleName);
throw new RoleNotFoundException(excMsgStrB.toString());
}
List<ObjectName> currRoleValue = role.getRoleValue();
// Note: no need to test if list not null before cloning, null value
// not allowed for role value.
List<ObjectName> newRoleValue = new ArrayList<ObjectName>(currRoleValue);
newRoleValue.remove(objectName);
Role newRole = new Role(roleName, newRoleValue);
// Can throw InvalidRoleValueException,
// RelationTypeNotFoundException
// (RoleNotFoundException already detected)
Object result =
setRoleInt(newRole, relationServCallFlg, relationServ, false);
RELATION_LOGGER.exiting(RelationSupport.class.getName(),
"handleMBeanUnregistrationInt");
return;
}
}
| Java |
/*
* Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management.relation;
import static com.sun.jmx.mbeanserver.Util.cast;
import static com.sun.jmx.defaults.JmxProperties.RELATION_LOGGER;
import com.sun.jmx.mbeanserver.GetPropertyAction;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamField;
import java.security.AccessController;
import java.util.List;
import java.util.Vector;
import javax.management.MBeanServerNotification;
import javax.management.Notification;
import javax.management.NotificationFilterSupport;
import javax.management.ObjectName;
import java.util.List;
import java.util.logging.Level;
import java.util.Vector;
/** {@collect.stats}
* Filter for {@link MBeanServerNotification}.
* This filter filters MBeanServerNotification notifications by
* selecting the ObjectNames of interest and the operations (registration,
* unregistration, both) of interest (corresponding to notification
* types).
*
* <p>The <b>serialVersionUID</b> of this class is <code>2605900539589789736L</code>.
*
* @since 1.5
*/
@SuppressWarnings("serial") // serialVersionUID must be constant
public class MBeanServerNotificationFilter extends NotificationFilterSupport {
// 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 = 6001782699077323605L;
//
// Serial version for new serial form
private static final long newSerialVersionUID = 2605900539589789736L;
//
// Serializable fields in old serial form
private static final ObjectStreamField[] oldSerialPersistentFields =
{
new ObjectStreamField("mySelectObjNameList", Vector.class),
new ObjectStreamField("myDeselectObjNameList", Vector.class)
};
//
// Serializable fields in new serial form
private static final ObjectStreamField[] newSerialPersistentFields =
{
new ObjectStreamField("selectedNames", List.class),
new ObjectStreamField("deselectedNames", List.class)
};
//
// Actual serial version and serial form
private static final long serialVersionUID;
/** {@collect.stats}
* @serialField selectedNames List List of {@link ObjectName}s of interest
* <ul>
* <li><code>null</code> means that all {@link ObjectName}s are implicitly selected
* (check for explicit deselections)</li>
* <li>Empty vector means that no {@link ObjectName} is explicitly selected</li>
* </ul>
* @serialField deselectedNames List List of {@link ObjectName}s with no interest
* <ul>
* <li><code>null</code> means that all {@link ObjectName}s are implicitly deselected
* (check for explicit selections))</li>
* <li>Empty vector means that no {@link ObjectName} is explicitly deselected</li>
* </ul>
*/
private static final ObjectStreamField[] serialPersistentFields;
private static boolean compat = false;
static {
try {
GetPropertyAction act = new GetPropertyAction("jmx.serial.form");
String form = AccessController.doPrivileged(act);
compat = (form != null && form.equals("1.0"));
} catch (Exception e) {
// OK : Too bad, no compat with 1.0
}
if (compat) {
serialPersistentFields = oldSerialPersistentFields;
serialVersionUID = oldSerialVersionUID;
} else {
serialPersistentFields = newSerialPersistentFields;
serialVersionUID = newSerialVersionUID;
}
}
//
// END Serialization compatibility stuff
//
// Private members
//
/** {@collect.stats}
* @serial List of {@link ObjectName}s of interest
* <ul>
* <li><code>null</code> means that all {@link ObjectName}s are implicitly selected
* (check for explicit deselections)</li>
* <li>Empty vector means that no {@link ObjectName} is explicitly selected</li>
* </ul>
*/
private List<ObjectName> selectedNames = new Vector<ObjectName>();
/** {@collect.stats}
* @serial List of {@link ObjectName}s with no interest
* <ul>
* <li><code>null</code> means that all {@link ObjectName}s are implicitly deselected
* (check for explicit selections))</li>
* <li>Empty vector means that no {@link ObjectName} is explicitly deselected</li>
* </ul>
*/
private List<ObjectName> deselectedNames = null;
//
// Constructor
//
/** {@collect.stats}
* Creates a filter selecting all MBeanServerNotification notifications for
* all ObjectNames.
*/
public MBeanServerNotificationFilter() {
super();
RELATION_LOGGER.entering(MBeanServerNotificationFilter.class.getName(),
"MBeanServerNotificationFilter");
enableType(MBeanServerNotification.REGISTRATION_NOTIFICATION);
enableType(MBeanServerNotification.UNREGISTRATION_NOTIFICATION);
RELATION_LOGGER.exiting(MBeanServerNotificationFilter.class.getName(),
"MBeanServerNotificationFilter");
return;
}
//
// Accessors
//
/** {@collect.stats}
* Disables any MBeanServerNotification (all ObjectNames are
* deselected).
*/
public synchronized void disableAllObjectNames() {
RELATION_LOGGER.entering(MBeanServerNotificationFilter.class.getName(),
"disableAllObjectNames");
selectedNames = new Vector<ObjectName>();
deselectedNames = null;
RELATION_LOGGER.exiting(MBeanServerNotificationFilter.class.getName(),
"disableAllObjectNames");
return;
}
/** {@collect.stats}
* Disables MBeanServerNotifications concerning given ObjectName.
*
* @param objectName ObjectName no longer of interest
*
* @exception IllegalArgumentException if the given ObjectName is null
*/
public synchronized void disableObjectName(ObjectName objectName)
throws IllegalArgumentException {
if (objectName == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(MBeanServerNotificationFilter.class.getName(),
"disableObjectName", objectName);
// Removes from selected ObjectNames, if present
if (selectedNames != null) {
if (selectedNames.size() != 0) {
selectedNames.remove(objectName);
}
}
// Adds it in deselected ObjectNames
if (deselectedNames != null) {
// If all are deselected, no need to do anything :)
if (!(deselectedNames.contains(objectName))) {
// ObjectName was not already deselected
deselectedNames.add(objectName);
}
}
RELATION_LOGGER.exiting(MBeanServerNotificationFilter.class.getName(),
"disableObjectName");
return;
}
/** {@collect.stats}
* Enables all MBeanServerNotifications (all ObjectNames are selected).
*/
public synchronized void enableAllObjectNames() {
RELATION_LOGGER.entering(MBeanServerNotificationFilter.class.getName(),
"enableAllObjectNames");
selectedNames = null;
deselectedNames = new Vector<ObjectName>();
RELATION_LOGGER.exiting(MBeanServerNotificationFilter.class.getName(),
"enableAllObjectNames");
return;
}
/** {@collect.stats}
* Enables MBeanServerNotifications concerning given ObjectName.
*
* @param objectName ObjectName of interest
*
* @exception IllegalArgumentException if the given ObjectName is null
*/
public synchronized void enableObjectName(ObjectName objectName)
throws IllegalArgumentException {
if (objectName == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(MBeanServerNotificationFilter.class.getName(),
"enableObjectName", objectName);
// Removes from deselected ObjectNames, if present
if (deselectedNames != null) {
if (deselectedNames.size() != 0) {
deselectedNames.remove(objectName);
}
}
// Adds it in selected ObjectNames
if (selectedNames != null) {
// If all are selected, no need to do anything :)
if (!(selectedNames.contains(objectName))) {
// ObjectName was not already selected
selectedNames.add(objectName);
}
}
RELATION_LOGGER.exiting(MBeanServerNotificationFilter.class.getName(),
"enableObjectName");
return;
}
/** {@collect.stats}
* Gets all the ObjectNames enabled.
*
* @return Vector of ObjectNames:
* <P>- null means all ObjectNames are implicitly selected, except the
* ObjectNames explicitly deselected
* <P>- empty means all ObjectNames are deselected, i.e. no ObjectName
* selected.
*/
public synchronized Vector<ObjectName> getEnabledObjectNames() {
if (selectedNames != null) {
return new Vector<ObjectName>(selectedNames);
} else {
return null;
}
}
/** {@collect.stats}
* Gets all the ObjectNames disabled.
*
* @return Vector of ObjectNames:
* <P>- null means all ObjectNames are implicitly deselected, except the
* ObjectNames explicitly selected
* <P>- empty means all ObjectNames are selected, i.e. no ObjectName
* deselected.
*/
public synchronized Vector<ObjectName> getDisabledObjectNames() {
if (deselectedNames != null) {
return new Vector<ObjectName>(deselectedNames);
} else {
return null;
}
}
//
// NotificationFilter interface
//
/** {@collect.stats}
* Invoked before sending the specified notification to the listener.
* <P>If:
* <P>- the ObjectName of the concerned MBean is selected (explicitly OR
* (implicitly and not explicitly deselected))
* <P>AND
* <P>- the type of the operation (registration or unregistration) is
* selected
* <P>then the notification is sent to the listener.
*
* @param notif The notification to be sent.
*
* @return true if the notification has to be sent to the listener, false
* otherwise.
*
* @exception IllegalArgumentException if null parameter
*/
public synchronized boolean isNotificationEnabled(Notification notif)
throws IllegalArgumentException {
if (notif == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(MBeanServerNotificationFilter.class.getName(),
"isNotificationEnabled", notif);
// Checks the type first
String ntfType = notif.getType();
Vector enabledTypes = getEnabledTypes();
if (!(enabledTypes.contains(ntfType))) {
RELATION_LOGGER.logp(Level.FINER,
MBeanServerNotificationFilter.class.getName(),
"isNotificationEnabled",
"Type not selected, exiting");
return false;
}
// We have a MBeanServerNotification: downcasts it
MBeanServerNotification mbsNtf = (MBeanServerNotification)notif;
// Checks the ObjectName
ObjectName objName = mbsNtf.getMBeanName();
// Is it selected?
boolean isSelectedFlg = false;
if (selectedNames != null) {
// Not all are implicitly selected:
// checks for explicit selection
if (selectedNames.size() == 0) {
// All are explicitly not selected
RELATION_LOGGER.logp(Level.FINER,
MBeanServerNotificationFilter.class.getName(),
"isNotificationEnabled",
"No ObjectNames selected, exiting");
return false;
}
isSelectedFlg = selectedNames.contains(objName);
if (!isSelectedFlg) {
// Not in the explicit selected list
RELATION_LOGGER.logp(Level.FINER,
MBeanServerNotificationFilter.class.getName(),
"isNotificationEnabled",
"ObjectName not in selected list, exiting");
return false;
}
}
if (!isSelectedFlg) {
// Not explicitly selected: is it deselected?
if (deselectedNames == null) {
// All are implicitly deselected and it is not explicitly
// selected
RELATION_LOGGER.logp(Level.FINER,
MBeanServerNotificationFilter.class.getName(),
"isNotificationEnabled",
"ObjectName not selected, and all " +
"names deselected, exiting");
return false;
} else if (deselectedNames.contains(objName)) {
// Explicitly deselected
RELATION_LOGGER.logp(Level.FINER,
MBeanServerNotificationFilter.class.getName(),
"isNotificationEnabled",
"ObjectName explicitly not selected, exiting");
return false;
}
}
RELATION_LOGGER.logp(Level.FINER,
MBeanServerNotificationFilter.class.getName(),
"isNotificationEnabled",
"ObjectName selected, exiting");
return true;
}
/** {@collect.stats}
* Deserializes an {@link MBeanServerNotificationFilter} 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();
selectedNames = cast(fields.get("mySelectObjNameList", null));
if (fields.defaulted("mySelectObjNameList"))
{
throw new NullPointerException("mySelectObjNameList");
}
deselectedNames = cast(fields.get("myDeselectObjNameList", null));
if (fields.defaulted("myDeselectObjNameList"))
{
throw new NullPointerException("myDeselectObjNameList");
}
}
else
{
// Read an object serialized in the new serial form
//
in.defaultReadObject();
}
}
/** {@collect.stats}
* Serializes an {@link MBeanServerNotificationFilter} 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("mySelectObjNameList", (Vector)selectedNames);
fields.put("myDeselectObjNameList", (Vector)deselectedNames);
out.writeFields();
}
else
{
// Serializes this instance in the new serial form
//
out.defaultWriteObject();
}
}
}
| Java |
/*
* Copyright (c) 2000, 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management.relation;
/** {@collect.stats}
* A RelationSupport object is used internally by the Relation Service to
* represent simple relations (only roles, no properties or methods), with an
* unlimited number of roles, of any relation type. As internal representation,
* it is not exposed to the user.
* <P>RelationSupport class conforms to the design patterns of standard MBean. So
* the user can decide to instantiate a RelationSupport object himself as
* a MBean (as it follows the MBean design patterns), to register it in the
* MBean Server, and then to add it in the Relation Service.
* <P>The user can also, when creating his own MBean relation class, have it
* extending RelationSupport, to retrieve the implementations of required
* interfaces (see below).
* <P>It is also possible to have in a user relation MBean class a member
* being a RelationSupport object, and to implement the required interfaces by
* delegating all to this member.
* <P> RelationSupport implements the Relation interface (to be handled by the
* Relation Service).
*
* @since 1.5
*/
public interface RelationSupportMBean
extends Relation {
/** {@collect.stats}
* Returns an internal flag specifying if the object is still handled by
* the Relation Service.
*
* @return a Boolean equal to {@link Boolean#TRUE} if the object
* is still handled by the Relation Service and {@link
* Boolean#FALSE} otherwise.
*/
public Boolean isInRelationService();
/** {@collect.stats}
* <p>Specifies whether this relation is handled by the Relation
* Service.</p>
* <P>BEWARE, this method has to be exposed as the Relation Service will
* access the relation through its management interface. It is RECOMMENDED
* NOT to use this method. Using it does not affect the registration of the
* relation object in the Relation Service, but will provide wrong
* information about it!
*
* @param flag whether the relation is handled by the Relation Service.
*
* @exception IllegalArgumentException if null parameter
*/
public void setRelationServiceManagementFlag(Boolean flag)
throws IllegalArgumentException;
}
| Java |
/*
* Copyright (c) 2000, 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management.relation;
/** {@collect.stats}
* Invalid relation type.
* This exception is raised when, in a relation type, there is already a
* relation type with that name, or the same name has been used for two
* different role infos, or no role info provided, or one null role info
* provided.
*
* @since 1.5
*/
public class InvalidRelationTypeException extends RelationException {
/* Serial version */
private static final long serialVersionUID = 3007446608299169961L;
/** {@collect.stats}
* Default constructor, no message put in exception.
*/
public InvalidRelationTypeException() {
super();
}
/** {@collect.stats}
* Constructor with given message put in exception.
*
* @param message the detail message.
*/
public InvalidRelationTypeException(String message) {
super(message);
}
}
| Java |
/*
* Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management.relation;
import static com.sun.jmx.defaults.JmxProperties.RELATION_LOGGER;
import static com.sun.jmx.mbeanserver.Util.cast;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import javax.management.Attribute;
import javax.management.AttributeNotFoundException;
import javax.management.InstanceNotFoundException;
import javax.management.InvalidAttributeValueException;
import javax.management.MBeanException;
import javax.management.MBeanNotificationInfo;
import javax.management.MBeanRegistration;
import javax.management.MBeanServer;
import javax.management.MBeanServerDelegate;
import javax.management.MBeanServerNotification;
import javax.management.Notification;
import javax.management.NotificationBroadcasterSupport;
import javax.management.NotificationListener;
import javax.management.ObjectName;
import javax.management.ReflectionException;
/** {@collect.stats}
* The Relation Service is in charge of creating and deleting relation types
* and relations, of handling the consistency and of providing query
* mechanisms.
* <P>It implements the NotificationBroadcaster by extending
* NotificationBroadcasterSupport to send notifications when a relation is
* removed from it.
* <P>It implements the NotificationListener interface to be able to receive
* notifications concerning unregistration of MBeans referenced in relation
* roles and of relation MBeans.
* <P>It implements the MBeanRegistration interface to be able to retrieve
* its ObjectName and MBean Server.
*
* @since 1.5
*/
public class RelationService extends NotificationBroadcasterSupport
implements RelationServiceMBean, MBeanRegistration, NotificationListener {
//
// Private members
//
// Map associating:
// <relation id> -> <RelationSupport object/ObjectName>
// depending if the relation has been created using createRelation()
// method (so internally handled) or is an MBean added as a relation by the
// user
private Map<String,Object> myRelId2ObjMap = new HashMap<String,Object>();
// Map associating:
// <relation id> -> <relation type name>
private Map<String,String> myRelId2RelTypeMap = new HashMap<String,String>();
// Map associating:
// <relation MBean Object Name> -> <relation id>
private Map<ObjectName,String> myRelMBeanObjName2RelIdMap =
new HashMap<ObjectName,String>();
// Map associating:
// <relation type name> -> <RelationType object>
private Map<String,RelationType> myRelType2ObjMap =
new HashMap<String,RelationType>();
// Map associating:
// <relation type name> -> ArrayList of <relation id>
// to list all the relations of a given type
private Map<String,List<String>> myRelType2RelIdsMap =
new HashMap<String,List<String>>();
// Map associating:
// <ObjectName> -> HashMap
// the value HashMap mapping:
// <relation id> -> ArrayList of <role name>
// to track where a given MBean is referenced.
private Map<ObjectName,Map<String,List<String>>>
myRefedMBeanObjName2RelIdsMap =
new HashMap<ObjectName,Map<String,List<String>>>();
// Flag to indicate if, when a notification is received for the
// unregistration of an MBean referenced in a relation, if an immediate
// "purge" of the relations (look for the relations no
// longer valid) has to be performed , or if that will be performed only
// when the purgeRelations method will be explicitly called.
// true is immediate purge.
private boolean myPurgeFlag = true;
// Internal counter to provide sequence numbers for notifications sent by:
// - the Relation Service
// - a relation handled by the Relation Service
private Long myNtfSeqNbrCounter = new Long(0);
// ObjectName used to register the Relation Service in the MBean Server
private ObjectName myObjName = null;
// MBean Server where the Relation Service is registered
private MBeanServer myMBeanServer = null;
// Filter registered in the MBean Server with the Relation Service to be
// informed of referenced MBean unregistrations
private MBeanServerNotificationFilter myUnregNtfFilter = null;
// List of unregistration notifications received (storage used if purge
// of relations when unregistering a referenced MBean is not immediate but
// on user request)
private List<MBeanServerNotification> myUnregNtfList =
new ArrayList<MBeanServerNotification>();
//
// Constructor
//
/** {@collect.stats}
* Constructor.
*
* @param immediatePurgeFlag flag to indicate when a notification is
* received for the unregistration of an MBean referenced in a relation, if
* an immediate "purge" of the relations (look for the relations no
* longer valid) has to be performed , or if that will be performed only
* when the purgeRelations method will be explicitly called.
* <P>true is immediate purge.
*/
public RelationService(boolean immediatePurgeFlag) {
RELATION_LOGGER.entering(RelationService.class.getName(),
"RelationService");
setPurgeFlag(immediatePurgeFlag);
RELATION_LOGGER.exiting(RelationService.class.getName(),
"RelationService");
return;
}
/** {@collect.stats}
* Checks if the Relation Service is active.
* Current condition is that the Relation Service must be registered in the
* MBean Server
*
* @exception RelationServiceNotRegisteredException if it is not
* registered
*/
public void isActive()
throws RelationServiceNotRegisteredException {
if (myMBeanServer == null) {
// MBean Server not set by preRegister(): relation service not
// registered
String excMsg =
"Relation Service not registered in the MBean Server.";
throw new RelationServiceNotRegisteredException(excMsg);
}
return;
}
//
// MBeanRegistration interface
//
// Pre-registration: retrieves its ObjectName and MBean Server
//
// No exception thrown.
public ObjectName preRegister(MBeanServer server,
ObjectName name)
throws Exception {
myMBeanServer = server;
myObjName = name;
return name;
}
// Post-registration: does nothing
public void postRegister(Boolean registrationDone) {
return;
}
// Pre-unregistration: does nothing
public void preDeregister()
throws Exception {
return;
}
// Post-unregistration: does nothing
public void postDeregister() {
return;
}
//
// Accessors
//
/** {@collect.stats}
* Returns the flag to indicate if when a notification is received for the
* unregistration of an MBean referenced in a relation, if an immediate
* "purge" of the relations (look for the relations no longer valid)
* has to be performed , or if that will be performed only when the
* purgeRelations method will be explicitly called.
* <P>true is immediate purge.
*
* @return true if purges are automatic.
*
* @see #setPurgeFlag
*/
public boolean getPurgeFlag() {
return myPurgeFlag;
}
/** {@collect.stats}
* Sets the flag to indicate if when a notification is received for the
* unregistration of an MBean referenced in a relation, if an immediate
* "purge" of the relations (look for the relations no longer valid)
* has to be performed , or if that will be performed only when the
* purgeRelations method will be explicitly called.
* <P>true is immediate purge.
*
* @param purgeFlag flag
*
* @see #getPurgeFlag
*/
public void setPurgeFlag(boolean purgeFlag) {
myPurgeFlag = purgeFlag;
return;
}
// Returns internal counter to be used for Sequence Numbers of
// notifications to be raised by:
// - a relation handled by this Relation Service (when updated)
// - the Relation Service
private Long getNotificationSequenceNumber() {
Long result = null;
synchronized(myNtfSeqNbrCounter) {
result = new Long(myNtfSeqNbrCounter.longValue() + 1);
myNtfSeqNbrCounter = new Long(result.longValue());
}
return result;
}
//
// Relation type handling
//
/** {@collect.stats}
* Creates a relation type (a RelationTypeSupport object) with given
* role infos (provided by the RoleInfo objects), and adds it in the
* Relation Service.
*
* @param relationTypeName name of the relation type
* @param roleInfoArray array of role infos
*
* @exception IllegalArgumentException if null parameter
* @exception InvalidRelationTypeException If:
* <P>- there is already a relation type with that name
* <P>- the same name has been used for two different role infos
* <P>- no role info provided
* <P>- one null role info provided
*/
public void createRelationType(String relationTypeName,
RoleInfo[] roleInfoArray)
throws IllegalArgumentException,
InvalidRelationTypeException {
if (relationTypeName == null || roleInfoArray == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"createRelationType", relationTypeName);
// Can throw an InvalidRelationTypeException
RelationType relType =
new RelationTypeSupport(relationTypeName, roleInfoArray);
addRelationTypeInt(relType);
RELATION_LOGGER.exiting(RelationService.class.getName(),
"createRelationType");
return;
}
/** {@collect.stats}
* Adds given object as a relation type. The object is expected to
* implement the RelationType interface.
*
* @param relationTypeObj relation type object (implementing the
* RelationType interface)
*
* @exception IllegalArgumentException if null parameter or if
* {@link RelationType#getRelationTypeName
* relationTypeObj.getRelationTypeName()} returns null.
* @exception InvalidRelationTypeException if:
* <P>- the same name has been used for two different roles
* <P>- no role info provided
* <P>- one null role info provided
* <P>- there is already a relation type with that name
*/
public void addRelationType(RelationType relationTypeObj)
throws IllegalArgumentException,
InvalidRelationTypeException {
if (relationTypeObj == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"addRelationType");
// Checks the role infos
List<RoleInfo> roleInfoList = relationTypeObj.getRoleInfos();
if (roleInfoList == null) {
String excMsg = "No role info provided.";
throw new InvalidRelationTypeException(excMsg);
}
RoleInfo[] roleInfoArray = new RoleInfo[roleInfoList.size()];
int i = 0;
for (RoleInfo currRoleInfo : roleInfoList) {
roleInfoArray[i] = currRoleInfo;
i++;
}
// Can throw InvalidRelationTypeException
RelationTypeSupport.checkRoleInfos(roleInfoArray);
addRelationTypeInt(relationTypeObj);
RELATION_LOGGER.exiting(RelationService.class.getName(),
"addRelationType");
return;
}
/** {@collect.stats}
* Retrieves names of all known relation types.
*
* @return ArrayList of relation type names (Strings)
*/
public List<String> getAllRelationTypeNames() {
ArrayList<String> result = null;
synchronized(myRelType2ObjMap) {
result = new ArrayList<String>(myRelType2ObjMap.keySet());
}
return result;
}
/** {@collect.stats}
* Retrieves list of role infos (RoleInfo objects) of a given relation
* type.
*
* @param relationTypeName name of relation type
*
* @return ArrayList of RoleInfo.
*
* @exception IllegalArgumentException if null parameter
* @exception RelationTypeNotFoundException if there is no relation type
* with that name.
*/
public List<RoleInfo> getRoleInfos(String relationTypeName)
throws IllegalArgumentException,
RelationTypeNotFoundException {
if (relationTypeName == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"getRoleInfos", relationTypeName);
// Can throw a RelationTypeNotFoundException
RelationType relType = getRelationType(relationTypeName);
RELATION_LOGGER.exiting(RelationService.class.getName(),
"getRoleInfos");
return relType.getRoleInfos();
}
/** {@collect.stats}
* Retrieves role info for given role name of a given relation type.
*
* @param relationTypeName name of relation type
* @param roleInfoName name of role
*
* @return RoleInfo object.
*
* @exception IllegalArgumentException if null parameter
* @exception RelationTypeNotFoundException if the relation type is not
* known in the Relation Service
* @exception RoleInfoNotFoundException if the role is not part of the
* relation type.
*/
public RoleInfo getRoleInfo(String relationTypeName,
String roleInfoName)
throws IllegalArgumentException,
RelationTypeNotFoundException,
RoleInfoNotFoundException {
if (relationTypeName == null || roleInfoName == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"getRoleInfo", new Object[] {relationTypeName, roleInfoName});
// Can throw a RelationTypeNotFoundException
RelationType relType = getRelationType(relationTypeName);
// Can throw a RoleInfoNotFoundException
RoleInfo roleInfo = relType.getRoleInfo(roleInfoName);
RELATION_LOGGER.exiting(RelationService.class.getName(),
"getRoleInfo");
return roleInfo;
}
/** {@collect.stats}
* Removes given relation type from Relation Service.
* <P>The relation objects of that type will be removed from the
* Relation Service.
*
* @param relationTypeName name of the relation type to be removed
*
* @exception RelationServiceNotRegisteredException if the Relation
* Service is not registered in the MBean Server
* @exception IllegalArgumentException if null parameter
* @exception RelationTypeNotFoundException If there is no relation type
* with that name
*/
public void removeRelationType(String relationTypeName)
throws RelationServiceNotRegisteredException,
IllegalArgumentException,
RelationTypeNotFoundException {
// Can throw RelationServiceNotRegisteredException
isActive();
if (relationTypeName == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"removeRelationType", relationTypeName);
// Checks if the relation type to be removed exists
// Can throw a RelationTypeNotFoundException
RelationType relType = getRelationType(relationTypeName);
// Retrieves the relation ids for relations of that type
List<String> relIdList = null;
synchronized(myRelType2RelIdsMap) {
// Note: take a copy of the list as it is a part of a map that
// will be updated by removeRelation() below.
List<String> relIdList1 =
myRelType2RelIdsMap.get(relationTypeName);
if (relIdList1 != null) {
relIdList = new ArrayList<String>(relIdList1);
}
}
// Removes the relation type from all maps
synchronized(myRelType2ObjMap) {
myRelType2ObjMap.remove(relationTypeName);
}
synchronized(myRelType2RelIdsMap) {
myRelType2RelIdsMap.remove(relationTypeName);
}
// Removes all relations of that type
if (relIdList != null) {
for (String currRelId : relIdList) {
// Note: will remove it from myRelId2RelTypeMap :)
//
// Can throw RelationServiceNotRegisteredException (detected
// above)
// Shall not throw a RelationNotFoundException
try {
removeRelation(currRelId);
} catch (RelationNotFoundException exc1) {
throw new RuntimeException(exc1.getMessage());
}
}
}
RELATION_LOGGER.exiting(RelationService.class.getName(),
"removeRelationType");
return;
}
//
// Relation handling
//
/** {@collect.stats}
* Creates a simple relation (represented by a RelationSupport object) of
* given relation type, and adds it in the Relation Service.
* <P>Roles are initialized according to the role list provided in
* parameter. The ones not initialized in this way are set to an empty
* ArrayList of ObjectNames.
* <P>A RelationNotification, with type RELATION_BASIC_CREATION, is sent.
*
* @param relationId relation identifier, to identify uniquely the relation
* inside the Relation Service
* @param relationTypeName name of the relation type (has to be created
* in the Relation Service)
* @param roleList role list to initialize roles of the relation (can
* be null).
*
* @exception RelationServiceNotRegisteredException if the Relation
* Service is not registered in the MBean Server
* @exception IllegalArgumentException if null parameter, except the role
* list which can be null if no role initialization
* @exception RoleNotFoundException if a value is provided for a role
* that does not exist in the relation type
* @exception InvalidRelationIdException if relation id already used
* @exception RelationTypeNotFoundException if relation type not known in
* Relation Service
* @exception InvalidRoleValueException if:
* <P>- the same role name is used for two different roles
* <P>- the number of referenced MBeans in given value is less than
* expected minimum degree
* <P>- the number of referenced MBeans in provided value exceeds expected
* maximum degree
* <P>- one referenced MBean in the value is not an Object of the MBean
* class expected for that role
* <P>- an MBean provided for that role does not exist
*/
public void createRelation(String relationId,
String relationTypeName,
RoleList roleList)
throws RelationServiceNotRegisteredException,
IllegalArgumentException,
RoleNotFoundException,
InvalidRelationIdException,
RelationTypeNotFoundException,
InvalidRoleValueException {
// Can throw RelationServiceNotRegisteredException
isActive();
if (relationId == null ||
relationTypeName == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"createRelation",
new Object[] {relationId, relationTypeName, roleList});
// Creates RelationSupport object
// Can throw InvalidRoleValueException
RelationSupport relObj = new RelationSupport(relationId,
myObjName,
relationTypeName,
roleList);
// Adds relation object as a relation into the Relation Service
// Can throw RoleNotFoundException, InvalidRelationId,
// RelationTypeNotFoundException, InvalidRoleValueException
//
// Cannot throw MBeanException
addRelationInt(true,
relObj,
null,
relationId,
relationTypeName,
roleList);
RELATION_LOGGER.exiting(RelationService.class.getName(),
"createRelation");
return;
}
/** {@collect.stats}
* Adds an MBean created by the user (and registered by him in the MBean
* Server) as a relation in the Relation Service.
* <P>To be added as a relation, the MBean must conform to the
* following:
* <P>- implement the Relation interface
* <P>- have for RelationService ObjectName the ObjectName of current
* Relation Service
* <P>- have a relation id unique and unused in current Relation Service
* <P>- have for relation type a relation type created in the Relation
* Service
* <P>- have roles conforming to the role info provided in the relation
* type.
*
* @param relationObjectName ObjectName of the relation MBean to be added.
*
* @exception IllegalArgumentException if null parameter
* @exception RelationServiceNotRegisteredException if the Relation
* Service is not registered in the MBean Server
* @exception NoSuchMethodException If the MBean does not implement the
* Relation interface
* @exception InvalidRelationIdException if:
* <P>- no relation identifier in MBean
* <P>- the relation identifier is already used in the Relation Service
* @exception InstanceNotFoundException if the MBean for given ObjectName
* has not been registered
* @exception InvalidRelationServiceException if:
* <P>- no Relation Service name in MBean
* <P>- the Relation Service name in the MBean is not the one of the
* current Relation Service
* @exception RelationTypeNotFoundException if:
* <P>- no relation type name in MBean
* <P>- the relation type name in MBean does not correspond to a relation
* type created in the Relation Service
* @exception InvalidRoleValueException if:
* <P>- the number of referenced MBeans in a role is less than
* expected minimum degree
* <P>- the number of referenced MBeans in a role exceeds expected
* maximum degree
* <P>- one referenced MBean in the value is not an Object of the MBean
* class expected for that role
* <P>- an MBean provided for a role does not exist
* @exception RoleNotFoundException if a value is provided for a role
* that does not exist in the relation type
*/
public void addRelation(ObjectName relationObjectName)
throws IllegalArgumentException,
RelationServiceNotRegisteredException,
NoSuchMethodException,
InvalidRelationIdException,
InstanceNotFoundException,
InvalidRelationServiceException,
RelationTypeNotFoundException,
RoleNotFoundException,
InvalidRoleValueException {
if (relationObjectName == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"addRelation", relationObjectName);
// Can throw RelationServiceNotRegisteredException
isActive();
// Checks that the relation MBean implements the Relation interface.
// It will also check that the provided ObjectName corresponds to a
// registered MBean (else will throw an InstanceNotFoundException)
if ((!(myMBeanServer.isInstanceOf(relationObjectName, "javax.management.relation.Relation")))) {
String excMsg = "This MBean does not implement the Relation interface.";
throw new NoSuchMethodException(excMsg);
}
// Checks there is a relation id in the relation MBean (its uniqueness
// is checked in addRelationInt())
// Can throw InstanceNotFoundException (but detected above)
// No MBeanException as no exception raised by this method, and no
// ReflectionException
String relId = null;
try {
relId = (String)(myMBeanServer.getAttribute(relationObjectName,
"RelationId"));
} catch (MBeanException exc1) {
throw new RuntimeException(
(exc1.getTargetException()).getMessage());
} catch (ReflectionException exc2) {
throw new RuntimeException(exc2.getMessage());
} catch (AttributeNotFoundException exc3) {
throw new RuntimeException(exc3.getMessage());
}
if (relId == null) {
String excMsg = "This MBean does not provide a relation id.";
throw new InvalidRelationIdException(excMsg);
}
// Checks that the Relation Service where the relation MBean is
// expected to be added is the current one
// Can throw InstanceNotFoundException (but detected above)
// No MBeanException as no exception raised by this method, no
// ReflectionException
ObjectName relServObjName = null;
try {
relServObjName = (ObjectName)
(myMBeanServer.getAttribute(relationObjectName,
"RelationServiceName"));
} catch (MBeanException exc1) {
throw new RuntimeException(
(exc1.getTargetException()).getMessage());
} catch (ReflectionException exc2) {
throw new RuntimeException(exc2.getMessage());
} catch (AttributeNotFoundException exc3) {
throw new RuntimeException(exc3.getMessage());
}
boolean badRelServFlag = false;
if (relServObjName == null) {
badRelServFlag = true;
} else if (!(relServObjName.equals(myObjName))) {
badRelServFlag = true;
}
if (badRelServFlag) {
String excMsg = "The Relation Service referenced in the MBean is not the current one.";
throw new InvalidRelationServiceException(excMsg);
}
// Checks that a relation type has been specified for the relation
// Can throw InstanceNotFoundException (but detected above)
// No MBeanException as no exception raised by this method, no
// ReflectionException
String relTypeName = null;
try {
relTypeName = (String)(myMBeanServer.getAttribute(relationObjectName,
"RelationTypeName"));
} catch (MBeanException exc1) {
throw new RuntimeException(
(exc1.getTargetException()).getMessage());
}catch (ReflectionException exc2) {
throw new RuntimeException(exc2.getMessage());
} catch (AttributeNotFoundException exc3) {
throw new RuntimeException(exc3.getMessage());
}
if (relTypeName == null) {
String excMsg = "No relation type provided.";
throw new RelationTypeNotFoundException(excMsg);
}
// Retrieves all roles without considering read mode
// Can throw InstanceNotFoundException (but detected above)
// No MBeanException as no exception raised by this method, no
// ReflectionException
RoleList roleList = null;
try {
roleList = (RoleList)(myMBeanServer.invoke(relationObjectName,
"retrieveAllRoles",
null,
null));
} catch (MBeanException exc1) {
throw new RuntimeException(
(exc1.getTargetException()).getMessage());
} catch (ReflectionException exc2) {
throw new RuntimeException(exc2.getMessage());
}
// Can throw RoleNotFoundException, InvalidRelationIdException,
// RelationTypeNotFoundException, InvalidRoleValueException
addRelationInt(false,
null,
relationObjectName,
relId,
relTypeName,
roleList);
// Adds relation MBean ObjectName in map
synchronized(myRelMBeanObjName2RelIdMap) {
myRelMBeanObjName2RelIdMap.put(relationObjectName, relId);
}
// Updates flag to specify that the relation is managed by the Relation
// Service
// This flag and setter are inherited from RelationSupport and not parts
// of the Relation interface, so may be not supported.
try {
myMBeanServer.setAttribute(relationObjectName,
new Attribute(
"RelationServiceManagementFlag",
Boolean.TRUE));
} catch (Exception exc) {
// OK : The flag is not supported.
}
// Updates listener information to received notification for
// unregistration of this MBean
List<ObjectName> newRefList = new ArrayList<ObjectName>();
newRefList.add(relationObjectName);
updateUnregistrationListener(newRefList, null);
RELATION_LOGGER.exiting(RelationService.class.getName(),
"addRelation");
return;
}
/** {@collect.stats}
* If the relation is represented by an MBean (created by the user and
* added as a relation in the Relation Service), returns the ObjectName of
* the MBean.
*
* @param relationId relation id identifying the relation
*
* @return ObjectName of the corresponding relation MBean, or null if
* the relation is not an MBean.
*
* @exception IllegalArgumentException if null parameter
* @exception RelationNotFoundException there is no relation associated
* to that id
*/
public ObjectName isRelationMBean(String relationId)
throws IllegalArgumentException,
RelationNotFoundException{
if (relationId == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"isRelationMBean", relationId);
// Can throw RelationNotFoundException
Object result = getRelation(relationId);
if (result instanceof ObjectName) {
return ((ObjectName)result);
} else {
return null;
}
}
/** {@collect.stats}
* Returns the relation id associated to the given ObjectName if the
* MBean has been added as a relation in the Relation Service.
*
* @param objectName ObjectName of supposed relation
*
* @return relation id (String) or null (if the ObjectName is not a
* relation handled by the Relation Service)
*
* @exception IllegalArgumentException if null parameter
*/
public String isRelation(ObjectName objectName)
throws IllegalArgumentException {
if (objectName == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"isRelation", objectName);
String result = null;
synchronized(myRelMBeanObjName2RelIdMap) {
String relId = myRelMBeanObjName2RelIdMap.get(objectName);
if (relId != null) {
result = relId;
}
}
return result;
}
/** {@collect.stats}
* Checks if there is a relation identified in Relation Service with given
* relation id.
*
* @param relationId relation id identifying the relation
*
* @return boolean: true if there is a relation, false else
*
* @exception IllegalArgumentException if null parameter
*/
public Boolean hasRelation(String relationId)
throws IllegalArgumentException {
if (relationId == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"hasRelation", relationId);
try {
// Can throw RelationNotFoundException
Object result = getRelation(relationId);
return true;
} catch (RelationNotFoundException exc) {
return false;
}
}
/** {@collect.stats}
* Returns all the relation ids for all the relations handled by the
* Relation Service.
*
* @return ArrayList of String
*/
public List<String> getAllRelationIds() {
List<String> result = null;
synchronized(myRelId2ObjMap) {
result = new ArrayList<String>(myRelId2ObjMap.keySet());
}
return result;
}
/** {@collect.stats}
* Checks if given Role can be read in a relation of the given type.
*
* @param roleName name of role to be checked
* @param relationTypeName name of the relation type
*
* @return an Integer wrapping an integer corresponding to possible
* problems represented as constants in RoleUnresolved:
* <P>- 0 if role can be read
* <P>- integer corresponding to RoleStatus.NO_ROLE_WITH_NAME
* <P>- integer corresponding to RoleStatus.ROLE_NOT_READABLE
*
* @exception IllegalArgumentException if null parameter
* @exception RelationTypeNotFoundException if the relation type is not
* known in the Relation Service
*/
public Integer checkRoleReading(String roleName,
String relationTypeName)
throws IllegalArgumentException,
RelationTypeNotFoundException {
if (roleName == null || relationTypeName == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"checkRoleReading", new Object[] {roleName, relationTypeName});
Integer result = null;
// Can throw a RelationTypeNotFoundException
RelationType relType = getRelationType(relationTypeName);
try {
// Can throw a RoleInfoNotFoundException to be transformed into
// returned value RoleStatus.NO_ROLE_WITH_NAME
RoleInfo roleInfo = relType.getRoleInfo(roleName);
result = checkRoleInt(1,
roleName,
null,
roleInfo,
false);
} catch (RoleInfoNotFoundException exc) {
result = new Integer(RoleStatus.NO_ROLE_WITH_NAME);
}
RELATION_LOGGER.exiting(RelationService.class.getName(),
"checkRoleReading");
return result;
}
/** {@collect.stats}
* Checks if given Role can be set in a relation of given type.
*
* @param role role to be checked
* @param relationTypeName name of relation type
* @param initFlag flag to specify that the checking is done for the
* initialization of a role, write access shall not be verified.
*
* @return an Integer wrapping an integer corresponding to possible
* problems represented as constants in RoleUnresolved:
* <P>- 0 if role can be set
* <P>- integer corresponding to RoleStatus.NO_ROLE_WITH_NAME
* <P>- integer for RoleStatus.ROLE_NOT_WRITABLE
* <P>- integer for RoleStatus.LESS_THAN_MIN_ROLE_DEGREE
* <P>- integer for RoleStatus.MORE_THAN_MAX_ROLE_DEGREE
* <P>- integer for RoleStatus.REF_MBEAN_OF_INCORRECT_CLASS
* <P>- integer for RoleStatus.REF_MBEAN_NOT_REGISTERED
*
* @exception IllegalArgumentException if null parameter
* @exception RelationTypeNotFoundException if unknown relation type
*/
public Integer checkRoleWriting(Role role,
String relationTypeName,
Boolean initFlag)
throws IllegalArgumentException,
RelationTypeNotFoundException {
if (role == null ||
relationTypeName == null ||
initFlag == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"checkRoleWriting",
new Object[] {role, relationTypeName, initFlag});
// Can throw a RelationTypeNotFoundException
RelationType relType = getRelationType(relationTypeName);
String roleName = role.getRoleName();
List<ObjectName> roleValue = role.getRoleValue();
boolean writeChkFlag = true;
if (initFlag.booleanValue()) {
writeChkFlag = false;
}
RoleInfo roleInfo = null;
try {
roleInfo = relType.getRoleInfo(roleName);
} catch (RoleInfoNotFoundException exc) {
RELATION_LOGGER.exiting(RelationService.class.getName(),
"checkRoleWriting");
return new Integer(RoleStatus.NO_ROLE_WITH_NAME);
}
Integer result = checkRoleInt(2,
roleName,
roleValue,
roleInfo,
writeChkFlag);
RELATION_LOGGER.exiting(RelationService.class.getName(),
"checkRoleWriting");
return result;
}
/** {@collect.stats}
* Sends a notification (RelationNotification) for a relation creation.
* The notification type is:
* <P>- RelationNotification.RELATION_BASIC_CREATION if the relation is an
* object internal to the Relation Service
* <P>- RelationNotification.RELATION_MBEAN_CREATION if the relation is a
* MBean added as a relation.
* <P>The source object is the Relation Service itself.
* <P>It is called in Relation Service createRelation() and
* addRelation() methods.
*
* @param relationId relation identifier of the updated relation
*
* @exception IllegalArgumentException if null parameter
* @exception RelationNotFoundException if there is no relation for given
* relation id
*/
public void sendRelationCreationNotification(String relationId)
throws IllegalArgumentException,
RelationNotFoundException {
if (relationId == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"sendRelationCreationNotification", relationId);
// Message
StringBuilder ntfMsg = new StringBuilder("Creation of relation ");
ntfMsg.append(relationId);
// Can throw RelationNotFoundException
sendNotificationInt(1,
ntfMsg.toString(),
relationId,
null,
null,
null,
null);
RELATION_LOGGER.exiting(RelationService.class.getName(),
"sendRelationCreationNotification");
return;
}
/** {@collect.stats}
* Sends a notification (RelationNotification) for a role update in the
* given relation. The notification type is:
* <P>- RelationNotification.RELATION_BASIC_UPDATE if the relation is an
* object internal to the Relation Service
* <P>- RelationNotification.RELATION_MBEAN_UPDATE if the relation is a
* MBean added as a relation.
* <P>The source object is the Relation Service itself.
* <P>It is called in relation MBean setRole() (for given role) and
* setRoles() (for each role) methods (implementation provided in
* RelationSupport class).
* <P>It is also called in Relation Service setRole() (for given role) and
* setRoles() (for each role) methods.
*
* @param relationId relation identifier of the updated relation
* @param newRole new role (name and new value)
* @param oldValue old role value (List of ObjectName objects)
*
* @exception IllegalArgumentException if null parameter
* @exception RelationNotFoundException if there is no relation for given
* relation id
*/
public void sendRoleUpdateNotification(String relationId,
Role newRole,
List<ObjectName> oldValue)
throws IllegalArgumentException,
RelationNotFoundException {
if (relationId == null ||
newRole == null ||
oldValue == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
if (!(oldValue instanceof ArrayList))
oldValue = new ArrayList<ObjectName>(oldValue);
RELATION_LOGGER.entering(RelationService.class.getName(),
"sendRoleUpdateNotification",
new Object[] {relationId, newRole, oldValue});
String roleName = newRole.getRoleName();
List<ObjectName> newRoleVal = newRole.getRoleValue();
// Message
String newRoleValString = Role.roleValueToString(newRoleVal);
String oldRoleValString = Role.roleValueToString(oldValue);
StringBuilder ntfMsg = new StringBuilder("Value of role ");
ntfMsg.append(roleName);
ntfMsg.append(" has changed\nOld value:\n");
ntfMsg.append(oldRoleValString);
ntfMsg.append("\nNew value:\n");
ntfMsg.append(newRoleValString);
// Can throw a RelationNotFoundException
sendNotificationInt(2,
ntfMsg.toString(),
relationId,
null,
roleName,
newRoleVal,
oldValue);
RELATION_LOGGER.exiting(RelationService.class.getName(),
"sendRoleUpdateNotification");
}
/** {@collect.stats}
* Sends a notification (RelationNotification) for a relation removal.
* The notification type is:
* <P>- RelationNotification.RELATION_BASIC_REMOVAL if the relation is an
* object internal to the Relation Service
* <P>- RelationNotification.RELATION_MBEAN_REMOVAL if the relation is a
* MBean added as a relation.
* <P>The source object is the Relation Service itself.
* <P>It is called in Relation Service removeRelation() method.
*
* @param relationId relation identifier of the updated relation
* @param unregMBeanList List of ObjectNames of MBeans expected
* to be unregistered due to relation removal (can be null)
*
* @exception IllegalArgumentException if null parameter
* @exception RelationNotFoundException if there is no relation for given
* relation id
*/
public void sendRelationRemovalNotification(String relationId,
List<ObjectName> unregMBeanList)
throws IllegalArgumentException,
RelationNotFoundException {
if (relationId == null) {
String excMsg = "Invalid parameter";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"sendRelationRemovalNotification",
new Object[] {relationId, unregMBeanList});
// Can throw RelationNotFoundException
sendNotificationInt(3,
"Removal of relation " + relationId,
relationId,
unregMBeanList,
null,
null,
null);
RELATION_LOGGER.exiting(RelationService.class.getName(),
"sendRelationRemovalNotification");
return;
}
/** {@collect.stats}
* Handles update of the Relation Service role map for the update of given
* role in given relation.
* <P>It is called in relation MBean setRole() (for given role) and
* setRoles() (for each role) methods (implementation provided in
* RelationSupport class).
* <P>It is also called in Relation Service setRole() (for given role) and
* setRoles() (for each role) methods.
* <P>To allow the Relation Service to maintain the consistency (in case
* of MBean unregistration) and to be able to perform queries, this method
* must be called when a role is updated.
*
* @param relationId relation identifier of the updated relation
* @param newRole new role (name and new value)
* @param oldValue old role value (List of ObjectName objects)
*
* @exception IllegalArgumentException if null parameter
* @exception RelationServiceNotRegisteredException if the Relation
* Service is not registered in the MBean Server
* @exception RelationNotFoundException if no relation for given id.
*/
public void updateRoleMap(String relationId,
Role newRole,
List<ObjectName> oldValue)
throws IllegalArgumentException,
RelationServiceNotRegisteredException,
RelationNotFoundException {
if (relationId == null ||
newRole == null ||
oldValue == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"updateRoleMap", new Object[] {relationId, newRole, oldValue});
// Can throw RelationServiceNotRegisteredException
isActive();
// Verifies the relation has been added in the Relation Service
// Can throw a RelationNotFoundException
Object result = getRelation(relationId);
String roleName = newRole.getRoleName();
List<ObjectName> newRoleValue = newRole.getRoleValue();
// Note: no need to test if oldValue not null before cloning,
// tested above.
List<ObjectName> oldRoleValue =
new ArrayList<ObjectName>(oldValue);
// List of ObjectNames of new referenced MBeans
List<ObjectName> newRefList = new ArrayList<ObjectName>();
for (ObjectName currObjName : newRoleValue) {
// Checks if this ObjectName was already present in old value
// Note: use copy (oldRoleValue) instead of original
// oldValue to speed up, as oldRoleValue is decreased
// by removing unchanged references :)
int currObjNamePos = oldRoleValue.indexOf(currObjName);
if (currObjNamePos == -1) {
// New reference to an ObjectName
// Stores this reference into map
// Returns true if new reference, false if MBean already
// referenced
boolean isNewFlag = addNewMBeanReference(currObjName,
relationId,
roleName);
if (isNewFlag) {
// Adds it into list of new reference
newRefList.add(currObjName);
}
} else {
// MBean was already referenced in old value
// Removes it from old value (local list) to ignore it when
// looking for remove MBean references
oldRoleValue.remove(currObjNamePos);
}
}
// List of ObjectNames of MBeans no longer referenced
List<ObjectName> obsRefList = new ArrayList<ObjectName>();
// Each ObjectName remaining in oldRoleValue is an ObjectName no longer
// referenced in new value
for (ObjectName currObjName : oldRoleValue) {
// Removes MBean reference from map
// Returns true if the MBean is no longer referenced in any
// relation
boolean noLongerRefFlag = removeMBeanReference(currObjName,
relationId,
roleName,
false);
if (noLongerRefFlag) {
// Adds it into list of references to be removed
obsRefList.add(currObjName);
}
}
// To avoid having one listener per ObjectName of referenced MBean,
// and to increase performances, there is only one listener recording
// all ObjectNames of interest
updateUnregistrationListener(newRefList, obsRefList);
RELATION_LOGGER.exiting(RelationService.class.getName(),
"updateRoleMap");
return;
}
/** {@collect.stats}
* Removes given relation from the Relation Service.
* <P>A RelationNotification notification is sent, its type being:
* <P>- RelationNotification.RELATION_BASIC_REMOVAL if the relation was
* only internal to the Relation Service
* <P>- RelationNotification.RELATION_MBEAN_REMOVAL if the relation is
* registered as an MBean.
* <P>For MBeans referenced in such relation, nothing will be done,
*
* @param relationId relation id of the relation to be removed
*
* @exception RelationServiceNotRegisteredException if the Relation
* Service is not registered in the MBean Server
* @exception IllegalArgumentException if null parameter
* @exception RelationNotFoundException if no relation corresponding to
* given relation id
*/
public void removeRelation(String relationId)
throws RelationServiceNotRegisteredException,
IllegalArgumentException,
RelationNotFoundException {
// Can throw RelationServiceNotRegisteredException
isActive();
if (relationId == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"removeRelation", relationId);
// Checks there is a relation with this id
// Can throw RelationNotFoundException
Object result = getRelation(relationId);
// Removes it from listener filter
if (result instanceof ObjectName) {
List<ObjectName> obsRefList = new ArrayList<ObjectName>();
obsRefList.add((ObjectName)result);
// Can throw a RelationServiceNotRegisteredException
updateUnregistrationListener(null, obsRefList);
}
// Sends a notification
// Note: has to be done FIRST as needs the relation to be still in the
// Relation Service
// No RelationNotFoundException as checked above
// Revisit [cebro] Handle CIM "Delete" and "IfDeleted" qualifiers:
// deleting the relation can mean to delete referenced MBeans. In
// that case, MBeans to be unregistered are put in a list sent along
// with the notification below
// Can throw a RelationNotFoundException (but detected above)
sendRelationRemovalNotification(relationId, null);
// Removes the relation from various internal maps
// - MBean reference map
// Retrieves the MBeans referenced in this relation
// Note: here we cannot use removeMBeanReference() because it would
// require to know the MBeans referenced in the relation. For
// that it would be necessary to call 'getReferencedMBeans()'
// on the relation itself. Ok if it is an internal one, but if
// it is an MBean, it is possible it is already unregistered, so
// not available through the MBean Server.
List<ObjectName> refMBeanList = new ArrayList<ObjectName>();
// List of MBeans no longer referenced in any relation, to be
// removed fom the map
List<ObjectName> nonRefObjNameList = new ArrayList<ObjectName>();
synchronized(myRefedMBeanObjName2RelIdsMap) {
for (ObjectName currRefObjName :
myRefedMBeanObjName2RelIdsMap.keySet()) {
// Retrieves relations where the MBean is referenced
Map<String,List<String>> relIdMap =
myRefedMBeanObjName2RelIdsMap.get(currRefObjName);
if (relIdMap.containsKey(relationId)) {
relIdMap.remove(relationId);
refMBeanList.add(currRefObjName);
}
if (relIdMap.isEmpty()) {
// MBean no longer referenced
// Note: do not remove it here because pointed by the
// iterator!
nonRefObjNameList.add(currRefObjName);
}
}
// Cleans MBean reference map by removing MBeans no longer
// referenced
for (ObjectName currRefObjName : nonRefObjNameList) {
myRefedMBeanObjName2RelIdsMap.remove(currRefObjName);
}
}
// - Relation id to object map
synchronized(myRelId2ObjMap) {
myRelId2ObjMap.remove(relationId);
}
if (result instanceof ObjectName) {
// - ObjectName to relation id map
synchronized(myRelMBeanObjName2RelIdMap) {
myRelMBeanObjName2RelIdMap.remove((ObjectName)result);
}
}
// Relation id to relation type name map
// First retrieves the relation type name
String relTypeName = null;
synchronized(myRelId2RelTypeMap) {
relTypeName = myRelId2RelTypeMap.get(relationId);
myRelId2RelTypeMap.remove(relationId);
}
// - Relation type name to relation id map
synchronized(myRelType2RelIdsMap) {
List<String> relIdList = myRelType2RelIdsMap.get(relTypeName);
if (relIdList != null) {
// Can be null if called from removeRelationType()
relIdList.remove(relationId);
if (relIdList.isEmpty()) {
// No other relation of that type
myRelType2RelIdsMap.remove(relTypeName);
}
}
}
RELATION_LOGGER.exiting(RelationService.class.getName(),
"removeRelation");
return;
}
/** {@collect.stats}
* Purges the relations.
*
* <P>Depending on the purgeFlag value, this method is either called
* automatically when a notification is received for the unregistration of
* an MBean referenced in a relation (if the flag is set to true), or not
* (if the flag is set to false).
* <P>In that case it is up to the user to call it to maintain the
* consistency of the relations. To be kept in mind that if an MBean is
* unregistered and the purge not done immediately, if the ObjectName is
* reused and assigned to another MBean referenced in a relation, calling
* manually this purgeRelations() method will cause trouble, as will
* consider the ObjectName as corresponding to the unregistered MBean, not
* seeing the new one.
*
* <P>The behavior depends on the cardinality of the role where the
* unregistered MBean is referenced:
* <P>- if removing one MBean reference in the role makes its number of
* references less than the minimum degree, the relation has to be removed.
* <P>- if the remaining number of references after removing the MBean
* reference is still in the cardinality range, keep the relation and
* update it calling its handleMBeanUnregistration() callback.
*
* @exception RelationServiceNotRegisteredException if the Relation
* Service is not registered in the MBean Server.
*/
public void purgeRelations()
throws RelationServiceNotRegisteredException {
RELATION_LOGGER.entering(RelationService.class.getName(),
"purgeRelations");
// Can throw RelationServiceNotRegisteredException
isActive();
// Revisit [cebro] Handle the CIM "Delete" and "IfDeleted" qualifier:
// if the unregistered MBean has the "IfDeleted" qualifier,
// possible that the relation itself or other referenced MBeans
// have to be removed (then a notification would have to be sent
// to inform that they should be unregistered.
// Clones the list of notifications to be able to still receive new
// notifications while proceeding those ones
List<MBeanServerNotification> localUnregNtfList;
synchronized(myUnregNtfList) {
localUnregNtfList =
new ArrayList<MBeanServerNotification>(myUnregNtfList);
// Resets list
myUnregNtfList = new ArrayList<MBeanServerNotification>();
}
// Updates the listener filter to avoid receiving notifications for
// those MBeans again
// Makes also a local "myRefedMBeanObjName2RelIdsMap" map, mapping
// ObjectName -> relId -> roles, to remove the MBean from the global
// map
// List of references to be removed from the listener filter
List<ObjectName> obsRefList = new ArrayList<ObjectName>();
// Map including ObjectNames for unregistered MBeans, with
// referencing relation ids and roles
Map<ObjectName,Map<String,List<String>>> localMBean2RelIdMap =
new HashMap<ObjectName,Map<String,List<String>>>();
synchronized(myRefedMBeanObjName2RelIdsMap) {
for (MBeanServerNotification currNtf : localUnregNtfList) {
ObjectName unregMBeanName = currNtf.getMBeanName();
// Adds the unregsitered MBean in the list of references to
// remove from the listener filter
obsRefList.add(unregMBeanName);
// Retrieves the associated map of relation ids and roles
Map<String,List<String>> relIdMap =
myRefedMBeanObjName2RelIdsMap.get(unregMBeanName);
localMBean2RelIdMap.put(unregMBeanName, relIdMap);
myRefedMBeanObjName2RelIdsMap.remove(unregMBeanName);
}
}
// Updates the listener
// Can throw RelationServiceNotRegisteredException
updateUnregistrationListener(null, obsRefList);
for (MBeanServerNotification currNtf : localUnregNtfList) {
ObjectName unregMBeanName = currNtf.getMBeanName();
// Retrieves the relations where the MBean is referenced
Map<String,List<String>> localRelIdMap =
localMBean2RelIdMap.get(unregMBeanName);
// List of relation ids where the unregistered MBean is
// referenced
for (Map.Entry<String,List<String>> currRel :
localRelIdMap.entrySet()) {
final String currRelId = currRel.getKey();
// List of roles of the relation where the MBean is
// referenced
List<String> localRoleNameList = currRel.getValue();
// Checks if the relation has to be removed or not,
// regarding expected minimum role cardinality and current
// number of references after removal of the current one
// If the relation is kept, calls
// handleMBeanUnregistration() callback of the relation to
// update it
//
// Can throw RelationServiceNotRegisteredException
//
// Shall not throw RelationNotFoundException,
// RoleNotFoundException, MBeanException
try {
handleReferenceUnregistration(currRelId,
unregMBeanName,
localRoleNameList);
} catch (RelationNotFoundException exc1) {
throw new RuntimeException(exc1.getMessage());
} catch (RoleNotFoundException exc2) {
throw new RuntimeException(exc2.getMessage());
}
}
}
RELATION_LOGGER.exiting(RelationService.class.getName(),
"purgeRelations");
return;
}
/** {@collect.stats}
* Retrieves the relations where a given MBean is referenced.
* <P>This corresponds to the CIM "References" and "ReferenceNames"
* operations.
*
* @param mbeanName ObjectName of MBean
* @param relationTypeName can be null; if specified, only the relations
* of that type will be considered in the search. Else all relation types
* are considered.
* @param roleName can be null; if specified, only the relations
* where the MBean is referenced in that role will be returned. Else all
* roles are considered.
*
* @return an HashMap, where the keys are the relation ids of the relations
* where the MBean is referenced, and the value is, for each key,
* an ArrayList of role names (as an MBean can be referenced in several
* roles in the same relation).
*
* @exception IllegalArgumentException if null parameter
*/
public Map<String,List<String>>
findReferencingRelations(ObjectName mbeanName,
String relationTypeName,
String roleName)
throws IllegalArgumentException {
if (mbeanName == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"findReferencingRelations",
new Object[] {mbeanName, relationTypeName, roleName});
Map<String,List<String>> result = new HashMap<String,List<String>>();
synchronized(myRefedMBeanObjName2RelIdsMap) {
// Retrieves the relations referencing the MBean
Map<String,List<String>> relId2RoleNamesMap =
myRefedMBeanObjName2RelIdsMap.get(mbeanName);
if (relId2RoleNamesMap != null) {
// Relation Ids where the MBean is referenced
Set<String> allRelIdSet = relId2RoleNamesMap.keySet();
// List of relation ids of interest regarding the selected
// relation type
List<String> relIdList = null;
if (relationTypeName == null) {
// Considers all relations
relIdList = new ArrayList<String>(allRelIdSet);
} else {
relIdList = new ArrayList<String>();
// Considers only the relation ids for relations of given
// type
for (String currRelId : allRelIdSet) {
// Retrieves its relation type
String currRelTypeName = null;
synchronized(myRelId2RelTypeMap) {
currRelTypeName =
myRelId2RelTypeMap.get(currRelId);
}
if (currRelTypeName.equals(relationTypeName)) {
relIdList.add(currRelId);
}
}
}
// Now looks at the roles where the MBean is expected to be
// referenced
for (String currRelId : relIdList) {
// Retrieves list of role names where the MBean is
// referenced
List<String> currRoleNameList =
relId2RoleNamesMap.get(currRelId);
if (roleName == null) {
// All roles to be considered
// Note: no need to test if list not null before
// cloning, MUST be not null else bug :(
result.put(currRelId,
new ArrayList<String>(currRoleNameList));
} else if (currRoleNameList.contains(roleName)) {
// Filters only the relations where the MBean is
// referenced in // given role
List<String> dummyList = new ArrayList<String>();
dummyList.add(roleName);
result.put(currRelId, dummyList);
}
}
}
}
RELATION_LOGGER.exiting(RelationService.class.getName(),
"findReferencingRelations");
return result;
}
/** {@collect.stats}
* Retrieves the MBeans associated to given one in a relation.
* <P>This corresponds to CIM Associators and AssociatorNames operations.
*
* @param mbeanName ObjectName of MBean
* @param relationTypeName can be null; if specified, only the relations
* of that type will be considered in the search. Else all
* relation types are considered.
* @param roleName can be null; if specified, only the relations
* where the MBean is referenced in that role will be considered. Else all
* roles are considered.
*
* @return an HashMap, where the keys are the ObjectNames of the MBeans
* associated to given MBean, and the value is, for each key, an ArrayList
* of the relation ids of the relations where the key MBean is
* associated to given one (as they can be associated in several different
* relations).
*
* @exception IllegalArgumentException if null parameter
*/
public Map<ObjectName,List<String>>
findAssociatedMBeans(ObjectName mbeanName,
String relationTypeName,
String roleName)
throws IllegalArgumentException {
if (mbeanName == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"findAssociatedMBeans",
new Object[] {mbeanName, relationTypeName, roleName});
// Retrieves the map <relation id> -> <role names> for those
// criterias
Map<String,List<String>> relId2RoleNamesMap =
findReferencingRelations(mbeanName,
relationTypeName,
roleName);
Map<ObjectName,List<String>> result =
new HashMap<ObjectName,List<String>>();
for (String currRelId : relId2RoleNamesMap.keySet()) {
// Retrieves ObjectNames of MBeans referenced in this relation
//
// Shall not throw a RelationNotFoundException if incorrect status
// of maps :(
Map<ObjectName,List<String>> objName2RoleNamesMap;
try {
objName2RoleNamesMap = getReferencedMBeans(currRelId);
} catch (RelationNotFoundException exc) {
throw new RuntimeException(exc.getMessage());
}
// For each MBean associated to given one in a relation, adds the
// association <ObjectName> -> <relation id> into result map
for (ObjectName currObjName : objName2RoleNamesMap.keySet()) {
if (!(currObjName.equals(mbeanName))) {
// Sees if this MBean is already associated to the given
// one in another relation
List<String> currRelIdList = result.get(currObjName);
if (currRelIdList == null) {
currRelIdList = new ArrayList<String>();
currRelIdList.add(currRelId);
result.put(currObjName, currRelIdList);
} else {
currRelIdList.add(currRelId);
}
}
}
}
RELATION_LOGGER.exiting(RelationService.class.getName(),
"findAssociatedMBeans");
return result;
}
/** {@collect.stats}
* Returns the relation ids for relations of the given type.
*
* @param relationTypeName relation type name
*
* @return an ArrayList of relation ids.
*
* @exception IllegalArgumentException if null parameter
* @exception RelationTypeNotFoundException if there is no relation type
* with that name.
*/
public List<String> findRelationsOfType(String relationTypeName)
throws IllegalArgumentException,
RelationTypeNotFoundException {
if (relationTypeName == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"findRelationsOfType");
// Can throw RelationTypeNotFoundException
RelationType relType = getRelationType(relationTypeName);
List<String> result;
synchronized(myRelType2RelIdsMap) {
List<String> result1 = myRelType2RelIdsMap.get(relationTypeName);
if (result1 == null)
result = new ArrayList<String>();
else
result = new ArrayList<String>(result1);
}
RELATION_LOGGER.exiting(RelationService.class.getName(),
"findRelationsOfType");
return result;
}
/** {@collect.stats}
* Retrieves role value for given role name in given relation.
*
* @param relationId relation id
* @param roleName name of role
*
* @return the ArrayList of ObjectName objects being the role value
*
* @exception RelationServiceNotRegisteredException if the Relation
* Service is not registered
* @exception IllegalArgumentException if null parameter
* @exception RelationNotFoundException if no relation with given id
* @exception RoleNotFoundException if:
* <P>- there is no role with given name
* <P>or
* <P>- the role is not readable.
*
* @see #setRole
*/
public List<ObjectName> getRole(String relationId,
String roleName)
throws RelationServiceNotRegisteredException,
IllegalArgumentException,
RelationNotFoundException,
RoleNotFoundException {
if (relationId == null || roleName == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"getRole", new Object[] {relationId, roleName});
// Can throw RelationServiceNotRegisteredException
isActive();
// Can throw a RelationNotFoundException
Object relObj = getRelation(relationId);
List<ObjectName> result;
if (relObj instanceof RelationSupport) {
// Internal relation
// Can throw RoleNotFoundException
result = cast(
((RelationSupport)relObj).getRoleInt(roleName,
true,
this,
false));
} else {
// Relation MBean
Object[] params = new Object[1];
params[0] = roleName;
String[] signature = new String[1];
signature[0] = "java.lang.String";
// Can throw MBeanException wrapping a RoleNotFoundException:
// throw wrapped exception
//
// Shall not throw InstanceNotFoundException or ReflectionException
try {
List<ObjectName> invokeResult = cast(
myMBeanServer.invoke(((ObjectName)relObj),
"getRole",
params,
signature));
if (invokeResult == null || invokeResult instanceof ArrayList)
result = invokeResult;
else
result = new ArrayList<ObjectName>(invokeResult);
} catch (InstanceNotFoundException exc1) {
throw new RuntimeException(exc1.getMessage());
} catch (ReflectionException exc2) {
throw new RuntimeException(exc2.getMessage());
} catch (MBeanException exc3) {
Exception wrappedExc = exc3.getTargetException();
if (wrappedExc instanceof RoleNotFoundException) {
throw ((RoleNotFoundException)wrappedExc);
} else {
throw new RuntimeException(wrappedExc.getMessage());
}
}
}
RELATION_LOGGER.exiting(RelationService.class.getName(), "getRole");
return result;
}
/** {@collect.stats}
* Retrieves values of roles with given names in given relation.
*
* @param relationId relation id
* @param roleNameArray array of names of roles to be retrieved
*
* @return a RoleResult object, including a RoleList (for roles
* successfully retrieved) and a RoleUnresolvedList (for roles not
* retrieved).
*
* @exception RelationServiceNotRegisteredException if the Relation
* Service is not registered in the MBean Server
* @exception IllegalArgumentException if null parameter
* @exception RelationNotFoundException if no relation with given id
*
* @see #setRoles
*/
public RoleResult getRoles(String relationId,
String[] roleNameArray)
throws RelationServiceNotRegisteredException,
IllegalArgumentException,
RelationNotFoundException {
if (relationId == null || roleNameArray == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"getRoles", relationId);
// Can throw RelationServiceNotRegisteredException
isActive();
// Can throw a RelationNotFoundException
Object relObj = getRelation(relationId);
RoleResult result = null;
if (relObj instanceof RelationSupport) {
// Internal relation
result = ((RelationSupport)relObj).getRolesInt(roleNameArray,
true,
this);
} else {
// Relation MBean
Object[] params = new Object[1];
params[0] = roleNameArray;
String[] signature = new String[1];
try {
signature[0] = (roleNameArray.getClass()).getName();
} catch (Exception exc) {
// OK : This is an array of java.lang.String
// so this should never happen...
}
// Shall not throw InstanceNotFoundException, ReflectionException
// or MBeanException
try {
result = (RoleResult)
(myMBeanServer.invoke(((ObjectName)relObj),
"getRoles",
params,
signature));
} catch (InstanceNotFoundException exc1) {
throw new RuntimeException(exc1.getMessage());
} catch (ReflectionException exc2) {
throw new RuntimeException(exc2.getMessage());
} catch (MBeanException exc3) {
throw new
RuntimeException((exc3.getTargetException()).getMessage());
}
}
RELATION_LOGGER.exiting(RelationService.class.getName(), "getRoles");
return result;
}
/** {@collect.stats}
* Returns all roles present in the relation.
*
* @param relationId relation id
*
* @return a RoleResult object, including a RoleList (for roles
* successfully retrieved) and a RoleUnresolvedList (for roles not
* readable).
*
* @exception IllegalArgumentException if null parameter
* @exception RelationNotFoundException if no relation for given id
* @exception RelationServiceNotRegisteredException if the Relation
* Service is not registered in the MBean Server
*/
public RoleResult getAllRoles(String relationId)
throws IllegalArgumentException,
RelationNotFoundException,
RelationServiceNotRegisteredException {
if (relationId == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"getRoles", relationId);
// Can throw a RelationNotFoundException
Object relObj = getRelation(relationId);
RoleResult result = null;
if (relObj instanceof RelationSupport) {
// Internal relation
result = ((RelationSupport)relObj).getAllRolesInt(true, this);
} else {
// Relation MBean
// Shall not throw any Exception
try {
result = (RoleResult)
(myMBeanServer.getAttribute(((ObjectName)relObj),
"AllRoles"));
} catch (Exception exc) {
throw new RuntimeException(exc.getMessage());
}
}
RELATION_LOGGER.exiting(RelationService.class.getName(), "getRoles");
return result;
}
/** {@collect.stats}
* Retrieves the number of MBeans currently referenced in the given role.
*
* @param relationId relation id
* @param roleName name of role
*
* @return the number of currently referenced MBeans in that role
*
* @exception IllegalArgumentException if null parameter
* @exception RelationNotFoundException if no relation with given id
* @exception RoleNotFoundException if there is no role with given name
*/
public Integer getRoleCardinality(String relationId,
String roleName)
throws IllegalArgumentException,
RelationNotFoundException,
RoleNotFoundException {
if (relationId == null || roleName == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"getRoleCardinality", new Object[] {relationId, roleName});
// Can throw a RelationNotFoundException
Object relObj = getRelation(relationId);
Integer result = null;
if (relObj instanceof RelationSupport) {
// Internal relation
// Can throw RoleNotFoundException
result = ((RelationSupport)relObj).getRoleCardinality(roleName);
} else {
// Relation MBean
Object[] params = new Object[1];
params[0] = roleName;
String[] signature = new String[1];
signature[0] = "java.lang.String";
// Can throw MBeanException wrapping RoleNotFoundException:
// throw wrapped exception
//
// Shall not throw InstanceNotFoundException or ReflectionException
try {
result = (Integer)
(myMBeanServer.invoke(((ObjectName)relObj),
"getRoleCardinality",
params,
signature));
} catch (InstanceNotFoundException exc1) {
throw new RuntimeException(exc1.getMessage());
} catch (ReflectionException exc2) {
throw new RuntimeException(exc2.getMessage());
} catch (MBeanException exc3) {
Exception wrappedExc = exc3.getTargetException();
if (wrappedExc instanceof RoleNotFoundException) {
throw ((RoleNotFoundException)wrappedExc);
} else {
throw new RuntimeException(wrappedExc.getMessage());
}
}
}
RELATION_LOGGER.exiting(RelationService.class.getName(),
"getRoleCardinality");
return result;
}
/** {@collect.stats}
* Sets the given role in given relation.
* <P>Will check the role according to its corresponding role definition
* provided in relation's relation type
* <P>The Relation Service will keep track of the change to keep the
* consistency of relations by handling referenced MBean unregistrations.
*
* @param relationId relation id
* @param role role to be set (name and new value)
*
* @exception RelationServiceNotRegisteredException if the Relation
* Service is not registered in the MBean Server
* @exception IllegalArgumentException if null parameter
* @exception RelationNotFoundException if no relation with given id
* @exception RoleNotFoundException if the role does not exist or is not
* writable
* @exception InvalidRoleValueException if value provided for role is not
* valid:
* <P>- the number of referenced MBeans in given value is less than
* expected minimum degree
* <P>or
* <P>- the number of referenced MBeans in provided value exceeds expected
* maximum degree
* <P>or
* <P>- one referenced MBean in the value is not an Object of the MBean
* class expected for that role
* <P>or
* <P>- an MBean provided for that role does not exist
*
* @see #getRole
*/
public void setRole(String relationId,
Role role)
throws RelationServiceNotRegisteredException,
IllegalArgumentException,
RelationNotFoundException,
RoleNotFoundException,
InvalidRoleValueException {
if (relationId == null || role == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"setRole", new Object[] {relationId, role});
// Can throw RelationServiceNotRegisteredException
isActive();
// Can throw a RelationNotFoundException
Object relObj = getRelation(relationId);
if (relObj instanceof RelationSupport) {
// Internal relation
// Can throw RoleNotFoundException,
// InvalidRoleValueException and
// RelationServiceNotRegisteredException
//
// Shall not throw RelationTypeNotFoundException
// (as relation exists in the RS, its relation type is known)
try {
((RelationSupport)relObj).setRoleInt(role,
true,
this,
false);
} catch (RelationTypeNotFoundException exc) {
throw new RuntimeException(exc.getMessage());
}
} else {
// Relation MBean
Object[] params = new Object[1];
params[0] = role;
String[] signature = new String[1];
signature[0] = "javax.management.relation.Role";
// Can throw MBeanException wrapping RoleNotFoundException,
// InvalidRoleValueException
//
// Shall not MBeanException wrapping an MBeanException wrapping
// RelationTypeNotFoundException, or ReflectionException, or
// InstanceNotFoundException
try {
myMBeanServer.setAttribute(((ObjectName)relObj),
new Attribute("Role", role));
} catch (InstanceNotFoundException exc1) {
throw new RuntimeException(exc1.getMessage());
} catch (ReflectionException exc3) {
throw new RuntimeException(exc3.getMessage());
} catch (MBeanException exc2) {
Exception wrappedExc = exc2.getTargetException();
if (wrappedExc instanceof RoleNotFoundException) {
throw ((RoleNotFoundException)wrappedExc);
} else if (wrappedExc instanceof InvalidRoleValueException) {
throw ((InvalidRoleValueException)wrappedExc);
} else {
throw new RuntimeException(wrappedExc.getMessage());
}
} catch (AttributeNotFoundException exc4) {
throw new RuntimeException(exc4.getMessage());
} catch (InvalidAttributeValueException exc5) {
throw new RuntimeException(exc5.getMessage());
}
}
RELATION_LOGGER.exiting(RelationService.class.getName(), "setRole");
return;
}
/** {@collect.stats}
* Sets the given roles in given relation.
* <P>Will check the role according to its corresponding role definition
* provided in relation's relation type
* <P>The Relation Service keeps track of the changes to keep the
* consistency of relations by handling referenced MBean unregistrations.
*
* @param relationId relation id
* @param roleList list of roles to be set
*
* @return a RoleResult object, including a RoleList (for roles
* successfully set) and a RoleUnresolvedList (for roles not
* set).
*
* @exception RelationServiceNotRegisteredException if the Relation
* Service is not registered in the MBean Server
* @exception IllegalArgumentException if null parameter
* @exception RelationNotFoundException if no relation with given id
*
* @see #getRoles
*/
public RoleResult setRoles(String relationId,
RoleList roleList)
throws RelationServiceNotRegisteredException,
IllegalArgumentException,
RelationNotFoundException {
if (relationId == null || roleList == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"setRoles", new Object[] {relationId, roleList});
// Can throw RelationServiceNotRegisteredException
isActive();
// Can throw a RelationNotFoundException
Object relObj = getRelation(relationId);
RoleResult result = null;
if (relObj instanceof RelationSupport) {
// Internal relation
// Can throw RelationServiceNotRegisteredException
//
// Shall not throw RelationTypeNotFoundException (as relation is
// known, its relation type exists)
try {
result = ((RelationSupport)relObj).setRolesInt(roleList,
true,
this);
} catch (RelationTypeNotFoundException exc) {
throw new RuntimeException(exc.getMessage());
}
} else {
// Relation MBean
Object[] params = new Object[1];
params[0] = roleList;
String[] signature = new String[1];
signature[0] = "javax.management.relation.RoleList";
// Shall not throw InstanceNotFoundException or an MBeanException
// or ReflectionException
try {
result = (RoleResult)
(myMBeanServer.invoke(((ObjectName)relObj),
"setRoles",
params,
signature));
} catch (InstanceNotFoundException exc1) {
throw new RuntimeException(exc1.getMessage());
} catch (ReflectionException exc3) {
throw new RuntimeException(exc3.getMessage());
} catch (MBeanException exc2) {
throw new
RuntimeException((exc2.getTargetException()).getMessage());
}
}
RELATION_LOGGER.exiting(RelationService.class.getName(), "setRoles");
return result;
}
/** {@collect.stats}
* Retrieves MBeans referenced in the various roles of the relation.
*
* @param relationId relation id
*
* @return a HashMap mapping:
* <P> ObjectName -> ArrayList of String (role
* names)
*
* @exception IllegalArgumentException if null parameter
* @exception RelationNotFoundException if no relation for given
* relation id
*/
public Map<ObjectName,List<String>>
getReferencedMBeans(String relationId)
throws IllegalArgumentException,
RelationNotFoundException {
if (relationId == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"getReferencedMBeans", relationId);
// Can throw a RelationNotFoundException
Object relObj = getRelation(relationId);
Map<ObjectName,List<String>> result;
if (relObj instanceof RelationSupport) {
// Internal relation
result = ((RelationSupport)relObj).getReferencedMBeans();
} else {
// Relation MBean
// No Exception
try {
result = cast(
myMBeanServer.getAttribute(((ObjectName)relObj),
"ReferencedMBeans"));
} catch (Exception exc) {
throw new RuntimeException(exc.getMessage());
}
}
RELATION_LOGGER.exiting(RelationService.class.getName(),
"getReferencedMBeans");
return result;
}
/** {@collect.stats}
* Returns name of associated relation type for given relation.
*
* @param relationId relation id
*
* @return the name of the associated relation type.
*
* @exception IllegalArgumentException if null parameter
* @exception RelationNotFoundException if no relation for given
* relation id
*/
public String getRelationTypeName(String relationId)
throws IllegalArgumentException,
RelationNotFoundException {
if (relationId == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"getRelationTypeName", relationId);
// Can throw a RelationNotFoundException
Object relObj = getRelation(relationId);
String result = null;
if (relObj instanceof RelationSupport) {
// Internal relation
result = ((RelationSupport)relObj).getRelationTypeName();
} else {
// Relation MBean
// No Exception
try {
result = (String)
(myMBeanServer.getAttribute(((ObjectName)relObj),
"RelationTypeName"));
} catch (Exception exc) {
throw new RuntimeException(exc.getMessage());
}
}
RELATION_LOGGER.exiting(RelationService.class.getName(),
"getRelationTypeName");
return result;
}
//
// NotificationListener Interface
//
/** {@collect.stats}
* Invoked when a JMX notification occurs.
* Currently handles notifications for unregistration of MBeans, either
* referenced in a relation role or being a relation itself.
*
* @param notif The notification.
* @param handback An opaque object which helps the listener to
* associate information regarding the MBean emitter (can be null).
*/
public void handleNotification(Notification notif,
Object handback) {
if (notif == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"handleNotification", notif);
if (notif instanceof MBeanServerNotification) {
MBeanServerNotification mbsNtf = (MBeanServerNotification) notif;
String ntfType = notif.getType();
if (ntfType.equals(
MBeanServerNotification.UNREGISTRATION_NOTIFICATION )) {
ObjectName mbeanName =
((MBeanServerNotification)notif).getMBeanName();
// Note: use a flag to block access to
// myRefedMBeanObjName2RelIdsMap only for a quick access
boolean isRefedMBeanFlag = false;
synchronized(myRefedMBeanObjName2RelIdsMap) {
if (myRefedMBeanObjName2RelIdsMap.containsKey(mbeanName)) {
// Unregistration of a referenced MBean
synchronized(myUnregNtfList) {
myUnregNtfList.add(mbsNtf);
}
isRefedMBeanFlag = true;
}
if (isRefedMBeanFlag && myPurgeFlag) {
// Immediate purge
// Can throw RelationServiceNotRegisteredException
// but assume that will be fine :)
try {
purgeRelations();
} catch (Exception exc) {
throw new RuntimeException(exc.getMessage());
}
}
}
// Note: do both tests as a relation can be an MBean and be
// itself referenced in another relation :)
String relId = null;
synchronized(myRelMBeanObjName2RelIdMap){
relId = myRelMBeanObjName2RelIdMap.get(mbeanName);
}
if (relId != null) {
// Unregistration of a relation MBean
// Can throw RelationTypeNotFoundException,
// RelationServiceNotRegisteredException
//
// Shall not throw RelationTypeNotFoundException or
// InstanceNotFoundException
try {
removeRelation(relId);
} catch (Exception exc) {
throw new RuntimeException(exc.getMessage());
}
}
}
}
RELATION_LOGGER.exiting(RelationService.class.getName(),
"handleNotification");
return;
}
//
// NotificationBroadcaster interface
//
/** {@collect.stats}
* Returns a NotificationInfo object containing the name of the Java class
* of the notification and the notification types sent.
*/
public MBeanNotificationInfo[] getNotificationInfo() {
RELATION_LOGGER.entering(RelationService.class.getName(),
"getNotificationInfo");
MBeanNotificationInfo[] ntfInfoArray =
new MBeanNotificationInfo[1];
String ntfClass = "javax.management.relation.RelationNotification";
String[] ntfTypes = new String[] {
RelationNotification.RELATION_BASIC_CREATION,
RelationNotification.RELATION_MBEAN_CREATION,
RelationNotification.RELATION_BASIC_UPDATE,
RelationNotification.RELATION_MBEAN_UPDATE,
RelationNotification.RELATION_BASIC_REMOVAL,
RelationNotification.RELATION_MBEAN_REMOVAL,
};
String ntfDesc = "Sent when a relation is created, updated or deleted.";
MBeanNotificationInfo ntfInfo =
new MBeanNotificationInfo(ntfTypes, ntfClass, ntfDesc);
RELATION_LOGGER.exiting(RelationService.class.getName(),
"getNotificationInfo");
return new MBeanNotificationInfo[] {ntfInfo};
}
//
// Misc
//
// Adds given object as a relation type.
//
// -param relationTypeObj relation type object
//
// -exception IllegalArgumentException if null parameter
// -exception InvalidRelationTypeException if there is already a relation
// type with that name
private void addRelationTypeInt(RelationType relationTypeObj)
throws IllegalArgumentException,
InvalidRelationTypeException {
if (relationTypeObj == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"addRelationTypeInt");
String relTypeName = relationTypeObj.getRelationTypeName();
// Checks that there is not already a relation type with that name
// existing in the Relation Service
try {
// Can throw a RelationTypeNotFoundException (in fact should ;)
RelationType relType = getRelationType(relTypeName);
if (relType != null) {
String excMsg = "There is already a relation type in the Relation Service with name ";
StringBuilder excMsgStrB = new StringBuilder(excMsg);
excMsgStrB.append(relTypeName);
throw new InvalidRelationTypeException(excMsgStrB.toString());
}
} catch (RelationTypeNotFoundException exc) {
// OK : The RelationType could not be found.
}
// Adds the relation type
synchronized(myRelType2ObjMap) {
myRelType2ObjMap.put(relTypeName, relationTypeObj);
}
if (relationTypeObj instanceof RelationTypeSupport) {
((RelationTypeSupport)relationTypeObj).setRelationServiceFlag(true);
}
RELATION_LOGGER.exiting(RelationService.class.getName(),
"addRelationTypeInt");
return;
}
// Retrieves relation type with given name
//
// -param relationTypeName expected name of a relation type created in the
// Relation Service
//
// -return RelationType object corresponding to given name
//
// -exception IllegalArgumentException if null parameter
// -exception RelationTypeNotFoundException if no relation type for that
// name created in Relation Service
//
RelationType getRelationType(String relationTypeName)
throws IllegalArgumentException,
RelationTypeNotFoundException {
if (relationTypeName == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"getRelationType", relationTypeName);
// No null relation type accepted, so can use get()
RelationType relType = null;
synchronized(myRelType2ObjMap) {
relType = (myRelType2ObjMap.get(relationTypeName));
}
if (relType == null) {
String excMsg = "No relation type created in the Relation Service with the name ";
StringBuilder excMsgStrB = new StringBuilder(excMsg);
excMsgStrB.append(relationTypeName);
throw new RelationTypeNotFoundException(excMsgStrB.toString());
}
RELATION_LOGGER.exiting(RelationService.class.getName(),
"getRelationType");
return relType;
}
// Retrieves relation corresponding to given relation id.
// Returns either:
// - a RelationSupport object if the relation is internal
// or
// - the ObjectName of the corresponding MBean
//
// -param relationId expected relation id
//
// -return RelationSupport object or ObjectName of relation with given id
//
// -exception IllegalArgumentException if null parameter
// -exception RelationNotFoundException if no relation for that
// relation id created in Relation Service
//
Object getRelation(String relationId)
throws IllegalArgumentException,
RelationNotFoundException {
if (relationId == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"getRelation", relationId);
// No null relation accepted, so can use get()
Object rel = null;
synchronized(myRelId2ObjMap) {
rel = myRelId2ObjMap.get(relationId);
}
if (rel == null) {
String excMsg = "No relation associated to relation id " + relationId;
throw new RelationNotFoundException(excMsg);
}
RELATION_LOGGER.exiting(RelationService.class.getName(),
"getRelation");
return rel;
}
// Adds a new MBean reference (reference to an ObjectName) in the
// referenced MBean map (myRefedMBeanObjName2RelIdsMap).
//
// -param objectName ObjectName of new referenced MBean
// -param relationId relation id of the relation where the MBean is
// referenced
// -param roleName name of the role where the MBean is referenced
//
// -return boolean:
// - true if the MBean was not referenced before, so really a new
// reference
// - false else
//
// -exception IllegalArgumentException if null parameter
private boolean addNewMBeanReference(ObjectName objectName,
String relationId,
String roleName)
throws IllegalArgumentException {
if (objectName == null ||
relationId == null ||
roleName == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"addNewMBeanReference",
new Object[] {objectName, relationId, roleName});
boolean isNewFlag = false;
synchronized(myRefedMBeanObjName2RelIdsMap) {
// Checks if the MBean was already referenced
// No null value allowed, use get() directly
Map<String,List<String>> mbeanRefMap =
myRefedMBeanObjName2RelIdsMap.get(objectName);
if (mbeanRefMap == null) {
// MBean not referenced in any relation yet
isNewFlag = true;
// List of roles where the MBean is referenced in given
// relation
List<String> roleNames = new ArrayList<String>();
roleNames.add(roleName);
// Map of relations where the MBean is referenced
mbeanRefMap = new HashMap<String,List<String>>();
mbeanRefMap.put(relationId, roleNames);
myRefedMBeanObjName2RelIdsMap.put(objectName, mbeanRefMap);
} else {
// MBean already referenced in at least another relation
// Checks if already referenced in another role in current
// relation
List<String> roleNames = mbeanRefMap.get(relationId);
if (roleNames == null) {
// MBean not referenced in current relation
// List of roles where the MBean is referenced in given
// relation
roleNames = new ArrayList<String>();
roleNames.add(roleName);
// Adds new reference done in current relation
mbeanRefMap.put(relationId, roleNames);
} else {
// MBean already referenced in current relation in another
// role
// Adds new reference done
roleNames.add(roleName);
}
}
}
RELATION_LOGGER.exiting(RelationService.class.getName(),
"addNewMBeanReference");
return isNewFlag;
}
// Removes an obsolete MBean reference (reference to an ObjectName) in
// the referenced MBean map (myRefedMBeanObjName2RelIdsMap).
//
// -param objectName ObjectName of MBean no longer referenced
// -param relationId relation id of the relation where the MBean was
// referenced
// -param roleName name of the role where the MBean was referenced
// -param allRolesFlag flag, if true removes reference to MBean for all
// roles in the relation, not only for the one above
//
// -return boolean:
// - true if the MBean is no longer reference in any relation
// - false else
//
// -exception IllegalArgumentException if null parameter
private boolean removeMBeanReference(ObjectName objectName,
String relationId,
String roleName,
boolean allRolesFlag)
throws IllegalArgumentException {
if (objectName == null ||
relationId == null ||
roleName == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"removeMBeanReference",
new Object[] {objectName, relationId, roleName, allRolesFlag});
boolean noLongerRefFlag = false;
synchronized(myRefedMBeanObjName2RelIdsMap) {
// Retrieves the set of relations (designed via their relation ids)
// where the MBean is referenced
// Note that it is possible that the MBean has already been removed
// from the internal map: this is the case when the MBean is
// unregistered, the role is updated, then we arrive here.
HashMap mbeanRefMap = (HashMap)
(myRefedMBeanObjName2RelIdsMap.get(objectName));
if (mbeanRefMap == null) {
// The MBean is no longer referenced
RELATION_LOGGER.exiting(RelationService.class.getName(),
"removeMBeanReference");
return true;
}
ArrayList roleNames = new ArrayList();
if (!allRolesFlag) {
// Now retrieves the roles of current relation where the MBean
// was referenced
roleNames = (ArrayList)(mbeanRefMap.get(relationId));
// Removes obsolete reference to role
int obsRefIdx = roleNames.indexOf(roleName);
if (obsRefIdx != -1) {
roleNames.remove(obsRefIdx);
}
}
// Checks if there is still at least one role in current relation
// where the MBean is referenced
if (roleNames.isEmpty() || allRolesFlag) {
// MBean no longer referenced in current relation: removes
// entry
mbeanRefMap.remove(relationId);
}
// Checks if the MBean is still referenced in at least on relation
if (mbeanRefMap.isEmpty()) {
// MBean no longer referenced in any relation: removes entry
myRefedMBeanObjName2RelIdsMap.remove(objectName);
noLongerRefFlag = true;
}
}
RELATION_LOGGER.exiting(RelationService.class.getName(),
"removeMBeanReference");
return noLongerRefFlag;
}
// Updates the listener registered to the MBean Server to be informed of
// referenced MBean unregistrations
//
// -param newRefList ArrayList of ObjectNames for new references done
// to MBeans (can be null)
// -param obsoleteRefList ArrayList of ObjectNames for obsolete references
// to MBeans (can be null)
//
// -exception RelationServiceNotRegisteredException if the Relation
// Service is not registered in the MBean Server.
private void updateUnregistrationListener(List newRefList,
List obsoleteRefList)
throws RelationServiceNotRegisteredException {
if (newRefList != null && obsoleteRefList != null) {
if (newRefList.isEmpty() && obsoleteRefList.isEmpty()) {
// Nothing to do :)
return;
}
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"updateUnregistrationListener",
new Object[] {newRefList, obsoleteRefList});
// Can throw RelationServiceNotRegisteredException
isActive();
if (newRefList != null || obsoleteRefList != null) {
boolean newListenerFlag = false;
if (myUnregNtfFilter == null) {
// Initialize it to be able to synchronise it :)
myUnregNtfFilter = new MBeanServerNotificationFilter();
newListenerFlag = true;
}
synchronized(myUnregNtfFilter) {
// Enables ObjectNames in newRefList
if (newRefList != null) {
for (Iterator newRefIter = newRefList.iterator();
newRefIter.hasNext();) {
ObjectName newObjName = (ObjectName)
(newRefIter.next());
myUnregNtfFilter.enableObjectName(newObjName);
}
}
if (obsoleteRefList != null) {
// Disables ObjectNames in obsoleteRefList
for (Iterator obsRefIter = obsoleteRefList.iterator();
obsRefIter.hasNext();) {
ObjectName obsObjName = (ObjectName)
(obsRefIter.next());
myUnregNtfFilter.disableObjectName(obsObjName);
}
}
// Under test
if (newListenerFlag) {
try {
myMBeanServer.addNotificationListener(
MBeanServerDelegate.DELEGATE_NAME,
this,
myUnregNtfFilter,
null);
} catch (InstanceNotFoundException exc) {
throw new
RelationServiceNotRegisteredException(exc.getMessage());
}
}
// End test
// if (!newListenerFlag) {
// The Relation Service was already registered as a
// listener:
// removes it
// Shall not throw InstanceNotFoundException (as the
// MBean Server Delegate is expected to exist) or
// ListenerNotFoundException (as it has been checked above
// that the Relation Service is registered)
// try {
// myMBeanServer.removeNotificationListener(
// MBeanServerDelegate.DELEGATE_NAME,
// this);
// } catch (InstanceNotFoundException exc1) {
// throw new RuntimeException(exc1.getMessage());
// } catch (ListenerNotFoundException exc2) {
// throw new
// RelationServiceNotRegisteredException(exc2.getMessage());
// }
// }
// Adds Relation Service with current filter
// Can throw InstanceNotFoundException if the Relation
// Service is not registered, to be transformed into
// RelationServiceNotRegisteredException
//
// Assume that there will not be any InstanceNotFoundException
// for the MBean Server Delegate :)
// try {
// myMBeanServer.addNotificationListener(
// MBeanServerDelegate.DELEGATE_NAME,
// this,
// myUnregNtfFilter,
// null);
// } catch (InstanceNotFoundException exc) {
// throw new
// RelationServiceNotRegisteredException(exc.getMessage());
// }
}
}
RELATION_LOGGER.exiting(RelationService.class.getName(),
"updateUnregistrationListener");
return;
}
// Adds a relation (being either a RelationSupport object or an MBean
// referenced using its ObjectName) in the Relation Service.
// Will send a notification RelationNotification with type:
// - RelationNotification.RELATION_BASIC_CREATION for internal relation
// creation
// - RelationNotification.RELATION_MBEAN_CREATION for an MBean being added
// as a relation.
//
// -param relationBaseFlag flag true if the relation is a RelationSupport
// object, false if it is an MBean
// -param relationObj RelationSupport object (if relation is internal)
// -param relationObjName ObjectName of the MBean to be added as a relation
// (only for the relation MBean)
// -param relationId relation identifier, to uniquely identify the relation
// inside the Relation Service
// -param relationTypeName name of the relation type (has to be created
// in the Relation Service)
// -param roleList role list to initialize roles of the relation
// (can be null)
//
// -exception IllegalArgumentException if null paramater
// -exception RelationServiceNotRegisteredException if the Relation
// Service is not registered in the MBean Server
// -exception RoleNotFoundException if a value is provided for a role
// that does not exist in the relation type
// -exception InvalidRelationIdException if relation id already used
// -exception RelationTypeNotFoundException if relation type not known in
// Relation Service
// -exception InvalidRoleValueException if:
// - the same role name is used for two different roles
// - the number of referenced MBeans in given value is less than
// expected minimum degree
// - the number of referenced MBeans in provided value exceeds expected
// maximum degree
// - one referenced MBean in the value is not an Object of the MBean
// class expected for that role
// - an MBean provided for that role does not exist
private void addRelationInt(boolean relationBaseFlag,
RelationSupport relationObj,
ObjectName relationObjName,
String relationId,
String relationTypeName,
RoleList roleList)
throws IllegalArgumentException,
RelationServiceNotRegisteredException,
RoleNotFoundException,
InvalidRelationIdException,
RelationTypeNotFoundException,
InvalidRoleValueException {
if (relationId == null ||
relationTypeName == null ||
(relationBaseFlag &&
(relationObj == null ||
relationObjName != null)) ||
(!relationBaseFlag &&
(relationObjName == null ||
relationObj != null))) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"addRelationInt", new Object[] {relationBaseFlag, relationObj,
relationObjName, relationId, relationTypeName, roleList});
// Can throw RelationServiceNotRegisteredException
isActive();
// Checks if there is already a relation with given id
try {
// Can throw a RelationNotFoundException (in fact should :)
Object rel = getRelation(relationId);
if (rel != null) {
// There is already a relation with that id
String excMsg = "There is already a relation with id ";
StringBuilder excMsgStrB = new StringBuilder(excMsg);
excMsgStrB.append(relationId);
throw new InvalidRelationIdException(excMsgStrB.toString());
}
} catch (RelationNotFoundException exc) {
// OK : The Relation could not be found.
}
// Retrieves the relation type
// Can throw RelationTypeNotFoundException
RelationType relType = getRelationType(relationTypeName);
// Checks that each provided role conforms to its role info provided in
// the relation type
// First retrieves a local list of the role infos of the relation type
// to see which roles have not been initialized
// Note: no need to test if list not null before cloning, not allowed
// to have an empty relation type.
ArrayList roleInfoList = (ArrayList)
(((ArrayList)(relType.getRoleInfos())).clone());
if (roleList != null) {
for (Iterator roleIter = roleList.iterator();
roleIter.hasNext();) {
Role currRole = (Role)(roleIter.next());
String currRoleName = currRole.getRoleName();
ArrayList currRoleValue = (ArrayList)
(currRole.getRoleValue());
// Retrieves corresponding role info
// Can throw a RoleInfoNotFoundException to be converted into a
// RoleNotFoundException
RoleInfo roleInfo = null;
try {
roleInfo = relType.getRoleInfo(currRoleName);
} catch (RoleInfoNotFoundException exc) {
throw new RoleNotFoundException(exc.getMessage());
}
// Checks that role conforms to role info,
Integer status = checkRoleInt(2,
currRoleName,
currRoleValue,
roleInfo,
false);
int pbType = status.intValue();
if (pbType != 0) {
// A problem has occurred: throws appropriate exception
// here InvalidRoleValueException
throwRoleProblemException(pbType, currRoleName);
}
// Removes role info for that list from list of role infos for
// roles to be defaulted
int roleInfoIdx = roleInfoList.indexOf(roleInfo);
// Note: no need to check if != -1, MUST be there :)
roleInfoList.remove(roleInfoIdx);
}
}
// Initializes roles not initialized by roleList
// Can throw InvalidRoleValueException
initializeMissingRoles(relationBaseFlag,
relationObj,
relationObjName,
relationId,
relationTypeName,
roleInfoList);
// Creation of relation successfull!!!!
// Updates internal maps
// Relation id to object map
synchronized(myRelId2ObjMap) {
if (relationBaseFlag) {
// Note: do not clone relation object, created by us :)
myRelId2ObjMap.put(relationId, relationObj);
} else {
myRelId2ObjMap.put(relationId, relationObjName);
}
}
// Relation id to relation type name map
synchronized(myRelId2RelTypeMap) {
myRelId2RelTypeMap.put(relationId,
relationTypeName);
}
// Relation type to relation id map
synchronized(myRelType2RelIdsMap) {
List<String> relIdList =
myRelType2RelIdsMap.get(relationTypeName);
boolean firstRelFlag = false;
if (relIdList == null) {
firstRelFlag = true;
relIdList = new ArrayList<String>();
}
relIdList.add(relationId);
if (firstRelFlag) {
myRelType2RelIdsMap.put(relationTypeName, relIdList);
}
}
// Referenced MBean to relation id map
// Only role list parameter used, as default initialization of roles
// done automatically in initializeMissingRoles() sets each
// uninitialized role to an empty value.
for (Iterator roleIter = roleList.iterator();
roleIter.hasNext();) {
Role currRole = (Role)(roleIter.next());
// Creates a dummy empty ArrayList of ObjectNames to be the old
// role value :)
List<ObjectName> dummyList = new ArrayList<ObjectName>();
// Will not throw a RelationNotFoundException (as the RelId2Obj map
// has been updated above) so catch it :)
try {
updateRoleMap(relationId, currRole, dummyList);
} catch (RelationNotFoundException exc) {
// OK : The Relation could not be found.
}
}
// Sends a notification for relation creation
// Will not throw RelationNotFoundException so catch it :)
try {
sendRelationCreationNotification(relationId);
} catch (RelationNotFoundException exc) {
// OK : The Relation could not be found.
}
RELATION_LOGGER.exiting(RelationService.class.getName(),
"addRelationInt");
return;
}
// Checks that given role conforms to given role info.
//
// -param chkType type of check:
// - 1: read, just check read access
// - 2: write, check value and write access if writeChkFlag
// -param roleName role name
// -param roleValue role value
// -param roleInfo corresponding role info
// -param writeChkFlag boolean to specify a current write access and
// to check it
//
// -return Integer with value:
// - 0: ok
// - RoleStatus.NO_ROLE_WITH_NAME
// - RoleStatus.ROLE_NOT_READABLE
// - RoleStatus.ROLE_NOT_WRITABLE
// - RoleStatus.LESS_THAN_MIN_ROLE_DEGREE
// - RoleStatus.MORE_THAN_MAX_ROLE_DEGREE
// - RoleStatus.REF_MBEAN_OF_INCORRECT_CLASS
// - RoleStatus.REF_MBEAN_NOT_REGISTERED
//
// -exception IllegalArgumentException if null parameter
private Integer checkRoleInt(int chkType,
String roleName,
List roleValue,
RoleInfo roleInfo,
boolean writeChkFlag)
throws IllegalArgumentException {
if (roleName == null ||
roleInfo == null ||
(chkType == 2 && roleValue == null)) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"checkRoleInt", new Object[] {chkType, roleName,
roleValue, roleInfo, writeChkFlag});
// Compares names
String expName = roleInfo.getName();
if (!(roleName.equals(expName))) {
RELATION_LOGGER.exiting(RelationService.class.getName(),
"checkRoleInt");
return new Integer(RoleStatus.NO_ROLE_WITH_NAME);
}
// Checks read access if required
if (chkType == 1) {
boolean isReadable = roleInfo.isReadable();
if (!isReadable) {
RELATION_LOGGER.exiting(RelationService.class.getName(),
"checkRoleInt");
return new Integer(RoleStatus.ROLE_NOT_READABLE);
} else {
// End of check :)
RELATION_LOGGER.exiting(RelationService.class.getName(),
"checkRoleInt");
return new Integer(0);
}
}
// Checks write access if required
if (writeChkFlag) {
boolean isWritable = roleInfo.isWritable();
if (!isWritable) {
RELATION_LOGGER.exiting(RelationService.class.getName(),
"checkRoleInt");
return new Integer(RoleStatus.ROLE_NOT_WRITABLE);
}
}
int refNbr = roleValue.size();
// Checks minimum cardinality
boolean chkMinFlag = roleInfo.checkMinDegree(refNbr);
if (!chkMinFlag) {
RELATION_LOGGER.exiting(RelationService.class.getName(),
"checkRoleInt");
return new Integer(RoleStatus.LESS_THAN_MIN_ROLE_DEGREE);
}
// Checks maximum cardinality
boolean chkMaxFlag = roleInfo.checkMaxDegree(refNbr);
if (!chkMaxFlag) {
RELATION_LOGGER.exiting(RelationService.class.getName(),
"checkRoleInt");
return new Integer(RoleStatus.MORE_THAN_MAX_ROLE_DEGREE);
}
// Verifies that each referenced MBean is registered in the MBean
// Server and that it is an instance of the class specified in the
// role info, or of a subclass of it
// Note that here again this is under the assumption that
// referenced MBeans, relation MBeans and the Relation Service are
// registered in the same MBean Server.
String expClassName = roleInfo.getRefMBeanClassName();
for (Iterator refMBeanIter = roleValue.iterator();
refMBeanIter.hasNext();) {
ObjectName currObjName = (ObjectName)(refMBeanIter.next());
// Checks it is registered
if (currObjName == null) {
RELATION_LOGGER.exiting(RelationService.class.getName(),
"checkRoleInt");
return new Integer(RoleStatus.REF_MBEAN_NOT_REGISTERED);
}
// Checks if it is of the correct class
// Can throw an InstanceNotFoundException, if MBean not registered
try {
boolean classSts = myMBeanServer.isInstanceOf(currObjName,
expClassName);
if (!classSts) {
RELATION_LOGGER.exiting(RelationService.class.getName(),
"checkRoleInt");
return new Integer(RoleStatus.REF_MBEAN_OF_INCORRECT_CLASS);
}
} catch (InstanceNotFoundException exc) {
RELATION_LOGGER.exiting(RelationService.class.getName(),
"checkRoleInt");
return new Integer(RoleStatus.REF_MBEAN_NOT_REGISTERED);
}
}
RELATION_LOGGER.exiting(RelationService.class.getName(),
"checkRoleInt");
return new Integer(0);
}
// Initializes roles associated to given role infos to default value (empty
// ArrayList of ObjectNames) in given relation.
// It will succeed for every role except if the role info has a minimum
// cardinality greater than 0. In that case, an InvalidRoleValueException
// will be raised.
//
// -param relationBaseFlag flag true if the relation is a RelationSupport
// object, false if it is an MBean
// -param relationObj RelationSupport object (if relation is internal)
// -param relationObjName ObjectName of the MBean to be added as a relation
// (only for the relation MBean)
// -param relationId relation id
// -param relationTypeName name of the relation type (has to be created
// in the Relation Service)
// -param roleInfoList list of role infos for roles to be defaulted
//
// -exception IllegalArgumentException if null paramater
// -exception RelationServiceNotRegisteredException if the Relation
// Service is not registered in the MBean Server
// -exception InvalidRoleValueException if role must have a non-empty
// value
// Revisit [cebro] Handle CIM qualifiers as REQUIRED to detect roles which
// should have been initialized by the user
private void initializeMissingRoles(boolean relationBaseFlag,
RelationSupport relationObj,
ObjectName relationObjName,
String relationId,
String relationTypeName,
List roleInfoList)
throws IllegalArgumentException,
RelationServiceNotRegisteredException,
InvalidRoleValueException {
if ((relationBaseFlag &&
(relationObj == null ||
relationObjName != null)) ||
(!relationBaseFlag &&
(relationObjName == null ||
relationObj != null)) ||
relationId == null ||
relationTypeName == null ||
roleInfoList == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"initializeMissingRoles", new Object[] {relationBaseFlag,
relationObj, relationObjName, relationId, relationTypeName,
roleInfoList});
// Can throw RelationServiceNotRegisteredException
isActive();
// For each role info (corresponding to a role not initialized by the
// role list provided by the user), try to set in the relation a role
// with an empty list of ObjectNames.
// A check is performed to verify that the role can be set to an
// empty value, according to its minimum cardinality
for (Iterator roleInfoIter = roleInfoList.iterator();
roleInfoIter.hasNext();) {
RoleInfo currRoleInfo = (RoleInfo)(roleInfoIter.next());
String roleName = currRoleInfo.getName();
// Creates an empty value
List<ObjectName> emptyValue = new ArrayList<ObjectName>();
// Creates a role
Role role = new Role(roleName, emptyValue);
if (relationBaseFlag) {
// Internal relation
// Can throw InvalidRoleValueException
//
// Will not throw RoleNotFoundException (role to be
// initialized), or RelationNotFoundException, or
// RelationTypeNotFoundException
try {
relationObj.setRoleInt(role, true, this, false);
} catch (RoleNotFoundException exc1) {
throw new RuntimeException(exc1.getMessage());
} catch (RelationNotFoundException exc2) {
throw new RuntimeException(exc2.getMessage());
} catch (RelationTypeNotFoundException exc3) {
throw new RuntimeException(exc3.getMessage());
}
} else {
// Relation is an MBean
// Use standard setRole()
Object[] params = new Object[1];
params[0] = role;
String[] signature = new String[1];
signature[0] = "javax.management.relation.Role";
// Can throw MBeanException wrapping
// InvalidRoleValueException. Returns the target exception to
// be homogeneous.
//
// Will not throw MBeanException (wrapping
// RoleNotFoundException or MBeanException) or
// InstanceNotFoundException, or ReflectionException
//
// Again here the assumption is that the Relation Service and
// the relation MBeans are registered in the same MBean Server.
try {
myMBeanServer.setAttribute(relationObjName,
new Attribute("Role", role));
} catch (InstanceNotFoundException exc1) {
throw new RuntimeException(exc1.getMessage());
} catch (ReflectionException exc3) {
throw new RuntimeException(exc3.getMessage());
} catch (MBeanException exc2) {
Exception wrappedExc = exc2.getTargetException();
if (wrappedExc instanceof InvalidRoleValueException) {
throw ((InvalidRoleValueException)wrappedExc);
} else {
throw new RuntimeException(wrappedExc.getMessage());
}
} catch (AttributeNotFoundException exc4) {
throw new RuntimeException(exc4.getMessage());
} catch (InvalidAttributeValueException exc5) {
throw new RuntimeException(exc5.getMessage());
}
}
}
RELATION_LOGGER.exiting(RelationService.class.getName(),
"initializeMissingRoles");
return;
}
// Throws an exception corresponding to a given problem type
//
// -param pbType possible problem, defined in RoleUnresolved
// -param roleName role name
//
// -exception IllegalArgumentException if null parameter
// -exception RoleNotFoundException for problems:
// - NO_ROLE_WITH_NAME
// - ROLE_NOT_READABLE
// - ROLE_NOT_WRITABLE
// -exception InvalidRoleValueException for problems:
// - LESS_THAN_MIN_ROLE_DEGREE
// - MORE_THAN_MAX_ROLE_DEGREE
// - REF_MBEAN_OF_INCORRECT_CLASS
// - REF_MBEAN_NOT_REGISTERED
static void throwRoleProblemException(int pbType,
String roleName)
throws IllegalArgumentException,
RoleNotFoundException,
InvalidRoleValueException {
if (roleName == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
// Exception type: 1 = RoleNotFoundException
// 2 = InvalidRoleValueException
int excType = 0;
String excMsgPart = null;
switch (pbType) {
case RoleStatus.NO_ROLE_WITH_NAME:
excMsgPart = " does not exist in relation.";
excType = 1;
break;
case RoleStatus.ROLE_NOT_READABLE:
excMsgPart = " is not readable.";
excType = 1;
break;
case RoleStatus.ROLE_NOT_WRITABLE:
excMsgPart = " is not writable.";
excType = 1;
break;
case RoleStatus.LESS_THAN_MIN_ROLE_DEGREE:
excMsgPart = " has a number of MBean references less than the expected minimum degree.";
excType = 2;
break;
case RoleStatus.MORE_THAN_MAX_ROLE_DEGREE:
excMsgPart = " has a number of MBean references greater than the expected maximum degree.";
excType = 2;
break;
case RoleStatus.REF_MBEAN_OF_INCORRECT_CLASS:
excMsgPart = " has an MBean reference to an MBean not of the expected class of references for that role.";
excType = 2;
break;
case RoleStatus.REF_MBEAN_NOT_REGISTERED:
excMsgPart = " has a reference to null or to an MBean not registered.";
excType = 2;
break;
}
// No default as we must have been in one of those cases
StringBuilder excMsgStrB = new StringBuilder(roleName);
excMsgStrB.append(excMsgPart);
String excMsg = excMsgStrB.toString();
if (excType == 1) {
throw new RoleNotFoundException(excMsg);
} else if (excType == 2) {
throw new InvalidRoleValueException(excMsg);
}
}
// Sends a notification of given type, with given parameters
//
// -param intNtfType integer to represent notification type:
// - 1 : create
// - 2 : update
// - 3 : delete
// -param message human-readable message
// -param relationId relation id of the created/updated/deleted relation
// -param unregMBeanList list of ObjectNames of referenced MBeans
// expected to be unregistered due to relation removal (only for removal,
// due to CIM qualifiers, can be null)
// -param roleName role name
// -param roleNewValue role new value (ArrayList of ObjectNames)
// -param oldValue old role value (ArrayList of ObjectNames)
//
// -exception IllegalArgument if null parameter
// -exception RelationNotFoundException if no relation for given id
private void sendNotificationInt(int intNtfType,
String message,
String relationId,
List<ObjectName> unregMBeanList,
String roleName,
List<ObjectName> roleNewValue,
List<ObjectName> oldValue)
throws IllegalArgumentException,
RelationNotFoundException {
if (message == null ||
relationId == null ||
(intNtfType != 3 && unregMBeanList != null) ||
(intNtfType == 2 &&
(roleName == null ||
roleNewValue == null ||
oldValue == null))) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"sendNotificationInt", new Object[] {intNtfType, message,
relationId, unregMBeanList, roleName, roleNewValue, oldValue});
// Relation type name
// Note: do not use getRelationTypeName() as if it is a relation MBean
// it is already unregistered.
String relTypeName = null;
synchronized(myRelId2RelTypeMap) {
relTypeName = (myRelId2RelTypeMap.get(relationId));
}
// ObjectName (for a relation MBean)
// Can also throw a RelationNotFoundException, but detected above
ObjectName relObjName = isRelationMBean(relationId);
String ntfType = null;
if (relObjName != null) {
switch (intNtfType) {
case 1:
ntfType = RelationNotification.RELATION_MBEAN_CREATION;
break;
case 2:
ntfType = RelationNotification.RELATION_MBEAN_UPDATE;
break;
case 3:
ntfType = RelationNotification.RELATION_MBEAN_REMOVAL;
break;
}
} else {
switch (intNtfType) {
case 1:
ntfType = RelationNotification.RELATION_BASIC_CREATION;
break;
case 2:
ntfType = RelationNotification.RELATION_BASIC_UPDATE;
break;
case 3:
ntfType = RelationNotification.RELATION_BASIC_REMOVAL;
break;
}
}
// Sequence number
Long seqNbr = getNotificationSequenceNumber();
// Timestamp
Date currDate = new Date();
long timeStamp = currDate.getTime();
RelationNotification ntf = null;
if (ntfType.equals(RelationNotification.RELATION_BASIC_CREATION) ||
ntfType.equals(RelationNotification.RELATION_MBEAN_CREATION) ||
ntfType.equals(RelationNotification.RELATION_BASIC_REMOVAL) ||
ntfType.equals(RelationNotification.RELATION_MBEAN_REMOVAL))
// Creation or removal
ntf = new RelationNotification(ntfType,
this,
seqNbr.longValue(),
timeStamp,
message,
relationId,
relTypeName,
relObjName,
unregMBeanList);
else if (ntfType.equals(RelationNotification.RELATION_BASIC_UPDATE)
||
ntfType.equals(RelationNotification.RELATION_MBEAN_UPDATE))
{
// Update
ntf = new RelationNotification(ntfType,
this,
seqNbr.longValue(),
timeStamp,
message,
relationId,
relTypeName,
relObjName,
roleName,
roleNewValue,
oldValue);
}
sendNotification(ntf);
RELATION_LOGGER.exiting(RelationService.class.getName(),
"sendNotificationInt");
return;
}
// Checks, for the unregistration of an MBean referenced in the roles given
// in parameter, if the relation has to be removed or not, regarding
// expected minimum role cardinality and current number of
// references in each role after removal of the current one.
// If the relation is kept, calls handleMBeanUnregistration() callback of
// the relation to update it.
//
// -param relationId relation id
// -param objectName ObjectName of the unregistered MBean
// -param roleNameList list of names of roles where the unregistered
// MBean is referenced.
//
// -exception IllegalArgumentException if null parameter
// -exception RelationServiceNotRegisteredException if the Relation
// Service is not registered in the MBean Server
// -exception RelationNotFoundException if unknown relation id
// -exception RoleNotFoundException if one role given as parameter does
// not exist in the relation
private void handleReferenceUnregistration(String relationId,
ObjectName objectName,
List roleNameList)
throws IllegalArgumentException,
RelationServiceNotRegisteredException,
RelationNotFoundException,
RoleNotFoundException {
if (relationId == null ||
roleNameList == null ||
objectName == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"handleReferenceUnregistration",
new Object[] {relationId, objectName, roleNameList});
// Can throw RelationServiceNotRegisteredException
isActive();
// Retrieves the relation type name of the relation
// Can throw RelationNotFoundException
String currRelTypeName = getRelationTypeName(relationId);
// Retrieves the relation
// Can throw RelationNotFoundException, but already detected above
Object relObj = getRelation(relationId);
// Flag to specify if the relation has to be deleted
boolean deleteRelFlag = false;
for (Iterator roleNameIter = roleNameList.iterator();
roleNameIter.hasNext();) {
if (deleteRelFlag) {
break;
}
String currRoleName = (String)(roleNameIter.next());
// Retrieves number of MBeans currently referenced in role
// BEWARE! Do not use getRole() as role may be not readable
//
// Can throw RelationNotFoundException (but already checked),
// RoleNotFoundException
int currRoleRefNbr =
(getRoleCardinality(relationId, currRoleName)).intValue();
// Retrieves new number of element in role
int currRoleNewRefNbr = currRoleRefNbr - 1;
// Retrieves role info for that role
//
// Shall not throw RelationTypeNotFoundException or
// RoleInfoNotFoundException
RoleInfo currRoleInfo = null;
try {
currRoleInfo = getRoleInfo(currRelTypeName,
currRoleName);
} catch (RelationTypeNotFoundException exc1) {
throw new RuntimeException(exc1.getMessage());
} catch (RoleInfoNotFoundException exc2) {
throw new RuntimeException(exc2.getMessage());
}
// Checks with expected minimum number of elements
boolean chkMinFlag = currRoleInfo.checkMinDegree(currRoleNewRefNbr);
if (!chkMinFlag) {
// The relation has to be deleted
deleteRelFlag = true;
}
}
if (deleteRelFlag) {
// Removes the relation
removeRelation(relationId);
} else {
// Updates each role in the relation using
// handleMBeanUnregistration() callback
//
// BEWARE: this roleNameList list MUST BE A COPY of a role name
// list for a referenced MBean in a relation, NOT a
// reference to an original one part of the
// myRefedMBeanObjName2RelIdsMap!!!! Because each role
// which name is in that list will be updated (potentially
// using setRole(). So the Relation Service will update the
// myRefedMBeanObjName2RelIdsMap to refelect the new role
// value!
for (Iterator roleNameIter = roleNameList.iterator();
roleNameIter.hasNext();) {
String currRoleName = (String)(roleNameIter.next());
if (relObj instanceof RelationSupport) {
// Internal relation
// Can throw RoleNotFoundException (but already checked)
//
// Shall not throw
// RelationTypeNotFoundException,
// InvalidRoleValueException (value was correct, removing
// one reference shall not invalidate it, else detected
// above)
try {
((RelationSupport)relObj).handleMBeanUnregistrationInt(
objectName,
currRoleName,
true,
this);
} catch (RelationTypeNotFoundException exc3) {
throw new RuntimeException(exc3.getMessage());
} catch (InvalidRoleValueException exc4) {
throw new RuntimeException(exc4.getMessage());
}
} else {
// Relation MBean
Object[] params = new Object[2];
params[0] = objectName;
params[1] = currRoleName;
String[] signature = new String[2];
signature[0] = "javax.management.ObjectName";
signature[1] = "java.lang.String";
// Shall not throw InstanceNotFoundException, or
// MBeanException (wrapping RoleNotFoundException or
// MBeanException or InvalidRoleValueException) or
// ReflectionException
try {
myMBeanServer.invoke(((ObjectName)relObj),
"handleMBeanUnregistration",
params,
signature);
} catch (InstanceNotFoundException exc1) {
throw new RuntimeException(exc1.getMessage());
} catch (ReflectionException exc3) {
throw new RuntimeException(exc3.getMessage());
} catch (MBeanException exc2) {
Exception wrappedExc = exc2.getTargetException();
throw new RuntimeException(wrappedExc.getMessage());
}
}
}
}
RELATION_LOGGER.exiting(RelationService.class.getName(),
"handleReferenceUnregistration");
return;
}
}
| Java |
/*
* Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management.relation;
import static com.sun.jmx.mbeanserver.Util.cast;
import com.sun.jmx.mbeanserver.GetPropertyAction;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamField;
import java.io.Serializable;
import java.security.AccessController;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.management.ObjectName;
/** {@collect.stats}
* Represents a role: includes a role name and referenced MBeans (via their
* ObjectNames). The role value is always represented as an ArrayList
* collection (of ObjectNames) to homogenize the access.
*
* <p>The <b>serialVersionUID</b> of this class is <code>-279985518429862552L</code>.
*
* @since 1.5
*/
@SuppressWarnings("serial") // serialVersionUID not constant
public class Role implements Serializable {
// Serialization compatibility stuff:
// Two serial forms are supported in this class. The selected form depends
// on system property "jmx.serial.form":
// - "1.0" for JMX 1.0
// - any other value for JMX 1.1 and higher
//
// Serial version for old serial form
private static final long oldSerialVersionUID = -1959486389343113026L;
//
// Serial version for new serial form
private static final long newSerialVersionUID = -279985518429862552L;
//
// Serializable fields in old serial form
private static final ObjectStreamField[] oldSerialPersistentFields =
{
new ObjectStreamField("myName", String.class),
new ObjectStreamField("myObjNameList", ArrayList.class)
};
//
// Serializable fields in new serial form
private static final ObjectStreamField[] newSerialPersistentFields =
{
new ObjectStreamField("name", String.class),
new ObjectStreamField("objectNameList", List.class)
};
//
// Actual serial version and serial form
private static final long serialVersionUID;
/** {@collect.stats}
* @serialField name String Role name
* @serialField objectNameList List {@link List} of {@link ObjectName}s of referenced MBeans
*/
private static final ObjectStreamField[] serialPersistentFields;
private static boolean compat = false;
static {
try {
GetPropertyAction act = new GetPropertyAction("jmx.serial.form");
String form = AccessController.doPrivileged(act);
compat = (form != null && form.equals("1.0"));
} catch (Exception e) {
// OK : Too bad, no compat with 1.0
}
if (compat) {
serialPersistentFields = oldSerialPersistentFields;
serialVersionUID = oldSerialVersionUID;
} else {
serialPersistentFields = newSerialPersistentFields;
serialVersionUID = newSerialVersionUID;
}
}
//
// END Serialization compatibility stuff
//
// Private members
//
/** {@collect.stats}
* @serial Role name
*/
private String name = null;
/** {@collect.stats}
* @serial {@link List} of {@link ObjectName}s of referenced MBeans
*/
private List<ObjectName> objectNameList = new ArrayList<ObjectName>();
//
// Constructors
//
/** {@collect.stats}
* <p>Make a new Role object.
* No check is made that the ObjectNames in the role value exist in
* an MBean server. That check will be made when the role is set
* in a relation.
*
* @param roleName role name
* @param roleValue role value (List of ObjectName objects)
*
* @exception IllegalArgumentException if null parameter
*/
public Role(String roleName,
List<ObjectName> roleValue)
throws IllegalArgumentException {
if (roleName == null || roleValue == null) {
String excMsg = "Invalid parameter";
throw new IllegalArgumentException(excMsg);
}
setRoleName(roleName);
setRoleValue(roleValue);
return;
}
//
// Accessors
//
/** {@collect.stats}
* Retrieves role name.
*
* @return the role name.
*
* @see #setRoleName
*/
public String getRoleName() {
return name;
}
/** {@collect.stats}
* Retrieves role value.
*
* @return ArrayList of ObjectName objects for referenced MBeans.
*
* @see #setRoleValue
*/
public List<ObjectName> getRoleValue() {
return objectNameList;
}
/** {@collect.stats}
* Sets role name.
*
* @param roleName role name
*
* @exception IllegalArgumentException if null parameter
*
* @see #getRoleName
*/
public void setRoleName(String roleName)
throws IllegalArgumentException {
if (roleName == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
name = roleName;
return;
}
/** {@collect.stats}
* Sets role value.
*
* @param roleValue List of ObjectName objects for referenced
* MBeans.
*
* @exception IllegalArgumentException if null parameter
*
* @see #getRoleValue
*/
public void setRoleValue(List<ObjectName> roleValue)
throws IllegalArgumentException {
if (roleValue == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
objectNameList = new ArrayList<ObjectName>(roleValue);
return;
}
/** {@collect.stats}
* Returns a string describing the role.
*
* @return the description of the role.
*/
public String toString() {
StringBuilder result = new StringBuilder();
result.append("role name: " + name + "; role value: ");
for (Iterator objNameIter = objectNameList.iterator();
objNameIter.hasNext();) {
ObjectName currObjName = (ObjectName)(objNameIter.next());
result.append(currObjName.toString());
if (objNameIter.hasNext()) {
result.append(", ");
}
}
return result.toString();
}
//
// Misc
//
/** {@collect.stats}
* Clone the role object.
*
* @return a Role that is an independent copy of the current Role object.
*/
public Object clone() {
try {
return new Role(name, objectNameList);
} catch (IllegalArgumentException exc) {
return null; // can't happen
}
}
/** {@collect.stats}
* Returns a string for the given role value.
*
* @param roleValue List of ObjectName objects
*
* @return A String consisting of the ObjectNames separated by
* newlines (\n).
*
* @exception IllegalArgumentException if null parameter
*/
public static String roleValueToString(List<ObjectName> roleValue)
throws IllegalArgumentException {
if (roleValue == null) {
String excMsg = "Invalid parameter";
throw new IllegalArgumentException(excMsg);
}
StringBuilder result = new StringBuilder();
for (ObjectName currObjName : roleValue) {
if (result.length() > 0)
result.append("\n");
result.append(currObjName.toString());
}
return result.toString();
}
/** {@collect.stats}
* Deserializes a {@link Role} from an {@link ObjectInputStream}.
*/
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException {
if (compat)
{
// Read an object serialized in the old serial form
//
ObjectInputStream.GetField fields = in.readFields();
name = (String) fields.get("myName", null);
if (fields.defaulted("myName"))
{
throw new NullPointerException("myName");
}
objectNameList = cast(fields.get("myObjNameList", null));
if (fields.defaulted("myObjNameList"))
{
throw new NullPointerException("myObjNameList");
}
}
else
{
// Read an object serialized in the new serial form
//
in.defaultReadObject();
}
}
/** {@collect.stats}
* Serializes a {@link Role} to an {@link ObjectOutputStream}.
*/
private void writeObject(ObjectOutputStream out)
throws IOException {
if (compat)
{
// Serializes this instance in the old serial form
//
ObjectOutputStream.PutField fields = out.putFields();
fields.put("myName", name);
fields.put("myObjNameList", (ArrayList)objectNameList);
out.writeFields();
}
else
{
// Serializes this instance in the new serial form
//
out.defaultWriteObject();
}
}
}
| Java |
/*
* Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management.relation;
import com.sun.jmx.mbeanserver.GetPropertyAction;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamField;
import java.io.Serializable;
import java.security.AccessController;
import java.util.Iterator;
/** {@collect.stats}
* Represents the result of a multiple access to several roles of a relation
* (either for reading or writing).
*
* <p>The <b>serialVersionUID</b> of this class is <code>-6304063118040985512L</code>.
*
* @since 1.5
*/
@SuppressWarnings("serial")
public class RoleResult implements Serializable {
// Serialization compatibility stuff:
// Two serial forms are supported in this class. The selected form depends
// on system property "jmx.serial.form":
// - "1.0" for JMX 1.0
// - any other value for JMX 1.1 and higher
//
// Serial version for old serial form
private static final long oldSerialVersionUID = 3786616013762091099L;
//
// Serial version for new serial form
private static final long newSerialVersionUID = -6304063118040985512L;
//
// Serializable fields in old serial form
private static final ObjectStreamField[] oldSerialPersistentFields =
{
new ObjectStreamField("myRoleList", RoleList.class),
new ObjectStreamField("myRoleUnresList", RoleUnresolvedList.class)
};
//
// Serializable fields in new serial form
private static final ObjectStreamField[] newSerialPersistentFields =
{
new ObjectStreamField("roleList", RoleList.class),
new ObjectStreamField("unresolvedRoleList", RoleUnresolvedList.class)
};
//
// Actual serial version and serial form
private static final long serialVersionUID;
/** {@collect.stats}
* @serialField roleList RoleList List of roles successfully accessed
* @serialField unresolvedRoleList RoleUnresolvedList List of roles unsuccessfully accessed
*/
private static final ObjectStreamField[] serialPersistentFields;
private static boolean compat = false;
static {
try {
GetPropertyAction act = new GetPropertyAction("jmx.serial.form");
String form = AccessController.doPrivileged(act);
compat = (form != null && form.equals("1.0"));
} catch (Exception e) {
// OK : Too bad, no compat with 1.0
}
if (compat) {
serialPersistentFields = oldSerialPersistentFields;
serialVersionUID = oldSerialVersionUID;
} else {
serialPersistentFields = newSerialPersistentFields;
serialVersionUID = newSerialVersionUID;
}
}
//
// END Serialization compatibility stuff
//
// Private members
//
/** {@collect.stats}
* @serial List of roles successfully accessed
*/
private RoleList roleList = null;
/** {@collect.stats}
* @serial List of roles unsuccessfully accessed
*/
private RoleUnresolvedList unresolvedRoleList = null;
//
// Constructor
//
/** {@collect.stats}
* Constructor.
*
* @param list list of roles successfully accessed.
* @param unresolvedList list of roles not accessed (with problem
* descriptions).
*/
public RoleResult(RoleList list,
RoleUnresolvedList unresolvedList) {
setRoles(list);
setRolesUnresolved(unresolvedList);
return;
}
//
// Accessors
//
/** {@collect.stats}
* Retrieves list of roles successfully accessed.
*
* @return a RoleList
*
* @see #setRoles
*/
public RoleList getRoles() {
return roleList;
}
/** {@collect.stats}
* Retrieves list of roles unsuccessfully accessed.
*
* @return a RoleUnresolvedList.
*
* @see #setRolesUnresolved
*/
public RoleUnresolvedList getRolesUnresolved() {
return unresolvedRoleList;
}
/** {@collect.stats}
* Sets list of roles successfully accessed.
*
* @param list list of roles successfully accessed
*
* @see #getRoles
*/
public void setRoles(RoleList list) {
if (list != null) {
roleList = new RoleList();
for (Iterator roleIter = list.iterator();
roleIter.hasNext();) {
Role currRole = (Role)(roleIter.next());
roleList.add((Role)(currRole.clone()));
}
} else {
roleList = null;
}
return;
}
/** {@collect.stats}
* Sets list of roles unsuccessfully accessed.
*
* @param unresolvedList list of roles unsuccessfully accessed
*
* @see #getRolesUnresolved
*/
public void setRolesUnresolved(RoleUnresolvedList unresolvedList) {
if (unresolvedList != null) {
unresolvedRoleList = new RoleUnresolvedList();
for (Iterator roleUnresIter = unresolvedList.iterator();
roleUnresIter.hasNext();) {
RoleUnresolved currRoleUnres =
(RoleUnresolved)(roleUnresIter.next());
unresolvedRoleList.add((RoleUnresolved)(currRoleUnres.clone()));
}
} else {
unresolvedRoleList = null;
}
return;
}
/** {@collect.stats}
* Deserializes a {@link RoleResult} 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();
roleList = (RoleList) fields.get("myRoleList", null);
if (fields.defaulted("myRoleList"))
{
throw new NullPointerException("myRoleList");
}
unresolvedRoleList = (RoleUnresolvedList) fields.get("myRoleUnresList", null);
if (fields.defaulted("myRoleUnresList"))
{
throw new NullPointerException("myRoleUnresList");
}
}
else
{
// Read an object serialized in the new serial form
//
in.defaultReadObject();
}
}
/** {@collect.stats}
* Serializes a {@link RoleResult} 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("myRoleList", roleList);
fields.put("myRoleUnresList", unresolvedRoleList);
out.writeFields();
}
else
{
// Serializes this instance in the new serial form
//
out.defaultWriteObject();
}
}
}
| Java |
/*
* Copyright (c) 2000, 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management.relation;
import javax.management.JMException;
/** {@collect.stats}
* This class is the superclass of any exception which can be raised during
* relation management.
*
* @since 1.5
*/
public class RelationException extends JMException {
/* Serial version */
private static final long serialVersionUID = 5434016005679159613L;
/** {@collect.stats}
* Default constructor, no message put in exception.
*/
public RelationException() {
super();
}
/** {@collect.stats}
* Constructor with given message put in exception.
*
* @param message the detail message.
*/
public RelationException(String message) {
super(message);
}
}
| Java |
/*
* Copyright (c) 2000, 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management.relation;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/** {@collect.stats}
* A RoleList represents a list of roles (Role objects). It is used as
* parameter when creating a relation, and when trying to set several roles in
* a relation (via 'setRoles()' method). It is returned as part of a
* RoleResult, to provide roles successfully retrieved.
*
* @since 1.5
*/
/* We cannot extend ArrayList<Role> because our legacy
add(Role) 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,Role). Grrr. We cannot use covariance
to override the most important methods and have them return
Role, either, because that would break subclasses that
override those methods in turn (using the original return type
of Object). Finally, we cannot implement Iterable<Role>
so you could write
for (Role r : roleList)
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 (Role r : roleList.asList())
*/
public class RoleList extends ArrayList<Object> {
private transient boolean typeSafe;
private transient boolean tainted;
/* Serial version */
private static final long serialVersionUID = 5568344346499649313L;
//
// Constructors
//
/** {@collect.stats}
* Constructs an empty RoleList.
*/
public RoleList() {
super();
}
/** {@collect.stats}
* Constructs an empty RoleList with the initial capacity
* specified.
*
* @param initialCapacity initial capacity
*/
public RoleList(int initialCapacity) {
super(initialCapacity);
}
/** {@collect.stats}
* Constructs a {@code RoleList} containing the elements of the
* {@code List} specified, in the order in which they are returned by
* the {@code List}'s iterator. The {@code RoleList} instance has
* an initial capacity of 110% of the size of the {@code List}
* specified.
*
* @param list the {@code List} that defines the initial contents of
* the new {@code RoleList}.
*
* @exception IllegalArgumentException if the {@code list} parameter
* is {@code null} or if the {@code list} parameter contains any
* non-Role objects.
*
* @see ArrayList#ArrayList(java.util.Collection)
*/
public RoleList(List<Role> list) throws IllegalArgumentException {
// Check for null parameter
//
if (list == null)
throw new IllegalArgumentException("Null parameter");
// Check for non-Role objects
//
checkTypeSafe(list);
// Build the List<Role>
//
super.addAll(list);
}
/** {@collect.stats}
* Return a view of this list as a {@code List<Role>}.
* Changes to the returned value are reflected by changes
* to the original {@code RoleList} and vice versa.
*
* @return a {@code List<Role>} whose contents
* reflect the contents of this {@code RoleList}.
*
* <p>If this method has ever been called on a given
* {@code RoleList} instance, a subsequent attempt to add
* an object to that instance which is not a {@code Role}
* will fail with an {@code IllegalArgumentException}. For compatibility
* reasons, a {@code RoleList} on which this method has never
* been called does allow objects other than {@code Role}s to
* be added.</p>
*
* @throws IllegalArgumentException if this {@code RoleList} contains
* an element that is not a {@code Role}.
*
* @since 1.6
*/
@SuppressWarnings("unchecked")
public List<Role> asList() {
if (!typeSafe) {
if (tainted)
checkTypeSafe(this);
typeSafe = true;
}
return (List<Role>) (List) this;
}
//
// Accessors
//
/** {@collect.stats}
* Adds the Role specified as the last element of the list.
*
* @param role the role to be added.
*
* @exception IllegalArgumentException if the role is null.
*/
public void add(Role role)
throws IllegalArgumentException {
if (role == null) {
String excMsg = "Invalid parameter";
throw new IllegalArgumentException(excMsg);
}
super.add(role);
}
/** {@collect.stats}
* Inserts the role specified as an element at the position specified.
* Elements with an index greater than or equal to the current position are
* shifted up.
*
* @param index The position in the list where the new Role
* object is to be inserted.
* @param role The Role object to be inserted.
*
* @exception IllegalArgumentException if the role is null.
* @exception IndexOutOfBoundsException if accessing with an index
* outside of the list.
*/
public void add(int index,
Role role)
throws IllegalArgumentException,
IndexOutOfBoundsException {
if (role == null) {
String excMsg = "Invalid parameter";
throw new IllegalArgumentException(excMsg);
}
super.add(index, role);
}
/** {@collect.stats}
* Sets the element at the position specified to be the role
* specified.
* The previous element at that position is discarded.
*
* @param index The position specified.
* @param role The value to which the role element should be set.
*
* @exception IllegalArgumentException if the role is null.
* @exception IndexOutOfBoundsException if accessing with an index
* outside of the list.
*/
public void set(int index,
Role role)
throws IllegalArgumentException,
IndexOutOfBoundsException {
if (role == null) {
// Revisit [cebro] Localize message
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
super.set(index, role);
}
/** {@collect.stats}
* Appends all the elements in the RoleList specified to the end
* of the list, in the order in which they are returned by the Iterator of
* the RoleList specified.
*
* @param roleList Elements to be inserted into the list (can be null)
*
* @return true if this list changed as a result of the call.
*
* @exception IndexOutOfBoundsException if accessing with an index
* outside of the list.
*
* @see ArrayList#addAll(Collection)
*/
public boolean addAll(RoleList roleList)
throws IndexOutOfBoundsException {
if (roleList == null) {
return true;
}
return (super.addAll(roleList));
}
/** {@collect.stats}
* Inserts all of the elements in the RoleList specified into this
* list, starting at the specified position, in the order in which they are
* returned by the Iterator of the RoleList specified.
*
* @param index Position at which to insert the first element from the
* RoleList specified.
* @param roleList Elements to be inserted into the list.
*
* @return true if this list changed as a result of the call.
*
* @exception IllegalArgumentException if the role is null.
* @exception IndexOutOfBoundsException if accessing with an index
* outside of the list.
*
* @see ArrayList#addAll(int, Collection)
*/
public boolean addAll(int index,
RoleList roleList)
throws IllegalArgumentException,
IndexOutOfBoundsException {
if (roleList == null) {
// Revisit [cebro] Localize message
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
return (super.addAll(index, roleList));
}
/*
* Override all of the methods from ArrayList<Object> that might add
* a non-Role to the List, and disallow that if asList has ever
* been called on this instance.
*/
@Override
public boolean add(Object o) {
if (!tainted)
tainted = isTainted(o);
if (typeSafe)
checkTypeSafe(o);
return super.add(o);
}
@Override
public void add(int index, Object element) {
if (!tainted)
tainted = isTainted(element);
if (typeSafe)
checkTypeSafe(element);
super.add(index, element);
}
@Override
public boolean addAll(Collection<?> c) {
if (!tainted)
tainted = isTainted(c);
if (typeSafe)
checkTypeSafe(c);
return super.addAll(c);
}
@Override
public boolean addAll(int index, Collection<?> c) {
if (!tainted)
tainted = isTainted(c);
if (typeSafe)
checkTypeSafe(c);
return super.addAll(index, c);
}
@Override
public Object set(int index, Object element) {
if (!tainted)
tainted = isTainted(element);
if (typeSafe)
checkTypeSafe(element);
return super.set(index, element);
}
/** {@collect.stats}
* IllegalArgumentException if o is a non-Role object.
*/
private static void checkTypeSafe(Object o) {
try {
o = (Role) o;
} catch (ClassCastException e) {
throw new IllegalArgumentException(e);
}
}
/** {@collect.stats}
* IllegalArgumentException if c contains any non-Role objects.
*/
private static void checkTypeSafe(Collection<?> c) {
try {
Role r;
for (Object o : c)
r = (Role) o;
} catch (ClassCastException e) {
throw new IllegalArgumentException(e);
}
}
/** {@collect.stats}
* Returns true if o is a non-Role object.
*/
private static boolean isTainted(Object o) {
try {
checkTypeSafe(o);
} catch (IllegalArgumentException e) {
return true;
}
return false;
}
/** {@collect.stats}
* Returns true if c contains any non-Role objects.
*/
private static boolean isTainted(Collection<?> c) {
try {
checkTypeSafe(c);
} catch (IllegalArgumentException e) {
return true;
}
return false;
}
}
| Java |
/*
* Copyright (c) 2000, 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management.relation;
import javax.management.ObjectName;
import javax.management.InstanceNotFoundException;
import java.util.List;
import java.util.Map;
/** {@collect.stats}
* The Relation Service is in charge of creating and deleting relation types
* and relations, of handling the consistency and of providing query
* mechanisms.
*
* @since 1.5
*/
public interface RelationServiceMBean {
/** {@collect.stats}
* Checks if the Relation Service is active.
* Current condition is that the Relation Service must be registered in the
* MBean Server
*
* @exception RelationServiceNotRegisteredException if it is not
* registered
*/
public void isActive()
throws RelationServiceNotRegisteredException;
//
// Accessors
//
/** {@collect.stats}
* Returns the flag to indicate if when a notification is received for the
* unregistration of an MBean referenced in a relation, if an immediate
* "purge" of the relations (look for the relations no longer valid)
* has to be performed, or if that will be performed only when the
* purgeRelations method is explicitly called.
* <P>true is immediate purge.
*
* @return true if purges are immediate.
*
* @see #setPurgeFlag
*/
public boolean getPurgeFlag();
/** {@collect.stats}
* Sets the flag to indicate if when a notification is received for the
* unregistration of an MBean referenced in a relation, if an immediate
* "purge" of the relations (look for the relations no longer valid)
* has to be performed, or if that will be performed only when the
* purgeRelations method is explicitly called.
* <P>true is immediate purge.
*
* @param purgeFlag flag
*
* @see #getPurgeFlag
*/
public void setPurgeFlag(boolean purgeFlag);
//
// Relation type handling
//
/** {@collect.stats}
* Creates a relation type (RelationTypeSupport object) with given
* role infos (provided by the RoleInfo objects), and adds it in the
* Relation Service.
*
* @param relationTypeName name of the relation type
* @param roleInfoArray array of role infos
*
* @exception IllegalArgumentException if null parameter
* @exception InvalidRelationTypeException If:
* <P>- there is already a relation type with that name
* <P>- the same name has been used for two different role infos
* <P>- no role info provided
* <P>- one null role info provided
*/
public void createRelationType(String relationTypeName,
RoleInfo[] roleInfoArray)
throws IllegalArgumentException,
InvalidRelationTypeException;
/** {@collect.stats}
* Adds given object as a relation type. The object is expected to
* implement the RelationType interface.
*
* @param relationTypeObj relation type object (implementing the
* RelationType interface)
*
* @exception IllegalArgumentException if null parameter or if
* {@link RelationType#getRelationTypeName
* relationTypeObj.getRelationTypeName()} returns null.
* @exception InvalidRelationTypeException if there is already a relation
* type with that name
*/
public void addRelationType(RelationType relationTypeObj)
throws IllegalArgumentException,
InvalidRelationTypeException;
/** {@collect.stats}
* Retrieves names of all known relation types.
*
* @return ArrayList of relation type names (Strings)
*/
public List<String> getAllRelationTypeNames();
/** {@collect.stats}
* Retrieves list of role infos (RoleInfo objects) of a given relation
* type.
*
* @param relationTypeName name of relation type
*
* @return ArrayList of RoleInfo.
*
* @exception IllegalArgumentException if null parameter
* @exception RelationTypeNotFoundException if there is no relation type
* with that name.
*/
public List<RoleInfo> getRoleInfos(String relationTypeName)
throws IllegalArgumentException,
RelationTypeNotFoundException;
/** {@collect.stats}
* Retrieves role info for given role of a given relation type.
*
* @param relationTypeName name of relation type
* @param roleInfoName name of role
*
* @return RoleInfo object.
*
* @exception IllegalArgumentException if null parameter
* @exception RelationTypeNotFoundException if the relation type is not
* known in the Relation Service
* @exception RoleInfoNotFoundException if the role is not part of the
* relation type.
*/
public RoleInfo getRoleInfo(String relationTypeName,
String roleInfoName)
throws IllegalArgumentException,
RelationTypeNotFoundException,
RoleInfoNotFoundException;
/** {@collect.stats}
* Removes given relation type from Relation Service.
* <P>The relation objects of that type will be removed from the
* Relation Service.
*
* @param relationTypeName name of the relation type to be removed
*
* @exception RelationServiceNotRegisteredException if the Relation
* Service is not registered in the MBean Server
* @exception IllegalArgumentException if null parameter
* @exception RelationTypeNotFoundException If there is no relation type
* with that name
*/
public void removeRelationType(String relationTypeName)
throws RelationServiceNotRegisteredException,
IllegalArgumentException,
RelationTypeNotFoundException;
//
// Relation handling
//
/** {@collect.stats}
* Creates a simple relation (represented by a RelationSupport object) of
* given relation type, and adds it in the Relation Service.
* <P>Roles are initialized according to the role list provided in
* parameter. The ones not initialized in this way are set to an empty
* ArrayList of ObjectNames.
* <P>A RelationNotification, with type RELATION_BASIC_CREATION, is sent.
*
* @param relationId relation identifier, to identify uniquely the relation
* inside the Relation Service
* @param relationTypeName name of the relation type (has to be created
* in the Relation Service)
* @param roleList role list to initialize roles of the relation (can
* be null).
*
* @exception RelationServiceNotRegisteredException if the Relation
* Service is not registered in the MBean Server
* @exception IllegalArgumentException if null parameter
* @exception RoleNotFoundException if a value is provided for a role
* that does not exist in the relation type
* @exception InvalidRelationIdException if relation id already used
* @exception RelationTypeNotFoundException if relation type not known in
* Relation Service
* @exception InvalidRoleValueException if:
* <P>- the same role name is used for two different roles
* <P>- the number of referenced MBeans in given value is less than
* expected minimum degree
* <P>- the number of referenced MBeans in provided value exceeds expected
* maximum degree
* <P>- one referenced MBean in the value is not an Object of the MBean
* class expected for that role
* <P>- an MBean provided for that role does not exist
*/
public void createRelation(String relationId,
String relationTypeName,
RoleList roleList)
throws RelationServiceNotRegisteredException,
IllegalArgumentException,
RoleNotFoundException,
InvalidRelationIdException,
RelationTypeNotFoundException,
InvalidRoleValueException;
/** {@collect.stats}
* Adds an MBean created by the user (and registered by him in the MBean
* Server) as a relation in the Relation Service.
* <P>To be added as a relation, the MBean must conform to the
* following:
* <P>- implement the Relation interface
* <P>- have for RelationService ObjectName the ObjectName of current
* Relation Service
* <P>- have a relation id that is unique and unused in current Relation Service
* <P>- have for relation type a relation type created in the Relation
* Service
* <P>- have roles conforming to the role info provided in the relation
* type.
*
* @param relationObjectName ObjectName of the relation MBean to be added.
*
* @exception IllegalArgumentException if null parameter
* @exception RelationServiceNotRegisteredException if the Relation
* Service is not registered in the MBean Server
* @exception NoSuchMethodException If the MBean does not implement the
* Relation interface
* @exception InvalidRelationIdException if:
* <P>- no relation identifier in MBean
* <P>- the relation identifier is already used in the Relation Service
* @exception InstanceNotFoundException if the MBean for given ObjectName
* has not been registered
* @exception InvalidRelationServiceException if:
* <P>- no Relation Service name in MBean
* <P>- the Relation Service name in the MBean is not the one of the
* current Relation Service
* @exception RelationTypeNotFoundException if:
* <P>- no relation type name in MBean
* <P>- the relation type name in MBean does not correspond to a relation
* type created in the Relation Service
* @exception InvalidRoleValueException if:
* <P>- the number of referenced MBeans in a role is less than
* expected minimum degree
* <P>- the number of referenced MBeans in a role exceeds expected
* maximum degree
* <P>- one referenced MBean in the value is not an Object of the MBean
* class expected for that role
* <P>- an MBean provided for a role does not exist
* @exception RoleNotFoundException if a value is provided for a role
* that does not exist in the relation type
*/
public void addRelation(ObjectName relationObjectName)
throws IllegalArgumentException,
RelationServiceNotRegisteredException,
NoSuchMethodException,
InvalidRelationIdException,
InstanceNotFoundException,
InvalidRelationServiceException,
RelationTypeNotFoundException,
RoleNotFoundException,
InvalidRoleValueException;
/** {@collect.stats}
* If the relation is represented by an MBean (created by the user and
* added as a relation in the Relation Service), returns the ObjectName of
* the MBean.
*
* @param relationId relation id identifying the relation
*
* @return ObjectName of the corresponding relation MBean, or null if
* the relation is not an MBean.
*
* @exception IllegalArgumentException if null parameter
* @exception RelationNotFoundException there is no relation associated
* to that id
*/
public ObjectName isRelationMBean(String relationId)
throws IllegalArgumentException,
RelationNotFoundException;
/** {@collect.stats}
* Returns the relation id associated to the given ObjectName if the
* MBean has been added as a relation in the Relation Service.
*
* @param objectName ObjectName of supposed relation
*
* @return relation id (String) or null (if the ObjectName is not a
* relation handled by the Relation Service)
*
* @exception IllegalArgumentException if null parameter
*/
public String isRelation(ObjectName objectName)
throws IllegalArgumentException;
/** {@collect.stats}
* Checks if there is a relation identified in Relation Service with given
* relation id.
*
* @param relationId relation id identifying the relation
*
* @return boolean: true if there is a relation, false else
*
* @exception IllegalArgumentException if null parameter
*/
public Boolean hasRelation(String relationId)
throws IllegalArgumentException;
/** {@collect.stats}
* Returns all the relation ids for all the relations handled by the
* Relation Service.
*
* @return ArrayList of String
*/
public List<String> getAllRelationIds();
/** {@collect.stats}
* Checks if given Role can be read in a relation of the given type.
*
* @param roleName name of role to be checked
* @param relationTypeName name of the relation type
*
* @return an Integer wrapping an integer corresponding to possible
* problems represented as constants in RoleUnresolved:
* <P>- 0 if role can be read
* <P>- integer corresponding to RoleStatus.NO_ROLE_WITH_NAME
* <P>- integer corresponding to RoleStatus.ROLE_NOT_READABLE
*
* @exception IllegalArgumentException if null parameter
* @exception RelationTypeNotFoundException if the relation type is not
* known in the Relation Service
*/
public Integer checkRoleReading(String roleName,
String relationTypeName)
throws IllegalArgumentException,
RelationTypeNotFoundException;
/** {@collect.stats}
* Checks if given Role can be set in a relation of given type.
*
* @param role role to be checked
* @param relationTypeName name of relation type
* @param initFlag flag to specify that the checking is done for the
* initialization of a role, write access shall not be verified.
*
* @return an Integer wrapping an integer corresponding to possible
* problems represented as constants in RoleUnresolved:
* <P>- 0 if role can be set
* <P>- integer corresponding to RoleStatus.NO_ROLE_WITH_NAME
* <P>- integer for RoleStatus.ROLE_NOT_WRITABLE
* <P>- integer for RoleStatus.LESS_THAN_MIN_ROLE_DEGREE
* <P>- integer for RoleStatus.MORE_THAN_MAX_ROLE_DEGREE
* <P>- integer for RoleStatus.REF_MBEAN_OF_INCORRECT_CLASS
* <P>- integer for RoleStatus.REF_MBEAN_NOT_REGISTERED
*
* @exception IllegalArgumentException if null parameter
* @exception RelationTypeNotFoundException if unknown relation type
*/
public Integer checkRoleWriting(Role role,
String relationTypeName,
Boolean initFlag)
throws IllegalArgumentException,
RelationTypeNotFoundException;
/** {@collect.stats}
* Sends a notification (RelationNotification) for a relation creation.
* The notification type is:
* <P>- RelationNotification.RELATION_BASIC_CREATION if the relation is an
* object internal to the Relation Service
* <P>- RelationNotification.RELATION_MBEAN_CREATION if the relation is a
* MBean added as a relation.
* <P>The source object is the Relation Service itself.
* <P>It is called in Relation Service createRelation() and
* addRelation() methods.
*
* @param relationId relation identifier of the updated relation
*
* @exception IllegalArgumentException if null parameter
* @exception RelationNotFoundException if there is no relation for given
* relation id
*/
public void sendRelationCreationNotification(String relationId)
throws IllegalArgumentException,
RelationNotFoundException;
/** {@collect.stats}
* Sends a notification (RelationNotification) for a role update in the
* given relation. The notification type is:
* <P>- RelationNotification.RELATION_BASIC_UPDATE if the relation is an
* object internal to the Relation Service
* <P>- RelationNotification.RELATION_MBEAN_UPDATE if the relation is a
* MBean added as a relation.
* <P>The source object is the Relation Service itself.
* <P>It is called in relation MBean setRole() (for given role) and
* setRoles() (for each role) methods (implementation provided in
* RelationSupport class).
* <P>It is also called in Relation Service setRole() (for given role) and
* setRoles() (for each role) methods.
*
* @param relationId relation identifier of the updated relation
* @param newRole new role (name and new value)
* @param oldRoleValue old role value (List of ObjectName objects)
*
* @exception IllegalArgumentException if null parameter
* @exception RelationNotFoundException if there is no relation for given
* relation id
*/
public void sendRoleUpdateNotification(String relationId,
Role newRole,
List<ObjectName> oldRoleValue)
throws IllegalArgumentException,
RelationNotFoundException;
/** {@collect.stats}
* Sends a notification (RelationNotification) for a relation removal.
* The notification type is:
* <P>- RelationNotification.RELATION_BASIC_REMOVAL if the relation is an
* object internal to the Relation Service
* <P>- RelationNotification.RELATION_MBEAN_REMOVAL if the relation is a
* MBean added as a relation.
* <P>The source object is the Relation Service itself.
* <P>It is called in Relation Service removeRelation() method.
*
* @param relationId relation identifier of the updated relation
* @param unregMBeanList List of ObjectNames of MBeans expected
* to be unregistered due to relation removal (can be null)
*
* @exception IllegalArgumentException if null parameter
* @exception RelationNotFoundException if there is no relation for given
* relation id
*/
public void sendRelationRemovalNotification(String relationId,
List<ObjectName> unregMBeanList)
throws IllegalArgumentException,
RelationNotFoundException;
/** {@collect.stats}
* Handles update of the Relation Service role map for the update of given
* role in given relation.
* <P>It is called in relation MBean setRole() (for given role) and
* setRoles() (for each role) methods (implementation provided in
* RelationSupport class).
* <P>It is also called in Relation Service setRole() (for given role) and
* setRoles() (for each role) methods.
* <P>To allow the Relation Service to maintain the consistency (in case
* of MBean unregistration) and to be able to perform queries, this method
* must be called when a role is updated.
*
* @param relationId relation identifier of the updated relation
* @param newRole new role (name and new value)
* @param oldRoleValue old role value (List of ObjectName objects)
*
* @exception IllegalArgumentException if null parameter
* @exception RelationServiceNotRegisteredException if the Relation
* Service is not registered in the MBean Server
* @exception RelationNotFoundException if no relation for given id.
*/
public void updateRoleMap(String relationId,
Role newRole,
List<ObjectName> oldRoleValue)
throws IllegalArgumentException,
RelationServiceNotRegisteredException,
RelationNotFoundException;
/** {@collect.stats}
* Removes given relation from the Relation Service.
* <P>A RelationNotification notification is sent, its type being:
* <P>- RelationNotification.RELATION_BASIC_REMOVAL if the relation was
* only internal to the Relation Service
* <P>- RelationNotification.RELATION_MBEAN_REMOVAL if the relation is
* registered as an MBean.
* <P>For MBeans referenced in such relation, nothing will be done,
*
* @param relationId relation id of the relation to be removed
*
* @exception RelationServiceNotRegisteredException if the Relation
* Service is not registered in the MBean Server
* @exception IllegalArgumentException if null parameter
* @exception RelationNotFoundException if no relation corresponding to
* given relation id
*/
public void removeRelation(String relationId)
throws RelationServiceNotRegisteredException,
IllegalArgumentException,
RelationNotFoundException;
/** {@collect.stats}
* Purges the relations.
*
* <P>Depending on the purgeFlag value, this method is either called
* automatically when a notification is received for the unregistration of
* an MBean referenced in a relation (if the flag is set to true), or not
* (if the flag is set to false).
* <P>In that case it is up to the user to call it to maintain the
* consistency of the relations. To be kept in mind that if an MBean is
* unregistered and the purge not done immediately, if the ObjectName is
* reused and assigned to another MBean referenced in a relation, calling
* manually this purgeRelations() method will cause trouble, as will
* consider the ObjectName as corresponding to the unregistered MBean, not
* seeing the new one.
*
* <P>The behavior depends on the cardinality of the role where the
* unregistered MBean is referenced:
* <P>- if removing one MBean reference in the role makes its number of
* references less than the minimum degree, the relation has to be removed.
* <P>- if the remaining number of references after removing the MBean
* reference is still in the cardinality range, keep the relation and
* update it calling its handleMBeanUnregistration() callback.
*
* @exception RelationServiceNotRegisteredException if the Relation
* Service is not registered in the MBean Server.
*/
public void purgeRelations()
throws RelationServiceNotRegisteredException;
/** {@collect.stats}
* Retrieves the relations where a given MBean is referenced.
* <P>This corresponds to the CIM "References" and "ReferenceNames"
* operations.
*
* @param mbeanName ObjectName of MBean
* @param relationTypeName can be null; if specified, only the relations
* of that type will be considered in the search. Else all relation types
* are considered.
* @param roleName can be null; if specified, only the relations
* where the MBean is referenced in that role will be returned. Else all
* roles are considered.
*
* @return an HashMap, where the keys are the relation ids of the relations
* where the MBean is referenced, and the value is, for each key,
* an ArrayList of role names (as an MBean can be referenced in several
* roles in the same relation).
*
* @exception IllegalArgumentException if null parameter
*/
public Map<String,List<String>>
findReferencingRelations(ObjectName mbeanName,
String relationTypeName,
String roleName)
throws IllegalArgumentException;
/** {@collect.stats}
* Retrieves the MBeans associated to given one in a relation.
* <P>This corresponds to CIM Associators and AssociatorNames operations.
*
* @param mbeanName ObjectName of MBean
* @param relationTypeName can be null; if specified, only the relations
* of that type will be considered in the search. Else all
* relation types are considered.
* @param roleName can be null; if specified, only the relations
* where the MBean is referenced in that role will be considered. Else all
* roles are considered.
*
* @return an HashMap, where the keys are the ObjectNames of the MBeans
* associated to given MBean, and the value is, for each key, an ArrayList
* of the relation ids of the relations where the key MBean is
* associated to given one (as they can be associated in several different
* relations).
*
* @exception IllegalArgumentException if null parameter
*/
public Map<ObjectName,List<String>>
findAssociatedMBeans(ObjectName mbeanName,
String relationTypeName,
String roleName)
throws IllegalArgumentException;
/** {@collect.stats}
* Returns the relation ids for relations of the given type.
*
* @param relationTypeName relation type name
*
* @return an ArrayList of relation ids.
*
* @exception IllegalArgumentException if null parameter
* @exception RelationTypeNotFoundException if there is no relation type
* with that name.
*/
public List<String> findRelationsOfType(String relationTypeName)
throws IllegalArgumentException,
RelationTypeNotFoundException;
/** {@collect.stats}
* Retrieves role value for given role name in given relation.
*
* @param relationId relation id
* @param roleName name of role
*
* @return the ArrayList of ObjectName objects being the role value
*
* @exception RelationServiceNotRegisteredException if the Relation
* Service is not registered
* @exception IllegalArgumentException if null parameter
* @exception RelationNotFoundException if no relation with given id
* @exception RoleNotFoundException if:
* <P>- there is no role with given name
* <P>or
* <P>- the role is not readable.
*
* @see #setRole
*/
public List<ObjectName> getRole(String relationId,
String roleName)
throws RelationServiceNotRegisteredException,
IllegalArgumentException,
RelationNotFoundException,
RoleNotFoundException;
/** {@collect.stats}
* Retrieves values of roles with given names in given relation.
*
* @param relationId relation id
* @param roleNameArray array of names of roles to be retrieved
*
* @return a RoleResult object, including a RoleList (for roles
* successfully retrieved) and a RoleUnresolvedList (for roles not
* retrieved).
*
* @exception RelationServiceNotRegisteredException if the Relation
* Service is not registered in the MBean Server
* @exception IllegalArgumentException if null parameter
* @exception RelationNotFoundException if no relation with given id
*
* @see #setRoles
*/
public RoleResult getRoles(String relationId,
String[] roleNameArray)
throws RelationServiceNotRegisteredException,
IllegalArgumentException,
RelationNotFoundException;
/** {@collect.stats}
* Returns all roles present in the relation.
*
* @param relationId relation id
*
* @return a RoleResult object, including a RoleList (for roles
* successfully retrieved) and a RoleUnresolvedList (for roles not
* readable).
*
* @exception IllegalArgumentException if null parameter
* @exception RelationNotFoundException if no relation for given id
* @exception RelationServiceNotRegisteredException if the Relation
* Service is not registered in the MBean Server
*/
public RoleResult getAllRoles(String relationId)
throws IllegalArgumentException,
RelationNotFoundException,
RelationServiceNotRegisteredException;
/** {@collect.stats}
* Retrieves the number of MBeans currently referenced in the
* given role.
*
* @param relationId relation id
* @param roleName name of role
*
* @return the number of currently referenced MBeans in that role
*
* @exception IllegalArgumentException if null parameter
* @exception RelationNotFoundException if no relation with given id
* @exception RoleNotFoundException if there is no role with given name
*/
public Integer getRoleCardinality(String relationId,
String roleName)
throws IllegalArgumentException,
RelationNotFoundException,
RoleNotFoundException;
/** {@collect.stats}
* Sets the given role in given relation.
* <P>Will check the role according to its corresponding role definition
* provided in relation's relation type
* <P>The Relation Service will keep track of the change to keep the
* consistency of relations by handling referenced MBean unregistrations.
*
* @param relationId relation id
* @param role role to be set (name and new value)
*
* @exception RelationServiceNotRegisteredException if the Relation
* Service is not registered in the MBean Server
* @exception IllegalArgumentException if null parameter
* @exception RelationNotFoundException if no relation with given id
* @exception RoleNotFoundException if:
* <P>- internal relation
* <P>and
* <P>- the role does not exist or is not writable
* @exception InvalidRoleValueException if internal relation and value
* provided for role is not valid:
* <P>- the number of referenced MBeans in given value is less than
* expected minimum degree
* <P>or
* <P>- the number of referenced MBeans in provided value exceeds expected
* maximum degree
* <P>or
* <P>- one referenced MBean in the value is not an Object of the MBean
* class expected for that role
* <P>or
* <P>- an MBean provided for that role does not exist
* @exception RelationTypeNotFoundException if unknown relation type
*
* @see #getRole
*/
public void setRole(String relationId,
Role role)
throws RelationServiceNotRegisteredException,
IllegalArgumentException,
RelationNotFoundException,
RoleNotFoundException,
InvalidRoleValueException,
RelationTypeNotFoundException;
/** {@collect.stats}
* Sets the given roles in given relation.
* <P>Will check the role according to its corresponding role definition
* provided in relation's relation type
* <P>The Relation Service keeps track of the changes to keep the
* consistency of relations by handling referenced MBean unregistrations.
*
* @param relationId relation id
* @param roleList list of roles to be set
*
* @return a RoleResult object, including a RoleList (for roles
* successfully set) and a RoleUnresolvedList (for roles not
* set).
*
* @exception RelationServiceNotRegisteredException if the Relation
* Service is not registered in the MBean Server
* @exception IllegalArgumentException if null parameter
* @exception RelationNotFoundException if no relation with given id
*
* @see #getRoles
*/
public RoleResult setRoles(String relationId,
RoleList roleList)
throws RelationServiceNotRegisteredException,
IllegalArgumentException,
RelationNotFoundException;
/** {@collect.stats}
* Retrieves MBeans referenced in the various roles of the relation.
*
* @param relationId relation id
*
* @return a HashMap mapping:
* <P> ObjectName -> ArrayList of String (role
* names)
*
* @exception IllegalArgumentException if null parameter
* @exception RelationNotFoundException if no relation for given
* relation id
*/
public Map<ObjectName,List<String>> getReferencedMBeans(String relationId)
throws IllegalArgumentException,
RelationNotFoundException;
/** {@collect.stats}
* Returns name of associated relation type for given relation.
*
* @param relationId relation id
*
* @return the name of the associated relation type.
*
* @exception IllegalArgumentException if null parameter
* @exception RelationNotFoundException if no relation for given
* relation id
*/
public String getRelationTypeName(String relationId)
throws IllegalArgumentException,
RelationNotFoundException;
}
| Java |
/*
* Copyright (c) 2000, 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.management.relation;
/** {@collect.stats}
* This exception is raised when there is no relation type with given name in
* Relation Service.
*
* @since 1.5
*/
public class RelationTypeNotFoundException extends RelationException {
/* Serial version */
private static final long serialVersionUID = 1274155316284300752L;
/** {@collect.stats}
* Default constructor, no message put in exception.
*/
public RelationTypeNotFoundException() {
super();
}
/** {@collect.stats}
* Constructor with given message put in exception.
*
* @param message the detail message.
*/
public RelationTypeNotFoundException(String message) {
super(message);
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.