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 * http://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
18 package org.apache.commons.exec.util;
19
20 import java.util.HashMap;
21 import java.util.Map;
22 import java.util.Objects;
23
24 /**
25 * Helper classes to manipulate maps to pass substition map to the CommandLine. This class is not part of the public API and could change without warning.
26 */
27 public class MapUtils {
28 /**
29 * Clones a map.
30 *
31 * @param source the Map to clone.
32 * @param <K> the map key type.
33 * @param <V> the map value type.
34 * @return the cloned map.
35 */
36 public static <K, V> Map<K, V> copy(final Map<K, V> source) {
37 return source == null ? null : new HashMap<>(source);
38 }
39
40 /**
41 * Clones the lhs map and add all things from the rhs map.
42 *
43 * @param lhs the first map.
44 * @param rhs the second map.
45 * @param <K> the map key type.
46 * @param <V> the map value type.
47 * @return the merged map.
48 */
49 public static <K, V> Map<K, V> merge(final Map<K, V> lhs, final Map<K, V> rhs) {
50 Map<K, V> result = null;
51 if (lhs == null || lhs.isEmpty()) {
52 result = copy(rhs);
53 } else if (rhs == null || rhs.isEmpty()) {
54 result = copy(lhs);
55 } else {
56 result = copy(lhs);
57 result.putAll(rhs);
58 }
59 return result;
60 }
61
62 /**
63 * Clones a map and prefixes the keys in the clone, e.g. for mapping "JAVA_HOME" to "env.JAVA_HOME" to simulate the behavior of Ant.
64 *
65 * @param source the source map.
66 * @param prefix the prefix used for all names.
67 * @param <K> the map key type.
68 * @param <V> the map value type.
69 * @return the clone of the source map.
70 */
71 public static <K, V> Map<String, V> prefix(final Map<K, V> source, final String prefix) {
72 if (source == null) {
73 return null;
74 }
75 final Map<String, V> result = new HashMap<>();
76 for (final Map.Entry<K, V> entry : source.entrySet()) {
77 result.put(prefix + '.' + Objects.toString(entry.getKey(), ""), entry.getValue());
78 }
79 return result;
80 }
81 }