b79ef109dba709dc38b64b581961528552ee6208
[mir.git] / source / mir / util / StringRoutines.java
1 /*
2  * Copyright (C) 2001, 2002 The Mir-coders group
3  *
4  * This file is part of Mir.
5  *
6  * Mir is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * Mir is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with Mir; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  *
20  * In addition, as a special exception, The Mir-coders gives permission to link
21  * the code of this program with  any library licensed under the Apache Software License,
22  * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
23  * (or with modified versions of the above that use the same license as the above),
24  * and distribute linked combinations including the two.  You must obey the
25  * GNU General Public License in all respects for all of the code used other than
26  * the above mentioned libraries.  If you modify this file, you may extend this
27  * exception to your version of the file, but you are not obligated to do so.
28  * If you do not wish to do so, delete this exception statement from your version.
29  */
30 package mir.util;
31
32 import gnu.regexp.RE;
33
34 import java.util.ArrayList;
35 import java.util.List;
36
37 public class StringRoutines {
38
39   private StringRoutines() {
40   }
41
42   public static int indexOfCharacters(String aString, char[] aCharacters, int aFrom) {
43     int i;
44     int result=-1;
45     int position;
46
47     for (i=0; i<aCharacters.length ; i++) {
48       position = aString.indexOf(aCharacters[i], aFrom);
49
50       if (position != -1 && ( result == -1 || position < result )) {
51         result = position;
52       }
53     }
54
55     return result;
56   }
57
58   public static String replaceStringCharacters(String aText, char[] aCharactersToReplace, String[] aStringsToSubstitute) {
59     if (aText==null)
60       return null;
61
62     int position, nextPosition;
63     int i;
64     StringBuffer result = new StringBuffer();
65
66     position=0;
67     do {
68       nextPosition = StringRoutines.indexOfCharacters(aText, aCharactersToReplace, position);
69
70       if (nextPosition<0)
71         nextPosition = aText.length();
72
73       result.append(aText.substring(position, nextPosition));
74
75       if (nextPosition<aText.length())
76         for (i=0; i<aCharactersToReplace.length; i++) {
77           if (aCharactersToReplace[i] == aText.charAt(nextPosition)) {
78             result.append(aStringsToSubstitute[i]);
79             break;
80           }
81         }
82       position=nextPosition+1;
83     }
84     while (nextPosition<aText.length()) ;
85
86     return result.toString();
87   }
88   /**
89    */
90
91   public static String replaceEscapedStringCharacters(String aText, char anEscapeCharacter, char[] aCharactersToReplace, String[] aStringsToSubstitute) {
92     if (aText==null)
93       return null;
94
95     int position, nextPosition;
96     int i;
97     StringBuffer result = new StringBuffer();
98
99     position=0;
100     do {
101       nextPosition = aText.indexOf(anEscapeCharacter, position);
102
103       if (nextPosition<0)
104         nextPosition = aText.length();
105
106       result.append(aText.substring(position, nextPosition));
107
108       if (nextPosition+1<aText.length()) {
109         nextPosition = nextPosition+1;
110
111         boolean found = false;
112         for (i = 0; i < aCharactersToReplace.length; i++) {
113           if (aCharactersToReplace[i] == aText.charAt(nextPosition)) {
114             result.append(aStringsToSubstitute[i]);
115             found=true;
116             break;
117           }
118         }
119
120         if (!found) {
121           result.append(aText.charAt(nextPosition));
122         }
123       }
124       position=nextPosition+1;
125     }
126     while (nextPosition<aText.length()) ;
127
128     return result.toString();
129   }
130
131   public static String interpretAsString(Object aValue) throws Exception {
132     if (aValue instanceof String)
133       return (String) aValue;
134
135     if (aValue instanceof Integer)
136       return aValue.toString();
137
138     if (aValue == null)
139       return "";
140
141     throw new Exception("String expected, "+aValue+" found");
142   }
143
144   public static int interpretAsInteger(Object aValue) throws Exception {
145     if (aValue instanceof Integer)
146       return ((Integer) aValue).intValue();
147
148     if (aValue instanceof String)
149       try {
150         return Integer.parseInt((String) aValue);
151       }
152       catch (Throwable t) {
153         throw new Exception("Integer expected, "+aValue+" found");
154       }
155
156     throw new Exception("Integer expected, "+aValue+" found");
157   }
158
159   public static String performRegularExpressionReplacement(String aSource, String aSearchExpression, String aReplacement) {
160     try {
161       RE regularExpression;
162
163       regularExpression = new RE(aSearchExpression);
164
165       return regularExpression.substituteAll(aSource, aReplacement);
166     }
167     catch (Throwable t) {
168       throw new UtilFailure("StringRoutines.performRegularExpressionReplacement: " + t.toString(), t);
169     }
170   }
171
172   public static String performCaseInsensitiveRegularExpressionReplacement(String aSource, String aSearchExpression, String aReplacement) {
173     try {
174       RE regularExpression;
175
176       regularExpression = new RE(aSearchExpression, RE.REG_ICASE);
177
178       return regularExpression.substituteAll(aSource, aReplacement);
179     }
180     catch (Throwable t) {
181       throw new UtilFailure("StringRoutines.performRegularExpressionReplacement: " + t.toString(), t);
182     }
183   }
184
185   public static boolean performRegularExpressionSearch(String aSource, String aSearchExpression) {
186     try {
187       RE regularExpression;
188
189       regularExpression = new RE(aSearchExpression);
190
191       return regularExpression.isMatch(aSource);
192     }
193     catch (Throwable t) {
194       throw new UtilFailure("StringRoutines.performRegularExpressionSearch: " + t.toString(), t);
195     }
196   }
197
198   /**
199    * Separates a string based on a separator:
200    *     <code>seperateString("a:b:c", ":");</code> will lead to
201    *     a List with 3 Strings: <code>"a"</code>, <code>"b"</code> and <code>"c"</code>
202    *
203    * @param aString     The string to split
204    * @param aSeparator
205    * @return
206    */
207
208   public static List splitString(String aString, String aSeparator) {
209     List result= new ArrayList();
210     int previousPosition = 0;
211     int position;
212
213     if (aString!=null) {
214       while ( (position = aString.indexOf(aSeparator, previousPosition)) >= 0) {
215         result.add(aString.substring(previousPosition, position));
216         previousPosition = position + aSeparator.length();
217       }
218       result.add(aString.substring(previousPosition, aString.length()));
219     }
220
221     return result;
222   }
223
224   /**
225    * Separates a String into at most 2 parts based on a separator:
226    * <ul>
227    *   <li>
228    *     <code>seperateString("a:b:c", ":");</code> will lead to
229    *     a List with 2 Strings: <code>"a"</code> and <code>"b:c"</code>
230    *   <li>
231    *     <code>seperateString("abc", ":");</code> will lead to
232    *     a List with a single String: <code>"abc"</code>
233    * </ul>
234    *
235    *
236    * @param aString
237    * @param aSeparator
238    * @return
239    */
240   public static List separateString(String aString, String aSeparator) {
241     List result= new ArrayList();
242     int previousPosition = 0;
243     int position;
244
245     if((position = aString.indexOf(aSeparator, previousPosition))>=0) {
246       result.add(aString.substring(previousPosition, position));
247       previousPosition = position + aSeparator.length();
248     }
249
250     result.add(aString.substring(previousPosition, aString.length()));
251
252     return result;
253   }
254
255   /**
256    * Separates a string based on a separator, taking into account an escape character:
257    *     <code>seperateString("a:/::b", ":", "/");</code> will lead to
258    *     a List with 3 Strings: <code>"a"</code>, <code>":"</code> and <code>"b"</code>
259    *
260    * @param aString     The string to split
261    * @param aSeparator
262    * @return
263    */
264
265   public static List splitStringWithEscape(String aString, char aSeparator, char anEscape) {
266     List result= new ArrayList();
267     int previousPosition = 0;
268     int position;
269
270     StringBuffer currentItem = new StringBuffer();
271
272     if (aString!=null && aString.length()>0) {
273       while ((position = indexOfCharacters(aString, new char[] {aSeparator, anEscape}, previousPosition))>=0) {
274         currentItem.append(aString.substring(previousPosition, position));
275
276         if (aString.charAt(position)==aSeparator) {
277           result.add(currentItem.toString());
278           currentItem.delete(0, currentItem.length());
279         }
280         else {
281           if (aString.length()>position+1) {
282             position=position+1;
283             currentItem.append(aString.charAt(position));
284           }
285           else {
286             currentItem.append(aString.charAt(position));
287           }
288         }
289         previousPosition = position + 1;
290       }
291       currentItem.append(aString.substring(previousPosition, aString.length()));
292       result.add(currentItem.toString());
293     }
294
295     return result;
296   }
297
298   public static String replicateString(String aString, int aCount) {
299     StringBuffer result = new StringBuffer();
300
301     for (int i=0; i<aCount; i++)
302       result.append(aString);
303
304     return result.toString();
305   }
306
307   public static String replicateChar(char aCharacter, int aCount) {
308     char result[] = new char[aCount];
309
310     for (int i=0; i<aCount; i++)
311       result[i]= aCharacter;
312
313     return new String(result);
314   }
315
316   public static String padStringLeft(String aString, int aLength, char aPadCharacter) {
317     if (aString.length()<aLength)
318       return replicateChar(aPadCharacter, aLength-aString.length()) + aString;
319                 return aString;
320   }
321
322   private static final char HEX_CHARACTERS[] = {
323       '0', '1', '2', '3', '4', '5', '6', '7',
324       '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
325   };
326
327   public static String convertToHex(long aData, int aNumberOfDigits) {
328     StringBuffer result = new StringBuffer();
329
330     for (int digit = aNumberOfDigits-1; digit>=0; digit--) {
331       int value = (int) (aData >> (digit*4)) & 0xf;
332       result.append(HEX_CHARACTERS[value]);
333     }
334
335     return result.toString();
336   }
337
338   public static String convertToHex(byte[] aData) {
339     StringBuffer result = new StringBuffer();
340
341     for (int i = 0; i<aData.length; i++) {
342       result.append(convertToHex(aData[i], 2));
343
344     }
345
346     return result.toString();
347   }
348 }