/* * @(#)file DescriptorSupport.java * @(#)author IBM Corp. * @(#)version 1.53 * @(#)lastedit 05/11/23 */ /* * Copyright IBM Corp. 1999-2000. All rights reserved. * * The program is provided "as is" without any warranty express or implied, * including the warranty of non-infringement and the implied warranties of * merchantibility and fitness for a particular purpose. IBM will not be * liable for any damages suffered by you or any third party claim against * you regarding the Program. * * Copyright 2005 Sun Microsystems, Inc. All rights reserved. * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * * Copyright 2005 Sun Microsystems, Inc. Tous droits reserves. * Ce logiciel est propriete de Sun Microsystems, Inc. * Distribue par des licences qui en restreignent l'utilisation. * */ package javax.management.modelmbean; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.ObjectStreamField; import java.lang.reflect.Constructor; import java.security.AccessController; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; import javax.management.RuntimeOperationsException; import javax.management.MBeanException; import com.sun.jmx.mbeanserver.GetPropertyAction; import com.sun.jmx.trace.Trace; import java.util.Collections; import java.util.SortedMap; import java.util.TreeMap; /** * This class represents the metadata set for a ModelMBean element. A * descriptor is part of the ModelMBeanInfo, * ModelMBeanNotificationInfo, ModelMBeanAttributeInfo, * ModelMBeanConstructorInfo, and ModelMBeanParameterInfo. *
* A descriptor consists of a collection of fields. Each field is in * fieldname=fieldvalue format. Field names are not case sensitive, * case will be preserved on field values. *
* All field names and values are not predefined. New fields can be
* defined and added by any program. Some fields have been predefined
* for consistency of implementation and support by the
* ModelMBeanInfo, ModelMBeanAttributeInfo, ModelMBeanConstructorInfo,
* ModelMBeanNotificationInfo, ModelMBeanOperationInfo and ModelMBean
* classes.
*
* @since 1.5
*/
public class DescriptorSupport
implements javax.management.Descriptor
{
// Serialization compatibility stuff:
// Two serial forms are supported in this class. The selected form depends
// on system property "jmx.serial.form":
// - "1.0" for JMX 1.0
// - any other value for JMX 1.1 and higher
//
// Serial version for old serial form
private static final long oldSerialVersionUID = 8071560848919417985L;
//
// Serial version for new serial form
private static final long newSerialVersionUID = -6292969195866300415L;
//
// Serializable fields in old serial form
private static final ObjectStreamField[] oldSerialPersistentFields =
{
new ObjectStreamField("descriptor", HashMap.class),
new ObjectStreamField("currClass", String.class)
};
//
// Serializable fields in new serial form
private static final ObjectStreamField[] newSerialPersistentFields =
{
new ObjectStreamField("descriptor", HashMap.class)
};
//
// Actual serial version and serial form
private static final long serialVersionUID;
/**
* @serialField descriptor HashMap The collection of fields representing this descriptor
*/
private static final ObjectStreamField[] serialPersistentFields;
private static final String serialForm;
static {
String form = null;
boolean compat = false;
try {
GetPropertyAction act = new GetPropertyAction("jmx.serial.form");
form = (String) AccessController.doPrivileged(act);
compat = "1.0".equals(form); // form may be null
} catch (Exception e) {
// OK: No compat with 1.0
}
serialForm = form;
if (compat) {
serialPersistentFields = oldSerialPersistentFields;
serialVersionUID = oldSerialVersionUID;
} else {
serialPersistentFields = newSerialPersistentFields;
serialVersionUID = newSerialVersionUID;
}
}
//
// END Serialization compatibility stuff
/* Spec says that field names are case-insensitive, but that case
is preserved. This means that we need to be able to map from a
name that may differ in case to the actual name that is used in
the HashMap. Thus, descriptorMap is a TreeMap with a Comparator
that ignores case.
Previous versions of this class had a field called "descriptor"
of type HashMap where the keys were directly Strings. This is
hard to reconcile with the required semantics, so we fabricate
that field virtually during serialization and deserialization
but keep the real information in descriptorMap.
*/
private transient SortedMap Descriptor constructor taking an XML String. The format of the XML string is not defined, but an
* implementation must ensure that the string returned by
* {@link #toXMLString() toXMLString()} on an existing
* descriptor can be used to instantiate an equivalent
* descriptor using this constructor. In this implementation, all field values will be created
* as Strings. If the field values are not Strings, the
* programmer will have to reset or convert these fields
* correctly. Note: array sizes of parameters should match. If both arrays
* are null or empty, then an empty descriptor is created. All field values should be Strings. If the field values are
* not Strings, the programmer will have to reset or convert these
* fields correctly.
*
* Note: Each string should be of the form
* fieldName=fieldValue.
*
* @exception RuntimeOperationsException for illegal value for
* field Names or field Values. The field must contain an
* "=". "=fieldValue", "fieldName", and "fieldValue" are illegal.
* FieldName cannot be null. "fieldName=" will cause the value to
* be null. If the descriptor construction fails for any reason,
* this exception will be thrown.
*
*/
public DescriptorSupport(String[] fields)
{
if (tracing()) {
trace("Descriptor(fields)","Constructor");
}
init(null);
if (( fields == null ) || ( fields.length == 0))
return;
init(null);
for (int i=0; i < fields.length; i++) {
if ((fields[i] == null) || (fields[i].equals(""))) {
continue;
}
int eq_separator = fields[i].indexOf("=");
if (eq_separator < 0) {
// illegal if no = or is first character
if (tracing()) {
trace("Descriptor(String[])",
"Illegal arguments: field does not have '=' " +
"as a name and value separator");
}
final String msg = "Field in invalid format: no equals sign";
final RuntimeException iae = new IllegalArgumentException(msg);
throw new RuntimeOperationsException(iae, msg);
}
String fieldName = fields[i].substring(0,eq_separator);
String fieldValue = null;
if (eq_separator < fields[i].length()) {
// = is not in last character
fieldValue = fields[i].substring(eq_separator+1);
}
if (fieldName.equals("")) {
if (tracing()) {
trace("Descriptor(String[])",
"Illegal arguments: fieldName is empty");
}
final String msg = "Field in invalid format: no fieldName";
final RuntimeException iae = new IllegalArgumentException(msg);
throw new RuntimeOperationsException(iae, msg);
}
setField(fieldName,fieldValue);
}
if (tracing()) {
trace("Descriptor(fields)","Exit");
}
}
private void init(Map
* This implementation does not support interoperating with a directory
* or lookup service. Thus, conforming to the specification, no checking is
* done on the "export" field.
*
* Otherwise this implementation returns false if:
*
* Returns an XML String representing the descriptor. The format is not defined, but an implementation must
* ensure that the string returned by this method can be
* used to build an equivalent descriptor when instantiated
* using the constructor {@link #DescriptorSupport(String)
* DescriptorSupport(String inStr)}. Fields which are not String objects will have toString()
* called on them to create the value. The value will be
* enclosed in parentheses. It is not guaranteed that you can
* reconstruct these objects unless they have been
* specifically set up to support toString() in a meaningful
* format and have a matching constructor that accepts a
* String in the same format. If the descriptor is empty the following String is
* returned: <Descriptor></Descriptor>
* Note that the created empty descriptor is not a valid descriptor
* (the method {@link #isValid isValid} returns false
)
*/
public DescriptorSupport() {
if (tracing())
trace("DescriptorSupport()", "Constructor");
init(null);
}
/**
* Descriptor constructor. Takes as parameter the initial
* capacity of the Map that stores the descriptor fields.
* Capacity will grow as needed.
Note that the created empty
* descriptor is not a valid descriptor (the method {@link
* #isValid isValid} returns false
).
*
* @param initNumFields The initial capacity of the Map that
* stores the descriptor fields.
*
* @exception RuntimeOperationsException for illegal value for
* initNumFields (<= 0)
* @exception MBeanException Wraps a distributed communication Exception.
*/
public DescriptorSupport(int initNumFields)
throws MBeanException, RuntimeOperationsException {
if (tracing()) {
trace("Descriptor(initNumFields=" + initNumFields + ")",
"Constructor");
}
if (initNumFields <= 0) {
if (tracing()) {
trace("Descriptor(maxNumFields)",
"Illegal arguments: initNumFields <= 0");
}
final String msg =
"Descriptor field limit invalid: " + initNumFields;
final RuntimeException iae = new IllegalArgumentException(msg);
throw new RuntimeOperationsException(iae, msg);
}
init(null);
}
/**
* Descriptor constructor taking a Descriptor as parameter.
* Creates a new descriptor initialized to the values of the
* descriptor passed in parameter.
*
* @param inDescr the descriptor to be used to initialize the
* constructed descriptor. If it is null or contains no descriptor
* fields, an empty Descriptor will be created.
*/
public DescriptorSupport(DescriptorSupport inDescr) {
if (tracing()) {
trace("Descriptor(Descriptor)","Constructor");
}
if (inDescr == null)
init(null);
else
init(inDescr.descriptorMap);
}
/**
* fieldValue
must be valid for the
* fieldName
(as defined in method {@link #isValid
* isValid})
*
*
* If the array is empty then an empty array will be returned.
* If the array is 'null' then all values will be returned. The
* order is not the order in which the fields were set.
* If a field name in the array does not exist, then null is
* returned for the matching array element being returned.
*
* @return Object array of field values. If the descriptor is
* empty, you will get an empty array.
*/
public synchronized Object[] getFieldValues(String[] fieldNames) {
if (tracing()) {
trace("getFieldValues(fieldNames)","Entry");
}
// if fieldNames == null return all values
// if fieldNames is String[0] return no values
int numberOfEntries = descriptorMap.size();
/* Following test is somewhat inconsistent but is called for
by the @return clause above. */
if (numberOfEntries == 0)
return new Object[0];
Object[] responseFields;
if (fieldNames != null) {
responseFields = new Object[fieldNames.length];
// room for selected
} else {
responseFields = new Object[numberOfEntries];
// room for all
}
int i = 0;
if (tracing()) {
trace("getFieldValues()",
"Returning " + numberOfEntries + " fields");
}
if (fieldNames == null) {
for (Iterator iter = descriptorMap.values().iterator();
iter.hasNext(); i++)
responseFields[i] = iter.next();
} else {
for (i=0; i < fieldNames.length; i++) {
if ((fieldNames[i] == null) || (fieldNames[i].equals(""))) {
responseFields[i] = null;
} else {
responseFields[i] = getFieldValue(fieldNames[i]);
}
}
}
if (tracing()) {
trace("getFieldValues()","Exit");
}
return responseFields;
}
/**
* Sets all Fields in the list to the new value with the same
* index in the fieldValue array. Array sizes must match. The
* field value will be validated before it is set (by calling the
* method {@link #isValid isValid}). If it is not valid, then an
* exception will be thrown. If the arrays are empty, then no
* change will take effect.
*
* @param fieldNames String array of field names. The array and
* array elements cannot be null.
* @param fieldValues Object array of the corresponding field
* values. The array cannot be null. Elements of the array can
* be null.
*
* @exception RuntimeOperationsException for illegal value for
* field Names or field Values. Neither can be null. The array
* lengths must be equal.
*
* @see #getFields
*/
public synchronized void setFields(String[] fieldNames,
Object[] fieldValues)
throws RuntimeOperationsException {
if (tracing()) {
trace("setFields(fieldNames, ObjectValues)","Entry");
}
if ((fieldNames == null) || (fieldValues == null) ||
(fieldNames.length != fieldValues.length)) {
if (tracing()) {
trace("Descriptor.setFields(String[],Object[])",
"Illegal arguments");
}
final String msg = "FieldNames and FieldValues are null or invalid";
final RuntimeException iae = new IllegalArgumentException(msg);
throw new RuntimeOperationsException(iae, msg);
}
for (int i=0; i < fieldNames.length; i++) {
if (( fieldNames[i] == null) || (fieldNames[i].equals(""))) {
if (tracing()) {
trace("Descriptor.setFields(String[],Object[])",
"Null field name encountered at " + i + " element");
}
final String msg = "FieldNames is null or invalid";
final RuntimeException iae = new IllegalArgumentException(msg);
throw new RuntimeOperationsException(iae, msg);
}
setField(fieldNames[i], fieldValues[i]);
}
if (tracing()) {
trace("Descriptor.setFields(fieldNames, fieldObjects)","Exit");
}
}
/**
* Returns a new Descriptor which is a duplicate of the Descriptor.
*
* @exception RuntimeOperationsException for illegal value for
* field Names or field Values. If the descriptor construction
* fails for any reason, this exception will be thrown.
*/
public synchronized Object clone() throws RuntimeOperationsException {
if (tracing()) {
trace("Descriptor.clone()","Executed");
}
return(new DescriptorSupport(this));
}
/**
* Removes a field from the descriptor.
*
* @param fieldName String name of the field to be removed.
* If the field is not found no exception is thrown.
*/
public synchronized void removeField(String fieldName) {
if ((fieldName == null) || (fieldName.equals(""))) {
return;
}
descriptorMap.remove(fieldName);
}
/**
* Returns true if all of the fields have legal values given their
* names.
*
*
*
* @exception RuntimeOperationsException If the validity checking
* fails for any reason, this exception will be thrown.
*/
public synchronized boolean isValid() throws RuntimeOperationsException {
if (tracing()) {
trace("Descriptor.isValid()","Executed");
}
// verify that the descriptor is valid, by iterating over each field...
Set returnedSet = descriptorMap.entrySet();
if (returnedSet == null) { // null descriptor, not valid
if (tracing()) {
trace("Descriptor.isValid()","returns false (null set)");
}
return false;
}
// must have a name and descriptor type field
String thisName = (String)(this.getFieldValue("name"));
String thisDescType = (String)(getFieldValue("descriptorType"));
if ((thisName == null) || (thisDescType == null) ||
(thisName.equals("")) || (thisDescType.equals(""))) {
return false;
}
// According to the descriptor type we validate the fields contained
for (Iterator iter = returnedSet.iterator(); iter.hasNext();) {
Map.Entry currElement = (Map.Entry) iter.next();
if (currElement != null) {
if (currElement.getValue() != null) {
// validate the field valued...
if (validateField((currElement.getKey()).toString(),
(currElement.getValue()).toString())) {
continue;
} else {
if (tracing()) {
trace("isValid()",
"Field " + currElement.getKey() + "=" +
currElement.getValue() + " is not valid");
}
return false;
}
}
}
}
// fell through, all fields OK
if (tracing()) {
trace("Descriptor.isValid()","returns true");
}
return true;
}
// worker routine for isValid()
// name is not null
// descriptorType is not null
// getMethod and setMethod are not null
// persistPeriod is numeric
// currencyTimeLimit is numeric
// lastUpdatedTimeStamp is numeric
// visibility is 1-4
// severity is 0-6
// log is T or F
// role is not null
// class is not null
// lastReturnedTimeStamp is numeric
private boolean validateField(String fldName, Object fldValue) {
if ((fldName == null) || (fldName.equals("")))
return false;
String SfldValue = "";
boolean isAString = false;
if ((fldValue != null) && (fldValue instanceof java.lang.String)) {
SfldValue = (String) fldValue;
isAString = true;
}
boolean nameOrDescriptorType =
(fldName.equalsIgnoreCase("Name") ||
fldName.equalsIgnoreCase("DescriptorType"));
if (nameOrDescriptorType ||
fldName.equalsIgnoreCase("SetMethod") ||
fldName.equalsIgnoreCase("GetMethod") ||
fldName.equalsIgnoreCase("Role") ||
fldName.equalsIgnoreCase("Class")) {
if (fldValue == null || !isAString)
return false;
if (nameOrDescriptorType && SfldValue.equals(""))
return false;
return true;
} else if (fldName.equalsIgnoreCase("visibility")) {
long v;
if ((fldValue != null) && (isAString)) {
v = toNumeric(SfldValue);
} else if (fldValue instanceof java.lang.Integer) {
v = ((Integer)fldValue).intValue();
} else return false;
if (v >= 1 && v <= 4)
return true;
else
return false;
} else if (fldName.equalsIgnoreCase("severity")) {
long v;
if ((fldValue != null) && (isAString)) {
v = toNumeric(SfldValue);
} else if (fldValue instanceof java.lang.Integer) {
v = ((Integer)fldValue).intValue();
} else return false;
return (v >= 0 && v <= 6);
} else if (fldName.equalsIgnoreCase("PersistPolicy")) {
return (((fldValue != null) && (isAString)) &&
( SfldValue.equalsIgnoreCase("OnUpdate") ||
SfldValue.equalsIgnoreCase("OnTimer") ||
SfldValue.equalsIgnoreCase("NoMoreOftenThan") ||
SfldValue.equalsIgnoreCase("Always") ||
SfldValue.equalsIgnoreCase("Never") ));
} else if (fldName.equalsIgnoreCase("PersistPeriod") ||
fldName.equalsIgnoreCase("CurrencyTimeLimit") ||
fldName.equalsIgnoreCase("LastUpdatedTimeStamp") ||
fldName.equalsIgnoreCase("LastReturnedTimeStamp")) {
long v;
if ((fldValue != null) && (isAString)) {
v = toNumeric(SfldValue);
} else if (fldValue instanceof java.lang.Number) {
v = ((Number)fldValue).longValue();
} else return false;
return (v >= -1);
} else if (fldName.equalsIgnoreCase("log")) {
return ((fldValue instanceof java.lang.Boolean) ||
(isAString &&
(SfldValue.equalsIgnoreCase("T") ||
SfldValue.equalsIgnoreCase("true") ||
SfldValue.equalsIgnoreCase("F") ||
SfldValue.equalsIgnoreCase("false") )));
}
// default to true, it is a field we aren't validating (user etc.)
return true;
}
/**
*
*
* "OnUpdate", "OnTimer", "NoMoreOftenThan", "Always",
* "Never". These String values must not be case sensitive.
*
*
* If there are no fields in the descriptor, then an empty String
* is returned.
*
* If a fieldValue is an object then the toString() method is
* called on it and its returned value is used as the value for
* the field enclosed in parenthesis.
*
* @exception RuntimeOperationsException for illegal value for
* field Names or field Values. If the descriptor string fails
* for any reason, this exception will be thrown.
*/
public synchronized String toString() {
if (tracing()) {
trace("Descriptor.toString()","Entry");
}
String respStr = "";
String[] fields = getFields();
if (tracing()) {
trace("Descriptor.toString()",
"Printing " + fields.length + " fields");
}
if ((fields == null) || (fields.length == 0)) {
if (tracing()) {
trace("Descriptor.toString()","Empty Descriptor");
}
return respStr;
}
for (int i=0; i < fields.length; i++) {
if (i == (fields.length - 1)) {
respStr = respStr.concat(fields[i]);
} else {
respStr = respStr.concat(fields[i] + ", ");
}
}
if (tracing()) {
trace("Descriptor.toString()","Exit returning " + respStr);
}
return respStr;
}
// utility to convert to int, returns -2 if bogus.
private long toNumeric(String inStr) {
long result = -2;
try {
result = java.lang.Long.parseLong(inStr);
} catch (Exception e) {
return -2;
}
return result;
}
// Trace and debug functions
private boolean tracing() {
return Trace.isSelected(Trace.LEVEL_TRACE, Trace.INFO_MODELMBEAN);
}
private void trace(String inClass, String inMethod, String inText) {
Trace.send(Trace.LEVEL_TRACE, Trace.INFO_MODELMBEAN, inClass,
inMethod,
Integer.toHexString(this.hashCode()) + " " + inText);
}
private void trace(String inMethod, String inText) {
trace(currClass, inMethod, inText);
}
/**
* Deserializes a {@link DescriptorSupport} from an {@link
* ObjectInputStream}.
*/
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException {
ObjectInputStream.GetField fields = in.readFields();
Map descriptor = (Map) fields.get("descriptor", null);
init(null);
descriptorMap.putAll(descriptor);
}
/**
* Serializes a {@link DescriptorSupport} to an {@link ObjectOutputStream}.
*/
/* If you set jmx.serial.form to "1.2.0" or "1.2.1", then we are
bug-compatible with those versions. Specifically, field names
are forced to lower-case before being written. This
contradicts the spec, which, though it does not mention
serialization explicitly, does say that the case of field names
is preserved. But in 1.2.0 and 1.2.1, this requirement was not
met. Instead, field names in the descriptor map were forced to
lower case. Those versions expect this to have happened to a
descriptor they deserialize and e.g. getFieldValue will not
find a field whose name is spelt with a different case.
*/
private void writeObject(ObjectOutputStream out) throws IOException {
ObjectOutputStream.PutField fields = out.putFields();
boolean compat = "1.0".equals(serialForm);
if (compat)
fields.put("currClass", currClass);
/* Purge the field "targetObject" from the DescriptorSupport before
* serializing since the referenced object is typically not
* serializable. We do this here rather than purging the "descriptor"
* variable below because that HashMap doesn't do case-insensitivity.
* See CR 6332962.
*/
SortedMap