    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 *      http://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</code> 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 * If trying to remove or clear the map, an UnsupportedOperationException is
    041 * thrown. If trying to put a new mapping into the map, an
    042 * IllegalArgumentException is thrown. This is because the put method can
    043 * succeed if the mapping's key already exists in the map, so the put method
    044 * is not always unsupported.
    045 * <p>
    046 * <strong>Note that FixedSizeSortedMap 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#synchronizedSortedMap}. This class may throw
    050 * exceptions when accessed by concurrent threads without synchronization.
    051 * <p>
    052 * This class is Serializable from Commons Collections 3.1.
    053 *
    054 * @param <K> the type of the keys in this map
    055 * @param <V> the type of the values in this map
    056 * @since 3.0
    057 */
    058public class FixedSizeSortedMap<K, V>
    059        extends AbstractSortedMapDecorator<K, V>
    060        implements BoundedMap<K, V>, Serializable {
    061
    062    /** Serialization version */
    063    private static final long serialVersionUID = 3126019624511683653L;
    064
    065    /**
    066     * Factory method to create a fixed size sorted map.
    067     *
    068     * @param <K>  the key type
    069     * @param <V>  the value type
    070     * @param map  the map to decorate, must not be null
    071     * @return a new fixed size sorted map
    072     * @throws NullPointerException if map is null
    073     * @since 4.0
    074     */
    075    public static <K, V> FixedSizeSortedMap<K, V> fixedSizeSortedMap(final SortedMap<K, V> map) {
    076        return new FixedSizeSortedMap<>(map);
    077    }
    078
    079    //-----------------------------------------------------------------------
    080    /**
    081     * Constructor that wraps (not copies).
    082     *
    083     * @param map  the map to decorate, must not be null
    084     * @throws NullPointerException if map is null
    085     */
    086    protected FixedSizeSortedMap(final SortedMap<K, V> map) {
    087        super(map);
    088    }
    089
    090    /**
    091     * Gets the map being decorated.
    092     *
    093     * @return the decorated map
    094     */
    095    protected SortedMap<K, V> getSortedMap() {
    096        return (SortedMap<K, V>) map;
    097    }
    098
    099    //-----------------------------------------------------------------------
    100    /**
    101     * Write the map out using a custom routine.
    102     *
    103     * @param out  the output stream
    104     * @throws IOException if an error occurs while writing to the stream
    105     */
    106    private void writeObject(final ObjectOutputStream out) throws IOException {
    107        out.defaultWriteObject();
    108        out.writeObject(map);
    109    }
    110
    111    /**
    112     * Read the map in using a custom routine.
    113     *
    114     * @param in the input stream
    115     * @throws IOException if an error occurs while reading from the stream
    116     * @throws ClassNotFoundException if an object read from the stream can not be loaded
    117     */
    118    @SuppressWarnings("unchecked") // (1) should only fail if input stream is incorrect
    119    private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
    120        in.defaultReadObject();
    121        map = (Map<K, V>) in.readObject(); // (1)
    122    }
    123
    124    //-----------------------------------------------------------------------
    125    @Override
    126    public V put(final K key, final V value) {
    127        if (map.containsKey(key) == false) {
    128            throw new IllegalArgumentException("Cannot put new key/value pair - Map is fixed size");
    129        }
    130        return map.put(key, value);
    131    }
    132
    133    @Override
    134    public void putAll(final Map<? extends K, ? extends V> mapToCopy) {
    135        if (CollectionUtils.isSubCollection(mapToCopy.keySet(), keySet())) {
    136            throw new IllegalArgumentException("Cannot put new key/value pair - Map is fixed size");
    137        }
    138        map.putAll(mapToCopy);
    139    }
    140
    141    @Override
    142    public void clear() {
    143        throw new UnsupportedOperationException("Map is fixed size");
    144    }
    145
    146    @Override
    147    public V remove(final Object key) {
    148        throw new UnsupportedOperationException("Map is fixed size");
    149    }
    150
    151    @Override
    152    public Set<Map.Entry<K, V>> entrySet() {
    153        return UnmodifiableSet.unmodifiableSet(map.entrySet());
    154    }
    155
    156    @Override
    157    public Set<K> keySet() {
    158        return UnmodifiableSet.unmodifiableSet(map.keySet());
    159    }
    160
    161    @Override
    162    public Collection<V> values() {
    163        return UnmodifiableCollection.unmodifiableCollection(map.values());
    164    }
    165
    166    //-----------------------------------------------------------------------
    167    @Override
    168    public SortedMap<K, V> subMap(final K fromKey, final K toKey) {
    169        return new FixedSizeSortedMap<>(getSortedMap().subMap(fromKey, toKey));
    170    }
    171
    172    @Override
    173    public SortedMap<K, V> headMap(final K toKey) {
    174        return new FixedSizeSortedMap<>(getSortedMap().headMap(toKey));
    175    }
    176
    177    @Override
    178    public SortedMap<K, V> tailMap(final K fromKey) {
    179        return new FixedSizeSortedMap<>(getSortedMap().tailMap(fromKey));
    180    }
    181
    182    @Override
    183    public boolean isFull() {
    184        return true;
    185    }
    186
    187    @Override
    188    public int maxSize() {
    189        return size();
    190    }
    191
    192}