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