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
9 * IBM Corporation - initial API and implementation
10 *******************************************************************************/
11 package net.sourceforge.phpdt.core.tests.util;
14 import java.net.ServerSocket;
15 import java.util.Locale;
17 import java.util.zip.ZipEntry;
18 import java.util.zip.ZipOutputStream;
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;
29 public static String OUTPUT_DIRECTORY = "comptest";
31 public static CompilationUnit[] compilationUnits(String[] testFiles) {
32 int length = testFiles.length / 2;
33 CompilationUnit[] result = new CompilationUnit[length];
35 for (int i = 0; i < length; i++) {
36 result[i] = new CompilationUnit(testFiles[index + 1].toCharArray(), testFiles[index], null);
41 //public static void compile(String[] pathsAndContents, Map options, String outputPath) {
42 // IProblemFactory problemFactory = new DefaultProblemFactory(Locale.getDefault());
43 // Requestor requestor =
46 // outputPath.endsWith(File.separator) ? outputPath : outputPath + File.separator,
48 // INameEnvironment nameEnvironment = new FileSystem(getJavaClassLibs(), new String[] {}, null);
49 // IErrorHandlingPolicy errorHandlingPolicy =
50 // new IErrorHandlingPolicy() {
51 // public boolean stopOnFirstError() {
54 // public boolean proceedOnErrors() {
58 // Compiler batchCompiler =
61 // errorHandlingPolicy,
65 // batchCompiler.compile(compilationUnits(pathsAndContents)); // compile all files together
66 // System.err.print(requestor.problemLog); // problem log empty if no problems
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];
73 System.arraycopy(classLibs, 0, defaultClassPaths, 1, length);
74 defaultClassPaths[0] = classpath;
76 System.arraycopy(classLibs, 0, defaultClassPaths, 0, length);
77 defaultClassPaths[length] = classpath;
79 return defaultClassPaths;
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);
87 if (i < length-1 && source.charAt(i+1) == '\n') {
88 i++; // skip \n after \r
94 return buffer.toString();
97 * Copy the given source (a file or a directory that must exists) to the given destination (a directory that must exists).
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();
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);
115 copy(sourceFile.getPath(), destSubDir.getPath());
117 copy(sourceFile.getPath(), dest.getPath());
122 FileInputStream in = null;
123 FileOutputStream out = null;
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");
130 out = new FileOutputStream(destFile);
131 int bufferLength = 1024;
132 byte[] buffer = new byte[bufferLength];
135 read = in.read(buffer, 0, bufferLength);
137 out.write(buffer, 0, read);
140 } catch (IOException e) {
141 throw new Error(e.toString());
146 } catch (IOException e) {
152 } catch (IOException e) {
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);
166 * Generate a display string from the given String.
167 * @param indent number of tabs are added at the begining of each line.
169 * Example of use: [org.eclipse.jdt.core.tests.util.Util.displayString("abc\ndef\tghi")]
171 public static String displayString(String inputString){
172 return displayString(inputString, 0);
175 * Generate a display string from the given String.
183 * <li>\" to \\\"</li>
185 * <li>\\ to \\\\</li>
186 * <li>All other characters are unchanged.</li>
188 * This method doesn't convert \r\n to \n.
194 * input string = "abc\ndef\tghi",
196 * result = "\"\t\t\tabc\\n" +
202 * input string = "abc\ndef\tghi\n",
204 * result = "\"\t\t\tabc\\n" +
205 * "\t\t\tdef\tghi\\n\""
210 * input string = "abc\r\ndef\tghi\r\n",
212 * result = "\"\t\t\tabc\\r\\n" +
213 * "\t\t\tdef\tghi\\r\\n\""
219 * @param inputString the given input string
220 * @param indent number of tabs are added at the begining of each line.
222 * @return the displayed string
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");
230 while (tokenizer.hasMoreTokens()){
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");
246 buffer.append("\" + \n");
247 for (int i = 0; i < indent; i++) buffer.append("\t");
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");
263 StringBuffer tokenBuffer = new StringBuffer();
264 for (int i = 0; i < token.length(); i++){
265 char c = token.charAt(i);
268 tokenBuffer.append("\\r");
271 tokenBuffer.append("\\n");
274 tokenBuffer.append("\\b");
277 tokenBuffer.append("\t");
280 tokenBuffer.append("\\f");
283 tokenBuffer.append("\\\"");
286 tokenBuffer.append("\\'");
289 tokenBuffer.append("\\\\");
292 tokenBuffer.append(c);
295 buffer.append(tokenBuffer.toString());
298 return buffer.toString();
301 * Reads the content of the given source file and converts it to a display string.
303 * Example of use: [org.eclipse.jdt.core.tests.util.Util.fileContentToDisplayString("c:/temp/X.java", 0)]
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.");
311 if (!sourceFile.isFile()) {
312 System.out.println(sourceFilePath + " is not a file.");
315 StringBuffer sourceContentBuffer = new StringBuffer();
316 FileInputStream input = null;
318 input = new FileInputStream(sourceFile);
319 } catch (FileNotFoundException e) {
327 sourceContentBuffer.append((char)read);
329 } while (read != -1);
331 } catch (IOException e) {
337 } catch (IOException e2) {
340 String sourceString = sourceContentBuffer.toString();
341 if (independantLineDelimiter) {
342 sourceString = convertToIndependantLineDelimiter(sourceString);
344 return displayString(sourceString, indent);
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.
351 * Example of use: [org.eclipse.jdt.core.tests.util.Util.fileContentToDisplayString("c:/temp/X.java", 0, null)]
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);
359 writeToFile(displayString, destinationFilePath);
362 * Flush content of a given directory (leaving it empty),
363 * no-op if not a directory.
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);
379 * Search the user hard-drive for a Java class library.
380 * Returns null if none could be found.
382 * Example of use: [org.eclipse.jdt.core.tests.util.Util.getJavaClassLib()]
384 public static String[] getJavaClassLibs() {
385 String jreDir = getJREDirectory();
386 if (jreDir == null) {
387 return new String[] {};
389 final String vmName = System.getProperty("java.vm.name");
390 if ("J9".equals(vmName)) {
391 return new String[] { toNativePath(jreDir + "/lib/jclMax/classes.zip")};
393 File file = new File(jreDir + "/lib/rt.jar");
395 return new String[] {
396 toNativePath(jreDir + "/lib/rt.jar")
399 return new String[] {
400 toNativePath(jreDir + "/lib/core.jar"),
401 toNativePath(jreDir + "/lib/security.jar"),
402 toNativePath(jreDir + "/lib/graphics.jar")
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++) {
413 .append(classLibs[i])
414 .append(File.pathSeparatorChar);
417 return buffer.toString();
420 * Returns the JRE directory this tests are running on.
421 * Returns null if none could be found.
423 * Example of use: [org.eclipse.jdt.core.tests.util.Util.getJREDirectory()]
425 public static String getJREDirectory() {
426 return System.getProperty("java.home");
429 * Search the user hard-drive for a possible output directory.
430 * Returns null if none could be found.
432 * Example of use: [org.eclipse.jdt.core.tests.util.Util.getOutputDirectory()]
434 public static String getOutputDirectory() {
435 String container = System.getProperty("user.home");
436 if (container == null){
439 return toNativePath(container) + File.separator + OUTPUT_DIRECTORY;
443 * Returns the next available port number on the local host.
445 public static int getFreePort() {
446 ServerSocket socket = null;
448 socket = new ServerSocket(0);
449 return socket.getLocalPort();
450 } catch (IOException e) {
453 if (socket != null) {
456 } catch (IOException e) {
464 * Makes the given path a path using native path separators as returned by File.getPath()
465 * and trimming any extra slash.
467 public static String toNativePath(String path) {
468 String nativePath = path.replace('\\', File.separatorChar).replace('/', File.separatorChar);
470 nativePath.endsWith("/") || nativePath.endsWith("\\") ?
471 nativePath.substring(0, nativePath.length() - 1) :
474 public static void writeToFile(String contents, String destinationFilePath) {
475 File destFile = new File(destinationFilePath);
476 FileOutputStream output = null;
478 output = new FileOutputStream(destFile);
479 PrintWriter writer = new PrintWriter(output);
480 writer.print(contents);
482 } catch (IOException e) {
486 if (output != null) {
489 } catch (IOException e2) {
494 //public static void zip(File rootDir, String zipPath) throws IOException {
495 // ZipOutputStream zip = null;
497 // zip = new ZipOutputStream(new FileOutputStream(zipPath));
498 // zip(rootDir, zip, rootDir.getPath().length()+1); // 1 for last slash
500 // if (zip != null) {
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);
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));