KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > antlr > xjlib > foundation > XJUtils


1 /*
2
3 [The "BSD licence"]
4 Copyright (c) 2005 Jean Bovet
5 All rights reserved.
6
7 Redistribution and use in source and binary forms, with or without
8 modification, are permitted provided that the following conditions
9 are met:
10
11 1. Redistributions of source code must retain the above copyright
12 notice, this list of conditions and the following disclaimer.
13 2. Redistributions in binary form must reproduce the above copyright
14 notice, this list of conditions and the following disclaimer in the
15 documentation and/or other materials provided with the distribution.
16 3. The name of the author may not be used to endorse or promote products
17 derived from this software without specific prior written permission.
18
19 THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
20 IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
21 OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
22 IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
23 INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
24 NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29
30 */

31
32 package org.antlr.xjlib.foundation;
33
34 import java.io.*;
35 import java.net.URLEncoder JavaDoc;
36 import java.util.Arrays JavaDoc;
37 import java.util.Collections JavaDoc;
38 import java.util.List JavaDoc;
39
40 public class XJUtils {
41
42     public static String JavaDoc concatPath(String JavaDoc a, String JavaDoc b, String JavaDoc separator) {
43         if(a.endsWith(separator) && b.startsWith(separator)) {
44             return a+b.substring(1);
45         } else if(a.endsWith(separator)) {
46             return a+b;
47         } else if(b.startsWith(separator)) {
48             return a+b;
49         }
50         return a+separator+b;
51     }
52
53     public static String JavaDoc concatPath(String JavaDoc a, String JavaDoc b) {
54         return concatPath(a, b, File.separator);
55     }
56
57     public static String JavaDoc getLastPathComponent(String JavaDoc path) {
58         if(path == null)
59             return null;
60
61         int index = path.lastIndexOf(File.separator);
62         if(index == -1)
63             return path;
64         else
65             return path.substring(index+1, path.length());
66     }
67
68     public static String JavaDoc getPathByDeletingPathExtension(String JavaDoc path) {
69         if(path == null)
70             return null;
71
72         int index = path.lastIndexOf(".");
73         if(index == -1)
74             return path;
75
76         return path.substring(0, index);
77     }
78
79     public static String JavaDoc getPathByDeletingLastComponent(String JavaDoc path, String JavaDoc separator) {
80         if(path == null)
81             return null;
82
83         if(path.endsWith(separator)) {
84             path = path.substring(0, path.length()-1);
85         }
86
87         int index = path.lastIndexOf(separator);
88         if(index == -1)
89             return path;
90         else
91             return path.substring(0, index);
92     }
93
94     public static String JavaDoc getPathByDeletingLastComponent(String JavaDoc path) {
95         return getPathByDeletingLastComponent(path, File.separator);
96     }
97
98     public static List JavaDoc sortedFilesInPath(String JavaDoc path) {
99         File[] files = new File(path).listFiles();
100         List JavaDoc sortedFiles = Arrays.asList(files);
101         Collections.sort(sortedFiles);
102         return sortedFiles;
103     }
104
105     public static String JavaDoc escapeString(String JavaDoc a) {
106         StringBuffer JavaDoc b = new StringBuffer JavaDoc();
107         for(int i=0; i<a.length(); i++) {
108             char c1 = a.charAt(i);
109             char c2 = (i+1<a.length())?a.charAt(i+1):0;
110             if(c1 == '\\' && c2 != '\\') {
111                 b.append('\\');
112                 b.append('\\');
113             } else if(c1 == '\\') {
114                 b.append('\\');
115                 b.append('\\');
116                 i++;
117             } else {
118                 b.append(c1);
119             }
120         }
121         return b.toString();
122     }
123
124     public static Object JavaDoc clone(Object JavaDoc object) throws Exception JavaDoc {
125         Object JavaDoc copy = null;
126
127         ObjectOutputStream oos = null;
128         ObjectInputStream ois = null;
129
130         try {
131             ByteArrayOutputStream bos = new ByteArrayOutputStream();
132             oos = new ObjectOutputStream(bos);
133             oos.writeObject(object);
134             oos.flush();
135
136             ByteArrayInputStream bin = new ByteArrayInputStream(bos.toByteArray());
137             ois = new ObjectInputStream(bin);
138             copy = ois.readObject();
139         } finally {
140             if(ois != null)
141                 ois.close();
142             if(oos != null)
143                 oos.close();
144         }
145         return copy;
146     }
147
148     public static void writeStringToFile(String JavaDoc text, String JavaDoc file) throws IOException {
149         OutputStream os = new FileOutputStream(file);
150         os.write(text.getBytes());
151         os.close();
152     }
153
154     public static String JavaDoc getStringFromFile(String JavaDoc file) throws IOException {
155         char [] data = null;
156         FileReader fr = null;
157         try {
158             File f = new File(file);
159             int max = (int)f.length();
160             data = new char[max];
161             fr = new FileReader(f);
162             int count = 0;
163             while(count < max) {
164                 count += fr.read(data, count, max-count);
165             }
166         } catch(IOException e) {
167             throw e;
168         } finally {
169             if ( fr!=null ) {
170                 try {
171                     fr.close();
172                 } catch (IOException e) {
173                     e.printStackTrace();
174                 }
175             }
176         }
177         return new String JavaDoc(data);
178     }
179
180     public static final String JavaDoc VERSION_EA = "ea";
181     public static final String JavaDoc VERSION_BETA = "b";
182
183     protected static int[] parseVersionElement(String JavaDoc e) {
184         int[] v = new int[] { 0, 0, 0 };
185
186         int index;
187         if((index = e.indexOf(VERSION_EA)) > 0) {
188             v[0] = Integer.parseInt(e.substring(0, index));
189             v[1] = -2;
190             v[2] = Integer.parseInt(e.substring(index+VERSION_EA.length()));
191         } else if((index = e.indexOf(VERSION_BETA)) > 0) {
192             v[0] = Integer.parseInt(e.substring(0, index));
193             v[1] = -1;
194             v[2] = Integer.parseInt(e.substring(index+VERSION_BETA.length()));
195         } else {
196             v[0] = Integer.parseInt(e);
197         }
198
199         return v;
200     }
201
202     protected static int compareVersionElement(String JavaDoc a, String JavaDoc b) {
203         // -1 if a < b
204
// 1 if a > b
205
// 0 if a == b
206

207         int[] va = parseVersionElement(a);
208         int[] vb = parseVersionElement(b);
209
210         for(int i=0; i<va.length; i++) {
211             if(va[i] < vb[i])
212                 return -1;
213             else if(va[i] > vb[i])
214                 return 1;
215         }
216
217         return 0;
218
219     }
220
221     public static boolean isVersionGreaterThan(String JavaDoc a, String JavaDoc b) {
222         // Return true if version a > version b
223

224         if(a == null || b == null)
225             return false;
226
227         String JavaDoc[] va = a.split("\\.");
228         String JavaDoc[] vb = b.split("\\.");
229
230         for(int i=0; i<va.length; i++) {
231             if(i == vb.length)
232                 return true;
233
234             switch(compareVersionElement(va[i], vb[i])) {
235                 case 1: // ia > ib
236
return true;
237                 case -1: // ia < ib
238
return false;
239                 case 0: // equal
240
// continue
241
}
242         }
243
244         return false;
245     }
246
247     public static String JavaDoc encodeToURL(String JavaDoc s) {
248         return encodeToURL(s, "");
249     }
250
251     public static String JavaDoc encodeToURL(String JavaDoc s, String JavaDoc defaultString) {
252         String JavaDoc encoded = defaultString;
253         if(s != null && s.length() > 0) {
254             try {
255                 encoded = URLEncoder.encode(s, "UTF-8");
256             } catch (UnsupportedEncodingException e) {
257                 System.err.println("XJUtils:encodeToURL exception: "+e);
258             }
259         }
260         return encoded;
261     }
262
263     /** Returns a text where all line separator are \n
264      *
265      * @return the normalized text
266      */

267
268     public static String JavaDoc getNormalizedText(String JavaDoc text) {
269         StringBuffer JavaDoc normalizedText = new StringBuffer JavaDoc();
270         BufferedReader reader = new BufferedReader(new StringReader(text));
271         try {
272             String JavaDoc line;
273             while((line = reader.readLine()) != null) {
274                 normalizedText.append(line);
275                 normalizedText.append("\n");
276             }
277         } catch (IOException e) {
278             e.printStackTrace();
279         }
280         try {
281             reader.close();
282         } catch (IOException e) {
283             e.printStackTrace();
284         }
285         return normalizedText.toString();
286     }
287
288     /** Returns a text where all line separator are taken from the system property
289      *
290      * @return the localized text
291      */

292
293     public static String JavaDoc getLocalizedText(String JavaDoc text) {
294         StringBuffer JavaDoc localizedText = new StringBuffer JavaDoc();
295         BufferedReader reader = new BufferedReader(new StringReader(text));
296         String JavaDoc lineSeparator = XJSystem.getLineSeparator();
297         try {
298             String JavaDoc line;
299             while((line = reader.readLine()) != null) {
300                 localizedText.append(line);
301                 localizedText.append(lineSeparator);
302             }
303         } catch (IOException e) {
304             e.printStackTrace();
305         }
306         try {
307             reader.close();
308         } catch (IOException e) {
309             e.printStackTrace();
310         }
311         return localizedText.toString();
312     }
313
314     /** Returns a string containing the representation of the stack trace
315      * of the exception
316      *
317      */

318
319     public static String JavaDoc stackTrace(Throwable JavaDoc e) {
320         StringWriter sw = new StringWriter();
321         PrintWriter pw = new PrintWriter(sw, true);
322         e.printStackTrace(pw);
323         pw.flush();
324         sw.flush();
325         return sw.toString();
326     }
327
328     public static boolean deleteDirectory(String JavaDoc dir) {
329         return deleteDirectoryRecursively(new File(dir));
330     }
331
332     private static boolean deleteDirectoryRecursively(File dir) {
333         if (dir.isDirectory()) {
334             String JavaDoc[] children = dir.list();
335             for (int i=0; i<children.length; i++) {
336                 boolean success = deleteDirectoryRecursively(new File(dir, children[i]));
337                 if (!success) {
338                     return false;
339                 }
340             }
341         }
342
343         return dir.delete();
344     }
345 }
346
Popular Tags