001/* ===========================================================
002 * JFreeChart : a free chart library for the Java(tm) platform
003 * ===========================================================
004 *
005 * (C) Copyright 2000-2020, by Object Refinery Limited and Contributors.
006 *
007 * Project Info:  http://www.jfree.org/jfreechart/index.html
008 *
009 * This library is free software; you can redistribute it and/or modify it
010 * under the terms of the GNU Lesser General Public License as published by
011 * the Free Software Foundation; either version 2.1 of the License, or
012 * (at your option) any later version.
013 *
014 * This library is distributed in the hope that it will be useful, but
015 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
016 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
017 * License for more details.
018 *
019 * You should have received a copy of the GNU Lesser General Public
020 * License along with this library; if not, write to the Free Software
021 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
022 * USA.
023 *
024 * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. 
025 * Other names may be trademarks of their respective owners.]
026 *
027 * ------------------
028 * KeyToGroupMap.java
029 * ------------------
030 * (C) Copyright 2004-2016, by Object Refinery Limited and Contributors.
031 *
032 * Original Author:  David Gilbert (for Object Refinery Limited);
033 * Contributor(s):   -;
034 *
035 * Changes
036 * -------
037 * 29-Apr-2004 : Version 1 (DG);
038 * 07-Jul-2004 : Added a group list to ensure group index is consistent, fixed
039 *               cloning problem (DG);
040 * 18-Aug-2005 : Added casts in clone() method to suppress 1.5 compiler
041 *               warnings - see patch 1260587 (DG);
042 * 03-Jul-2013 : Use ParamChecks (DG);
043 *
044 */
045
046package org.jfree.data;
047
048import java.io.Serializable;
049import java.lang.reflect.Method;
050import java.lang.reflect.Modifier;
051import java.util.ArrayList;
052import java.util.Collection;
053import java.util.HashMap;
054import java.util.Iterator;
055import java.util.List;
056import java.util.Map;
057import org.jfree.chart.util.ObjectUtils;
058import org.jfree.chart.util.Args;
059import org.jfree.chart.util.PublicCloneable;
060
061/**
062 * A class that maps keys (instances of {@code Comparable}) to groups.
063 */
064public class KeyToGroupMap implements Cloneable, PublicCloneable, Serializable {
065
066    /** For serialization. */
067    private static final long serialVersionUID = -2228169345475318082L;
068
069    /** The default group. */
070    private Comparable defaultGroup;
071
072    /** The groups. */
073    private List groups;
074
075    /** A mapping between keys and groups. */
076    private Map keyToGroupMap;
077
078    /**
079     * Creates a new map with a default group named 'Default Group'.
080     */
081    public KeyToGroupMap() {
082        this("Default Group");
083    }
084
085    /**
086     * Creates a new map with the specified default group.
087     *
088     * @param defaultGroup  the default group ({@code null} not permitted).
089     */
090    public KeyToGroupMap(Comparable defaultGroup) {
091        Args.nullNotPermitted(defaultGroup, "defaultGroup");
092        this.defaultGroup = defaultGroup;
093        this.groups = new ArrayList();
094        this.keyToGroupMap = new HashMap();
095    }
096
097    /**
098     * Returns the number of groups in the map.
099     *
100     * @return The number of groups in the map.
101     */
102    public int getGroupCount() {
103        return this.groups.size() + 1;
104    }
105
106    /**
107     * Returns a list of the groups (always including the default group) in the
108     * map.  The returned list is independent of the map, so altering the list
109     * will have no effect.
110     *
111     * @return The groups (never {@code null}).
112     */
113    public List getGroups() {
114        List result = new ArrayList();
115        result.add(this.defaultGroup);
116        Iterator iterator = this.groups.iterator();
117        while (iterator.hasNext()) {
118            Comparable group = (Comparable) iterator.next();
119            if (!result.contains(group)) {
120                result.add(group);
121            }
122        }
123        return result;
124    }
125
126    /**
127     * Returns the index for the group.
128     *
129     * @param group  the group.
130     *
131     * @return The group index (or -1 if the group is not represented within
132     *         the map).
133     */
134    public int getGroupIndex(Comparable group) {
135        int result = this.groups.indexOf(group);
136        if (result < 0) {
137            if (this.defaultGroup.equals(group)) {
138                result = 0;
139            }
140        }
141        else {
142            result = result + 1;
143        }
144        return result;
145    }
146
147    /**
148     * Returns the group that a key is mapped to.
149     *
150     * @param key  the key ({@code null} not permitted).
151     *
152     * @return The group (never {@code null}, returns the default group if
153     *         there is no mapping for the specified key).
154     */
155    public Comparable getGroup(Comparable key) {
156        Args.nullNotPermitted(key, "key");
157        Comparable result = this.defaultGroup;
158        Comparable group = (Comparable) this.keyToGroupMap.get(key);
159        if (group != null) {
160            result = group;
161        }
162        return result;
163    }
164
165    /**
166     * Maps a key to a group.
167     *
168     * @param key  the key ({@code null} not permitted).
169     * @param group  the group ({@code null} permitted, clears any
170     *               existing mapping).
171     */
172    public void mapKeyToGroup(Comparable key, Comparable group) {
173        Args.nullNotPermitted(key, "key");
174        Comparable currentGroup = getGroup(key);
175        if (!currentGroup.equals(this.defaultGroup)) {
176            if (!currentGroup.equals(group)) {
177                int count = getKeyCount(currentGroup);
178                if (count == 1) {
179                    this.groups.remove(currentGroup);
180                }
181            }
182        }
183        if (group == null) {
184            this.keyToGroupMap.remove(key);
185        }
186        else {
187            if (!this.groups.contains(group)) {
188                if (!this.defaultGroup.equals(group)) {
189                    this.groups.add(group);
190                }
191            }
192            this.keyToGroupMap.put(key, group);
193        }
194    }
195
196    /**
197     * Returns the number of keys mapped to the specified group.  This method
198     * won't always return an accurate result for the default group, since
199     * explicit mappings are not required for this group.
200     *
201     * @param group  the group ({@code null} not permitted).
202     *
203     * @return The key count.
204     */
205    public int getKeyCount(Comparable group) {
206        Args.nullNotPermitted(group, "group");
207        int result = 0;
208        Iterator iterator = this.keyToGroupMap.values().iterator();
209        while (iterator.hasNext()) {
210            Comparable g = (Comparable) iterator.next();
211            if (group.equals(g)) {
212                result++;
213            }
214        }
215        return result;
216    }
217
218    /**
219     * Tests the map for equality against an arbitrary object.
220     *
221     * @param obj  the object to test against ({@code null} permitted).
222     *
223     * @return A boolean.
224     */
225    @Override
226    public boolean equals(Object obj) {
227        if (obj == this) {
228            return true;
229        }
230        if (!(obj instanceof KeyToGroupMap)) {
231            return false;
232        }
233        KeyToGroupMap that = (KeyToGroupMap) obj;
234        if (!ObjectUtils.equal(this.defaultGroup, that.defaultGroup)) {
235            return false;
236        }
237        if (!this.keyToGroupMap.equals(that.keyToGroupMap)) {
238            return false;
239        }
240        return true;
241    }
242
243    /**
244     * Returns a clone of the map.
245     *
246     * @return A clone.
247     *
248     * @throws CloneNotSupportedException  if there is a problem cloning the
249     *                                     map.
250     */
251    @Override
252    public Object clone() throws CloneNotSupportedException {
253        KeyToGroupMap result = (KeyToGroupMap) super.clone();
254        result.defaultGroup
255            = (Comparable) KeyToGroupMap.clone(this.defaultGroup);
256        result.groups = (List) KeyToGroupMap.clone(this.groups);
257        result.keyToGroupMap = (Map) KeyToGroupMap.clone(this.keyToGroupMap);
258        return result;
259    }
260
261    /**
262     * Attempts to clone the specified object using reflection.
263     *
264     * @param object  the object ({@code null} permitted).
265     *
266     * @return The cloned object, or the original object if cloning failed.
267     */
268    private static Object clone(Object object) {
269        if (object == null) {
270            return null;
271        }
272        Class c = object.getClass();
273        Object result = null;
274        try {
275            Method m = c.getMethod("clone", (Class[]) null);
276            if (Modifier.isPublic(m.getModifiers())) {
277                try {
278                    result = m.invoke(object, (Object[]) null);
279                }
280                catch (Exception e) {
281                    e.printStackTrace();
282                }
283            }
284        }
285        catch (NoSuchMethodException e) {
286            result = object;
287        }
288        return result;
289    }
290
291    /**
292     * Returns a clone of the list.
293     *
294     * @param list  the list.
295     *
296     * @return A clone of the list.
297     *
298     * @throws CloneNotSupportedException if the list could not be cloned.
299     */
300    private static Collection clone(Collection list)
301        throws CloneNotSupportedException {
302        Collection result = null;
303        if (list != null) {
304            try {
305                List clone = (List) list.getClass().newInstance();
306                Iterator iterator = list.iterator();
307                while (iterator.hasNext()) {
308                    clone.add(KeyToGroupMap.clone(iterator.next()));
309                }
310                result = clone;
311            }
312            catch (Exception e) {
313                throw new CloneNotSupportedException("Exception.");
314            }
315        }
316        return result;
317    }
318
319}