001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      https://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.commons.collections4.map;
018
019import java.io.IOException;
020import java.io.ObjectInputStream;
021import java.io.ObjectOutputStream;
022import java.io.Serializable;
023import java.util.Collection;
024import java.util.Map;
025import java.util.Set;
026import java.util.SortedMap;
027
028import org.apache.commons.collections4.BoundedMap;
029import org.apache.commons.collections4.CollectionUtils;
030import org.apache.commons.collections4.collection.UnmodifiableCollection;
031import org.apache.commons.collections4.set.UnmodifiableSet;
032
033/**
034 * Decorates another {@code SortedMap} to fix the size blocking add/remove.
035 * <p>
036 * Any action that would change the size of the map is disallowed.
037 * The put method is allowed to change the value associated with an existing
038 * key however.
039 * </p>
040 * <p>
041 * If trying to remove or clear the map, an UnsupportedOperationException is
042 * thrown. If trying to put a new mapping into the map, an
043 * IllegalArgumentException is thrown. This is because the put method can
044 * succeed if the mapping's key already exists in the map, so the put method
045 * is not always unsupported.
046 * </p>
047 * <p>
048 * <strong>Note that FixedSizeSortedMap is not synchronized and is not thread-safe.</strong>
049 * If you wish to use this map from multiple threads concurrently, you must use
050 * appropriate synchronization. The simplest approach is to wrap this map
051 * using {@link java.util.Collections#synchronizedSortedMap}. This class may throw
052 * exceptions when accessed by concurrent threads without synchronization.
053 * </p>
054 * <p>
055 * This class is Serializable from Commons Collections 3.1.
056 * </p>
057 *
058 * @param <K> The type of the keys in this map
059 * @param <V> The type of the values in this map
060 * @since 3.0
061 */
062public class FixedSizeSortedMap<K, V>
063        extends AbstractSortedMapDecorator<K, V>
064        implements BoundedMap<K, V>, Serializable {
065
066    /** Serialization version */
067    private static final long serialVersionUID = 3126019624511683653L;
068
069    /**
070     * Factory method to create a fixed size sorted map.
071     *
072     * @param <K>  the key type
073     * @param <V>  the value type
074     * @param map  The map to decorate, must not be null
075     * @return A new fixed size sorted map
076     * @throws NullPointerException if map is null
077     * @since 4.0
078     */
079    public static <K, V> FixedSizeSortedMap<K, V> fixedSizeSortedMap(final SortedMap<K, V> map) {
080        return new FixedSizeSortedMap<>(map);
081    }
082
083    /**
084     * Constructor that wraps (not copies).
085     *
086     * @param map  The map to decorate, must not be null
087     * @throws NullPointerException if map is null
088     */
089    protected FixedSizeSortedMap(final SortedMap<K, V> map) {
090        super(map);
091    }
092
093    /**
094     * Always throws {@link UnsupportedOperationException}.
095     *
096     * @throws UnsupportedOperationException Always thrown.
097     */
098    @Override
099    public void clear() {
100        throw new UnsupportedOperationException("Map is fixed size");
101    }
102
103    @Override
104    public Set<Map.Entry<K, V>> entrySet() {
105        return UnmodifiableSet.unmodifiableSet(map.entrySet());
106    }
107
108    /**
109     * Gets the map being decorated.
110     *
111     * @return The decorated map
112     */
113    protected SortedMap<K, V> getSortedMap() {
114        return (SortedMap<K, V>) map;
115    }
116
117    @Override
118    public SortedMap<K, V> headMap(final K toKey) {
119        return new FixedSizeSortedMap<>(getSortedMap().headMap(toKey));
120    }
121
122    @Override
123    public boolean isFull() {
124        return true;
125    }
126
127    @Override
128    public Set<K> keySet() {
129        return UnmodifiableSet.unmodifiableSet(map.keySet());
130    }
131
132    @Override
133    public int maxSize() {
134        return size();
135    }
136
137    @Override
138    public V put(final K key, final V value) {
139        if (!map.containsKey(key)) {
140            throw new IllegalArgumentException("Cannot put new key/value pair - Map is fixed size");
141        }
142        return map.put(key, value);
143    }
144
145    @Override
146    public void putAll(final Map<? extends K, ? extends V> mapToCopy) {
147        if (CollectionUtils.isSubCollection(mapToCopy.keySet(), keySet())) {
148            throw new IllegalArgumentException("Cannot put new key/value pair - Map is fixed size");
149        }
150        map.putAll(mapToCopy);
151    }
152
153    /**
154     * Deserializes the map in using a custom routine.
155     *
156     * @param in The input stream
157     * @throws IOException Thrown if an error occurs while reading from the stream
158     * @throws ClassNotFoundException if an object read from the stream cannot be loaded
159     */
160    @SuppressWarnings("unchecked") // (1) should only fail if input stream is incorrect
161    private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
162        in.defaultReadObject();
163        map = (Map<K, V>) in.readObject(); // (1)
164    }
165
166    /**
167     * Always throws {@link UnsupportedOperationException}.
168     *
169     * @param key Ignored.
170     * @throws UnsupportedOperationException Always thrown.
171     */
172    @Override
173    public V remove(final Object key) {
174        throw new UnsupportedOperationException("Map is fixed size");
175    }
176
177    @Override
178    public SortedMap<K, V> subMap(final K fromKey, final K toKey) {
179        return new FixedSizeSortedMap<>(getSortedMap().subMap(fromKey, toKey));
180    }
181
182    @Override
183    public SortedMap<K, V> tailMap(final K fromKey) {
184        return new FixedSizeSortedMap<>(getSortedMap().tailMap(fromKey));
185    }
186
187    @Override
188    public Collection<V> values() {
189        return UnmodifiableCollection.unmodifiableCollection(map.values());
190    }
191
192    /**
193     * Writes the map out using a custom routine.
194     *
195     * @param out  The output stream
196     * @throws IOException Thrown if an error occurs while writing to the stream
197     */
198    private void writeObject(final ObjectOutputStream out) throws IOException {
199        out.defaultWriteObject();
200        out.writeObject(map);
201    }
202
203}