KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > jdt > internal > compiler > util > Util


1 /*******************************************************************************
2  * Copyright (c) 2000, 2007 IBM Corporation and others.
3  * All rights reserved. This program and the accompanying materials
4  * are made available under the terms of the Eclipse Public License v1.0
5  * which accompanies this distribution, and is available at
6  * http://www.eclipse.org/legal/epl-v10.html
7  *
8  * Contributors:
9  * IBM Corporation - initial API and implementation
10  *******************************************************************************/

11 package org.eclipse.jdt.internal.compiler.util;
12
13 import java.io.ByteArrayInputStream JavaDoc;
14 import java.io.File JavaDoc;
15 import java.io.FileInputStream JavaDoc;
16 import java.io.IOException JavaDoc;
17 import java.io.InputStream JavaDoc;
18 import java.io.InputStreamReader JavaDoc;
19 import java.io.UnsupportedEncodingException JavaDoc;
20 import java.util.zip.ZipEntry JavaDoc;
21 import java.util.zip.ZipFile JavaDoc;
22 import org.eclipse.jdt.core.compiler.CharOperation;
23
24 public class Util implements SuffixConstants {
25
26     public interface Displayable {
27         String JavaDoc displayString(Object JavaDoc o);
28     }
29
30     private static final int DEFAULT_READING_SIZE = 8192;
31     public final static String JavaDoc UTF_8 = "UTF-8"; //$NON-NLS-1$
32
public static final String JavaDoc LINE_SEPARATOR = System.getProperty("line.separator"); //$NON-NLS-1$
33

34     public static final String JavaDoc EMPTY_STRING = new String JavaDoc(CharOperation.NO_CHAR);
35     public static final int[] EMPTY_INT_ARRAY= new int[0];
36     
37     /**
38      * Returns the given bytes as a char array using a given encoding (null means platform default).
39      */

40     public static char[] bytesToChar(byte[] bytes, String JavaDoc encoding) throws IOException JavaDoc {
41
42         return getInputStreamAsCharArray(new ByteArrayInputStream JavaDoc(bytes), bytes.length, encoding);
43
44     }
45     /**
46      * Returns the contents of the given file as a byte array.
47      * @throws IOException if a problem occured reading the file.
48      */

49     public static byte[] getFileByteContent(File JavaDoc file) throws IOException JavaDoc {
50         InputStream JavaDoc stream = null;
51         try {
52             stream = new FileInputStream JavaDoc(file);
53             return getInputStreamAsByteArray(stream, (int) file.length());
54         } finally {
55             if (stream != null) {
56                 try {
57                     stream.close();
58                 } catch (IOException JavaDoc e) {
59                     // ignore
60
}
61             }
62         }
63     }
64     /**
65      * Returns the contents of the given file as a char array.
66      * When encoding is null, then the platform default one is used
67      * @throws IOException if a problem occured reading the file.
68      */

69     public static char[] getFileCharContent(File JavaDoc file, String JavaDoc encoding) throws IOException JavaDoc {
70         InputStream JavaDoc stream = null;
71         try {
72             stream = new FileInputStream JavaDoc(file);
73             return getInputStreamAsCharArray(stream, (int) file.length(), encoding);
74         } finally {
75             if (stream != null) {
76                 try {
77                     stream.close();
78                 } catch (IOException JavaDoc e) {
79                     // ignore
80
}
81             }
82         }
83     }
84     /*
85      * NIO support to get input stream as byte array.
86      * Not used as with JDK 1.4.2 this support is slower than standard IO one...
87      * Keep it as comment for future in case of next JDK versions improve performance
88      * in this area...
89      *
90     public static byte[] getInputStreamAsByteArray(FileInputStream stream, int length)
91         throws IOException {
92
93         FileChannel channel = stream.getChannel();
94         int size = (int)channel.size();
95         if (length >= 0 && length < size) size = length;
96         byte[] contents = new byte[size];
97         ByteBuffer buffer = ByteBuffer.wrap(contents);
98         channel.read(buffer);
99         return contents;
100     }
101     */

102     /**
103      * Returns the given input stream's contents as a byte array.
104      * If a length is specified (ie. if length != -1), only length bytes
105      * are returned. Otherwise all bytes in the stream are returned.
106      * Note this doesn't close the stream.
107      * @throws IOException if a problem occured reading the stream.
108      */

109     public static byte[] getInputStreamAsByteArray(InputStream JavaDoc stream, int length)
110         throws IOException JavaDoc {
111         byte[] contents;
112         if (length == -1) {
113             contents = new byte[0];
114             int contentsLength = 0;
115             int amountRead = -1;
116             do {
117                 int amountRequested = Math.max(stream.available(), DEFAULT_READING_SIZE); // read at least 8K
118

119                 // resize contents if needed
120
if (contentsLength + amountRequested > contents.length) {
121                     System.arraycopy(
122                         contents,
123                         0,
124                         contents = new byte[contentsLength + amountRequested],
125                         0,
126                         contentsLength);
127                 }
128
129                 // read as many bytes as possible
130
amountRead = stream.read(contents, contentsLength, amountRequested);
131
132                 if (amountRead > 0) {
133                     // remember length of contents
134
contentsLength += amountRead;
135                 }
136             } while (amountRead != -1);
137
138             // resize contents if necessary
139
if (contentsLength < contents.length) {
140                 System.arraycopy(
141                     contents,
142                     0,
143                     contents = new byte[contentsLength],
144                     0,
145                     contentsLength);
146             }
147         } else {
148             contents = new byte[length];
149             int len = 0;
150             int readSize = 0;
151             while ((readSize != -1) && (len != length)) {
152                 // See PR 1FMS89U
153
// We record first the read size. In this case len is the actual read size.
154
len += readSize;
155                 readSize = stream.read(contents, len, length - len);
156             }
157         }
158
159         return contents;
160     }
161     /*
162      * NIO support to get input stream as char array.
163      * Not used as with JDK 1.4.2 this support is slower than standard IO one...
164      * Keep it as comment for future in case of next JDK versions improve performance
165      * in this area...
166     public static char[] getInputStreamAsCharArray(FileInputStream stream, int length, String encoding)
167         throws IOException {
168     
169         FileChannel channel = stream.getChannel();
170         int size = (int)channel.size();
171         if (length >= 0 && length < size) size = length;
172         Charset charset = encoding==null?systemCharset:Charset.forName(encoding);
173         if (charset != null) {
174             MappedByteBuffer bbuffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, size);
175             CharsetDecoder decoder = charset.newDecoder();
176             CharBuffer buffer = decoder.decode(bbuffer);
177             char[] contents = new char[buffer.limit()];
178             buffer.get(contents);
179             return contents;
180         }
181         throw new UnsupportedCharsetException(SYSTEM_FILE_ENCODING);
182     }
183     */

184     /**
185      * Returns the given input stream's contents as a character array.
186      * If a length is specified (ie. if length != -1), this represents the number of bytes in the stream.
187      * Note this doesn't close the stream.
188      * @throws IOException if a problem occured reading the stream.
189      */

190     public static char[] getInputStreamAsCharArray(InputStream JavaDoc stream, int length, String JavaDoc encoding)
191         throws IOException JavaDoc {
192         InputStreamReader JavaDoc reader = null;
193         try {
194             reader = encoding == null
195                         ? new InputStreamReader JavaDoc(stream)
196                         : new InputStreamReader JavaDoc(stream, encoding);
197         } catch (UnsupportedEncodingException JavaDoc e) {
198             // encoding is not supported
199
reader = new InputStreamReader JavaDoc(stream);
200         }
201         char[] contents;
202         int totalRead = 0;
203         if (length == -1) {
204             contents = CharOperation.NO_CHAR;
205         } else {
206             // length is a good guess when the encoding produces less or the same amount of characters than the file length
207
contents = new char[length]; // best guess
208
}
209
210         while (true) {
211             int amountRequested;
212             if (totalRead < length) {
213                 // until known length is met, reuse same array sized eagerly
214
amountRequested = length - totalRead;
215             } else {
216                 // reading beyond known length
217
int current = reader.read();
218                 if (current < 0) break;
219                 
220                 amountRequested = Math.max(stream.available(), DEFAULT_READING_SIZE); // read at least 8K
221

222                 // resize contents if needed
223
if (totalRead + 1 + amountRequested > contents.length)
224                     System.arraycopy(contents, 0, contents = new char[totalRead + 1 + amountRequested], 0, totalRead);
225                 
226                 // add current character
227
contents[totalRead++] = (char) current; // coming from totalRead==length
228
}
229             // read as many chars as possible
230
int amountRead = reader.read(contents, totalRead, amountRequested);
231             if (amountRead < 0) break;
232             totalRead += amountRead;
233         }
234
235         // Do not keep first character for UTF-8 BOM encoding
236
int start = 0;
237         if (totalRead > 0 && UTF_8.equals(encoding)) {
238             if (contents[0] == 0xFEFF) { // if BOM char then skip
239
totalRead--;
240                 start = 1;
241             }
242         }
243         
244         // resize contents if necessary
245
if (totalRead < contents.length)
246             System.arraycopy(contents, start, contents = new char[totalRead], 0, totalRead);
247
248         return contents;
249     }
250     
251     public static int getLineNumber(int position, int[] lineEnds, int g, int d) {
252         if (lineEnds == null)
253             return 1;
254         if (d == -1)
255             return 1;
256         int m = g, start;
257         while (g <= d) {
258             m = g + (d - g) /2;
259             if (position < (start = lineEnds[m])) {
260                 d = m-1;
261             } else if (position > start) {
262                 g = m+1;
263             } else {
264                 return m + 1;
265             }
266         }
267         if (position < lineEnds[m]) {
268             return m+1;
269         }
270         return m+2;
271     }
272
273     /**
274      * Returns the contents of the given zip entry as a byte array.
275      * @throws IOException if a problem occured reading the zip entry.
276      */

277     public static byte[] getZipEntryByteContent(ZipEntry JavaDoc ze, ZipFile JavaDoc zip)
278         throws IOException JavaDoc {
279
280         InputStream JavaDoc stream = null;
281         try {
282             stream = zip.getInputStream(ze);
283             if (stream == null) throw new IOException JavaDoc("Invalid zip entry name : " + ze.getName()); //$NON-NLS-1$
284
return getInputStreamAsByteArray(stream, (int) ze.getSize());
285         } finally {
286             if (stream != null) {
287                 try {
288                     stream.close();
289                 } catch (IOException JavaDoc e) {
290                     // ignore
291
}
292             }
293         }
294     }
295
296     /**
297      * Returns true iff str.toLowerCase().endsWith(".jar") || str.toLowerCase().endsWith(".zip")
298      * implementation is not creating extra strings.
299      */

300     public final static boolean isArchiveFileName(String JavaDoc name) {
301         int nameLength = name == null ? 0 : name.length();
302         int suffixLength = SUFFIX_JAR.length;
303         if (nameLength < suffixLength) return false;
304
305         // try to match as JAR file
306
for (int i = 0; i < suffixLength; i++) {
307             char c = name.charAt(nameLength - i - 1);
308             int suffixIndex = suffixLength - i - 1;
309             if (c != SUFFIX_jar[suffixIndex] && c != SUFFIX_JAR[suffixIndex]) {
310
311                 // try to match as ZIP file
312
suffixLength = SUFFIX_ZIP.length;
313                 if (nameLength < suffixLength) return false;
314                 for (int j = 0; j < suffixLength; j++) {
315                     c = name.charAt(nameLength - j - 1);
316                     suffixIndex = suffixLength - j - 1;
317                     if (c != SUFFIX_zip[suffixIndex] && c != SUFFIX_ZIP[suffixIndex]) return false;
318                 }
319                 return true;
320             }
321         }
322         return true;
323     }
324     /**
325      * Returns true iff str.toLowerCase().endsWith(".class")
326      * implementation is not creating extra strings.
327      */

328     public final static boolean isClassFileName(char[] name) {
329         int nameLength = name == null ? 0 : name.length;
330         int suffixLength = SUFFIX_CLASS.length;
331         if (nameLength < suffixLength) return false;
332
333         for (int i = 0, offset = nameLength - suffixLength; i < suffixLength; i++) {
334             char c = name[offset + i];
335             if (c != SUFFIX_class[i] && c != SUFFIX_CLASS[i]) return false;
336         }
337         return true;
338     }
339     /**
340      * Returns true iff str.toLowerCase().endsWith(".class")
341      * implementation is not creating extra strings.
342      */

343     public final static boolean isClassFileName(String JavaDoc name) {
344         int nameLength = name == null ? 0 : name.length();
345         int suffixLength = SUFFIX_CLASS.length;
346         if (nameLength < suffixLength) return false;
347
348         for (int i = 0; i < suffixLength; i++) {
349             char c = name.charAt(nameLength - i - 1);
350             int suffixIndex = suffixLength - i - 1;
351             if (c != SUFFIX_class[suffixIndex] && c != SUFFIX_CLASS[suffixIndex]) return false;
352         }
353         return true;
354     }
355     /* TODO (philippe) should consider promoting it to CharOperation
356      * Returns whether the given resource path matches one of the inclusion/exclusion
357      * patterns.
358      * NOTE: should not be asked directly using pkg root pathes
359      * @see IClasspathEntry#getInclusionPatterns
360      * @see IClasspathEntry#getExclusionPatterns
361      */

362     public final static boolean isExcluded(char[] path, char[][] inclusionPatterns, char[][] exclusionPatterns, boolean isFolderPath) {
363         if (inclusionPatterns == null && exclusionPatterns == null) return false;
364
365         inclusionCheck: if (inclusionPatterns != null) {
366             for (int i = 0, length = inclusionPatterns.length; i < length; i++) {
367                 char[] pattern = inclusionPatterns[i];
368                 char[] folderPattern = pattern;
369                 if (isFolderPath) {
370                     int lastSlash = CharOperation.lastIndexOf('/', pattern);
371                     if (lastSlash != -1 && lastSlash != pattern.length-1){ // trailing slash -> adds '**' for free (see http://ant.apache.org/manual/dirtasks.html)
372
int star = CharOperation.indexOf('*', pattern, lastSlash);
373                         if ((star == -1
374                                 || star >= pattern.length-1
375                                 || pattern[star+1] != '*')) {
376                             folderPattern = CharOperation.subarray(pattern, 0, lastSlash);
377                         }
378                     }
379                 }
380                 if (CharOperation.pathMatch(folderPattern, path, true, '/')) {
381                     break inclusionCheck;
382                 }
383             }
384             return true; // never included
385
}
386         if (isFolderPath) {
387             path = CharOperation.concat(path, new char[] {'*'}, '/');
388         }
389         if (exclusionPatterns != null) {
390             for (int i = 0, length = exclusionPatterns.length; i < length; i++) {
391                 if (CharOperation.pathMatch(exclusionPatterns[i], path, true, '/')) {
392                     return true;
393                 }
394             }
395         }
396         return false;
397     }
398     /**
399      * Returns true iff str.toLowerCase().endsWith(".java")
400      * implementation is not creating extra strings.
401      */

402     public final static boolean isJavaFileName(char[] name) {
403         int nameLength = name == null ? 0 : name.length;
404         int suffixLength = SUFFIX_JAVA.length;
405         if (nameLength < suffixLength) return false;
406
407         for (int i = 0, offset = nameLength - suffixLength; i < suffixLength; i++) {
408             char c = name[offset + i];
409             if (c != SUFFIX_java[i] && c != SUFFIX_JAVA[i]) return false;
410         }
411         return true;
412     }
413     /**
414      * Returns true iff str.toLowerCase().endsWith(".java")
415      * implementation is not creating extra strings.
416      */

417     public final static boolean isJavaFileName(String JavaDoc name) {
418         int nameLength = name == null ? 0 : name.length();
419         int suffixLength = SUFFIX_JAVA.length;
420         if (nameLength < suffixLength) return false;
421
422         for (int i = 0; i < suffixLength; i++) {
423             char c = name.charAt(nameLength - i - 1);
424             int suffixIndex = suffixLength - i - 1;
425             if (c != SUFFIX_java[suffixIndex] && c != SUFFIX_JAVA[suffixIndex]) return false;
426         }
427         return true;
428     }
429
430     /**
431      * INTERNAL USE-ONLY
432      * Search the column number corresponding to a specific position
433      */

434     public static final int searchColumnNumber(int[] startLineIndexes, int lineNumber, int position) {
435         switch(lineNumber) {
436             case 1 :
437                 return position + 1;
438             case 2:
439                 return position - startLineIndexes[0];
440             default:
441                 int line = lineNumber - 2;
442                 int length = startLineIndexes.length;
443                 if (line >= length) {
444                     return position - startLineIndexes[length - 1];
445                 }
446                 return position - startLineIndexes[line];
447         }
448     }
449     /**
450      * Converts a boolean value into Boolean.
451      * @param bool The boolean to convert
452      * @return The corresponding Boolean object (TRUE or FALSE).
453      */

454     public static Boolean JavaDoc toBoolean(boolean bool) {
455         if (bool) {
456             return Boolean.TRUE;
457         } else {
458             return Boolean.FALSE;
459         }
460     }
461     /**
462      * Converts an array of Objects into String.
463      */

464     public static String JavaDoc toString(Object JavaDoc[] objects) {
465         return toString(objects,
466             new Displayable(){
467                 public String JavaDoc displayString(Object JavaDoc o) {
468                     if (o == null) return "null"; //$NON-NLS-1$
469
return o.toString();
470                 }
471             });
472     }
473
474     /**
475      * Converts an array of Objects into String.
476      */

477     public static String JavaDoc toString(Object JavaDoc[] objects, Displayable renderer) {
478         if (objects == null) return ""; //$NON-NLS-1$
479
StringBuffer JavaDoc buffer = new StringBuffer JavaDoc(10);
480         for (int i = 0; i < objects.length; i++){
481             if (i > 0) buffer.append(", "); //$NON-NLS-1$
482
buffer.append(renderer.displayString(objects[i]));
483         }
484         return buffer.toString();
485     }
486 }
487
Popular Tags