Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/javax/management/ImmutableDescriptor.java
38829 views
/*1* Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package javax.management;2627import com.sun.jmx.mbeanserver.Util;28import java.io.InvalidObjectException;29import java.lang.reflect.Array;30import java.util.Arrays;31import java.util.Comparator;32import java.util.Map;33import java.util.SortedMap;34import java.util.TreeMap;3536/**37* An immutable descriptor.38* @since 1.639*/40public class ImmutableDescriptor implements Descriptor {41private static final long serialVersionUID = 8853308591080540165L;4243/**44* The names of the fields in this ImmutableDescriptor with their45* original case. The names must be in alphabetical order as determined46* by {@link String#CASE_INSENSITIVE_ORDER}.47*/48private final String[] names;49/**50* The values of the fields in this ImmutableDescriptor. The51* elements in this array match the corresponding elements in the52* {@code names} array.53*/54private final Object[] values;5556private transient int hashCode = -1;5758/**59* An empty descriptor.60*/61public static final ImmutableDescriptor EMPTY_DESCRIPTOR =62new ImmutableDescriptor();6364/**65* Construct a descriptor containing the given fields and values.66*67* @throws IllegalArgumentException if either array is null, or68* if the arrays have different sizes, or69* if a field name is null or empty, or if the same field name70* appears more than once.71*/72public ImmutableDescriptor(String[] fieldNames, Object[] fieldValues) {73this(makeMap(fieldNames, fieldValues));74}7576/**77* Construct a descriptor containing the given fields. Each String78* must be of the form {@code fieldName=fieldValue}. The field name79* ends at the first {@code =} character; for example if the String80* is {@code a=b=c} then the field name is {@code a} and its value81* is {@code b=c}.82*83* @throws IllegalArgumentException if the parameter is null, or84* if a field name is empty, or if the same field name appears85* more than once, or if one of the strings does not contain86* an {@code =} character.87*/88public ImmutableDescriptor(String... fields) {89this(makeMap(fields));90}9192/**93* <p>Construct a descriptor where the names and values of the fields94* are the keys and values of the given Map.</p>95*96* @throws IllegalArgumentException if the parameter is null, or97* if a field name is null or empty, or if the same field name appears98* more than once (which can happen because field names are not case99* sensitive).100*/101public ImmutableDescriptor(Map<String, ?> fields) {102if (fields == null)103throw new IllegalArgumentException("Null Map");104SortedMap<String, Object> map =105new TreeMap<String, Object>(String.CASE_INSENSITIVE_ORDER);106for (Map.Entry<String, ?> entry : fields.entrySet()) {107String name = entry.getKey();108if (name == null || name.equals(""))109throw new IllegalArgumentException("Empty or null field name");110if (map.containsKey(name))111throw new IllegalArgumentException("Duplicate name: " + name);112map.put(name, entry.getValue());113}114int size = map.size();115this.names = map.keySet().toArray(new String[size]);116this.values = map.values().toArray(new Object[size]);117}118119/**120* This method can replace a deserialized instance of this121* class with another instance. For example, it might replace122* a deserialized empty ImmutableDescriptor with123* {@link #EMPTY_DESCRIPTOR}.124*125* @return the replacement object, which may be {@code this}.126*127* @throws InvalidObjectException if the read object has invalid fields.128*/129private Object readResolve() throws InvalidObjectException {130131boolean bad = false;132if (names == null || values == null || names.length != values.length)133bad = true;134if (!bad) {135if (names.length == 0 && getClass() == ImmutableDescriptor.class)136return EMPTY_DESCRIPTOR;137final Comparator<String> compare = String.CASE_INSENSITIVE_ORDER;138String lastName = ""; // also catches illegal null name139for (int i = 0; i < names.length; i++) {140if (names[i] == null ||141compare.compare(lastName, names[i]) >= 0) {142bad = true;143break;144}145lastName = names[i];146}147}148if (bad)149throw new InvalidObjectException("Bad names or values");150151return this;152}153154private static SortedMap<String, ?> makeMap(String[] fieldNames,155Object[] fieldValues) {156if (fieldNames == null || fieldValues == null)157throw new IllegalArgumentException("Null array parameter");158if (fieldNames.length != fieldValues.length)159throw new IllegalArgumentException("Different size arrays");160SortedMap<String, Object> map =161new TreeMap<String, Object>(String.CASE_INSENSITIVE_ORDER);162for (int i = 0; i < fieldNames.length; i++) {163String name = fieldNames[i];164if (name == null || name.equals(""))165throw new IllegalArgumentException("Empty or null field name");166Object old = map.put(name, fieldValues[i]);167if (old != null) {168throw new IllegalArgumentException("Duplicate field name: " +169name);170}171}172return map;173}174175private static SortedMap<String, ?> makeMap(String[] fields) {176if (fields == null)177throw new IllegalArgumentException("Null fields parameter");178String[] fieldNames = new String[fields.length];179String[] fieldValues = new String[fields.length];180for (int i = 0; i < fields.length; i++) {181String field = fields[i];182int eq = field.indexOf('=');183if (eq < 0) {184throw new IllegalArgumentException("Missing = character: " +185field);186}187fieldNames[i] = field.substring(0, eq);188// makeMap will catch the case where the name is empty189fieldValues[i] = field.substring(eq + 1);190}191return makeMap(fieldNames, fieldValues);192}193194/**195* <p>Return an {@code ImmutableDescriptor} whose contents are the union of196* the given descriptors. Every field name that appears in any of197* the descriptors will appear in the result with the198* value that it has when the method is called. Subsequent changes199* to any of the descriptors do not affect the ImmutableDescriptor200* returned here.</p>201*202* <p>In the simplest case, there is only one descriptor and the203* returned {@code ImmutableDescriptor} is a copy of its fields at the204* time this method is called:</p>205*206* <pre>207* Descriptor d = something();208* ImmutableDescriptor copy = ImmutableDescriptor.union(d);209* </pre>210*211* @param descriptors the descriptors to be combined. Any of the212* descriptors can be null, in which case it is skipped.213*214* @return an {@code ImmutableDescriptor} that is the union of the given215* descriptors. The returned object may be identical to one of the216* input descriptors if it is an ImmutableDescriptor that contains all of217* the required fields.218*219* @throws IllegalArgumentException if two Descriptors contain the220* same field name with different associated values. Primitive array221* values are considered the same if they are of the same type with222* the same elements. Object array values are considered the same if223* {@link Arrays#deepEquals(Object[],Object[])} returns true.224*/225public static ImmutableDescriptor union(Descriptor... descriptors) {226// Optimize the case where exactly one Descriptor is non-Empty227// and it is immutable - we can just return it.228int index = findNonEmpty(descriptors, 0);229if (index < 0)230return EMPTY_DESCRIPTOR;231if (descriptors[index] instanceof ImmutableDescriptor232&& findNonEmpty(descriptors, index + 1) < 0)233return (ImmutableDescriptor) descriptors[index];234235Map<String, Object> map =236new TreeMap<String, Object>(String.CASE_INSENSITIVE_ORDER);237ImmutableDescriptor biggestImmutable = EMPTY_DESCRIPTOR;238for (Descriptor d : descriptors) {239if (d != null) {240String[] names;241if (d instanceof ImmutableDescriptor) {242ImmutableDescriptor id = (ImmutableDescriptor) d;243names = id.names;244if (id.getClass() == ImmutableDescriptor.class245&& names.length > biggestImmutable.names.length)246biggestImmutable = id;247} else248names = d.getFieldNames();249for (String n : names) {250Object v = d.getFieldValue(n);251Object old = map.put(n, v);252if (old != null) {253boolean equal;254if (old.getClass().isArray()) {255equal = Arrays.deepEquals(new Object[] {old},256new Object[] {v});257} else258equal = old.equals(v);259if (!equal) {260final String msg =261"Inconsistent values for descriptor field " +262n + ": " + old + " :: " + v;263throw new IllegalArgumentException(msg);264}265}266}267}268}269if (biggestImmutable.names.length == map.size())270return biggestImmutable;271return new ImmutableDescriptor(map);272}273274private static boolean isEmpty(Descriptor d) {275if (d == null)276return true;277else if (d instanceof ImmutableDescriptor)278return ((ImmutableDescriptor) d).names.length == 0;279else280return (d.getFieldNames().length == 0);281}282283private static int findNonEmpty(Descriptor[] ds, int start) {284for (int i = start; i < ds.length; i++) {285if (!isEmpty(ds[i]))286return i;287}288return -1;289}290291private int fieldIndex(String name) {292return Arrays.binarySearch(names, name, String.CASE_INSENSITIVE_ORDER);293}294295public final Object getFieldValue(String fieldName) {296checkIllegalFieldName(fieldName);297int i = fieldIndex(fieldName);298if (i < 0)299return null;300Object v = values[i];301if (v == null || !v.getClass().isArray())302return v;303if (v instanceof Object[])304return ((Object[]) v).clone();305// clone the primitive array, could use an 8-way if/else here306int len = Array.getLength(v);307Object a = Array.newInstance(v.getClass().getComponentType(), len);308System.arraycopy(v, 0, a, 0, len);309return a;310}311312public final String[] getFields() {313String[] result = new String[names.length];314for (int i = 0; i < result.length; i++) {315Object value = values[i];316if (value == null)317value = "";318else if (!(value instanceof String))319value = "(" + value + ")";320result[i] = names[i] + "=" + value;321}322return result;323}324325public final Object[] getFieldValues(String... fieldNames) {326if (fieldNames == null)327return values.clone();328Object[] result = new Object[fieldNames.length];329for (int i = 0; i < fieldNames.length; i++) {330String name = fieldNames[i];331if (name != null && !name.equals(""))332result[i] = getFieldValue(name);333}334return result;335}336337public final String[] getFieldNames() {338return names.clone();339}340341/**342* Compares this descriptor to the given object. The objects are equal if343* the given object is also a Descriptor, and if the two Descriptors have344* the same field names (possibly differing in case) and the same345* associated values. The respective values for a field in the two346* Descriptors are equal if the following conditions hold:347*348* <ul>349* <li>If one value is null then the other must be too.</li>350* <li>If one value is a primitive array then the other must be a primitive351* array of the same type with the same elements.</li>352* <li>If one value is an object array then the other must be too and353* {@link Arrays#deepEquals(Object[],Object[])} must return true.</li>354* <li>Otherwise {@link Object#equals(Object)} must return true.</li>355* </ul>356*357* @param o the object to compare with.358*359* @return {@code true} if the objects are the same; {@code false}360* otherwise.361*362*/363// Note: this Javadoc is copied from javax.management.Descriptor364// due to 6369229.365@Override366public boolean equals(Object o) {367if (o == this)368return true;369if (!(o instanceof Descriptor))370return false;371String[] onames;372if (o instanceof ImmutableDescriptor) {373onames = ((ImmutableDescriptor) o).names;374} else {375onames = ((Descriptor) o).getFieldNames();376Arrays.sort(onames, String.CASE_INSENSITIVE_ORDER);377}378if (names.length != onames.length)379return false;380for (int i = 0; i < names.length; i++) {381if (!names[i].equalsIgnoreCase(onames[i]))382return false;383}384Object[] ovalues;385if (o instanceof ImmutableDescriptor)386ovalues = ((ImmutableDescriptor) o).values;387else388ovalues = ((Descriptor) o).getFieldValues(onames);389return Arrays.deepEquals(values, ovalues);390}391392/**393* <p>Returns the hash code value for this descriptor. The hash394* code is computed as the sum of the hash codes for each field in395* the descriptor. The hash code of a field with name {@code n}396* and value {@code v} is {@code n.toLowerCase().hashCode() ^ h}.397* Here {@code h} is the hash code of {@code v}, computed as398* follows:</p>399*400* <ul>401* <li>If {@code v} is null then {@code h} is 0.</li>402* <li>If {@code v} is a primitive array then {@code h} is computed using403* the appropriate overloading of {@code java.util.Arrays.hashCode}.</li>404* <li>If {@code v} is an object array then {@code h} is computed using405* {@link Arrays#deepHashCode(Object[])}.</li>406* <li>Otherwise {@code h} is {@code v.hashCode()}.</li>407* </ul>408*409* @return A hash code value for this object.410*411*/412// Note: this Javadoc is copied from javax.management.Descriptor413// due to 6369229.414@Override415public int hashCode() {416if (hashCode == -1) {417hashCode = Util.hashCode(names, values);418}419return hashCode;420}421422@Override423public String toString() {424StringBuilder sb = new StringBuilder("{");425for (int i = 0; i < names.length; i++) {426if (i > 0)427sb.append(", ");428sb.append(names[i]).append("=");429Object v = values[i];430if (v != null && v.getClass().isArray()) {431String s = Arrays.deepToString(new Object[] {v});432s = s.substring(1, s.length() - 1); // remove [...]433v = s;434}435sb.append(String.valueOf(v));436}437return sb.append("}").toString();438}439440/**441* Returns true if all of the fields have legal values given their442* names. This method always returns true, but a subclass can443* override it to return false when appropriate.444*445* @return true if the values are legal.446*447* @exception RuntimeOperationsException if the validity checking fails.448* The method returns false if the descriptor is not valid, but throws449* this exception if the attempt to determine validity fails.450*/451public boolean isValid() {452return true;453}454455/**456* <p>Returns a descriptor which is equal to this descriptor.457* Changes to the returned descriptor will have no effect on this458* descriptor, and vice versa.</p>459*460* <p>This method returns the object on which it is called.461* A subclass can override it462* to return another object provided the contract is respected.463*464* @exception RuntimeOperationsException for illegal value for field Names465* or field Values.466* If the descriptor construction fails for any reason, this exception will467* be thrown.468*/469@Override470public Descriptor clone() {471return this;472}473474/**475* This operation is unsupported since this class is immutable. If476* this call would change a mutable descriptor with the same contents,477* then a {@link RuntimeOperationsException} wrapping an478* {@link UnsupportedOperationException} is thrown. Otherwise,479* the behavior is the same as it would be for a mutable descriptor:480* either an exception is thrown because of illegal parameters, or481* there is no effect.482*/483public final void setFields(String[] fieldNames, Object[] fieldValues)484throws RuntimeOperationsException {485if (fieldNames == null || fieldValues == null)486illegal("Null argument");487if (fieldNames.length != fieldValues.length)488illegal("Different array sizes");489for (int i = 0; i < fieldNames.length; i++)490checkIllegalFieldName(fieldNames[i]);491for (int i = 0; i < fieldNames.length; i++)492setField(fieldNames[i], fieldValues[i]);493}494495/**496* This operation is unsupported since this class is immutable. If497* this call would change a mutable descriptor with the same contents,498* then a {@link RuntimeOperationsException} wrapping an499* {@link UnsupportedOperationException} is thrown. Otherwise,500* the behavior is the same as it would be for a mutable descriptor:501* either an exception is thrown because of illegal parameters, or502* there is no effect.503*/504public final void setField(String fieldName, Object fieldValue)505throws RuntimeOperationsException {506checkIllegalFieldName(fieldName);507int i = fieldIndex(fieldName);508if (i < 0)509unsupported();510Object value = values[i];511if ((value == null) ?512(fieldValue != null) :513!value.equals(fieldValue))514unsupported();515}516517/**518* Removes a field from the descriptor.519*520* @param fieldName String name of the field to be removed.521* If the field name is illegal or the field is not found,522* no exception is thrown.523*524* @exception RuntimeOperationsException if a field of the given name525* exists and the descriptor is immutable. The wrapped exception will526* be an {@link UnsupportedOperationException}.527*/528public final void removeField(String fieldName) {529if (fieldName != null && fieldIndex(fieldName) >= 0)530unsupported();531}532533static Descriptor nonNullDescriptor(Descriptor d) {534if (d == null)535return EMPTY_DESCRIPTOR;536else537return d;538}539540private static void checkIllegalFieldName(String name) {541if (name == null || name.equals(""))542illegal("Null or empty field name");543}544545private static void unsupported() {546UnsupportedOperationException uoe =547new UnsupportedOperationException("Descriptor is read-only");548throw new RuntimeOperationsException(uoe);549}550551private static void illegal(String message) {552IllegalArgumentException iae = new IllegalArgumentException(message);553throw new RuntimeOperationsException(iae);554}555}556557558