0627dbc13d1b29f562207c099e2da171bbbd0fa3
[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.List;
35 import java.util.Vector;
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    * @param aText
91    * @param anEscapeCharacater
92    * @param aCharactersToReplace
93    * @param aStringsToSubstitute
94    * @return
95    */
96
97   public static String replaceEscapedStringCharacters(String aText, char anEscapeCharacter, char[] aCharactersToReplace, String[] aStringsToSubstitute) {
98     if (aText==null)
99       return null;
100
101     int position, nextPosition;
102     int i;
103     StringBuffer result = new StringBuffer();
104
105     position=0;
106     do {
107       nextPosition = aText.indexOf(anEscapeCharacter, position);
108
109       if (nextPosition<0)
110         nextPosition = aText.length();
111
112       result.append(aText.substring(position, nextPosition));
113
114       if (nextPosition+1<aText.length()) {
115         nextPosition = nextPosition+1;
116
117         boolean found = false;
118         for (i = 0; i < aCharactersToReplace.length; i++) {
119           if (aCharactersToReplace[i] == aText.charAt(nextPosition)) {
120             result.append(aStringsToSubstitute[i]);
121             found=true;
122             break;
123           }
124         }
125
126         if (!found) {
127           result.append(aText.charAt(nextPosition));
128         }
129       }
130       position=nextPosition+1;
131     }
132     while (nextPosition<aText.length()) ;
133
134     return result.toString();
135   }
136
137   public static String interpretAsString(Object aValue) throws Exception {
138     if (aValue instanceof String)
139       return (String) aValue;
140
141     if (aValue instanceof Integer)
142       return ((Integer) aValue).toString();
143
144     if (aValue == null)
145       return "";
146
147     throw new Exception("String expected, "+aValue+" found");
148   }
149
150   public static int interpretAsInteger(Object aValue) throws Exception {
151     if (aValue instanceof Integer)
152       return ((Integer) aValue).intValue();
153
154     if (aValue instanceof String)
155       try {
156         return Integer.parseInt((String) aValue);
157       }
158       catch (Throwable t) {
159         throw new Exception("Integer expected, "+aValue+" found");
160       }
161
162     throw new Exception("Integer expected, "+aValue+" found");
163   }
164
165   /**
166    *
167    * @param aSource
168    * @param aSearchExpression
169    * @param aReplacement
170    * @return
171    * @throws Exception
172    */
173   public static String performRegularExpressionReplacement(String aSource,
174       String aSearchExpression, String aReplacement) throws UtilExc {
175     try {
176       RE regularExpression;
177
178       regularExpression = new RE(aSearchExpression);
179
180       return regularExpression.substituteAll(aSource, aReplacement);
181     }
182     catch (Throwable t) {
183       throw new UtilFailure("StringRoutines.performRegularExpressionReplacement: " + t.toString(), t);
184     }
185   }
186
187   public static String performCaseInsensitiveRegularExpressionReplacement(String aSource,
188       String aSearchExpression, String aReplacement) throws UtilExc {
189     try {
190       RE regularExpression;
191
192       regularExpression = new RE(aSearchExpression, RE.REG_ICASE);
193
194       return regularExpression.substituteAll(aSource, aReplacement);
195     }
196     catch (Throwable t) {
197       throw new UtilFailure("StringRoutines.performRegularExpressionReplacement: " + t.toString(), t);
198     }
199   }
200
201   /**
202    *
203    * @param aSource
204    * @param aSearchExpression
205    * @return
206    * @throws REException
207    */
208   public static boolean performRegularExpressionSearch(String aSource,
209       String aSearchExpression) throws UtilExc {
210     try {
211       RE regularExpression;
212
213       regularExpression = new RE(aSearchExpression);
214
215       return regularExpression.isMatch(aSource);
216     }
217     catch (Throwable t) {
218       throw new UtilFailure("StringRoutines.performRegularExpressionSearch: " + t.toString(), t);
219     }
220   }
221
222   /**
223    * Separates a string based on a separator:
224    *     <code>seperateString("a:b:c", ":");</code> will lead to
225    *     a List with 3 Strings: <code>"a"</code>, <code>"b"</code> and <code>"c"</code>
226    *
227    * @param aString     The string to split
228    * @param aSeparator
229    * @return
230    */
231
232   public static List splitString(String aString, String aSeparator) {
233     List result= new Vector();
234     int previousPosition = 0;
235     int position;
236     int endOfNamePosition;
237
238     if (aString!=null) {
239       while ( (position = aString.indexOf(aSeparator, previousPosition)) >= 0) {
240         result.add(aString.substring(previousPosition, position));
241         previousPosition = position + aSeparator.length();
242       }
243       result.add(aString.substring(previousPosition, aString.length()));
244     }
245
246     return result;
247   }
248
249   /**
250    * Separates a String into at most 2 parts based on a separator:
251    * <ul>
252    *   <li>
253    *     <code>seperateString("a:b:c", ":");</code> will lead to
254    *     a List with 2 Strings: <code>"a"</code> and <code>"b:c"</code>
255    *   <li>
256    *     <code>seperateString("abc", ":");</code> will lead to
257    *     a List with a single String: <code>"abc"</code>
258    * </ul>
259    *
260    *
261    * @param aString
262    * @param aSeparator
263    * @return
264    */
265   public static List separateString(String aString, String aSeparator) {
266     List result= new Vector();
267     int previousPosition = 0;
268     int position;
269
270     if((position = aString.indexOf(aSeparator, previousPosition))>=0) {
271       result.add(aString.substring(previousPosition, position));
272       previousPosition = position + aSeparator.length();
273     }
274
275     result.add(aString.substring(previousPosition, aString.length()));
276
277     return result;
278   }
279
280   /**
281    * Separates a string based on a separator, taking into account an escape character:
282    *     <code>seperateString("a:/::b", ":", "/");</code> will lead to
283    *     a List with 3 Strings: <code>"a"</code>, <code>":"</code> and <code>"b"</code>
284    *
285    * @param aString     The string to split
286    * @param aSeparator
287    * @return
288    */
289
290   public static List splitStringWithEscape(String aString, char aSeparator, char anEscape) {
291     List result= new Vector();
292     int previousPosition = 0;
293     int position;
294     int endOfNamePosition;
295     StringBuffer currentItem = new StringBuffer();
296
297     if (aString!=null) {
298       while ((position = indexOfCharacters(aString, new char[] {aSeparator, anEscape}, previousPosition))>=0) {
299         currentItem.append(aString.substring(previousPosition, position));
300
301         if (aString.charAt(position)==aSeparator) {
302           result.add(currentItem.toString());
303           currentItem.delete(0, currentItem.length());
304         }
305         else {
306           currentItem.append(aString.charAt(position));
307           if (aString.length()>position+1) {
308             position=position+1;
309             currentItem.append(aString.charAt(position));
310           }
311         }
312         previousPosition = position + 1;
313       }
314       currentItem.append(aString.substring(previousPosition, aString.length()));
315       result.add(currentItem.toString());
316     }
317
318     return result;
319   }
320
321   public static String replicateString(String aString, int aCount) {
322     StringBuffer result = new StringBuffer();
323
324     for (int i=0; i<aCount; i++)
325       result.append(aString);
326
327     return result.toString();
328   }
329
330   public static String replicateChar(char aCharacter, int aCount) {
331     char result[] = new char[aCount];
332
333     for (int i=0; i<aCount; i++)
334       result[i]= aCharacter;
335
336     return new String(result);
337   }
338
339   public static String padStringLeft(String aString, int aLength, char aPadCharacter) {
340     if (aString.length()<aLength)
341       return replicateChar(aPadCharacter, aLength-aString.length()) + aString;
342     else
343       return aString;
344   }
345
346   private static final char HEX_CHARACTERS[] = {
347       '0', '1', '2', '3', '4', '5', '6', '7',
348       '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
349   };
350
351   public static String convertToHex(long aData, int aNumberOfDigits) {
352     StringBuffer result = new StringBuffer();
353
354     for (int digit = aNumberOfDigits-1; digit>=0; digit--) {
355       int value = (int) (aData >> (digit*4)) & 0xf;
356       result.append(HEX_CHARACTERS[value]);
357     }
358
359     return result.toString();
360   }
361
362   public static String convertToHex(byte[] aData) {
363     StringBuffer result = new StringBuffer();
364
365     for (int i = 0; i<aData.length; i++) {
366       result.append(convertToHex(aData[i], 2));
367
368     }
369
370     return result.toString();
371   }
372 }