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