View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      https://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.commons.collections4.splitmap;
18  
19  import java.io.IOException;
20  import java.io.ObjectInputStream;
21  import java.io.ObjectOutputStream;
22  import java.io.Serializable;
23  import java.util.Map;
24  import java.util.Objects;
25  
26  import org.apache.commons.collections4.Get;
27  import org.apache.commons.collections4.Put;
28  import org.apache.commons.collections4.Transformer;
29  import org.apache.commons.collections4.map.LinkedMap;
30  import org.apache.commons.collections4.map.TransformedMap;
31  
32  /**
33   * Decorates another {@link Map} to transform objects that are added.
34   * <p>
35   * The Map put methods and Map.Entry setValue method are affected by this class.
36   * Thus objects must be removed or searched for using their transformed form.
37   * For example, if the transformation converts Strings to Integers, you must use
38   * the Integer form to remove objects.
39   * </p>
40   * <p>
41   * <strong>Note that TransformedMap is not synchronized and is not
42   * thread-safe.</strong> If you wish to use this map from multiple threads
43   * concurrently, you must use appropriate synchronization. The simplest approach
44   * is to wrap this map using {@link java.util.Collections#synchronizedMap(Map)}.
45   * This class may throw exceptions when accessed by concurrent threads without
46   * synchronization.
47   * </p>
48   * <p>
49   * The "put" and "get" type constraints of this class are mutually independent;
50   * contrast with {@link TransformedMap} which,
51   * by virtue of its implementing {@link Map}&lt;K, V&gt;, must be constructed in such
52   * a way that its read and write parameters are generalized to a common (super-)type.
53   * In practice this would often mean {@code &gt;Object, Object&gt;}, defeating
54   * much of the usefulness of having parameterized types.
55   * </p>
56   * <p>
57   * On the downside, this class is not drop-in compatible with {@link Map}
58   * but is intended to be worked with either directly or by {@link Put} and
59   * {@link Get Get} generalizations.
60   * </p>
61   *
62   * @param <J> The type of the keys to put in this map
63   * @param <K> The type of the keys to get in this map
64   * @param <U> The type of the values to put in this map
65   * @param <V> The type of the values to get in this map
66   * @since 4.0
67   * @see org.apache.commons.collections4.SplitMapUtils#readableMap(org.apache.commons.collections4.Get)
68   * @see org.apache.commons.collections4.SplitMapUtils#writableMap(Put)
69   */
70  public class TransformedSplitMap<J, K, U, V> extends AbstractIterableGetMapDecorator<K, V>
71          implements Put<J, U>, Serializable {
72  
73      /** Serialization version */
74      private static final long serialVersionUID = 5966875321133456994L;
75  
76      /**
77       * Factory method to create a transforming map.
78       * <p>
79       * If there are any elements already in the map being decorated, they are
80       * NOT transformed.
81       *
82       * @param <J>  the input key type
83       * @param <K>  the output key type
84       * @param <U>  the input value type
85       * @param <V>  the output value type
86       * @param map The map to decorate, must not be null
87       * @param keyTransformer The transformer to use for key conversion, must not be null
88       * @param valueTransformer The transformer to use for value conversion, must not be null
89       * @return A new transformed map
90       * @throws NullPointerException if map or either of the transformers is null
91       */
92      public static <J, K, U, V> TransformedSplitMap<J, K, U, V> transformingMap(final Map<K, V> map,
93              final Transformer<? super J, ? extends K> keyTransformer,
94              final Transformer<? super U, ? extends V> valueTransformer) {
95          return new TransformedSplitMap<>(map, keyTransformer, valueTransformer);
96      }
97  
98      /** The transformer to use for the key */
99      private final Transformer<? super J, ? extends K> keyTransformer;
100 
101     /** The transformer to use for the value */
102     private final Transformer<? super U, ? extends V> valueTransformer;
103 
104     /**
105      * Constructor that wraps (not copies).
106      * <p>
107      * If there are any elements already in the collection being decorated, they
108      * are NOT transformed.
109      *
110      * @param map The map to decorate, must not be null
111      * @param keyTransformer The transformer to use for key conversion, must not be null
112      * @param valueTransformer The transformer to use for value conversion, must not be null
113      * @throws NullPointerException if map or either of the transformers is null
114      */
115     protected TransformedSplitMap(final Map<K, V> map, final Transformer<? super J, ? extends K> keyTransformer,
116             final Transformer<? super U, ? extends V> valueTransformer) {
117         super(map);
118         this.keyTransformer = Objects.requireNonNull(keyTransformer, "keyTransformer");
119         this.valueTransformer = Objects.requireNonNull(valueTransformer, "valueTransformer");
120     }
121 
122     /**
123      * Override to transform the value when using {@code setValue}.
124      *
125      * @param value The value to transform
126      * @return The transformed value
127      */
128     protected V checkSetValue(final U value) {
129         return valueTransformer.apply(value);
130     }
131 
132     @Override
133     public void clear() {
134         decorated().clear();
135     }
136 
137     @Override
138     public V put(final J key, final U value) {
139         return decorated().put(transformKey(key), transformValue(value));
140     }
141 
142     @Override
143     public void putAll(final Map<? extends J, ? extends U> mapToCopy) {
144         decorated().putAll(transformMap(mapToCopy));
145     }
146 
147     /**
148      * Deserializes the map in using a custom routine.
149      *
150      * @param in The input stream
151      * @throws IOException Thrown if an error occurs while reading from the stream
152      * @throws ClassNotFoundException if an object read from the stream cannot be loaded
153      * @since 3.1
154      */
155     @SuppressWarnings("unchecked") // (1) should only fail if input stream is incorrect
156     private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
157         in.defaultReadObject();
158         map = (Map<K, V>) in.readObject(); // (1)
159     }
160 
161     /**
162      * Transforms a key.
163      * <p>
164      * The transformer itself may throw an exception if necessary.
165      *
166      * @param object The object to transform
167      * @return The transformed object
168      */
169     protected K transformKey(final J object) {
170         return keyTransformer.apply(object);
171     }
172 
173     /**
174      * Transforms a map.
175      * <p>
176      * The transformer itself may throw an exception if necessary.
177      *
178      * @param map The map to transform
179      * @return The transformed object
180      */
181     @SuppressWarnings("unchecked")
182     protected Map<K, V> transformMap(final Map<? extends J, ? extends U> map) {
183         if (map.isEmpty()) {
184             return (Map<K, V>) map;
185         }
186         final Map<K, V> result = new LinkedMap<>(map.size());
187 
188         for (final Map.Entry<? extends J, ? extends U> entry : map.entrySet()) {
189             result.put(transformKey(entry.getKey()), transformValue(entry.getValue()));
190         }
191         return result;
192     }
193 
194     /**
195      * Transforms a value.
196      * <p>
197      * The transformer itself may throw an exception if necessary.
198      *
199      * @param object The object to transform
200      * @return The transformed object
201      */
202     protected V transformValue(final U object) {
203         return valueTransformer.apply(object);
204     }
205 
206     /**
207      * Serializes this object to an ObjectOutputStream.
208      *
209      * @param out The target ObjectOutputStream.
210      * @throws IOException thrown when an I/O errors occur writing to the target stream.
211      */
212     private void writeObject(final ObjectOutputStream out) throws IOException {
213         out.defaultWriteObject();
214         out.writeObject(decorated());
215     }
216 }