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 * @since 3.2
060 * @version $Id: DefaultedMap.html 972421 2015-11-14 20:00:04Z tn $
061 *
062 * @see LazyMap
063 */
064public class DefaultedMap<K, V> extends AbstractMapDecorator<K, V> implements Serializable {
065
066    /** Serialization version */
067    private static final long serialVersionUID = 19698628745827L;
068
069    /** The transformer to use if the map does not contain a key */
070    private final Transformer<? super K, ? extends V> value;
071
072    //-----------------------------------------------------------------------
073    /**
074     * Factory method to create a defaulting map.
075     * <p>
076     * The value specified is returned when a missing key is found.
077     *
078     * @param <K>  the key type
079     * @param <V>  the value type
080     * @param map  the map to decorate, must not be null
081     * @param defaultValue  the default value to return when the key is not found
082     * @return a new defaulting map
083     * @throws IllegalArgumentException if map is null
084     * @since 4.0
085     */
086    public static <K, V> DefaultedMap<K, V> defaultedMap(final Map<K, V> map, final V defaultValue) {
087        return new DefaultedMap<K, V>(map, ConstantTransformer.constantTransformer(defaultValue));
088    }
089
090    /**
091     * Factory method to create a defaulting map.
092     * <p>
093     * The factory specified is called when a missing key is found.
094     * The result will be returned as the result of the map get(key) method.
095     *
096     * @param <K>  the key type
097     * @param <V>  the value type
098     * @param map  the map to decorate, must not be null
099     * @param factory  the factory to use to create entries, must not be null
100     * @return a new defaulting map
101     * @throws IllegalArgumentException if map or factory is null
102     * @since 4.0
103     */
104    public static <K, V> DefaultedMap<K, V> defaultedMap(final Map<K, V> map, final Factory<? extends V> factory) {
105        if (factory == null) {
106            throw new IllegalArgumentException("Factory must not be null");
107        }
108        return new DefaultedMap<K, V>(map, FactoryTransformer.factoryTransformer(factory));
109    }
110
111    /**
112     * Factory method to create a defaulting map.
113     * <p>
114     * The transformer specified is called when a missing key is found.
115     * The key is passed to the transformer as the input, and the result
116     * will be returned as the result of the map get(key) method.
117     *
118     * @param <K>  the key type
119     * @param <V>  the value type
120     * @param map  the map to decorate, must not be null
121     * @param transformer  the transformer to use as a factory to create entries, must not be null
122     * @return a new defaulting map
123     * @throws IllegalArgumentException if map or factory is null
124     * @since 4.0
125     */
126    public static <K, V> Map<K, V> defaultedMap(final Map<K, V> map,
127                                                final Transformer<? super K, ? extends V> transformer) {
128        if (transformer == null) {
129           throw new IllegalArgumentException("Transformer must not be null");
130       }
131       return new DefaultedMap<K, V>(map, transformer);
132    }
133
134    //-----------------------------------------------------------------------
135    /**
136     * Constructs a new empty <code>DefaultedMap</code> that decorates
137     * a <code>HashMap</code>.
138     * <p>
139     * The object passed in will be returned by the map whenever an
140     * unknown key is requested.
141     *
142     * @param defaultValue  the default value to return when the key is not found
143     */
144    public DefaultedMap(final V defaultValue) {
145        this(ConstantTransformer.constantTransformer(defaultValue));
146    }
147
148    /**
149     * Constructs a new empty <code>DefaultedMap</code> that decorates a <code>HashMap</code>.
150     *
151     * @param defaultValueTransformer transformer to use to generate missing values.
152     */
153    public DefaultedMap(final Transformer<? super K, ? extends V> defaultValueTransformer) {
154        this(new HashMap<K, V>(), defaultValueTransformer);
155    }
156
157    /**
158     * Constructor that wraps (not copies).
159     *
160     * @param map  the map to decorate, must not be null
161     * @param defaultValueTransformer  the value transformer to use
162     * @throws IllegalArgumentException if map or transformer is null
163     */
164    protected DefaultedMap(final Map<K, V> map, final Transformer<? super K, ? extends V> defaultValueTransformer) {
165        super(map);
166        if (defaultValueTransformer == null) {
167            throw new IllegalArgumentException("transformer must not be null");
168        }
169        this.value = defaultValueTransformer;
170    }
171
172    //-----------------------------------------------------------------------
173    /**
174     * Write the map out using a custom routine.
175     *
176     * @param out  the output stream
177     * @throws IOException
178     */
179    private void writeObject(final ObjectOutputStream out) throws IOException {
180        out.defaultWriteObject();
181        out.writeObject(map);
182    }
183
184    /**
185     * Read the map in using a custom routine.
186     *
187     * @param in  the input stream
188     * @throws IOException
189     * @throws ClassNotFoundException
190     */
191    @SuppressWarnings("unchecked")
192    private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
193        in.defaultReadObject();
194        map = (Map<K, V>) in.readObject();
195    }
196
197    //-----------------------------------------------------------------------
198    @Override
199    @SuppressWarnings("unchecked")
200    public V get(final Object key) {
201        // create value for key if key is not currently in the map
202        if (map.containsKey(key) == false) {
203            return value.transform((K) key);
204        }
205        return map.get(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}