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;
026
027import org.apache.commons.collections4.BoundedMap;
028import org.apache.commons.collections4.collection.UnmodifiableCollection;
029import org.apache.commons.collections4.set.UnmodifiableSet;
030
031/**
032 * Decorates another {@code Map} to fix the size, preventing add/remove.
033 * <p>
034 * Any action that would change the size of the map is disallowed.
035 * The put method is allowed to change the value associated with an existing
036 * key however.
037 * </p>
038 * <p>
039 * If trying to remove or clear the map, an UnsupportedOperationException is
040 * thrown. If trying to put a new mapping into the map, an
041 * IllegalArgumentException is thrown. This is because the put method can
042 * succeed if the mapping's key already exists in the map, so the put method
043 * is not always unsupported.
044 * </p>
045 * <p>
046 * <strong>Note that FixedSizeMap is not synchronized and is not thread-safe.</strong>
047 * If you wish to use this map from multiple threads concurrently, you must use
048 * appropriate synchronization. The simplest approach is to wrap this map
049 * using {@link java.util.Collections#synchronizedMap(Map)}. This class may throw
050 * exceptions when accessed by concurrent threads without synchronization.
051 * </p>
052 * <p>
053 * This class is Serializable from Commons Collections 3.1.
054 * </p>
055 *
056 * @param <K> The type of the keys in this map
057 * @param <V> The type of the values in this map
058 * @since 3.0
059 */
060public class FixedSizeMap<K, V>
061        extends AbstractMapDecorator<K, V>
062        implements BoundedMap<K, V>, Serializable {
063
064    /** Serialization version */
065    private static final long serialVersionUID = 7450927208116179316L;
066
067    /**
068     * Factory method to create a fixed size map.
069     *
070     * @param <K>  the key type
071     * @param <V>  the value type
072     * @param map  The map to decorate, must not be null
073     * @return A new fixed size map
074     * @throws NullPointerException if map is null
075     * @since 4.0
076     */
077    public static <K, V> FixedSizeMap<K, V> fixedSizeMap(final Map<K, V> map) {
078        return new FixedSizeMap<>(map);
079    }
080
081    /**
082     * Constructor that wraps (not copies).
083     *
084     * @param map  The map to decorate, must not be null
085     * @throws NullPointerException if map is null
086     */
087    protected FixedSizeMap(final Map<K, V> map) {
088        super(map);
089    }
090
091    /**
092     * Always throws {@link UnsupportedOperationException}.
093     *
094     * @throws UnsupportedOperationException Always thrown.
095     */
096    @Override
097    public void clear() {
098        throw new UnsupportedOperationException("Map is fixed size");
099    }
100
101    @Override
102    public Set<Map.Entry<K, V>> entrySet() {
103        final Set<Map.Entry<K, V>> set = map.entrySet();
104        // unmodifiable set will still allow modification via Map.Entry objects
105        return UnmodifiableSet.unmodifiableSet(set);
106    }
107
108    @Override
109    public boolean isFull() {
110        return true;
111    }
112
113    @Override
114    public Set<K> keySet() {
115        final Set<K> set = map.keySet();
116        return UnmodifiableSet.unmodifiableSet(set);
117    }
118
119    @Override
120    public int maxSize() {
121        return size();
122    }
123
124    @Override
125    public V put(final K key, final V value) {
126        if (!map.containsKey(key)) {
127            throw new IllegalArgumentException("Cannot put new key/value pair - Map is fixed size");
128        }
129        return map.put(key, value);
130    }
131
132    @Override
133    public void putAll(final Map<? extends K, ? extends V> mapToCopy) {
134        for (final K key : mapToCopy.keySet()) {
135            if (!containsKey(key)) {
136                throw new IllegalArgumentException("Cannot put new key/value pair - Map is fixed size");
137            }
138        }
139        map.putAll(mapToCopy);
140    }
141
142    /**
143     * Deserializes the map in using a custom routine.
144     *
145     * @param in  The input stream
146     * @throws IOException Thrown if an error occurs while reading from the stream
147     * @throws ClassNotFoundException if an object read from the stream cannot be loaded
148     * @since 3.1
149     */
150    @SuppressWarnings("unchecked") // (1) should only fail if input stream is incorrect
151    private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
152        in.defaultReadObject();
153        map = (Map<K, V>) in.readObject(); // (1)
154    }
155
156    /**
157     * Always throws {@link UnsupportedOperationException}.
158     *
159     * @param key Ignored.
160     * @throws UnsupportedOperationException Always thrown.
161     */
162    @Override
163    public V remove(final Object key) {
164        throw new UnsupportedOperationException("Map is fixed size");
165    }
166
167    @Override
168    public Collection<V> values() {
169        return UnmodifiableCollection.unmodifiableCollection(map.values());
170    }
171
172    /**
173     * Serializes this object to an ObjectOutputStream.
174     *
175     * @param out The target ObjectOutputStream.
176     * @throws IOException thrown when an I/O errors occur writing to the target stream.
177     * @since 3.1
178     */
179    private void writeObject(final ObjectOutputStream out) throws IOException {
180        out.defaultWriteObject();
181        out.writeObject(map);
182    }
183
184}