KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ofbiz > base > util > StringUtil


1 /*
2  * $Id: StringUtil.java 5462 2005-08-05 18:35:48Z jonesde $
3  *
4  * Copyright (c) 2001-2005 The Open For Business Project - www.ofbiz.org
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a
7  * copy of this software and associated documentation files (the "Software"),
8  * to deal in the Software without restriction, including without limitation
9  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10  * and/or sell copies of the Software, and to permit persons to whom the
11  * Software is furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included
14  * in all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
17  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19  * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20  * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
21  * OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
22  * THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23  */

24 package org.ofbiz.base.util;
25
26 import java.io.UnsupportedEncodingException JavaDoc;
27 import java.net.URLDecoder JavaDoc;
28 import java.net.URLEncoder JavaDoc;
29 import java.util.ArrayList JavaDoc;
30 import java.util.HashMap JavaDoc;
31 import java.util.Iterator JavaDoc;
32 import java.util.List JavaDoc;
33 import java.util.Map JavaDoc;
34 import java.util.Set JavaDoc;
35 import java.util.StringTokenizer JavaDoc;
36
37 /**
38  * Misc String Utility Functions
39  *
40  * @author <a HREF="mailto:jaz@ofbiz.org">Andy Zeneski</a>
41  * @version $Rev: 5462 $
42  * @since 2.0
43  */

44 public class StringUtil {
45     
46     public static final String JavaDoc module = StringUtil.class.getName();
47
48     /**
49      * Replaces all occurances of oldString in mainString with newString
50      * @param mainString The original string
51      * @param oldString The string to replace
52      * @param newString The string to insert in place of the old
53      * @return mainString with all occurances of oldString replaced by newString
54      */

55     public static String JavaDoc replaceString(String JavaDoc mainString, String JavaDoc oldString, String JavaDoc newString) {
56         if (mainString == null) {
57             return null;
58         }
59         if (oldString == null || oldString.length() == 0) {
60             return mainString;
61         }
62         if (newString == null) {
63             newString = "";
64         }
65
66         int i = mainString.lastIndexOf(oldString);
67
68         if (i < 0) return mainString;
69
70         StringBuffer JavaDoc mainSb = new StringBuffer JavaDoc(mainString);
71
72         while (i >= 0) {
73             mainSb.replace(i, i + oldString.length(), newString);
74             i = mainString.lastIndexOf(oldString, i - 1);
75         }
76         return mainSb.toString();
77     }
78
79     /**
80      * Creates a single string from a List of strings seperated by a delimiter.
81      * @param list a list of strings to join
82      * @param delim the delimiter character(s) to use. (null value will join with no delimiter)
83      * @return a String of all values in the list seperated by the delimiter
84      */

85     public static String JavaDoc join(List JavaDoc list, String JavaDoc delim) {
86         if (list == null || list.size() < 1)
87             return null;
88         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
89         Iterator JavaDoc i = list.iterator();
90
91         while (i.hasNext()) {
92             buf.append((String JavaDoc) i.next());
93             if (i.hasNext())
94                 buf.append(delim);
95         }
96         return buf.toString();
97     }
98
99     /**
100      * Splits a String on a delimiter into a List of Strings.
101      * @param str the String to split
102      * @param delim the delimiter character(s) to join on (null will split on whitespace)
103      * @return a list of Strings
104      */

105     public static List JavaDoc split(String JavaDoc str, String JavaDoc delim) {
106         List JavaDoc splitList = null;
107         StringTokenizer JavaDoc st = null;
108
109         if (str == null)
110             return splitList;
111
112         if (delim != null)
113             st = new StringTokenizer JavaDoc(str, delim);
114         else
115             st = new StringTokenizer JavaDoc(str);
116
117         if (st != null && st.hasMoreTokens()) {
118             splitList = new ArrayList JavaDoc();
119
120             while (st.hasMoreTokens())
121                 splitList.add(st.nextToken());
122         }
123         return splitList;
124     }
125
126     /**
127      * Encloses each of a List of Strings in quotes.
128      * @param list List of String(s) to quote.
129      */

130     public static List JavaDoc quoteStrList(List JavaDoc list) {
131         List JavaDoc tmpList = list;
132
133         list = new ArrayList JavaDoc();
134         Iterator JavaDoc i = tmpList.iterator();
135
136         while (i.hasNext()) {
137             String JavaDoc str = (String JavaDoc) i.next();
138
139             str = "'" + str + "''";
140             list.add(str);
141         }
142         return list;
143     }
144
145     /**
146      * Creates a Map from an encoded name/value pair string
147      * @param str The string to decode and format
148      * @param trim Trim whitespace off fields
149      * @return a Map of name/value pairs
150      */

151     public static Map JavaDoc strToMap(String JavaDoc str, boolean trim) {
152         if (str == null) return null;
153         Map JavaDoc decodedMap = new HashMap JavaDoc();
154         List JavaDoc elements = split(str, "|");
155         Iterator JavaDoc i = elements.iterator();
156
157         while (i.hasNext()) {
158             String JavaDoc s = (String JavaDoc) i.next();
159             List JavaDoc e = split(s, "=");
160
161             if (e.size() != 2) {
162                 continue;
163             }
164             String JavaDoc name = (String JavaDoc) e.get(0);
165             String JavaDoc value = (String JavaDoc) e.get(1);
166             if (trim) {
167                 if (name != null) {
168                     name = name.trim();
169                 }
170                 if (value != null) {
171                     value = value.trim();
172                 }
173             }
174
175             try {
176                 decodedMap.put(URLDecoder.decode(name, "UTF-8"), URLDecoder.decode(value, "UTF-8"));
177             } catch (UnsupportedEncodingException JavaDoc e1) {
178                 Debug.logError(e1, module);
179             }
180         }
181         return decodedMap;
182     }
183
184     /**
185      * Creates a Map from an encoded name/value pair string
186      * @param str The string to decode and format
187      * @return a Map of name/value pairs
188      */

189     public static Map JavaDoc strToMap(String JavaDoc str) {
190         return strToMap(str, false);
191     }
192
193     /**
194      * Creates an encoded String from a Map of name/value pairs (MUST BE STRINGS!)
195      * @param map The Map of name/value pairs
196      * @return String The encoded String
197      */

198     public static String JavaDoc mapToStr(Map JavaDoc map) {
199         if (map == null) return null;
200         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
201         Set JavaDoc keySet = map.keySet();
202         Iterator JavaDoc i = keySet.iterator();
203         boolean first = true;
204
205         while (i.hasNext()) {
206             Object JavaDoc key = i.next();
207             Object JavaDoc value = map.get(key);
208
209             if (!(key instanceof String JavaDoc) || !(value instanceof String JavaDoc))
210                 continue;
211             String JavaDoc encodedName = null;
212             try {
213                 encodedName = URLEncoder.encode((String JavaDoc) key, "UTF-8");
214             } catch (UnsupportedEncodingException JavaDoc e) {
215                 Debug.logError(e, module);
216             }
217             String JavaDoc encodedValue = null;
218             try {
219                 encodedValue = URLEncoder.encode((String JavaDoc) value, "UTF-8");
220             } catch (UnsupportedEncodingException JavaDoc e) {
221                 Debug.logError(e, module);
222             }
223             
224             if (first)
225                 first = false;
226             else
227                 buf.append("|");
228
229             buf.append(encodedName);
230             buf.append("=");
231             buf.append(encodedValue);
232         }
233         return buf.toString();
234     }
235
236     /**
237      * Create a Map from a List of keys and a List of values
238      * @param keys List of keys
239      * @param values List of values
240      * @return Map of combined lists
241      * @throws IllegalArgumentException When either List is null or the sizes do not equal
242      */

243     public static Map JavaDoc createMap(List JavaDoc keys, List JavaDoc values) {
244         if (keys == null || values == null || keys.size() != values.size()) {
245             throw new IllegalArgumentException JavaDoc("Keys and Values cannot be null and must be the same size");
246         }
247         Map JavaDoc newMap = new HashMap JavaDoc();
248         for (int i = 0; i < keys.size(); i++) {
249             newMap.put(keys.get(i), values.get(i));
250         }
251         return newMap;
252     }
253
254     /** Make sure the string starts with a forward slash but does not end with one; converts back-slashes to forward-slashes; if in String is null or empty, returns zero length string. */
255     public static String JavaDoc cleanUpPathPrefix(String JavaDoc prefix) {
256         if (prefix == null || prefix.length() == 0) return "";
257
258         StringBuffer JavaDoc cppBuff = new StringBuffer JavaDoc(prefix.replace('\\', '/'));
259
260         if (cppBuff.charAt(0) != '/') {
261             cppBuff.insert(0, '/');
262         }
263         if (cppBuff.charAt(cppBuff.length() - 1) == '/') {
264             cppBuff.deleteCharAt(cppBuff.length() - 1);
265         }
266         return cppBuff.toString();
267     }
268     
269     /** Removes all spaces from a string */
270     public static String JavaDoc removeSpaces(String JavaDoc str) {
271         StringBuffer JavaDoc newString = new StringBuffer JavaDoc();
272         for (int i = 0; i < str.length(); i++) {
273             if (str.charAt(i) != ' ')
274                 newString.append(str.charAt(i));
275         }
276         return newString.toString();
277     }
278
279     public static String JavaDoc toHexString(byte[] bytes) {
280         StringBuffer JavaDoc buf = new StringBuffer JavaDoc(bytes.length * 2);
281         for (int i = 0; i < bytes.length; i++) {
282             buf.append(hexChar[(bytes[i] & 0xf0) >>> 4]);
283             buf.append(hexChar[bytes[i] & 0x0f]);
284         }
285         return buf.toString();
286
287     }
288
289     public static String JavaDoc cleanHexString(String JavaDoc str) {
290         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
291         for (int i = 0; i < str.length(); i++) {
292             if (str.charAt(i) != (int) 32 && str.charAt(i) != ':') {
293                 buf.append(str.charAt(i));
294             }
295         }
296         return buf.toString();
297     }
298
299     public static byte[] fromHexString(String JavaDoc str) {
300         str = cleanHexString(str);
301         int stringLength = str.length();
302         if ((stringLength & 0x1) != 0) {
303             throw new IllegalArgumentException JavaDoc("fromHexString requires an even number of hex characters");
304         }
305         byte[] b = new byte[stringLength / 2];
306
307         for (int i = 0, j = 0; i < stringLength; i+= 2, j++) {
308             int high = convertChar(str.charAt(i));
309             int low = convertChar(str.charAt(i+1));
310             b[j] = (byte) ((high << 4) | low);
311         }
312         return b;
313     }
314
315     private static char[] hexChar = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
316     public static int convertChar(char c) {
317         if ( '0' <= c && c <= '9' ) {
318             return c - '0' ;
319         } else if ( 'a' <= c && c <= 'f' ) {
320             return c - 'a' + 0xa ;
321         } else if ( 'A' <= c && c <= 'F' ) {
322             return c - 'A' + 0xa ;
323         } else {
324             throw new IllegalArgumentException JavaDoc("Invalid hex character: [" + c + "]");
325         }
326     }
327
328     public static char[] encodeInt(int i, int j, char digestChars[]) {
329         if (i < 16) {
330             digestChars[j] = '0';
331         }
332         j++;
333         do {
334             digestChars[j--] = hexChar[i & 0xf];
335             i >>>= 4;
336         } while (i != 0);
337         return digestChars;
338     }
339 }
340
Popular Tags