Deleted unused commenst and unused vars.
[phpeclipse.git] / net.sourceforge.phpeclipse.tests / src / net / sourceforge / phpdt / core / tests / util / Util.java
1 /*******************************************************************************
2  * Copyright (c) 2000, 2004 IBM Corporation and others.
3  * All rights reserved. This program and the accompanying materials 
4  * are made available under the terms of the Common Public License v1.0
5  * which accompanies this distribution, and is available at
6  * http://www.eclipse.org/legal/cpl-v10.html
7  * 
8  * Contributors:
9  *     IBM Corporation - initial API and implementation
10  *******************************************************************************/
11 package net.sourceforge.phpdt.core.tests.util;
12
13 import java.io.File;
14 import java.io.FileInputStream;
15 import java.io.FileNotFoundException;
16 import java.io.FileOutputStream;
17 import java.io.IOException;
18 import java.io.PrintWriter;
19 import java.net.ServerSocket;
20
21 import net.sourceforge.phpdt.internal.compiler.batch.CompilationUnit;
22
23 public class Util {
24         public static String OUTPUT_DIRECTORY = "comptest";
25
26         public static CompilationUnit[] compilationUnits(String[] testFiles) {
27                 int length = testFiles.length / 2;
28                 CompilationUnit[] result = new CompilationUnit[length];
29                 int index = 0;
30                 for (int i = 0; i < length; i++) {
31                         result[i] = new CompilationUnit(testFiles[index + 1].toCharArray(),
32                                         testFiles[index], null);
33                         index += 2;
34                 }
35                 return result;
36         }
37
38         public static String[] concatWithClassLibs(String classpath, boolean inFront) {
39                 String[] classLibs = getJavaClassLibs();
40                 final int length = classLibs.length;
41                 String[] defaultClassPaths = new String[length + 1];
42                 if (inFront) {
43                         System.arraycopy(classLibs, 0, defaultClassPaths, 1, length);
44                         defaultClassPaths[0] = classpath;
45                 } else {
46                         System.arraycopy(classLibs, 0, defaultClassPaths, 0, length);
47                         defaultClassPaths[length] = classpath;
48                 }
49                 return defaultClassPaths;
50         }
51
52         public static String convertToIndependantLineDelimiter(String source) {
53                 StringBuffer buffer = new StringBuffer();
54                 for (int i = 0, length = source.length(); i < length; i++) {
55                         char car = source.charAt(i);
56                         if (car == '\r') {
57                                 buffer.append('\n');
58                                 if (i < length - 1 && source.charAt(i + 1) == '\n') {
59                                         i++; // skip \n after \r
60                                 }
61                         } else {
62                                 buffer.append(car);
63                         }
64                 }
65                 return buffer.toString();
66         }
67
68         /**
69          * Copy the given source (a file or a directory that must exists) to the
70          * given destination (a directory that must exists).
71          */
72         public static void copy(String sourcePath, String destPath) {
73                 sourcePath = toNativePath(sourcePath);
74                 destPath = toNativePath(destPath);
75                 File source = new File(sourcePath);
76                 if (!source.exists())
77                         return;
78                 File dest = new File(destPath);
79                 if (!dest.exists())
80                         return;
81                 if (source.isDirectory()) {
82                         String[] files = source.list();
83                         if (files != null) {
84                                 for (int i = 0; i < files.length; i++) {
85                                         String file = files[i];
86                                         File sourceFile = new File(source, file);
87                                         if (sourceFile.isDirectory()) {
88                                                 File destSubDir = new File(dest, file);
89                                                 destSubDir.mkdir();
90                                                 copy(sourceFile.getPath(), destSubDir.getPath());
91                                         } else {
92                                                 copy(sourceFile.getPath(), dest.getPath());
93                                         }
94                                 }
95                         }
96                 } else {
97                         FileInputStream in = null;
98                         FileOutputStream out = null;
99                         try {
100                                 in = new FileInputStream(source);
101                                 File destFile = new File(dest, source.getName());
102                                 if (destFile.exists() && !destFile.delete()) {
103                                         throw new IOException(destFile + " is in use");
104                                 }
105                                 out = new FileOutputStream(destFile);
106                                 int bufferLength = 1024;
107                                 byte[] buffer = new byte[bufferLength];
108                                 int read = 0;
109                                 while (read != -1) {
110                                         read = in.read(buffer, 0, bufferLength);
111                                         if (read != -1) {
112                                                 out.write(buffer, 0, read);
113                                         }
114                                 }
115                         } catch (IOException e) {
116                                 throw new Error(e.toString());
117                         } finally {
118                                 if (in != null) {
119                                         try {
120                                                 in.close();
121                                         } catch (IOException e) {
122                                         }
123                                 }
124                                 if (out != null) {
125                                         try {
126                                                 out.close();
127                                         } catch (IOException e) {
128                                         }
129                                 }
130                         }
131                 }
132         }
133
134         // public static void createJar(String[] pathsAndContents, Map options,
135         // String
136         // jarPath) throws IOException {
137         // String classesPath = getOutputDirectory() + File.separator + "classes";
138         // File classesDir = new File(classesPath);
139         // flushDirectoryContent(classesDir);
140         // compile(pathsAndContents, options, classesPath);
141         // zip(classesDir, jarPath);
142         // }
143         /**
144          * Generate a display string from the given String.
145          * 
146          * @param indent
147          *            number of tabs are added at the begining of each line.
148          * 
149          * Example of use:
150          * [org.eclipse.jdt.core.tests.util.Util.displayString("abc\ndef\tghi")]
151          */
152         public static String displayString(String inputString) {
153                 return displayString(inputString, 0);
154         }
155
156         /**
157          * Generate a display string from the given String. It converts:
158          * <ul>
159          * <li>\t to \t</li>
160          * <li>\r to \\r</li>
161          * <li>\n to \n</li>
162          * <li>\b to \\b</li>
163          * <li>\f to \\f</li>
164          * <li>\" to \\\"</li>
165          * <li>\' to \\'</li>
166          * <li>\\ to \\\\</li>
167          * <li>All other characters are unchanged.</li>
168          * </ul>
169          * This method doesn't convert \r\n to \n.
170          * <p>
171          * Example of use: <o>
172          * <li>
173          * 
174          * <pre>
175          *   input string = &quot;abc\ndef\tghi&quot;,
176          *   indent = 3
177          *   result = &quot;\&quot;\t\t\tabc\\n&quot; +
178          *                      &quot;\t\t\tdef\tghi\&quot;&quot;
179          * </pre>
180          * 
181          * </li>
182          * <li>
183          * 
184          * <pre>
185          *   input string = &quot;abc\ndef\tghi\n&quot;,
186          *   indent = 3
187          *   result = &quot;\&quot;\t\t\tabc\\n&quot; +
188          *                      &quot;\t\t\tdef\tghi\\n\&quot;&quot;
189          * </pre>
190          * 
191          * </li>
192          * <li>
193          * 
194          * <pre>
195          *   input string = &quot;abc\r\ndef\tghi\r\n&quot;,
196          *   indent = 3
197          *   result = &quot;\&quot;\t\t\tabc\\r\\n&quot; +
198          *                      &quot;\t\t\tdef\tghi\\r\\n\&quot;&quot;
199          * </pre>
200          * 
201          * </li>
202          * </ol>
203          * </p>
204          * 
205          * @param inputString
206          *            the given input string
207          * @param indent
208          *            number of tabs are added at the begining of each line.
209          * 
210          * @return the displayed string
211          */
212         public static String displayString(String inputString, int indent) {
213                 int length = inputString.length();
214                 StringBuffer buffer = new StringBuffer(length);
215                 java.util.StringTokenizer tokenizer = new java.util.StringTokenizer(
216                                 inputString, "\n\r", true);
217                 for (int i = 0; i < indent; i++)
218                         buffer.append("\t");
219                 buffer.append("\"");
220                 while (tokenizer.hasMoreTokens()) {
221
222                         String token = tokenizer.nextToken();
223                         if (token.equals("\r")) {
224                                 buffer.append("\\r");
225                                 if (tokenizer.hasMoreTokens()) {
226                                         token = tokenizer.nextToken();
227                                         if (token.equals("\n")) {
228                                                 buffer.append("\\n");
229                                                 if (tokenizer.hasMoreTokens()) {
230                                                         buffer.append("\" + \n");
231                                                         for (int i = 0; i < indent; i++)
232                                                                 buffer.append("\t");
233                                                         buffer.append("\"");
234                                                 }
235                                                 continue;
236                                         } else {
237                                                 buffer.append("\" + \n");
238                                                 for (int i = 0; i < indent; i++)
239                                                         buffer.append("\t");
240                                                 buffer.append("\"");
241                                         }
242                                 } else {
243                                         continue;
244                                 }
245                         } else if (token.equals("\n")) {
246                                 buffer.append("\\n");
247                                 if (tokenizer.hasMoreTokens()) {
248                                         buffer.append("\" + \n");
249                                         for (int i = 0; i < indent; i++)
250                                                 buffer.append("\t");
251                                         buffer.append("\"");
252                                 }
253                                 continue;
254                         }
255
256                         StringBuffer tokenBuffer = new StringBuffer();
257                         for (int i = 0; i < token.length(); i++) {
258                                 char c = token.charAt(i);
259                                 switch (c) {
260                                 case '\r':
261                                         tokenBuffer.append("\\r");
262                                         break;
263                                 case '\n':
264                                         tokenBuffer.append("\\n");
265                                         break;
266                                 case '\b':
267                                         tokenBuffer.append("\\b");
268                                         break;
269                                 case '\t':
270                                         tokenBuffer.append("\t");
271                                         break;
272                                 case '\f':
273                                         tokenBuffer.append("\\f");
274                                         break;
275                                 case '\"':
276                                         tokenBuffer.append("\\\"");
277                                         break;
278                                 case '\'':
279                                         tokenBuffer.append("\\'");
280                                         break;
281                                 case '\\':
282                                         tokenBuffer.append("\\\\");
283                                         break;
284                                 default:
285                                         tokenBuffer.append(c);
286                                 }
287                         }
288                         buffer.append(tokenBuffer.toString());
289                 }
290                 buffer.append("\"");
291                 return buffer.toString();
292         }
293
294         /**
295          * Reads the content of the given source file and converts it to a display
296          * string.
297          * 
298          * Example of use:
299          * [org.eclipse.jdt.core.tests.util.Util.fileContentToDisplayString("c:/temp/X.java",
300          * 0)]
301          */
302         public static String fileContentToDisplayString(String sourceFilePath,
303                         int indent, boolean independantLineDelimiter) {
304                 File sourceFile = new File(sourceFilePath);
305                 if (!sourceFile.exists()) {
306                         System.out.println("File " + sourceFilePath + " does not exists.");
307                         return null;
308                 }
309                 if (!sourceFile.isFile()) {
310                         System.out.println(sourceFilePath + " is not a file.");
311                         return null;
312                 }
313                 StringBuffer sourceContentBuffer = new StringBuffer();
314                 FileInputStream input = null;
315                 try {
316                         input = new FileInputStream(sourceFile);
317                 } catch (FileNotFoundException e) {
318                         return null;
319                 }
320                 try {
321                         int read;
322                         do {
323                                 read = input.read();
324                                 if (read != -1) {
325                                         sourceContentBuffer.append((char) read);
326                                 }
327                         } while (read != -1);
328                         input.close();
329                 } catch (IOException e) {
330                         e.printStackTrace();
331                         return null;
332                 } finally {
333                         try {
334                                 input.close();
335                         } catch (IOException e2) {
336                         }
337                 }
338                 String sourceString = sourceContentBuffer.toString();
339                 if (independantLineDelimiter) {
340                         sourceString = convertToIndependantLineDelimiter(sourceString);
341                 }
342                 return displayString(sourceString, indent);
343         }
344
345         /**
346          * Reads the content of the given source file, converts it to a display
347          * string. If the destination file path is not null, writes the result to
348          * this file. Otherwise writes it to the console.
349          * 
350          * Example of use:
351          * [org.eclipse.jdt.core.tests.util.Util.fileContentToDisplayString("c:/temp/X.java",
352          * 0, null)]
353          */
354         public static void fileContentToDisplayString(String sourceFilePath,
355                         int indent, String destinationFilePath,
356                         boolean independantLineDelimiter) {
357                 String displayString = fileContentToDisplayString(sourceFilePath,
358                                 indent, independantLineDelimiter);
359                 if (destinationFilePath == null) {
360                         System.out.println(displayString);
361                         return;
362                 }
363                 writeToFile(displayString, destinationFilePath);
364         }
365
366         /**
367          * Flush content of a given directory (leaving it empty), no-op if not a
368          * directory.
369          */
370         public static void flushDirectoryContent(File dir) {
371                 if (dir.isDirectory()) {
372                         String[] files = dir.list();
373                         if (files == null)
374                                 return;
375                         for (int i = 0, max = files.length; i < max; i++) {
376                                 File current = new File(dir, files[i]);
377                                 if (current.isDirectory()) {
378                                         flushDirectoryContent(current);
379                                 }
380                                 current.delete();
381                         }
382                 }
383         }
384
385         /**
386          * Search the user hard-drive for a Java class library. Returns null if none
387          * could be found.
388          * 
389          * Example of use: [org.eclipse.jdt.core.tests.util.Util.getJavaClassLib()]
390          */
391         public static String[] getJavaClassLibs() {
392                 String jreDir = getJREDirectory();
393                 if (jreDir == null) {
394                         return new String[] {};
395                 } else {
396                         final String vmName = System.getProperty("java.vm.name");
397                         if ("J9".equals(vmName)) {
398                                 return new String[] { toNativePath(jreDir
399                                                 + "/lib/jclMax/classes.zip") };
400                         } else {
401                                 File file = new File(jreDir + "/lib/rt.jar");
402                                 if (file.exists()) {
403                                         return new String[] { toNativePath(jreDir + "/lib/rt.jar") };
404                                 } else {
405                                         return new String[] {
406                                                         toNativePath(jreDir + "/lib/core.jar"),
407                                                         toNativePath(jreDir + "/lib/security.jar"),
408                                                         toNativePath(jreDir + "/lib/graphics.jar") };
409                                 }
410                         }
411                 }
412         }
413
414         public static String getJavaClassLibsAsString() {
415                 String[] classLibs = getJavaClassLibs();
416                 StringBuffer buffer = new StringBuffer();
417                 for (int i = 0, max = classLibs.length; i < max; i++) {
418                         buffer.append(classLibs[i]).append(File.pathSeparatorChar);
419
420                 }
421                 return buffer.toString();
422         }
423
424         /**
425          * Returns the JRE directory this tests are running on. Returns null if none
426          * could be found.
427          * 
428          * Example of use: [org.eclipse.jdt.core.tests.util.Util.getJREDirectory()]
429          */
430         public static String getJREDirectory() {
431                 return System.getProperty("java.home");
432         }
433
434         /**
435          * Search the user hard-drive for a possible output directory. Returns null
436          * if none could be found.
437          * 
438          * Example of use:
439          * [org.eclipse.jdt.core.tests.util.Util.getOutputDirectory()]
440          */
441         public static String getOutputDirectory() {
442                 String container = System.getProperty("user.home");
443                 if (container == null) {
444                         return null;
445                 } else {
446                         return toNativePath(container) + File.separator + OUTPUT_DIRECTORY;
447                 }
448         }
449
450         /**
451          * Returns the next available port number on the local host.
452          */
453         public static int getFreePort() {
454                 ServerSocket socket = null;
455                 try {
456                         socket = new ServerSocket(0);
457                         return socket.getLocalPort();
458                 } catch (IOException e) {
459                         // ignore
460                 } finally {
461                         if (socket != null) {
462                                 try {
463                                         socket.close();
464                                 } catch (IOException e) {
465                                         // ignore
466                                 }
467                         }
468                 }
469                 return -1;
470         }
471
472         /**
473          * Makes the given path a path using native path separators as returned by
474          * File.getPath() and trimming any extra slash.
475          */
476         public static String toNativePath(String path) {
477                 String nativePath = path.replace('\\', File.separatorChar).replace('/',
478                                 File.separatorChar);
479                 return nativePath.endsWith("/") || nativePath.endsWith("\\") ? nativePath
480                                 .substring(0, nativePath.length() - 1)
481                                 : nativePath;
482         }
483
484         public static void writeToFile(String contents, String destinationFilePath) {
485                 File destFile = new File(destinationFilePath);
486                 FileOutputStream output = null;
487                 try {
488                         output = new FileOutputStream(destFile);
489                         PrintWriter writer = new PrintWriter(output);
490                         writer.print(contents);
491                         writer.flush();
492                 } catch (IOException e) {
493                         e.printStackTrace();
494                         return;
495                 } finally {
496                         if (output != null) {
497                                 try {
498                                         output.close();
499                                 } catch (IOException e2) {
500                                 }
501                         }
502                 }
503         }
504 }