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