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