1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * https://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20 package org.apache.commons.exec.util;
21
22 import java.util.HashMap;
23 import java.util.Map;
24 import java.util.Objects;
25
26 /**
27 * Helper classes to manipulate maps to pass substitution map to the CommandLine. This class is not part of the public API and could change without warning.
28 */
29 public class MapUtils {
30 /**
31 * Clones a map.
32 *
33 * @param source the Map to clone.
34 * @param <K> the map key type.
35 * @param <V> the map value type.
36 * @return the cloned map.
37 */
38 public static <K, V> Map<K, V> copy(final Map<K, V> source) {
39 return source == null ? null : new HashMap<>(source);
40 }
41
42 /**
43 * Clones the lhs map and add all things from the rhs map.
44 *
45 * @param lhs the first map.
46 * @param rhs the second map.
47 * @param <K> the map key type.
48 * @param <V> the map value type.
49 * @return the merged map.
50 */
51 public static <K, V> Map<K, V> merge(final Map<K, V> lhs, final Map<K, V> rhs) {
52 Map<K, V> result = null;
53 if (lhs == null || lhs.isEmpty()) {
54 result = copy(rhs);
55 } else if (rhs == null || rhs.isEmpty()) {
56 result = copy(lhs);
57 } else {
58 result = copy(lhs);
59 result.putAll(rhs);
60 }
61 return result;
62 }
63
64 /**
65 * 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.
66 *
67 * @param source the source map.
68 * @param prefix the prefix used for all names.
69 * @param <K> the map key type.
70 * @param <V> the map value type.
71 * @return the clone of the source map.
72 */
73 public static <K, V> Map<String, V> prefix(final Map<K, V> source, final String prefix) {
74 if (source == null) {
75 return null;
76 }
77 final Map<String, V> result = new HashMap<>();
78 for (final Map.Entry<K, V> entry : source.entrySet()) {
79 result.put(prefix + '.' + Objects.toString(entry.getKey(), ""), entry.getValue());
80 }
81 return result;
82 }
83
84 /**
85 * Constructs a new instance.
86 *
87 * @deprecated Will be private in the next major version.
88 */
89 @Deprecated
90 public MapUtils() {
91 // empty
92 }
93 }