001    /* CompositeData.java -- A composite data structure implementation.
002       Copyright (C) 2006, 2007 Free Software Foundation, Inc.
003    
004    This file is part of GNU Classpath.
005    
006    GNU Classpath is free software; you can redistribute it and/or modify
007    it under the terms of the GNU General Public License as published by
008    the Free Software Foundation; either version 2, or (at your option)
009    any later version.
010    
011    GNU Classpath is distributed in the hope that it will be useful, but
012    WITHOUT ANY WARRANTY; without even the implied warranty of
013    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
014    General Public License for more details.
015    
016    You should have received a copy of the GNU General Public License
017    along with GNU Classpath; see the file COPYING.  If not, write to the
018    Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
019    02110-1301 USA.
020    
021    Linking this library statically or dynamically with other modules is
022    making a combined work based on this library.  Thus, the terms and
023    conditions of the GNU General Public License cover the whole
024    combination.
025    
026    As a special exception, the copyright holders of this library give you
027    permission to link this library with independent modules to produce an
028    executable, regardless of the license terms of these independent
029    modules, and to copy and distribute the resulting executable under
030    terms of your choice, provided that you also meet, for each linked
031    independent module, the terms and conditions of the license of that
032    module.  An independent module is a module which is not derived from
033    or based on this library.  If you modify this library, you may extend
034    this exception to your version of the library, but you are not
035    obligated to do so.  If you do not wish to do so, delete this
036    exception statement from your version. */
037    
038    package javax.management.openmbean;
039    
040    import java.io.Serializable;
041    
042    import java.util.Collection;
043    import java.util.Collections;
044    import java.util.Iterator;
045    import java.util.Map;
046    import java.util.Set;
047    import java.util.SortedMap;
048    import java.util.TreeMap;
049    
050    /**
051     * Provides an implementation of the {@link CompositeData}
052     * interface.
053     *
054     * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
055     * @since 1.5
056     */
057    public class CompositeDataSupport
058      implements CompositeData, Serializable
059    {
060    
061      /**
062       * Compatible with JDK 1.5
063       */
064      private static final long serialVersionUID = 8003518976613702244L;
065    
066      /**
067       * Mapping of field names to values.
068       *
069       * @serial the map of field names to values.
070       */
071      private SortedMap<String, Object> contents;
072    
073      /**
074       * The composite type which represents this composite data instance.
075       *
076       * @serial the type information for this instance.
077       */
078      private CompositeType compositeType;
079    
080      /**
081       * Constructs a new {@link CompositeDataSupport} instance with the
082       * specified type using field names and values from the supplied map.
083       * The keys of the map become the field names, while the values
084       * become the values of each respective field.  This constructor simply
085       * calls the other constructor, with the two arrays formed using the
086       * keys and values of this map, respectively.  Thus, the input parameters
087       * given should conform to the same requirements given there (i.e. no
088       * null values or empty strings).
089       *
090       * @param type the composite type of this composite data structure.
091       * @param items a mapping of field names to values.  This should match
092       *              the mappings given by the type (i.e. for each mapping
093       *              in the type, there should be a corresponding field name
094       *              with a value of the correct type).
095       * @throws IllegalArgumentException if the type, the map or any of the keys
096       *                                  or values in the map are <code>null</code>,
097       *                                  or if any key from the map is an empty
098       *                                  string.
099       * @throws OpenDataException if a mismatch occurs between the map and the
100       *                           field name/type specification given by the
101       *                           {@link CompositeType} instance.  This may be
102       *                           due to the two having a different size, a
103       *                           mismatch between keys or an incorrectly typed
104       *                           value.
105       * @throws ArrayStoreException if one of the keys is not a
106       *                             {@link java.lang.String} (thus calling a failure
107       *                             in converting the keys to an array of strings).
108       */
109      public CompositeDataSupport(CompositeType type, Map<String, ?> items)
110        throws OpenDataException
111      {
112        this(type, 
113             items.keySet().toArray(new String[items.size()]),
114             items.values().toArray());
115      }
116    
117      /**
118       * Constructs a new {@link CompositeDataSupport} instance with the
119       * specified type using the supplied arrays of field names and
120       * values.  Neither the type, the two arrays or any elements of the
121       * arrays may be <code>null</code>.  The {@link java.lang.String}s
122       * within the <code>names</code> array must be non-empty.  The
123       * arrays must match in size and order, as each element of the
124       * <code>names</code> array is matched against the corresponding
125       * value in the <code>values</code> array.  Internally, the two are
126       * stored in a map, lexographically ordered using the field names.
127       * The data given should also conform to the description of the
128       * instance given by the {@link CompositeType} instance supplied.
129       *
130       * @param type the composite type of this composite data structure.
131       * @param names the field names.
132       * @param values the corresponding values of the fields.
133       * @throws IllegalArgumentException if the type, the arrays or any of the keys
134       *                                  or values in the arrays are <code>null</code>,
135       *                                  or if any key from <code>names</code> is
136       *                                  an empty string.  This also occurs if the
137       *                                  arrays differ in length.
138       * @throws OpenDataException if a mismatch occurs between the arrays and the
139       *                           field name/type specification given by the
140       *                           {@link CompositeType} instance.  This may be
141       *                           due to a differing number of field names, a
142       *                           mismatch between names or an incorrectly typed
143       *                           value.
144       */
145      public CompositeDataSupport(CompositeType type, String[] names, Object[] values)
146        throws OpenDataException
147      {
148        if (type == null)
149          throw new IllegalArgumentException("The given composite type is null.");
150        compositeType = type;
151        if (names == null)
152          throw new IllegalArgumentException("The names array is null.");
153        if (values == null)
154          throw new IllegalArgumentException("The values array is null.");
155        if (names.length != values.length)
156          throw new IllegalArgumentException("The sizes of the arrays differ.");
157        Set typeKeys = type.keySet();
158        if (typeKeys.size() != names.length)
159          throw new OpenDataException("The number of field names does not match " +
160                                      "the type description.");
161        contents = new TreeMap<String, Object>();
162        for (int a = 0; a < names.length; ++a)
163          {
164            if (names[a] == null)
165              throw new IllegalArgumentException("Element " + a + " of the names " +
166                                                 "array is null.");
167            if (names[a].length() == 0)
168              throw new IllegalArgumentException("Element " + a + " of the names " +
169                                                 "array is an empty string.");
170            if (values[a] == null)
171              throw new IllegalArgumentException("Element " + a + " of the values " +
172                                                 "array is null.");
173            if (!(typeKeys.contains(names[a])))
174              throw new OpenDataException("The name, " + names[a] + ", is not a " +
175                                          "field in the given type description.");
176            if (!(type.getType(names[a]).isValue(values[a])))
177              throw new OpenDataException("The value, " + values[a] + ", is not a " +
178                                          "valid value for the " + names[a] + " field.");
179            contents.put(names[a], values[a]);
180          }
181      }
182    
183      /**
184       * Returns true if this {@link CompositeData} instance contains
185       * the specified key.  This method always returns false for
186       * an input key equal to <code>null</code> or the empty string.
187       *
188       * @param key the key to find in the structure.
189       * @return true if the key exists.
190       */
191      public boolean containsKey(String key)
192      {
193        if (key == null || key.length() == 0)
194          return false;
195        else
196          return contents.containsKey(key);
197      }
198    
199      /**
200       * Returns true if this {@link CompositeData} instance has
201       * a value equal to that supplied.
202       *
203       * @param value the value to look for.
204       * @return true if the value exists.
205       */
206      public boolean containsValue(Object value)
207      {
208        return contents.containsValue(value);
209      }
210    
211    
212      /**
213       * Compares the specified object with this object for equality.
214       * The object is judged equivalent if it is non-null, and also
215       * an instance of {@link CompositeData} with the same name-value
216       * mappings and types.  The two compared instances may be
217       * equivalent even if they represent different implementations of
218       * {@link CompositeData}.
219       *
220       * @param obj the object to compare for equality.
221       * @return true if <code>obj</code> is equal to <code>this</code>.
222       */
223      public boolean equals(Object obj)
224      {
225        if (!(obj instanceof CompositeData))
226          return false;
227        CompositeData data = (CompositeData) obj;
228        if (!(data.getCompositeType().equals(compositeType)))
229          return false;
230        Iterator it = contents.keySet().iterator();
231        while (it.hasNext())
232          {
233            String key = (String) it.next();
234            if (!(data.containsKey(key)))
235              return false;
236            if (!(data.get(key).equals(contents.get(key))))
237              return false;
238          }
239        return true;
240      }
241    
242      /**
243       * Retrieves the value for the specified key.
244       *
245       * @param key the key whose value should be returned.
246       * @return the matching value.
247       * @throws IllegalArgumentException if the key is <code>null</code>
248       *                                  or the empty string.
249       * @throws InvalidKeyException if the key does not exist.
250       */
251      public Object get(String key)
252      {
253        if (key == null)
254          throw new IllegalArgumentException("The supplied key is null.");
255        if (key.length() == 0)
256          throw new IllegalArgumentException("The supplied key is the empty string.");
257        if (!(contents.containsKey(key)))
258          throw new InvalidKeyException("The supplied key does not exist.");
259        return contents.get(key);
260      }
261    
262      /**
263       * Returns the appropriate value for each key in the given array,
264       * using the same ordering.
265       *
266       * @param keys the keys whose values should be returned.
267       * @return the matching values.
268       * @throws IllegalArgumentException if one of the keys is
269       *                                  <code>null</code> or the
270       *                                  empty string.
271       * @throws InvalidKeyException if one of the keys does not exist.
272       */
273      public Object[] getAll(String[] keys)
274      {
275        Object[] values = new Object[keys.length];
276        for (int a = 0; a < keys.length; ++a)
277          values[a] = get(keys[a]);
278        return values;
279      }
280    
281    
282      /**
283       * Returns the composite type which corresponds to this instance
284       * of {@link CompositeData}.
285       *
286       * @return the composite type for this instance.
287       */
288      public CompositeType getCompositeType()
289      {
290        return compositeType;
291      }
292    
293      /**
294       * Returns the hash code of this instance.  The hash code is
295       * computed as the sum of the hash codes of all the values plus
296       * the hash code of the composite type.  As equality comparisons
297       * take place using this same information, this should ensure that
298       * the property, <code>e1.equals(e2)</code> implies
299       * <code>e1.hashCode() == e2.hashCode(), holds for any pair
300       * of instances, <code>e1</code> and <code>e2</code>. However,
301       * this relies on the other instance implementing the
302       * <code>hashCode</code> method correctly, if it is not an
303       * instance of {@link CompositeDataSupport}.
304       *
305       * @return the hash code of this {@link CompositeData}.
306       * @see Object#equals(Object)
307       */
308      public int hashCode()
309      {
310        int code = compositeType.hashCode();
311        Iterator it = values().iterator();
312        while (it.hasNext())
313          code += it.next().hashCode();
314        return code;
315      }
316    
317    
318      /**
319       * Returns a textual representation of this instance.  The
320       * exact format is left up to the implementation, but it
321       * should contain the name of the implementing class,
322       * the name of the type and a mapping of the form
323       * <code>key=value</code> for each pair of key and value.
324       *
325       * @return a {@link java.lang.String} representation of the
326       *         object.
327       */
328      public String toString()
329      {
330        return getClass().getName() +
331          "[compositeType=" + compositeType +
332          ",contents=" + contents +
333          "]";
334      }
335    
336      /**
337       * Returns a read-only collection of the values associated with
338       * this instance.  The values are sorted using the lexicographic
339       * ordering of the corresponding keys.
340       *
341       * @return the values of this instance.
342       */
343      public Collection<?> values()
344      {
345        return Collections.unmodifiableCollection(contents.values());
346      }
347    
348    }
349