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.commons.validator.util;
018
019import java.lang.reflect.InvocationTargetException;
020import java.util.Collection;
021import java.util.HashMap;
022import java.util.Iterator;
023import java.util.Map;
024import java.util.Map.Entry;
025
026import org.apache.commons.beanutils.PropertyUtils;
027import org.apache.commons.collections.FastHashMap; // DEPRECATED
028import org.apache.commons.logging.Log;
029import org.apache.commons.logging.LogFactory;
030import org.apache.commons.validator.Arg;
031import org.apache.commons.validator.Msg;
032import org.apache.commons.validator.Var;
033
034/**
035 * Basic utility methods.
036 * <p>
037 * The use of FastHashMap is deprecated and will be replaced in a future
038 * release.
039 * </p>
040 *
041 * @version $Revision: 1713452 $
042 */
043public class ValidatorUtils {
044
045    private static final Log LOG = LogFactory.getLog(ValidatorUtils.class);
046
047    /**
048     * <p>Replace part of a <code>String</code> with another value.</p>
049     *
050     * @param value <code>String</code> to perform the replacement on.
051     * @param key The name of the constant.
052     * @param replaceValue The value of the constant.
053     *
054     * @return The modified value.
055     */
056    public static String replace(String value, String key, String replaceValue) {
057
058        if (value == null || key == null || replaceValue == null) {
059            return value;
060        }
061
062        int pos = value.indexOf(key);
063
064        if (pos < 0) {
065            return value;
066        }
067
068        int length = value.length();
069        int start = pos;
070        int end = pos + key.length();
071
072        if (length == key.length()) {
073            value = replaceValue;
074
075        } else if (end == length) {
076            value = value.substring(0, start) + replaceValue;
077
078        } else {
079            value =
080                    value.substring(0, start)
081                    + replaceValue
082                    + replace(value.substring(end), key, replaceValue);
083        }
084
085        return value;
086    }
087
088    /**
089     * Convenience method for getting a value from a bean property as a
090     * <code>String</code>.  If the property is a <code>String[]</code> or
091     * <code>Collection</code> and it is empty, an empty <code>String</code>
092     * "" is returned.  Otherwise, property.toString() is returned.  This method
093     * may return <code>null</code> if there was an error retrieving the
094     * property.
095     *
096     * @param bean The bean object.
097     * @param property The name of the property to access.
098     *
099     * @return The value of the property.
100     */
101    public static String getValueAsString(Object bean, String property) {
102        Object value = null;
103
104        try {
105            value = PropertyUtils.getProperty(bean, property);
106
107        } catch(IllegalAccessException e) {
108            LOG.error(e.getMessage(), e);
109        } catch(InvocationTargetException e) {
110            LOG.error(e.getMessage(), e);
111        } catch(NoSuchMethodException e) {
112            LOG.error(e.getMessage(), e);
113        }
114
115        if (value == null) {
116            return null;
117        }
118
119        if (value instanceof String[]) {
120            return ((String[]) value).length > 0 ? value.toString() : "";
121
122        } else if (value instanceof Collection) {
123            return ((Collection<?>) value).isEmpty() ? "" : value.toString();
124
125        } else {
126            return value.toString();
127        }
128
129    }
130
131    /**
132     * Makes a deep copy of a <code>FastHashMap</code> if the values
133     * are <code>Msg</code>, <code>Arg</code>,
134     * or <code>Var</code>.  Otherwise it is a shallow copy.
135     *
136     * @param map <code>FastHashMap</code> to copy.
137     * @return FastHashMap A copy of the <code>FastHashMap</code> that was
138     * passed in.
139     * @deprecated This method is not part of Validator's public API.  Validator
140     * will use it internally until FastHashMap references are removed.  Use
141     * copyMap() instead.
142     */
143    public static FastHashMap copyFastHashMap(FastHashMap map) {
144        FastHashMap results = new FastHashMap();
145
146        @SuppressWarnings("unchecked") // FastHashMap is not generic
147        Iterator<Entry<String, ?>> i = map.entrySet().iterator();
148        while (i.hasNext()) {
149            Entry<String, ?> entry = i.next();
150            String key = (String) entry.getKey();
151            Object value = entry.getValue();
152
153            if (value instanceof Msg) {
154                results.put(key, ((Msg) value).clone());
155            } else if (value instanceof Arg) {
156                results.put(key, ((Arg) value).clone());
157            } else if (value instanceof Var) {
158                results.put(key, ((Var) value).clone());
159            } else {
160                results.put(key, value);
161            }
162        }
163
164        results.setFast(true);
165        return results;
166    }
167
168    /**
169     * Makes a deep copy of a <code>Map</code> if the values are
170     * <code>Msg</code>, <code>Arg</code>, or <code>Var</code>.  Otherwise,
171     * it is a shallow copy.
172     *
173     * @param map The source Map to copy.
174     *
175     * @return A copy of the <code>Map</code> that was passed in.
176     */
177    public static Map<String, Object> copyMap(Map<String, Object> map) {
178        Map<String, Object> results = new HashMap<String, Object>();
179
180        Iterator<Entry<String, Object>> i = map.entrySet().iterator();
181        while (i.hasNext()) {
182            Entry<String, Object> entry = i.next();
183            String key = entry.getKey();
184            Object value = entry.getValue();
185
186            if (value instanceof Msg) {
187                results.put(key, ((Msg) value).clone());
188            } else if (value instanceof Arg) {
189                results.put(key, ((Arg) value).clone());
190            } else if (value instanceof Var) {
191                results.put(key, ((Var) value).clone());
192            } else {
193                results.put(key, value);
194            }
195        }
196        return results;
197    }
198
199}