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 *
017 */
018
019 package org.apache.commons.exec.util;
020
021 import java.util.Map;
022 import java.util.HashMap;
023 import java.util.Iterator;
024
025 /**
026 * Helper classes to manipulate maps to pass substition map to the
027 * CommandLine. This class is not part of the public API and
028 * could change without warning.
029 *
030 * @author <a href="mailto:siegfried.goeschl@it20one.at">Siegfried Goeschl</a>
031 */
032 public class MapUtils
033 {
034 /**
035 * Clones a map.
036 *
037 * @param source the source map
038 * @return the clone of the source map
039 */
040 public static Map copy(Map source) {
041
042 if(source == null) {
043 return null;
044 }
045
046 Map result = new HashMap();
047 result.putAll(source);
048 return result;
049 }
050
051 /**
052 * Clones a map and prefixes the keys in the clone, e.g.
053 * for mapping "JAVA_HOME" to "env.JAVA_HOME" to simulate
054 * the behaviour of ANT.
055 *
056 * @param source the source map
057 * @param prefix the prefix used for all names
058 * @return the clone of the source map
059 */
060 public static Map prefix(Map source, String prefix) {
061
062 if(source == null) {
063 return null;
064 }
065
066 Map result = new HashMap();
067
068 Iterator iter = source.entrySet().iterator();
069
070 while(iter.hasNext()) {
071 Map.Entry entry = (Map.Entry) iter.next();
072 Object key = entry.getKey();
073 Object value = entry.getValue();
074 result.put(prefix + '.' + key.toString(), value);
075 }
076
077 return result;
078 }
079
080 /**
081 * Clones the lhs map and add all things from the
082 * rhs map.
083 *
084 * @param lhs the first map
085 * @param rhs the second map
086 * @return the merged map
087 */
088 public static Map merge(Map lhs, Map rhs) {
089
090 Map result = null;
091
092 if((lhs == null) || (lhs.size() == 0)) {
093 result = copy(rhs);
094 }
095 else if((rhs == null) || (rhs.size() == 0)) {
096 result = copy(lhs);
097 }
098 else {
099 result = copy(lhs);
100 result.putAll(rhs);
101 }
102
103 return result;
104 }
105 }