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.HashMap;
024import java.util.Map;
025
026import org.apache.commons.collections4.Factory;
027import org.apache.commons.collections4.Transformer;
028import org.apache.commons.collections4.functors.ConstantTransformer;
029import org.apache.commons.collections4.functors.FactoryTransformer;
030
031/**
032 * Decorates another <code>Map</code> returning a default value if the map
033 * does not contain the requested key.
034 * <p>
035 * When the {@link #get(Object)} method is called with a key that does not
036 * exist in the map, this map will return the default value specified in
037 * the constructor/factory. Only the get method is altered, so the
038 * {@link Map#containsKey(Object)} can be used to determine if a key really
039 * is in the map or not.
040 * <p>
041 * The defaulted value is not added to the map.
042 * Compare this behaviour with {@link LazyMap}, which does add the value
043 * to the map (via a Transformer).
044 * <p>
045 * For instance:
046 * <pre>
047 * Map map = new DefaultedMap("NULL");
048 * Object obj = map.get("Surname");
049 * // obj == "NULL"
050 * </pre>
051 * After the above code is executed the map is still empty.
052 * <p>
053 * <strong>Note that DefaultedMap is not synchronized and is not thread-safe.</strong>
054 * If you wish to use this map from multiple threads concurrently, you must use
055 * appropriate synchronization. The simplest approach is to wrap this map
056 * using {@link java.util.Collections#synchronizedMap(Map)}. This class may throw
057 * exceptions when accessed by concurrent threads without synchronization.
058 *
059 * @param <K> the type of the keys in this map
060 * @param <V> the type of the values in this map
061 *
062 * @since 3.2
063 * @see LazyMap
064 */
065public class DefaultedMap<K, V> extends AbstractMapDecorator<K, V> implements Serializable {
066
067    /** Serialization version */
068    private static final long serialVersionUID = 19698628745827L;
069
070    /** The transformer to use if the map does not contain a key */
071    private final Transformer<? super K, ? extends V> value;
072
073    //-----------------------------------------------------------------------
074    /**
075     * Factory method to create a defaulting map.
076     * <p>
077     * The value specified is returned when a missing key is found.
078     *
079     * @param <K>  the key type
080     * @param <V>  the value type
081     * @param map  the map to decorate, must not be null
082     * @param defaultValue  the default value to return when the key is not found
083     * @return a new defaulting map
084     * @throws NullPointerException if map is null
085     * @since 4.0
086     */
087    public static <K, V> DefaultedMap<K, V> defaultedMap(final Map<K, V> map, final V defaultValue) {
088        return new DefaultedMap<>(map, ConstantTransformer.constantTransformer(defaultValue));
089    }
090
091    /**
092     * Factory method to create a defaulting map.
093     * <p>
094     * The factory specified is called when a missing key is found.
095     * The result will be returned as the result of the map get(key) method.
096     *
097     * @param <K>  the key type
098     * @param <V>  the value type
099     * @param map  the map to decorate, must not be null
100     * @param factory  the factory to use to create entries, must not be null
101     * @return a new defaulting map
102     * @throws NullPointerException if map or factory is null
103     * @since 4.0
104     */
105    public static <K, V> DefaultedMap<K, V> defaultedMap(final Map<K, V> map, final Factory<? extends V> factory) {
106        if (factory == null) {
107            throw new IllegalArgumentException("Factory must not be null");
108        }
109        return new DefaultedMap<>(map, FactoryTransformer.factoryTransformer(factory));
110    }
111
112    /**
113     * Factory method to create a defaulting map.
114     * <p>
115     * The transformer specified is called when a missing key is found.
116     * The key is passed to the transformer as the input, and the result
117     * will be returned as the result of the map get(key) method.
118     *
119     * @param <K>  the key type
120     * @param <V>  the value type
121     * @param map  the map to decorate, must not be null
122     * @param transformer  the transformer to use as a factory to create entries, must not be null
123     * @return a new defaulting map
124     * @throws NullPointerException if map or factory is null
125     * @since 4.0
126     */
127    public static <K, V> Map<K, V> defaultedMap(final Map<K, V> map,
128                                                final Transformer<? super K, ? extends V> transformer) {
129        if (transformer == null) {
130           throw new IllegalArgumentException("Transformer must not be null");
131       }
132       return new DefaultedMap<>(map, transformer);
133    }
134
135    //-----------------------------------------------------------------------
136    /**
137     * Constructs a new empty <code>DefaultedMap</code> that decorates
138     * a <code>HashMap</code>.
139     * <p>
140     * The object passed in will be returned by the map whenever an
141     * unknown key is requested.
142     *
143     * @param defaultValue  the default value to return when the key is not found
144     */
145    public DefaultedMap(final V defaultValue) {
146        this(ConstantTransformer.constantTransformer(defaultValue));
147    }
148
149    /**
150     * Constructs a new empty <code>DefaultedMap</code> that decorates a <code>HashMap</code>.
151     *
152     * @param defaultValueTransformer transformer to use to generate missing values.
153     */
154    public DefaultedMap(final Transformer<? super K, ? extends V> defaultValueTransformer) {
155        this(new HashMap<K, V>(), defaultValueTransformer);
156    }
157
158    /**
159     * Constructor that wraps (not copies).
160     *
161     * @param map  the map to decorate, must not be null
162     * @param defaultValueTransformer  the value transformer to use
163     * @throws NullPointerException if map or transformer is null
164     */
165    protected DefaultedMap(final Map<K, V> map, final Transformer<? super K, ? extends V> defaultValueTransformer) {
166        super(map);
167        if (defaultValueTransformer == null) {
168            throw new NullPointerException("Transformer must not be null.");
169        }
170        this.value = defaultValueTransformer;
171    }
172
173    //-----------------------------------------------------------------------
174    /**
175     * Write the map out using a custom routine.
176     *
177     * @param out  the output stream
178     * @throws IOException if an error occurs while writing to the stream
179     */
180    private void writeObject(final ObjectOutputStream out) throws IOException {
181        out.defaultWriteObject();
182        out.writeObject(map);
183    }
184
185    /**
186     * Read the map in using a custom routine.
187     *
188     * @param in  the input stream
189     * @throws IOException if an error occurs while reading from the stream
190     * @throws ClassNotFoundException if an object read from the stream can not be loaded
191     */
192    @SuppressWarnings("unchecked")
193    private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
194        in.defaultReadObject();
195        map = (Map<K, V>) in.readObject();
196    }
197
198    //-----------------------------------------------------------------------
199    @Override
200    @SuppressWarnings("unchecked")
201    public V get(final Object key) {
202        V v;
203        return (((v = map.get(key)) != null) || map.containsKey(key))
204          ? v
205          : value.transform((K) key);
206    }
207
208    // no need to wrap keySet, entrySet or values as they are views of
209    // existing map entries - you can't do a map-style get on them.
210}