1 /*
   2  * Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 
  27 package javax.management.openmbean;
  28 
  29 
  30 // java import
  31 //
  32 import java.io.Serializable;
  33 import java.util.Arrays;
  34 import java.util.Collection;
  35 import java.util.Collections;
  36 import java.util.LinkedHashMap;
  37 import java.util.Map;
  38 import java.util.Set;
  39 import java.util.SortedMap;
  40 import java.util.TreeMap;
  41 
  42 // jmx import
  43 import java.util.TreeSet;
  44 //
  45 
  46 
  47 /**
  48  * The {@code CompositeDataSupport} class is the <i>open data</i> class which
  49  * implements the {@code CompositeData} interface.
  50  *
  51  *
  52  * @since 1.5
  53  */
  54 public class CompositeDataSupport
  55     implements CompositeData, Serializable {
  56 
  57     /* Serial version */
  58     static final long serialVersionUID = 8003518976613702244L;
  59 
  60     /**
  61      * @serial Internal representation of the mapping of item names to their
  62      * respective values.
  63      *         A {@link SortedMap} is used for faster retrieval of elements.
  64      */
  65     @SuppressWarnings("serial") // Conditionally serializable
  66     private final SortedMap<String, Object> contents;
  67 
  68     /**
  69      * @serial The <i>composite type </i> of this <i>composite data</i> instance.
  70      */
  71     private final CompositeType compositeType;
  72 
  73     /**
  74      * <p>Constructs a {@code CompositeDataSupport} instance with the specified
  75      * {@code compositeType}, whose item values
  76      * are specified by {@code itemValues[]}, in the same order as in
  77      * {@code itemNames[]}.
  78      * As a {@code CompositeType} does not specify any order on its items,
  79      * the {@code itemNames[]} parameter is used
  80      * to specify the order in which the values are given in {@code itemValues[]}.
  81      * The items contained in this {@code CompositeDataSupport} instance are
  82      * internally stored in a {@code TreeMap},
  83      * thus sorted in ascending lexicographic order of their names, for faster
  84      * retrieval of individual item values.</p>
  85      *
  86      * <p>The constructor checks that all the constraints listed below for each
  87      * parameter are satisfied,
  88      * and throws the appropriate exception if they are not.</p>
  89      *
  90      * @param compositeType the <i>composite type </i> of this <i>composite
  91      * data</i> instance; must not be null.
  92      *
  93      * @param itemNames {@code itemNames} must list, in any order, all the
  94      * item names defined in {@code compositeType}; the order in which the
  95      * names are listed, is used to match values in {@code itemValues[]}; must
  96      * not be null or empty.
  97      *
  98      * @param itemValues the values of the items, listed in the same order as
  99      * their respective names in {@code itemNames}; each item value can be
 100      * null, but if it is non-null it must be a valid value for the open type
 101      * defined in {@code compositeType} for the corresponding item; must be of
 102      * the same size as {@code itemNames}; must not be null or empty.
 103      *
 104      * @throws IllegalArgumentException {@code compositeType} is null, or
 105      * {@code itemNames[]} or {@code itemValues[]} is null or empty, or one
 106      * of the elements in {@code itemNames[]} is a null or empty string, or
 107      * {@code itemNames[]} and {@code itemValues[]} are not of the same size.
 108      *
 109      * @throws OpenDataException {@code itemNames[]} or
 110      * {@code itemValues[]}'s size differs from the number of items defined in
 111      * {@code compositeType}, or one of the elements in {@code itemNames[]}
 112      * does not exist as an item name defined in {@code compositeType}, or one
 113      * of the elements in {@code itemValues[]} is not a valid value for the
 114      * corresponding item as defined in {@code compositeType}.
 115      */
 116     public CompositeDataSupport(
 117             CompositeType compositeType, String[] itemNames, Object[] itemValues)
 118             throws OpenDataException {
 119         this(makeMap(itemNames, itemValues), compositeType);
 120     }
 121 
 122     private static SortedMap<String, Object> makeMap(
 123             String[] itemNames, Object[] itemValues)
 124             throws OpenDataException {
 125 
 126         if (itemNames == null || itemValues == null)
 127             throw new IllegalArgumentException("Null itemNames or itemValues");
 128         if (itemNames.length == 0 || itemValues.length == 0)
 129             throw new IllegalArgumentException("Empty itemNames or itemValues");
 130         if (itemNames.length != itemValues.length) {
 131             throw new IllegalArgumentException(
 132                     "Different lengths: itemNames[" + itemNames.length +
 133                     "], itemValues[" + itemValues.length + "]");
 134         }
 135 
 136         SortedMap<String, Object> map = new TreeMap<String, Object>();
 137         for (int i = 0; i < itemNames.length; i++) {
 138             String name = itemNames[i];
 139             if (name == null || name.equals(""))
 140                 throw new IllegalArgumentException("Null or empty item name");
 141             if (map.containsKey(name))
 142                 throw new OpenDataException("Duplicate item name " + name);
 143             map.put(itemNames[i], itemValues[i]);
 144         }
 145 
 146         return map;
 147     }
 148 
 149     /**
 150      * <p>
 151      * Constructs a {@code CompositeDataSupport} instance with the specified {@code compositeType},
 152      * whose item names and corresponding values
 153      * are given by the mappings in the map {@code items}.
 154      * This constructor converts the keys to a string array and the values to an object array and calls
 155      * {@code CompositeDataSupport(javax.management.openmbean.CompositeType, java.lang.String[], java.lang.Object[])}.
 156      *
 157      * @param  compositeType  the <i>composite type </i> of this <i>composite data</i> instance;
 158      *                        must not be null.
 159      * @param  items  the mappings of all the item names to their values;
 160      *                {@code items} must contain all the item names defined in {@code compositeType};
 161      *                must not be null or empty.
 162      *
 163      * @throws IllegalArgumentException {@code compositeType} is null, or
 164      * {@code items} is null or empty, or one of the keys in {@code items} is a null
 165      * or empty string.
 166      * @throws OpenDataException {@code items}' size differs from the
 167      * number of items defined in {@code compositeType}, or one of the
 168      * keys in {@code items} does not exist as an item name defined in
 169      * {@code compositeType}, or one of the values in {@code items}
 170      * is not a valid value for the corresponding item as defined in
 171      * {@code compositeType}.
 172      * @throws ArrayStoreException one or more keys in {@code items} is not of
 173      * the class {@code java.lang.String}.
 174      */
 175     public CompositeDataSupport(CompositeType compositeType,
 176                                 Map<String,?> items)
 177             throws OpenDataException {
 178         this(makeMap(items), compositeType);
 179     }
 180 
 181     private static SortedMap<String, Object> makeMap(Map<String, ?> items) {
 182         if (items == null || items.isEmpty())
 183             throw new IllegalArgumentException("Null or empty items map");
 184 
 185         SortedMap<String, Object> map = new TreeMap<String, Object>();
 186         for (Object key : items.keySet()) {
 187             if (key == null || key.equals(""))
 188                 throw new IllegalArgumentException("Null or empty item name");
 189             if (!(key instanceof String)) {
 190                 throw new ArrayStoreException("Item name is not string: " + key);
 191                 // This can happen because of erasure.  The particular
 192                 // exception is a historical artifact - an implementation
 193                 // detail that leaked into the API.
 194             }
 195             map.put((String) key, items.get(key));
 196         }
 197         return map;
 198     }
 199 
 200     private CompositeDataSupport(
 201             SortedMap<String, Object> items, CompositeType compositeType)
 202             throws OpenDataException {
 203 
 204         // Check compositeType is not null
 205         //
 206         if (compositeType == null) {
 207             throw new IllegalArgumentException("Argument compositeType cannot be null.");
 208         }
 209 
 210         // item names defined in compositeType:
 211         Set<String> namesFromType = compositeType.keySet();
 212         Set<String> namesFromItems = items.keySet();
 213 
 214         // This is just a comparison, but we do it this way for a better
 215         // exception message.
 216         if (!namesFromType.equals(namesFromItems)) {
 217             Set<String> extraFromType = new TreeSet<String>(namesFromType);
 218             extraFromType.removeAll(namesFromItems);
 219             Set<String> extraFromItems = new TreeSet<String>(namesFromItems);
 220             extraFromItems.removeAll(namesFromType);
 221             if (!extraFromType.isEmpty() || !extraFromItems.isEmpty()) {
 222                 throw new OpenDataException(
 223                         "Item names do not match CompositeType: " +
 224                         "names in items but not in CompositeType: " + extraFromItems +
 225                         "; names in CompositeType but not in items: " + extraFromType);
 226             }
 227         }
 228 
 229         // Check each value, if not null, is of the open type defined for the
 230         // corresponding item
 231         for (String name : namesFromType) {
 232             Object value = items.get(name);
 233             if (value != null) {
 234                 OpenType<?> itemType = compositeType.getType(name);
 235                 if (!itemType.isValue(value)) {
 236                     throw new OpenDataException(
 237                             "Argument value of wrong type for item " + name +
 238                             ": value " + value + ", type " + itemType);
 239                 }
 240             }
 241         }
 242 
 243         // Initialize internal fields: compositeType and contents
 244         //
 245         this.compositeType = compositeType;
 246         this.contents = items;
 247     }
 248 
 249     /**
 250      * Returns the <i>composite type </i> of this <i>composite data</i> instance.
 251      */
 252     public CompositeType getCompositeType() {
 253 
 254         return compositeType;
 255     }
 256 
 257     /**
 258      * Returns the value of the item whose name is {@code key}.
 259      *
 260      * @throws IllegalArgumentException  if {@code key} is a null or empty String.
 261      *
 262      * @throws InvalidKeyException  if {@code key} is not an existing item name for
 263      * this {@code CompositeData} instance.
 264      */
 265     public Object get(String key) {
 266 
 267         if ( (key == null) || (key.trim().equals("")) ) {
 268             throw new IllegalArgumentException("Argument key cannot be a null or empty String.");
 269         }
 270         if ( ! contents.containsKey(key.trim())) {
 271             throw new InvalidKeyException("Argument key=\""+ key.trim() +"\" is not an existing item name for this CompositeData instance.");
 272         }
 273         return contents.get(key.trim());
 274     }
 275 
 276     /**
 277      * Returns an array of the values of the items whose names are specified by
 278      * {@code keys}, in the same order as {@code keys}.
 279      *
 280      * @throws IllegalArgumentException  if an element in {@code keys} is a null
 281      * or empty String.
 282      *
 283      * @throws InvalidKeyException  if an element in {@code keys} is not an existing
 284      * item name for this {@code CompositeData} instance.
 285      */
 286     public Object[] getAll(String[] keys) {
 287 
 288         if ( (keys == null) || (keys.length == 0) ) {
 289             return new Object[0];
 290         }
 291         Object[] results = new Object[keys.length];
 292         for (int i=0; i<keys.length; i++) {
 293             results[i] = this.get(keys[i]);
 294         }
 295         return results;
 296     }
 297 
 298     /**
 299      * Returns {@code true} if and only if this {@code CompositeData} instance contains
 300      * an item whose name is {@code key}.
 301      * If {@code key} is a null or empty String, this method simply returns false.
 302      */
 303     public boolean containsKey(String key) {
 304 
 305         if ( (key == null) || (key.trim().equals("")) ) {
 306             return false;
 307         }
 308         return contents.containsKey(key);
 309     }
 310 
 311     /**
 312      * Returns {@code true} if and only if this {@code CompositeData} instance
 313      * contains an item
 314      * whose value is {@code value}.
 315      */
 316     public boolean containsValue(Object value) {
 317 
 318         return contents.containsValue(value);
 319     }
 320 
 321     /**
 322      * Returns an unmodifiable Collection view of the item values contained in this
 323      * {@code CompositeData} instance.
 324      * The returned collection's iterator will return the values in the ascending
 325      * lexicographic order of the corresponding
 326      * item names.
 327      */
 328     public Collection<?> values() {
 329 
 330         return Collections.unmodifiableCollection(contents.values());
 331     }
 332 
 333     /**
 334      * Compares the specified <var>obj</var> parameter with this
 335      * <code>CompositeDataSupport</code> instance for equality.
 336      * <p>
 337      * Returns {@code true} if and only if all of the following statements are true:
 338      * <ul>
 339      * <li><var>obj</var> is non null,</li>
 340      * <li><var>obj</var> also implements the <code>CompositeData</code> interface,</li>
 341      * <li>their composite types are equal</li>
 342      * <li>their contents, i.e. (name, value) pairs are equal. If a value contained in
 343      * the content is an array, the value comparison is done as if by calling
 344      * the {@link java.util.Arrays#deepEquals(Object[], Object[]) deepEquals} method
 345      * for arrays of object reference types or the appropriate overloading of
 346      * {@code Arrays.equals(e1,e2)} for arrays of primitive types</li>
 347      * </ul>
 348      * <p>
 349      * This ensures that this {@code equals} method works properly for
 350      * <var>obj</var> parameters which are different implementations of the
 351      * <code>CompositeData</code> interface, with the restrictions mentioned in the
 352      * {@link java.util.Collection#equals(Object) equals}
 353      * method of the {@code java.util.Collection} interface.
 354      *
 355      * @param  obj  the object to be compared for equality with this
 356      * <code>CompositeDataSupport</code> instance.
 357      * @return  <code>true</code> if the specified object is equal to this
 358      * <code>CompositeDataSupport</code> instance.
 359      */
 360     @Override
 361     public boolean equals(Object obj) {
 362         if (this == obj) {
 363             return true;
 364         }
 365 
 366         // if obj is not a CompositeData, return false
 367         if (!(obj instanceof CompositeData)) {
 368             return false;
 369         }
 370 
 371         CompositeData other = (CompositeData) obj;
 372 
 373         // their compositeType should be equal
 374         if (!this.getCompositeType().equals(other.getCompositeType()) ) {
 375             return false;
 376         }
 377 
 378         if (contents.size() != other.values().size()) {
 379             return false;
 380         }
 381 
 382         for (Map.Entry<String,Object> entry : contents.entrySet()) {
 383             Object e1 = entry.getValue();
 384             Object e2 = other.get(entry.getKey());
 385 
 386             if (e1 == e2)
 387                 continue;
 388             if (e1 == null)
 389                 return false;
 390 
 391             boolean eq = e1.getClass().isArray() ?
 392                 Arrays.deepEquals(new Object[] {e1}, new Object[] {e2}) :
 393                 e1.equals(e2);
 394 
 395             if (!eq)
 396                 return false;
 397         }
 398 
 399         // All tests for equality were successful
 400         //
 401         return true;
 402     }
 403 
 404     /**
 405      * Returns the hash code value for this <code>CompositeDataSupport</code> instance.
 406      * <p>
 407      * The hash code of a <code>CompositeDataSupport</code> instance is the sum of the hash codes
 408      * of all elements of information used in <code>equals</code> comparisons
 409      * (ie: its <i>composite type</i> and all the item values).
 410      * <p>
 411      * This ensures that <code> t1.equals(t2) </code> implies that <code> t1.hashCode()==t2.hashCode() </code>
 412      * for any two <code>CompositeDataSupport</code> instances <code>t1</code> and <code>t2</code>,
 413      * as required by the general contract of the method
 414      * {@link Object#hashCode() Object.hashCode()}.
 415      * <p>
 416      * Each item value's hash code is added to the returned hash code.
 417      * If an item value is an array,
 418      * its hash code is obtained as if by calling the
 419      * {@link java.util.Arrays#deepHashCode(Object[]) deepHashCode} method
 420      * for arrays of object reference types or the appropriate overloading
 421      * of {@code Arrays.hashCode(e)} for arrays of primitive types.
 422      *
 423      * @return the hash code value for this <code>CompositeDataSupport</code> instance
 424      */
 425     @Override
 426     public int hashCode() {
 427         int hashcode = compositeType.hashCode();
 428 
 429         for (Object o : contents.values()) {
 430             if (o instanceof Object[])
 431                 hashcode += Arrays.deepHashCode((Object[]) o);
 432             else if (o instanceof byte[])
 433                 hashcode += Arrays.hashCode((byte[]) o);
 434             else if (o instanceof short[])
 435                 hashcode += Arrays.hashCode((short[]) o);
 436             else if (o instanceof int[])
 437                 hashcode += Arrays.hashCode((int[]) o);
 438             else if (o instanceof long[])
 439                 hashcode += Arrays.hashCode((long[]) o);
 440             else if (o instanceof char[])
 441                 hashcode += Arrays.hashCode((char[]) o);
 442             else if (o instanceof float[])
 443                 hashcode += Arrays.hashCode((float[]) o);
 444             else if (o instanceof double[])
 445                 hashcode += Arrays.hashCode((double[]) o);
 446             else if (o instanceof boolean[])
 447                 hashcode += Arrays.hashCode((boolean[]) o);
 448             else if (o != null)
 449                 hashcode += o.hashCode();
 450         }
 451 
 452         return hashcode;
 453     }
 454 
 455     /**
 456      * Returns a string representation of this <code>CompositeDataSupport</code> instance.
 457      * <p>
 458      * The string representation consists of the name of this class (ie <code>javax.management.openmbean.CompositeDataSupport</code>),
 459      * the string representation of the composite type of this instance, and the string representation of the contents
 460      * (ie list the itemName=itemValue mappings).
 461      *
 462      * @return  a string representation of this <code>CompositeDataSupport</code> instance
 463      */
 464     @Override
 465     public String toString() {
 466         return new StringBuilder()
 467             .append(this.getClass().getName())
 468             .append("(compositeType=")
 469             .append(compositeType.toString())
 470             .append(",contents=")
 471             .append(contentString())
 472             .append(")")
 473             .toString();
 474     }
 475 
 476     private String contentString() {
 477         StringBuilder sb = new StringBuilder("{");
 478         String sep = "";
 479         for (Map.Entry<String, Object> entry : contents.entrySet()) {
 480             sb.append(sep).append(entry.getKey()).append("=");
 481             String s = Arrays.deepToString(new Object[] {entry.getValue()});
 482             sb.append(s.substring(1, s.length() - 1));
 483             sep = ", ";
 484         }
 485         sb.append("}");
 486         return sb.toString();
 487     }
 488 }