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.camel.util;
018
019import java.lang.reflect.Array;
020import java.util.ArrayList;
021import java.util.Arrays;
022import java.util.Collection;
023import java.util.Collections;
024import java.util.HashMap;
025import java.util.HashSet;
026import java.util.Iterator;
027import java.util.LinkedHashMap;
028import java.util.List;
029import java.util.Map;
030import java.util.Properties;
031import java.util.Set;
032import java.util.function.Supplier;
033
034import org.w3c.dom.NodeList;
035
036/**
037 * A number of helper methods for working with collections
038 */
039public final class CollectionHelper {
040
041    /**
042     * Utility classes should not have a public constructor.
043     */
044    private CollectionHelper() {
045    }
046
047    /**
048     * Returns the size of the collection if it can be determined to be a collection
049     *
050     * @param  value the collection
051     * @return       the size, or <tt>null</tt> if not a collection
052     */
053    public static Integer size(Object value) {
054        if (value != null) {
055            if (value instanceof Collection) {
056                Collection<?> collection = (Collection<?>) value;
057                return collection.size();
058            } else if (value instanceof Map) {
059                Map<?, ?> map = (Map<?, ?>) value;
060                return map.size();
061            } else if (value instanceof Object[]) {
062                Object[] array = (Object[]) value;
063                return array.length;
064            } else if (value.getClass().isArray()) {
065                return Array.getLength(value);
066            } else if (value instanceof NodeList) {
067                NodeList nodeList = (NodeList) value;
068                return nodeList.getLength();
069            }
070        }
071        return null;
072    }
073
074    /**
075     * Sets the value of the entry in the map for the given key, though if the map already contains a value for the
076     * given key then the value is appended to a list of values.
077     *
078     * @param map   the map to add the entry to
079     * @param key   the key in the map
080     * @param value the value to put in the map
081     */
082    @SuppressWarnings("unchecked")
083    public static void appendValue(Map<String, Object> map, String key, Object value) {
084        Object oldValue = map.get(key);
085        if (oldValue != null) {
086            List<Object> list;
087            if (oldValue instanceof List) {
088                list = (List<Object>) oldValue;
089            } else {
090                list = new ArrayList<>();
091                list.add(oldValue);
092                // replace old entry with list
093                map.remove(key);
094                map.put(key, list);
095            }
096            list.add(value);
097        } else {
098            map.put(key, value);
099        }
100    }
101
102    public static <T> Set<T> createSetContaining(T... contents) {
103        return new HashSet<>(Arrays.asList(contents));
104    }
105
106    public static String collectionAsCommaDelimitedString(Collection<?> col) {
107        if (col == null || col.isEmpty()) {
108            return "";
109        }
110
111        StringBuilder sb = new StringBuilder();
112        Iterator<?> it = col.iterator();
113        while (it.hasNext()) {
114            sb.append(it.next().toString());
115            if (it.hasNext()) {
116                sb.append(",");
117            }
118        }
119
120        return sb.toString();
121    }
122
123    /**
124     * Traverses the given map recursively and flattern the keys by combining them with the optional separator.
125     *
126     * @param  map       the map
127     * @param  separator optional separator to use in key name, for example a hyphen or dot.
128     * @return           the map with flattern keys
129     */
130    public static Map<String, Object> flattenKeysInMap(Map<String, Object> map, String separator) {
131        Map<String, Object> answer = new LinkedHashMap<>();
132        doFlattenKeysInMap(map, "", ObjectHelper.isNotEmpty(separator) ? separator : "", answer);
133        return answer;
134    }
135
136    private static void doFlattenKeysInMap(
137            Map<String, Object> source, String prefix, String separator, Map<String, Object> target) {
138        for (Map.Entry<String, Object> entry : source.entrySet()) {
139            String key = entry.getKey();
140            Object value = entry.getValue();
141            String newKey = prefix.isEmpty() ? key : prefix + separator + key;
142
143            if (value instanceof Map) {
144                Map map = (Map) value;
145                doFlattenKeysInMap(map, newKey, separator, target);
146            } else {
147                target.put(newKey, value);
148            }
149        }
150    }
151
152    /**
153     * Build an unmodifiable map on top of a given map. Note tha thew given map is copied if not null.
154     *
155     * @param  map a map
156     * @return     an unmodifiable map.
157     */
158    public static <K, V> Map<K, V> unmodifiableMap(Map<K, V> map) {
159        return map == null
160                ? Collections.emptyMap()
161                : Collections.unmodifiableMap(new HashMap<>(map));
162    }
163
164    /**
165     * Build a map from varargs.
166     */
167    @SuppressWarnings("unchecked")
168    public static <K, V> Map<K, V> mapOf(Supplier<Map<K, V>> creator, K key, V value, Object... keyVals) {
169        Map<K, V> map = creator.get();
170        map.put(key, value);
171
172        for (int i = 0; i < keyVals.length; i += 2) {
173            map.put(
174                    (K) keyVals[i],
175                    (V) keyVals[i + 1]);
176        }
177
178        return map;
179    }
180
181    /**
182     * Build an immutable map from varargs.
183     */
184    public static <K, V> Map<K, V> immutableMapOf(Supplier<Map<K, V>> creator, K key, V value, Object... keyVals) {
185        return Collections.unmodifiableMap(
186                mapOf(creator, key, value, keyVals));
187    }
188
189    /**
190     * Build a map from varargs.
191     */
192    public static <K, V> Map<K, V> mapOf(K key, V value, Object... keyVals) {
193        return mapOf(HashMap::new, key, value, keyVals);
194    }
195
196    /**
197     * Build an immutable map from varargs.
198     */
199    public static <K, V> Map<K, V> immutableMapOf(K key, V value, Object... keyVals) {
200        return Collections.unmodifiableMap(
201                mapOf(HashMap::new, key, value, keyVals));
202    }
203
204    /**
205     * Build a {@link java.util.Properties} from varargs.
206     */
207    public static Properties propertiesOf(String key, String value, String... keyVals) {
208        Properties properties = new Properties();
209        properties.setProperty(key, value);
210
211        for (int i = 0; i < keyVals.length; i += 2) {
212            properties.setProperty(
213                    keyVals[i],
214                    keyVals[i + 1]);
215        }
216
217        return properties;
218    }
219
220    /**
221     * Build a new map that is the result of merging the given list of maps.
222     */
223    @SafeVarargs
224    public static <K, V> Map<K, V> mergeMaps(Map<K, V> map, Map<K, V>... maps) {
225        Map<K, V> answer = new HashMap<>();
226
227        if (map != null) {
228            answer.putAll(map);
229        }
230
231        for (Map<K, V> m : maps) {
232            answer.putAll(m);
233        }
234
235        return answer;
236    }
237}